Passed
Push — master ( db7d4f...be8d41 )
by Alxarafe
21:50
created
dolibarr/htdocs/core/class/stats.class.php 3 patches
Indentation   +499 added lines, -499 removed lines patch added patch discarded remove patch
@@ -29,116 +29,22 @@  discard block
 block discarded – undo
29 29
  */
30 30
 abstract class Stats
31 31
 {
32
-	protected $db;
33
-	var $_lastfetchdate=array();	// Dates of cache file read by methods
34
-	var $cachefilesuffix='';		// Suffix to add to name of cache file (to avoid file name conflicts)
35
-
36
-	/**
37
-	 * Return nb of elements by month for several years
38
-	 *
39
-	 * @param 	int		$endyear		Start year
40
-	 * @param 	int		$startyear		End year
41
-	 * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
32
+    protected $db;
33
+    var $_lastfetchdate=array();	// Dates of cache file read by methods
34
+    var $cachefilesuffix='';		// Suffix to add to name of cache file (to avoid file name conflicts)
35
+
36
+    /**
37
+     * Return nb of elements by month for several years
38
+     *
39
+     * @param 	int		$endyear		Start year
40
+     * @param 	int		$startyear		End year
41
+     * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
42 42
      *	@param	int		$format			0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
43
-	 * @return 	array					Array of values
44
-	 */
45
-	function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
46
-	{
47
-		global $conf,$user,$langs;
48
-
49
-	    if ($startyear > $endyear) return -1;
50
-
51
-		$datay=array();
52
-
53
-		// Search into cache
54
-		if (! empty($cachedelay))
55
-	    {
56
-	    	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
57
-	    	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
58
-	    }
59
-
60
-		$newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
61
-		$newmask='0644';
62
-
63
-		$nowgmt = dol_now();
64
-
65
-		$foundintocache=0;
66
-		if ($cachedelay > 0)
67
-		{
68
-			$filedate=dol_filemtime($newpathofdestfile);
69
-			if ($filedate >= ($nowgmt - $cachedelay))
70
-			{
71
-				$foundintocache=1;
72
-
73
-				$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
74
-			}
75
-			else
76
-			{
77
-				dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
78
-			}
79
-		}
80
-		// Load file into $data
81
-		if ($foundintocache)    // Cache file found and is not too old
82
-		{
83
-			dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
84
-			$data = json_decode(file_get_contents($newpathofdestfile), true);
85
-		}
86
-		else
87
-		{
88
-			$year=$startyear;
89
-			while ($year <= $endyear)
90
-			{
91
-				$datay[$year] = $this->getNbByMonth($year, $format);
92
-				$year++;
93
-			}
94
-
95
-			$data = array();
96
-
97
-			for ($i = 0 ; $i < 12 ; $i++)
98
-			{
99
-				$data[$i][]=$datay[$endyear][$i][0];
100
-				$year=$startyear;
101
-				while($year <= $endyear)
102
-				{
103
-					$data[$i][]=$datay[$year][$i][1];
104
-					$year++;
105
-				}
106
-			}
107
-		}
108
-
109
-		// Save cache file
110
-		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
111
-		{
112
-			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
113
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
114
-			$fp = fopen($newpathofdestfile, 'w');
115
-			fwrite($fp, json_encode($data));
116
-			fclose($fp);
117
-			if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
118
-			@chmod($newpathofdestfile, octdec($newmask));
119
-
120
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
121
-		}
122
-
123
-		// return array(array('Month',val1,val2,val3),...)
124
-		return $data;
125
-	}
126
-
127
-	/**
128
-	 * Return amount of elements by month for several years.
129
-	 * Criterias used to build request are defined into the constructor of parent class into xxx/class/xxxstats.class.php
130
-	 * The caller of class can add more filters into sql request by adding criteris into the $stats->where property just after
131
-	 * calling constructor.
132
-	 *
133
-	 * @param	int		$endyear		Start year
134
-	 * @param	int		$startyear		End year
135
-	 * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
136
-     * @param	int		$format			0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
137
-	 * @return 	array					Array of values
138
-	 */
139
-	function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
140
-	{
141
-		global $conf,$user,$langs;
43
+     * @return 	array					Array of values
44
+     */
45
+    function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
46
+    {
47
+        global $conf,$user,$langs;
142 48
 
143 49
         if ($startyear > $endyear) return -1;
144 50
 
@@ -147,8 +53,8 @@  discard block
 block discarded – undo
147 53
         // Search into cache
148 54
         if (! empty($cachedelay))
149 55
         {
150
-        	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
151
-        	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
56
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
57
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
152 58
         }
153 59
 
154 60
         $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
@@ -159,122 +65,216 @@  discard block
 block discarded – undo
159 65
         $foundintocache=0;
160 66
         if ($cachedelay > 0)
161 67
         {
162
-        	$filedate=dol_filemtime($newpathofdestfile);
163
-        	if ($filedate >= ($nowgmt - $cachedelay))
164
-        	{
165
-        		$foundintocache=1;
68
+            $filedate=dol_filemtime($newpathofdestfile);
69
+            if ($filedate >= ($nowgmt - $cachedelay))
70
+            {
71
+                $foundintocache=1;
72
+
73
+                $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
74
+            }
75
+            else
76
+            {
77
+                dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
78
+            }
79
+        }
80
+        // Load file into $data
81
+        if ($foundintocache)    // Cache file found and is not too old
82
+        {
83
+            dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
84
+            $data = json_decode(file_get_contents($newpathofdestfile), true);
85
+        }
86
+        else
87
+        {
88
+            $year=$startyear;
89
+            while ($year <= $endyear)
90
+            {
91
+                $datay[$year] = $this->getNbByMonth($year, $format);
92
+                $year++;
93
+            }
94
+
95
+            $data = array();
96
+
97
+            for ($i = 0 ; $i < 12 ; $i++)
98
+            {
99
+                $data[$i][]=$datay[$endyear][$i][0];
100
+                $year=$startyear;
101
+                while($year <= $endyear)
102
+                {
103
+                    $data[$i][]=$datay[$year][$i][1];
104
+                    $year++;
105
+                }
106
+            }
107
+        }
108
+
109
+        // Save cache file
110
+        if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
111
+        {
112
+            dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
113
+            if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
114
+            $fp = fopen($newpathofdestfile, 'w');
115
+            fwrite($fp, json_encode($data));
116
+            fclose($fp);
117
+            if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
118
+            @chmod($newpathofdestfile, octdec($newmask));
119
+
120
+            $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
121
+        }
122
+
123
+        // return array(array('Month',val1,val2,val3),...)
124
+        return $data;
125
+    }
126
+
127
+    /**
128
+     * Return amount of elements by month for several years.
129
+     * Criterias used to build request are defined into the constructor of parent class into xxx/class/xxxstats.class.php
130
+     * The caller of class can add more filters into sql request by adding criteris into the $stats->where property just after
131
+     * calling constructor.
132
+     *
133
+     * @param	int		$endyear		Start year
134
+     * @param	int		$startyear		End year
135
+     * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
136
+     * @param	int		$format			0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
137
+     * @return 	array					Array of values
138
+     */
139
+    function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
140
+    {
141
+        global $conf,$user,$langs;
166 142
 
167
-        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
168
-        	}
169
-        	else
170
-        	{
171
-        		dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
172
-        	}
143
+        if ($startyear > $endyear) return -1;
144
+
145
+        $datay=array();
146
+
147
+        // Search into cache
148
+        if (! empty($cachedelay))
149
+        {
150
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
151
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
152
+        }
153
+
154
+        $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
155
+        $newmask='0644';
156
+
157
+        $nowgmt = dol_now();
158
+
159
+        $foundintocache=0;
160
+        if ($cachedelay > 0)
161
+        {
162
+            $filedate=dol_filemtime($newpathofdestfile);
163
+            if ($filedate >= ($nowgmt - $cachedelay))
164
+            {
165
+                $foundintocache=1;
166
+
167
+                $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
168
+            }
169
+            else
170
+            {
171
+                dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
172
+            }
173 173
         }
174 174
 
175 175
         // Load file into $data
176 176
         if ($foundintocache)    // Cache file found and is not too old
177 177
         {
178
-        	dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
179
-        	$data = json_decode(file_get_contents($newpathofdestfile), true);
178
+            dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
179
+            $data = json_decode(file_get_contents($newpathofdestfile), true);
180 180
         }
181 181
         else
182
-		{
183
-			$year=$startyear;
184
-			while($year <= $endyear)
185
-			{
186
-				$datay[$year] = $this->getAmountByMonth($year, $format);
187
-				$year++;
188
-			}
189
-
190
-			$data = array();
191
-			// $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
192
-			for ($i = 0 ; $i < 12 ; $i++)
193
-			{
194
-				$data[$i][]=$datay[$endyear][$i][0];	// set label
195
-				$year=$startyear;
196
-				while($year <= $endyear)
197
-				{
198
-					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
199
-					$year++;
200
-				}
201
-			}
202
-		}
203
-
204
-		// Save cache file
205
-		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
206
-		{
207
-			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
208
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
209
-			$fp = fopen($newpathofdestfile, 'w');
210
-			if ($fp)
211
-			{
212
-				fwrite($fp, json_encode($data));
213
-				fclose($fp);
214
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
215
-				@chmod($newpathofdestfile, octdec($newmask));
216
-			}
217
-			else dol_syslog("Failed to write cache file", LOG_ERR);
218
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
219
-		}
220
-
221
-		return $data;
222
-	}
223
-
224
-	/**
225
-	 * Return average of entity by month for several years
226
-	 *
227
-	 * @param	int		$endyear		Start year
228
-	 * @param	int		$startyear		End year
229
-	 * @return 	array					Array of values
230
-	 */
231
-	function getAverageByMonthWithPrevYear($endyear,$startyear)
232
-	{
182
+        {
183
+            $year=$startyear;
184
+            while($year <= $endyear)
185
+            {
186
+                $datay[$year] = $this->getAmountByMonth($year, $format);
187
+                $year++;
188
+            }
189
+
190
+            $data = array();
191
+            // $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
192
+            for ($i = 0 ; $i < 12 ; $i++)
193
+            {
194
+                $data[$i][]=$datay[$endyear][$i][0];	// set label
195
+                $year=$startyear;
196
+                while($year <= $endyear)
197
+                {
198
+                    $data[$i][]=$datay[$year][$i][1];	// set yval for x=i
199
+                    $year++;
200
+                }
201
+            }
202
+        }
203
+
204
+        // Save cache file
205
+        if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
206
+        {
207
+            dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
208
+            if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
209
+            $fp = fopen($newpathofdestfile, 'w');
210
+            if ($fp)
211
+            {
212
+                fwrite($fp, json_encode($data));
213
+                fclose($fp);
214
+                if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
215
+                @chmod($newpathofdestfile, octdec($newmask));
216
+            }
217
+            else dol_syslog("Failed to write cache file", LOG_ERR);
218
+            $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
219
+        }
220
+
221
+        return $data;
222
+    }
223
+
224
+    /**
225
+     * Return average of entity by month for several years
226
+     *
227
+     * @param	int		$endyear		Start year
228
+     * @param	int		$startyear		End year
229
+     * @return 	array					Array of values
230
+     */
231
+    function getAverageByMonthWithPrevYear($endyear,$startyear)
232
+    {
233 233
         if ($startyear > $endyear) return -1;
234 234
 
235 235
         $datay=array();
236 236
 
237
-		$year=$startyear;
238
-		while($year <= $endyear)
239
-		{
240
-			$datay[$year] = $this->getAverageByMonth($year);
241
-			$year++;
242
-		}
243
-
244
-		$data = array();
245
-
246
-		for ($i = 0 ; $i < 12 ; $i++)
247
-		{
248
-			$data[$i][]=$datay[$endyear][$i][0];
249
-			$year=$startyear;
250
-			while($year <= $endyear)
251
-			{
252
-				$data[$i][]=$datay[$year][$i][1];
253
-				$year++;
254
-			}
255
-		}
256
-
257
-		return $data;
258
-	}
259
-
260
-	/**
261
-	 * Return count, and sum of products
262
-	 *
263
-	 * @param	int		$year			Year
264
-	 * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
265
-	 * @return 	array					Array of values
266
-	 */
267
-	function getAllByProductEntry($year,$cachedelay=0)
268
-	{
269
-		global $conf,$user,$langs;
237
+        $year=$startyear;
238
+        while($year <= $endyear)
239
+        {
240
+            $datay[$year] = $this->getAverageByMonth($year);
241
+            $year++;
242
+        }
243
+
244
+        $data = array();
245
+
246
+        for ($i = 0 ; $i < 12 ; $i++)
247
+        {
248
+            $data[$i][]=$datay[$endyear][$i][0];
249
+            $year=$startyear;
250
+            while($year <= $endyear)
251
+            {
252
+                $data[$i][]=$datay[$year][$i][1];
253
+                $year++;
254
+            }
255
+        }
256
+
257
+        return $data;
258
+    }
259
+
260
+    /**
261
+     * Return count, and sum of products
262
+     *
263
+     * @param	int		$year			Year
264
+     * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
265
+     * @return 	array					Array of values
266
+     */
267
+    function getAllByProductEntry($year,$cachedelay=0)
268
+    {
269
+        global $conf,$user,$langs;
270 270
 
271 271
         $datay=array();
272 272
 
273 273
         // Search into cache
274 274
         if (! empty($cachedelay))
275 275
         {
276
-        	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
277
-        	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
276
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
277
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
278 278
         }
279 279
 
280 280
         $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
@@ -285,324 +285,324 @@  discard block
 block discarded – undo
285 285
         $foundintocache=0;
286 286
         if ($cachedelay > 0)
287 287
         {
288
-        	$filedate=dol_filemtime($newpathofdestfile);
289
-        	if ($filedate >= ($nowgmt - $cachedelay))
290
-        	{
291
-        		$foundintocache=1;
292
-
293
-        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
294
-        	}
295
-        	else
296
-        	{
297
-        		dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
298
-        	}
288
+            $filedate=dol_filemtime($newpathofdestfile);
289
+            if ($filedate >= ($nowgmt - $cachedelay))
290
+            {
291
+                $foundintocache=1;
292
+
293
+                $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
294
+            }
295
+            else
296
+            {
297
+                dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
298
+            }
299 299
         }
300 300
 
301 301
         // Load file into $data
302 302
         if ($foundintocache)    // Cache file found and is not too old
303 303
         {
304
-        	dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
305
-        	$data = json_decode(file_get_contents($newpathofdestfile), true);
304
+            dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
305
+            $data = json_decode(file_get_contents($newpathofdestfile), true);
306 306
         }
307 307
         else
308
-		{
309
-			$data=$this->getAllByProduct($year);
310
-			//					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
311
-		}
312
-
313
-		// Save cache file
314
-		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
315
-		{
316
-			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
317
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
318
-			$fp = fopen($newpathofdestfile, 'w');
319
-			if ($fp)
320
-			{
321
-				fwrite($fp, json_encode($data));
322
-				fclose($fp);
323
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
324
-				@chmod($newpathofdestfile, octdec($newmask));
325
-			}
326
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
327
-		}
328
-
329
-		return $data;
330
-	}
331
-
332
-
333
-	// Here we have low level of shared code called by XxxStats.class.php
334
-
335
-
336
-	/**
337
-	 * 	Return nb of elements by year
338
-	 *
339
-	 *	@param	string	$sql		SQL request
340
-	 * 	@return	array
341
-	 */
342
-	function _getNbByYear($sql)
343
-	{
344
-		$result = array();
345
-
346
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
347
-		$resql=$this->db->query($sql);
348
-		if ($resql)
349
-		{
350
-			$num = $this->db->num_rows($resql);
351
-			$i = 0;
352
-			while ($i < $num)
353
-			{
354
-				$row = $this->db->fetch_row($resql);
355
-				$result[$i] = $row;
356
-				$i++;
357
-			}
358
-			$this->db->free($resql);
359
-		}
360
-		else {
361
-			dol_print_error($this->db);
362
-		}
363
-		return $result;
364
-	}
365
-
366
-	/**
367
-	 * 	Return nb of elements, total amount and avg amount each year
368
-	 *
369
-	 *	@param	string	$sql	SQL request
370
-	 * 	@return	array			Array with nb, total amount, average for each year
371
-	 */
372
-	function _getAllByYear($sql)
373
-	{
374
-		$result = array();
375
-
376
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
377
-		$resql=$this->db->query($sql);
378
-		if ($resql)
379
-		{
380
-			$num = $this->db->num_rows($resql);
381
-			$i = 0;
382
-			while ($i < $num)
383
-			{
384
-				$row = $this->db->fetch_object($resql);
385
-				$result[$i]['year'] = $row->year;
386
-				$result[$i]['nb'] = $row->nb;
387
-				if($i>0 && $row->nb) $result[$i-1]['nb_diff'] = ($result[$i-1]['nb'] - $row->nb) / $row->nb * 100;
388
-				$result[$i]['total'] = $row->total;
389
-				if($i>0 && $row->total) $result[$i-1]['total_diff'] = ($result[$i-1]['total'] - $row->total) / $row->total * 100;
390
-				$result[$i]['avg'] = $row->avg;
391
-				if($i>0 && $row->avg) $result[$i-1]['avg_diff'] = ($result[$i-1]['avg'] - $row->avg) / $row->avg * 100;
392
-				// For some $sql only
393
-				if (isset($row->weighted))
394
-				{
395
-				    $result[$i]['weighted'] = $row->weighted;
396
-				    if($i>0 && $row->weighted) $result[$i-1]['avg_weighted'] = ($result[$i-1]['weighted'] - $row->weighted) / $row->weighted * 100;
397
-				}
398
-				$i++;
399
-			}
400
-			$this->db->free($resql);
401
-		}
402
-		else {
403
-			dol_print_error($this->db);
404
-		}
405
-		return $result;
406
-	}
407
-
408
-	/**
409
-	 *     Renvoie le nombre de proposition par mois pour une annee donnee
410
-	 *
308
+        {
309
+            $data=$this->getAllByProduct($year);
310
+            //					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
311
+        }
312
+
313
+        // Save cache file
314
+        if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
315
+        {
316
+            dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
317
+            if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
318
+            $fp = fopen($newpathofdestfile, 'w');
319
+            if ($fp)
320
+            {
321
+                fwrite($fp, json_encode($data));
322
+                fclose($fp);
323
+                if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
324
+                @chmod($newpathofdestfile, octdec($newmask));
325
+            }
326
+            $this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
327
+        }
328
+
329
+        return $data;
330
+    }
331
+
332
+
333
+    // Here we have low level of shared code called by XxxStats.class.php
334
+
335
+
336
+    /**
337
+     * 	Return nb of elements by year
338
+     *
339
+     *	@param	string	$sql		SQL request
340
+     * 	@return	array
341
+     */
342
+    function _getNbByYear($sql)
343
+    {
344
+        $result = array();
345
+
346
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
347
+        $resql=$this->db->query($sql);
348
+        if ($resql)
349
+        {
350
+            $num = $this->db->num_rows($resql);
351
+            $i = 0;
352
+            while ($i < $num)
353
+            {
354
+                $row = $this->db->fetch_row($resql);
355
+                $result[$i] = $row;
356
+                $i++;
357
+            }
358
+            $this->db->free($resql);
359
+        }
360
+        else {
361
+            dol_print_error($this->db);
362
+        }
363
+        return $result;
364
+    }
365
+
366
+    /**
367
+     * 	Return nb of elements, total amount and avg amount each year
368
+     *
369
+     *	@param	string	$sql	SQL request
370
+     * 	@return	array			Array with nb, total amount, average for each year
371
+     */
372
+    function _getAllByYear($sql)
373
+    {
374
+        $result = array();
375
+
376
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
377
+        $resql=$this->db->query($sql);
378
+        if ($resql)
379
+        {
380
+            $num = $this->db->num_rows($resql);
381
+            $i = 0;
382
+            while ($i < $num)
383
+            {
384
+                $row = $this->db->fetch_object($resql);
385
+                $result[$i]['year'] = $row->year;
386
+                $result[$i]['nb'] = $row->nb;
387
+                if($i>0 && $row->nb) $result[$i-1]['nb_diff'] = ($result[$i-1]['nb'] - $row->nb) / $row->nb * 100;
388
+                $result[$i]['total'] = $row->total;
389
+                if($i>0 && $row->total) $result[$i-1]['total_diff'] = ($result[$i-1]['total'] - $row->total) / $row->total * 100;
390
+                $result[$i]['avg'] = $row->avg;
391
+                if($i>0 && $row->avg) $result[$i-1]['avg_diff'] = ($result[$i-1]['avg'] - $row->avg) / $row->avg * 100;
392
+                // For some $sql only
393
+                if (isset($row->weighted))
394
+                {
395
+                    $result[$i]['weighted'] = $row->weighted;
396
+                    if($i>0 && $row->weighted) $result[$i-1]['avg_weighted'] = ($result[$i-1]['weighted'] - $row->weighted) / $row->weighted * 100;
397
+                }
398
+                $i++;
399
+            }
400
+            $this->db->free($resql);
401
+        }
402
+        else {
403
+            dol_print_error($this->db);
404
+        }
405
+        return $result;
406
+    }
407
+
408
+    /**
409
+     *     Renvoie le nombre de proposition par mois pour une annee donnee
410
+     *
411 411
      *     @param   int		$year       Year
412 412
      *     @param   string	$sql        SQL
413 413
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
414 414
      *     @return	array				Array of nb each month
415
-	 */
416
-	function _getNbByMonth($year, $sql, $format=0)
417
-	{
418
-		global $langs;
419
-
420
-		$result=array();
421
-		$res=array();
422
-
423
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
424
-		$resql=$this->db->query($sql);
425
-		if ($resql)
426
-		{
427
-			$num = $this->db->num_rows($resql);
428
-			$i = 0; $j = 0;
429
-			while ($i < $num)
430
-			{
431
-				$row = $this->db->fetch_row($resql);
432
-				$j = $row[0] * 1;
433
-				$result[$j] = $row[1];
434
-				$i++;
435
-			}
436
-			$this->db->free($resql);
437
-		}
438
-		else
439
-		{
440
-			dol_print_error($this->db);
441
-		}
442
-
443
-		for ($i = 1 ; $i < 13 ; $i++)
444
-		{
445
-			$res[$i] = (isset($result[$i])?$result[$i]:0);
446
-		}
447
-
448
-		$data = array();
449
-
450
-		for ($i = 1 ; $i < 13 ; $i++)
451
-		{
452
-			$month='unknown';
453
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
454
-			elseif ($format == 1) $month=$i;
455
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
456
-			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
457
-			//$month=dol_substr($month,0,3);
458
-			$data[$i-1] = array($month, $res[$i]);
459
-		}
460
-
461
-		return $data;
462
-	}
463
-
464
-
465
-	/**
466
-	 *     Renvoie le nombre d'element par mois pour une annee donnee
467
-	 *
468
-	 *     @param	int		$year       Year
469
-	 *     @param   string	$sql		SQL
415
+     */
416
+    function _getNbByMonth($year, $sql, $format=0)
417
+    {
418
+        global $langs;
419
+
420
+        $result=array();
421
+        $res=array();
422
+
423
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
424
+        $resql=$this->db->query($sql);
425
+        if ($resql)
426
+        {
427
+            $num = $this->db->num_rows($resql);
428
+            $i = 0; $j = 0;
429
+            while ($i < $num)
430
+            {
431
+                $row = $this->db->fetch_row($resql);
432
+                $j = $row[0] * 1;
433
+                $result[$j] = $row[1];
434
+                $i++;
435
+            }
436
+            $this->db->free($resql);
437
+        }
438
+        else
439
+        {
440
+            dol_print_error($this->db);
441
+        }
442
+
443
+        for ($i = 1 ; $i < 13 ; $i++)
444
+        {
445
+            $res[$i] = (isset($result[$i])?$result[$i]:0);
446
+        }
447
+
448
+        $data = array();
449
+
450
+        for ($i = 1 ; $i < 13 ; $i++)
451
+        {
452
+            $month='unknown';
453
+            if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
454
+            elseif ($format == 1) $month=$i;
455
+            elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
456
+            //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
457
+            //$month=dol_substr($month,0,3);
458
+            $data[$i-1] = array($month, $res[$i]);
459
+        }
460
+
461
+        return $data;
462
+    }
463
+
464
+
465
+    /**
466
+     *     Renvoie le nombre d'element par mois pour une annee donnee
467
+     *
468
+     *     @param	int		$year       Year
469
+     *     @param   string	$sql		SQL
470 470
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
471
-	 *     @return	array
472
-	 */
473
-	function _getAmountByMonth($year, $sql, $format=0)
474
-	{
475
-		global $langs;
476
-
477
-		$result=array();
478
-		$res=array();
479
-
480
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
481
-
482
-		$resql=$this->db->query($sql);
483
-		if ($resql)
484
-		{
485
-			$num = $this->db->num_rows($resql);
486
-			$i = 0;
487
-			while ($i < $num)
488
-		  	{
489
-		  		$row = $this->db->fetch_row($resql);
490
-		  		$j = $row[0] * 1;
491
-		  		$result[$j] = $row[1];
492
-		  		$i++;
493
-		  	}
494
-		  	$this->db->free($resql);
495
-		}
471
+     *     @return	array
472
+     */
473
+    function _getAmountByMonth($year, $sql, $format=0)
474
+    {
475
+        global $langs;
476
+
477
+        $result=array();
478
+        $res=array();
479
+
480
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
481
+
482
+        $resql=$this->db->query($sql);
483
+        if ($resql)
484
+        {
485
+            $num = $this->db->num_rows($resql);
486
+            $i = 0;
487
+            while ($i < $num)
488
+                {
489
+                    $row = $this->db->fetch_row($resql);
490
+                    $j = $row[0] * 1;
491
+                    $result[$j] = $row[1];
492
+                    $i++;
493
+                }
494
+                $this->db->free($resql);
495
+        }
496 496
         else dol_print_error($this->db);
497 497
 
498
-		for ($i = 1 ; $i < 13 ; $i++)
499
-		{
500
-			$res[$i] = (int) round((isset($result[$i])?$result[$i]:0));
501
-		}
502
-
503
-		$data = array();
504
-
505
-		for ($i = 1 ; $i < 13 ; $i++)
506
-		{
507
-			$month='unknown';
508
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
509
-			elseif ($format == 1) $month=$i;
510
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
511
-			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
512
-			//$month=dol_substr($month,0,3);
513
-			$data[$i-1] = array($month, $res[$i]);
514
-		}
515
-
516
-		return $data;
517
-	}
518
-
519
-	/**
520
-	 *	   Renvoie le montant moyen par mois pour une annee donnee
521
-	 *
498
+        for ($i = 1 ; $i < 13 ; $i++)
499
+        {
500
+            $res[$i] = (int) round((isset($result[$i])?$result[$i]:0));
501
+        }
502
+
503
+        $data = array();
504
+
505
+        for ($i = 1 ; $i < 13 ; $i++)
506
+        {
507
+            $month='unknown';
508
+            if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
509
+            elseif ($format == 1) $month=$i;
510
+            elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
511
+            //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
512
+            //$month=dol_substr($month,0,3);
513
+            $data[$i-1] = array($month, $res[$i]);
514
+        }
515
+
516
+        return $data;
517
+    }
518
+
519
+    /**
520
+     *	   Renvoie le montant moyen par mois pour une annee donnee
521
+     *
522 522
      *     @param	int		$year       Year
523 523
      *     @param  	string	$sql        SQL
524 524
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
525
-	 *     @return	array
526
-	 */
527
-	function _getAverageByMonth($year, $sql, $format=0)
528
-	{
529
-		global $langs;
530
-
531
-		$result=array();
532
-		$res=array();
533
-
534
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
535
-		$resql=$this->db->query($sql);
536
-		if ($resql)
537
-		{
538
-			$num = $this->db->num_rows($resql);
539
-			$i = 0; $j = 0;
540
-			while ($i < $num)
541
-			{
542
-		  		$row = $this->db->fetch_row($resql);
543
-		  		$j = $row[0] * 1;
544
-		  		$result[$j] = $row[1];
545
-		  		$i++;
546
-		  	}
547
-		  	$this->db->free($resql);
548
-		}
525
+     *     @return	array
526
+     */
527
+    function _getAverageByMonth($year, $sql, $format=0)
528
+    {
529
+        global $langs;
530
+
531
+        $result=array();
532
+        $res=array();
533
+
534
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
535
+        $resql=$this->db->query($sql);
536
+        if ($resql)
537
+        {
538
+            $num = $this->db->num_rows($resql);
539
+            $i = 0; $j = 0;
540
+            while ($i < $num)
541
+            {
542
+                    $row = $this->db->fetch_row($resql);
543
+                    $j = $row[0] * 1;
544
+                    $result[$j] = $row[1];
545
+                    $i++;
546
+                }
547
+                $this->db->free($resql);
548
+        }
549 549
         else dol_print_error($this->db);
550 550
 
551
-		for ($i = 1 ; $i < 13 ; $i++)
552
-		{
553
-			$res[$i] = (isset($result[$i])?$result[$i]:0);
554
-		}
551
+        for ($i = 1 ; $i < 13 ; $i++)
552
+        {
553
+            $res[$i] = (isset($result[$i])?$result[$i]:0);
554
+        }
555 555
 
556
-		$data = array();
556
+        $data = array();
557 557
 
558
-		for ($i = 1 ; $i < 13 ; $i++)
559
-		{
560
-			$month='unknown';
561
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
562
-			elseif ($format == 1) $month=$i;
563
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
564
-			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
565
-			//$month=dol_substr($month,0,3);
566
-			$data[$i-1] = array($month, $res[$i]);
567
-		}
558
+        for ($i = 1 ; $i < 13 ; $i++)
559
+        {
560
+            $month='unknown';
561
+            if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
562
+            elseif ($format == 1) $month=$i;
563
+            elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
564
+            //$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
565
+            //$month=dol_substr($month,0,3);
566
+            $data[$i-1] = array($month, $res[$i]);
567
+        }
568 568
 
569
-		return $data;
570
-	}
569
+        return $data;
570
+    }
571 571
 
572 572
 
573
-	/**
574
-	 *	   Return number or total of product refs
575
-	 *
573
+    /**
574
+     *	   Return number or total of product refs
575
+     *
576 576
      *     @param  	string	$sql        SQL
577 577
      *     @param	int		$limit		Limit
578 578
      *     @return	array
579
-	 */
580
-	function _getAllByProduct($sql, $limit=10)
581
-	{
582
-		global $langs;
583
-
584
-		$result=array();
585
-		$res=array();
586
-
587
-		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
588
-		$resql=$this->db->query($sql);
589
-		if ($resql)
590
-		{
591
-			$num = $this->db->num_rows($resql);
592
-			$i = 0; $other=0;
593
-			while ($i < $num)
594
-			{
595
-		  		$row = $this->db->fetch_row($resql);
596
-		  		if ($i < $limit || $num == $limit) $result[$i] = array($row[0],$row[1]);	// Ref of product, nb
597
-		  		else $other += $row[1];
598
-		  		$i++;
599
-		  	}
600
-		  	if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"),$other);
601
-		  	$this->db->free($resql);
602
-		}
579
+     */
580
+    function _getAllByProduct($sql, $limit=10)
581
+    {
582
+        global $langs;
583
+
584
+        $result=array();
585
+        $res=array();
586
+
587
+        dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
588
+        $resql=$this->db->query($sql);
589
+        if ($resql)
590
+        {
591
+            $num = $this->db->num_rows($resql);
592
+            $i = 0; $other=0;
593
+            while ($i < $num)
594
+            {
595
+                    $row = $this->db->fetch_row($resql);
596
+                    if ($i < $limit || $num == $limit) $result[$i] = array($row[0],$row[1]);	// Ref of product, nb
597
+                    else $other += $row[1];
598
+                    $i++;
599
+                }
600
+                if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"),$other);
601
+                $this->db->free($resql);
602
+        }
603 603
         else dol_print_error($this->db);
604 604
 
605
-		return $result;
606
-	}
605
+        return $result;
606
+    }
607 607
 }
608 608
 
Please login to merge, or discard this patch.
Spacing   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -30,8 +30,8 @@  discard block
 block discarded – undo
30 30
 abstract class Stats
31 31
 {
32 32
 	protected $db;
33
-	var $_lastfetchdate=array();	// Dates of cache file read by methods
34
-	var $cachefilesuffix='';		// Suffix to add to name of cache file (to avoid file name conflicts)
33
+	var $_lastfetchdate = array(); // Dates of cache file read by methods
34
+	var $cachefilesuffix = ''; // Suffix to add to name of cache file (to avoid file name conflicts)
35 35
 
36 36
 	/**
37 37
 	 * Return nb of elements by month for several years
@@ -42,35 +42,35 @@  discard block
 block discarded – undo
42 42
      *	@param	int		$format			0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
43 43
 	 * @return 	array					Array of values
44 44
 	 */
45
-	function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
45
+	function getNbByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0)
46 46
 	{
47
-		global $conf,$user,$langs;
47
+		global $conf, $user, $langs;
48 48
 
49 49
 	    if ($startyear > $endyear) return -1;
50 50
 
51
-		$datay=array();
51
+		$datay = array();
52 52
 
53 53
 		// Search into cache
54
-		if (! empty($cachedelay))
54
+		if (!empty($cachedelay))
55 55
 	    {
56 56
 	    	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
57 57
 	    	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
58 58
 	    }
59 59
 
60
-		$newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
61
-		$newmask='0644';
60
+		$newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
61
+		$newmask = '0644';
62 62
 
63 63
 		$nowgmt = dol_now();
64 64
 
65
-		$foundintocache=0;
65
+		$foundintocache = 0;
66 66
 		if ($cachedelay > 0)
67 67
 		{
68
-			$filedate=dol_filemtime($newpathofdestfile);
68
+			$filedate = dol_filemtime($newpathofdestfile);
69 69
 			if ($filedate >= ($nowgmt - $cachedelay))
70 70
 			{
71
-				$foundintocache=1;
71
+				$foundintocache = 1;
72 72
 
73
-				$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
73
+				$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
74 74
 			}
75 75
 			else
76 76
 			{
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 		}
86 86
 		else
87 87
 		{
88
-			$year=$startyear;
88
+			$year = $startyear;
89 89
 			while ($year <= $endyear)
90 90
 			{
91 91
 				$datay[$year] = $this->getNbByMonth($year, $format);
@@ -94,13 +94,13 @@  discard block
 block discarded – undo
94 94
 
95 95
 			$data = array();
96 96
 
97
-			for ($i = 0 ; $i < 12 ; $i++)
97
+			for ($i = 0; $i < 12; $i++)
98 98
 			{
99
-				$data[$i][]=$datay[$endyear][$i][0];
100
-				$year=$startyear;
101
-				while($year <= $endyear)
99
+				$data[$i][] = $datay[$endyear][$i][0];
100
+				$year = $startyear;
101
+				while ($year <= $endyear)
102 102
 				{
103
-					$data[$i][]=$datay[$year][$i][1];
103
+					$data[$i][] = $datay[$year][$i][1];
104 104
 					$year++;
105 105
 				}
106 106
 			}
@@ -110,14 +110,14 @@  discard block
 block discarded – undo
110 110
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
111 111
 		{
112 112
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
113
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
113
+			if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
114 114
 			$fp = fopen($newpathofdestfile, 'w');
115 115
 			fwrite($fp, json_encode($data));
116 116
 			fclose($fp);
117
-			if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
117
+			if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
118 118
 			@chmod($newpathofdestfile, octdec($newmask));
119 119
 
120
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
120
+			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
121 121
 		}
122 122
 
123 123
 		// return array(array('Month',val1,val2,val3),...)
@@ -136,35 +136,35 @@  discard block
 block discarded – undo
136 136
      * @param	int		$format			0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
137 137
 	 * @return 	array					Array of values
138 138
 	 */
139
-	function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay=0, $format=0)
139
+	function getAmountByMonthWithPrevYear($endyear, $startyear, $cachedelay = 0, $format = 0)
140 140
 	{
141
-		global $conf,$user,$langs;
141
+		global $conf, $user, $langs;
142 142
 
143 143
         if ($startyear > $endyear) return -1;
144 144
 
145
-        $datay=array();
145
+        $datay = array();
146 146
 
147 147
         // Search into cache
148
-        if (! empty($cachedelay))
148
+        if (!empty($cachedelay))
149 149
         {
150 150
         	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
151 151
         	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
152 152
         }
153 153
 
154
-        $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
155
-        $newmask='0644';
154
+        $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
155
+        $newmask = '0644';
156 156
 
157 157
         $nowgmt = dol_now();
158 158
 
159
-        $foundintocache=0;
159
+        $foundintocache = 0;
160 160
         if ($cachedelay > 0)
161 161
         {
162
-        	$filedate=dol_filemtime($newpathofdestfile);
162
+        	$filedate = dol_filemtime($newpathofdestfile);
163 163
         	if ($filedate >= ($nowgmt - $cachedelay))
164 164
         	{
165
-        		$foundintocache=1;
165
+        		$foundintocache = 1;
166 166
 
167
-        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
167
+        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
168 168
         	}
169 169
         	else
170 170
         	{
@@ -180,8 +180,8 @@  discard block
 block discarded – undo
180 180
         }
181 181
         else
182 182
 		{
183
-			$year=$startyear;
184
-			while($year <= $endyear)
183
+			$year = $startyear;
184
+			while ($year <= $endyear)
185 185
 			{
186 186
 				$datay[$year] = $this->getAmountByMonth($year, $format);
187 187
 				$year++;
@@ -189,13 +189,13 @@  discard block
 block discarded – undo
189 189
 
190 190
 			$data = array();
191 191
 			// $data = array('xval'=>array(0=>xlabel,1=>yval1,2=>yval2...),...)
192
-			for ($i = 0 ; $i < 12 ; $i++)
192
+			for ($i = 0; $i < 12; $i++)
193 193
 			{
194
-				$data[$i][]=$datay[$endyear][$i][0];	// set label
195
-				$year=$startyear;
196
-				while($year <= $endyear)
194
+				$data[$i][] = $datay[$endyear][$i][0]; // set label
195
+				$year = $startyear;
196
+				while ($year <= $endyear)
197 197
 				{
198
-					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
198
+					$data[$i][] = $datay[$year][$i][1]; // set yval for x=i
199 199
 					$year++;
200 200
 				}
201 201
 			}
@@ -205,17 +205,17 @@  discard block
 block discarded – undo
205 205
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
206 206
 		{
207 207
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
208
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
208
+			if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
209 209
 			$fp = fopen($newpathofdestfile, 'w');
210 210
 			if ($fp)
211 211
 			{
212 212
 				fwrite($fp, json_encode($data));
213 213
 				fclose($fp);
214
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
214
+				if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
215 215
 				@chmod($newpathofdestfile, octdec($newmask));
216 216
 			}
217 217
 			else dol_syslog("Failed to write cache file", LOG_ERR);
218
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
218
+			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
219 219
 		}
220 220
 
221 221
 		return $data;
@@ -228,14 +228,14 @@  discard block
 block discarded – undo
228 228
 	 * @param	int		$startyear		End year
229 229
 	 * @return 	array					Array of values
230 230
 	 */
231
-	function getAverageByMonthWithPrevYear($endyear,$startyear)
231
+	function getAverageByMonthWithPrevYear($endyear, $startyear)
232 232
 	{
233 233
         if ($startyear > $endyear) return -1;
234 234
 
235
-        $datay=array();
235
+        $datay = array();
236 236
 
237
-		$year=$startyear;
238
-		while($year <= $endyear)
237
+		$year = $startyear;
238
+		while ($year <= $endyear)
239 239
 		{
240 240
 			$datay[$year] = $this->getAverageByMonth($year);
241 241
 			$year++;
@@ -243,13 +243,13 @@  discard block
 block discarded – undo
243 243
 
244 244
 		$data = array();
245 245
 
246
-		for ($i = 0 ; $i < 12 ; $i++)
246
+		for ($i = 0; $i < 12; $i++)
247 247
 		{
248
-			$data[$i][]=$datay[$endyear][$i][0];
249
-			$year=$startyear;
250
-			while($year <= $endyear)
248
+			$data[$i][] = $datay[$endyear][$i][0];
249
+			$year = $startyear;
250
+			while ($year <= $endyear)
251 251
 			{
252
-				$data[$i][]=$datay[$year][$i][1];
252
+				$data[$i][] = $datay[$year][$i][1];
253 253
 				$year++;
254 254
 			}
255 255
 		}
@@ -264,33 +264,33 @@  discard block
 block discarded – undo
264 264
 	 * @param	int		$cachedelay		Delay we accept for cache file (0=No read, no save of cache, -1=No read but save)
265 265
 	 * @return 	array					Array of values
266 266
 	 */
267
-	function getAllByProductEntry($year,$cachedelay=0)
267
+	function getAllByProductEntry($year, $cachedelay = 0)
268 268
 	{
269
-		global $conf,$user,$langs;
269
+		global $conf, $user, $langs;
270 270
 
271
-        $datay=array();
271
+        $datay = array();
272 272
 
273 273
         // Search into cache
274
-        if (! empty($cachedelay))
274
+        if (!empty($cachedelay))
275 275
         {
276 276
         	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
277 277
         	include_once DOL_DOCUMENT_ROOT.'/core/lib/json.lib.php';
278 278
         }
279 279
 
280
-        $newpathofdestfile=$conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix)?'':$this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
281
-        $newmask='0644';
280
+        $newpathofdestfile = $conf->user->dir_temp.'/'.get_class($this).'_'.__FUNCTION__.'_'.(empty($this->cachefilesuffix) ? '' : $this->cachefilesuffix.'_').$langs->defaultlang.'_entity.'.$conf->entity.'_user'.$user->id.'.cache';
281
+        $newmask = '0644';
282 282
 
283 283
         $nowgmt = dol_now();
284 284
 
285
-        $foundintocache=0;
285
+        $foundintocache = 0;
286 286
         if ($cachedelay > 0)
287 287
         {
288
-        	$filedate=dol_filemtime($newpathofdestfile);
288
+        	$filedate = dol_filemtime($newpathofdestfile);
289 289
         	if ($filedate >= ($nowgmt - $cachedelay))
290 290
         	{
291
-        		$foundintocache=1;
291
+        		$foundintocache = 1;
292 292
 
293
-        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
293
+        		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $filedate;
294 294
         	}
295 295
         	else
296 296
         	{
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
         }
307 307
         else
308 308
 		{
309
-			$data=$this->getAllByProduct($year);
309
+			$data = $this->getAllByProduct($year);
310 310
 			//					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
311 311
 		}
312 312
 
@@ -314,16 +314,16 @@  discard block
 block discarded – undo
314 314
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
315 315
 		{
316 316
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
317
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
317
+			if (!dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
318 318
 			$fp = fopen($newpathofdestfile, 'w');
319 319
 			if ($fp)
320 320
 			{
321 321
 				fwrite($fp, json_encode($data));
322 322
 				fclose($fp);
323
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
323
+				if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
324 324
 				@chmod($newpathofdestfile, octdec($newmask));
325 325
 			}
326
-			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
326
+			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__] = $nowgmt;
327 327
 		}
328 328
 
329 329
 		return $data;
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 		$result = array();
345 345
 
346 346
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
347
-		$resql=$this->db->query($sql);
347
+		$resql = $this->db->query($sql);
348 348
 		if ($resql)
349 349
 		{
350 350
 			$num = $this->db->num_rows($resql);
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 		$result = array();
375 375
 
376 376
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
377
-		$resql=$this->db->query($sql);
377
+		$resql = $this->db->query($sql);
378 378
 		if ($resql)
379 379
 		{
380 380
 			$num = $this->db->num_rows($resql);
@@ -384,16 +384,16 @@  discard block
 block discarded – undo
384 384
 				$row = $this->db->fetch_object($resql);
385 385
 				$result[$i]['year'] = $row->year;
386 386
 				$result[$i]['nb'] = $row->nb;
387
-				if($i>0 && $row->nb) $result[$i-1]['nb_diff'] = ($result[$i-1]['nb'] - $row->nb) / $row->nb * 100;
387
+				if ($i > 0 && $row->nb) $result[$i - 1]['nb_diff'] = ($result[$i - 1]['nb'] - $row->nb) / $row->nb * 100;
388 388
 				$result[$i]['total'] = $row->total;
389
-				if($i>0 && $row->total) $result[$i-1]['total_diff'] = ($result[$i-1]['total'] - $row->total) / $row->total * 100;
389
+				if ($i > 0 && $row->total) $result[$i - 1]['total_diff'] = ($result[$i - 1]['total'] - $row->total) / $row->total * 100;
390 390
 				$result[$i]['avg'] = $row->avg;
391
-				if($i>0 && $row->avg) $result[$i-1]['avg_diff'] = ($result[$i-1]['avg'] - $row->avg) / $row->avg * 100;
391
+				if ($i > 0 && $row->avg) $result[$i - 1]['avg_diff'] = ($result[$i - 1]['avg'] - $row->avg) / $row->avg * 100;
392 392
 				// For some $sql only
393 393
 				if (isset($row->weighted))
394 394
 				{
395 395
 				    $result[$i]['weighted'] = $row->weighted;
396
-				    if($i>0 && $row->weighted) $result[$i-1]['avg_weighted'] = ($result[$i-1]['weighted'] - $row->weighted) / $row->weighted * 100;
396
+				    if ($i > 0 && $row->weighted) $result[$i - 1]['avg_weighted'] = ($result[$i - 1]['weighted'] - $row->weighted) / $row->weighted * 100;
397 397
 				}
398 398
 				$i++;
399 399
 			}
@@ -413,15 +413,15 @@  discard block
 block discarded – undo
413 413
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
414 414
      *     @return	array				Array of nb each month
415 415
 	 */
416
-	function _getNbByMonth($year, $sql, $format=0)
416
+	function _getNbByMonth($year, $sql, $format = 0)
417 417
 	{
418 418
 		global $langs;
419 419
 
420
-		$result=array();
421
-		$res=array();
420
+		$result = array();
421
+		$res = array();
422 422
 
423 423
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
424
-		$resql=$this->db->query($sql);
424
+		$resql = $this->db->query($sql);
425 425
 		if ($resql)
426 426
 		{
427 427
 			$num = $this->db->num_rows($resql);
@@ -440,22 +440,22 @@  discard block
 block discarded – undo
440 440
 			dol_print_error($this->db);
441 441
 		}
442 442
 
443
-		for ($i = 1 ; $i < 13 ; $i++)
443
+		for ($i = 1; $i < 13; $i++)
444 444
 		{
445
-			$res[$i] = (isset($result[$i])?$result[$i]:0);
445
+			$res[$i] = (isset($result[$i]) ? $result[$i] : 0);
446 446
 		}
447 447
 
448 448
 		$data = array();
449 449
 
450
-		for ($i = 1 ; $i < 13 ; $i++)
450
+		for ($i = 1; $i < 13; $i++)
451 451
 		{
452
-			$month='unknown';
453
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
454
-			elseif ($format == 1) $month=$i;
455
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
452
+			$month = 'unknown';
453
+			if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
454
+			elseif ($format == 1) $month = $i;
455
+			elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
456 456
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
457 457
 			//$month=dol_substr($month,0,3);
458
-			$data[$i-1] = array($month, $res[$i]);
458
+			$data[$i - 1] = array($month, $res[$i]);
459 459
 		}
460 460
 
461 461
 		return $data;
@@ -470,16 +470,16 @@  discard block
 block discarded – undo
470 470
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
471 471
 	 *     @return	array
472 472
 	 */
473
-	function _getAmountByMonth($year, $sql, $format=0)
473
+	function _getAmountByMonth($year, $sql, $format = 0)
474 474
 	{
475 475
 		global $langs;
476 476
 
477
-		$result=array();
478
-		$res=array();
477
+		$result = array();
478
+		$res = array();
479 479
 
480 480
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
481 481
 
482
-		$resql=$this->db->query($sql);
482
+		$resql = $this->db->query($sql);
483 483
 		if ($resql)
484 484
 		{
485 485
 			$num = $this->db->num_rows($resql);
@@ -495,22 +495,22 @@  discard block
 block discarded – undo
495 495
 		}
496 496
         else dol_print_error($this->db);
497 497
 
498
-		for ($i = 1 ; $i < 13 ; $i++)
498
+		for ($i = 1; $i < 13; $i++)
499 499
 		{
500
-			$res[$i] = (int) round((isset($result[$i])?$result[$i]:0));
500
+			$res[$i] = (int) round((isset($result[$i]) ? $result[$i] : 0));
501 501
 		}
502 502
 
503 503
 		$data = array();
504 504
 
505
-		for ($i = 1 ; $i < 13 ; $i++)
505
+		for ($i = 1; $i < 13; $i++)
506 506
 		{
507
-			$month='unknown';
508
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
509
-			elseif ($format == 1) $month=$i;
510
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
507
+			$month = 'unknown';
508
+			if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
509
+			elseif ($format == 1) $month = $i;
510
+			elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
511 511
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
512 512
 			//$month=dol_substr($month,0,3);
513
-			$data[$i-1] = array($month, $res[$i]);
513
+			$data[$i - 1] = array($month, $res[$i]);
514 514
 		}
515 515
 
516 516
 		return $data;
@@ -524,15 +524,15 @@  discard block
 block discarded – undo
524 524
      *     @param	int		$format		0=Label of absiss is a translated text, 1=Label of absiss is month number, 2=Label of absiss is first letter of month
525 525
 	 *     @return	array
526 526
 	 */
527
-	function _getAverageByMonth($year, $sql, $format=0)
527
+	function _getAverageByMonth($year, $sql, $format = 0)
528 528
 	{
529 529
 		global $langs;
530 530
 
531
-		$result=array();
532
-		$res=array();
531
+		$result = array();
532
+		$res = array();
533 533
 
534 534
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
535
-		$resql=$this->db->query($sql);
535
+		$resql = $this->db->query($sql);
536 536
 		if ($resql)
537 537
 		{
538 538
 			$num = $this->db->num_rows($resql);
@@ -548,22 +548,22 @@  discard block
 block discarded – undo
548 548
 		}
549 549
         else dol_print_error($this->db);
550 550
 
551
-		for ($i = 1 ; $i < 13 ; $i++)
551
+		for ($i = 1; $i < 13; $i++)
552 552
 		{
553
-			$res[$i] = (isset($result[$i])?$result[$i]:0);
553
+			$res[$i] = (isset($result[$i]) ? $result[$i] : 0);
554 554
 		}
555 555
 
556 556
 		$data = array();
557 557
 
558
-		for ($i = 1 ; $i < 13 ; $i++)
558
+		for ($i = 1; $i < 13; $i++)
559 559
 		{
560
-			$month='unknown';
561
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
562
-			elseif ($format == 1) $month=$i;
563
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
560
+			$month = 'unknown';
561
+			if ($format == 0) $month = $langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
562
+			elseif ($format == 1) $month = $i;
563
+			elseif ($format == 2) $month = $langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
564 564
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
565 565
 			//$month=dol_substr($month,0,3);
566
-			$data[$i-1] = array($month, $res[$i]);
566
+			$data[$i - 1] = array($month, $res[$i]);
567 567
 		}
568 568
 
569 569
 		return $data;
@@ -577,27 +577,27 @@  discard block
 block discarded – undo
577 577
      *     @param	int		$limit		Limit
578 578
      *     @return	array
579 579
 	 */
580
-	function _getAllByProduct($sql, $limit=10)
580
+	function _getAllByProduct($sql, $limit = 10)
581 581
 	{
582 582
 		global $langs;
583 583
 
584
-		$result=array();
585
-		$res=array();
584
+		$result = array();
585
+		$res = array();
586 586
 
587 587
 		dol_syslog(get_class($this).'::'.__FUNCTION__."", LOG_DEBUG);
588
-		$resql=$this->db->query($sql);
588
+		$resql = $this->db->query($sql);
589 589
 		if ($resql)
590 590
 		{
591 591
 			$num = $this->db->num_rows($resql);
592
-			$i = 0; $other=0;
592
+			$i = 0; $other = 0;
593 593
 			while ($i < $num)
594 594
 			{
595 595
 		  		$row = $this->db->fetch_row($resql);
596
-		  		if ($i < $limit || $num == $limit) $result[$i] = array($row[0],$row[1]);	// Ref of product, nb
596
+		  		if ($i < $limit || $num == $limit) $result[$i] = array($row[0], $row[1]); // Ref of product, nb
597 597
 		  		else $other += $row[1];
598 598
 		  		$i++;
599 599
 		  	}
600
-		  	if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"),$other);
600
+		  	if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"), $other);
601 601
 		  	$this->db->free($resql);
602 602
 		}
603 603
         else dol_print_error($this->db);
Please login to merge, or discard this patch.
Braces   +99 added lines, -53 removed lines patch added patch discarded remove patch
@@ -46,7 +46,9 @@  discard block
 block discarded – undo
46 46
 	{
47 47
 		global $conf,$user,$langs;
48 48
 
49
-	    if ($startyear > $endyear) return -1;
49
+	    if ($startyear > $endyear) {
50
+	        return -1;
51
+	    }
50 52
 
51 53
 		$datay=array();
52 54
 
@@ -71,19 +73,19 @@  discard block
 block discarded – undo
71 73
 				$foundintocache=1;
72 74
 
73 75
 				$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
74
-			}
75
-			else
76
+			} else
76 77
 			{
77 78
 				dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
78 79
 			}
79 80
 		}
80 81
 		// Load file into $data
81
-		if ($foundintocache)    // Cache file found and is not too old
82
+		if ($foundintocache) {
83
+		    // Cache file found and is not too old
82 84
 		{
83 85
 			dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
84
-			$data = json_decode(file_get_contents($newpathofdestfile), true);
85 86
 		}
86
-		else
87
+			$data = json_decode(file_get_contents($newpathofdestfile), true);
88
+		} else
87 89
 		{
88 90
 			$year=$startyear;
89 91
 			while ($year <= $endyear)
@@ -110,11 +112,15 @@  discard block
 block discarded – undo
110 112
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
111 113
 		{
112 114
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
113
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
115
+			if (! dol_is_dir($conf->user->dir_temp)) {
116
+			    dol_mkdir($conf->user->dir_temp);
117
+			}
114 118
 			$fp = fopen($newpathofdestfile, 'w');
115 119
 			fwrite($fp, json_encode($data));
116 120
 			fclose($fp);
117
-			if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
121
+			if (! empty($conf->global->MAIN_UMASK)) {
122
+			    $newmask=$conf->global->MAIN_UMASK;
123
+			}
118 124
 			@chmod($newpathofdestfile, octdec($newmask));
119 125
 
120 126
 			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
@@ -140,7 +146,9 @@  discard block
 block discarded – undo
140 146
 	{
141 147
 		global $conf,$user,$langs;
142 148
 
143
-        if ($startyear > $endyear) return -1;
149
+        if ($startyear > $endyear) {
150
+            return -1;
151
+        }
144 152
 
145 153
         $datay=array();
146 154
 
@@ -165,20 +173,20 @@  discard block
 block discarded – undo
165 173
         		$foundintocache=1;
166 174
 
167 175
         		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
168
-        	}
169
-        	else
176
+        	} else
170 177
         	{
171 178
         		dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
172 179
         	}
173 180
         }
174 181
 
175 182
         // Load file into $data
176
-        if ($foundintocache)    // Cache file found and is not too old
183
+        if ($foundintocache) {
184
+            // Cache file found and is not too old
177 185
         {
178 186
         	dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
179
-        	$data = json_decode(file_get_contents($newpathofdestfile), true);
180 187
         }
181
-        else
188
+        	$data = json_decode(file_get_contents($newpathofdestfile), true);
189
+        } else
182 190
 		{
183 191
 			$year=$startyear;
184 192
 			while($year <= $endyear)
@@ -205,16 +213,21 @@  discard block
 block discarded – undo
205 213
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
206 214
 		{
207 215
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
208
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
216
+			if (! dol_is_dir($conf->user->dir_temp)) {
217
+			    dol_mkdir($conf->user->dir_temp);
218
+			}
209 219
 			$fp = fopen($newpathofdestfile, 'w');
210 220
 			if ($fp)
211 221
 			{
212 222
 				fwrite($fp, json_encode($data));
213 223
 				fclose($fp);
214
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
224
+				if (! empty($conf->global->MAIN_UMASK)) {
225
+				    $newmask=$conf->global->MAIN_UMASK;
226
+				}
215 227
 				@chmod($newpathofdestfile, octdec($newmask));
228
+			} else {
229
+			    dol_syslog("Failed to write cache file", LOG_ERR);
216 230
 			}
217
-			else dol_syslog("Failed to write cache file", LOG_ERR);
218 231
 			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
219 232
 		}
220 233
 
@@ -230,7 +243,9 @@  discard block
 block discarded – undo
230 243
 	 */
231 244
 	function getAverageByMonthWithPrevYear($endyear,$startyear)
232 245
 	{
233
-        if ($startyear > $endyear) return -1;
246
+        if ($startyear > $endyear) {
247
+            return -1;
248
+        }
234 249
 
235 250
         $datay=array();
236 251
 
@@ -291,20 +306,20 @@  discard block
 block discarded – undo
291 306
         		$foundintocache=1;
292 307
 
293 308
         		$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$filedate;
294
-        	}
295
-        	else
309
+        	} else
296 310
         	{
297 311
         		dol_syslog(get_class($this).'::'.__FUNCTION__." cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
298 312
         	}
299 313
         }
300 314
 
301 315
         // Load file into $data
302
-        if ($foundintocache)    // Cache file found and is not too old
316
+        if ($foundintocache) {
317
+            // Cache file found and is not too old
303 318
         {
304 319
         	dol_syslog(get_class($this).'::'.__FUNCTION__." read data from cache file ".$newpathofdestfile." ".$filedate.".");
305
-        	$data = json_decode(file_get_contents($newpathofdestfile), true);
306 320
         }
307
-        else
321
+        	$data = json_decode(file_get_contents($newpathofdestfile), true);
322
+        } else
308 323
 		{
309 324
 			$data=$this->getAllByProduct($year);
310 325
 			//					$data[$i][]=$datay[$year][$i][1];	// set yval for x=i
@@ -314,13 +329,17 @@  discard block
 block discarded – undo
314 329
 		if (empty($foundintocache) && ($cachedelay > 0 || $cachedelay == -1))
315 330
 		{
316 331
 			dol_syslog(get_class($this).'::'.__FUNCTION__." save cache file ".$newpathofdestfile." onto disk.");
317
-			if (! dol_is_dir($conf->user->dir_temp)) dol_mkdir($conf->user->dir_temp);
332
+			if (! dol_is_dir($conf->user->dir_temp)) {
333
+			    dol_mkdir($conf->user->dir_temp);
334
+			}
318 335
 			$fp = fopen($newpathofdestfile, 'w');
319 336
 			if ($fp)
320 337
 			{
321 338
 				fwrite($fp, json_encode($data));
322 339
 				fclose($fp);
323
-				if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
340
+				if (! empty($conf->global->MAIN_UMASK)) {
341
+				    $newmask=$conf->global->MAIN_UMASK;
342
+				}
324 343
 				@chmod($newpathofdestfile, octdec($newmask));
325 344
 			}
326 345
 			$this->_lastfetchdate[get_class($this).'_'.__FUNCTION__]=$nowgmt;
@@ -356,8 +375,7 @@  discard block
 block discarded – undo
356 375
 				$i++;
357 376
 			}
358 377
 			$this->db->free($resql);
359
-		}
360
-		else {
378
+		} else {
361 379
 			dol_print_error($this->db);
362 380
 		}
363 381
 		return $result;
@@ -384,22 +402,29 @@  discard block
 block discarded – undo
384 402
 				$row = $this->db->fetch_object($resql);
385 403
 				$result[$i]['year'] = $row->year;
386 404
 				$result[$i]['nb'] = $row->nb;
387
-				if($i>0 && $row->nb) $result[$i-1]['nb_diff'] = ($result[$i-1]['nb'] - $row->nb) / $row->nb * 100;
405
+				if($i>0 && $row->nb) {
406
+				    $result[$i-1]['nb_diff'] = ($result[$i-1]['nb'] - $row->nb) / $row->nb * 100;
407
+				}
388 408
 				$result[$i]['total'] = $row->total;
389
-				if($i>0 && $row->total) $result[$i-1]['total_diff'] = ($result[$i-1]['total'] - $row->total) / $row->total * 100;
409
+				if($i>0 && $row->total) {
410
+				    $result[$i-1]['total_diff'] = ($result[$i-1]['total'] - $row->total) / $row->total * 100;
411
+				}
390 412
 				$result[$i]['avg'] = $row->avg;
391
-				if($i>0 && $row->avg) $result[$i-1]['avg_diff'] = ($result[$i-1]['avg'] - $row->avg) / $row->avg * 100;
413
+				if($i>0 && $row->avg) {
414
+				    $result[$i-1]['avg_diff'] = ($result[$i-1]['avg'] - $row->avg) / $row->avg * 100;
415
+				}
392 416
 				// For some $sql only
393 417
 				if (isset($row->weighted))
394 418
 				{
395 419
 				    $result[$i]['weighted'] = $row->weighted;
396
-				    if($i>0 && $row->weighted) $result[$i-1]['avg_weighted'] = ($result[$i-1]['weighted'] - $row->weighted) / $row->weighted * 100;
420
+				    if($i>0 && $row->weighted) {
421
+				        $result[$i-1]['avg_weighted'] = ($result[$i-1]['weighted'] - $row->weighted) / $row->weighted * 100;
422
+				    }
397 423
 				}
398 424
 				$i++;
399 425
 			}
400 426
 			$this->db->free($resql);
401
-		}
402
-		else {
427
+		} else {
403 428
 			dol_print_error($this->db);
404 429
 		}
405 430
 		return $result;
@@ -434,8 +459,7 @@  discard block
 block discarded – undo
434 459
 				$i++;
435 460
 			}
436 461
 			$this->db->free($resql);
437
-		}
438
-		else
462
+		} else
439 463
 		{
440 464
 			dol_print_error($this->db);
441 465
 		}
@@ -450,9 +474,13 @@  discard block
 block discarded – undo
450 474
 		for ($i = 1 ; $i < 13 ; $i++)
451 475
 		{
452 476
 			$month='unknown';
453
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
454
-			elseif ($format == 1) $month=$i;
455
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
477
+			if ($format == 0) {
478
+			    $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
479
+			} elseif ($format == 1) {
480
+			    $month=$i;
481
+			} elseif ($format == 2) {
482
+			    $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
483
+			}
456 484
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
457 485
 			//$month=dol_substr($month,0,3);
458 486
 			$data[$i-1] = array($month, $res[$i]);
@@ -492,8 +520,9 @@  discard block
 block discarded – undo
492 520
 		  		$i++;
493 521
 		  	}
494 522
 		  	$this->db->free($resql);
495
-		}
496
-        else dol_print_error($this->db);
523
+		} else {
524
+            dol_print_error($this->db);
525
+        }
497 526
 
498 527
 		for ($i = 1 ; $i < 13 ; $i++)
499 528
 		{
@@ -505,9 +534,13 @@  discard block
 block discarded – undo
505 534
 		for ($i = 1 ; $i < 13 ; $i++)
506 535
 		{
507 536
 			$month='unknown';
508
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
509
-			elseif ($format == 1) $month=$i;
510
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
537
+			if ($format == 0) {
538
+			    $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
539
+			} elseif ($format == 1) {
540
+			    $month=$i;
541
+			} elseif ($format == 2) {
542
+			    $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
543
+			}
511 544
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
512 545
 			//$month=dol_substr($month,0,3);
513 546
 			$data[$i-1] = array($month, $res[$i]);
@@ -545,8 +578,9 @@  discard block
 block discarded – undo
545 578
 		  		$i++;
546 579
 		  	}
547 580
 		  	$this->db->free($resql);
548
-		}
549
-        else dol_print_error($this->db);
581
+		} else {
582
+            dol_print_error($this->db);
583
+        }
550 584
 
551 585
 		for ($i = 1 ; $i < 13 ; $i++)
552 586
 		{
@@ -558,9 +592,13 @@  discard block
 block discarded – undo
558 592
 		for ($i = 1 ; $i < 13 ; $i++)
559 593
 		{
560 594
 			$month='unknown';
561
-			if ($format == 0) $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
562
-			elseif ($format == 1) $month=$i;
563
-			elseif ($format == 2) $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
595
+			if ($format == 0) {
596
+			    $month=$langs->transnoentitiesnoconv('MonthShort'.sprintf("%02d", $i));
597
+			} elseif ($format == 1) {
598
+			    $month=$i;
599
+			} elseif ($format == 2) {
600
+			    $month=$langs->transnoentitiesnoconv('MonthVeryShort'.sprintf("%02d", $i));
601
+			}
564 602
 			//$month=dol_print_date(dol_mktime(12,0,0,$i,1,$year),($format?"%m":"%b"));
565 603
 			//$month=dol_substr($month,0,3);
566 604
 			$data[$i-1] = array($month, $res[$i]);
@@ -593,14 +631,22 @@  discard block
 block discarded – undo
593 631
 			while ($i < $num)
594 632
 			{
595 633
 		  		$row = $this->db->fetch_row($resql);
596
-		  		if ($i < $limit || $num == $limit) $result[$i] = array($row[0],$row[1]);	// Ref of product, nb
597
-		  		else $other += $row[1];
634
+		  		if ($i < $limit || $num == $limit) {
635
+		  		    $result[$i] = array($row[0],$row[1]);
636
+		  		}
637
+		  		// Ref of product, nb
638
+		  		else {
639
+		  		    $other += $row[1];
640
+		  		}
598 641
 		  		$i++;
599 642
 		  	}
600
-		  	if ($num > $limit) $result[$i] = array($langs->transnoentitiesnoconv("Other"),$other);
643
+		  	if ($num > $limit) {
644
+		  	    $result[$i] = array($langs->transnoentitiesnoconv("Other"),$other);
645
+		  	}
601 646
 		  	$this->db->free($resql);
602
-		}
603
-        else dol_print_error($this->db);
647
+		} else {
648
+            dol_print_error($this->db);
649
+        }
604 650
 
605 651
 		return $result;
606 652
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formfile.class.php 3 patches
Indentation   +1761 added lines, -1761 removed lines patch added patch discarded remove patch
@@ -34,312 +34,312 @@  discard block
 block discarded – undo
34 34
  */
35 35
 class FormFile
36 36
 {
37
-	private $db;
37
+    private $db;
38 38
 
39
-	/**
40
-	 * @var string Error code (or message)
41
-	 */
42
-	public $error;
39
+    /**
40
+     * @var string Error code (or message)
41
+     */
42
+    public $error;
43 43
 
44
-	public $numoffiles;
45
-	public $infofiles;			// Used to return informations by function getDocumentsLink
44
+    public $numoffiles;
45
+    public $infofiles;			// Used to return informations by function getDocumentsLink
46 46
 
47 47
 
48
-	/**
49
-	 *	Constructor
50
-	 *
51
-	 *  @param		DoliDB		$db      Database handler
52
-	 */
53
-	function __construct($db)
54
-	{
55
-		$this->db = $db;
56
-		$this->numoffiles=0;
57
-	}
48
+    /**
49
+     *	Constructor
50
+     *
51
+     *  @param		DoliDB		$db      Database handler
52
+     */
53
+    function __construct($db)
54
+    {
55
+        $this->db = $db;
56
+        $this->numoffiles=0;
57
+    }
58 58
 
59 59
 
60 60
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
61
-	/**
62
-	 *  Show form to upload a new file.
63
-	 *
64
-	 *  @param  string		$url			Url
65
-	 *  @param  string		$title			Title zone (Title or '' or 'none')
66
-	 *  @param  int			$addcancel		1=Add 'Cancel' button
67
-	 *	@param	int			$sectionid		If upload must be done inside a particular ECM section (is sectionid defined, sectiondir must not be)
68
-	 * 	@param	int			$perm			Value of permission to allow upload
69
-	 *  @param  int			$size          		Length of input file area. Deprecated.
70
-	 *  @param	Object		$object			Object to use (when attachment is done on an element)
71
-	 *  @param	string		$options		Add an option column
72
-	 *  @param	integer		$useajax		Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). @deprecated 2 should never be used and if 1 is used, option should no be enabled.
73
-	 *  @param	string		$savingdocmask		Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
74
-	 *  @param	integer		$linkfiles		1=Also add form to link files, 0=Do not show form to link files
75
-	 *  @param	string		$htmlname		Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM)
76
-	 *  @param	string		$accept			Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
77
-	 *	@param	string		$sectiondir		If upload must be done inside a particular directory (is sectiondir defined, sectionid must not be)
78
-	 * 	@return	int							<0 if KO, >0 if OK
79
-	 */
80
-	function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='', $sectiondir='')
81
-	{
61
+    /**
62
+     *  Show form to upload a new file.
63
+     *
64
+     *  @param  string		$url			Url
65
+     *  @param  string		$title			Title zone (Title or '' or 'none')
66
+     *  @param  int			$addcancel		1=Add 'Cancel' button
67
+     *	@param	int			$sectionid		If upload must be done inside a particular ECM section (is sectionid defined, sectiondir must not be)
68
+     * 	@param	int			$perm			Value of permission to allow upload
69
+     *  @param  int			$size          		Length of input file area. Deprecated.
70
+     *  @param	Object		$object			Object to use (when attachment is done on an element)
71
+     *  @param	string		$options		Add an option column
72
+     *  @param	integer		$useajax		Use fileupload ajax (0=never, 1=if enabled, 2=always whatever is option). @deprecated 2 should never be used and if 1 is used, option should no be enabled.
73
+     *  @param	string		$savingdocmask		Mask to use to define output filename. For example 'XXXXX-__YYYYMMDD__-__file__'
74
+     *  @param	integer		$linkfiles		1=Also add form to link files, 0=Do not show form to link files
75
+     *  @param	string		$htmlname		Name and id of HTML form ('formuserfile' by default, 'formuserfileecm' when used to upload a file in ECM)
76
+     *  @param	string		$accept			Specifies the types of files accepted (This is not a security check but an user interface facility. eg '.pdf,image/*' or '.png,.jpg' or 'video/*')
77
+     *	@param	string		$sectiondir		If upload must be done inside a particular directory (is sectiondir defined, sectionid must not be)
78
+     * 	@return	int							<0 if KO, >0 if OK
79
+     */
80
+    function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='', $sectiondir='')
81
+    {
82 82
         // phpcs:enable
83
-		global $conf,$langs, $hookmanager;
84
-		$hookmanager->initHooks(array('formfile'));
85
-
86
-
87
-		if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
88
-
89
-		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
90
-		{
91
-			// TODO: Check this works with 2 forms on same page
92
-			// TODO: Check this works with GED module, otherwise, force useajax to 0
93
-			// TODO: This does not support option savingdocmask
94
-			// TODO: This break feature to upload links too
95
-			return $this->_formAjaxFileUpload($object);
96
-		}
97
-		else
98
-	   	{
99
-			//If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
100
-			if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
101
-				return 1;
102
-			}
103
-
104
-			$maxlength=$size;
105
-
106
-			$out = "\n\n<!-- Start form attach new file -->\n";
107
-
108
-			if (empty($title)) $title=$langs->trans("AttachANewFile");
109
-			if ($title != 'none') $out.=load_fiche_titre($title, null, null);
110
-
111
-			$out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
112
-			$out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="'.$sectiondir.'">';
113
-			$out .= '<input type="hidden" id="'.$htmlname.'_section_id"  name="section_id" value="'.$sectionid.'">';
114
-			$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
115
-
116
-			$out .= '<table width="100%" class="nobordernopadding">';
117
-			$out .= '<tr>';
118
-
119
-			if (! empty($options)) $out .= '<td>'.$options.'</td>';
120
-
121
-			$out .= '<td class="valignmiddle nowrap">';
122
-
123
-			$max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
124
-			$maxphp=@ini_get('upload_max_filesize');	// En inconnu
125
-			if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
126
-			if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
127
-			if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
128
-			if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
129
-			// Now $max and $maxphp are in Kb
130
-			$maxmin = $max;
131
-			if ($maxphp > 0) $maxmin=min($max,$maxphp);
132
-
133
-			if ($maxmin > 0)
134
-			{
135
-				// MAX_FILE_SIZE doit précéder le champ input de type file
136
-				$out .= '<input type="hidden" name="max_file_size" value="'.($maxmin*1024).'">';
137
-			}
138
-
139
-			$out .= '<input class="flat minwidth400" type="file"';
140
-			$out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
141
-			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
142
-			$out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""');
143
-			$out .= '>';
144
-			$out .= ' ';
145
-			$out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
146
-			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
147
-			$out .= '>';
148
-
149
-			if ($addcancel)
150
-			{
151
-				$out .= ' &nbsp; ';
152
-				$out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
153
-			}
154
-
155
-			if (! empty($conf->global->MAIN_UPLOAD_DOC))
156
-			{
157
-				if ($perm)
158
-				{
159
-					$langs->load('other');
160
-					$out .= ' ';
161
-					$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
162
-				}
163
-			}
164
-			else
165
-			{
166
-				$out .= ' ('.$langs->trans("UploadDisabled").')';
167
-			}
168
-			$out .= "</td></tr>";
169
-
170
-			if ($savingdocmask)
171
-			{
172
-				$out .= '<tr>';
173
-   				if (! empty($options)) $out .= '<td>'.$options.'</td>';
174
-				$out .= '<td valign="middle" class="nowrap">';
175
-				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
176
-				$out .= '</td>';
177
-				$out .= '</tr>';
178
-			}
179
-
180
-			$out .= "</table>";
181
-
182
-			$out .= '</form>';
183
-			if (empty($sectionid)) $out .= '<br>';
184
-
185
-			$out .= "\n<!-- End form attach new file -->\n";
186
-
187
-			if ($linkfiles)
188
-			{
189
-				$out .= "\n<!-- Start form link new url -->\n";
190
-				$langs->load('link');
191
-				$title = $langs->trans("LinkANewFile");
192
-				$out .= load_fiche_titre($title, null, null);
193
-				$out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">';
194
-				$out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">';
195
-				$out .= '<input type="hidden" id="'.$htmlname.'_link_section_id"  name="link_section_id" value="'.$sectionid.'">';
196
-				$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
197
-
198
-				$out .= '<div class="valignmiddle" >';
199
-				$out .= '<div class="inline-block" style="padding-right: 10px;">';
200
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
201
-				$out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
202
-				$out .= '</div>';
203
-				$out .= '<div class="inline-block" style="padding-right: 10px;">';
204
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
205
-				$out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
206
-				$out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
207
-				$out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
208
-				$out .= '</div>';
209
-				$out .= '<div class="inline-block" style="padding-right: 10px;">';
210
-				$out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
211
-				$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
212
-				$out .= '>';
213
-				$out .= '</div>';
214
-				$out .= '</div>';
215
-				$out .= '<div class="clearboth"></div>';
216
-				$out .= '</form><br>';
217
-
218
-				$out .= "\n<!-- End form link new url -->\n";
219
-			}
220
-
221
-			$parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''), 'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
222
-			$res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
223
-			if (empty($res))
224
-			{
225
-				print '<div class="attacharea attacharea'.$htmlname.'">';
226
-				print $out;
227
-				print '</div>';
228
-			}
229
-			print $hookmanager->resPrint;
230
-
231
-			return 1;
232
-		}
233
-	}
83
+        global $conf,$langs, $hookmanager;
84
+        $hookmanager->initHooks(array('formfile'));
85
+
86
+
87
+        if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
88
+
89
+        if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
90
+        {
91
+            // TODO: Check this works with 2 forms on same page
92
+            // TODO: Check this works with GED module, otherwise, force useajax to 0
93
+            // TODO: This does not support option savingdocmask
94
+            // TODO: This break feature to upload links too
95
+            return $this->_formAjaxFileUpload($object);
96
+        }
97
+        else
98
+            {
99
+            //If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
100
+            if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
101
+                return 1;
102
+            }
103
+
104
+            $maxlength=$size;
105
+
106
+            $out = "\n\n<!-- Start form attach new file -->\n";
107
+
108
+            if (empty($title)) $title=$langs->trans("AttachANewFile");
109
+            if ($title != 'none') $out.=load_fiche_titre($title, null, null);
110
+
111
+            $out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
112
+            $out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="'.$sectiondir.'">';
113
+            $out .= '<input type="hidden" id="'.$htmlname.'_section_id"  name="section_id" value="'.$sectionid.'">';
114
+            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
115
+
116
+            $out .= '<table width="100%" class="nobordernopadding">';
117
+            $out .= '<tr>';
118
+
119
+            if (! empty($options)) $out .= '<td>'.$options.'</td>';
120
+
121
+            $out .= '<td class="valignmiddle nowrap">';
122
+
123
+            $max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
124
+            $maxphp=@ini_get('upload_max_filesize');	// En inconnu
125
+            if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
126
+            if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
127
+            if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
128
+            if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
129
+            // Now $max and $maxphp are in Kb
130
+            $maxmin = $max;
131
+            if ($maxphp > 0) $maxmin=min($max,$maxphp);
132
+
133
+            if ($maxmin > 0)
134
+            {
135
+                // MAX_FILE_SIZE doit précéder le champ input de type file
136
+                $out .= '<input type="hidden" name="max_file_size" value="'.($maxmin*1024).'">';
137
+            }
138
+
139
+            $out .= '<input class="flat minwidth400" type="file"';
140
+            $out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
141
+            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
142
+            $out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""');
143
+            $out .= '>';
144
+            $out .= ' ';
145
+            $out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
146
+            $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
147
+            $out .= '>';
148
+
149
+            if ($addcancel)
150
+            {
151
+                $out .= ' &nbsp; ';
152
+                $out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
153
+            }
154
+
155
+            if (! empty($conf->global->MAIN_UPLOAD_DOC))
156
+            {
157
+                if ($perm)
158
+                {
159
+                    $langs->load('other');
160
+                    $out .= ' ';
161
+                    $out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
162
+                }
163
+            }
164
+            else
165
+            {
166
+                $out .= ' ('.$langs->trans("UploadDisabled").')';
167
+            }
168
+            $out .= "</td></tr>";
169
+
170
+            if ($savingdocmask)
171
+            {
172
+                $out .= '<tr>';
173
+                    if (! empty($options)) $out .= '<td>'.$options.'</td>';
174
+                $out .= '<td valign="middle" class="nowrap">';
175
+                $out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
176
+                $out .= '</td>';
177
+                $out .= '</tr>';
178
+            }
179
+
180
+            $out .= "</table>";
181
+
182
+            $out .= '</form>';
183
+            if (empty($sectionid)) $out .= '<br>';
184
+
185
+            $out .= "\n<!-- End form attach new file -->\n";
186
+
187
+            if ($linkfiles)
188
+            {
189
+                $out .= "\n<!-- Start form link new url -->\n";
190
+                $langs->load('link');
191
+                $title = $langs->trans("LinkANewFile");
192
+                $out .= load_fiche_titre($title, null, null);
193
+                $out .= '<form name="'.$htmlname.'_link" id="'.$htmlname.'_link" action="'.$url.'" method="POST">';
194
+                $out .= '<input type="hidden" id="'.$htmlname.'_link_section_dir" name="link_section_dir" value="">';
195
+                $out .= '<input type="hidden" id="'.$htmlname.'_link_section_id"  name="link_section_id" value="'.$sectionid.'">';
196
+                $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
197
+
198
+                $out .= '<div class="valignmiddle" >';
199
+                $out .= '<div class="inline-block" style="padding-right: 10px;">';
200
+                if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
201
+                $out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
202
+                $out .= '</div>';
203
+                $out .= '<div class="inline-block" style="padding-right: 10px;">';
204
+                if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
205
+                $out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
206
+                $out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
207
+                $out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
208
+                $out .= '</div>';
209
+                $out .= '<div class="inline-block" style="padding-right: 10px;">';
210
+                $out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
211
+                $out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
212
+                $out .= '>';
213
+                $out .= '</div>';
214
+                $out .= '</div>';
215
+                $out .= '<div class="clearboth"></div>';
216
+                $out .= '</form><br>';
217
+
218
+                $out .= "\n<!-- End form link new url -->\n";
219
+            }
220
+
221
+            $parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''), 'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
222
+            $res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
223
+            if (empty($res))
224
+            {
225
+                print '<div class="attacharea attacharea'.$htmlname.'">';
226
+                print $out;
227
+                print '</div>';
228
+            }
229
+            print $hookmanager->resPrint;
230
+
231
+            return 1;
232
+        }
233
+    }
234 234
 
235 235
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
236
-	/**
237
-	 *      Show the box with list of available documents for object
238
-	 *
239
-	 *      @param      string				$modulepart         propal, facture, facture_fourn, ...
240
-	 *      @param      string				$modulesubdir       Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
241
-	 *      @param      string				$filedir            Directory to scan
242
-	 *      @param      string				$urlsource          Url of origin page (for return)
243
-	 *      @param      int					$genallowed         Generation is allowed (1/0 or array of formats)
244
-	 *      @param      int					$delallowed         Remove is allowed (1/0)
245
-	 *      @param      string				$modelselected      Model to preselect by default
246
-	 *      @param      integer				$allowgenifempty	Show warning if no model activated
247
-	 *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
248
-	 *      @param      int					$iconPDF            Show only PDF icon with link (1/0)
249
-	 * 		@param		int					$notused	        Not used
250
-	 * 		@param		integer				$noform				Do not output html form tags
251
-	 * 		@param		string				$param				More param on http links
252
-	 * 		@param		string				$title				Title to show on top of form
253
-	 * 		@param		string				$buttonlabel		Label on submit button
254
-	 * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
255
-	 * 		@return		int										<0 if KO, number of shown files if OK
256
-	 *      @deprecated                                         Use print xxx->showdocuments() instead.
257
-	 */
258
-	function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
259
-	{
236
+    /**
237
+     *      Show the box with list of available documents for object
238
+     *
239
+     *      @param      string				$modulepart         propal, facture, facture_fourn, ...
240
+     *      @param      string				$modulesubdir       Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
241
+     *      @param      string				$filedir            Directory to scan
242
+     *      @param      string				$urlsource          Url of origin page (for return)
243
+     *      @param      int					$genallowed         Generation is allowed (1/0 or array of formats)
244
+     *      @param      int					$delallowed         Remove is allowed (1/0)
245
+     *      @param      string				$modelselected      Model to preselect by default
246
+     *      @param      integer				$allowgenifempty	Show warning if no model activated
247
+     *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
248
+     *      @param      int					$iconPDF            Show only PDF icon with link (1/0)
249
+     * 		@param		int					$notused	        Not used
250
+     * 		@param		integer				$noform				Do not output html form tags
251
+     * 		@param		string				$param				More param on http links
252
+     * 		@param		string				$title				Title to show on top of form
253
+     * 		@param		string				$buttonlabel		Label on submit button
254
+     * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
255
+     * 		@return		int										<0 if KO, number of shown files if OK
256
+     *      @deprecated                                         Use print xxx->showdocuments() instead.
257
+     */
258
+    function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
259
+    {
260 260
         // phpcs:enable
261
-		$this->numoffiles=0;
262
-		print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
263
-		return $this->numoffiles;
264
-	}
265
-
266
-	/**
267
-	 *      Return a string to show the box with list of available documents for object.
268
-	 *      This also set the property $this->numoffiles
269
-	 *
270
-	 *      @param      string				$modulepart         Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...)
271
-	 *      @param      string				$modulesubdir       Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
272
-	 *      @param      string				$filedir            Directory to scan
273
-	 *      @param      string				$urlsource          Url of origin page (for return)
274
-	 *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
275
-	 *      @param      int					$delallowed         Remove is allowed (1/0)
276
-	 *      @param      string				$modelselected      Model to preselect by default
277
-	 *      @param      integer				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
278
-	 *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
279
-	 *      @param      int					$iconPDF            Deprecated, see getDocumentsLink
280
-	 * 		@param		int					$notused	        Not used
281
-	 * 		@param		integer				$noform				Do not output html form tags
282
-	 * 		@param		string				$param				More param on http links
283
-	 * 		@param		string				$title				Title to show on top of form
284
-	 * 		@param		string				$buttonlabel		Label on submit button
285
-	 * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
286
-	 * 		@param		string				$morepicto			Add more HTML content into cell with picto
287
-	 *      @param      Object              $object             Object when method is called from an object card.
288
-	 *      @param		int					$hideifempty		Hide section of generated files if there is no file
289
-	 * 		@return		string              					Output string with HTML array of documents (might be empty string)
290
-	 */
291
-	function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null,$hideifempty=0)
292
-	{
293
-		// Deprecation warning
294
-		if (! empty($iconPDF)) {
295
-			dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
296
-		}
297
-
298
-		global $langs, $conf, $user, $hookmanager;
299
-		global $form;
300
-
301
-		if (! is_object($form)) $form=new Form($this->db);
302
-
303
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
304
-
305
-		// For backward compatibility
306
-		if (! empty($iconPDF)) {
307
-			return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
308
-		}
309
-
310
-		// Add entity in $param
311
-		$param.= 'entity='.(!empty($object->entity)?$object->entity:$conf->entity);
312
-
313
-		$printer=0;
314
-		if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport','livraison')))	// The direct print feature is implemented only for such elements
315
-		{
316
-			$printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
317
-		}
318
-
319
-		$hookmanager->initHooks(array('formfile'));
320
-
321
-		// Get list of files
322
-		$file_list=null;
323
-		if (! empty($filedir))
324
-		{
325
-			$file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
326
-		}
327
-		if ($hideifempty && empty($file_list)) return '';
328
-
329
-		$out='';
330
-		$forname='builddoc';
331
-		$headershown=0;
332
-		$showempty=0;
333
-		$i=0;
334
-
335
-		$out.= "\n".'<!-- Start show_document -->'."\n";
336
-		//print 'filedir='.$filedir;
337
-
338
-		if (preg_match('/massfilesarea_/', $modulepart))
339
-		{
340
-			$out.='<div id="show_files"><br></div>'."\n";
341
-			$title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
342
-			$title.='<script type="text/javascript" language="javascript">
261
+        $this->numoffiles=0;
262
+        print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
263
+        return $this->numoffiles;
264
+    }
265
+
266
+    /**
267
+     *      Return a string to show the box with list of available documents for object.
268
+     *      This also set the property $this->numoffiles
269
+     *
270
+     *      @param      string				$modulepart         Module the files are related to ('propal', 'facture', 'facture_fourn', 'mymodule', 'mymodule_temp', ...)
271
+     *      @param      string				$modulesubdir       Existing (so sanitized) sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
272
+     *      @param      string				$filedir            Directory to scan
273
+     *      @param      string				$urlsource          Url of origin page (for return)
274
+     *      @param      int					$genallowed         Generation is allowed (1/0 or array list of templates)
275
+     *      @param      int					$delallowed         Remove is allowed (1/0)
276
+     *      @param      string				$modelselected      Model to preselect by default
277
+     *      @param      integer				$allowgenifempty	Allow generation even if list of template ($genallowed) is empty (show however a warning)
278
+     *      @param      integer				$forcenomultilang	Do not show language option (even if MAIN_MULTILANGS defined)
279
+     *      @param      int					$iconPDF            Deprecated, see getDocumentsLink
280
+     * 		@param		int					$notused	        Not used
281
+     * 		@param		integer				$noform				Do not output html form tags
282
+     * 		@param		string				$param				More param on http links
283
+     * 		@param		string				$title				Title to show on top of form
284
+     * 		@param		string				$buttonlabel		Label on submit button
285
+     * 		@param		string				$codelang			Default language code to use on lang combo box if multilang is enabled
286
+     * 		@param		string				$morepicto			Add more HTML content into cell with picto
287
+     *      @param      Object              $object             Object when method is called from an object card.
288
+     *      @param		int					$hideifempty		Hide section of generated files if there is no file
289
+     * 		@return		string              					Output string with HTML array of documents (might be empty string)
290
+     */
291
+    function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null,$hideifempty=0)
292
+    {
293
+        // Deprecation warning
294
+        if (! empty($iconPDF)) {
295
+            dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
296
+        }
297
+
298
+        global $langs, $conf, $user, $hookmanager;
299
+        global $form;
300
+
301
+        if (! is_object($form)) $form=new Form($this->db);
302
+
303
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
304
+
305
+        // For backward compatibility
306
+        if (! empty($iconPDF)) {
307
+            return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
308
+        }
309
+
310
+        // Add entity in $param
311
+        $param.= 'entity='.(!empty($object->entity)?$object->entity:$conf->entity);
312
+
313
+        $printer=0;
314
+        if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport','livraison')))	// The direct print feature is implemented only for such elements
315
+        {
316
+            $printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
317
+        }
318
+
319
+        $hookmanager->initHooks(array('formfile'));
320
+
321
+        // Get list of files
322
+        $file_list=null;
323
+        if (! empty($filedir))
324
+        {
325
+            $file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
326
+        }
327
+        if ($hideifempty && empty($file_list)) return '';
328
+
329
+        $out='';
330
+        $forname='builddoc';
331
+        $headershown=0;
332
+        $showempty=0;
333
+        $i=0;
334
+
335
+        $out.= "\n".'<!-- Start show_document -->'."\n";
336
+        //print 'filedir='.$filedir;
337
+
338
+        if (preg_match('/massfilesarea_/', $modulepart))
339
+        {
340
+            $out.='<div id="show_files"><br></div>'."\n";
341
+            $title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
342
+            $title.='<script type="text/javascript" language="javascript">
343 343
 				jQuery(document).ready(function() {
344 344
 					jQuery(\'#togglemassfilesarea\').click(function() {
345 345
 						if (jQuery(\'#togglemassfilesarea\').attr(\'ref\') == "shown")
@@ -358,1489 +358,1489 @@  discard block
 block discarded – undo
358 358
 					});
359 359
 				});
360 360
 				</script>';
361
-		}
362
-
363
-		$titletoshow=$langs->trans("Documents");
364
-		if (! empty($title)) $titletoshow=$title;
365
-
366
-		// Show table
367
-		if ($genallowed)
368
-		{
369
-			$modellist=array();
370
-
371
-			if ($modulepart == 'company')
372
-			{
373
-				$showempty=1;
374
-				if (is_array($genallowed)) $modellist=$genallowed;
375
-				else
376
-				{
377
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
378
-					$modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
379
-				}
380
-			}
381
-			else if ($modulepart == 'propal')
382
-			{
383
-				if (is_array($genallowed)) $modellist=$genallowed;
384
-				else
385
-				{
386
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
387
-					$modellist=ModelePDFPropales::liste_modeles($this->db);
388
-				}
389
-			}
390
-			else if ($modulepart == 'supplier_proposal')
391
-			{
392
-				if (is_array($genallowed)) $modellist=$genallowed;
393
-				else
394
-				{
395
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
396
-					$modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
397
-				}
398
-			}
399
-			else if ($modulepart == 'commande')
400
-			{
401
-				if (is_array($genallowed)) $modellist=$genallowed;
402
-				else
403
-				{
404
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
405
-					$modellist=ModelePDFCommandes::liste_modeles($this->db);
406
-				}
407
-			}
408
-			elseif ($modulepart == 'expedition')
409
-			{
410
-				if (is_array($genallowed)) $modellist=$genallowed;
411
-				else
412
-				{
413
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
414
-					$modellist=ModelePDFExpedition::liste_modeles($this->db);
415
-				}
416
-			}
361
+        }
362
+
363
+        $titletoshow=$langs->trans("Documents");
364
+        if (! empty($title)) $titletoshow=$title;
365
+
366
+        // Show table
367
+        if ($genallowed)
368
+        {
369
+            $modellist=array();
370
+
371
+            if ($modulepart == 'company')
372
+            {
373
+                $showempty=1;
374
+                if (is_array($genallowed)) $modellist=$genallowed;
375
+                else
376
+                {
377
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
378
+                    $modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
379
+                }
380
+            }
381
+            else if ($modulepart == 'propal')
382
+            {
383
+                if (is_array($genallowed)) $modellist=$genallowed;
384
+                else
385
+                {
386
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
387
+                    $modellist=ModelePDFPropales::liste_modeles($this->db);
388
+                }
389
+            }
390
+            else if ($modulepart == 'supplier_proposal')
391
+            {
392
+                if (is_array($genallowed)) $modellist=$genallowed;
393
+                else
394
+                {
395
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
396
+                    $modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
397
+                }
398
+            }
399
+            else if ($modulepart == 'commande')
400
+            {
401
+                if (is_array($genallowed)) $modellist=$genallowed;
402
+                else
403
+                {
404
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
405
+                    $modellist=ModelePDFCommandes::liste_modeles($this->db);
406
+                }
407
+            }
408
+            elseif ($modulepart == 'expedition')
409
+            {
410
+                if (is_array($genallowed)) $modellist=$genallowed;
411
+                else
412
+                {
413
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
414
+                    $modellist=ModelePDFExpedition::liste_modeles($this->db);
415
+                }
416
+            }
417 417
             elseif ($modulepart == 'reception')
418 418
             {
419 419
                 if (is_array($genallowed)) $modellist=$genallowed;
420 420
                 else
421 421
                 {
422
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
423
-					$modellist = ModelePdfReception::liste_modeles($this->db);
424
-				}
425
-            }
426
-			elseif ($modulepart == 'livraison')
427
-			{
428
-				if (is_array($genallowed)) $modellist=$genallowed;
429
-				else
430
-				{
431
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
432
-					$modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
433
-				}
434
-			}
435
-			else if ($modulepart == 'ficheinter')
436
-			{
437
-				if (is_array($genallowed)) $modellist=$genallowed;
438
-				else
439
-				{
440
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
441
-					$modellist=ModelePDFFicheinter::liste_modeles($this->db);
442
-				}
443
-			}
444
-			elseif ($modulepart == 'facture')
445
-			{
446
-				if (is_array($genallowed)) $modellist=$genallowed;
447
-				else
448
-				{
449
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
450
-					$modellist=ModelePDFFactures::liste_modeles($this->db);
451
-				}
452
-			}
453
-			elseif ($modulepart == 'contract')
454
-			{
455
-				if (is_array($genallowed)) $modellist=$genallowed;
456
-				else
457
-				{
458
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
459
-					$modellist=ModelePDFContract::liste_modeles($this->db);
460
-				}
461
-			}
462
-			elseif ($modulepart == 'project')
463
-			{
464
-				if (is_array($genallowed)) $modellist=$genallowed;
465
-				else
466
-				{
467
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
468
-					$modellist=ModelePDFProjects::liste_modeles($this->db);
469
-				}
470
-			}
471
-			elseif ($modulepart == 'project_task')
472
-			{
473
-				if (is_array($genallowed)) $modellist=$genallowed;
474
-				else
475
-				{
476
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
477
-					$modellist=ModelePDFTask::liste_modeles($this->db);
478
-				}
479
-			}
480
-			elseif ($modulepart == 'product')
481
-			{
482
-				if (is_array($genallowed)) $modellist=$genallowed;
483
-				else
484
-				{
485
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
486
-					$modellist=ModelePDFProduct::liste_modeles($this->db);
487
-				}
488
-			}
489
-			elseif ($modulepart == 'product_batch')
490
-			{
491
-				if (is_array($genallowed)) $modellist=$genallowed;
492
-				else
493
-				{
494
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php';
495
-					$modellist=ModelePDFProductBatch::liste_modeles($this->db);
496
-				}
497
-			}
498
-			elseif ($modulepart == 'stock')
499
-			{
500
-				if (is_array($genallowed)) $modellist=$genallowed;
501
-				else
502
-				{
503
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php';
504
-					$modellist=ModelePDFStock::liste_modeles($this->db);
505
-				}
506
-			}
507
-			elseif ($modulepart == 'movement')
508
-			{
509
-				if (is_array($genallowed)) $modellist=$genallowed;
510
-				else
511
-				{
512
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php';
513
-					$modellist=ModelePDFMovement::liste_modeles($this->db);
514
-				}
515
-			}
516
-			elseif ($modulepart == 'export')
517
-			{
518
-				if (is_array($genallowed)) $modellist=$genallowed;
519
-				else
520
-				{
521
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
522
-					$modellist=ModeleExports::liste_modeles($this->db);
523
-				}
524
-			}
525
-			else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
526
-			{
527
-				if (is_array($genallowed)) $modellist=$genallowed;
528
-				else
529
-				{
530
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
531
-					$modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
532
-				}
533
-			}
534
-			else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
535
-			{
536
-				if (is_array($genallowed)) $modellist=$genallowed;
537
-				else
538
-				{
539
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
540
-					$modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
541
-				}
542
-			}
543
-			else if ($modulepart == 'supplier_payment')
544
-			{
545
-				if (is_array($genallowed)) $modellist=$genallowed;
546
-				else
547
-				{
548
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
549
-					$modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
550
-				}
551
-			}
552
-			else if ($modulepart == 'remisecheque')
553
-			{
554
-				if (is_array($genallowed)) $modellist=$genallowed;
555
-				else
556
-				{
557
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
558
-					$modellist=ModeleChequeReceipts::liste_modeles($this->db);
559
-				}
560
-			}
561
-			elseif ($modulepart == 'donation')
562
-			{
563
-				if (is_array($genallowed)) $modellist=$genallowed;
564
-				else
565
-				{
566
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
567
-					$modellist=ModeleDon::liste_modeles($this->db);
568
-				}
569
-			}
570
-			elseif ($modulepart == 'member')
571
-			{
572
-				if (is_array($genallowed)) $modellist=$genallowed;
573
-				else
574
-				{
575
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
576
-					$modellist=ModelePDFCards::liste_modeles($this->db);
577
-				}
578
-			}
579
-			elseif ($modulepart == 'agenda' || $modulepart == 'actions')
580
-			{
581
-				if (is_array($genallowed)) $modellist=$genallowed;
582
-				else
583
-				{
584
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
585
-					$modellist=ModeleAction::liste_modeles($this->db);
586
-				}
587
-			}
588
-			else if ($modulepart == 'expensereport')
589
-			{
590
-				if (is_array($genallowed)) $modellist=$genallowed;
591
-				else
592
-				{
593
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
594
-					$modellist=ModeleExpenseReport::liste_modeles($this->db);
595
-				}
596
-			}
597
-			else if ($modulepart == 'unpaid')
598
-			{
599
-				$modellist='';
600
-			}
601
-			elseif ($modulepart == 'user')
602
-			{
603
-				if (is_array($genallowed)) $modellist=$genallowed;
604
-				else
605
-				{
606
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
607
-					$modellist=ModelePDFUser::liste_modeles($this->db);
608
-				}
609
-			}
610
-			elseif ($modulepart == 'usergroup')
611
-			{
612
-				if (is_array($genallowed)) $modellist=$genallowed;
613
-				else
614
-				{
615
-					include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
616
-					$modellist=ModelePDFUserGroup::liste_modeles($this->db);
617
-				}
618
-			}
619
-			else
620
-			{
621
-				// For normalized standard modules
622
-				$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
623
-				if (file_exists($file))
624
-				{
625
-					$res=include_once $file;
626
-				}
627
-				// For normalized external modules
628
-				else
629
-				{
630
-					$file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
631
-					$res=include_once $file;
632
-				}
633
-				$class='ModelePDF'.ucfirst($modulepart);
634
-				if (class_exists($class))
635
-				{
636
-					$modellist=call_user_func($class.'::liste_modeles',$this->db);
637
-				}
638
-				else
639
-				{
640
-					dol_print_error($this->db,'Bad value for modulepart');
641
-					return -1;
642
-				}
643
-			}
644
-
645
-			// Set headershown to avoid to have table opened a second time later
646
-			$headershown=1;
647
-
648
-			$buttonlabeltoshow=$buttonlabel;
649
-			if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
650
-
651
-			if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
652
-			if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
653
-			$out.= '<input type="hidden" name="action" value="builddoc">';
654
-			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
655
-
656
-			$out.= load_fiche_titre($titletoshow, '', '');
657
-			$out.= '<div class="div-table-responsive-no-min">';
658
-			$out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
659
-
660
-			$out.= '<tr class="liste_titre">';
661
-
662
-			$addcolumforpicto=($delallowed || $printer || $morepicto);
663
-			$out.= '<th align="center" colspan="'.(3+($addcolumforpicto?1:0)).'" class="formdoc liste_titre maxwidthonsmartphone">';
664
-
665
-			// Model
666
-			if (! empty($modellist))
667
-			{
668
-				$out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
669
-				if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
670
-				{
671
-					$arraykeys=array_keys($modellist);
672
-					$modelselected=$arraykeys[0];
673
-				}
674
-				$out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
675
-				if ($conf->use_javascript_ajax)
676
-				{
677
-					$out.= ajax_combobox('model');
678
-				}
679
-			}
680
-			else
681
-			{
682
-				$out.= '<div class="float">'.$langs->trans("Files").'</div>';
683
-			}
684
-
685
-			// Language code (if multilang)
686
-			if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
687
-			{
688
-				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
689
-				$formadmin=new FormAdmin($this->db);
690
-				$defaultlang=$codelang?$codelang:$langs->getDefaultLang();
691
-				$morecss='maxwidth150';
692
-				if ($conf->browser->layout == 'phone') $morecss='maxwidth100';
693
-				$out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
694
-			}
695
-			else
696
-			{
697
-				$out.= '&nbsp;';
698
-			}
699
-
700
-			// Button
701
-			$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
702
-			$genbutton.= ' type="submit" value="'.$buttonlabel.'"';
703
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
704
-			$genbutton.= '>';
705
-			if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
706
-			{
707
-			   	$langs->load("errors");
708
-			   	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
709
-			}
710
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
711
-			if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
712
-			$out.= $genbutton;
713
-			$out.= '</th>';
714
-
715
-			if (!empty($hookmanager->hooks['formfile']))
716
-			{
717
-				foreach($hookmanager->hooks['formfile'] as $module)
718
-				{
719
-					if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
720
-				}
721
-			}
722
-			$out.= '</tr>';
723
-
724
-			// Execute hooks
725
-			$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
726
-			if (is_object($hookmanager))
727
-			{
728
-				$reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
729
-				$out.= $hookmanager->resPrint;
730
-			}
731
-		}
732
-
733
-		// Get list of files
734
-		if (! empty($filedir))
735
-		{
736
-			$link_list = array();
737
-			if (is_object($object))
738
-			{
739
-				require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
740
-				$link = new Link($this->db);
741
-				$sortfield = $sortorder = null;
742
-				$res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
743
-			}
744
-
745
-			$out.= '<!-- html.formfile::showdocuments -->'."\n";
746
-
747
-			// Show title of array if not already shown
748
-			if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart))
749
-				&& ! $headershown)
750
-			{
751
-				$headershown=1;
752
-				$out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
753
-				$out.= '<div class="div-table-responsive-no-min">';
754
-				$out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
755
-			}
756
-
757
-			// Loop on each file found
758
-			if (is_array($file_list))
759
-			{
760
-				foreach($file_list as $file)
761
-				{
762
-					// Define relative path for download link (depends on module)
763
-					$relativepath=$file["name"];										// Cas general
764
-					if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
765
-					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
766
-
767
-					$out.= '<tr class="oddeven">';
768
-
769
-					$documenturl = DOL_URL_ROOT.'/document.php';
770
-					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
771
-
772
-					// Show file name with link to download
773
-					$out.= '<td class="minwidth200">';
774
-					$out.= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
775
-					$mime=dol_mimetype($relativepath,'',0);
776
-					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
777
-					$out.= ' target="_blank">';
778
-					$out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]);
779
-					$out.= dol_trunc($file["name"], 150);
780
-					$out.= '</a>'."\n";
781
-					$out.= $this->showPreview($file,$modulepart,$relativepath,0,$param);
782
-					$out.= '</td>';
783
-
784
-					// Show file size
785
-					$size=(! empty($file['size'])?$file['size']:dol_filesize($filedir."/".$file["name"]));
786
-					$out.= '<td align="right" class="nowrap">'.dol_print_size($size,1,1).'</td>';
787
-
788
-					// Show file date
789
-					$date=(! empty($file['date'])?$file['date']:dol_filemtime($filedir."/".$file["name"]));
790
-					$out.= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
791
-
792
-					if ($delallowed || $printer || $morepicto)
793
-					{
794
-						$out.= '<td class="right nowraponall">';
795
-						if ($delallowed)
796
-						{
797
-							$tmpurlsource = preg_replace('/#[a-zA-Z0-9_]*$/', '', $urlsource);
798
-							$out.= '<a href="'.$tmpurlsource.(strpos($tmpurlsource,'?')?'&amp;':'?').'action=remove_file&amp;file='.urlencode($relativepath);
799
-							$out.= ($param?'&amp;'.$param:'');
800
-							//$out.= '&modulepart='.$modulepart; // TODO obsolete ?
801
-							//$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
802
-							$out.= '">'.img_picto($langs->trans("Delete"), 'delete').'</a>';
803
-						}
804
-						if ($printer)
805
-						{
806
-							//$out.= '<td align="right">';
807
-							$out.= '<a class="paddingleft" href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
808
-							$out.= ($param?'&amp;'.$param:'');
809
-							$out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
810
-						}
811
-						if ($morepicto)
812
-						{
813
-							$morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto);
814
-							$out.=$morepicto;
815
-						}
816
-						$out.='</td>';
817
-					}
818
-
819
-					if (is_object($hookmanager))
820
-					{
821
-						$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
822
-						$res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
823
-						if (empty($res))
824
-						{
825
-							$out.= $hookmanager->resPrint;		// Complete line
826
-							$out.= '</tr>';
827
-						}
828
-						else $out = $hookmanager->resPrint;		// Replace line
829
-			  		}
830
-				}
831
-
832
-				$this->numoffiles++;
833
-			}
834
-			// Loop on each link found
835
-			if (is_array($link_list))
836
-			{
837
-				$colspan=2;
838
-
839
-				foreach($link_list as $file)
840
-				{
841
-					$out.='<tr class="oddeven">';
842
-					$out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
843
-					$out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
844
-					$out.=$file->label;
845
-					$out.='</a>';
846
-					$out.='</td>';
847
-					$out.='<td align="right">';
848
-					$out.=dol_print_date($file->datea,'dayhour');
849
-					$out.='</td>';
850
-					if ($delallowed || $printer || $morepicto) $out.='<td></td>';
851
-					$out.='</tr>'."\n";
852
-				}
853
-				$this->numoffiles++;
854
-			}
855
-
856
-		 	if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
857
-			{
858
-				$out.='<tr><td colspan="'.(3+($addcolumforpicto?1:0)).'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
859
-			}
860
-		}
861
-
862
-		if ($headershown)
863
-		{
864
-			// Affiche pied du tableau
865
-			$out.= "</table>\n";
866
-			$out.= "</div>\n";
867
-			if ($genallowed)
868
-			{
869
-				if (empty($noform)) $out.= '</form>'."\n";
870
-			}
871
-		}
872
-		$out.= '<!-- End show_document -->'."\n";
873
-		//return ($i?$i:$headershown);
874
-		return $out;
875
-	}
876
-
877
-	/**
878
-	 *	Show a Document icon with link(s)
879
-	 *  You may want to call this into a div like this:
880
-	 *  print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>';
881
-	 *
882
-	 *	@param	string	$modulepart		propal, facture, facture_fourn, ...
883
-	 *	@param	string	$modulesubdir	Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
884
-	 *	@param	string	$filedir		Full path to directory to scan
885
-	 *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
886
-	 *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
887
-	 */
888
-	function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
889
-	{
890
-		global $conf, $langs;
891
-
892
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
893
-
894
-		$out='';
895
-		$this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
896
-
897
-		$entity = 1; // Without multicompany
898
-
899
-		// Get object entity
900
-		if (! empty($conf->multicompany->enabled))
901
-		{
902
-			preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir,'/').'$/', $filedir, $regs);
903
-			$entity = ((! empty($regs[1]) && $regs[1] > 1) ? $regs[1] : 1); // If entity id not found in $filedir this is entity 1 by default
904
-		}
905
-
906
-		// Get list of files starting with name of ref (but not followed by "-" to discard uploaded files and get only generated files)
907
-		// @TODO Why not showing by default all files by just removing the '[^\-]+' at end of regex ?
908
-		if (! empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP))
909
-		{
910
-			$filterforfilesearch = preg_quote(basename($modulesubdir),'/');
911
-		}
912
-		else
913
-		{
914
-			$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
915
-		}
916
-		$file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// We also discard .meta and .png preview
917
-
918
-		//var_dump($file_list);
919
-		// For ajax treatment
920
-		$out.= '<!-- html.formfile::getDocumentsLink -->'."\n";
921
-		if (! empty($file_list))
922
-		{
923
-			$out='<dl class="dropdown inline-block">
422
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
423
+                    $modellist = ModelePdfReception::liste_modeles($this->db);
424
+                }
425
+            }
426
+            elseif ($modulepart == 'livraison')
427
+            {
428
+                if (is_array($genallowed)) $modellist=$genallowed;
429
+                else
430
+                {
431
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
432
+                    $modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
433
+                }
434
+            }
435
+            else if ($modulepart == 'ficheinter')
436
+            {
437
+                if (is_array($genallowed)) $modellist=$genallowed;
438
+                else
439
+                {
440
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
441
+                    $modellist=ModelePDFFicheinter::liste_modeles($this->db);
442
+                }
443
+            }
444
+            elseif ($modulepart == 'facture')
445
+            {
446
+                if (is_array($genallowed)) $modellist=$genallowed;
447
+                else
448
+                {
449
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
450
+                    $modellist=ModelePDFFactures::liste_modeles($this->db);
451
+                }
452
+            }
453
+            elseif ($modulepart == 'contract')
454
+            {
455
+                if (is_array($genallowed)) $modellist=$genallowed;
456
+                else
457
+                {
458
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
459
+                    $modellist=ModelePDFContract::liste_modeles($this->db);
460
+                }
461
+            }
462
+            elseif ($modulepart == 'project')
463
+            {
464
+                if (is_array($genallowed)) $modellist=$genallowed;
465
+                else
466
+                {
467
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
468
+                    $modellist=ModelePDFProjects::liste_modeles($this->db);
469
+                }
470
+            }
471
+            elseif ($modulepart == 'project_task')
472
+            {
473
+                if (is_array($genallowed)) $modellist=$genallowed;
474
+                else
475
+                {
476
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
477
+                    $modellist=ModelePDFTask::liste_modeles($this->db);
478
+                }
479
+            }
480
+            elseif ($modulepart == 'product')
481
+            {
482
+                if (is_array($genallowed)) $modellist=$genallowed;
483
+                else
484
+                {
485
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
486
+                    $modellist=ModelePDFProduct::liste_modeles($this->db);
487
+                }
488
+            }
489
+            elseif ($modulepart == 'product_batch')
490
+            {
491
+                if (is_array($genallowed)) $modellist=$genallowed;
492
+                else
493
+                {
494
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php';
495
+                    $modellist=ModelePDFProductBatch::liste_modeles($this->db);
496
+                }
497
+            }
498
+            elseif ($modulepart == 'stock')
499
+            {
500
+                if (is_array($genallowed)) $modellist=$genallowed;
501
+                else
502
+                {
503
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php';
504
+                    $modellist=ModelePDFStock::liste_modeles($this->db);
505
+                }
506
+            }
507
+            elseif ($modulepart == 'movement')
508
+            {
509
+                if (is_array($genallowed)) $modellist=$genallowed;
510
+                else
511
+                {
512
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php';
513
+                    $modellist=ModelePDFMovement::liste_modeles($this->db);
514
+                }
515
+            }
516
+            elseif ($modulepart == 'export')
517
+            {
518
+                if (is_array($genallowed)) $modellist=$genallowed;
519
+                else
520
+                {
521
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
522
+                    $modellist=ModeleExports::liste_modeles($this->db);
523
+                }
524
+            }
525
+            else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
526
+            {
527
+                if (is_array($genallowed)) $modellist=$genallowed;
528
+                else
529
+                {
530
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
531
+                    $modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
532
+                }
533
+            }
534
+            else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
535
+            {
536
+                if (is_array($genallowed)) $modellist=$genallowed;
537
+                else
538
+                {
539
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
540
+                    $modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
541
+                }
542
+            }
543
+            else if ($modulepart == 'supplier_payment')
544
+            {
545
+                if (is_array($genallowed)) $modellist=$genallowed;
546
+                else
547
+                {
548
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
549
+                    $modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
550
+                }
551
+            }
552
+            else if ($modulepart == 'remisecheque')
553
+            {
554
+                if (is_array($genallowed)) $modellist=$genallowed;
555
+                else
556
+                {
557
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
558
+                    $modellist=ModeleChequeReceipts::liste_modeles($this->db);
559
+                }
560
+            }
561
+            elseif ($modulepart == 'donation')
562
+            {
563
+                if (is_array($genallowed)) $modellist=$genallowed;
564
+                else
565
+                {
566
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
567
+                    $modellist=ModeleDon::liste_modeles($this->db);
568
+                }
569
+            }
570
+            elseif ($modulepart == 'member')
571
+            {
572
+                if (is_array($genallowed)) $modellist=$genallowed;
573
+                else
574
+                {
575
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
576
+                    $modellist=ModelePDFCards::liste_modeles($this->db);
577
+                }
578
+            }
579
+            elseif ($modulepart == 'agenda' || $modulepart == 'actions')
580
+            {
581
+                if (is_array($genallowed)) $modellist=$genallowed;
582
+                else
583
+                {
584
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
585
+                    $modellist=ModeleAction::liste_modeles($this->db);
586
+                }
587
+            }
588
+            else if ($modulepart == 'expensereport')
589
+            {
590
+                if (is_array($genallowed)) $modellist=$genallowed;
591
+                else
592
+                {
593
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
594
+                    $modellist=ModeleExpenseReport::liste_modeles($this->db);
595
+                }
596
+            }
597
+            else if ($modulepart == 'unpaid')
598
+            {
599
+                $modellist='';
600
+            }
601
+            elseif ($modulepart == 'user')
602
+            {
603
+                if (is_array($genallowed)) $modellist=$genallowed;
604
+                else
605
+                {
606
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
607
+                    $modellist=ModelePDFUser::liste_modeles($this->db);
608
+                }
609
+            }
610
+            elseif ($modulepart == 'usergroup')
611
+            {
612
+                if (is_array($genallowed)) $modellist=$genallowed;
613
+                else
614
+                {
615
+                    include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
616
+                    $modellist=ModelePDFUserGroup::liste_modeles($this->db);
617
+                }
618
+            }
619
+            else
620
+            {
621
+                // For normalized standard modules
622
+                $file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
623
+                if (file_exists($file))
624
+                {
625
+                    $res=include_once $file;
626
+                }
627
+                // For normalized external modules
628
+                else
629
+                {
630
+                    $file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
631
+                    $res=include_once $file;
632
+                }
633
+                $class='ModelePDF'.ucfirst($modulepart);
634
+                if (class_exists($class))
635
+                {
636
+                    $modellist=call_user_func($class.'::liste_modeles',$this->db);
637
+                }
638
+                else
639
+                {
640
+                    dol_print_error($this->db,'Bad value for modulepart');
641
+                    return -1;
642
+                }
643
+            }
644
+
645
+            // Set headershown to avoid to have table opened a second time later
646
+            $headershown=1;
647
+
648
+            $buttonlabeltoshow=$buttonlabel;
649
+            if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
650
+
651
+            if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
652
+            if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
653
+            $out.= '<input type="hidden" name="action" value="builddoc">';
654
+            $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
655
+
656
+            $out.= load_fiche_titre($titletoshow, '', '');
657
+            $out.= '<div class="div-table-responsive-no-min">';
658
+            $out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
659
+
660
+            $out.= '<tr class="liste_titre">';
661
+
662
+            $addcolumforpicto=($delallowed || $printer || $morepicto);
663
+            $out.= '<th align="center" colspan="'.(3+($addcolumforpicto?1:0)).'" class="formdoc liste_titre maxwidthonsmartphone">';
664
+
665
+            // Model
666
+            if (! empty($modellist))
667
+            {
668
+                $out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
669
+                if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
670
+                {
671
+                    $arraykeys=array_keys($modellist);
672
+                    $modelselected=$arraykeys[0];
673
+                }
674
+                $out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
675
+                if ($conf->use_javascript_ajax)
676
+                {
677
+                    $out.= ajax_combobox('model');
678
+                }
679
+            }
680
+            else
681
+            {
682
+                $out.= '<div class="float">'.$langs->trans("Files").'</div>';
683
+            }
684
+
685
+            // Language code (if multilang)
686
+            if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
687
+            {
688
+                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
689
+                $formadmin=new FormAdmin($this->db);
690
+                $defaultlang=$codelang?$codelang:$langs->getDefaultLang();
691
+                $morecss='maxwidth150';
692
+                if ($conf->browser->layout == 'phone') $morecss='maxwidth100';
693
+                $out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
694
+            }
695
+            else
696
+            {
697
+                $out.= '&nbsp;';
698
+            }
699
+
700
+            // Button
701
+            $genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
702
+            $genbutton.= ' type="submit" value="'.$buttonlabel.'"';
703
+            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
704
+            $genbutton.= '>';
705
+            if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
706
+            {
707
+                    $langs->load("errors");
708
+                    $genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
709
+            }
710
+            if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
711
+            if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
712
+            $out.= $genbutton;
713
+            $out.= '</th>';
714
+
715
+            if (!empty($hookmanager->hooks['formfile']))
716
+            {
717
+                foreach($hookmanager->hooks['formfile'] as $module)
718
+                {
719
+                    if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
720
+                }
721
+            }
722
+            $out.= '</tr>';
723
+
724
+            // Execute hooks
725
+            $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
726
+            if (is_object($hookmanager))
727
+            {
728
+                $reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
729
+                $out.= $hookmanager->resPrint;
730
+            }
731
+        }
732
+
733
+        // Get list of files
734
+        if (! empty($filedir))
735
+        {
736
+            $link_list = array();
737
+            if (is_object($object))
738
+            {
739
+                require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
740
+                $link = new Link($this->db);
741
+                $sortfield = $sortorder = null;
742
+                $res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
743
+            }
744
+
745
+            $out.= '<!-- html.formfile::showdocuments -->'."\n";
746
+
747
+            // Show title of array if not already shown
748
+            if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart))
749
+                && ! $headershown)
750
+            {
751
+                $headershown=1;
752
+                $out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
753
+                $out.= '<div class="div-table-responsive-no-min">';
754
+                $out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
755
+            }
756
+
757
+            // Loop on each file found
758
+            if (is_array($file_list))
759
+            {
760
+                foreach($file_list as $file)
761
+                {
762
+                    // Define relative path for download link (depends on module)
763
+                    $relativepath=$file["name"];										// Cas general
764
+                    if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
765
+                    if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
766
+
767
+                    $out.= '<tr class="oddeven">';
768
+
769
+                    $documenturl = DOL_URL_ROOT.'/document.php';
770
+                    if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
771
+
772
+                    // Show file name with link to download
773
+                    $out.= '<td class="minwidth200">';
774
+                    $out.= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
775
+                    $mime=dol_mimetype($relativepath,'',0);
776
+                    if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
777
+                    $out.= ' target="_blank">';
778
+                    $out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]);
779
+                    $out.= dol_trunc($file["name"], 150);
780
+                    $out.= '</a>'."\n";
781
+                    $out.= $this->showPreview($file,$modulepart,$relativepath,0,$param);
782
+                    $out.= '</td>';
783
+
784
+                    // Show file size
785
+                    $size=(! empty($file['size'])?$file['size']:dol_filesize($filedir."/".$file["name"]));
786
+                    $out.= '<td align="right" class="nowrap">'.dol_print_size($size,1,1).'</td>';
787
+
788
+                    // Show file date
789
+                    $date=(! empty($file['date'])?$file['date']:dol_filemtime($filedir."/".$file["name"]));
790
+                    $out.= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
791
+
792
+                    if ($delallowed || $printer || $morepicto)
793
+                    {
794
+                        $out.= '<td class="right nowraponall">';
795
+                        if ($delallowed)
796
+                        {
797
+                            $tmpurlsource = preg_replace('/#[a-zA-Z0-9_]*$/', '', $urlsource);
798
+                            $out.= '<a href="'.$tmpurlsource.(strpos($tmpurlsource,'?')?'&amp;':'?').'action=remove_file&amp;file='.urlencode($relativepath);
799
+                            $out.= ($param?'&amp;'.$param:'');
800
+                            //$out.= '&modulepart='.$modulepart; // TODO obsolete ?
801
+                            //$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
802
+                            $out.= '">'.img_picto($langs->trans("Delete"), 'delete').'</a>';
803
+                        }
804
+                        if ($printer)
805
+                        {
806
+                            //$out.= '<td align="right">';
807
+                            $out.= '<a class="paddingleft" href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
808
+                            $out.= ($param?'&amp;'.$param:'');
809
+                            $out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
810
+                        }
811
+                        if ($morepicto)
812
+                        {
813
+                            $morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto);
814
+                            $out.=$morepicto;
815
+                        }
816
+                        $out.='</td>';
817
+                    }
818
+
819
+                    if (is_object($hookmanager))
820
+                    {
821
+                        $parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
822
+                        $res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
823
+                        if (empty($res))
824
+                        {
825
+                            $out.= $hookmanager->resPrint;		// Complete line
826
+                            $out.= '</tr>';
827
+                        }
828
+                        else $out = $hookmanager->resPrint;		// Replace line
829
+                        }
830
+                }
831
+
832
+                $this->numoffiles++;
833
+            }
834
+            // Loop on each link found
835
+            if (is_array($link_list))
836
+            {
837
+                $colspan=2;
838
+
839
+                foreach($link_list as $file)
840
+                {
841
+                    $out.='<tr class="oddeven">';
842
+                    $out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
843
+                    $out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
844
+                    $out.=$file->label;
845
+                    $out.='</a>';
846
+                    $out.='</td>';
847
+                    $out.='<td align="right">';
848
+                    $out.=dol_print_date($file->datea,'dayhour');
849
+                    $out.='</td>';
850
+                    if ($delallowed || $printer || $morepicto) $out.='<td></td>';
851
+                    $out.='</tr>'."\n";
852
+                }
853
+                $this->numoffiles++;
854
+            }
855
+
856
+                if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
857
+            {
858
+                $out.='<tr><td colspan="'.(3+($addcolumforpicto?1:0)).'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
859
+            }
860
+        }
861
+
862
+        if ($headershown)
863
+        {
864
+            // Affiche pied du tableau
865
+            $out.= "</table>\n";
866
+            $out.= "</div>\n";
867
+            if ($genallowed)
868
+            {
869
+                if (empty($noform)) $out.= '</form>'."\n";
870
+            }
871
+        }
872
+        $out.= '<!-- End show_document -->'."\n";
873
+        //return ($i?$i:$headershown);
874
+        return $out;
875
+    }
876
+
877
+    /**
878
+     *	Show a Document icon with link(s)
879
+     *  You may want to call this into a div like this:
880
+     *  print '<div class="inline-block valignmiddle">'.$formfile->getDocumentsLink($element_doc, $filename, $filedir).'</div>';
881
+     *
882
+     *	@param	string	$modulepart		propal, facture, facture_fourn, ...
883
+     *	@param	string	$modulesubdir	Sub-directory to scan (Example: '0/1/10', 'FA/DD/MM/YY/9999'). Use '' if file is not into subdir of module.
884
+     *	@param	string	$filedir		Full path to directory to scan
885
+     *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
886
+     *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
887
+     */
888
+    function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
889
+    {
890
+        global $conf, $langs;
891
+
892
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
893
+
894
+        $out='';
895
+        $this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
896
+
897
+        $entity = 1; // Without multicompany
898
+
899
+        // Get object entity
900
+        if (! empty($conf->multicompany->enabled))
901
+        {
902
+            preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir,'/').'$/', $filedir, $regs);
903
+            $entity = ((! empty($regs[1]) && $regs[1] > 1) ? $regs[1] : 1); // If entity id not found in $filedir this is entity 1 by default
904
+        }
905
+
906
+        // Get list of files starting with name of ref (but not followed by "-" to discard uploaded files and get only generated files)
907
+        // @TODO Why not showing by default all files by just removing the '[^\-]+' at end of regex ?
908
+        if (! empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP))
909
+        {
910
+            $filterforfilesearch = preg_quote(basename($modulesubdir),'/');
911
+        }
912
+        else
913
+        {
914
+            $filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
915
+        }
916
+        $file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// We also discard .meta and .png preview
917
+
918
+        //var_dump($file_list);
919
+        // For ajax treatment
920
+        $out.= '<!-- html.formfile::getDocumentsLink -->'."\n";
921
+        if (! empty($file_list))
922
+        {
923
+            $out='<dl class="dropdown inline-block">
924 924
     			<dt><a data-ajax="false" href="#" onClick="return false;">'.img_picto('', 'listlight', '', 0, 0, 0, '', 'valignmiddle').'</a></dt>
925 925
     			<dd><div class="multichoicedoc" style="position:absolute;left:100px;" ><ul class="ulselectedfields" style="display: none;">';
926
-			$tmpout='';
927
-
928
-			// Loop on each file found
929
-			$found=0;
930
-			foreach($file_list as $file)
931
-			{
932
-				$i++;
933
-				if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
934
-
935
-				$found++;
936
-				// Define relative path for download link (depends on module)
937
-				$relativepath=$file["name"];								// Cas general
938
-				if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
939
-				// Autre cas
940
-				if ($modulepart == 'donation')            {
941
-					$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
942
-				}
943
-				if ($modulepart == 'export')              {
944
-					$relativepath = $file["name"];
945
-				}
946
-
947
-				$this->infofiles['nboffiles']++;
948
-				$this->infofiles['files'][]=$file['fullname'];
949
-				$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
950
-				if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
951
-				else $this->infofiles['extensions'][$ext]++;
952
-
953
-				// Preview
954
-				if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
955
-				{
956
-					$tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
957
-					if ($tmparray && $tmparray['url'])
958
-					{
959
-						$tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>';
960
-						//$tmpout.= img_picto('','detail');
961
-						$tmpout.= '<i class="fa fa-search-plus paddingright" style="color: gray"></i>';
962
-						$tmpout.= $langs->trans("Preview").' '.$ext.'</a></li>';
963
-					}
964
-				}
965
-
966
-				// Download
967
-				$tmpout.= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
968
-				$mime=dol_mimetype($relativepath,'',0);
969
-				if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
970
-				$tmpout.= '>';
971
-				$tmpout.= img_mime($relativepath, $file["name"]);
972
-				$tmpout.= $langs->trans("Download").' '.$ext;
973
-				$tmpout.= '</a></li>'."\n";
974
-			}
975
-			$out.=$tmpout;
976
-			$out.='</ul></div></dd>
926
+            $tmpout='';
927
+
928
+            // Loop on each file found
929
+            $found=0;
930
+            foreach($file_list as $file)
931
+            {
932
+                $i++;
933
+                if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
934
+
935
+                $found++;
936
+                // Define relative path for download link (depends on module)
937
+                $relativepath=$file["name"];								// Cas general
938
+                if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
939
+                // Autre cas
940
+                if ($modulepart == 'donation')            {
941
+                    $relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
942
+                }
943
+                if ($modulepart == 'export')              {
944
+                    $relativepath = $file["name"];
945
+                }
946
+
947
+                $this->infofiles['nboffiles']++;
948
+                $this->infofiles['files'][]=$file['fullname'];
949
+                $ext=pathinfo($file["name"], PATHINFO_EXTENSION);
950
+                if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
951
+                else $this->infofiles['extensions'][$ext]++;
952
+
953
+                // Preview
954
+                if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
955
+                {
956
+                    $tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
957
+                    if ($tmparray && $tmparray['url'])
958
+                    {
959
+                        $tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>';
960
+                        //$tmpout.= img_picto('','detail');
961
+                        $tmpout.= '<i class="fa fa-search-plus paddingright" style="color: gray"></i>';
962
+                        $tmpout.= $langs->trans("Preview").' '.$ext.'</a></li>';
963
+                    }
964
+                }
965
+
966
+                // Download
967
+                $tmpout.= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
968
+                $mime=dol_mimetype($relativepath,'',0);
969
+                if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
970
+                $tmpout.= '>';
971
+                $tmpout.= img_mime($relativepath, $file["name"]);
972
+                $tmpout.= $langs->trans("Download").' '.$ext;
973
+                $tmpout.= '</a></li>'."\n";
974
+            }
975
+            $out.=$tmpout;
976
+            $out.='</ul></div></dd>
977 977
     			</dl>';
978 978
 
979
-			if (! $found) $out='';
980
-		}
981
-		else
982
-		{
983
-			// TODO Add link to regenerate doc ?
984
-			//$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
985
-		}
979
+            if (! $found) $out='';
980
+        }
981
+        else
982
+        {
983
+            // TODO Add link to regenerate doc ?
984
+            //$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
985
+        }
986 986
 
987
-		return $out;
988
-	}
987
+        return $out;
988
+    }
989 989
 
990 990
 
991 991
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
992
-	/**
993
-	 *  Show list of documents in $filearray (may be they are all in same directory but may not)
994
-	 *  This also sync database if $upload_dir is defined.
995
-	 *
996
-	 *  @param	 array	$filearray          Array of files loaded by dol_dir_list('files') function before calling this.
997
-	 * 	@param	 Object	$object				Object on which document is linked to.
998
-	 * 	@param	 string	$modulepart			Value for modulepart used by download or viewimage wrapper.
999
-	 * 	@param	 string	$param				Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd)
1000
-	 * 	@param	 int	$forcedownload		Force to open dialog box "Save As" when clicking on file.
1001
-	 * 	@param	 string	$relativepath		Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT.
1002
-	 * 	@param	 int	$permonobject		Permission on object (so permission to delete or crop document)
1003
-	 * 	@param	 int	$useinecm			Change output for use in ecm module:
1004
-	 * 										0: Add a previw link. Show also rename and crop file
1005
-	 * 										1: Add link to edit ECM entry
1006
-	 * 										2: Add rename and crop file
1007
-	 * 	@param	 string	$textifempty		Text to show if filearray is empty ('NoFileFound' if not defined)
1008
-	 *  @param   int	$maxlength          Maximum length of file name shown.
1009
-	 *  @param	 string	$title				Title before list. Use 'none' to disable title.
1010
-	 *  @param	 string $url				Full url to use for click links ('' = autodetect)
1011
-	 *  @param	 int	$showrelpart		0=Show only filename (default), 1=Show first level 1 dir
1012
-	 *  @param   int    $permtoeditline     Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more)
1013
-	 *  @param   string $upload_dir         Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this to complete file data with database indexes.
1014
-	 *  @param   string $sortfield          Sort field ('name', 'size', 'position', ...)
1015
-	 *  @param   string $sortorder          Sort order ('ASC' or 'DESC')
1016
-	 *  @param   int    $disablemove        1=Disable move button, 0=Position move is possible.
1017
-	 *  @param	 int	$addfilterfields	Add line with filters
1018
-	 * 	@return	 int						<0 if KO, nb of files shown if OK
1019
-	 *  @see list_of_autoecmfiles
1020
-	 */
1021
-	function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0)
1022
-	{
992
+    /**
993
+     *  Show list of documents in $filearray (may be they are all in same directory but may not)
994
+     *  This also sync database if $upload_dir is defined.
995
+     *
996
+     *  @param	 array	$filearray          Array of files loaded by dol_dir_list('files') function before calling this.
997
+     * 	@param	 Object	$object				Object on which document is linked to.
998
+     * 	@param	 string	$modulepart			Value for modulepart used by download or viewimage wrapper.
999
+     * 	@param	 string	$param				Parameters on sort links (param must start with &, example &aaa=bbb&ccc=ddd)
1000
+     * 	@param	 int	$forcedownload		Force to open dialog box "Save As" when clicking on file.
1001
+     * 	@param	 string	$relativepath		Relative path of docs (autodefined if not provided), relative to module dir, not to MAIN_DATA_ROOT.
1002
+     * 	@param	 int	$permonobject		Permission on object (so permission to delete or crop document)
1003
+     * 	@param	 int	$useinecm			Change output for use in ecm module:
1004
+     * 										0: Add a previw link. Show also rename and crop file
1005
+     * 										1: Add link to edit ECM entry
1006
+     * 										2: Add rename and crop file
1007
+     * 	@param	 string	$textifempty		Text to show if filearray is empty ('NoFileFound' if not defined)
1008
+     *  @param   int	$maxlength          Maximum length of file name shown.
1009
+     *  @param	 string	$title				Title before list. Use 'none' to disable title.
1010
+     *  @param	 string $url				Full url to use for click links ('' = autodetect)
1011
+     *  @param	 int	$showrelpart		0=Show only filename (default), 1=Show first level 1 dir
1012
+     *  @param   int    $permtoeditline     Permission to edit document line (You must provide a value, -1 is deprecated and must not be used any more)
1013
+     *  @param   string $upload_dir         Full path directory so we can know dir relative to MAIN_DATA_ROOT. Fill this to complete file data with database indexes.
1014
+     *  @param   string $sortfield          Sort field ('name', 'size', 'position', ...)
1015
+     *  @param   string $sortorder          Sort order ('ASC' or 'DESC')
1016
+     *  @param   int    $disablemove        1=Disable move button, 0=Position move is possible.
1017
+     *  @param	 int	$addfilterfields	Add line with filters
1018
+     * 	@return	 int						<0 if KO, nb of files shown if OK
1019
+     *  @see list_of_autoecmfiles
1020
+     */
1021
+    function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0)
1022
+    {
1023 1023
         // phpcs:enable
1024
-		global $user, $conf, $langs, $hookmanager;
1025
-		global $sortfield, $sortorder, $maxheightmini;
1026
-		global $dolibarr_main_url_root;
1027
-		global $form;
1028
-
1029
-		$disablecrop=1;
1030
-		if (in_array($modulepart, array('expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) $disablecrop=0;
1031
-
1032
-		// Define relative path used to store the file
1033
-		if (empty($relativepath))
1034
-		{
1035
-			$relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
1036
-			if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
1037
-			if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1038
-		}
1039
-		// For backward compatiblity, we detect file stored into an old path
1040
-		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos')
1041
-		{
1042
-		    $relativepath=preg_replace('/^.*\/produit\//','',$filearray[0]['path']).'/';
1043
-		}
1044
-		// Defined relative dir to DOL_DATA_ROOT
1045
-		$relativedir = '';
1046
-		if ($upload_dir)
1047
-		{
1048
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
1049
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
1050
-		}
1051
-
1052
-		$hookmanager->initHooks(array('formfile'));
1053
-		$parameters=array(
1054
-				'filearray' => $filearray,
1055
-				'modulepart'=> $modulepart,
1056
-				'param' => $param,
1057
-				'forcedownload' => $forcedownload,
1058
-				'relativepath' => $relativepath,    // relative filename to module dir
1059
-				'relativedir' => $relativedir,      // relative dirname to DOL_DATA_ROOT
1060
-				'permtodelete' => $permonobject,
1061
-				'useinecm' => $useinecm,
1062
-				'textifempty' => $textifempty,
1063
-				'maxlength' => $maxlength,
1064
-				'title' => $title,
1065
-				'url' => $url
1066
-		);
1067
-		$reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
1068
-
1069
-		if (isset($reshook) && $reshook != '') // null or '' for bypass
1070
-		{
1071
-			return $reshook;
1072
-		}
1073
-		else
1074
-		{
1075
-			if (! is_object($form))
1076
-			{
1077
-				include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';		// The compoent may be included into ajax page that does not include the Form class
1078
-				$form=new Form($this->db);
1079
-			}
1080
-
1081
-			if (! preg_match('/&id=/', $param) && isset($object->id)) $param.='&id='.$object->id;
1082
-			$relativepathwihtoutslashend=preg_replace('/\/$/', '', $relativepath);
1083
-			if ($relativepathwihtoutslashend) $param.= '&file='.urlencode($relativepathwihtoutslashend);
1084
-
1085
-			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1086
-			{
1087
-				$permtoeditline=0;
1088
-				if (in_array($modulepart, array('product','produit','service')))
1089
-				{
1090
-					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
1091
-					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
1092
-				}
1093
-			}
1094
-			if (empty($conf->global->MAIN_UPLOAD_DOC))
1095
-			{
1096
-				$permtoeditline=0;
1097
-				$permonobject=0;
1098
-			}
1099
-
1100
-			// Show list of existing files
1101
-			if (empty($useinecm) && $title != 'none') print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1102
-			if (empty($url)) $url=$_SERVER["PHP_SELF"];
1103
-
1104
-			print '<!-- html.formfile::list_of_documents -->'."\n";
1105
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1106
-			{
1107
-				print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1108
-				print '<input type="hidden" name="action" value="renamefile">';
1109
-				print '<input type="hidden" name="id" value="'.$object->id.'">';
1110
-				print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1111
-			}
1112
-
1113
-			print '<div class="div-table-responsive-no-min">';
1114
-			print '<table width="100%" id="tablelines" class="'.($useinecm?'liste noborder':'liste').'">'."\n";
1115
-
1116
-			if (! empty($addfilterfields))
1117
-			{
1118
-				print '<tr class="liste_titre nodrag nodrop">';
1119
-				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1120
-				print '<td></td>';
1121
-				print '<td></td>';
1122
-				if (empty($useinecm)) print '<td></td>';
1123
-				print '<td></td>';
1124
-				print '<td></td>';
1125
-				if (! $disablemove) print '<td></td>';
1126
-				print "</tr>\n";
1127
-			}
1128
-
1129
-			print '<tr class="liste_titre nodrag nodrop">';
1130
-			//print $url.' sortfield='.$sortfield.' sortorder='.$sortorder;
1131
-			print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1132
-			print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1133
-			print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1134
-			if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');					// Preview
1135
-			print_liste_field_titre('');
1136
-			print_liste_field_titre('');
1137
-			if (! $disablemove) print_liste_field_titre('');
1138
-			print "</tr>\n";
1139
-
1140
-			// Get list of files stored into database for same relative directory
1141
-			if ($relativedir)
1142
-			{
1143
-				completeFileArrayWithDatabaseInfo($filearray, $relativedir);
1144
-
1145
-				//var_dump($sortfield.' - '.$sortorder);
1146
-				if ($sortfield && $sortorder)	// If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
1147
-				{
1148
-					$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1149
-				}
1150
-			}
1151
-
1152
-			$nboffiles=count($filearray);
1153
-			if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1154
-
1155
-			$i=0; $nboflines = 0; $lastrowid=0;
1156
-			foreach($filearray as $key => $file)      // filearray must be only files here
1157
-			{
1158
-				if ($file['name'] != '.'
1159
-						&& $file['name'] != '..'
1160
-						&& ! preg_match('/\.meta$/i',$file['name']))
1161
-				{
1162
-					if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1163
-					$filepath=$relativepath.$file['name'];
1164
-
1165
-					$editline=0;
1166
-					$nboflines++;
1167
-					print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1168
-					// Do we have entry into database ?
1169
-					print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1170
-					print '<tr class="oddeven" id="row-'.($filearray[$key]['rowid']>0?$filearray[$key]['rowid']:'AFTER'.$lastrowid.'POS'.($i+1)).'">';
1171
-
1172
-					// File name
1173
-					print '<td class="minwith200">';
1174
-
1175
-					// Show file name with link to download
1176
-					//print "XX".$file['name'];	//$file['name'] must be utf8
1177
-					print '<a class="paddingright" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1178
-					if ($forcedownload) print '&attachment=1';
1179
-					if (! empty($object->entity)) print '&entity='.$object->entity;
1180
-					print '&file='.urlencode($filepath);
1181
-					print '">';
1182
-					print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'],0,0).')', 'inline-block valignbottom paddingright');
1183
-					if ($showrelpart == 1) print $relativepath;
1184
-					//print dol_trunc($file['name'],$maxlength,'middle');
1185
-					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile','alpha')))
1186
-					{
1187
-						print '</a>';
1188
-						$section_dir=dirname(GETPOST('urlfile','alpha'));
1189
-						print '<input type="hidden" name="section_dir" value="'.$section_dir.'">';
1190
-						print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1191
-						print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1192
-						$editline=1;
1193
-					}
1194
-					else
1195
-					{
1196
-						print dol_trunc($file['name'], 200);
1197
-						print '</a>';
1198
-					}
1199
-					// Preview link
1200
-					if (! $editline) print $this->showPreview($file, $modulepart, $filepath);
1201
-					// Public share link
1202
-					//if (! $editline && ! empty($filearray[$key]['hashp'])) print pictowithlinktodirectdownload;
1203
-
1204
-					print "</td>\n";
1205
-
1206
-					// Size
1207
-					$sizetoshow = dol_print_size($file['size'],1,1);
1208
-					$sizetoshowbytes = dol_print_size($file['size'],0,1);
1209
-
1210
-					print '<td align="right" width="80px">';
1211
-					if ($sizetoshow == $sizetoshowbytes) print $sizetoshow;
1212
-					else {
1213
-						print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1);
1214
-					}
1215
-					print '</td>';
1216
-
1217
-					// Date
1218
-					print '<td align="center" width="140px">'.dol_print_date($file['date'],"dayhour","tzuser").'</td>';	// 140px = width for date with PM format
1219
-
1220
-					// Preview
1221
-					if (empty($useinecm))
1222
-					{
1223
-						$fileinfo = pathinfo($file['name']);
1224
-						print '<td align="center">';
1225
-						if (image_format_supported($file['name']) > 0)
1226
-						{
1227
-							$minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1228
-							if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1229
-							//print $file['path'].'/'.$minifile.'<br>';
1230
-
1231
-							$urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1232
-							if (empty($urlforhref)) {
1233
-								$urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1234
-								print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1235
-							} else {
1236
-								print '<a href="'.$urlforhref['url'].'" class="'.$urlforhref['css'].'" target="'.$urlforhref['target'].'" mime="'.$urlforhref['mime'].'">';
1237
-							}
1238
-							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1239
-							print '</a>';
1240
-						}
1241
-						else print '&nbsp;';
1242
-						print '</td>';
1243
-					}
1244
-
1245
-					// Hash of file (only if we are in a mode where a scan of dir were done and we have id of file in ECM table)
1246
-					print '<td align="center">';
1247
-					if ($relativedir && $filearray[$key]['rowid'] > 0)
1248
-					{
1249
-						if ($editline)
1250
-						{
1251
-							print $langs->trans("FileSharedViaALink").' ';
1252
-							print '<input class="inline-block" type="checkbox" name="shareenabled"'.($file['share']?' checked="checked"':'').' /> ';
1253
-						}
1254
-						else
1255
-						{
1256
-							if ($file['share'])
1257
-							{
1258
-								// Define $urlwithroot
1259
-								$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
1260
-								$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
1261
-								//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
1262
-
1263
-								//print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
1264
-								$forcedownload=0;
1265
-								$paramlink='';
1266
-								if (! empty($file['share'])) $paramlink.=($paramlink?'&':'').'hashp='.$file['share'];			// Hash for public share
1267
-								if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
1268
-
1269
-								$fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
1270
-
1271
-								print img_picto($langs->trans("FileSharedViaALink"),'object_globe.png').' ';
1272
-								print '<input type="text" class="quatrevingtpercent" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
1273
-							}
1274
-							else
1275
-							{
1276
-								//print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
1277
-							}
1278
-						}
1279
-					}
1280
-					print '</td>';
1281
-
1282
-					// Actions buttons
1283
-					if (! $editline)
1284
-					{
1285
-						// Delete or view link
1286
-						// ($param must start with &)
1287
-						print '<td class="valignmiddle right actionbuttons"><!-- action on files -->';
1288
-						if ($useinecm == 1)
1289
-						{
1290
-							print '<a href="'.DOL_URL_ROOT.'/ecm/file_card.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
1291
-						}
1292
-						if (! $useinecm || $useinecm == 2)
1293
-						{
1294
-							$newmodulepart=$modulepart;
1295
-							if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1296
-
1297
-							if (! $disablecrop && image_format_supported($file['name']) > 0)
1298
-							{
1299
-								if ($permtoeditline)
1300
-								{
1301
-	   								// Link to resize
1302
-	   						   		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("ResizeOrCrop")).'">'.img_picto($langs->trans("ResizeOrCrop"),'resize','class="paddingrightonly"').'</a>';
1303
-								}
1304
-							}
1305
-
1306
-							if ($permtoeditline)
1307
-							{
1308
-								$paramsectiondir=(in_array($modulepart, array('medias','ecm'))?'&section_dir='.urlencode($relativepath):'');
1309
-								print '<a href="'.(($useinecm == 1)?'#':($url.'?action=editfile&urlfile='.urlencode($filepath).$paramsectiondir.$param)).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1310
-							}
1311
-						}
1312
-						if ($permonobject)
1313
-						{
1314
-							$useajax=1;
1315
-							if (! empty($conf->dol_use_jmobile)) $useajax=0;
1316
-							if (empty($conf->use_javascript_ajax)) $useajax=0;
1317
-							if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1318
-							print '<a href="'.(($useinecm && $useajax)?'#':($url.'?action=delete&urlfile='.urlencode($filepath).$param)).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1319
-						}
1320
-						print "</td>";
1024
+        global $user, $conf, $langs, $hookmanager;
1025
+        global $sortfield, $sortorder, $maxheightmini;
1026
+        global $dolibarr_main_url_root;
1027
+        global $form;
1028
+
1029
+        $disablecrop=1;
1030
+        if (in_array($modulepart, array('expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) $disablecrop=0;
1031
+
1032
+        // Define relative path used to store the file
1033
+        if (empty($relativepath))
1034
+        {
1035
+            $relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
1036
+            if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
1037
+            if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1038
+        }
1039
+        // For backward compatiblity, we detect file stored into an old path
1040
+        if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos')
1041
+        {
1042
+            $relativepath=preg_replace('/^.*\/produit\//','',$filearray[0]['path']).'/';
1043
+        }
1044
+        // Defined relative dir to DOL_DATA_ROOT
1045
+        $relativedir = '';
1046
+        if ($upload_dir)
1047
+        {
1048
+            $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
1049
+            $relativedir = preg_replace('/^[\\/]/','',$relativedir);
1050
+        }
1051
+
1052
+        $hookmanager->initHooks(array('formfile'));
1053
+        $parameters=array(
1054
+                'filearray' => $filearray,
1055
+                'modulepart'=> $modulepart,
1056
+                'param' => $param,
1057
+                'forcedownload' => $forcedownload,
1058
+                'relativepath' => $relativepath,    // relative filename to module dir
1059
+                'relativedir' => $relativedir,      // relative dirname to DOL_DATA_ROOT
1060
+                'permtodelete' => $permonobject,
1061
+                'useinecm' => $useinecm,
1062
+                'textifempty' => $textifempty,
1063
+                'maxlength' => $maxlength,
1064
+                'title' => $title,
1065
+                'url' => $url
1066
+        );
1067
+        $reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
1068
+
1069
+        if (isset($reshook) && $reshook != '') // null or '' for bypass
1070
+        {
1071
+            return $reshook;
1072
+        }
1073
+        else
1074
+        {
1075
+            if (! is_object($form))
1076
+            {
1077
+                include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';		// The compoent may be included into ajax page that does not include the Form class
1078
+                $form=new Form($this->db);
1079
+            }
1321 1080
 
1322
-						if (empty($disablemove))
1323
-						{
1324
-							if ($nboffiles > 1 && $conf->browser->layout != 'phone') {
1325
-								print '<td align="center" class="linecolmove tdlineupdown">';
1326
-								if ($i > 0) {
1327
-									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1328
-								}
1329
-								if ($i < $nboffiles-1) {
1330
-									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1331
-								}
1332
-								print '</td>';
1333
-							}
1334
-							else {
1335
-							   	print '<td align="center"'.(($conf->browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1336
-							   	print '</td>';
1337
-							}
1338
-					   }
1339
-					}
1340
-					else
1341
-					{
1342
-						print '<td class="right">';
1343
-						print '<input type="hidden" name="ecmfileid" value="'.$filearray[$key]['rowid'].'">';
1344
-						print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1345
-						print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1346
-						print '</td>';
1347
-						if (empty($disablemove)) print '<td class="right"></td>';
1348
-					}
1349
-					print "</tr>\n";
1350
-
1351
-					$i++;
1352
-				}
1353
-			}
1354
-			if ($nboffiles == 0)
1355
-			{
1356
-				$colspan=(empty($useinecm)?'6':'6');
1357
-				if (empty($disablemove)) $colspan++;		// 6 columns or 7
1358
-				print '<tr class="oddeven"><td colspan="'.$colspan.'" class="opacitymedium">';
1359
-				if (empty($textifempty)) print $langs->trans("NoFileFound");
1360
-				else print $textifempty;
1361
-				print '</td></tr>';
1362
-			}
1363
-			print "</table>";
1364
-			print '</div>';
1365
-
1366
-			if ($nboflines > 1 && is_object($object)) {
1367
-				if (! empty($conf->use_javascript_ajax) && $permtoeditline) {
1368
-					$table_element_line = 'ecm_files';
1369
-					include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1370
-				}
1371
-			}
1372
-
1373
-			print ajax_autoselect('downloadlink');
1374
-
1375
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1376
-			{
1377
-				print '</form>';
1378
-			}
1379
-
1380
-			return $nboffiles;
1381
-		}
1382
-	}
1081
+            if (! preg_match('/&id=/', $param) && isset($object->id)) $param.='&id='.$object->id;
1082
+            $relativepathwihtoutslashend=preg_replace('/\/$/', '', $relativepath);
1083
+            if ($relativepathwihtoutslashend) $param.= '&file='.urlencode($relativepathwihtoutslashend);
1084
+
1085
+            if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1086
+            {
1087
+                $permtoeditline=0;
1088
+                if (in_array($modulepart, array('product','produit','service')))
1089
+                {
1090
+                    if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
1091
+                    if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
1092
+                }
1093
+            }
1094
+            if (empty($conf->global->MAIN_UPLOAD_DOC))
1095
+            {
1096
+                $permtoeditline=0;
1097
+                $permonobject=0;
1098
+            }
1099
+
1100
+            // Show list of existing files
1101
+            if (empty($useinecm) && $title != 'none') print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1102
+            if (empty($url)) $url=$_SERVER["PHP_SELF"];
1103
+
1104
+            print '<!-- html.formfile::list_of_documents -->'."\n";
1105
+            if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1106
+            {
1107
+                print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1108
+                print '<input type="hidden" name="action" value="renamefile">';
1109
+                print '<input type="hidden" name="id" value="'.$object->id.'">';
1110
+                print '<input type="hidden" name="modulepart" value="'.$modulepart.'">';
1111
+            }
1112
+
1113
+            print '<div class="div-table-responsive-no-min">';
1114
+            print '<table width="100%" id="tablelines" class="'.($useinecm?'liste noborder':'liste').'">'."\n";
1115
+
1116
+            if (! empty($addfilterfields))
1117
+            {
1118
+                print '<tr class="liste_titre nodrag nodrop">';
1119
+                print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1120
+                print '<td></td>';
1121
+                print '<td></td>';
1122
+                if (empty($useinecm)) print '<td></td>';
1123
+                print '<td></td>';
1124
+                print '<td></td>';
1125
+                if (! $disablemove) print '<td></td>';
1126
+                print "</tr>\n";
1127
+            }
1128
+
1129
+            print '<tr class="liste_titre nodrag nodrop">';
1130
+            //print $url.' sortfield='.$sortfield.' sortorder='.$sortorder;
1131
+            print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1132
+            print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1133
+            print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1134
+            if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');					// Preview
1135
+            print_liste_field_titre('');
1136
+            print_liste_field_titre('');
1137
+            if (! $disablemove) print_liste_field_titre('');
1138
+            print "</tr>\n";
1139
+
1140
+            // Get list of files stored into database for same relative directory
1141
+            if ($relativedir)
1142
+            {
1143
+                completeFileArrayWithDatabaseInfo($filearray, $relativedir);
1144
+
1145
+                //var_dump($sortfield.' - '.$sortorder);
1146
+                if ($sortfield && $sortorder)	// If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
1147
+                {
1148
+                    $filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1149
+                }
1150
+            }
1151
+
1152
+            $nboffiles=count($filearray);
1153
+            if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1154
+
1155
+            $i=0; $nboflines = 0; $lastrowid=0;
1156
+            foreach($filearray as $key => $file)      // filearray must be only files here
1157
+            {
1158
+                if ($file['name'] != '.'
1159
+                        && $file['name'] != '..'
1160
+                        && ! preg_match('/\.meta$/i',$file['name']))
1161
+                {
1162
+                    if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1163
+                    $filepath=$relativepath.$file['name'];
1164
+
1165
+                    $editline=0;
1166
+                    $nboflines++;
1167
+                    print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1168
+                    // Do we have entry into database ?
1169
+                    print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1170
+                    print '<tr class="oddeven" id="row-'.($filearray[$key]['rowid']>0?$filearray[$key]['rowid']:'AFTER'.$lastrowid.'POS'.($i+1)).'">';
1171
+
1172
+                    // File name
1173
+                    print '<td class="minwith200">';
1174
+
1175
+                    // Show file name with link to download
1176
+                    //print "XX".$file['name'];	//$file['name'] must be utf8
1177
+                    print '<a class="paddingright" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1178
+                    if ($forcedownload) print '&attachment=1';
1179
+                    if (! empty($object->entity)) print '&entity='.$object->entity;
1180
+                    print '&file='.urlencode($filepath);
1181
+                    print '">';
1182
+                    print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'],0,0).')', 'inline-block valignbottom paddingright');
1183
+                    if ($showrelpart == 1) print $relativepath;
1184
+                    //print dol_trunc($file['name'],$maxlength,'middle');
1185
+                    if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile','alpha')))
1186
+                    {
1187
+                        print '</a>';
1188
+                        $section_dir=dirname(GETPOST('urlfile','alpha'));
1189
+                        print '<input type="hidden" name="section_dir" value="'.$section_dir.'">';
1190
+                        print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1191
+                        print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1192
+                        $editline=1;
1193
+                    }
1194
+                    else
1195
+                    {
1196
+                        print dol_trunc($file['name'], 200);
1197
+                        print '</a>';
1198
+                    }
1199
+                    // Preview link
1200
+                    if (! $editline) print $this->showPreview($file, $modulepart, $filepath);
1201
+                    // Public share link
1202
+                    //if (! $editline && ! empty($filearray[$key]['hashp'])) print pictowithlinktodirectdownload;
1203
+
1204
+                    print "</td>\n";
1205
+
1206
+                    // Size
1207
+                    $sizetoshow = dol_print_size($file['size'],1,1);
1208
+                    $sizetoshowbytes = dol_print_size($file['size'],0,1);
1209
+
1210
+                    print '<td align="right" width="80px">';
1211
+                    if ($sizetoshow == $sizetoshowbytes) print $sizetoshow;
1212
+                    else {
1213
+                        print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1);
1214
+                    }
1215
+                    print '</td>';
1216
+
1217
+                    // Date
1218
+                    print '<td align="center" width="140px">'.dol_print_date($file['date'],"dayhour","tzuser").'</td>';	// 140px = width for date with PM format
1219
+
1220
+                    // Preview
1221
+                    if (empty($useinecm))
1222
+                    {
1223
+                        $fileinfo = pathinfo($file['name']);
1224
+                        print '<td align="center">';
1225
+                        if (image_format_supported($file['name']) > 0)
1226
+                        {
1227
+                            $minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1228
+                            if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1229
+                            //print $file['path'].'/'.$minifile.'<br>';
1230
+
1231
+                            $urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1232
+                            if (empty($urlforhref)) {
1233
+                                $urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1234
+                                print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1235
+                            } else {
1236
+                                print '<a href="'.$urlforhref['url'].'" class="'.$urlforhref['css'].'" target="'.$urlforhref['target'].'" mime="'.$urlforhref['mime'].'">';
1237
+                            }
1238
+                            print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1239
+                            print '</a>';
1240
+                        }
1241
+                        else print '&nbsp;';
1242
+                        print '</td>';
1243
+                    }
1244
+
1245
+                    // Hash of file (only if we are in a mode where a scan of dir were done and we have id of file in ECM table)
1246
+                    print '<td align="center">';
1247
+                    if ($relativedir && $filearray[$key]['rowid'] > 0)
1248
+                    {
1249
+                        if ($editline)
1250
+                        {
1251
+                            print $langs->trans("FileSharedViaALink").' ';
1252
+                            print '<input class="inline-block" type="checkbox" name="shareenabled"'.($file['share']?' checked="checked"':'').' /> ';
1253
+                        }
1254
+                        else
1255
+                        {
1256
+                            if ($file['share'])
1257
+                            {
1258
+                                // Define $urlwithroot
1259
+                                $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
1260
+                                $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
1261
+                                //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
1262
+
1263
+                                //print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
1264
+                                $forcedownload=0;
1265
+                                $paramlink='';
1266
+                                if (! empty($file['share'])) $paramlink.=($paramlink?'&':'').'hashp='.$file['share'];			// Hash for public share
1267
+                                if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
1268
+
1269
+                                $fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
1270
+
1271
+                                print img_picto($langs->trans("FileSharedViaALink"),'object_globe.png').' ';
1272
+                                print '<input type="text" class="quatrevingtpercent" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
1273
+                            }
1274
+                            else
1275
+                            {
1276
+                                //print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
1277
+                            }
1278
+                        }
1279
+                    }
1280
+                    print '</td>';
1281
+
1282
+                    // Actions buttons
1283
+                    if (! $editline)
1284
+                    {
1285
+                        // Delete or view link
1286
+                        // ($param must start with &)
1287
+                        print '<td class="valignmiddle right actionbuttons"><!-- action on files -->';
1288
+                        if ($useinecm == 1)
1289
+                        {
1290
+                            print '<a href="'.DOL_URL_ROOT.'/ecm/file_card.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
1291
+                        }
1292
+                        if (! $useinecm || $useinecm == 2)
1293
+                        {
1294
+                            $newmodulepart=$modulepart;
1295
+                            if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1296
+
1297
+                            if (! $disablecrop && image_format_supported($file['name']) > 0)
1298
+                            {
1299
+                                if ($permtoeditline)
1300
+                                {
1301
+                                        // Link to resize
1302
+                                            print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("ResizeOrCrop")).'">'.img_picto($langs->trans("ResizeOrCrop"),'resize','class="paddingrightonly"').'</a>';
1303
+                                }
1304
+                            }
1305
+
1306
+                            if ($permtoeditline)
1307
+                            {
1308
+                                $paramsectiondir=(in_array($modulepart, array('medias','ecm'))?'&section_dir='.urlencode($relativepath):'');
1309
+                                print '<a href="'.(($useinecm == 1)?'#':($url.'?action=editfile&urlfile='.urlencode($filepath).$paramsectiondir.$param)).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1310
+                            }
1311
+                        }
1312
+                        if ($permonobject)
1313
+                        {
1314
+                            $useajax=1;
1315
+                            if (! empty($conf->dol_use_jmobile)) $useajax=0;
1316
+                            if (empty($conf->use_javascript_ajax)) $useajax=0;
1317
+                            if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1318
+                            print '<a href="'.(($useinecm && $useajax)?'#':($url.'?action=delete&urlfile='.urlencode($filepath).$param)).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1319
+                        }
1320
+                        print "</td>";
1321
+
1322
+                        if (empty($disablemove))
1323
+                        {
1324
+                            if ($nboffiles > 1 && $conf->browser->layout != 'phone') {
1325
+                                print '<td align="center" class="linecolmove tdlineupdown">';
1326
+                                if ($i > 0) {
1327
+                                    print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1328
+                                }
1329
+                                if ($i < $nboffiles-1) {
1330
+                                    print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1331
+                                }
1332
+                                print '</td>';
1333
+                            }
1334
+                            else {
1335
+                                    print '<td align="center"'.(($conf->browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1336
+                                    print '</td>';
1337
+                            }
1338
+                        }
1339
+                    }
1340
+                    else
1341
+                    {
1342
+                        print '<td class="right">';
1343
+                        print '<input type="hidden" name="ecmfileid" value="'.$filearray[$key]['rowid'].'">';
1344
+                        print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1345
+                        print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1346
+                        print '</td>';
1347
+                        if (empty($disablemove)) print '<td class="right"></td>';
1348
+                    }
1349
+                    print "</tr>\n";
1350
+
1351
+                    $i++;
1352
+                }
1353
+            }
1354
+            if ($nboffiles == 0)
1355
+            {
1356
+                $colspan=(empty($useinecm)?'6':'6');
1357
+                if (empty($disablemove)) $colspan++;		// 6 columns or 7
1358
+                print '<tr class="oddeven"><td colspan="'.$colspan.'" class="opacitymedium">';
1359
+                if (empty($textifempty)) print $langs->trans("NoFileFound");
1360
+                else print $textifempty;
1361
+                print '</td></tr>';
1362
+            }
1363
+            print "</table>";
1364
+            print '</div>';
1365
+
1366
+            if ($nboflines > 1 && is_object($object)) {
1367
+                if (! empty($conf->use_javascript_ajax) && $permtoeditline) {
1368
+                    $table_element_line = 'ecm_files';
1369
+                    include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1370
+                }
1371
+            }
1372
+
1373
+            print ajax_autoselect('downloadlink');
1374
+
1375
+            if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1376
+            {
1377
+                print '</form>';
1378
+            }
1379
+
1380
+            return $nboffiles;
1381
+        }
1382
+    }
1383 1383
 
1384 1384
 
1385 1385
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1386
-	/**
1387
-	 *	Show list of documents in a directory
1388
-	 *
1389
-	 *  @param	string	$upload_dir         Directory that was scanned
1390
-	 *  @param  array	$filearray          Array of files loaded by dol_dir_list function before calling this function
1391
-	 *  @param  string	$modulepart         Value for modulepart used by download wrapper
1392
-	 *  @param  string	$param              Parameters on sort links
1393
-	 *  @param  int		$forcedownload      Force to open dialog box "Save As" when clicking on file
1394
-	 *  @param  string	$relativepath       Relative path of docs (autodefined if not provided)
1395
-	 *  @param  int		$permtodelete       Permission to delete
1396
-	 *  @param  int		$useinecm           Change output for use in ecm module
1397
-	 *  @param  int		$textifempty        Text to show if filearray is empty
1398
-	 *  @param  int		$maxlength          Maximum length of file name shown
1399
-	 *  @param	string 	$url				Full url to use for click links ('' = autodetect)
1400
-	 *  @param	int		$addfilterfields	Add line with filters
1401
-	 *  @return int                 		<0 if KO, nb of files shown if OK
1402
-	 *  @see list_of_documents
1403
-	 */
1404
-	function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload=0, $relativepath='', $permtodelete=1, $useinecm=0, $textifempty='', $maxlength=0, $url='', $addfilterfields=0)
1405
-	{
1386
+    /**
1387
+     *	Show list of documents in a directory
1388
+     *
1389
+     *  @param	string	$upload_dir         Directory that was scanned
1390
+     *  @param  array	$filearray          Array of files loaded by dol_dir_list function before calling this function
1391
+     *  @param  string	$modulepart         Value for modulepart used by download wrapper
1392
+     *  @param  string	$param              Parameters on sort links
1393
+     *  @param  int		$forcedownload      Force to open dialog box "Save As" when clicking on file
1394
+     *  @param  string	$relativepath       Relative path of docs (autodefined if not provided)
1395
+     *  @param  int		$permtodelete       Permission to delete
1396
+     *  @param  int		$useinecm           Change output for use in ecm module
1397
+     *  @param  int		$textifempty        Text to show if filearray is empty
1398
+     *  @param  int		$maxlength          Maximum length of file name shown
1399
+     *  @param	string 	$url				Full url to use for click links ('' = autodetect)
1400
+     *  @param	int		$addfilterfields	Add line with filters
1401
+     *  @return int                 		<0 if KO, nb of files shown if OK
1402
+     *  @see list_of_documents
1403
+     */
1404
+    function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload=0, $relativepath='', $permtodelete=1, $useinecm=0, $textifempty='', $maxlength=0, $url='', $addfilterfields=0)
1405
+    {
1406 1406
         // phpcs:enable
1407
-		global $user, $conf, $langs, $form;
1408
-		global $sortfield, $sortorder;
1409
-		global $search_doc_ref;
1410
-
1411
-		dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1412
-
1413
-		// Show list of documents
1414
-		if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1415
-		if (empty($url)) $url=$_SERVER["PHP_SELF"];
1416
-
1417
-		if (! empty($addfilterfields))
1418
-		{
1419
-			print '<form action="'.$_SERVER['PHP_SELF'].'">';
1420
-			print '<input type="hidden" name="module" value="'.$modulepart.'">';
1421
-		}
1422
-
1423
-		print '<div class="div-table-responsive-no-min">';
1424
-		print '<table width="100%" class="noborder">'."\n";
1425
-
1426
-		if (! empty($addfilterfields))
1427
-		{
1428
-			print '<tr class="liste_titre nodrag nodrop">';
1429
-			print '<td></td>';
1430
-			print '<td><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
1431
-			print '<td></td>';
1432
-			print '<td></td>';
1433
-			// Action column
1434
-			print '<td class="liste_titre" align="middle">';
1435
-			$searchpicto=$form->showFilterButtons();
1436
-			print $searchpicto;
1437
-			print '</td>';
1438
-			print "</tr>\n";
1439
-		}
1440
-
1441
-		print '<tr class="liste_titre">';
1442
-		$sortref="fullname";
1443
-		if ($modulepart == 'invoice_supplier') $sortref='level1name';
1444
-		print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1445
-		print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1446
-		print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1447
-		print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1448
-		print_liste_field_titre('','','');
1449
-		print '</tr>'."\n";
1450
-
1451
-		// To show ref or specific information according to view to show (defined by $module)
1452
-		if ($modulepart == 'company')
1453
-		{
1454
-			include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1455
-			$object_instance=new Societe($this->db);
1456
-		}
1457
-		else if ($modulepart == 'invoice')
1458
-		{
1459
-			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1460
-			$object_instance=new Facture($this->db);
1461
-		}
1462
-		else if ($modulepart == 'invoice_supplier')
1463
-		{
1464
-			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1465
-			$object_instance=new FactureFournisseur($this->db);
1466
-		}
1467
-		else if ($modulepart == 'propal')
1468
-		{
1469
-			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1470
-			$object_instance=new Propal($this->db);
1471
-		}
1472
-		else if ($modulepart == 'supplier_proposal')
1473
-		{
1474
-			include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1475
-			$object_instance=new SupplierProposal($this->db);
1476
-		}
1477
-		else if ($modulepart == 'order')
1478
-		{
1479
-			include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1480
-			$object_instance=new Commande($this->db);
1481
-		}
1482
-		else if ($modulepart == 'order_supplier')
1483
-		{
1484
-			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1485
-			$object_instance=new CommandeFournisseur($this->db);
1486
-		}
1487
-		else if ($modulepart == 'contract')
1488
-		{
1489
-			include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1490
-			$object_instance=new Contrat($this->db);
1491
-		}
1492
-		else if ($modulepart == 'product')
1493
-		{
1494
-			include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1495
-			$object_instance=new Product($this->db);
1496
-		}
1497
-		else if ($modulepart == 'tax')
1498
-		{
1499
-			include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1500
-			$object_instance=new ChargeSociales($this->db);
1501
-		}
1502
-		else if ($modulepart == 'project')
1503
-		{
1504
-			include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1505
-			$object_instance=new Project($this->db);
1506
-		}
1507
-		else if ($modulepart == 'fichinter')
1508
-		{
1509
-			include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1510
-			$object_instance=new Fichinter($this->db);
1511
-		}
1512
-		else if ($modulepart == 'user')
1513
-		{
1514
-			include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1515
-			$object_instance=new User($this->db);
1516
-		}
1517
-		else if ($modulepart == 'expensereport')
1518
-		{
1519
-			include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1520
-			$object_instance=new ExpenseReport($this->db);
1521
-		}
1522
-		else if ($modulepart == 'holiday')
1523
-		{
1524
-			include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
1525
-			$object_instance=new Holiday($this->db);
1526
-		}
1527
-
1528
-		foreach($filearray as $key => $file)
1529
-		{
1530
-			if (!is_dir($file['name'])
1531
-			&& $file['name'] != '.'
1532
-			&& $file['name'] != '..'
1533
-			&& $file['name'] != 'CVS'
1534
-			&& ! preg_match('/\.meta$/i',$file['name']))
1535
-			{
1536
-				// Define relative path used to store the file
1537
-				$relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1538
-
1539
-				//var_dump($file);
1540
-				$id=0; $ref=''; $label='';
1541
-
1542
-				// To show ref or specific information according to view to show (defined by $module)
1543
-				if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1544
-				if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1545
-				if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1546
-				if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1547
-				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1548
-				if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1549
-				if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1550
-				if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1551
-				if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1552
-				if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1553
-				if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1554
-				if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1555
-				if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1556
-				if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1557
-				if ($modulepart == 'holiday')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1558
-
1559
-				if (! $id && ! $ref) continue;
1560
-				$found=0;
1561
-				if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1562
-				{
1563
-					$found=1;
1564
-				}
1565
-				else
1566
-				{
1567
-					//print 'Fetch '.$id." - ".$ref.'<br>';
1568
-
1569
-					if ($id) {
1570
-						$result = $object_instance->fetch($id);
1571
-					} else {
1572
-						//fetchOneLike looks for objects with wildcards in its reference.
1573
-						//It is useful for those masks who get underscores instead of their actual symbols
1574
-						//fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned
1575
-						//that's why we look only look fetchOneLike when fetch returns 0
1576
-						if (!$result = $object_instance->fetch('', $ref)) {
1577
-							$result = $object_instance->fetchOneLike($ref);
1578
-						}
1579
-					}
1580
-
1581
-					if ($result > 0) {  // Save object into a cache
1582
-						$found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1583
-					}
1584
-					if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1585
-				}
1586
-
1587
-				if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1588
-
1589
-				print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1590
-				print '<tr class="oddeven">';
1591
-				print '<td>';
1592
-				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1593
-				else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1594
-
1595
-				//$modulesubdir=dol_sanitizeFileName($ref);
1596
-				$modulesubdir=dirname($relativefile);
1597
-
1598
-				//$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1599
-				$filedir=$file['path'];
1600
-				//$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1601
-				//print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1602
-
1603
-				print '</td>';
1604
-
1605
-				// File
1606
-				print '<td>';
1607
-				//print "XX".$file['name']; //$file['name'] must be utf8
1608
-				print '<a href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1609
-				if ($forcedownload) print '&attachment=1';
1610
-				print '&file='.urlencode($relativefile).'">';
1611
-				print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')');
1612
-				print dol_trunc($file['name'],$maxlength,'middle');
1613
-				print '</a>';
1614
-
1615
-				//print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1616
-				print $this->showPreview($file, $modulepart, $file['relativename']);
1617
-
1618
-				print "</td>\n";
1619
-				print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1620
-				print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1621
-				print '<td align="right">';
1622
-				//if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1623
-				//if ($forcedownload) print '&attachment=1';
1624
-				//print '&file='.urlencode($relativefile).'">';
1625
-				//print img_view().'</a> &nbsp; ';
1626
-				//if ($permtodelete) print '<a href="'.$url.'?id='.$object->id.'&section='.$_REQUEST["section"].'&action=delete&urlfile='.urlencode($file['name']).'">'.img_delete().'</a>';
1627
-				//else print '&nbsp;';
1628
-				print "</td></tr>\n";
1629
-			}
1630
-		}
1631
-
1632
-		if (count($filearray) == 0)
1633
-		{
1634
-			print '<tr class="oddeven"><td colspan="5">';
1635
-			if (empty($textifempty)) print $langs->trans("NoFileFound");
1636
-			else print $textifempty;
1637
-			print '</td></tr>';
1638
-		}
1639
-		print "</table>";
1640
-		print '</div>';
1641
-
1642
-		if (! empty($addfilterfields)) print '</form>';
1643
-		// Fin de zone
1644
-	}
1645
-
1646
-	/**
1647
-	 *    Show form to upload a new file with jquery fileupload.
1648
-	 *    This form use the fileupload.php file.
1649
-	 *
1650
-	 *    @param	Object	$object		Object to use
1651
-	 *    @return	void
1652
-	 */
1653
-	private function _formAjaxFileUpload($object)
1654
-	{
1655
-		global $langs, $conf;
1656
-
1657
-		// PHP post_max_size
1658
-		$post_max_size				= ini_get('post_max_size');
1659
-		$mul_post_max_size			= substr($post_max_size, -1);
1660
-		$mul_post_max_size			= ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1)));
1661
-		$post_max_size				= $mul_post_max_size * (int) $post_max_size;
1662
-		// PHP upload_max_filesize
1663
-		$upload_max_filesize		= ini_get('upload_max_filesize');
1664
-		$mul_upload_max_filesize	= substr($upload_max_filesize, -1);
1665
-		$mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1666
-		$upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1667
-		// Max file size
1668
-		$max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1669
-
1670
-		// Include main
1671
-		include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
1672
-
1673
-		// Include template
1674
-		include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php';
1675
-	}
1676
-
1677
-	/**
1678
-	 * Show array with linked files
1679
-	 *
1680
-	 * @param 	Object		$object			Object
1681
-	 * @param 	int			$permtodelete	Deletion is allowed
1682
-	 * @param 	string		$action			Action
1683
-	 * @param 	string		$selected		???
1684
-	 * @param	string		$param			More param to add into URL
1685
-	 * @return 	int							Number of links
1686
-	 */
1687
-	public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1688
-	{
1689
-		global $user, $conf, $langs, $user;
1690
-		global $sortfield, $sortorder;
1691
-
1692
-		$langs->load("link");
1693
-
1694
-		require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1695
-		$link = new Link($this->db);
1696
-		$links = array();
1697
-		if ($sortfield == "name") {
1698
-			$sortfield = "label";
1699
-		} elseif ($sortfield == "date") {
1700
-			$sortfield = "datea";
1701
-		} else {
1702
-			$sortfield = null;
1703
-		}
1704
-		$res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1705
-		$param .= (isset($object->id)?'&id=' . $object->id : '');
1706
-
1707
-		// Show list of associated links
1708
-		print load_fiche_titre($langs->trans("LinkedFiles"));
1709
-
1710
-		print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1711
-
1712
-		print '<table width="100%" class="liste">';
1713
-		print '<tr class="liste_titre">';
1714
-		print_liste_field_titre(
1715
-			$langs->trans("Links"),
1716
-			$_SERVER['PHP_SELF'],
1717
-			"name",
1718
-			"",
1719
-			$param,
1720
-			'align="left"',
1721
-			$sortfield,
1722
-			$sortorder
1723
-		);
1724
-		print_liste_field_titre(
1725
-			"",
1726
-			"",
1727
-			"",
1728
-			"",
1729
-			"",
1730
-			'align="right"'
1731
-		);
1732
-		print_liste_field_titre(
1733
-			$langs->trans("Date"),
1734
-			$_SERVER['PHP_SELF'],
1735
-			"date",
1736
-			"",
1737
-			$param,
1738
-			'align="center"',
1739
-			$sortfield,
1740
-			$sortorder
1741
-		);
1742
-		print_liste_field_titre(
1743
-			'',
1744
-			$_SERVER['PHP_SELF'],
1745
-			"",
1746
-			"",
1747
-			$param,
1748
-			'align="center"'
1749
-		);
1750
-		print_liste_field_titre('','','');
1751
-		print '</tr>';
1752
-		$nboflinks = count($links);
1753
-		if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1754
-
1755
-		foreach ($links as $link)
1756
-		{
1757
-			print '<tr class="oddeven">';
1758
-			//edit mode
1759
-			if ($action == 'update' && $selected === $link->id)
1760
-			{
1761
-				print '<td>';
1762
-				print '<input type="hidden" name="id" value="' . $object->id . '">';
1763
-				print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1764
-				print '<input type="hidden" name="action" value="confirm_updateline">';
1765
-				print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1766
-				print '</td>';
1767
-				print '<td>';
1768
-				print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1769
-				print '</td>';
1770
-				print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1771
-				print '<td align="right"></td>';
1772
-				print '<td align="right">';
1773
-				print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1774
-				print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1775
-				print '</td>';
1776
-			}
1777
-			else
1778
-			{
1779
-				print '<td>';
1780
-				print img_picto('', 'object_globe').' ';
1781
-				print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1782
-				print $link->label;
1783
-				print '</a>';
1784
-				print '</td>'."\n";
1785
-				print '<td align="right"></td>';
1786
-				print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1787
-				print '<td align="center"></td>';
1788
-				print '<td align="right">';
1789
-				print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1790
-				if ($permtodelete) {
1791
-					print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1792
-				} else {
1793
-					print '&nbsp;';
1794
-				}
1795
-				print '</td>';
1796
-			}
1797
-			print "</tr>\n";
1798
-		}
1799
-		if ($nboflinks == 0)
1800
-		{
1801
-			print '<tr class="oddeven"><td colspan="5" class="opacitymedium">';
1802
-			print $langs->trans("NoLinkFound");
1803
-			print '</td></tr>';
1804
-		}
1805
-		print "</table>";
1806
-
1807
-		print '</form>';
1808
-
1809
-		return $nboflinks;
1810
-	}
1811
-
1812
-
1813
-	/**
1814
-	 * Show detail icon with link for preview
1815
-	 *
1816
-	 * @param   array     $file           Array with data of file. Example: array('name'=>...)
1817
-	 * @param   string    $modulepart     propal, facture, facture_fourn, ...
1818
-	 * @param   string    $relativepath   Relative path of docs
1819
-	 * @param   string    $ruleforpicto   Rule for picto: 0=Use the generic preview picto, 1=Use the picto of mime type of file)
1820
-	 * @param	string	  $param		  More param on http links
1821
-	 * @return  string    $out            Output string with HTML
1822
-	 */
1823
-	public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1824
-	{
1825
-		global $langs, $conf;
1826
-
1827
-		$out='';
1828
-		if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1829
-		{
1830
-			$urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1831
-			if (count($urladvancedpreview))
1832
-			{
1833
-				$out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1834
-				//$out.= '<a class="pictopreview">';
1835
-				if (empty($ruleforpicto))
1836
-				{
1837
-					//$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1838
-					$out.='<span class="fa fa-search-plus" style="color: gray"></span>';
1839
-				}
1840
-				else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1841
-				$out.= '</a>';
1842
-			}
1843
-		}
1844
-		return $out;
1845
-	}
1407
+        global $user, $conf, $langs, $form;
1408
+        global $sortfield, $sortorder;
1409
+        global $search_doc_ref;
1410
+
1411
+        dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1412
+
1413
+        // Show list of documents
1414
+        if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1415
+        if (empty($url)) $url=$_SERVER["PHP_SELF"];
1416
+
1417
+        if (! empty($addfilterfields))
1418
+        {
1419
+            print '<form action="'.$_SERVER['PHP_SELF'].'">';
1420
+            print '<input type="hidden" name="module" value="'.$modulepart.'">';
1421
+        }
1422
+
1423
+        print '<div class="div-table-responsive-no-min">';
1424
+        print '<table width="100%" class="noborder">'."\n";
1425
+
1426
+        if (! empty($addfilterfields))
1427
+        {
1428
+            print '<tr class="liste_titre nodrag nodrop">';
1429
+            print '<td></td>';
1430
+            print '<td><input type="text" class="maxwidth100onsmartphone" name="search_doc_ref" value="'.dol_escape_htmltag($search_doc_ref).'"></td>';
1431
+            print '<td></td>';
1432
+            print '<td></td>';
1433
+            // Action column
1434
+            print '<td class="liste_titre" align="middle">';
1435
+            $searchpicto=$form->showFilterButtons();
1436
+            print $searchpicto;
1437
+            print '</td>';
1438
+            print "</tr>\n";
1439
+        }
1440
+
1441
+        print '<tr class="liste_titre">';
1442
+        $sortref="fullname";
1443
+        if ($modulepart == 'invoice_supplier') $sortref='level1name';
1444
+        print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1445
+        print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1446
+        print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1447
+        print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1448
+        print_liste_field_titre('','','');
1449
+        print '</tr>'."\n";
1450
+
1451
+        // To show ref or specific information according to view to show (defined by $module)
1452
+        if ($modulepart == 'company')
1453
+        {
1454
+            include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1455
+            $object_instance=new Societe($this->db);
1456
+        }
1457
+        else if ($modulepart == 'invoice')
1458
+        {
1459
+            include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1460
+            $object_instance=new Facture($this->db);
1461
+        }
1462
+        else if ($modulepart == 'invoice_supplier')
1463
+        {
1464
+            include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1465
+            $object_instance=new FactureFournisseur($this->db);
1466
+        }
1467
+        else if ($modulepart == 'propal')
1468
+        {
1469
+            include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1470
+            $object_instance=new Propal($this->db);
1471
+        }
1472
+        else if ($modulepart == 'supplier_proposal')
1473
+        {
1474
+            include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1475
+            $object_instance=new SupplierProposal($this->db);
1476
+        }
1477
+        else if ($modulepart == 'order')
1478
+        {
1479
+            include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1480
+            $object_instance=new Commande($this->db);
1481
+        }
1482
+        else if ($modulepart == 'order_supplier')
1483
+        {
1484
+            include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1485
+            $object_instance=new CommandeFournisseur($this->db);
1486
+        }
1487
+        else if ($modulepart == 'contract')
1488
+        {
1489
+            include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1490
+            $object_instance=new Contrat($this->db);
1491
+        }
1492
+        else if ($modulepart == 'product')
1493
+        {
1494
+            include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1495
+            $object_instance=new Product($this->db);
1496
+        }
1497
+        else if ($modulepart == 'tax')
1498
+        {
1499
+            include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1500
+            $object_instance=new ChargeSociales($this->db);
1501
+        }
1502
+        else if ($modulepart == 'project')
1503
+        {
1504
+            include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1505
+            $object_instance=new Project($this->db);
1506
+        }
1507
+        else if ($modulepart == 'fichinter')
1508
+        {
1509
+            include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1510
+            $object_instance=new Fichinter($this->db);
1511
+        }
1512
+        else if ($modulepart == 'user')
1513
+        {
1514
+            include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1515
+            $object_instance=new User($this->db);
1516
+        }
1517
+        else if ($modulepart == 'expensereport')
1518
+        {
1519
+            include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1520
+            $object_instance=new ExpenseReport($this->db);
1521
+        }
1522
+        else if ($modulepart == 'holiday')
1523
+        {
1524
+            include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
1525
+            $object_instance=new Holiday($this->db);
1526
+        }
1527
+
1528
+        foreach($filearray as $key => $file)
1529
+        {
1530
+            if (!is_dir($file['name'])
1531
+            && $file['name'] != '.'
1532
+            && $file['name'] != '..'
1533
+            && $file['name'] != 'CVS'
1534
+            && ! preg_match('/\.meta$/i',$file['name']))
1535
+            {
1536
+                // Define relative path used to store the file
1537
+                $relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1538
+
1539
+                //var_dump($file);
1540
+                $id=0; $ref=''; $label='';
1541
+
1542
+                // To show ref or specific information according to view to show (defined by $module)
1543
+                if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1544
+                if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1545
+                if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1546
+                if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1547
+                if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1548
+                if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1549
+                if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1550
+                if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1551
+                if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1552
+                if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1553
+                if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1554
+                if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1555
+                if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1556
+                if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1557
+                if ($modulepart == 'holiday')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1558
+
1559
+                if (! $id && ! $ref) continue;
1560
+                $found=0;
1561
+                if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1562
+                {
1563
+                    $found=1;
1564
+                }
1565
+                else
1566
+                {
1567
+                    //print 'Fetch '.$id." - ".$ref.'<br>';
1568
+
1569
+                    if ($id) {
1570
+                        $result = $object_instance->fetch($id);
1571
+                    } else {
1572
+                        //fetchOneLike looks for objects with wildcards in its reference.
1573
+                        //It is useful for those masks who get underscores instead of their actual symbols
1574
+                        //fetchOneLike requires some info in the object. If it doesn't have it, then 0 is returned
1575
+                        //that's why we look only look fetchOneLike when fetch returns 0
1576
+                        if (!$result = $object_instance->fetch('', $ref)) {
1577
+                            $result = $object_instance->fetchOneLike($ref);
1578
+                        }
1579
+                    }
1580
+
1581
+                    if ($result > 0) {  // Save object into a cache
1582
+                        $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1583
+                    }
1584
+                    if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1585
+                }
1586
+
1587
+                if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1588
+
1589
+                print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1590
+                print '<tr class="oddeven">';
1591
+                print '<td>';
1592
+                if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1593
+                else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1594
+
1595
+                //$modulesubdir=dol_sanitizeFileName($ref);
1596
+                $modulesubdir=dirname($relativefile);
1597
+
1598
+                //$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1599
+                $filedir=$file['path'];
1600
+                //$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1601
+                //print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1602
+
1603
+                print '</td>';
1604
+
1605
+                // File
1606
+                print '<td>';
1607
+                //print "XX".$file['name']; //$file['name'] must be utf8
1608
+                print '<a href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1609
+                if ($forcedownload) print '&attachment=1';
1610
+                print '&file='.urlencode($relativefile).'">';
1611
+                print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')');
1612
+                print dol_trunc($file['name'],$maxlength,'middle');
1613
+                print '</a>';
1614
+
1615
+                //print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1616
+                print $this->showPreview($file, $modulepart, $file['relativename']);
1617
+
1618
+                print "</td>\n";
1619
+                print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1620
+                print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1621
+                print '<td align="right">';
1622
+                //if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1623
+                //if ($forcedownload) print '&attachment=1';
1624
+                //print '&file='.urlencode($relativefile).'">';
1625
+                //print img_view().'</a> &nbsp; ';
1626
+                //if ($permtodelete) print '<a href="'.$url.'?id='.$object->id.'&section='.$_REQUEST["section"].'&action=delete&urlfile='.urlencode($file['name']).'">'.img_delete().'</a>';
1627
+                //else print '&nbsp;';
1628
+                print "</td></tr>\n";
1629
+            }
1630
+        }
1631
+
1632
+        if (count($filearray) == 0)
1633
+        {
1634
+            print '<tr class="oddeven"><td colspan="5">';
1635
+            if (empty($textifempty)) print $langs->trans("NoFileFound");
1636
+            else print $textifempty;
1637
+            print '</td></tr>';
1638
+        }
1639
+        print "</table>";
1640
+        print '</div>';
1641
+
1642
+        if (! empty($addfilterfields)) print '</form>';
1643
+        // Fin de zone
1644
+    }
1645
+
1646
+    /**
1647
+     *    Show form to upload a new file with jquery fileupload.
1648
+     *    This form use the fileupload.php file.
1649
+     *
1650
+     *    @param	Object	$object		Object to use
1651
+     *    @return	void
1652
+     */
1653
+    private function _formAjaxFileUpload($object)
1654
+    {
1655
+        global $langs, $conf;
1656
+
1657
+        // PHP post_max_size
1658
+        $post_max_size				= ini_get('post_max_size');
1659
+        $mul_post_max_size			= substr($post_max_size, -1);
1660
+        $mul_post_max_size			= ($mul_post_max_size == 'M' ? 1048576 : ($mul_post_max_size == 'K' ? 1024 : ($mul_post_max_size == 'G' ? 1073741824 : 1)));
1661
+        $post_max_size				= $mul_post_max_size * (int) $post_max_size;
1662
+        // PHP upload_max_filesize
1663
+        $upload_max_filesize		= ini_get('upload_max_filesize');
1664
+        $mul_upload_max_filesize	= substr($upload_max_filesize, -1);
1665
+        $mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1666
+        $upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1667
+        // Max file size
1668
+        $max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1669
+
1670
+        // Include main
1671
+        include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
1672
+
1673
+        // Include template
1674
+        include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_view.tpl.php';
1675
+    }
1676
+
1677
+    /**
1678
+     * Show array with linked files
1679
+     *
1680
+     * @param 	Object		$object			Object
1681
+     * @param 	int			$permtodelete	Deletion is allowed
1682
+     * @param 	string		$action			Action
1683
+     * @param 	string		$selected		???
1684
+     * @param	string		$param			More param to add into URL
1685
+     * @return 	int							Number of links
1686
+     */
1687
+    public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1688
+    {
1689
+        global $user, $conf, $langs, $user;
1690
+        global $sortfield, $sortorder;
1691
+
1692
+        $langs->load("link");
1693
+
1694
+        require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1695
+        $link = new Link($this->db);
1696
+        $links = array();
1697
+        if ($sortfield == "name") {
1698
+            $sortfield = "label";
1699
+        } elseif ($sortfield == "date") {
1700
+            $sortfield = "datea";
1701
+        } else {
1702
+            $sortfield = null;
1703
+        }
1704
+        $res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1705
+        $param .= (isset($object->id)?'&id=' . $object->id : '');
1706
+
1707
+        // Show list of associated links
1708
+        print load_fiche_titre($langs->trans("LinkedFiles"));
1709
+
1710
+        print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1711
+
1712
+        print '<table width="100%" class="liste">';
1713
+        print '<tr class="liste_titre">';
1714
+        print_liste_field_titre(
1715
+            $langs->trans("Links"),
1716
+            $_SERVER['PHP_SELF'],
1717
+            "name",
1718
+            "",
1719
+            $param,
1720
+            'align="left"',
1721
+            $sortfield,
1722
+            $sortorder
1723
+        );
1724
+        print_liste_field_titre(
1725
+            "",
1726
+            "",
1727
+            "",
1728
+            "",
1729
+            "",
1730
+            'align="right"'
1731
+        );
1732
+        print_liste_field_titre(
1733
+            $langs->trans("Date"),
1734
+            $_SERVER['PHP_SELF'],
1735
+            "date",
1736
+            "",
1737
+            $param,
1738
+            'align="center"',
1739
+            $sortfield,
1740
+            $sortorder
1741
+        );
1742
+        print_liste_field_titre(
1743
+            '',
1744
+            $_SERVER['PHP_SELF'],
1745
+            "",
1746
+            "",
1747
+            $param,
1748
+            'align="center"'
1749
+        );
1750
+        print_liste_field_titre('','','');
1751
+        print '</tr>';
1752
+        $nboflinks = count($links);
1753
+        if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1754
+
1755
+        foreach ($links as $link)
1756
+        {
1757
+            print '<tr class="oddeven">';
1758
+            //edit mode
1759
+            if ($action == 'update' && $selected === $link->id)
1760
+            {
1761
+                print '<td>';
1762
+                print '<input type="hidden" name="id" value="' . $object->id . '">';
1763
+                print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1764
+                print '<input type="hidden" name="action" value="confirm_updateline">';
1765
+                print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1766
+                print '</td>';
1767
+                print '<td>';
1768
+                print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1769
+                print '</td>';
1770
+                print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1771
+                print '<td align="right"></td>';
1772
+                print '<td align="right">';
1773
+                print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1774
+                print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1775
+                print '</td>';
1776
+            }
1777
+            else
1778
+            {
1779
+                print '<td>';
1780
+                print img_picto('', 'object_globe').' ';
1781
+                print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1782
+                print $link->label;
1783
+                print '</a>';
1784
+                print '</td>'."\n";
1785
+                print '<td align="right"></td>';
1786
+                print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1787
+                print '<td align="center"></td>';
1788
+                print '<td align="right">';
1789
+                print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1790
+                if ($permtodelete) {
1791
+                    print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1792
+                } else {
1793
+                    print '&nbsp;';
1794
+                }
1795
+                print '</td>';
1796
+            }
1797
+            print "</tr>\n";
1798
+        }
1799
+        if ($nboflinks == 0)
1800
+        {
1801
+            print '<tr class="oddeven"><td colspan="5" class="opacitymedium">';
1802
+            print $langs->trans("NoLinkFound");
1803
+            print '</td></tr>';
1804
+        }
1805
+        print "</table>";
1806
+
1807
+        print '</form>';
1808
+
1809
+        return $nboflinks;
1810
+    }
1811
+
1812
+
1813
+    /**
1814
+     * Show detail icon with link for preview
1815
+     *
1816
+     * @param   array     $file           Array with data of file. Example: array('name'=>...)
1817
+     * @param   string    $modulepart     propal, facture, facture_fourn, ...
1818
+     * @param   string    $relativepath   Relative path of docs
1819
+     * @param   string    $ruleforpicto   Rule for picto: 0=Use the generic preview picto, 1=Use the picto of mime type of file)
1820
+     * @param	string	  $param		  More param on http links
1821
+     * @return  string    $out            Output string with HTML
1822
+     */
1823
+    public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1824
+    {
1825
+        global $langs, $conf;
1826
+
1827
+        $out='';
1828
+        if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1829
+        {
1830
+            $urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1831
+            if (count($urladvancedpreview))
1832
+            {
1833
+                $out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1834
+                //$out.= '<a class="pictopreview">';
1835
+                if (empty($ruleforpicto))
1836
+                {
1837
+                    //$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1838
+                    $out.='<span class="fa fa-search-plus" style="color: gray"></span>';
1839
+                }
1840
+                else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1841
+                $out.= '</a>';
1842
+            }
1843
+        }
1844
+        return $out;
1845
+    }
1846 1846
 }
Please login to merge, or discard this patch.
Spacing   +444 added lines, -444 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 	public $error;
43 43
 
44 44
 	public $numoffiles;
45
-	public $infofiles;			// Used to return informations by function getDocumentsLink
45
+	public $infofiles; // Used to return informations by function getDocumentsLink
46 46
 
47 47
 
48 48
 	/**
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	function __construct($db)
54 54
 	{
55 55
 		$this->db = $db;
56
-		$this->numoffiles=0;
56
+		$this->numoffiles = 0;
57 57
 	}
58 58
 
59 59
 
@@ -77,16 +77,16 @@  discard block
 block discarded – undo
77 77
 	 *	@param	string		$sectiondir		If upload must be done inside a particular directory (is sectiondir defined, sectionid must not be)
78 78
 	 * 	@return	int							<0 if KO, >0 if OK
79 79
 	 */
80
-	function form_attach_new_file($url, $title='', $addcancel=0, $sectionid=0, $perm=1, $size=50, $object='', $options='', $useajax=1, $savingdocmask='', $linkfiles=1, $htmlname='formuserfile', $accept='', $sectiondir='')
80
+	function form_attach_new_file($url, $title = '', $addcancel = 0, $sectionid = 0, $perm = 1, $size = 50, $object = '', $options = '', $useajax = 1, $savingdocmask = '', $linkfiles = 1, $htmlname = 'formuserfile', $accept = '', $sectiondir = '')
81 81
 	{
82 82
         // phpcs:enable
83
-		global $conf,$langs, $hookmanager;
83
+		global $conf, $langs, $hookmanager;
84 84
 		$hookmanager->initHooks(array('formfile'));
85 85
 
86 86
 
87
-		if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
87
+		if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax = 0;
88 88
 
89
-		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
89
+		if ((!empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax == 2))
90 90
 		{
91 91
 			// TODO: Check this works with 2 forms on same page
92 92
 			// TODO: Check this works with GED module, otherwise, force useajax to 0
@@ -101,12 +101,12 @@  discard block
 block discarded – undo
101 101
 				return 1;
102 102
 			}
103 103
 
104
-			$maxlength=$size;
104
+			$maxlength = $size;
105 105
 
106 106
 			$out = "\n\n<!-- Start form attach new file -->\n";
107 107
 
108
-			if (empty($title)) $title=$langs->trans("AttachANewFile");
109
-			if ($title != 'none') $out.=load_fiche_titre($title, null, null);
108
+			if (empty($title)) $title = $langs->trans("AttachANewFile");
109
+			if ($title != 'none') $out .= load_fiche_titre($title, null, null);
110 110
 
111 111
 			$out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
112 112
 			$out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="'.$sectiondir.'">';
@@ -116,34 +116,34 @@  discard block
 block discarded – undo
116 116
 			$out .= '<table width="100%" class="nobordernopadding">';
117 117
 			$out .= '<tr>';
118 118
 
119
-			if (! empty($options)) $out .= '<td>'.$options.'</td>';
119
+			if (!empty($options)) $out .= '<td>'.$options.'</td>';
120 120
 
121 121
 			$out .= '<td class="valignmiddle nowrap">';
122 122
 
123
-			$max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
124
-			$maxphp=@ini_get('upload_max_filesize');	// En inconnu
125
-			if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
126
-			if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
127
-			if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
128
-			if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
123
+			$max = $conf->global->MAIN_UPLOAD_DOC; // En Kb
124
+			$maxphp = @ini_get('upload_max_filesize'); // En inconnu
125
+			if (preg_match('/k$/i', $maxphp)) $maxphp = $maxphp * 1;
126
+			if (preg_match('/m$/i', $maxphp)) $maxphp = $maxphp * 1024;
127
+			if (preg_match('/g$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024;
128
+			if (preg_match('/t$/i', $maxphp)) $maxphp = $maxphp * 1024 * 1024 * 1024;
129 129
 			// Now $max and $maxphp are in Kb
130 130
 			$maxmin = $max;
131
-			if ($maxphp > 0) $maxmin=min($max,$maxphp);
131
+			if ($maxphp > 0) $maxmin = min($max, $maxphp);
132 132
 
133 133
 			if ($maxmin > 0)
134 134
 			{
135 135
 				// MAX_FILE_SIZE doit précéder le champ input de type file
136
-				$out .= '<input type="hidden" name="max_file_size" value="'.($maxmin*1024).'">';
136
+				$out .= '<input type="hidden" name="max_file_size" value="'.($maxmin * 1024).'">';
137 137
 			}
138 138
 
139 139
 			$out .= '<input class="flat minwidth400" type="file"';
140
-			$out .= ((! empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic')?' name="userfile"':' name="userfile[]" multiple');
141
-			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
142
-			$out .= (!empty($accept)?' accept="'.$accept.'"':' accept=""');
140
+			$out .= ((!empty($conf->global->MAIN_DISABLE_MULTIPLE_FILEUPLOAD) || $conf->browser->layout != 'classic') ? ' name="userfile"' : ' name="userfile[]" multiple');
141
+			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
142
+			$out .= (!empty($accept) ? ' accept="'.$accept.'"' : ' accept=""');
143 143
 			$out .= '>';
144 144
 			$out .= ' ';
145 145
 			$out .= '<input type="submit" class="button" name="sendit" value="'.$langs->trans("Upload").'"';
146
-			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
146
+			$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
147 147
 			$out .= '>';
148 148
 
149 149
 			if ($addcancel)
@@ -152,13 +152,13 @@  discard block
 block discarded – undo
152 152
 				$out .= '<input type="submit" class="button" name="cancel" value="'.$langs->trans("Cancel").'">';
153 153
 			}
154 154
 
155
-			if (! empty($conf->global->MAIN_UPLOAD_DOC))
155
+			if (!empty($conf->global->MAIN_UPLOAD_DOC))
156 156
 			{
157 157
 				if ($perm)
158 158
 				{
159 159
 					$langs->load('other');
160 160
 					$out .= ' ';
161
-					$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
161
+					$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup", $max, $maxphp), 1);
162 162
 				}
163 163
 			}
164 164
 			else
@@ -170,9 +170,9 @@  discard block
 block discarded – undo
170 170
 			if ($savingdocmask)
171 171
 			{
172 172
 				$out .= '<tr>';
173
-   				if (! empty($options)) $out .= '<td>'.$options.'</td>';
173
+   				if (!empty($options)) $out .= '<td>'.$options.'</td>';
174 174
 				$out .= '<td valign="middle" class="nowrap">';
175
-				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
175
+				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/', $langs->transnoentitiesnoconv("OriginFileName"), $savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
176 176
 				$out .= '</td>';
177 177
 				$out .= '</tr>';
178 178
 			}
@@ -197,18 +197,18 @@  discard block
 block discarded – undo
197 197
 
198 198
 				$out .= '<div class="valignmiddle" >';
199 199
 				$out .= '<div class="inline-block" style="padding-right: 10px;">';
200
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
200
+				if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink").':</label> ';
201 201
 				$out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
202 202
 				$out .= '</div>';
203 203
 				$out .= '<div class="inline-block" style="padding-right: 10px;">';
204
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
204
+				if (!empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label").':</label> ';
205 205
 				$out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
206
-				$out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
207
-				$out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
206
+				$out .= '<input type="hidden" name="objecttype" value="'.$object->element.'">';
207
+				$out .= '<input type="hidden" name="objectid" value="'.$object->id.'">';
208 208
 				$out .= '</div>';
209 209
 				$out .= '<div class="inline-block" style="padding-right: 10px;">';
210 210
 				$out .= '<input type="submit" class="button" name="linkit" value="'.$langs->trans("ToLink").'"';
211
-				$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm)?' disabled':'');
211
+				$out .= (empty($conf->global->MAIN_UPLOAD_DOC) || empty($perm) ? ' disabled' : '');
212 212
 				$out .= '>';
213 213
 				$out .= '</div>';
214 214
 				$out .= '</div>';
@@ -218,8 +218,8 @@  discard block
 block discarded – undo
218 218
 				$out .= "\n<!-- End form link new url -->\n";
219 219
 			}
220 220
 
221
-			$parameters = array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''), 'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''), 'url'=>$url, 'perm'=>$perm);
222
-			$res = $hookmanager->executeHooks('formattachOptions',$parameters,$object);
221
+			$parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'url'=>$url, 'perm'=>$perm);
222
+			$res = $hookmanager->executeHooks('formattachOptions', $parameters, $object);
223 223
 			if (empty($res))
224 224
 			{
225 225
 				print '<div class="attacharea attacharea'.$htmlname.'">';
@@ -255,11 +255,11 @@  discard block
 block discarded – undo
255 255
 	 * 		@return		int										<0 if KO, number of shown files if OK
256 256
 	 *      @deprecated                                         Use print xxx->showdocuments() instead.
257 257
 	 */
258
-	function show_documents($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='')
258
+	function show_documents($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '')
259 259
 	{
260 260
         // phpcs:enable
261
-		$this->numoffiles=0;
262
-		print $this->showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed,$modelselected,$allowgenifempty,$forcenomultilang,$iconPDF,$notused,$noform,$param,$title,$buttonlabel,$codelang);
261
+		$this->numoffiles = 0;
262
+		print $this->showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed, $modelselected, $allowgenifempty, $forcenomultilang, $iconPDF, $notused, $noform, $param, $title, $buttonlabel, $codelang);
263 263
 		return $this->numoffiles;
264 264
 	}
265 265
 
@@ -288,58 +288,58 @@  discard block
 block discarded – undo
288 288
 	 *      @param		int					$hideifempty		Hide section of generated files if there is no file
289 289
 	 * 		@return		string              					Output string with HTML array of documents (might be empty string)
290 290
 	 */
291
-	function showdocuments($modulepart,$modulesubdir,$filedir,$urlsource,$genallowed,$delallowed=0,$modelselected='',$allowgenifempty=1,$forcenomultilang=0,$iconPDF=0,$notused=0,$noform=0,$param='',$title='',$buttonlabel='',$codelang='',$morepicto='',$object=null,$hideifempty=0)
291
+	function showdocuments($modulepart, $modulesubdir, $filedir, $urlsource, $genallowed, $delallowed = 0, $modelselected = '', $allowgenifempty = 1, $forcenomultilang = 0, $iconPDF = 0, $notused = 0, $noform = 0, $param = '', $title = '', $buttonlabel = '', $codelang = '', $morepicto = '', $object = null, $hideifempty = 0)
292 292
 	{
293 293
 		// Deprecation warning
294
-		if (! empty($iconPDF)) {
295
-			dol_syslog(__METHOD__ . ": passing iconPDF parameter is deprecated", LOG_WARNING);
294
+		if (!empty($iconPDF)) {
295
+			dol_syslog(__METHOD__.": passing iconPDF parameter is deprecated", LOG_WARNING);
296 296
 		}
297 297
 
298 298
 		global $langs, $conf, $user, $hookmanager;
299 299
 		global $form;
300 300
 
301
-		if (! is_object($form)) $form=new Form($this->db);
301
+		if (!is_object($form)) $form = new Form($this->db);
302 302
 
303 303
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
304 304
 
305 305
 		// For backward compatibility
306
-		if (! empty($iconPDF)) {
306
+		if (!empty($iconPDF)) {
307 307
 			return $this->getDocumentsLink($modulepart, $modulesubdir, $filedir);
308 308
 		}
309 309
 
310 310
 		// Add entity in $param
311
-		$param.= 'entity='.(!empty($object->entity)?$object->entity:$conf->entity);
311
+		$param .= 'entity='.(!empty($object->entity) ? $object->entity : $conf->entity);
312 312
 
313
-		$printer=0;
314
-		if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport','livraison')))	// The direct print feature is implemented only for such elements
313
+		$printer = 0;
314
+		if (in_array($modulepart, array('facture', 'supplier_proposal', 'propal', 'proposal', 'order', 'commande', 'expedition', 'commande_fournisseur', 'expensereport', 'livraison')))	// The direct print feature is implemented only for such elements
315 315
 		{
316
-			$printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
316
+			$printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled)) ?true:false;
317 317
 		}
318 318
 
319 319
 		$hookmanager->initHooks(array('formfile'));
320 320
 
321 321
 		// Get list of files
322
-		$file_list=null;
323
-		if (! empty($filedir))
322
+		$file_list = null;
323
+		if (!empty($filedir))
324 324
 		{
325
-			$file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
325
+			$file_list = dol_dir_list($filedir, 'files', 0, '', '(\.meta|_preview.*.*\.png)$', 'date', SORT_DESC);
326 326
 		}
327 327
 		if ($hideifempty && empty($file_list)) return '';
328 328
 
329
-		$out='';
330
-		$forname='builddoc';
331
-		$headershown=0;
332
-		$showempty=0;
333
-		$i=0;
329
+		$out = '';
330
+		$forname = 'builddoc';
331
+		$headershown = 0;
332
+		$showempty = 0;
333
+		$i = 0;
334 334
 
335
-		$out.= "\n".'<!-- Start show_document -->'."\n";
335
+		$out .= "\n".'<!-- Start show_document -->'."\n";
336 336
 		//print 'filedir='.$filedir;
337 337
 
338 338
 		if (preg_match('/massfilesarea_/', $modulepart))
339 339
 		{
340
-			$out.='<div id="show_files"><br></div>'."\n";
341
-			$title=$langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
342
-			$title.='<script type="text/javascript" language="javascript">
340
+			$out .= '<div id="show_files"><br></div>'."\n";
341
+			$title = $langs->trans("MassFilesArea").' <a href="" id="togglemassfilesarea" ref="shown">('.$langs->trans("Hide").')</a>';
342
+			$title .= '<script type="text/javascript" language="javascript">
343 343
 				jQuery(document).ready(function() {
344 344
 					jQuery(\'#togglemassfilesarea\').click(function() {
345 345
 						if (jQuery(\'#togglemassfilesarea\').attr(\'ref\') == "shown")
@@ -360,63 +360,63 @@  discard block
 block discarded – undo
360 360
 				</script>';
361 361
 		}
362 362
 
363
-		$titletoshow=$langs->trans("Documents");
364
-		if (! empty($title)) $titletoshow=$title;
363
+		$titletoshow = $langs->trans("Documents");
364
+		if (!empty($title)) $titletoshow = $title;
365 365
 
366 366
 		// Show table
367 367
 		if ($genallowed)
368 368
 		{
369
-			$modellist=array();
369
+			$modellist = array();
370 370
 
371 371
 			if ($modulepart == 'company')
372 372
 			{
373
-				$showempty=1;
374
-				if (is_array($genallowed)) $modellist=$genallowed;
373
+				$showempty = 1;
374
+				if (is_array($genallowed)) $modellist = $genallowed;
375 375
 				else
376 376
 				{
377 377
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
378
-					$modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
378
+					$modellist = ModeleThirdPartyDoc::liste_modeles($this->db);
379 379
 				}
380 380
 			}
381 381
 			else if ($modulepart == 'propal')
382 382
 			{
383
-				if (is_array($genallowed)) $modellist=$genallowed;
383
+				if (is_array($genallowed)) $modellist = $genallowed;
384 384
 				else
385 385
 				{
386 386
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
387
-					$modellist=ModelePDFPropales::liste_modeles($this->db);
387
+					$modellist = ModelePDFPropales::liste_modeles($this->db);
388 388
 				}
389 389
 			}
390 390
 			else if ($modulepart == 'supplier_proposal')
391 391
 			{
392
-				if (is_array($genallowed)) $modellist=$genallowed;
392
+				if (is_array($genallowed)) $modellist = $genallowed;
393 393
 				else
394 394
 				{
395 395
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
396
-					$modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
396
+					$modellist = ModelePDFSupplierProposal::liste_modeles($this->db);
397 397
 				}
398 398
 			}
399 399
 			else if ($modulepart == 'commande')
400 400
 			{
401
-				if (is_array($genallowed)) $modellist=$genallowed;
401
+				if (is_array($genallowed)) $modellist = $genallowed;
402 402
 				else
403 403
 				{
404 404
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
405
-					$modellist=ModelePDFCommandes::liste_modeles($this->db);
405
+					$modellist = ModelePDFCommandes::liste_modeles($this->db);
406 406
 				}
407 407
 			}
408 408
 			elseif ($modulepart == 'expedition')
409 409
 			{
410
-				if (is_array($genallowed)) $modellist=$genallowed;
410
+				if (is_array($genallowed)) $modellist = $genallowed;
411 411
 				else
412 412
 				{
413 413
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
414
-					$modellist=ModelePDFExpedition::liste_modeles($this->db);
414
+					$modellist = ModelePDFExpedition::liste_modeles($this->db);
415 415
 				}
416 416
 			}
417 417
             elseif ($modulepart == 'reception')
418 418
             {
419
-                if (is_array($genallowed)) $modellist=$genallowed;
419
+                if (is_array($genallowed)) $modellist = $genallowed;
420 420
                 else
421 421
                 {
422 422
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
@@ -425,407 +425,407 @@  discard block
 block discarded – undo
425 425
             }
426 426
 			elseif ($modulepart == 'livraison')
427 427
 			{
428
-				if (is_array($genallowed)) $modellist=$genallowed;
428
+				if (is_array($genallowed)) $modellist = $genallowed;
429 429
 				else
430 430
 				{
431 431
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
432
-					$modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
432
+					$modellist = ModelePDFDeliveryOrder::liste_modeles($this->db);
433 433
 				}
434 434
 			}
435 435
 			else if ($modulepart == 'ficheinter')
436 436
 			{
437
-				if (is_array($genallowed)) $modellist=$genallowed;
437
+				if (is_array($genallowed)) $modellist = $genallowed;
438 438
 				else
439 439
 				{
440 440
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
441
-					$modellist=ModelePDFFicheinter::liste_modeles($this->db);
441
+					$modellist = ModelePDFFicheinter::liste_modeles($this->db);
442 442
 				}
443 443
 			}
444 444
 			elseif ($modulepart == 'facture')
445 445
 			{
446
-				if (is_array($genallowed)) $modellist=$genallowed;
446
+				if (is_array($genallowed)) $modellist = $genallowed;
447 447
 				else
448 448
 				{
449 449
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
450
-					$modellist=ModelePDFFactures::liste_modeles($this->db);
450
+					$modellist = ModelePDFFactures::liste_modeles($this->db);
451 451
 				}
452 452
 			}
453 453
 			elseif ($modulepart == 'contract')
454 454
 			{
455
-				if (is_array($genallowed)) $modellist=$genallowed;
455
+				if (is_array($genallowed)) $modellist = $genallowed;
456 456
 				else
457 457
 				{
458 458
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
459
-					$modellist=ModelePDFContract::liste_modeles($this->db);
459
+					$modellist = ModelePDFContract::liste_modeles($this->db);
460 460
 				}
461 461
 			}
462 462
 			elseif ($modulepart == 'project')
463 463
 			{
464
-				if (is_array($genallowed)) $modellist=$genallowed;
464
+				if (is_array($genallowed)) $modellist = $genallowed;
465 465
 				else
466 466
 				{
467 467
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
468
-					$modellist=ModelePDFProjects::liste_modeles($this->db);
468
+					$modellist = ModelePDFProjects::liste_modeles($this->db);
469 469
 				}
470 470
 			}
471 471
 			elseif ($modulepart == 'project_task')
472 472
 			{
473
-				if (is_array($genallowed)) $modellist=$genallowed;
473
+				if (is_array($genallowed)) $modellist = $genallowed;
474 474
 				else
475 475
 				{
476 476
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
477
-					$modellist=ModelePDFTask::liste_modeles($this->db);
477
+					$modellist = ModelePDFTask::liste_modeles($this->db);
478 478
 				}
479 479
 			}
480 480
 			elseif ($modulepart == 'product')
481 481
 			{
482
-				if (is_array($genallowed)) $modellist=$genallowed;
482
+				if (is_array($genallowed)) $modellist = $genallowed;
483 483
 				else
484 484
 				{
485 485
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
486
-					$modellist=ModelePDFProduct::liste_modeles($this->db);
486
+					$modellist = ModelePDFProduct::liste_modeles($this->db);
487 487
 				}
488 488
 			}
489 489
 			elseif ($modulepart == 'product_batch')
490 490
 			{
491
-				if (is_array($genallowed)) $modellist=$genallowed;
491
+				if (is_array($genallowed)) $modellist = $genallowed;
492 492
 				else
493 493
 				{
494 494
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php';
495
-					$modellist=ModelePDFProductBatch::liste_modeles($this->db);
495
+					$modellist = ModelePDFProductBatch::liste_modeles($this->db);
496 496
 				}
497 497
 			}
498 498
 			elseif ($modulepart == 'stock')
499 499
 			{
500
-				if (is_array($genallowed)) $modellist=$genallowed;
500
+				if (is_array($genallowed)) $modellist = $genallowed;
501 501
 				else
502 502
 				{
503 503
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php';
504
-					$modellist=ModelePDFStock::liste_modeles($this->db);
504
+					$modellist = ModelePDFStock::liste_modeles($this->db);
505 505
 				}
506 506
 			}
507 507
 			elseif ($modulepart == 'movement')
508 508
 			{
509
-				if (is_array($genallowed)) $modellist=$genallowed;
509
+				if (is_array($genallowed)) $modellist = $genallowed;
510 510
 				else
511 511
 				{
512 512
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php';
513
-					$modellist=ModelePDFMovement::liste_modeles($this->db);
513
+					$modellist = ModelePDFMovement::liste_modeles($this->db);
514 514
 				}
515 515
 			}
516 516
 			elseif ($modulepart == 'export')
517 517
 			{
518
-				if (is_array($genallowed)) $modellist=$genallowed;
518
+				if (is_array($genallowed)) $modellist = $genallowed;
519 519
 				else
520 520
 				{
521 521
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
522
-					$modellist=ModeleExports::liste_modeles($this->db);
522
+					$modellist = ModeleExports::liste_modeles($this->db);
523 523
 				}
524 524
 			}
525 525
 			else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
526 526
 			{
527
-				if (is_array($genallowed)) $modellist=$genallowed;
527
+				if (is_array($genallowed)) $modellist = $genallowed;
528 528
 				else
529 529
 				{
530 530
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
531
-					$modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
531
+					$modellist = ModelePDFSuppliersOrders::liste_modeles($this->db);
532 532
 				}
533 533
 			}
534 534
 			else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
535 535
 			{
536
-				if (is_array($genallowed)) $modellist=$genallowed;
536
+				if (is_array($genallowed)) $modellist = $genallowed;
537 537
 				else
538 538
 				{
539 539
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
540
-					$modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
540
+					$modellist = ModelePDFSuppliersInvoices::liste_modeles($this->db);
541 541
 				}
542 542
 			}
543 543
 			else if ($modulepart == 'supplier_payment')
544 544
 			{
545
-				if (is_array($genallowed)) $modellist=$genallowed;
545
+				if (is_array($genallowed)) $modellist = $genallowed;
546 546
 				else
547 547
 				{
548 548
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
549
-					$modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
549
+					$modellist = ModelePDFSuppliersPayments::liste_modeles($this->db);
550 550
 				}
551 551
 			}
552 552
 			else if ($modulepart == 'remisecheque')
553 553
 			{
554
-				if (is_array($genallowed)) $modellist=$genallowed;
554
+				if (is_array($genallowed)) $modellist = $genallowed;
555 555
 				else
556 556
 				{
557 557
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
558
-					$modellist=ModeleChequeReceipts::liste_modeles($this->db);
558
+					$modellist = ModeleChequeReceipts::liste_modeles($this->db);
559 559
 				}
560 560
 			}
561 561
 			elseif ($modulepart == 'donation')
562 562
 			{
563
-				if (is_array($genallowed)) $modellist=$genallowed;
563
+				if (is_array($genallowed)) $modellist = $genallowed;
564 564
 				else
565 565
 				{
566 566
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
567
-					$modellist=ModeleDon::liste_modeles($this->db);
567
+					$modellist = ModeleDon::liste_modeles($this->db);
568 568
 				}
569 569
 			}
570 570
 			elseif ($modulepart == 'member')
571 571
 			{
572
-				if (is_array($genallowed)) $modellist=$genallowed;
572
+				if (is_array($genallowed)) $modellist = $genallowed;
573 573
 				else
574 574
 				{
575 575
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
576
-					$modellist=ModelePDFCards::liste_modeles($this->db);
576
+					$modellist = ModelePDFCards::liste_modeles($this->db);
577 577
 				}
578 578
 			}
579 579
 			elseif ($modulepart == 'agenda' || $modulepart == 'actions')
580 580
 			{
581
-				if (is_array($genallowed)) $modellist=$genallowed;
581
+				if (is_array($genallowed)) $modellist = $genallowed;
582 582
 				else
583 583
 				{
584 584
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
585
-					$modellist=ModeleAction::liste_modeles($this->db);
585
+					$modellist = ModeleAction::liste_modeles($this->db);
586 586
 				}
587 587
 			}
588 588
 			else if ($modulepart == 'expensereport')
589 589
 			{
590
-				if (is_array($genallowed)) $modellist=$genallowed;
590
+				if (is_array($genallowed)) $modellist = $genallowed;
591 591
 				else
592 592
 				{
593 593
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
594
-					$modellist=ModeleExpenseReport::liste_modeles($this->db);
594
+					$modellist = ModeleExpenseReport::liste_modeles($this->db);
595 595
 				}
596 596
 			}
597 597
 			else if ($modulepart == 'unpaid')
598 598
 			{
599
-				$modellist='';
599
+				$modellist = '';
600 600
 			}
601 601
 			elseif ($modulepart == 'user')
602 602
 			{
603
-				if (is_array($genallowed)) $modellist=$genallowed;
603
+				if (is_array($genallowed)) $modellist = $genallowed;
604 604
 				else
605 605
 				{
606 606
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
607
-					$modellist=ModelePDFUser::liste_modeles($this->db);
607
+					$modellist = ModelePDFUser::liste_modeles($this->db);
608 608
 				}
609 609
 			}
610 610
 			elseif ($modulepart == 'usergroup')
611 611
 			{
612
-				if (is_array($genallowed)) $modellist=$genallowed;
612
+				if (is_array($genallowed)) $modellist = $genallowed;
613 613
 				else
614 614
 				{
615 615
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
616
-					$modellist=ModelePDFUserGroup::liste_modeles($this->db);
616
+					$modellist = ModelePDFUserGroup::liste_modeles($this->db);
617 617
 				}
618 618
 			}
619 619
 			else
620 620
 			{
621 621
 				// For normalized standard modules
622
-				$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
622
+				$file = dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php', 0);
623 623
 				if (file_exists($file))
624 624
 				{
625
-					$res=include_once $file;
625
+					$res = include_once $file;
626 626
 				}
627 627
 				// For normalized external modules
628 628
 				else
629 629
 				{
630
-					$file=dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
631
-					$res=include_once $file;
630
+					$file = dol_buildpath('/'.$modulepart.'/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php', 0);
631
+					$res = include_once $file;
632 632
 				}
633
-				$class='ModelePDF'.ucfirst($modulepart);
633
+				$class = 'ModelePDF'.ucfirst($modulepart);
634 634
 				if (class_exists($class))
635 635
 				{
636
-					$modellist=call_user_func($class.'::liste_modeles',$this->db);
636
+					$modellist = call_user_func($class.'::liste_modeles', $this->db);
637 637
 				}
638 638
 				else
639 639
 				{
640
-					dol_print_error($this->db,'Bad value for modulepart');
640
+					dol_print_error($this->db, 'Bad value for modulepart');
641 641
 					return -1;
642 642
 				}
643 643
 			}
644 644
 
645 645
 			// Set headershown to avoid to have table opened a second time later
646
-			$headershown=1;
646
+			$headershown = 1;
647 647
 
648
-			$buttonlabeltoshow=$buttonlabel;
649
-			if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
648
+			$buttonlabeltoshow = $buttonlabel;
649
+			if (empty($buttonlabel)) $buttonlabel = $langs->trans('Generate');
650 650
 
651
-			if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
652
-			if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
653
-			$out.= '<input type="hidden" name="action" value="builddoc">';
654
-			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
651
+			if ($conf->browser->layout == 'phone') $urlsource .= '#'.$forname.'_form'; // So we switch to form after a generation
652
+			if (empty($noform)) $out .= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG) ? '' : '#builddoc').'" id="'.$forname.'_form" method="post">';
653
+			$out .= '<input type="hidden" name="action" value="builddoc">';
654
+			$out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
655 655
 
656
-			$out.= load_fiche_titre($titletoshow, '', '');
657
-			$out.= '<div class="div-table-responsive-no-min">';
658
-			$out.= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
656
+			$out .= load_fiche_titre($titletoshow, '', '');
657
+			$out .= '<div class="div-table-responsive-no-min">';
658
+			$out .= '<table class="liste formdoc noborder" summary="listofdocumentstable" width="100%">';
659 659
 
660
-			$out.= '<tr class="liste_titre">';
660
+			$out .= '<tr class="liste_titre">';
661 661
 
662
-			$addcolumforpicto=($delallowed || $printer || $morepicto);
663
-			$out.= '<th align="center" colspan="'.(3+($addcolumforpicto?1:0)).'" class="formdoc liste_titre maxwidthonsmartphone">';
662
+			$addcolumforpicto = ($delallowed || $printer || $morepicto);
663
+			$out .= '<th align="center" colspan="'.(3 + ($addcolumforpicto ? 1 : 0)).'" class="formdoc liste_titre maxwidthonsmartphone">';
664 664
 
665 665
 			// Model
666
-			if (! empty($modellist))
666
+			if (!empty($modellist))
667 667
 			{
668
-				$out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
668
+				$out .= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
669 669
 				if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
670 670
 				{
671
-					$arraykeys=array_keys($modellist);
672
-					$modelselected=$arraykeys[0];
671
+					$arraykeys = array_keys($modellist);
672
+					$modelselected = $arraykeys[0];
673 673
 				}
674
-				$out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
674
+				$out .= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
675 675
 				if ($conf->use_javascript_ajax)
676 676
 				{
677
-					$out.= ajax_combobox('model');
677
+					$out .= ajax_combobox('model');
678 678
 				}
679 679
 			}
680 680
 			else
681 681
 			{
682
-				$out.= '<div class="float">'.$langs->trans("Files").'</div>';
682
+				$out .= '<div class="float">'.$langs->trans("Files").'</div>';
683 683
 			}
684 684
 
685 685
 			// Language code (if multilang)
686
-			if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && ! $forcenomultilang && (! empty($modellist) || $showempty))
686
+			if (($allowgenifempty || (is_array($modellist) && count($modellist) > 0)) && $conf->global->MAIN_MULTILANGS && !$forcenomultilang && (!empty($modellist) || $showempty))
687 687
 			{
688 688
 				include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
689
-				$formadmin=new FormAdmin($this->db);
690
-				$defaultlang=$codelang?$codelang:$langs->getDefaultLang();
691
-				$morecss='maxwidth150';
692
-				if ($conf->browser->layout == 'phone') $morecss='maxwidth100';
693
-				$out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
689
+				$formadmin = new FormAdmin($this->db);
690
+				$defaultlang = $codelang ? $codelang : $langs->getDefaultLang();
691
+				$morecss = 'maxwidth150';
692
+				if ($conf->browser->layout == 'phone') $morecss = 'maxwidth100';
693
+				$out .= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
694 694
 			}
695 695
 			else
696 696
 			{
697
-				$out.= '&nbsp;';
697
+				$out .= '&nbsp;';
698 698
 			}
699 699
 
700 700
 			// Button
701 701
 			$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
702
-			$genbutton.= ' type="submit" value="'.$buttonlabel.'"';
703
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
704
-			$genbutton.= '>';
705
-			if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
702
+			$genbutton .= ' type="submit" value="'.$buttonlabel.'"';
703
+			if (!$allowgenifempty && !is_array($modellist) && empty($modellist)) $genbutton .= ' disabled';
704
+			$genbutton .= '>';
705
+			if ($allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
706 706
 			{
707 707
 			   	$langs->load("errors");
708
-			   	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
708
+			   	$genbutton .= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
709 709
 			}
710
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
711
-			if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
712
-			$out.= $genbutton;
713
-			$out.= '</th>';
710
+			if (!$allowgenifempty && !is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton = '';
711
+			if (empty($modellist) && !$showempty && $modulepart != 'unpaid') $genbutton = '';
712
+			$out .= $genbutton;
713
+			$out .= '</th>';
714 714
 
715 715
 			if (!empty($hookmanager->hooks['formfile']))
716 716
 			{
717
-				foreach($hookmanager->hooks['formfile'] as $module)
717
+				foreach ($hookmanager->hooks['formfile'] as $module)
718 718
 				{
719 719
 					if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
720 720
 				}
721 721
 			}
722
-			$out.= '</tr>';
722
+			$out .= '</tr>';
723 723
 
724 724
 			// Execute hooks
725
-			$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart);
725
+			$parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart);
726 726
 			if (is_object($hookmanager))
727 727
 			{
728
-				$reshook = $hookmanager->executeHooks('formBuilddocOptions',$parameters,$GLOBALS['object']);
729
-				$out.= $hookmanager->resPrint;
728
+				$reshook = $hookmanager->executeHooks('formBuilddocOptions', $parameters, $GLOBALS['object']);
729
+				$out .= $hookmanager->resPrint;
730 730
 			}
731 731
 		}
732 732
 
733 733
 		// Get list of files
734
-		if (! empty($filedir))
734
+		if (!empty($filedir))
735 735
 		{
736 736
 			$link_list = array();
737 737
 			if (is_object($object))
738 738
 			{
739
-				require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
739
+				require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
740 740
 				$link = new Link($this->db);
741 741
 				$sortfield = $sortorder = null;
742 742
 				$res = $link->fetchAll($link_list, $object->element, $object->id, $sortfield, $sortorder);
743 743
 			}
744 744
 
745
-			$out.= '<!-- html.formfile::showdocuments -->'."\n";
745
+			$out .= '<!-- html.formfile::showdocuments -->'."\n";
746 746
 
747 747
 			// Show title of array if not already shown
748
-			if ((! empty($file_list) || ! empty($link_list) || preg_match('/^massfilesarea/', $modulepart))
749
-				&& ! $headershown)
748
+			if ((!empty($file_list) || !empty($link_list) || preg_match('/^massfilesarea/', $modulepart))
749
+				&& !$headershown)
750 750
 			{
751
-				$headershown=1;
752
-				$out.= '<div class="titre">'.$titletoshow.'</div>'."\n";
753
-				$out.= '<div class="div-table-responsive-no-min">';
754
-				$out.= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
751
+				$headershown = 1;
752
+				$out .= '<div class="titre">'.$titletoshow.'</div>'."\n";
753
+				$out .= '<div class="div-table-responsive-no-min">';
754
+				$out .= '<table class="noborder" summary="listofdocumentstable" id="'.$modulepart.'_table" width="100%">'."\n";
755 755
 			}
756 756
 
757 757
 			// Loop on each file found
758 758
 			if (is_array($file_list))
759 759
 			{
760
-				foreach($file_list as $file)
760
+				foreach ($file_list as $file)
761 761
 				{
762 762
 					// Define relative path for download link (depends on module)
763
-					$relativepath=$file["name"];										// Cas general
764
-					if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
765
-					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
763
+					$relativepath = $file["name"]; // Cas general
764
+					if ($modulesubdir) $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
765
+					if ($modulepart == 'export') $relativepath = $file["name"]; // Other case
766 766
 
767
-					$out.= '<tr class="oddeven">';
767
+					$out .= '<tr class="oddeven">';
768 768
 
769 769
 					$documenturl = DOL_URL_ROOT.'/document.php';
770
-					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
770
+					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl = $conf->global->DOL_URL_ROOT_DOCUMENT_PHP; // To use another wrapper
771 771
 
772 772
 					// Show file name with link to download
773
-					$out.= '<td class="minwidth200">';
774
-					$out.= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
775
-					$mime=dol_mimetype($relativepath,'',0);
776
-					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
777
-					$out.= ' target="_blank">';
778
-					$out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]);
779
-					$out.= dol_trunc($file["name"], 150);
780
-					$out.= '</a>'."\n";
781
-					$out.= $this->showPreview($file,$modulepart,$relativepath,0,$param);
782
-					$out.= '</td>';
773
+					$out .= '<td class="minwidth200">';
774
+					$out .= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param ? '&'.$param : '').'"';
775
+					$mime = dol_mimetype($relativepath, '', 0);
776
+					if (preg_match('/text/', $mime)) $out .= ' target="_blank"';
777
+					$out .= ' target="_blank">';
778
+					$out .= img_mime($file["name"], $langs->trans("File").': '.$file["name"]);
779
+					$out .= dol_trunc($file["name"], 150);
780
+					$out .= '</a>'."\n";
781
+					$out .= $this->showPreview($file, $modulepart, $relativepath, 0, $param);
782
+					$out .= '</td>';
783 783
 
784 784
 					// Show file size
785
-					$size=(! empty($file['size'])?$file['size']:dol_filesize($filedir."/".$file["name"]));
786
-					$out.= '<td align="right" class="nowrap">'.dol_print_size($size,1,1).'</td>';
785
+					$size = (!empty($file['size']) ? $file['size'] : dol_filesize($filedir."/".$file["name"]));
786
+					$out .= '<td align="right" class="nowrap">'.dol_print_size($size, 1, 1).'</td>';
787 787
 
788 788
 					// Show file date
789
-					$date=(! empty($file['date'])?$file['date']:dol_filemtime($filedir."/".$file["name"]));
790
-					$out.= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
789
+					$date = (!empty($file['date']) ? $file['date'] : dol_filemtime($filedir."/".$file["name"]));
790
+					$out .= '<td align="right" class="nowrap">'.dol_print_date($date, 'dayhour', 'tzuser').'</td>';
791 791
 
792 792
 					if ($delallowed || $printer || $morepicto)
793 793
 					{
794
-						$out.= '<td class="right nowraponall">';
794
+						$out .= '<td class="right nowraponall">';
795 795
 						if ($delallowed)
796 796
 						{
797 797
 							$tmpurlsource = preg_replace('/#[a-zA-Z0-9_]*$/', '', $urlsource);
798
-							$out.= '<a href="'.$tmpurlsource.(strpos($tmpurlsource,'?')?'&amp;':'?').'action=remove_file&amp;file='.urlencode($relativepath);
799
-							$out.= ($param?'&amp;'.$param:'');
798
+							$out .= '<a href="'.$tmpurlsource.(strpos($tmpurlsource, '?') ? '&amp;' : '?').'action=remove_file&amp;file='.urlencode($relativepath);
799
+							$out .= ($param ? '&amp;'.$param : '');
800 800
 							//$out.= '&modulepart='.$modulepart; // TODO obsolete ?
801 801
 							//$out.= '&urlsource='.urlencode($urlsource); // TODO obsolete ?
802
-							$out.= '">'.img_picto($langs->trans("Delete"), 'delete').'</a>';
802
+							$out .= '">'.img_picto($langs->trans("Delete"), 'delete').'</a>';
803 803
 						}
804 804
 						if ($printer)
805 805
 						{
806 806
 							//$out.= '<td align="right">';
807
-							$out.= '<a class="paddingleft" href="'.$urlsource.(strpos($urlsource,'?')?'&amp;':'?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
808
-							$out.= ($param?'&amp;'.$param:'');
809
-							$out.= '">'.img_picto($langs->trans("PrintFile", $relativepath),'printer.png').'</a>';
807
+							$out .= '<a class="paddingleft" href="'.$urlsource.(strpos($urlsource, '?') ? '&amp;' : '?').'action=print_file&amp;printer='.$modulepart.'&amp;file='.urlencode($relativepath);
808
+							$out .= ($param ? '&amp;'.$param : '');
809
+							$out .= '">'.img_picto($langs->trans("PrintFile", $relativepath), 'printer.png').'</a>';
810 810
 						}
811 811
 						if ($morepicto)
812 812
 						{
813
-							$morepicto=preg_replace('/__FILENAMEURLENCODED__/',urlencode($relativepath),$morepicto);
814
-							$out.=$morepicto;
813
+							$morepicto = preg_replace('/__FILENAMEURLENCODED__/', urlencode($relativepath), $morepicto);
814
+							$out .= $morepicto;
815 815
 						}
816
-						$out.='</td>';
816
+						$out .= '</td>';
817 817
 					}
818 818
 
819 819
 					if (is_object($hookmanager))
820 820
 					{
821
-						$parameters=array('socid'=>(isset($GLOBALS['socid'])?$GLOBALS['socid']:''),'id'=>(isset($GLOBALS['id'])?$GLOBALS['id']:''),'modulepart'=>$modulepart,'relativepath'=>$relativepath);
822
-						$res = $hookmanager->executeHooks('formBuilddocLineOptions',$parameters,$file);
821
+						$parameters = array('socid'=>(isset($GLOBALS['socid']) ? $GLOBALS['socid'] : ''), 'id'=>(isset($GLOBALS['id']) ? $GLOBALS['id'] : ''), 'modulepart'=>$modulepart, 'relativepath'=>$relativepath);
822
+						$res = $hookmanager->executeHooks('formBuilddocLineOptions', $parameters, $file);
823 823
 						if (empty($res))
824 824
 						{
825
-							$out.= $hookmanager->resPrint;		// Complete line
826
-							$out.= '</tr>';
825
+							$out .= $hookmanager->resPrint; // Complete line
826
+							$out .= '</tr>';
827 827
 						}
828
-						else $out = $hookmanager->resPrint;		// Replace line
828
+						else $out = $hookmanager->resPrint; // Replace line
829 829
 			  		}
830 830
 				}
831 831
 
@@ -834,42 +834,42 @@  discard block
 block discarded – undo
834 834
 			// Loop on each link found
835 835
 			if (is_array($link_list))
836 836
 			{
837
-				$colspan=2;
837
+				$colspan = 2;
838 838
 
839
-				foreach($link_list as $file)
839
+				foreach ($link_list as $file)
840 840
 				{
841
-					$out.='<tr class="oddeven">';
842
-					$out.='<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
843
-					$out.='<a data-ajax="false" href="' . $link->url . '" target="_blank">';
844
-					$out.=$file->label;
845
-					$out.='</a>';
846
-					$out.='</td>';
847
-					$out.='<td align="right">';
848
-					$out.=dol_print_date($file->datea,'dayhour');
849
-					$out.='</td>';
850
-					if ($delallowed || $printer || $morepicto) $out.='<td></td>';
851
-					$out.='</tr>'."\n";
841
+					$out .= '<tr class="oddeven">';
842
+					$out .= '<td colspan="'.$colspan.'" class="maxwidhtonsmartphone">';
843
+					$out .= '<a data-ajax="false" href="'.$link->url.'" target="_blank">';
844
+					$out .= $file->label;
845
+					$out .= '</a>';
846
+					$out .= '</td>';
847
+					$out .= '<td align="right">';
848
+					$out .= dol_print_date($file->datea, 'dayhour');
849
+					$out .= '</td>';
850
+					if ($delallowed || $printer || $morepicto) $out .= '<td></td>';
851
+					$out .= '</tr>'."\n";
852 852
 				}
853 853
 				$this->numoffiles++;
854 854
 			}
855 855
 
856 856
 		 	if (count($file_list) == 0 && count($link_list) == 0 && $headershown)
857 857
 			{
858
-				$out.='<tr><td colspan="'.(3+($addcolumforpicto?1:0)).'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
858
+				$out .= '<tr><td colspan="'.(3 + ($addcolumforpicto ? 1 : 0)).'" class="opacitymedium">'.$langs->trans("None").'</td></tr>'."\n";
859 859
 			}
860 860
 		}
861 861
 
862 862
 		if ($headershown)
863 863
 		{
864 864
 			// Affiche pied du tableau
865
-			$out.= "</table>\n";
866
-			$out.= "</div>\n";
865
+			$out .= "</table>\n";
866
+			$out .= "</div>\n";
867 867
 			if ($genallowed)
868 868
 			{
869
-				if (empty($noform)) $out.= '</form>'."\n";
869
+				if (empty($noform)) $out .= '</form>'."\n";
870 870
 			}
871 871
 		}
872
-		$out.= '<!-- End show_document -->'."\n";
872
+		$out .= '<!-- End show_document -->'."\n";
873 873
 		//return ($i?$i:$headershown);
874 874
 		return $out;
875 875
 	}
@@ -885,98 +885,98 @@  discard block
 block discarded – undo
885 885
 	 *  @param	string	$filter			Filter filenames on this regex string (Example: '\.pdf$')
886 886
 	 *	@return	string              	Output string with HTML link of documents (might be empty string). This also fill the array ->infofiles
887 887
 	 */
888
-	function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter='')
888
+	function getDocumentsLink($modulepart, $modulesubdir, $filedir, $filter = '')
889 889
 	{
890 890
 		global $conf, $langs;
891 891
 
892 892
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
893 893
 
894
-		$out='';
895
-		$this->infofiles=array('nboffiles'=>0,'extensions'=>array(),'files'=>array());
894
+		$out = '';
895
+		$this->infofiles = array('nboffiles'=>0, 'extensions'=>array(), 'files'=>array());
896 896
 
897 897
 		$entity = 1; // Without multicompany
898 898
 
899 899
 		// Get object entity
900
-		if (! empty($conf->multicompany->enabled))
900
+		if (!empty($conf->multicompany->enabled))
901 901
 		{
902
-			preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir,'/').'$/', $filedir, $regs);
903
-			$entity = ((! empty($regs[1]) && $regs[1] > 1) ? $regs[1] : 1); // If entity id not found in $filedir this is entity 1 by default
902
+			preg_match('/\/([0-9]+)\/[^\/]+\/'.preg_quote($modulesubdir, '/').'$/', $filedir, $regs);
903
+			$entity = ((!empty($regs[1]) && $regs[1] > 1) ? $regs[1] : 1); // If entity id not found in $filedir this is entity 1 by default
904 904
 		}
905 905
 
906 906
 		// Get list of files starting with name of ref (but not followed by "-" to discard uploaded files and get only generated files)
907 907
 		// @TODO Why not showing by default all files by just removing the '[^\-]+' at end of regex ?
908
-		if (! empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP))
908
+		if (!empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP))
909 909
 		{
910
-			$filterforfilesearch = preg_quote(basename($modulesubdir),'/');
910
+			$filterforfilesearch = preg_quote(basename($modulesubdir), '/');
911 911
 		}
912 912
 		else
913 913
 		{
914
-			$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
914
+			$filterforfilesearch = preg_quote(basename($modulesubdir), '/').'[^\-]+';
915 915
 		}
916
-		$file_list=dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$');	// We also discard .meta and .png preview
916
+		$file_list = dol_dir_list($filedir, 'files', 0, $filterforfilesearch, '\.meta$|\.png$'); // We also discard .meta and .png preview
917 917
 
918 918
 		//var_dump($file_list);
919 919
 		// For ajax treatment
920
-		$out.= '<!-- html.formfile::getDocumentsLink -->'."\n";
921
-		if (! empty($file_list))
920
+		$out .= '<!-- html.formfile::getDocumentsLink -->'."\n";
921
+		if (!empty($file_list))
922 922
 		{
923
-			$out='<dl class="dropdown inline-block">
923
+			$out = '<dl class="dropdown inline-block">
924 924
     			<dt><a data-ajax="false" href="#" onClick="return false;">'.img_picto('', 'listlight', '', 0, 0, 0, '', 'valignmiddle').'</a></dt>
925 925
     			<dd><div class="multichoicedoc" style="position:absolute;left:100px;" ><ul class="ulselectedfields" style="display: none;">';
926
-			$tmpout='';
926
+			$tmpout = '';
927 927
 
928 928
 			// Loop on each file found
929
-			$found=0;
930
-			foreach($file_list as $file)
929
+			$found = 0;
930
+			foreach ($file_list as $file)
931 931
 			{
932 932
 				$i++;
933
-				if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
933
+				if ($filter && !preg_match('/'.$filter.'/i', $file["name"])) continue; // Discard this. It does not match provided filter.
934 934
 
935 935
 				$found++;
936 936
 				// Define relative path for download link (depends on module)
937
-				$relativepath=$file["name"];								// Cas general
938
-				if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
937
+				$relativepath = $file["name"]; // Cas general
938
+				if ($modulesubdir) $relativepath = $modulesubdir."/".$file["name"]; // Cas propal, facture...
939 939
 				// Autre cas
940
-				if ($modulepart == 'donation')            {
941
-					$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
940
+				if ($modulepart == 'donation') {
941
+					$relativepath = get_exdir($modulesubdir, 2, 0, 0, null, 'donation').$file["name"];
942 942
 				}
943
-				if ($modulepart == 'export')              {
943
+				if ($modulepart == 'export') {
944 944
 					$relativepath = $file["name"];
945 945
 				}
946 946
 
947 947
 				$this->infofiles['nboffiles']++;
948
-				$this->infofiles['files'][]=$file['fullname'];
949
-				$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
950
-				if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
948
+				$this->infofiles['files'][] = $file['fullname'];
949
+				$ext = pathinfo($file["name"], PATHINFO_EXTENSION);
950
+				if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext] = 1;
951 951
 				else $this->infofiles['extensions'][$ext]++;
952 952
 
953 953
 				// Preview
954
-				if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
954
+				if (!empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
955 955
 				{
956 956
 					$tmparray = getAdvancedPreviewUrl($modulepart, $relativepath, 1, '&entity='.$entity);
957 957
 					if ($tmparray && $tmparray['url'])
958 958
 					{
959
-						$tmpout.= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css']?' class="'.$tmparray['css'].'"':'').($tmparray['mime']?' mime="'.$tmparray['mime'].'"':'').($tmparray['target']?' target="'.$tmparray['target'].'"':'').'>';
959
+						$tmpout .= '<li><a href="'.$tmparray['url'].'"'.($tmparray['css'] ? ' class="'.$tmparray['css'].'"' : '').($tmparray['mime'] ? ' mime="'.$tmparray['mime'].'"' : '').($tmparray['target'] ? ' target="'.$tmparray['target'].'"' : '').'>';
960 960
 						//$tmpout.= img_picto('','detail');
961
-						$tmpout.= '<i class="fa fa-search-plus paddingright" style="color: gray"></i>';
962
-						$tmpout.= $langs->trans("Preview").' '.$ext.'</a></li>';
961
+						$tmpout .= '<i class="fa fa-search-plus paddingright" style="color: gray"></i>';
962
+						$tmpout .= $langs->trans("Preview").' '.$ext.'</a></li>';
963 963
 					}
964 964
 				}
965 965
 
966 966
 				// Download
967
-				$tmpout.= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
968
-				$mime=dol_mimetype($relativepath,'',0);
969
-				if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
970
-				$tmpout.= '>';
971
-				$tmpout.= img_mime($relativepath, $file["name"]);
972
-				$tmpout.= $langs->trans("Download").' '.$ext;
973
-				$tmpout.= '</a></li>'."\n";
974
-			}
975
-			$out.=$tmpout;
976
-			$out.='</ul></div></dd>
967
+				$tmpout .= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
968
+				$mime = dol_mimetype($relativepath, '', 0);
969
+				if (preg_match('/text/', $mime)) $tmpout .= ' target="_blank"';
970
+				$tmpout .= '>';
971
+				$tmpout .= img_mime($relativepath, $file["name"]);
972
+				$tmpout .= $langs->trans("Download").' '.$ext;
973
+				$tmpout .= '</a></li>'."\n";
974
+			}
975
+			$out .= $tmpout;
976
+			$out .= '</ul></div></dd>
977 977
     			</dl>';
978 978
 
979
-			if (! $found) $out='';
979
+			if (!$found) $out = '';
980 980
 		}
981 981
 		else
982 982
 		{
@@ -1018,7 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 	 * 	@return	 int						<0 if KO, nb of files shown if OK
1019 1019
 	 *  @see list_of_autoecmfiles
1020 1020
 	 */
1021
-	function list_of_documents($filearray,$object,$modulepart,$param='',$forcedownload=0,$relativepath='',$permonobject=1,$useinecm=0,$textifempty='',$maxlength=0,$title='',$url='', $showrelpart=0, $permtoeditline=-1,$upload_dir='',$sortfield='',$sortorder='ASC', $disablemove=1, $addfilterfields=0)
1021
+	function list_of_documents($filearray, $object, $modulepart, $param = '', $forcedownload = 0, $relativepath = '', $permonobject = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $title = '', $url = '', $showrelpart = 0, $permtoeditline = -1, $upload_dir = '', $sortfield = '', $sortorder = 'ASC', $disablemove = 1, $addfilterfields = 0)
1022 1022
 	{
1023 1023
         // phpcs:enable
1024 1024
 		global $user, $conf, $langs, $hookmanager;
@@ -1026,37 +1026,37 @@  discard block
 block discarded – undo
1026 1026
 		global $dolibarr_main_url_root;
1027 1027
 		global $form;
1028 1028
 
1029
-		$disablecrop=1;
1030
-		if (in_array($modulepart, array('expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) $disablecrop=0;
1029
+		$disablecrop = 1;
1030
+		if (in_array($modulepart, array('expensereport', 'holiday', 'member', 'project', 'product', 'produit', 'service', 'societe', 'tax', 'ticket', 'user'))) $disablecrop = 0;
1031 1031
 
1032 1032
 		// Define relative path used to store the file
1033 1033
 		if (empty($relativepath))
1034 1034
 		{
1035
-			$relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
1036
-			if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
1037
-			if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1035
+			$relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/';
1036
+			if ($object->element == 'invoice_supplier') $relativepath = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$relativepath; // TODO Call using a defined value for $relativepath
1037
+			if ($object->element == 'project_task') $relativepath = 'Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1038 1038
 		}
1039 1039
 		// For backward compatiblity, we detect file stored into an old path
1040
-		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos')
1040
+		if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos')
1041 1041
 		{
1042
-		    $relativepath=preg_replace('/^.*\/produit\//','',$filearray[0]['path']).'/';
1042
+		    $relativepath = preg_replace('/^.*\/produit\//', '', $filearray[0]['path']).'/';
1043 1043
 		}
1044 1044
 		// Defined relative dir to DOL_DATA_ROOT
1045 1045
 		$relativedir = '';
1046 1046
 		if ($upload_dir)
1047 1047
 		{
1048
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
1049
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
1048
+			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
1049
+			$relativedir = preg_replace('/^[\\/]/', '', $relativedir);
1050 1050
 		}
1051 1051
 
1052 1052
 		$hookmanager->initHooks(array('formfile'));
1053
-		$parameters=array(
1053
+		$parameters = array(
1054 1054
 				'filearray' => $filearray,
1055 1055
 				'modulepart'=> $modulepart,
1056 1056
 				'param' => $param,
1057 1057
 				'forcedownload' => $forcedownload,
1058
-				'relativepath' => $relativepath,    // relative filename to module dir
1059
-				'relativedir' => $relativedir,      // relative dirname to DOL_DATA_ROOT
1058
+				'relativepath' => $relativepath, // relative filename to module dir
1059
+				'relativedir' => $relativedir, // relative dirname to DOL_DATA_ROOT
1060 1060
 				'permtodelete' => $permonobject,
1061 1061
 				'useinecm' => $useinecm,
1062 1062
 				'textifempty' => $textifempty,
@@ -1064,7 +1064,7 @@  discard block
 block discarded – undo
1064 1064
 				'title' => $title,
1065 1065
 				'url' => $url
1066 1066
 		);
1067
-		$reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
1067
+		$reshook = $hookmanager->executeHooks('showFilesList', $parameters, $object);
1068 1068
 
1069 1069
 		if (isset($reshook) && $reshook != '') // null or '' for bypass
1070 1070
 		{
@@ -1072,37 +1072,37 @@  discard block
 block discarded – undo
1072 1072
 		}
1073 1073
 		else
1074 1074
 		{
1075
-			if (! is_object($form))
1075
+			if (!is_object($form))
1076 1076
 			{
1077
-				include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';		// The compoent may be included into ajax page that does not include the Form class
1078
-				$form=new Form($this->db);
1077
+				include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // The compoent may be included into ajax page that does not include the Form class
1078
+				$form = new Form($this->db);
1079 1079
 			}
1080 1080
 
1081
-			if (! preg_match('/&id=/', $param) && isset($object->id)) $param.='&id='.$object->id;
1082
-			$relativepathwihtoutslashend=preg_replace('/\/$/', '', $relativepath);
1083
-			if ($relativepathwihtoutslashend) $param.= '&file='.urlencode($relativepathwihtoutslashend);
1081
+			if (!preg_match('/&id=/', $param) && isset($object->id)) $param .= '&id='.$object->id;
1082
+			$relativepathwihtoutslashend = preg_replace('/\/$/', '', $relativepath);
1083
+			if ($relativepathwihtoutslashend) $param .= '&file='.urlencode($relativepathwihtoutslashend);
1084 1084
 
1085 1085
 			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1086 1086
 			{
1087
-				$permtoeditline=0;
1088
-				if (in_array($modulepart, array('product','produit','service')))
1087
+				$permtoeditline = 0;
1088
+				if (in_array($modulepart, array('product', 'produit', 'service')))
1089 1089
 				{
1090
-					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
1091
-					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
1090
+					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline = 1;
1091
+					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline = 1;
1092 1092
 				}
1093 1093
 			}
1094 1094
 			if (empty($conf->global->MAIN_UPLOAD_DOC))
1095 1095
 			{
1096
-				$permtoeditline=0;
1097
-				$permonobject=0;
1096
+				$permtoeditline = 0;
1097
+				$permonobject = 0;
1098 1098
 			}
1099 1099
 
1100 1100
 			// Show list of existing files
1101
-			if (empty($useinecm) && $title != 'none') print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1102
-			if (empty($url)) $url=$_SERVER["PHP_SELF"];
1101
+			if (empty($useinecm) && $title != 'none') print load_fiche_titre($title ? $title : $langs->trans("AttachedFiles"));
1102
+			if (empty($url)) $url = $_SERVER["PHP_SELF"];
1103 1103
 
1104 1104
 			print '<!-- html.formfile::list_of_documents -->'."\n";
1105
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1105
+			if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline)
1106 1106
 			{
1107 1107
 				print '<form action="'.$_SERVER["PHP_SELF"].'?'.$param.'" method="POST">';
1108 1108
 				print '<input type="hidden" name="action" value="renamefile">';
@@ -1111,30 +1111,30 @@  discard block
 block discarded – undo
1111 1111
 			}
1112 1112
 
1113 1113
 			print '<div class="div-table-responsive-no-min">';
1114
-			print '<table width="100%" id="tablelines" class="'.($useinecm?'liste noborder':'liste').'">'."\n";
1114
+			print '<table width="100%" id="tablelines" class="'.($useinecm ? 'liste noborder' : 'liste').'">'."\n";
1115 1115
 
1116
-			if (! empty($addfilterfields))
1116
+			if (!empty($addfilterfields))
1117 1117
 			{
1118 1118
 				print '<tr class="liste_titre nodrag nodrop">';
1119
-				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1119
+				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref', 'alpha')).'"></td>';
1120 1120
 				print '<td></td>';
1121 1121
 				print '<td></td>';
1122 1122
 				if (empty($useinecm)) print '<td></td>';
1123 1123
 				print '<td></td>';
1124 1124
 				print '<td></td>';
1125
-				if (! $disablemove) print '<td></td>';
1125
+				if (!$disablemove) print '<td></td>';
1126 1126
 				print "</tr>\n";
1127 1127
 			}
1128 1128
 
1129 1129
 			print '<tr class="liste_titre nodrag nodrop">';
1130 1130
 			//print $url.' sortfield='.$sortfield.' sortorder='.$sortorder;
1131
-			print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1132
-			print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1133
-			print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1134
-			if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');					// Preview
1131
+			print_liste_field_titre('Documents2', $url, "name", "", $param, 'align="left"', $sortfield, $sortorder);
1132
+			print_liste_field_titre('Size', $url, "size", "", $param, 'align="right"', $sortfield, $sortorder);
1133
+			print_liste_field_titre('Date', $url, "date", "", $param, 'align="center"', $sortfield, $sortorder);
1134
+			if (empty($useinecm)) print_liste_field_titre('', $url, "", "", $param, 'align="center"'); // Preview
1135 1135
 			print_liste_field_titre('');
1136 1136
 			print_liste_field_titre('');
1137
-			if (! $disablemove) print_liste_field_titre('');
1137
+			if (!$disablemove) print_liste_field_titre('');
1138 1138
 			print "</tr>\n";
1139 1139
 
1140 1140
 			// Get list of files stored into database for same relative directory
@@ -1145,29 +1145,29 @@  discard block
 block discarded – undo
1145 1145
 				//var_dump($sortfield.' - '.$sortorder);
1146 1146
 				if ($sortfield && $sortorder)	// If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
1147 1147
 				{
1148
-					$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1148
+					$filearray = dol_sort_array($filearray, $sortfield, $sortorder);
1149 1149
 				}
1150 1150
 			}
1151 1151
 
1152
-			$nboffiles=count($filearray);
1152
+			$nboffiles = count($filearray);
1153 1153
 			if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1154 1154
 
1155
-			$i=0; $nboflines = 0; $lastrowid=0;
1156
-			foreach($filearray as $key => $file)      // filearray must be only files here
1155
+			$i = 0; $nboflines = 0; $lastrowid = 0;
1156
+			foreach ($filearray as $key => $file)      // filearray must be only files here
1157 1157
 			{
1158 1158
 				if ($file['name'] != '.'
1159 1159
 						&& $file['name'] != '..'
1160
-						&& ! preg_match('/\.meta$/i',$file['name']))
1160
+						&& !preg_match('/\.meta$/i', $file['name']))
1161 1161
 				{
1162 1162
 					if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1163
-					$filepath=$relativepath.$file['name'];
1163
+					$filepath = $relativepath.$file['name'];
1164 1164
 
1165
-					$editline=0;
1165
+					$editline = 0;
1166 1166
 					$nboflines++;
1167 1167
 					print '<!-- Line list_of_documents '.$key.' relativepath = '.$relativepath.' -->'."\n";
1168 1168
 					// Do we have entry into database ?
1169 1169
 					print '<!-- In database: position='.$filearray[$key]['position'].' -->'."\n";
1170
-					print '<tr class="oddeven" id="row-'.($filearray[$key]['rowid']>0?$filearray[$key]['rowid']:'AFTER'.$lastrowid.'POS'.($i+1)).'">';
1170
+					print '<tr class="oddeven" id="row-'.($filearray[$key]['rowid'] > 0 ? $filearray[$key]['rowid'] : 'AFTER'.$lastrowid.'POS'.($i + 1)).'">';
1171 1171
 
1172 1172
 					// File name
1173 1173
 					print '<td class="minwith200">';
@@ -1176,20 +1176,20 @@  discard block
 block discarded – undo
1176 1176
 					//print "XX".$file['name'];	//$file['name'] must be utf8
1177 1177
 					print '<a class="paddingright" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1178 1178
 					if ($forcedownload) print '&attachment=1';
1179
-					if (! empty($object->entity)) print '&entity='.$object->entity;
1179
+					if (!empty($object->entity)) print '&entity='.$object->entity;
1180 1180
 					print '&file='.urlencode($filepath);
1181 1181
 					print '">';
1182
-					print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'],0,0).')', 'inline-block valignbottom paddingright');
1182
+					print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')', 'inline-block valignbottom paddingright');
1183 1183
 					if ($showrelpart == 1) print $relativepath;
1184 1184
 					//print dol_trunc($file['name'],$maxlength,'middle');
1185
-					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile','alpha')))
1185
+					if (GETPOST('action', 'aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile', 'alpha')))
1186 1186
 					{
1187 1187
 						print '</a>';
1188
-						$section_dir=dirname(GETPOST('urlfile','alpha'));
1188
+						$section_dir = dirname(GETPOST('urlfile', 'alpha'));
1189 1189
 						print '<input type="hidden" name="section_dir" value="'.$section_dir.'">';
1190 1190
 						print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1191 1191
 						print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1192
-						$editline=1;
1192
+						$editline = 1;
1193 1193
 					}
1194 1194
 					else
1195 1195
 					{
@@ -1197,15 +1197,15 @@  discard block
 block discarded – undo
1197 1197
 						print '</a>';
1198 1198
 					}
1199 1199
 					// Preview link
1200
-					if (! $editline) print $this->showPreview($file, $modulepart, $filepath);
1200
+					if (!$editline) print $this->showPreview($file, $modulepart, $filepath);
1201 1201
 					// Public share link
1202 1202
 					//if (! $editline && ! empty($filearray[$key]['hashp'])) print pictowithlinktodirectdownload;
1203 1203
 
1204 1204
 					print "</td>\n";
1205 1205
 
1206 1206
 					// Size
1207
-					$sizetoshow = dol_print_size($file['size'],1,1);
1208
-					$sizetoshowbytes = dol_print_size($file['size'],0,1);
1207
+					$sizetoshow = dol_print_size($file['size'], 1, 1);
1208
+					$sizetoshowbytes = dol_print_size($file['size'], 0, 1);
1209 1209
 
1210 1210
 					print '<td align="right" width="80px">';
1211 1211
 					if ($sizetoshow == $sizetoshowbytes) print $sizetoshow;
@@ -1215,7 +1215,7 @@  discard block
 block discarded – undo
1215 1215
 					print '</td>';
1216 1216
 
1217 1217
 					// Date
1218
-					print '<td align="center" width="140px">'.dol_print_date($file['date'],"dayhour","tzuser").'</td>';	// 140px = width for date with PM format
1218
+					print '<td align="center" width="140px">'.dol_print_date($file['date'], "dayhour", "tzuser").'</td>'; // 140px = width for date with PM format
1219 1219
 
1220 1220
 					// Preview
1221 1221
 					if (empty($useinecm))
@@ -1224,18 +1224,18 @@  discard block
 block discarded – undo
1224 1224
 						print '<td align="center">';
1225 1225
 						if (image_format_supported($file['name']) > 0)
1226 1226
 						{
1227
-							$minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1228
-							if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1227
+							$minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1228
+							if (!dol_is_file($file['path'].'/'.$minifile)) $minifile = getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1229 1229
 							//print $file['path'].'/'.$minifile.'<br>';
1230 1230
 
1231
-							$urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
1231
+							$urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity));
1232 1232
 							if (empty($urlforhref)) {
1233
-								$urlforhref=DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1233
+								$urlforhref = DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']));
1234 1234
 								print '<a href="'.$urlforhref.'" class="aphoto" target="_blank">';
1235 1235
 							} else {
1236 1236
 								print '<a href="'.$urlforhref['url'].'" class="'.$urlforhref['css'].'" target="'.$urlforhref['target'].'" mime="'.$urlforhref['mime'].'">';
1237 1237
 							}
1238
-							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1238
+							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1239 1239
 							print '</a>';
1240 1240
 						}
1241 1241
 						else print '&nbsp;';
@@ -1249,26 +1249,26 @@  discard block
 block discarded – undo
1249 1249
 						if ($editline)
1250 1250
 						{
1251 1251
 							print $langs->trans("FileSharedViaALink").' ';
1252
-							print '<input class="inline-block" type="checkbox" name="shareenabled"'.($file['share']?' checked="checked"':'').' /> ';
1252
+							print '<input class="inline-block" type="checkbox" name="shareenabled"'.($file['share'] ? ' checked="checked"' : '').' /> ';
1253 1253
 						}
1254 1254
 						else
1255 1255
 						{
1256 1256
 							if ($file['share'])
1257 1257
 							{
1258 1258
 								// Define $urlwithroot
1259
-								$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
1260
-								$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
1259
+								$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1260
+								$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1261 1261
 								//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
1262 1262
 
1263 1263
 								//print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
1264
-								$forcedownload=0;
1265
-								$paramlink='';
1266
-								if (! empty($file['share'])) $paramlink.=($paramlink?'&':'').'hashp='.$file['share'];			// Hash for public share
1267
-								if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
1264
+								$forcedownload = 0;
1265
+								$paramlink = '';
1266
+								if (!empty($file['share'])) $paramlink .= ($paramlink ? '&' : '').'hashp='.$file['share']; // Hash for public share
1267
+								if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
1268 1268
 
1269
-								$fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
1269
+								$fulllink = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
1270 1270
 
1271
-								print img_picto($langs->trans("FileSharedViaALink"),'object_globe.png').' ';
1271
+								print img_picto($langs->trans("FileSharedViaALink"), 'object_globe.png').' ';
1272 1272
 								print '<input type="text" class="quatrevingtpercent" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
1273 1273
 							}
1274 1274
 							else
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
 					print '</td>';
1281 1281
 
1282 1282
 					// Actions buttons
1283
-					if (! $editline)
1283
+					if (!$editline)
1284 1284
 					{
1285 1285
 						// Delete or view link
1286 1286
 						// ($param must start with &)
@@ -1289,33 +1289,33 @@  discard block
 block discarded – undo
1289 1289
 						{
1290 1290
 							print '<a href="'.DOL_URL_ROOT.'/ecm/file_card.php?urlfile='.urlencode($file['name']).$param.'" class="editfilelink" rel="'.urlencode($file['name']).'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
1291 1291
 						}
1292
-						if (! $useinecm || $useinecm == 2)
1292
+						if (!$useinecm || $useinecm == 2)
1293 1293
 						{
1294
-							$newmodulepart=$modulepart;
1295
-							if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1294
+							$newmodulepart = $modulepart;
1295
+							if (in_array($modulepart, array('product', 'produit', 'service'))) $newmodulepart = 'produit|service';
1296 1296
 
1297
-							if (! $disablecrop && image_format_supported($file['name']) > 0)
1297
+							if (!$disablecrop && image_format_supported($file['name']) > 0)
1298 1298
 							{
1299 1299
 								if ($permtoeditline)
1300 1300
 								{
1301 1301
 	   								// Link to resize
1302
-	   						   		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("ResizeOrCrop")).'">'.img_picto($langs->trans("ResizeOrCrop"),'resize','class="paddingrightonly"').'</a>';
1302
+	   						   		print '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode($newmodulepart).'&id='.$object->id.'&file='.urlencode($relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension'])).'" title="'.dol_escape_htmltag($langs->trans("ResizeOrCrop")).'">'.img_picto($langs->trans("ResizeOrCrop"), 'resize', 'class="paddingrightonly"').'</a>';
1303 1303
 								}
1304 1304
 							}
1305 1305
 
1306 1306
 							if ($permtoeditline)
1307 1307
 							{
1308
-								$paramsectiondir=(in_array($modulepart, array('medias','ecm'))?'&section_dir='.urlencode($relativepath):'');
1309
-								print '<a href="'.(($useinecm == 1)?'#':($url.'?action=editfile&urlfile='.urlencode($filepath).$paramsectiondir.$param)).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default',0,'class="paddingrightonly"').'</a>';
1308
+								$paramsectiondir = (in_array($modulepart, array('medias', 'ecm')) ? '&section_dir='.urlencode($relativepath) : '');
1309
+								print '<a href="'.(($useinecm == 1) ? '#' : ($url.'?action=editfile&urlfile='.urlencode($filepath).$paramsectiondir.$param)).'" class="editfilelink" rel="'.$filepath.'">'.img_edit('default', 0, 'class="paddingrightonly"').'</a>';
1310 1310
 							}
1311 1311
 						}
1312 1312
 						if ($permonobject)
1313 1313
 						{
1314
-							$useajax=1;
1315
-							if (! empty($conf->dol_use_jmobile)) $useajax=0;
1316
-							if (empty($conf->use_javascript_ajax)) $useajax=0;
1317
-							if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1318
-							print '<a href="'.(($useinecm && $useajax)?'#':($url.'?action=delete&urlfile='.urlencode($filepath).$param)).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1314
+							$useajax = 1;
1315
+							if (!empty($conf->dol_use_jmobile)) $useajax = 0;
1316
+							if (empty($conf->use_javascript_ajax)) $useajax = 0;
1317
+							if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax = 0;
1318
+							print '<a href="'.(($useinecm && $useajax) ? '#' : ($url.'?action=delete&urlfile='.urlencode($filepath).$param)).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1319 1319
 						}
1320 1320
 						print "</td>";
1321 1321
 
@@ -1324,15 +1324,15 @@  discard block
 block discarded – undo
1324 1324
 							if ($nboffiles > 1 && $conf->browser->layout != 'phone') {
1325 1325
 								print '<td align="center" class="linecolmove tdlineupdown">';
1326 1326
 								if ($i > 0) {
1327
-									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default',0,'imgupforline').'</a>';
1327
+									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id.'">'.img_up('default', 0, 'imgupforline').'</a>';
1328 1328
 								}
1329
-								if ($i < $nboffiles-1) {
1330
-									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1329
+								if ($i < $nboffiles - 1) {
1330
+									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default', 0, 'imgdownforline').'</a>';
1331 1331
 								}
1332 1332
 								print '</td>';
1333 1333
 							}
1334 1334
 							else {
1335
-							   	print '<td align="center"'.(($conf->browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1335
+							   	print '<td align="center"'.(($conf->browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown"' : ' class="linecolmove"').'>';
1336 1336
 							   	print '</td>';
1337 1337
 							}
1338 1338
 					   }
@@ -1353,8 +1353,8 @@  discard block
 block discarded – undo
1353 1353
 			}
1354 1354
 			if ($nboffiles == 0)
1355 1355
 			{
1356
-				$colspan=(empty($useinecm)?'6':'6');
1357
-				if (empty($disablemove)) $colspan++;		// 6 columns or 7
1356
+				$colspan = (empty($useinecm) ? '6' : '6');
1357
+				if (empty($disablemove)) $colspan++; // 6 columns or 7
1358 1358
 				print '<tr class="oddeven"><td colspan="'.$colspan.'" class="opacitymedium">';
1359 1359
 				if (empty($textifempty)) print $langs->trans("NoFileFound");
1360 1360
 				else print $textifempty;
@@ -1364,15 +1364,15 @@  discard block
 block discarded – undo
1364 1364
 			print '</div>';
1365 1365
 
1366 1366
 			if ($nboflines > 1 && is_object($object)) {
1367
-				if (! empty($conf->use_javascript_ajax) && $permtoeditline) {
1367
+				if (!empty($conf->use_javascript_ajax) && $permtoeditline) {
1368 1368
 					$table_element_line = 'ecm_files';
1369
-					include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
1369
+					include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php';
1370 1370
 				}
1371 1371
 			}
1372 1372
 
1373 1373
 			print ajax_autoselect('downloadlink');
1374 1374
 
1375
-			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
1375
+			if (GETPOST('action', 'aZ09') == 'editfile' && $permtoeditline)
1376 1376
 			{
1377 1377
 				print '</form>';
1378 1378
 			}
@@ -1401,7 +1401,7 @@  discard block
 block discarded – undo
1401 1401
 	 *  @return int                 		<0 if KO, nb of files shown if OK
1402 1402
 	 *  @see list_of_documents
1403 1403
 	 */
1404
-	function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload=0, $relativepath='', $permtodelete=1, $useinecm=0, $textifempty='', $maxlength=0, $url='', $addfilterfields=0)
1404
+	function list_of_autoecmfiles($upload_dir, $filearray, $modulepart, $param, $forcedownload = 0, $relativepath = '', $permtodelete = 1, $useinecm = 0, $textifempty = '', $maxlength = 0, $url = '', $addfilterfields = 0)
1405 1405
 	{
1406 1406
         // phpcs:enable
1407 1407
 		global $user, $conf, $langs, $form;
@@ -1412,9 +1412,9 @@  discard block
 block discarded – undo
1412 1412
 
1413 1413
 		// Show list of documents
1414 1414
 		if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1415
-		if (empty($url)) $url=$_SERVER["PHP_SELF"];
1415
+		if (empty($url)) $url = $_SERVER["PHP_SELF"];
1416 1416
 
1417
-		if (! empty($addfilterfields))
1417
+		if (!empty($addfilterfields))
1418 1418
 		{
1419 1419
 			print '<form action="'.$_SERVER['PHP_SELF'].'">';
1420 1420
 			print '<input type="hidden" name="module" value="'.$modulepart.'">';
@@ -1423,7 +1423,7 @@  discard block
 block discarded – undo
1423 1423
 		print '<div class="div-table-responsive-no-min">';
1424 1424
 		print '<table width="100%" class="noborder">'."\n";
1425 1425
 
1426
-		if (! empty($addfilterfields))
1426
+		if (!empty($addfilterfields))
1427 1427
 		{
1428 1428
 			print '<tr class="liste_titre nodrag nodrop">';
1429 1429
 			print '<td></td>';
@@ -1432,135 +1432,135 @@  discard block
 block discarded – undo
1432 1432
 			print '<td></td>';
1433 1433
 			// Action column
1434 1434
 			print '<td class="liste_titre" align="middle">';
1435
-			$searchpicto=$form->showFilterButtons();
1435
+			$searchpicto = $form->showFilterButtons();
1436 1436
 			print $searchpicto;
1437 1437
 			print '</td>';
1438 1438
 			print "</tr>\n";
1439 1439
 		}
1440 1440
 
1441 1441
 		print '<tr class="liste_titre">';
1442
-		$sortref="fullname";
1443
-		if ($modulepart == 'invoice_supplier') $sortref='level1name';
1444
-		print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1445
-		print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1446
-		print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1447
-		print_liste_field_titre("Date",$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1448
-		print_liste_field_titre('','','');
1442
+		$sortref = "fullname";
1443
+		if ($modulepart == 'invoice_supplier') $sortref = 'level1name';
1444
+		print_liste_field_titre("Ref", $url, $sortref, "", $param, 'align="left"', $sortfield, $sortorder);
1445
+		print_liste_field_titre("Documents2", $url, "name", "", $param, 'align="left"', $sortfield, $sortorder);
1446
+		print_liste_field_titre("Size", $url, "size", "", $param, 'align="right"', $sortfield, $sortorder);
1447
+		print_liste_field_titre("Date", $url, "date", "", $param, 'align="center"', $sortfield, $sortorder);
1448
+		print_liste_field_titre('', '', '');
1449 1449
 		print '</tr>'."\n";
1450 1450
 
1451 1451
 		// To show ref or specific information according to view to show (defined by $module)
1452 1452
 		if ($modulepart == 'company')
1453 1453
 		{
1454 1454
 			include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1455
-			$object_instance=new Societe($this->db);
1455
+			$object_instance = new Societe($this->db);
1456 1456
 		}
1457 1457
 		else if ($modulepart == 'invoice')
1458 1458
 		{
1459 1459
 			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1460
-			$object_instance=new Facture($this->db);
1460
+			$object_instance = new Facture($this->db);
1461 1461
 		}
1462 1462
 		else if ($modulepart == 'invoice_supplier')
1463 1463
 		{
1464 1464
 			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1465
-			$object_instance=new FactureFournisseur($this->db);
1465
+			$object_instance = new FactureFournisseur($this->db);
1466 1466
 		}
1467 1467
 		else if ($modulepart == 'propal')
1468 1468
 		{
1469 1469
 			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1470
-			$object_instance=new Propal($this->db);
1470
+			$object_instance = new Propal($this->db);
1471 1471
 		}
1472 1472
 		else if ($modulepart == 'supplier_proposal')
1473 1473
 		{
1474 1474
 			include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1475
-			$object_instance=new SupplierProposal($this->db);
1475
+			$object_instance = new SupplierProposal($this->db);
1476 1476
 		}
1477 1477
 		else if ($modulepart == 'order')
1478 1478
 		{
1479 1479
 			include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1480
-			$object_instance=new Commande($this->db);
1480
+			$object_instance = new Commande($this->db);
1481 1481
 		}
1482 1482
 		else if ($modulepart == 'order_supplier')
1483 1483
 		{
1484 1484
 			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1485
-			$object_instance=new CommandeFournisseur($this->db);
1485
+			$object_instance = new CommandeFournisseur($this->db);
1486 1486
 		}
1487 1487
 		else if ($modulepart == 'contract')
1488 1488
 		{
1489 1489
 			include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1490
-			$object_instance=new Contrat($this->db);
1490
+			$object_instance = new Contrat($this->db);
1491 1491
 		}
1492 1492
 		else if ($modulepart == 'product')
1493 1493
 		{
1494 1494
 			include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1495
-			$object_instance=new Product($this->db);
1495
+			$object_instance = new Product($this->db);
1496 1496
 		}
1497 1497
 		else if ($modulepart == 'tax')
1498 1498
 		{
1499 1499
 			include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1500
-			$object_instance=new ChargeSociales($this->db);
1500
+			$object_instance = new ChargeSociales($this->db);
1501 1501
 		}
1502 1502
 		else if ($modulepart == 'project')
1503 1503
 		{
1504 1504
 			include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1505
-			$object_instance=new Project($this->db);
1505
+			$object_instance = new Project($this->db);
1506 1506
 		}
1507 1507
 		else if ($modulepart == 'fichinter')
1508 1508
 		{
1509 1509
 			include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1510
-			$object_instance=new Fichinter($this->db);
1510
+			$object_instance = new Fichinter($this->db);
1511 1511
 		}
1512 1512
 		else if ($modulepart == 'user')
1513 1513
 		{
1514 1514
 			include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1515
-			$object_instance=new User($this->db);
1515
+			$object_instance = new User($this->db);
1516 1516
 		}
1517 1517
 		else if ($modulepart == 'expensereport')
1518 1518
 		{
1519 1519
 			include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1520
-			$object_instance=new ExpenseReport($this->db);
1520
+			$object_instance = new ExpenseReport($this->db);
1521 1521
 		}
1522 1522
 		else if ($modulepart == 'holiday')
1523 1523
 		{
1524 1524
 			include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
1525
-			$object_instance=new Holiday($this->db);
1525
+			$object_instance = new Holiday($this->db);
1526 1526
 		}
1527 1527
 
1528
-		foreach($filearray as $key => $file)
1528
+		foreach ($filearray as $key => $file)
1529 1529
 		{
1530 1530
 			if (!is_dir($file['name'])
1531 1531
 			&& $file['name'] != '.'
1532 1532
 			&& $file['name'] != '..'
1533 1533
 			&& $file['name'] != 'CVS'
1534
-			&& ! preg_match('/\.meta$/i',$file['name']))
1534
+			&& !preg_match('/\.meta$/i', $file['name']))
1535 1535
 			{
1536 1536
 				// Define relative path used to store the file
1537
-				$relativefile=preg_replace('/'.preg_quote($upload_dir.'/','/').'/','',$file['fullname']);
1537
+				$relativefile = preg_replace('/'.preg_quote($upload_dir.'/', '/').'/', '', $file['fullname']);
1538 1538
 
1539 1539
 				//var_dump($file);
1540
-				$id=0; $ref=''; $label='';
1540
+				$id = 0; $ref = ''; $label = '';
1541 1541
 
1542 1542
 				// To show ref or specific information according to view to show (defined by $module)
1543
-				if ($modulepart == 'company')           { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1544
-				if ($modulepart == 'invoice')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1545
-				if ($modulepart == 'invoice_supplier')  { preg_match('/([^\/]+)\/[^\/]+$/',$relativefile,$reg); $ref=(isset($reg[1])?$reg[1]:''); if (is_numeric($ref)) { $id=$ref; $ref=''; } }	// $ref may be also id with old supplier invoices
1546
-				if ($modulepart == 'propal')            { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1547
-				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1548
-				if ($modulepart == 'order')             { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1549
-				if ($modulepart == 'order_supplier')    { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1550
-				if ($modulepart == 'contract')          { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1551
-				if ($modulepart == 'product')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:''); }
1552
-				if ($modulepart == 'tax')               { preg_match('/(\d+)\/[^\/]+$/',$relativefile,$reg); $id=(isset($reg[1])?$reg[1]:''); }
1553
-				if ($modulepart == 'project')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1554
-				if ($modulepart == 'fichinter')         { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1555
-				if ($modulepart == 'user')              { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1556
-				if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1557
-				if ($modulepart == 'holiday')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1558
-
1559
-				if (! $id && ! $ref) continue;
1560
-				$found=0;
1561
-				if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1543
+				if ($modulepart == 'company') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1544
+				if ($modulepart == 'invoice') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1545
+				if ($modulepart == 'invoice_supplier') { preg_match('/([^\/]+)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); if (is_numeric($ref)) { $id = $ref; $ref = ''; } }	// $ref may be also id with old supplier invoices
1546
+				if ($modulepart == 'propal') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1547
+				if ($modulepart == 'supplier_proposal') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1548
+				if ($modulepart == 'order') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1549
+				if ($modulepart == 'order_supplier') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1550
+				if ($modulepart == 'contract') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1551
+				if ($modulepart == 'product') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1552
+				if ($modulepart == 'tax') { preg_match('/(\d+)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1553
+				if ($modulepart == 'project') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1554
+				if ($modulepart == 'fichinter') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1555
+				if ($modulepart == 'user') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1556
+				if ($modulepart == 'expensereport') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $ref = (isset($reg[1]) ? $reg[1] : ''); }
1557
+				if ($modulepart == 'holiday') { preg_match('/(.*)\/[^\/]+$/', $relativefile, $reg); $id = (isset($reg[1]) ? $reg[1] : ''); }
1558
+
1559
+				if (!$id && !$ref) continue;
1560
+				$found = 0;
1561
+				if (!empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1562 1562
 				{
1563
-					$found=1;
1563
+					$found = 1;
1564 1564
 				}
1565 1565
 				else
1566 1566
 				{
@@ -1579,24 +1579,24 @@  discard block
 block discarded – undo
1579 1579
 					}
1580 1580
 
1581 1581
 					if ($result > 0) {  // Save object into a cache
1582
-						$found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1582
+						$found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = clone $object_instance;
1583 1583
 					}
1584
-					if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1584
+					if ($result == 0) { $found = 1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref] = 'notfound'; unset($filearray[$key]); }
1585 1585
 				}
1586 1586
 
1587
-				if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1587
+				if (!$found > 0 || !is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue; // We do not show orphelins files
1588 1588
 
1589 1589
 				print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1590 1590
 				print '<tr class="oddeven">';
1591 1591
 				print '<td>';
1592
-				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1593
-				else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1592
+				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1, 'document');
1593
+				else print $langs->trans("ObjectDeleted", ($id ? $id : $ref));
1594 1594
 
1595 1595
 				//$modulesubdir=dol_sanitizeFileName($ref);
1596
-				$modulesubdir=dirname($relativefile);
1596
+				$modulesubdir = dirname($relativefile);
1597 1597
 
1598 1598
 				//$filedir=$conf->$modulepart->dir_output . '/' . dol_sanitizeFileName($obj->ref);
1599
-				$filedir=$file['path'];
1599
+				$filedir = $file['path'];
1600 1600
 				//$urlsource=$_SERVER['PHP_SELF'].'?id='.$obj->rowid;
1601 1601
 				//print $formfile->getDocumentsLink($modulepart, $filename, $filedir);
1602 1602
 
@@ -1608,16 +1608,16 @@  discard block
 block discarded – undo
1608 1608
 				print '<a href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1609 1609
 				if ($forcedownload) print '&attachment=1';
1610 1610
 				print '&file='.urlencode($relativefile).'">';
1611
-				print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')');
1612
-				print dol_trunc($file['name'],$maxlength,'middle');
1611
+				print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'], 0, 0).')');
1612
+				print dol_trunc($file['name'], $maxlength, 'middle');
1613 1613
 				print '</a>';
1614 1614
 
1615 1615
 				//print $this->getDocumentsLink($modulepart, $modulesubdir, $filedir, '^'.preg_quote($file['name'],'/').'$');
1616 1616
 				print $this->showPreview($file, $modulepart, $file['relativename']);
1617 1617
 
1618 1618
 				print "</td>\n";
1619
-				print '<td align="right">'.dol_print_size($file['size'],1,1).'</td>';
1620
-				print '<td align="center">'.dol_print_date($file['date'],"dayhour").'</td>';
1619
+				print '<td align="right">'.dol_print_size($file['size'], 1, 1).'</td>';
1620
+				print '<td align="center">'.dol_print_date($file['date'], "dayhour").'</td>';
1621 1621
 				print '<td align="right">';
1622 1622
 				//if (! empty($useinecm))  print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1623 1623
 				//if ($forcedownload) print '&attachment=1';
@@ -1639,7 +1639,7 @@  discard block
 block discarded – undo
1639 1639
 		print "</table>";
1640 1640
 		print '</div>';
1641 1641
 
1642
-		if (! empty($addfilterfields)) print '</form>';
1642
+		if (!empty($addfilterfields)) print '</form>';
1643 1643
 		// Fin de zone
1644 1644
 	}
1645 1645
 
@@ -1665,7 +1665,7 @@  discard block
 block discarded – undo
1665 1665
 		$mul_upload_max_filesize	= ($mul_upload_max_filesize == 'M' ? 1048576 : ($mul_upload_max_filesize == 'K' ? 1024 : ($mul_upload_max_filesize == 'G' ? 1073741824 : 1)));
1666 1666
 		$upload_max_filesize		= $mul_upload_max_filesize * (int) $upload_max_filesize;
1667 1667
 		// Max file size
1668
-		$max_file_size 				= (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1668
+		$max_file_size = (($post_max_size < $upload_max_filesize) ? $post_max_size : $upload_max_filesize);
1669 1669
 
1670 1670
 		// Include main
1671 1671
 		include DOL_DOCUMENT_ROOT.'/core/tpl/ajax/fileupload_main.tpl.php';
@@ -1684,14 +1684,14 @@  discard block
 block discarded – undo
1684 1684
 	 * @param	string		$param			More param to add into URL
1685 1685
 	 * @return 	int							Number of links
1686 1686
 	 */
1687
-	public function listOfLinks($object, $permtodelete=1, $action=null, $selected=null, $param='')
1687
+	public function listOfLinks($object, $permtodelete = 1, $action = null, $selected = null, $param = '')
1688 1688
 	{
1689 1689
 		global $user, $conf, $langs, $user;
1690 1690
 		global $sortfield, $sortorder;
1691 1691
 
1692 1692
 		$langs->load("link");
1693 1693
 
1694
-		require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
1694
+		require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
1695 1695
 		$link = new Link($this->db);
1696 1696
 		$links = array();
1697 1697
 		if ($sortfield == "name") {
@@ -1702,12 +1702,12 @@  discard block
 block discarded – undo
1702 1702
 			$sortfield = null;
1703 1703
 		}
1704 1704
 		$res = $link->fetchAll($links, $object->element, $object->id, $sortfield, $sortorder);
1705
-		$param .= (isset($object->id)?'&id=' . $object->id : '');
1705
+		$param .= (isset($object->id) ? '&id='.$object->id : '');
1706 1706
 
1707 1707
 		// Show list of associated links
1708 1708
 		print load_fiche_titre($langs->trans("LinkedFiles"));
1709 1709
 
1710
-		print '<form action="' . $_SERVER['PHP_SELF'] . ($param?'?'.$param:'') . '" method="POST">';
1710
+		print '<form action="'.$_SERVER['PHP_SELF'].($param ? '?'.$param : '').'" method="POST">';
1711 1711
 
1712 1712
 		print '<table width="100%" class="liste">';
1713 1713
 		print '<tr class="liste_titre">';
@@ -1747,7 +1747,7 @@  discard block
 block discarded – undo
1747 1747
 			$param,
1748 1748
 			'align="center"'
1749 1749
 		);
1750
-		print_liste_field_titre('','','');
1750
+		print_liste_field_titre('', '', '');
1751 1751
 		print '</tr>';
1752 1752
 		$nboflinks = count($links);
1753 1753
 		if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
@@ -1759,36 +1759,36 @@  discard block
 block discarded – undo
1759 1759
 			if ($action == 'update' && $selected === $link->id)
1760 1760
 			{
1761 1761
 				print '<td>';
1762
-				print '<input type="hidden" name="id" value="' . $object->id . '">';
1763
-				print '<input type="hidden" name="linkid" value="' . $link->id . '">';
1762
+				print '<input type="hidden" name="id" value="'.$object->id.'">';
1763
+				print '<input type="hidden" name="linkid" value="'.$link->id.'">';
1764 1764
 				print '<input type="hidden" name="action" value="confirm_updateline">';
1765
-				print $langs->trans('Link') . ': <input type="text" name="link" value="' . $link->url . '">';
1765
+				print $langs->trans('Link').': <input type="text" name="link" value="'.$link->url.'">';
1766 1766
 				print '</td>';
1767 1767
 				print '<td>';
1768
-				print $langs->trans('Label') . ': <input type="text" name="label" value="' . $link->label . '">';
1768
+				print $langs->trans('Label').': <input type="text" name="label" value="'.$link->label.'">';
1769 1769
 				print '</td>';
1770
-				print '<td align="center">' . dol_print_date(dol_now(), "dayhour", "tzuser") . '</td>';
1770
+				print '<td align="center">'.dol_print_date(dol_now(), "dayhour", "tzuser").'</td>';
1771 1771
 				print '<td align="right"></td>';
1772 1772
 				print '<td align="right">';
1773
-				print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1774
-				print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1773
+				print '<input type="submit" name="save" class="button" value="'.dol_escape_htmltag($langs->trans('Save')).'">';
1774
+				print '<input type="submit" name="cancel" class="button" value="'.dol_escape_htmltag($langs->trans('Cancel')).'">';
1775 1775
 				print '</td>';
1776 1776
 			}
1777 1777
 			else
1778 1778
 			{
1779 1779
 				print '<td>';
1780 1780
 				print img_picto('', 'object_globe').' ';
1781
-				print '<a data-ajax="false" href="' . $link->url . '" target="_blank">';
1781
+				print '<a data-ajax="false" href="'.$link->url.'" target="_blank">';
1782 1782
 				print $link->label;
1783 1783
 				print '</a>';
1784 1784
 				print '</td>'."\n";
1785 1785
 				print '<td align="right"></td>';
1786
-				print '<td align="center">' . dol_print_date($link->datea, "dayhour", "tzuser") . '</td>';
1786
+				print '<td align="center">'.dol_print_date($link->datea, "dayhour", "tzuser").'</td>';
1787 1787
 				print '<td align="center"></td>';
1788 1788
 				print '<td align="right">';
1789
-				print '<a href="' . $_SERVER['PHP_SELF'] . '?action=update&linkid=' . $link->id . $param . '" class="editfilelink" >' . img_edit() . '</a>';	// id= is included into $param
1789
+				print '<a href="'.$_SERVER['PHP_SELF'].'?action=update&linkid='.$link->id.$param.'" class="editfilelink" >'.img_edit().'</a>'; // id= is included into $param
1790 1790
 				if ($permtodelete) {
1791
-					print ' &nbsp; <a href="'. $_SERVER['PHP_SELF'] .'?action=delete&linkid=' . $link->id . $param . '" class="deletefilelink">' . img_delete() . '</a>';	// id= is included into $param
1791
+					print ' &nbsp; <a href="'.$_SERVER['PHP_SELF'].'?action=delete&linkid='.$link->id.$param.'" class="deletefilelink">'.img_delete().'</a>'; // id= is included into $param
1792 1792
 				} else {
1793 1793
 					print '&nbsp;';
1794 1794
 				}
@@ -1820,25 +1820,25 @@  discard block
 block discarded – undo
1820 1820
 	 * @param	string	  $param		  More param on http links
1821 1821
 	 * @return  string    $out            Output string with HTML
1822 1822
 	 */
1823
-	public function showPreview($file, $modulepart, $relativepath, $ruleforpicto=0, $param='')
1823
+	public function showPreview($file, $modulepart, $relativepath, $ruleforpicto = 0, $param = '')
1824 1824
 	{
1825 1825
 		global $langs, $conf;
1826 1826
 
1827
-		$out='';
1828
-		if ($conf->browser->layout != 'phone' && ! empty($conf->use_javascript_ajax))
1827
+		$out = '';
1828
+		if ($conf->browser->layout != 'phone' && !empty($conf->use_javascript_ajax))
1829 1829
 		{
1830
-			$urladvancedpreview=getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param);      // Return if a file is qualified for preview.
1830
+			$urladvancedpreview = getAdvancedPreviewUrl($modulepart, $relativepath, 1, $param); // Return if a file is qualified for preview.
1831 1831
 			if (count($urladvancedpreview))
1832 1832
 			{
1833
-				$out.= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime'])?'':' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target'])?'':' target="'.$urladvancedpreview['target'].'"').'>';
1833
+				$out .= '<a class="pictopreview '.$urladvancedpreview['css'].'" href="'.$urladvancedpreview['url'].'"'.(empty($urladvancedpreview['mime']) ? '' : ' mime="'.$urladvancedpreview['mime'].'"').' '.(empty($urladvancedpreview['target']) ? '' : ' target="'.$urladvancedpreview['target'].'"').'>';
1834 1834
 				//$out.= '<a class="pictopreview">';
1835 1835
 				if (empty($ruleforpicto))
1836 1836
 				{
1837 1837
 					//$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1838
-					$out.='<span class="fa fa-search-plus" style="color: gray"></span>';
1838
+					$out .= '<span class="fa fa-search-plus" style="color: gray"></span>';
1839 1839
 				}
1840
-				else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1841
-				$out.= '</a>';
1840
+				else $out .= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1841
+				$out .= '</a>';
1842 1842
 			}
1843 1843
 		}
1844 1844
 		return $out;
Please login to merge, or discard this patch.
Braces   +404 added lines, -255 removed lines patch added patch discarded remove patch
@@ -84,7 +84,9 @@  discard block
 block discarded – undo
84 84
 		$hookmanager->initHooks(array('formfile'));
85 85
 
86 86
 
87
-		if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $useajax=0;
87
+		if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
88
+		    $useajax=0;
89
+		}
88 90
 
89 91
 		if ((! empty($conf->global->MAIN_USE_JQUERY_FILEUPLOAD) && $useajax) || ($useajax==2))
90 92
 		{
@@ -93,8 +95,7 @@  discard block
 block discarded – undo
93 95
 			// TODO: This does not support option savingdocmask
94 96
 			// TODO: This break feature to upload links too
95 97
 			return $this->_formAjaxFileUpload($object);
96
-		}
97
-		else
98
+		} else
98 99
 	   	{
99 100
 			//If there is no permission and the option to hide unauthorized actions is enabled, then nothing is printed
100 101
 			if (!$perm && !empty($conf->global->MAIN_BUTTON_HIDE_UNAUTHORIZED)) {
@@ -105,8 +106,12 @@  discard block
 block discarded – undo
105 106
 
106 107
 			$out = "\n\n<!-- Start form attach new file -->\n";
107 108
 
108
-			if (empty($title)) $title=$langs->trans("AttachANewFile");
109
-			if ($title != 'none') $out.=load_fiche_titre($title, null, null);
109
+			if (empty($title)) {
110
+			    $title=$langs->trans("AttachANewFile");
111
+			}
112
+			if ($title != 'none') {
113
+			    $out.=load_fiche_titre($title, null, null);
114
+			}
110 115
 
111 116
 			$out .= '<form name="'.$htmlname.'" id="'.$htmlname.'" action="'.$url.'" enctype="multipart/form-data" method="POST">';
112 117
 			$out .= '<input type="hidden" id="'.$htmlname.'_section_dir" name="section_dir" value="'.$sectiondir.'">';
@@ -116,19 +121,31 @@  discard block
 block discarded – undo
116 121
 			$out .= '<table width="100%" class="nobordernopadding">';
117 122
 			$out .= '<tr>';
118 123
 
119
-			if (! empty($options)) $out .= '<td>'.$options.'</td>';
124
+			if (! empty($options)) {
125
+			    $out .= '<td>'.$options.'</td>';
126
+			}
120 127
 
121 128
 			$out .= '<td class="valignmiddle nowrap">';
122 129
 
123 130
 			$max=$conf->global->MAIN_UPLOAD_DOC;		// En Kb
124 131
 			$maxphp=@ini_get('upload_max_filesize');	// En inconnu
125
-			if (preg_match('/k$/i',$maxphp)) $maxphp=$maxphp*1;
126
-			if (preg_match('/m$/i',$maxphp)) $maxphp=$maxphp*1024;
127
-			if (preg_match('/g$/i',$maxphp)) $maxphp=$maxphp*1024*1024;
128
-			if (preg_match('/t$/i',$maxphp)) $maxphp=$maxphp*1024*1024*1024;
132
+			if (preg_match('/k$/i',$maxphp)) {
133
+			    $maxphp=$maxphp*1;
134
+			}
135
+			if (preg_match('/m$/i',$maxphp)) {
136
+			    $maxphp=$maxphp*1024;
137
+			}
138
+			if (preg_match('/g$/i',$maxphp)) {
139
+			    $maxphp=$maxphp*1024*1024;
140
+			}
141
+			if (preg_match('/t$/i',$maxphp)) {
142
+			    $maxphp=$maxphp*1024*1024*1024;
143
+			}
129 144
 			// Now $max and $maxphp are in Kb
130 145
 			$maxmin = $max;
131
-			if ($maxphp > 0) $maxmin=min($max,$maxphp);
146
+			if ($maxphp > 0) {
147
+			    $maxmin=min($max,$maxphp);
148
+			}
132 149
 
133 150
 			if ($maxmin > 0)
134 151
 			{
@@ -160,8 +177,7 @@  discard block
 block discarded – undo
160 177
 					$out .= ' ';
161 178
 					$out .= info_admin($langs->trans("ThisLimitIsDefinedInSetup",$max,$maxphp),1);
162 179
 				}
163
-			}
164
-			else
180
+			} else
165 181
 			{
166 182
 				$out .= ' ('.$langs->trans("UploadDisabled").')';
167 183
 			}
@@ -170,7 +186,9 @@  discard block
 block discarded – undo
170 186
 			if ($savingdocmask)
171 187
 			{
172 188
 				$out .= '<tr>';
173
-   				if (! empty($options)) $out .= '<td>'.$options.'</td>';
189
+   				if (! empty($options)) {
190
+   				    $out .= '<td>'.$options.'</td>';
191
+   				}
174 192
 				$out .= '<td valign="middle" class="nowrap">';
175 193
 				$out .= '<input type="checkbox" checked class="savingdocmask" name="savingdocmask" value="'.dol_escape_js($savingdocmask).'"> '.$langs->trans("SaveUploadedFileWithMask", preg_replace('/__file__/',$langs->transnoentitiesnoconv("OriginFileName"),$savingdocmask), $langs->transnoentitiesnoconv("OriginFileName"));
176 194
 				$out .= '</td>';
@@ -180,7 +198,9 @@  discard block
 block discarded – undo
180 198
 			$out .= "</table>";
181 199
 
182 200
 			$out .= '</form>';
183
-			if (empty($sectionid)) $out .= '<br>';
201
+			if (empty($sectionid)) {
202
+			    $out .= '<br>';
203
+			}
184 204
 
185 205
 			$out .= "\n<!-- End form attach new file -->\n";
186 206
 
@@ -197,11 +217,15 @@  discard block
 block discarded – undo
197 217
 
198 218
 				$out .= '<div class="valignmiddle" >';
199 219
 				$out .= '<div class="inline-block" style="padding-right: 10px;">';
200
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
220
+				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
221
+				    $out .= '<label for="link">'.$langs->trans("URLToLink") . ':</label> ';
222
+				}
201 223
 				$out .= '<input type="text" name="link" class="flat minwidth400imp" id="link" placeholder="'.dol_escape_htmltag($langs->trans("URLToLink")).'">';
202 224
 				$out .= '</div>';
203 225
 				$out .= '<div class="inline-block" style="padding-right: 10px;">';
204
-				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
226
+				if (! empty($conf->global->OPTIMIZEFORTEXTBROWSER)) {
227
+				    $out .= '<label for="label">'.$langs->trans("Label") . ':</label> ';
228
+				}
205 229
 				$out .= '<input type="text" class="flat" name="label" id="label" placeholder="'.dol_escape_htmltag($langs->trans("Label")).'">';
206 230
 				$out .= '<input type="hidden" name="objecttype" value="' . $object->element . '">';
207 231
 				$out .= '<input type="hidden" name="objectid" value="' . $object->id . '">';
@@ -298,7 +322,9 @@  discard block
 block discarded – undo
298 322
 		global $langs, $conf, $user, $hookmanager;
299 323
 		global $form;
300 324
 
301
-		if (! is_object($form)) $form=new Form($this->db);
325
+		if (! is_object($form)) {
326
+		    $form=new Form($this->db);
327
+		}
302 328
 
303 329
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
304 330
 
@@ -311,10 +337,12 @@  discard block
 block discarded – undo
311 337
 		$param.= 'entity='.(!empty($object->entity)?$object->entity:$conf->entity);
312 338
 
313 339
 		$printer=0;
314
-		if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport','livraison')))	// The direct print feature is implemented only for such elements
340
+		if (in_array($modulepart,array('facture','supplier_proposal','propal','proposal','order','commande','expedition', 'commande_fournisseur', 'expensereport','livraison'))) {
341
+		    // The direct print feature is implemented only for such elements
315 342
 		{
316 343
 			$printer = (!empty($user->rights->printing->read) && !empty($conf->printing->enabled))?true:false;
317 344
 		}
345
+		}
318 346
 
319 347
 		$hookmanager->initHooks(array('formfile'));
320 348
 
@@ -324,7 +352,9 @@  discard block
 block discarded – undo
324 352
 		{
325 353
 			$file_list=dol_dir_list($filedir,'files',0,'','(\.meta|_preview.*.*\.png)$','date',SORT_DESC);
326 354
 		}
327
-		if ($hideifempty && empty($file_list)) return '';
355
+		if ($hideifempty && empty($file_list)) {
356
+		    return '';
357
+		}
328 358
 
329 359
 		$out='';
330 360
 		$forname='builddoc';
@@ -361,7 +391,9 @@  discard block
 block discarded – undo
361 391
 		}
362 392
 
363 393
 		$titletoshow=$langs->trans("Documents");
364
-		if (! empty($title)) $titletoshow=$title;
394
+		if (! empty($title)) {
395
+		    $titletoshow=$title;
396
+		}
365 397
 
366 398
 		// Show table
367 399
 		if ($genallowed)
@@ -371,252 +403,251 @@  discard block
 block discarded – undo
371 403
 			if ($modulepart == 'company')
372 404
 			{
373 405
 				$showempty=1;
374
-				if (is_array($genallowed)) $modellist=$genallowed;
375
-				else
406
+				if (is_array($genallowed)) {
407
+				    $modellist=$genallowed;
408
+				} else
376 409
 				{
377 410
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/societe/modules_societe.class.php';
378 411
 					$modellist=ModeleThirdPartyDoc::liste_modeles($this->db);
379 412
 				}
380
-			}
381
-			else if ($modulepart == 'propal')
413
+			} else if ($modulepart == 'propal')
382 414
 			{
383
-				if (is_array($genallowed)) $modellist=$genallowed;
384
-				else
415
+				if (is_array($genallowed)) {
416
+				    $modellist=$genallowed;
417
+				} else
385 418
 				{
386 419
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
387 420
 					$modellist=ModelePDFPropales::liste_modeles($this->db);
388 421
 				}
389
-			}
390
-			else if ($modulepart == 'supplier_proposal')
422
+			} else if ($modulepart == 'supplier_proposal')
391 423
 			{
392
-				if (is_array($genallowed)) $modellist=$genallowed;
393
-				else
424
+				if (is_array($genallowed)) {
425
+				    $modellist=$genallowed;
426
+				} else
394 427
 				{
395 428
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_proposal/modules_supplier_proposal.php';
396 429
 					$modellist=ModelePDFSupplierProposal::liste_modeles($this->db);
397 430
 				}
398
-			}
399
-			else if ($modulepart == 'commande')
431
+			} else if ($modulepart == 'commande')
400 432
 			{
401
-				if (is_array($genallowed)) $modellist=$genallowed;
402
-				else
433
+				if (is_array($genallowed)) {
434
+				    $modellist=$genallowed;
435
+				} else
403 436
 				{
404 437
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/commande/modules_commande.php';
405 438
 					$modellist=ModelePDFCommandes::liste_modeles($this->db);
406 439
 				}
407
-			}
408
-			elseif ($modulepart == 'expedition')
440
+			} elseif ($modulepart == 'expedition')
409 441
 			{
410
-				if (is_array($genallowed)) $modellist=$genallowed;
411
-				else
442
+				if (is_array($genallowed)) {
443
+				    $modellist=$genallowed;
444
+				} else
412 445
 				{
413 446
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/expedition/modules_expedition.php';
414 447
 					$modellist=ModelePDFExpedition::liste_modeles($this->db);
415 448
 				}
416
-			}
417
-            elseif ($modulepart == 'reception')
449
+			} elseif ($modulepart == 'reception')
418 450
             {
419
-                if (is_array($genallowed)) $modellist=$genallowed;
420
-                else
451
+                if (is_array($genallowed)) {
452
+                    $modellist=$genallowed;
453
+                } else
421 454
                 {
422 455
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/reception/modules_reception.php';
423 456
 					$modellist = ModelePdfReception::liste_modeles($this->db);
424 457
 				}
425
-            }
426
-			elseif ($modulepart == 'livraison')
458
+            } elseif ($modulepart == 'livraison')
427 459
 			{
428
-				if (is_array($genallowed)) $modellist=$genallowed;
429
-				else
460
+				if (is_array($genallowed)) {
461
+				    $modellist=$genallowed;
462
+				} else
430 463
 				{
431 464
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/livraison/modules_livraison.php';
432 465
 					$modellist=ModelePDFDeliveryOrder::liste_modeles($this->db);
433 466
 				}
434
-			}
435
-			else if ($modulepart == 'ficheinter')
467
+			} else if ($modulepart == 'ficheinter')
436 468
 			{
437
-				if (is_array($genallowed)) $modellist=$genallowed;
438
-				else
469
+				if (is_array($genallowed)) {
470
+				    $modellist=$genallowed;
471
+				} else
439 472
 				{
440 473
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php';
441 474
 					$modellist=ModelePDFFicheinter::liste_modeles($this->db);
442 475
 				}
443
-			}
444
-			elseif ($modulepart == 'facture')
476
+			} elseif ($modulepart == 'facture')
445 477
 			{
446
-				if (is_array($genallowed)) $modellist=$genallowed;
447
-				else
478
+				if (is_array($genallowed)) {
479
+				    $modellist=$genallowed;
480
+				} else
448 481
 				{
449 482
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
450 483
 					$modellist=ModelePDFFactures::liste_modeles($this->db);
451 484
 				}
452
-			}
453
-			elseif ($modulepart == 'contract')
485
+			} elseif ($modulepart == 'contract')
454 486
 			{
455
-				if (is_array($genallowed)) $modellist=$genallowed;
456
-				else
487
+				if (is_array($genallowed)) {
488
+				    $modellist=$genallowed;
489
+				} else
457 490
 				{
458 491
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php';
459 492
 					$modellist=ModelePDFContract::liste_modeles($this->db);
460 493
 				}
461
-			}
462
-			elseif ($modulepart == 'project')
494
+			} elseif ($modulepart == 'project')
463 495
 			{
464
-				if (is_array($genallowed)) $modellist=$genallowed;
465
-				else
496
+				if (is_array($genallowed)) {
497
+				    $modellist=$genallowed;
498
+				} else
466 499
 				{
467 500
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/modules_project.php';
468 501
 					$modellist=ModelePDFProjects::liste_modeles($this->db);
469 502
 				}
470
-			}
471
-			elseif ($modulepart == 'project_task')
503
+			} elseif ($modulepart == 'project_task')
472 504
 			{
473
-				if (is_array($genallowed)) $modellist=$genallowed;
474
-				else
505
+				if (is_array($genallowed)) {
506
+				    $modellist=$genallowed;
507
+				} else
475 508
 				{
476 509
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/project/task/modules_task.php';
477 510
 					$modellist=ModelePDFTask::liste_modeles($this->db);
478 511
 				}
479
-			}
480
-			elseif ($modulepart == 'product')
512
+			} elseif ($modulepart == 'product')
481 513
 			{
482
-				if (is_array($genallowed)) $modellist=$genallowed;
483
-				else
514
+				if (is_array($genallowed)) {
515
+				    $modellist=$genallowed;
516
+				} else
484 517
 				{
485 518
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/product/modules_product.class.php';
486 519
 					$modellist=ModelePDFProduct::liste_modeles($this->db);
487 520
 				}
488
-			}
489
-			elseif ($modulepart == 'product_batch')
521
+			} elseif ($modulepart == 'product_batch')
490 522
 			{
491
-				if (is_array($genallowed)) $modellist=$genallowed;
492
-				else
523
+				if (is_array($genallowed)) {
524
+				    $modellist=$genallowed;
525
+				} else
493 526
 				{
494 527
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/product_batch/modules_product_batch.class.php';
495 528
 					$modellist=ModelePDFProductBatch::liste_modeles($this->db);
496 529
 				}
497
-			}
498
-			elseif ($modulepart == 'stock')
530
+			} elseif ($modulepart == 'stock')
499 531
 			{
500
-				if (is_array($genallowed)) $modellist=$genallowed;
501
-				else
532
+				if (is_array($genallowed)) {
533
+				    $modellist=$genallowed;
534
+				} else
502 535
 				{
503 536
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_stock.php';
504 537
 					$modellist=ModelePDFStock::liste_modeles($this->db);
505 538
 				}
506
-			}
507
-			elseif ($modulepart == 'movement')
539
+			} elseif ($modulepart == 'movement')
508 540
 			{
509
-				if (is_array($genallowed)) $modellist=$genallowed;
510
-				else
541
+				if (is_array($genallowed)) {
542
+				    $modellist=$genallowed;
543
+				} else
511 544
 				{
512 545
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/stock/modules_movement.php';
513 546
 					$modellist=ModelePDFMovement::liste_modeles($this->db);
514 547
 				}
515
-			}
516
-			elseif ($modulepart == 'export')
548
+			} elseif ($modulepart == 'export')
517 549
 			{
518
-				if (is_array($genallowed)) $modellist=$genallowed;
519
-				else
550
+				if (is_array($genallowed)) {
551
+				    $modellist=$genallowed;
552
+				} else
520 553
 				{
521 554
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
522 555
 					$modellist=ModeleExports::liste_modeles($this->db);
523 556
 				}
524
-			}
525
-			else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
557
+			} else if ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order')
526 558
 			{
527
-				if (is_array($genallowed)) $modellist=$genallowed;
528
-				else
559
+				if (is_array($genallowed)) {
560
+				    $modellist=$genallowed;
561
+				} else
529 562
 				{
530 563
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_order/modules_commandefournisseur.php';
531 564
 					$modellist=ModelePDFSuppliersOrders::liste_modeles($this->db);
532 565
 				}
533
-			}
534
-			else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
566
+			} else if ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
535 567
 			{
536
-				if (is_array($genallowed)) $modellist=$genallowed;
537
-				else
568
+				if (is_array($genallowed)) {
569
+				    $modellist=$genallowed;
570
+				} else
538 571
 				{
539 572
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
540 573
 					$modellist=ModelePDFSuppliersInvoices::liste_modeles($this->db);
541 574
 				}
542
-			}
543
-			else if ($modulepart == 'supplier_payment')
575
+			} else if ($modulepart == 'supplier_payment')
544 576
 			{
545
-				if (is_array($genallowed)) $modellist=$genallowed;
546
-				else
577
+				if (is_array($genallowed)) {
578
+				    $modellist=$genallowed;
579
+				} else
547 580
 				{
548 581
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
549 582
 					$modellist=ModelePDFSuppliersPayments::liste_modeles($this->db);
550 583
 				}
551
-			}
552
-			else if ($modulepart == 'remisecheque')
584
+			} else if ($modulepart == 'remisecheque')
553 585
 			{
554
-				if (is_array($genallowed)) $modellist=$genallowed;
555
-				else
586
+				if (is_array($genallowed)) {
587
+				    $modellist=$genallowed;
588
+				} else
556 589
 				{
557 590
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/cheque/modules_chequereceipts.php';
558 591
 					$modellist=ModeleChequeReceipts::liste_modeles($this->db);
559 592
 				}
560
-			}
561
-			elseif ($modulepart == 'donation')
593
+			} elseif ($modulepart == 'donation')
562 594
 			{
563
-				if (is_array($genallowed)) $modellist=$genallowed;
564
-				else
595
+				if (is_array($genallowed)) {
596
+				    $modellist=$genallowed;
597
+				} else
565 598
 				{
566 599
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/dons/modules_don.php';
567 600
 					$modellist=ModeleDon::liste_modeles($this->db);
568 601
 				}
569
-			}
570
-			elseif ($modulepart == 'member')
602
+			} elseif ($modulepart == 'member')
571 603
 			{
572
-				if (is_array($genallowed)) $modellist=$genallowed;
573
-				else
604
+				if (is_array($genallowed)) {
605
+				    $modellist=$genallowed;
606
+				} else
574 607
 				{
575 608
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/member/modules_cards.php';
576 609
 					$modellist=ModelePDFCards::liste_modeles($this->db);
577 610
 				}
578
-			}
579
-			elseif ($modulepart == 'agenda' || $modulepart == 'actions')
611
+			} elseif ($modulepart == 'agenda' || $modulepart == 'actions')
580 612
 			{
581
-				if (is_array($genallowed)) $modellist=$genallowed;
582
-				else
613
+				if (is_array($genallowed)) {
614
+				    $modellist=$genallowed;
615
+				} else
583 616
 				{
584 617
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/action/modules_action.php';
585 618
 					$modellist=ModeleAction::liste_modeles($this->db);
586 619
 				}
587
-			}
588
-			else if ($modulepart == 'expensereport')
620
+			} else if ($modulepart == 'expensereport')
589 621
 			{
590
-				if (is_array($genallowed)) $modellist=$genallowed;
591
-				else
622
+				if (is_array($genallowed)) {
623
+				    $modellist=$genallowed;
624
+				} else
592 625
 				{
593 626
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php';
594 627
 					$modellist=ModeleExpenseReport::liste_modeles($this->db);
595 628
 				}
596
-			}
597
-			else if ($modulepart == 'unpaid')
629
+			} else if ($modulepart == 'unpaid')
598 630
 			{
599 631
 				$modellist='';
600
-			}
601
-			elseif ($modulepart == 'user')
632
+			} elseif ($modulepart == 'user')
602 633
 			{
603
-				if (is_array($genallowed)) $modellist=$genallowed;
604
-				else
634
+				if (is_array($genallowed)) {
635
+				    $modellist=$genallowed;
636
+				} else
605 637
 				{
606 638
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/user/modules_user.class.php';
607 639
 					$modellist=ModelePDFUser::liste_modeles($this->db);
608 640
 				}
609
-			}
610
-			elseif ($modulepart == 'usergroup')
641
+			} elseif ($modulepart == 'usergroup')
611 642
 			{
612
-				if (is_array($genallowed)) $modellist=$genallowed;
613
-				else
643
+				if (is_array($genallowed)) {
644
+				    $modellist=$genallowed;
645
+				} else
614 646
 				{
615 647
 					include_once DOL_DOCUMENT_ROOT.'/core/modules/usergroup/modules_usergroup.class.php';
616 648
 					$modellist=ModelePDFUserGroup::liste_modeles($this->db);
617 649
 				}
618
-			}
619
-			else
650
+			} else
620 651
 			{
621 652
 				// For normalized standard modules
622 653
 				$file=dol_buildpath('/core/modules/'.$modulepart.'/modules_'.$modulepart.'.php',0);
@@ -634,8 +665,7 @@  discard block
 block discarded – undo
634 665
 				if (class_exists($class))
635 666
 				{
636 667
 					$modellist=call_user_func($class.'::liste_modeles',$this->db);
637
-				}
638
-				else
668
+				} else
639 669
 				{
640 670
 					dol_print_error($this->db,'Bad value for modulepart');
641 671
 					return -1;
@@ -646,10 +676,17 @@  discard block
 block discarded – undo
646 676
 			$headershown=1;
647 677
 
648 678
 			$buttonlabeltoshow=$buttonlabel;
649
-			if (empty($buttonlabel)) $buttonlabel=$langs->trans('Generate');
679
+			if (empty($buttonlabel)) {
680
+			    $buttonlabel=$langs->trans('Generate');
681
+			}
650 682
 
651
-			if ($conf->browser->layout == 'phone') $urlsource.='#'.$forname.'_form';   // So we switch to form after a generation
652
-			if (empty($noform)) $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
683
+			if ($conf->browser->layout == 'phone') {
684
+			    $urlsource.='#'.$forname.'_form';
685
+			}
686
+			// So we switch to form after a generation
687
+			if (empty($noform)) {
688
+			    $out.= '<form action="'.$urlsource.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc').'" id="'.$forname.'_form" method="post">';
689
+			}
653 690
 			$out.= '<input type="hidden" name="action" value="builddoc">';
654 691
 			$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
655 692
 
@@ -666,9 +703,11 @@  discard block
 block discarded – undo
666 703
 			if (! empty($modellist))
667 704
 			{
668 705
 				$out.= '<span class="hideonsmartphone">'.$langs->trans('Model').' </span>';
669
-				if (is_array($modellist) && count($modellist) == 1)    // If there is only one element
706
+				if (is_array($modellist) && count($modellist) == 1) {
707
+				    // If there is only one element
670 708
 				{
671 709
 					$arraykeys=array_keys($modellist);
710
+				}
672 711
 					$modelselected=$arraykeys[0];
673 712
 				}
674 713
 				$out.= $form->selectarray('model', $modellist, $modelselected, $showempty, 0, 0, '', 0, 0, 0, '', 'minwidth100');
@@ -676,8 +715,7 @@  discard block
 block discarded – undo
676 715
 				{
677 716
 					$out.= ajax_combobox('model');
678 717
 				}
679
-			}
680
-			else
718
+			} else
681 719
 			{
682 720
 				$out.= '<div class="float">'.$langs->trans("Files").'</div>';
683 721
 			}
@@ -689,10 +727,11 @@  discard block
 block discarded – undo
689 727
 				$formadmin=new FormAdmin($this->db);
690 728
 				$defaultlang=$codelang?$codelang:$langs->getDefaultLang();
691 729
 				$morecss='maxwidth150';
692
-				if ($conf->browser->layout == 'phone') $morecss='maxwidth100';
730
+				if ($conf->browser->layout == 'phone') {
731
+				    $morecss='maxwidth100';
732
+				}
693 733
 				$out.= $formadmin->select_language($defaultlang, 'lang_id', 0, 0, 0, 0, 0, $morecss);
694
-			}
695
-			else
734
+			} else
696 735
 			{
697 736
 				$out.= '&nbsp;';
698 737
 			}
@@ -700,15 +739,21 @@  discard block
 block discarded – undo
700 739
 			// Button
701 740
 			$genbutton = '<input class="button buttongen" id="'.$forname.'_generatebutton" name="'.$forname.'_generatebutton"';
702 741
 			$genbutton.= ' type="submit" value="'.$buttonlabel.'"';
703
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) $genbutton.= ' disabled';
742
+			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist)) {
743
+			    $genbutton.= ' disabled';
744
+			}
704 745
 			$genbutton.= '>';
705 746
 			if ($allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid')
706 747
 			{
707 748
 			   	$langs->load("errors");
708 749
 			   	$genbutton.= ' '.img_warning($langs->transnoentitiesnoconv("WarningNoDocumentModelActivated"));
709 750
 			}
710
-			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') $genbutton='';
711
-			if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') $genbutton='';
751
+			if (! $allowgenifempty && ! is_array($modellist) && empty($modellist) && empty($conf->dol_no_mouse_hover) && $modulepart != 'unpaid') {
752
+			    $genbutton='';
753
+			}
754
+			if (empty($modellist) && ! $showempty && $modulepart != 'unpaid') {
755
+			    $genbutton='';
756
+			}
712 757
 			$out.= $genbutton;
713 758
 			$out.= '</th>';
714 759
 
@@ -716,7 +761,9 @@  discard block
 block discarded – undo
716 761
 			{
717 762
 				foreach($hookmanager->hooks['formfile'] as $module)
718 763
 				{
719
-					if (method_exists($module, 'formBuilddocLineOptions')) $out .= '<th></th>';
764
+					if (method_exists($module, 'formBuilddocLineOptions')) {
765
+					    $out .= '<th></th>';
766
+					}
720 767
 				}
721 768
 			}
722 769
 			$out.= '</tr>';
@@ -761,19 +808,30 @@  discard block
 block discarded – undo
761 808
 				{
762 809
 					// Define relative path for download link (depends on module)
763 810
 					$relativepath=$file["name"];										// Cas general
764
-					if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
765
-					if ($modulepart == 'export') $relativepath = $file["name"];			// Other case
811
+					if ($modulesubdir) {
812
+					    $relativepath=$modulesubdir."/".$file["name"];
813
+					}
814
+					// Cas propal, facture...
815
+					if ($modulepart == 'export') {
816
+					    $relativepath = $file["name"];
817
+					}
818
+					// Other case
766 819
 
767 820
 					$out.= '<tr class="oddeven">';
768 821
 
769 822
 					$documenturl = DOL_URL_ROOT.'/document.php';
770
-					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;    // To use another wrapper
823
+					if (isset($conf->global->DOL_URL_ROOT_DOCUMENT_PHP)) {
824
+					    $documenturl=$conf->global->DOL_URL_ROOT_DOCUMENT_PHP;
825
+					}
826
+					// To use another wrapper
771 827
 
772 828
 					// Show file name with link to download
773 829
 					$out.= '<td class="minwidth200">';
774 830
 					$out.= '<a class="documentdownload paddingright" href="'.$documenturl.'?modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).($param?'&'.$param:'').'"';
775 831
 					$mime=dol_mimetype($relativepath,'',0);
776
-					if (preg_match('/text/',$mime)) $out.= ' target="_blank"';
832
+					if (preg_match('/text/',$mime)) {
833
+					    $out.= ' target="_blank"';
834
+					}
777 835
 					$out.= ' target="_blank">';
778 836
 					$out.= img_mime($file["name"],$langs->trans("File").': '.$file["name"]);
779 837
 					$out.= dol_trunc($file["name"], 150);
@@ -824,8 +882,10 @@  discard block
 block discarded – undo
824 882
 						{
825 883
 							$out.= $hookmanager->resPrint;		// Complete line
826 884
 							$out.= '</tr>';
885
+						} else {
886
+						    $out = $hookmanager->resPrint;
827 887
 						}
828
-						else $out = $hookmanager->resPrint;		// Replace line
888
+						// Replace line
829 889
 			  		}
830 890
 				}
831 891
 
@@ -847,7 +907,9 @@  discard block
 block discarded – undo
847 907
 					$out.='<td align="right">';
848 908
 					$out.=dol_print_date($file->datea,'dayhour');
849 909
 					$out.='</td>';
850
-					if ($delallowed || $printer || $morepicto) $out.='<td></td>';
910
+					if ($delallowed || $printer || $morepicto) {
911
+					    $out.='<td></td>';
912
+					}
851 913
 					$out.='</tr>'."\n";
852 914
 				}
853 915
 				$this->numoffiles++;
@@ -866,7 +928,9 @@  discard block
 block discarded – undo
866 928
 			$out.= "</div>\n";
867 929
 			if ($genallowed)
868 930
 			{
869
-				if (empty($noform)) $out.= '</form>'."\n";
931
+				if (empty($noform)) {
932
+				    $out.= '</form>'."\n";
933
+				}
870 934
 			}
871 935
 		}
872 936
 		$out.= '<!-- End show_document -->'."\n";
@@ -908,8 +972,7 @@  discard block
 block discarded – undo
908 972
 		if (! empty($conf->global->MAIN_SHOW_ALL_FILES_ON_DOCUMENT_TOOLTIP))
909 973
 		{
910 974
 			$filterforfilesearch = preg_quote(basename($modulesubdir),'/');
911
-		}
912
-		else
975
+		} else
913 976
 		{
914 977
 			$filterforfilesearch = preg_quote(basename($modulesubdir),'/').'[^\-]+';
915 978
 		}
@@ -930,12 +993,18 @@  discard block
 block discarded – undo
930 993
 			foreach($file_list as $file)
931 994
 			{
932 995
 				$i++;
933
-				if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) continue;	// Discard this. It does not match provided filter.
996
+				if ($filter && ! preg_match('/'.$filter.'/i', $file["name"])) {
997
+				    continue;
998
+				}
999
+				// Discard this. It does not match provided filter.
934 1000
 
935 1001
 				$found++;
936 1002
 				// Define relative path for download link (depends on module)
937 1003
 				$relativepath=$file["name"];								// Cas general
938
-				if ($modulesubdir) $relativepath=$modulesubdir."/".$file["name"];	// Cas propal, facture...
1004
+				if ($modulesubdir) {
1005
+				    $relativepath=$modulesubdir."/".$file["name"];
1006
+				}
1007
+				// Cas propal, facture...
939 1008
 				// Autre cas
940 1009
 				if ($modulepart == 'donation')            {
941 1010
 					$relativepath = get_exdir($modulesubdir,2,0,0,null,'donation').$file["name"];
@@ -947,8 +1016,11 @@  discard block
 block discarded – undo
947 1016
 				$this->infofiles['nboffiles']++;
948 1017
 				$this->infofiles['files'][]=$file['fullname'];
949 1018
 				$ext=pathinfo($file["name"], PATHINFO_EXTENSION);
950
-				if (empty($this->infofiles[$ext])) $this->infofiles['extensions'][$ext]=1;
951
-				else $this->infofiles['extensions'][$ext]++;
1019
+				if (empty($this->infofiles[$ext])) {
1020
+				    $this->infofiles['extensions'][$ext]=1;
1021
+				} else {
1022
+				    $this->infofiles['extensions'][$ext]++;
1023
+				}
952 1024
 
953 1025
 				// Preview
954 1026
 				if (! empty($conf->use_javascript_ajax) && ($conf->browser->layout != 'phone'))
@@ -966,7 +1038,9 @@  discard block
 block discarded – undo
966 1038
 				// Download
967 1039
 				$tmpout.= '<li class="nowrap"><a class="pictopreview nowrap" href="'.DOL_URL_ROOT . '/document.php?modulepart='.$modulepart.'&amp;entity='.$entity.'&amp;file='.urlencode($relativepath).'"';
968 1040
 				$mime=dol_mimetype($relativepath,'',0);
969
-				if (preg_match('/text/',$mime)) $tmpout.= ' target="_blank"';
1041
+				if (preg_match('/text/',$mime)) {
1042
+				    $tmpout.= ' target="_blank"';
1043
+				}
970 1044
 				$tmpout.= '>';
971 1045
 				$tmpout.= img_mime($relativepath, $file["name"]);
972 1046
 				$tmpout.= $langs->trans("Download").' '.$ext;
@@ -976,9 +1050,10 @@  discard block
 block discarded – undo
976 1050
 			$out.='</ul></div></dd>
977 1051
     			</dl>';
978 1052
 
979
-			if (! $found) $out='';
980
-		}
981
-		else
1053
+			if (! $found) {
1054
+			    $out='';
1055
+			}
1056
+		} else
982 1057
 		{
983 1058
 			// TODO Add link to regenerate doc ?
984 1059
 			//$out.= '<div id="gen_pdf_'.$modulesubdir.'" class="linkobject hideobject">'.img_picto('', 'refresh').'</div>'."\n";
@@ -1027,14 +1102,21 @@  discard block
 block discarded – undo
1027 1102
 		global $form;
1028 1103
 
1029 1104
 		$disablecrop=1;
1030
-		if (in_array($modulepart, array('expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) $disablecrop=0;
1105
+		if (in_array($modulepart, array('expensereport','holiday','member','project','product','produit','service','societe','tax','ticket','user'))) {
1106
+		    $disablecrop=0;
1107
+		}
1031 1108
 
1032 1109
 		// Define relative path used to store the file
1033 1110
 		if (empty($relativepath))
1034 1111
 		{
1035 1112
 			$relativepath=(! empty($object->ref)?dol_sanitizeFileName($object->ref):'').'/';
1036
-			if ($object->element == 'invoice_supplier') $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;	// TODO Call using a defined value for $relativepath
1037
-			if ($object->element == 'project_task') $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1113
+			if ($object->element == 'invoice_supplier') {
1114
+			    $relativepath=get_exdir($object->id,2,0,0,$object,'invoice_supplier').$relativepath;
1115
+			}
1116
+			// TODO Call using a defined value for $relativepath
1117
+			if ($object->element == 'project_task') {
1118
+			    $relativepath='Call_not_supported_._Call_function_using_a_defined_relative_path_.';
1119
+			}
1038 1120
 		}
1039 1121
 		// For backward compatiblity, we detect file stored into an old path
1040 1122
 		if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO) && $filearray[0]['level1name'] == 'photos')
@@ -1066,11 +1148,12 @@  discard block
 block discarded – undo
1066 1148
 		);
1067 1149
 		$reshook=$hookmanager->executeHooks('showFilesList', $parameters, $object);
1068 1150
 
1069
-		if (isset($reshook) && $reshook != '') // null or '' for bypass
1151
+		if (isset($reshook) && $reshook != '') {
1152
+		    // null or '' for bypass
1070 1153
 		{
1071 1154
 			return $reshook;
1072 1155
 		}
1073
-		else
1156
+		} else
1074 1157
 		{
1075 1158
 			if (! is_object($form))
1076 1159
 			{
@@ -1078,17 +1161,27 @@  discard block
 block discarded – undo
1078 1161
 				$form=new Form($this->db);
1079 1162
 			}
1080 1163
 
1081
-			if (! preg_match('/&id=/', $param) && isset($object->id)) $param.='&id='.$object->id;
1164
+			if (! preg_match('/&id=/', $param) && isset($object->id)) {
1165
+			    $param.='&id='.$object->id;
1166
+			}
1082 1167
 			$relativepathwihtoutslashend=preg_replace('/\/$/', '', $relativepath);
1083
-			if ($relativepathwihtoutslashend) $param.= '&file='.urlencode($relativepathwihtoutslashend);
1168
+			if ($relativepathwihtoutslashend) {
1169
+			    $param.= '&file='.urlencode($relativepathwihtoutslashend);
1170
+			}
1084 1171
 
1085
-			if ($permtoeditline < 0)  // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1172
+			if ($permtoeditline < 0) {
1173
+			    // Old behaviour for backward compatibility. New feature should call method with value 0 or 1
1086 1174
 			{
1087 1175
 				$permtoeditline=0;
1176
+			}
1088 1177
 				if (in_array($modulepart, array('product','produit','service')))
1089 1178
 				{
1090
-					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) $permtoeditline=1;
1091
-					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) $permtoeditline=1;
1179
+					if ($user->rights->produit->creer && $object->type == Product::TYPE_PRODUCT) {
1180
+					    $permtoeditline=1;
1181
+					}
1182
+					if ($user->rights->service->creer && $object->type == Product::TYPE_SERVICE) {
1183
+					    $permtoeditline=1;
1184
+					}
1092 1185
 				}
1093 1186
 			}
1094 1187
 			if (empty($conf->global->MAIN_UPLOAD_DOC))
@@ -1098,8 +1191,12 @@  discard block
 block discarded – undo
1098 1191
 			}
1099 1192
 
1100 1193
 			// Show list of existing files
1101
-			if (empty($useinecm) && $title != 'none') print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1102
-			if (empty($url)) $url=$_SERVER["PHP_SELF"];
1194
+			if (empty($useinecm) && $title != 'none') {
1195
+			    print load_fiche_titre($title?$title:$langs->trans("AttachedFiles"));
1196
+			}
1197
+			if (empty($url)) {
1198
+			    $url=$_SERVER["PHP_SELF"];
1199
+			}
1103 1200
 
1104 1201
 			print '<!-- html.formfile::list_of_documents -->'."\n";
1105 1202
 			if (GETPOST('action','aZ09') == 'editfile' && $permtoeditline)
@@ -1119,10 +1216,14 @@  discard block
 block discarded – undo
1119 1216
 				print '<td><input type="search_doc_ref" value="'.dol_escape_htmltag(GETPOST('search_doc_ref','alpha')).'"></td>';
1120 1217
 				print '<td></td>';
1121 1218
 				print '<td></td>';
1122
-				if (empty($useinecm)) print '<td></td>';
1219
+				if (empty($useinecm)) {
1220
+				    print '<td></td>';
1221
+				}
1123 1222
 				print '<td></td>';
1124 1223
 				print '<td></td>';
1125
-				if (! $disablemove) print '<td></td>';
1224
+				if (! $disablemove) {
1225
+				    print '<td></td>';
1226
+				}
1126 1227
 				print "</tr>\n";
1127 1228
 			}
1128 1229
 
@@ -1131,10 +1232,15 @@  discard block
 block discarded – undo
1131 1232
 			print_liste_field_titre('Documents2',$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1132 1233
 			print_liste_field_titre('Size',$url,"size","",$param,'align="right"',$sortfield,$sortorder);
1133 1234
 			print_liste_field_titre('Date',$url,"date","",$param,'align="center"',$sortfield,$sortorder);
1134
-			if (empty($useinecm)) print_liste_field_titre('',$url,"","",$param,'align="center"');					// Preview
1235
+			if (empty($useinecm)) {
1236
+			    print_liste_field_titre('',$url,"","",$param,'align="center"');
1237
+			}
1238
+			// Preview
1135 1239
 			print_liste_field_titre('');
1136 1240
 			print_liste_field_titre('');
1137
-			if (! $disablemove) print_liste_field_titre('');
1241
+			if (! $disablemove) {
1242
+			    print_liste_field_titre('');
1243
+			}
1138 1244
 			print "</tr>\n";
1139 1245
 
1140 1246
 			// Get list of files stored into database for same relative directory
@@ -1143,23 +1249,29 @@  discard block
 block discarded – undo
1143 1249
 				completeFileArrayWithDatabaseInfo($filearray, $relativedir);
1144 1250
 
1145 1251
 				//var_dump($sortfield.' - '.$sortorder);
1146
-				if ($sortfield && $sortorder)	// If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
1252
+				if ($sortfield && $sortorder) {
1253
+				    // If $sortfield is for example 'position_name', we will sort on the property 'position_name' (that is concat of position+name)
1147 1254
 				{
1148 1255
 					$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
1149 1256
 				}
1257
+				}
1150 1258
 			}
1151 1259
 
1152 1260
 			$nboffiles=count($filearray);
1153
-			if ($nboffiles > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1261
+			if ($nboffiles > 0) {
1262
+			    include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1263
+			}
1154 1264
 
1155 1265
 			$i=0; $nboflines = 0; $lastrowid=0;
1156
-			foreach($filearray as $key => $file)      // filearray must be only files here
1266
+			foreach($filearray as $key => $file) {
1267
+			    // filearray must be only files here
1157 1268
 			{
1158 1269
 				if ($file['name'] != '.'
1159 1270
 						&& $file['name'] != '..'
1160 1271
 						&& ! preg_match('/\.meta$/i',$file['name']))
1161 1272
 				{
1162 1273
 					if ($filearray[$key]['rowid'] > 0) $lastrowid = $filearray[$key]['rowid'];
1274
+			}
1163 1275
 					$filepath=$relativepath.$file['name'];
1164 1276
 
1165 1277
 					$editline=0;
@@ -1175,12 +1287,18 @@  discard block
 block discarded – undo
1175 1287
 					// Show file name with link to download
1176 1288
 					//print "XX".$file['name'];	//$file['name'] must be utf8
1177 1289
 					print '<a class="paddingright" href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1178
-					if ($forcedownload) print '&attachment=1';
1179
-					if (! empty($object->entity)) print '&entity='.$object->entity;
1290
+					if ($forcedownload) {
1291
+					    print '&attachment=1';
1292
+					}
1293
+					if (! empty($object->entity)) {
1294
+					    print '&entity='.$object->entity;
1295
+					}
1180 1296
 					print '&file='.urlencode($filepath);
1181 1297
 					print '">';
1182 1298
 					print img_mime($file['name'], $file['name'].' ('.dol_print_size($file['size'],0,0).')', 'inline-block valignbottom paddingright');
1183
-					if ($showrelpart == 1) print $relativepath;
1299
+					if ($showrelpart == 1) {
1300
+					    print $relativepath;
1301
+					}
1184 1302
 					//print dol_trunc($file['name'],$maxlength,'middle');
1185 1303
 					if (GETPOST('action','aZ09') == 'editfile' && $file['name'] == basename(GETPOST('urlfile','alpha')))
1186 1304
 					{
@@ -1190,14 +1308,15 @@  discard block
 block discarded – undo
1190 1308
 						print '<input type="hidden" name="renamefilefrom" value="'.dol_escape_htmltag($file['name']).'">';
1191 1309
 						print '<input type="text" name="renamefileto" class="quatrevingtpercent" value="'.dol_escape_htmltag($file['name']).'">';
1192 1310
 						$editline=1;
1193
-					}
1194
-					else
1311
+					} else
1195 1312
 					{
1196 1313
 						print dol_trunc($file['name'], 200);
1197 1314
 						print '</a>';
1198 1315
 					}
1199 1316
 					// Preview link
1200
-					if (! $editline) print $this->showPreview($file, $modulepart, $filepath);
1317
+					if (! $editline) {
1318
+					    print $this->showPreview($file, $modulepart, $filepath);
1319
+					}
1201 1320
 					// Public share link
1202 1321
 					//if (! $editline && ! empty($filearray[$key]['hashp'])) print pictowithlinktodirectdownload;
1203 1322
 
@@ -1208,8 +1327,9 @@  discard block
 block discarded – undo
1208 1327
 					$sizetoshowbytes = dol_print_size($file['size'],0,1);
1209 1328
 
1210 1329
 					print '<td align="right" width="80px">';
1211
-					if ($sizetoshow == $sizetoshowbytes) print $sizetoshow;
1212
-					else {
1330
+					if ($sizetoshow == $sizetoshowbytes) {
1331
+					    print $sizetoshow;
1332
+					} else {
1213 1333
 						print $form->textwithpicto($sizetoshow, $sizetoshowbytes, -1);
1214 1334
 					}
1215 1335
 					print '</td>';
@@ -1225,7 +1345,10 @@  discard block
 block discarded – undo
1225 1345
 						if (image_format_supported($file['name']) > 0)
1226 1346
 						{
1227 1347
 							$minifile=getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case howerver) than original
1228
-							if (! dol_is_file($file['path'].'/'.$minifile)) $minifile=getImageFileNameForSize($file['name'], '_mini', '.png'); // For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1348
+							if (! dol_is_file($file['path'].'/'.$minifile)) {
1349
+							    $minifile=getImageFileNameForSize($file['name'], '_mini', '.png');
1350
+							}
1351
+							// For backward compatibility of old thumbs that were created with filename in lower case and with .png extension
1229 1352
 							//print $file['path'].'/'.$minifile.'<br>';
1230 1353
 
1231 1354
 							$urlforhref=getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity)?$object->entity:$conf->entity));
@@ -1237,8 +1360,9 @@  discard block
 block discarded – undo
1237 1360
 							}
1238 1361
 							print '<img border="0" height="'.$maxheightmini.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.(!empty($object->entity)?$object->entity:$conf->entity).'&file='.urlencode($relativepath.$minifile).'" title="">';
1239 1362
 							print '</a>';
1363
+						} else {
1364
+						    print '&nbsp;';
1240 1365
 						}
1241
-						else print '&nbsp;';
1242 1366
 						print '</td>';
1243 1367
 					}
1244 1368
 
@@ -1250,8 +1374,7 @@  discard block
 block discarded – undo
1250 1374
 						{
1251 1375
 							print $langs->trans("FileSharedViaALink").' ';
1252 1376
 							print '<input class="inline-block" type="checkbox" name="shareenabled"'.($file['share']?' checked="checked"':'').' /> ';
1253
-						}
1254
-						else
1377
+						} else
1255 1378
 						{
1256 1379
 							if ($file['share'])
1257 1380
 							{
@@ -1263,15 +1386,19 @@  discard block
 block discarded – undo
1263 1386
 								//print '<span class="opacitymedium">'.$langs->trans("Hash").' : '.$file['share'].'</span>';
1264 1387
 								$forcedownload=0;
1265 1388
 								$paramlink='';
1266
-								if (! empty($file['share'])) $paramlink.=($paramlink?'&':'').'hashp='.$file['share'];			// Hash for public share
1267
-								if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
1389
+								if (! empty($file['share'])) {
1390
+								    $paramlink.=($paramlink?'&':'').'hashp='.$file['share'];
1391
+								}
1392
+								// Hash for public share
1393
+								if ($forcedownload) {
1394
+								    $paramlink.=($paramlink?'&':'').'attachment=1';
1395
+								}
1268 1396
 
1269 1397
 								$fulllink=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
1270 1398
 
1271 1399
 								print img_picto($langs->trans("FileSharedViaALink"),'object_globe.png').' ';
1272 1400
 								print '<input type="text" class="quatrevingtpercent" id="downloadlink" name="downloadexternallink" value="'.dol_escape_htmltag($fulllink).'">';
1273
-							}
1274
-							else
1401
+							} else
1275 1402
 							{
1276 1403
 								//print '<span class="opacitymedium">'.$langs->trans("FileNotShared").'</span>';
1277 1404
 							}
@@ -1292,7 +1419,9 @@  discard block
 block discarded – undo
1292 1419
 						if (! $useinecm || $useinecm == 2)
1293 1420
 						{
1294 1421
 							$newmodulepart=$modulepart;
1295
-							if (in_array($modulepart, array('product','produit','service'))) $newmodulepart='produit|service';
1422
+							if (in_array($modulepart, array('product','produit','service'))) {
1423
+							    $newmodulepart='produit|service';
1424
+							}
1296 1425
 
1297 1426
 							if (! $disablecrop && image_format_supported($file['name']) > 0)
1298 1427
 							{
@@ -1312,9 +1441,15 @@  discard block
 block discarded – undo
1312 1441
 						if ($permonobject)
1313 1442
 						{
1314 1443
 							$useajax=1;
1315
-							if (! empty($conf->dol_use_jmobile)) $useajax=0;
1316
-							if (empty($conf->use_javascript_ajax)) $useajax=0;
1317
-							if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax=0;
1444
+							if (! empty($conf->dol_use_jmobile)) {
1445
+							    $useajax=0;
1446
+							}
1447
+							if (empty($conf->use_javascript_ajax)) {
1448
+							    $useajax=0;
1449
+							}
1450
+							if (! empty($conf->global->MAIN_ECM_DISABLE_JS)) {
1451
+							    $useajax=0;
1452
+							}
1318 1453
 							print '<a href="'.(($useinecm && $useajax)?'#':($url.'?action=delete&urlfile='.urlencode($filepath).$param)).'" class="deletefilelink" rel="'.$filepath.'">'.img_delete().'</a>';
1319 1454
 						}
1320 1455
 						print "</td>";
@@ -1330,21 +1465,21 @@  discard block
 block discarded – undo
1330 1465
 									print '<a class="lineupdown" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id.'">'.img_down('default',0,'imgdownforline').'</a>';
1331 1466
 								}
1332 1467
 								print '</td>';
1333
-							}
1334
-							else {
1468
+							} else {
1335 1469
 							   	print '<td align="center"'.(($conf->browser->layout != 'phone' && empty($disablemove)) ?' class="linecolmove tdlineupdown"':' class="linecolmove"').'>';
1336 1470
 							   	print '</td>';
1337 1471
 							}
1338 1472
 					   }
1339
-					}
1340
-					else
1473
+					} else
1341 1474
 					{
1342 1475
 						print '<td class="right">';
1343 1476
 						print '<input type="hidden" name="ecmfileid" value="'.$filearray[$key]['rowid'].'">';
1344 1477
 						print '<input type="submit" class="button" name="renamefilesave" value="'.dol_escape_htmltag($langs->trans("Save")).'">';
1345 1478
 						print '<input type="submit" class="button" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'">';
1346 1479
 						print '</td>';
1347
-						if (empty($disablemove)) print '<td class="right"></td>';
1480
+						if (empty($disablemove)) {
1481
+						    print '<td class="right"></td>';
1482
+						}
1348 1483
 					}
1349 1484
 					print "</tr>\n";
1350 1485
 
@@ -1354,10 +1489,16 @@  discard block
 block discarded – undo
1354 1489
 			if ($nboffiles == 0)
1355 1490
 			{
1356 1491
 				$colspan=(empty($useinecm)?'6':'6');
1357
-				if (empty($disablemove)) $colspan++;		// 6 columns or 7
1492
+				if (empty($disablemove)) {
1493
+				    $colspan++;
1494
+				}
1495
+				// 6 columns or 7
1358 1496
 				print '<tr class="oddeven"><td colspan="'.$colspan.'" class="opacitymedium">';
1359
-				if (empty($textifempty)) print $langs->trans("NoFileFound");
1360
-				else print $textifempty;
1497
+				if (empty($textifempty)) {
1498
+				    print $langs->trans("NoFileFound");
1499
+				} else {
1500
+				    print $textifempty;
1501
+				}
1361 1502
 				print '</td></tr>';
1362 1503
 			}
1363 1504
 			print "</table>";
@@ -1411,8 +1552,12 @@  discard block
 block discarded – undo
1411 1552
 		dol_syslog(get_class($this).'::list_of_autoecmfiles upload_dir='.$upload_dir.' modulepart='.$modulepart);
1412 1553
 
1413 1554
 		// Show list of documents
1414
-		if (empty($useinecm)) print load_fiche_titre($langs->trans("AttachedFiles"));
1415
-		if (empty($url)) $url=$_SERVER["PHP_SELF"];
1555
+		if (empty($useinecm)) {
1556
+		    print load_fiche_titre($langs->trans("AttachedFiles"));
1557
+		}
1558
+		if (empty($url)) {
1559
+		    $url=$_SERVER["PHP_SELF"];
1560
+		}
1416 1561
 
1417 1562
 		if (! empty($addfilterfields))
1418 1563
 		{
@@ -1440,7 +1585,9 @@  discard block
 block discarded – undo
1440 1585
 
1441 1586
 		print '<tr class="liste_titre">';
1442 1587
 		$sortref="fullname";
1443
-		if ($modulepart == 'invoice_supplier') $sortref='level1name';
1588
+		if ($modulepart == 'invoice_supplier') {
1589
+		    $sortref='level1name';
1590
+		}
1444 1591
 		print_liste_field_titre("Ref",$url,$sortref,"",$param,'align="left"',$sortfield,$sortorder);
1445 1592
 		print_liste_field_titre("Documents2",$url,"name","",$param,'align="left"',$sortfield,$sortorder);
1446 1593
 		print_liste_field_titre("Size",$url,"size","",$param,'align="right"',$sortfield,$sortorder);
@@ -1453,73 +1600,59 @@  discard block
 block discarded – undo
1453 1600
 		{
1454 1601
 			include_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1455 1602
 			$object_instance=new Societe($this->db);
1456
-		}
1457
-		else if ($modulepart == 'invoice')
1603
+		} else if ($modulepart == 'invoice')
1458 1604
 		{
1459 1605
 			include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1460 1606
 			$object_instance=new Facture($this->db);
1461
-		}
1462
-		else if ($modulepart == 'invoice_supplier')
1607
+		} else if ($modulepart == 'invoice_supplier')
1463 1608
 		{
1464 1609
 			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1465 1610
 			$object_instance=new FactureFournisseur($this->db);
1466
-		}
1467
-		else if ($modulepart == 'propal')
1611
+		} else if ($modulepart == 'propal')
1468 1612
 		{
1469 1613
 			include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
1470 1614
 			$object_instance=new Propal($this->db);
1471
-		}
1472
-		else if ($modulepart == 'supplier_proposal')
1615
+		} else if ($modulepart == 'supplier_proposal')
1473 1616
 		{
1474 1617
 			include_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
1475 1618
 			$object_instance=new SupplierProposal($this->db);
1476
-		}
1477
-		else if ($modulepart == 'order')
1619
+		} else if ($modulepart == 'order')
1478 1620
 		{
1479 1621
 			include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1480 1622
 			$object_instance=new Commande($this->db);
1481
-		}
1482
-		else if ($modulepart == 'order_supplier')
1623
+		} else if ($modulepart == 'order_supplier')
1483 1624
 		{
1484 1625
 			include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1485 1626
 			$object_instance=new CommandeFournisseur($this->db);
1486
-		}
1487
-		else if ($modulepart == 'contract')
1627
+		} else if ($modulepart == 'contract')
1488 1628
 		{
1489 1629
 			include_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php';
1490 1630
 			$object_instance=new Contrat($this->db);
1491
-		}
1492
-		else if ($modulepart == 'product')
1631
+		} else if ($modulepart == 'product')
1493 1632
 		{
1494 1633
 			include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1495 1634
 			$object_instance=new Product($this->db);
1496
-		}
1497
-		else if ($modulepart == 'tax')
1635
+		} else if ($modulepart == 'tax')
1498 1636
 		{
1499 1637
 			include_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php';
1500 1638
 			$object_instance=new ChargeSociales($this->db);
1501
-		}
1502
-		else if ($modulepart == 'project')
1639
+		} else if ($modulepart == 'project')
1503 1640
 		{
1504 1641
 			include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1505 1642
 			$object_instance=new Project($this->db);
1506
-		}
1507
-		else if ($modulepart == 'fichinter')
1643
+		} else if ($modulepart == 'fichinter')
1508 1644
 		{
1509 1645
 			include_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
1510 1646
 			$object_instance=new Fichinter($this->db);
1511
-		}
1512
-		else if ($modulepart == 'user')
1647
+		} else if ($modulepart == 'user')
1513 1648
 		{
1514 1649
 			include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1515 1650
 			$object_instance=new User($this->db);
1516
-		}
1517
-		else if ($modulepart == 'expensereport')
1651
+		} else if ($modulepart == 'expensereport')
1518 1652
 		{
1519 1653
 			include_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
1520 1654
 			$object_instance=new ExpenseReport($this->db);
1521
-		}
1522
-		else if ($modulepart == 'holiday')
1655
+		} else if ($modulepart == 'holiday')
1523 1656
 		{
1524 1657
 			include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
1525 1658
 			$object_instance=new Holiday($this->db);
@@ -1556,13 +1689,14 @@  discard block
 block discarded – undo
1556 1689
 				if ($modulepart == 'expensereport')     { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $ref=(isset($reg[1])?$reg[1]:'');}
1557 1690
 				if ($modulepart == 'holiday')           { preg_match('/(.*)\/[^\/]+$/',$relativefile,$reg);  $id=(isset($reg[1])?$reg[1]:'');}
1558 1691
 
1559
-				if (! $id && ! $ref) continue;
1692
+				if (! $id && ! $ref) {
1693
+				    continue;
1694
+				}
1560 1695
 				$found=0;
1561 1696
 				if (! empty($this->cache_objects[$modulepart.'_'.$id.'_'.$ref]))
1562 1697
 				{
1563 1698
 					$found=1;
1564
-				}
1565
-				else
1699
+				} else
1566 1700
 				{
1567 1701
 					//print 'Fetch '.$id." - ".$ref.'<br>';
1568 1702
 
@@ -1584,13 +1718,19 @@  discard block
 block discarded – undo
1584 1718
 					if ($result == 0) { $found=1; $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]='notfound'; unset($filearray[$key]); }
1585 1719
 				}
1586 1720
 
1587
-				if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) continue;    // We do not show orphelins files
1721
+				if (! $found > 0 || ! is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
1722
+				    continue;
1723
+				}
1724
+				// We do not show orphelins files
1588 1725
 
1589 1726
 				print '<!-- Line list_of_autoecmfiles '.$key.' -->'."\n";
1590 1727
 				print '<tr class="oddeven">';
1591 1728
 				print '<td>';
1592
-				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1593
-				else print $langs->trans("ObjectDeleted",($id?$id:$ref));
1729
+				if ($found > 0 && is_object($this->cache_objects[$modulepart.'_'.$id.'_'.$ref])) {
1730
+				    print $this->cache_objects[$modulepart.'_'.$id.'_'.$ref]->getNomUrl(1,'document');
1731
+				} else {
1732
+				    print $langs->trans("ObjectDeleted",($id?$id:$ref));
1733
+				}
1594 1734
 
1595 1735
 				//$modulesubdir=dol_sanitizeFileName($ref);
1596 1736
 				$modulesubdir=dirname($relativefile);
@@ -1606,7 +1746,9 @@  discard block
 block discarded – undo
1606 1746
 				print '<td>';
1607 1747
 				//print "XX".$file['name']; //$file['name'] must be utf8
1608 1748
 				print '<a href="'.DOL_URL_ROOT.'/document.php?modulepart='.$modulepart;
1609
-				if ($forcedownload) print '&attachment=1';
1749
+				if ($forcedownload) {
1750
+				    print '&attachment=1';
1751
+				}
1610 1752
 				print '&file='.urlencode($relativefile).'">';
1611 1753
 				print img_mime($file['name'],$file['name'].' ('.dol_print_size($file['size'],0,0).')');
1612 1754
 				print dol_trunc($file['name'],$maxlength,'middle');
@@ -1632,14 +1774,19 @@  discard block
 block discarded – undo
1632 1774
 		if (count($filearray) == 0)
1633 1775
 		{
1634 1776
 			print '<tr class="oddeven"><td colspan="5">';
1635
-			if (empty($textifempty)) print $langs->trans("NoFileFound");
1636
-			else print $textifempty;
1777
+			if (empty($textifempty)) {
1778
+			    print $langs->trans("NoFileFound");
1779
+			} else {
1780
+			    print $textifempty;
1781
+			}
1637 1782
 			print '</td></tr>';
1638 1783
 		}
1639 1784
 		print "</table>";
1640 1785
 		print '</div>';
1641 1786
 
1642
-		if (! empty($addfilterfields)) print '</form>';
1787
+		if (! empty($addfilterfields)) {
1788
+		    print '</form>';
1789
+		}
1643 1790
 		// Fin de zone
1644 1791
 	}
1645 1792
 
@@ -1750,7 +1897,9 @@  discard block
 block discarded – undo
1750 1897
 		print_liste_field_titre('','','');
1751 1898
 		print '</tr>';
1752 1899
 		$nboflinks = count($links);
1753
-		if ($nboflinks > 0) include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1900
+		if ($nboflinks > 0) {
1901
+		    include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1902
+		}
1754 1903
 
1755 1904
 		foreach ($links as $link)
1756 1905
 		{
@@ -1773,8 +1922,7 @@  discard block
 block discarded – undo
1773 1922
 				print '<input type="submit" name="save" class="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '">';
1774 1923
 				print '<input type="submit" name="cancel" class="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '">';
1775 1924
 				print '</td>';
1776
-			}
1777
-			else
1925
+			} else
1778 1926
 			{
1779 1927
 				print '<td>';
1780 1928
 				print img_picto('', 'object_globe').' ';
@@ -1836,8 +1984,9 @@  discard block
 block discarded – undo
1836 1984
 				{
1837 1985
 					//$out.= img_picto($langs->trans('Preview').' '.$file['name'], 'detail');
1838 1986
 					$out.='<span class="fa fa-search-plus" style="color: gray"></span>';
1987
+				} else {
1988
+				    $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1839 1989
 				}
1840
-				else $out.= img_mime($relativepath, $langs->trans('Preview').' '.$file['name']);
1841 1990
 				$out.= '</a>';
1842 1991
 			}
1843 1992
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formaccounting.class.php 3 patches
Indentation   +303 added lines, -303 removed lines patch added patch discarded remove patch
@@ -33,110 +33,110 @@  discard block
 block discarded – undo
33 33
 class FormAccounting extends Form
34 34
 {
35 35
 
36
-	private $options_cache = array();
36
+    private $options_cache = array();
37 37
 
38
-	/**
38
+    /**
39 39
      * @var DoliDB Database handler.
40 40
      */
41 41
     public $db;
42 42
 
43
-	/**
44
-	 * @var string Error code (or message)
45
-	 */
46
-	public $error='';
47
-
48
-   /**
49
-	* Constructor
50
-	*
51
-	* @param		DoliDB		$db      Database handler
52
-	*/
53
-	public function __construct($db)
54
-	{
55
-	    $this->db = $db;
56
-	}
43
+    /**
44
+     * @var string Error code (or message)
45
+     */
46
+    public $error='';
47
+
48
+    /**
49
+     * Constructor
50
+     *
51
+     * @param		DoliDB		$db      Database handler
52
+     */
53
+    public function __construct($db)
54
+    {
55
+        $this->db = $db;
56
+    }
57 57
 
58 58
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
59
-	/**
60
-	 * Return list of journals with label by nature
61
-	 *
62
-	 * @param	string	$selectid	Preselected pcg_type
63
-	 * @param	string	$htmlname	Name of field in html form
64
-	 * @param	int		$nature		Limit the list to a particular type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
65
-	 * @param	int		$showempty	Add an empty field
66
-	 * @param	int		$select_in	0=selectid value is the journal rowid (default) or 1=selectid is journal code
67
-	 * @param	int		$select_out	Set value returned by select. 0=rowid (default), 1=code
68
-	 * @param	string	$morecss	More css non HTML object
69
-	 * @param	string	$usecache	Key to use to store result into a cache. Next call with same key will reuse the cache.
70
-	 * @param   int     $disabledajaxcombo Disable ajax combo box.
71
-	 * @return	string				String with HTML select
72
-	 */
73
-	function select_journal($selectid, $htmlname = 'journal', $nature=0, $showempty = 0, $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='', $disabledajaxcombo=0)
74
-	{
59
+    /**
60
+     * Return list of journals with label by nature
61
+     *
62
+     * @param	string	$selectid	Preselected pcg_type
63
+     * @param	string	$htmlname	Name of field in html form
64
+     * @param	int		$nature		Limit the list to a particular type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
65
+     * @param	int		$showempty	Add an empty field
66
+     * @param	int		$select_in	0=selectid value is the journal rowid (default) or 1=selectid is journal code
67
+     * @param	int		$select_out	Set value returned by select. 0=rowid (default), 1=code
68
+     * @param	string	$morecss	More css non HTML object
69
+     * @param	string	$usecache	Key to use to store result into a cache. Next call with same key will reuse the cache.
70
+     * @param   int     $disabledajaxcombo Disable ajax combo box.
71
+     * @return	string				String with HTML select
72
+     */
73
+    function select_journal($selectid, $htmlname = 'journal', $nature=0, $showempty = 0, $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='', $disabledajaxcombo=0)
74
+    {
75 75
         // phpcs:enable
76
-		global $conf,$langs;
77
-
78
-		$out = '';
79
-
80
-    	$options = array();
81
-		if ($usecache && ! empty($this->options_cache[$usecache]))
82
-		{
83
-		    $options = $this->options_cache[$usecache];
84
-		    $selected=$selectid;
85
-		}
86
-		else
87
-		{
88
-			$sql = "SELECT rowid, code, label, nature, entity, active";
89
-			$sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
90
-			$sql.= " WHERE active = 1";
91
-			$sql.= " AND entity = ".$conf->entity;
92
-			//if ($nature && is_numeric($nature))   $sql .= " AND nature = ".$nature;
93
-			$sql.= " ORDER BY code";
94
-
95
-			dol_syslog(get_class($this) . "::select_journal", LOG_DEBUG);
96
-			$resql = $this->db->query($sql);
97
-
98
-			if (!$resql) {
99
-				$this->error = "Error ".$this->db->lasterror();
100
-				dol_syslog(get_class($this)."::select_journal ".$this->error, LOG_ERR);
101
-				return -1;
102
-			}
103
-
104
-    		$selected = 0;
105
-			$langs->load('accountancy');
106
-			while ($obj = $this->db->fetch_object($resql))
107
-			{
108
-				$label = $obj->code . ' - ' . $langs->trans($obj->label);
109
-
110
-    			$select_value_in = $obj->rowid;
111
-				$select_value_out = $obj->rowid;
112
-
113
-				// Try to guess if we have found default value
114
-    			if ($select_in == 1) {
115
-    				$select_value_in = $obj->code;
116
-    			}
117
-    			if ($select_out == 1) {
118
-    				$select_value_out = $obj->code;
119
-    			}
120
-    			// Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid
121
-    			if ($selectid != '' && $selectid == $select_value_in) {
122
-    			    //var_dump("Found ".$selectid." ".$select_value_in);
123
-    				$selected = $select_value_out;
124
-    			}
125
-
126
-				$options[$select_value_out] = $label;
127
-			}
128
-			$this->db->free($resql);
129
-
130
-			if ($usecache)
131
-			{
132
-				$this->options_cache[$usecache] = $options;
133
-			}
134
-		}
135
-
136
-		$out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, ($disabledajaxcombo?0:1));
137
-
138
-		return $out;
139
-	}
76
+        global $conf,$langs;
77
+
78
+        $out = '';
79
+
80
+        $options = array();
81
+        if ($usecache && ! empty($this->options_cache[$usecache]))
82
+        {
83
+            $options = $this->options_cache[$usecache];
84
+            $selected=$selectid;
85
+        }
86
+        else
87
+        {
88
+            $sql = "SELECT rowid, code, label, nature, entity, active";
89
+            $sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
90
+            $sql.= " WHERE active = 1";
91
+            $sql.= " AND entity = ".$conf->entity;
92
+            //if ($nature && is_numeric($nature))   $sql .= " AND nature = ".$nature;
93
+            $sql.= " ORDER BY code";
94
+
95
+            dol_syslog(get_class($this) . "::select_journal", LOG_DEBUG);
96
+            $resql = $this->db->query($sql);
97
+
98
+            if (!$resql) {
99
+                $this->error = "Error ".$this->db->lasterror();
100
+                dol_syslog(get_class($this)."::select_journal ".$this->error, LOG_ERR);
101
+                return -1;
102
+            }
103
+
104
+            $selected = 0;
105
+            $langs->load('accountancy');
106
+            while ($obj = $this->db->fetch_object($resql))
107
+            {
108
+                $label = $obj->code . ' - ' . $langs->trans($obj->label);
109
+
110
+                $select_value_in = $obj->rowid;
111
+                $select_value_out = $obj->rowid;
112
+
113
+                // Try to guess if we have found default value
114
+                if ($select_in == 1) {
115
+                    $select_value_in = $obj->code;
116
+                }
117
+                if ($select_out == 1) {
118
+                    $select_value_out = $obj->code;
119
+                }
120
+                // Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid
121
+                if ($selectid != '' && $selectid == $select_value_in) {
122
+                    //var_dump("Found ".$selectid." ".$select_value_in);
123
+                    $selected = $select_value_out;
124
+                }
125
+
126
+                $options[$select_value_out] = $label;
127
+            }
128
+            $this->db->free($resql);
129
+
130
+            if ($usecache)
131
+            {
132
+                $this->options_cache[$usecache] = $options;
133
+            }
134
+        }
135
+
136
+        $out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, ($disabledajaxcombo?0:1));
137
+
138
+        return $out;
139
+    }
140 140
 
141 141
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
142 142
     /**
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
             $sql = "SELECT c.rowid, c.label as type, c.range_account";
168 168
             $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
169 169
             $sql.= " WHERE c.active = 1";
170
-			$sql.= " AND c.category_type = 0";
170
+            $sql.= " AND c.category_type = 0";
171 171
             if (empty($allcountries)) $sql.= " AND c.fk_country = ".$mysoc->country_id;
172 172
             $sql.= " ORDER BY c.label ASC";
173 173
         }
@@ -176,8 +176,8 @@  discard block
 block discarded – undo
176 176
             $sql = "SELECT c.rowid, c.label as type, c.range_account";
177 177
             $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
178 178
             $sql.= " WHERE c.active = 1";
179
-			$sql.= " AND c.category_type = 0";
180
-			$sql.= " AND c.fk_country = co.rowid";
179
+            $sql.= " AND c.category_type = 0";
180
+            $sql.= " AND c.fk_country = co.rowid";
181 181
             if (empty($allcountries)) $sql.= " AND co.code = '".$mysoc->country_code."'";
182 182
             $sql.= " ORDER BY c.label ASC";
183 183
         }
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
                     $out .= '<option value="'.$obj->rowid.'"';
200 200
                     if ($obj->rowid == $selected) $out .= ' selected';
201 201
                     $out .= '>'.($maxlen ? dol_trunc($obj->type,$maxlen) : $obj->type);
202
-					$out .= ' ('.$obj->range_account.')';
202
+                    $out .= ' ('.$obj->range_account.')';
203 203
                     $i++;
204 204
                 }
205 205
                 $out .=  '</select>';
@@ -221,231 +221,231 @@  discard block
 block discarded – undo
221 221
     }
222 222
 
223 223
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
224
-	/**
225
-	 * Return select filter with date of transaction
226
-	 *
227
-	 * @param string $htmlname Name of select field
228
-	 * @param string $selectedkey Value
229
-	 * @return string HTML edit field
230
-	 */
224
+    /**
225
+     * Return select filter with date of transaction
226
+     *
227
+     * @param string $htmlname Name of select field
228
+     * @param string $selectedkey Value
229
+     * @return string HTML edit field
230
+     */
231 231
     function select_bookkeeping_importkey($htmlname = 'importkey', $selectedkey = '')
232 232
     {
233 233
         // phpcs:enable
234
-		$options = array();
234
+        $options = array();
235 235
 
236
-		$sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping';
237
-	    $sql .= " WHERE entity IN (".getEntity('accountancy').")";
238
-		$sql .= ' ORDER BY import_key DESC';
236
+        $sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping';
237
+        $sql .= " WHERE entity IN (".getEntity('accountancy').")";
238
+        $sql .= ' ORDER BY import_key DESC';
239 239
 
240
-		dol_syslog(get_class($this) . "::select_bookkeeping_importkey", LOG_DEBUG);
241
-		$resql = $this->db->query($sql);
240
+        dol_syslog(get_class($this) . "::select_bookkeeping_importkey", LOG_DEBUG);
241
+        $resql = $this->db->query($sql);
242 242
 
243
-		if (!$resql) {
244
-			$this->error = "Error " . $this->db->lasterror();
245
-			dol_syslog(get_class($this) . "::select_bookkeeping_importkey " . $this->error, LOG_ERR);
246
-			return - 1;
247
-		}
243
+        if (!$resql) {
244
+            $this->error = "Error " . $this->db->lasterror();
245
+            dol_syslog(get_class($this) . "::select_bookkeeping_importkey " . $this->error, LOG_ERR);
246
+            return - 1;
247
+        }
248 248
 
249
-		while ($obj = $this->db->fetch_object($resql)) {
250
-			$options[$obj->import_key] = dol_print_date($obj->import_key, 'dayhourtext');
251
-		}
249
+        while ($obj = $this->db->fetch_object($resql)) {
250
+            $options[$obj->import_key] = dol_print_date($obj->import_key, 'dayhourtext');
251
+        }
252 252
 
253
-		return Form::selectarray($htmlname, $options, $selectedkey);
254
-	}
253
+        return Form::selectarray($htmlname, $options, $selectedkey);
254
+    }
255 255
 
256 256
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
257
-	/**
258
-	 * Return list of accounts with label by chart of accounts
259
-	 *
260
-	 * @param string   $selectid           Preselected id or code of accounting accounts (depends on $select_in)
261
-	 * @param string   $htmlname           Name of HTML field id. If name start with '.', it is name of HTML css class, so several component with same name in different forms can be used.
262
-	 * @param int      $showempty          1=Add an empty field, 2=Add an empty field+'None' field
263
-	 * @param array    $event              Event options
264
-	 * @param int      $select_in          0=selectid value is a aa.rowid (default) or 1=selectid is aa.account_number
265
-	 * @param int      $select_out         Set value returned by select. 0=rowid (default), 1=account_number
266
-	 * @param string   $morecss            More css non HTML object
267
-	 * @param string   $usecache           Key to use to store result into a cache. Next call with same key will reuse the cache.
268
-	 * @return string                      String with HTML select
269
-	 */
270
-	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
271
-	{
257
+    /**
258
+     * Return list of accounts with label by chart of accounts
259
+     *
260
+     * @param string   $selectid           Preselected id or code of accounting accounts (depends on $select_in)
261
+     * @param string   $htmlname           Name of HTML field id. If name start with '.', it is name of HTML css class, so several component with same name in different forms can be used.
262
+     * @param int      $showempty          1=Add an empty field, 2=Add an empty field+'None' field
263
+     * @param array    $event              Event options
264
+     * @param int      $select_in          0=selectid value is a aa.rowid (default) or 1=selectid is aa.account_number
265
+     * @param int      $select_out         Set value returned by select. 0=rowid (default), 1=account_number
266
+     * @param string   $morecss            More css non HTML object
267
+     * @param string   $usecache           Key to use to store result into a cache. Next call with same key will reuse the cache.
268
+     * @return string                      String with HTML select
269
+     */
270
+    function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
271
+    {
272 272
         // phpcs:enable
273
-		global $conf, $langs;
274
-
275
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
276
-
277
-		$out = '';
278
-
279
-    	$options = array();
280
-		if ($usecache && ! empty($this->options_cache[$usecache]))
281
-		{
282
-		    $options = $this->options_cache[$usecache];
283
-		    $selected=$selectid;
284
-		}
285
-		else
286
-		{
287
-    		$trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT) ? 50 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT;
288
-
289
-    		$sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version";
290
-    		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
291
-    		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
292
-    		$sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
293
-    		$sql .= " AND aa.active = 1";
294
-    		$sql .= " AND aa.entity=".$conf->entity;
295
-    		$sql .= " ORDER BY aa.account_number";
296
-
297
-    		dol_syslog(get_class($this) . "::select_account", LOG_DEBUG);
298
-    		$resql = $this->db->query($sql);
299
-
300
-    		if (!$resql) {
301
-    			$this->error = "Error " . $this->db->lasterror();
302
-    			dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR);
303
-    			return -1;
304
-    		}
305
-
306
-    		$selected = 0;
307
-    		while ($obj = $this->db->fetch_object($resql))
308
-    		{
309
-    			$label = length_accountg($obj->account_number) . ' - ' . $obj->label;
310
-    			$label = dol_trunc($label, $trunclength);
311
-
312
-    			$select_value_in = $obj->rowid;
313
-    			$select_value_out = $obj->rowid;
314
-
315
-    			// Try to guess if we have found default value
316
-    			if ($select_in == 1) {
317
-    				$select_value_in = $obj->account_number;
318
-    			}
319
-    			if ($select_out == 1) {
320
-    				$select_value_out = $obj->account_number;
321
-    			}
322
-    			// Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number
323
-    			// Because same account_number can be share between different accounting_system and do have the same meaning
324
-    			if ($selectid != '' && $selectid == $select_value_in) {
325
-    			    //var_dump("Found ".$selectid." ".$select_value_in);
326
-    				$selected = $select_value_out;
327
-    			}
328
-
329
-    			$options[$select_value_out] = $label;
330
-    		}
331
-    		$this->db->free($resql);
332
-
333
-    		if ($usecache)
334
-    		{
273
+        global $conf, $langs;
274
+
275
+        require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
276
+
277
+        $out = '';
278
+
279
+        $options = array();
280
+        if ($usecache && ! empty($this->options_cache[$usecache]))
281
+        {
282
+            $options = $this->options_cache[$usecache];
283
+            $selected=$selectid;
284
+        }
285
+        else
286
+        {
287
+            $trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT) ? 50 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT;
288
+
289
+            $sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version";
290
+            $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
291
+            $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
292
+            $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
293
+            $sql .= " AND aa.active = 1";
294
+            $sql .= " AND aa.entity=".$conf->entity;
295
+            $sql .= " ORDER BY aa.account_number";
296
+
297
+            dol_syslog(get_class($this) . "::select_account", LOG_DEBUG);
298
+            $resql = $this->db->query($sql);
299
+
300
+            if (!$resql) {
301
+                $this->error = "Error " . $this->db->lasterror();
302
+                dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR);
303
+                return -1;
304
+            }
305
+
306
+            $selected = 0;
307
+            while ($obj = $this->db->fetch_object($resql))
308
+            {
309
+                $label = length_accountg($obj->account_number) . ' - ' . $obj->label;
310
+                $label = dol_trunc($label, $trunclength);
311
+
312
+                $select_value_in = $obj->rowid;
313
+                $select_value_out = $obj->rowid;
314
+
315
+                // Try to guess if we have found default value
316
+                if ($select_in == 1) {
317
+                    $select_value_in = $obj->account_number;
318
+                }
319
+                if ($select_out == 1) {
320
+                    $select_value_out = $obj->account_number;
321
+                }
322
+                // Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number
323
+                // Because same account_number can be share between different accounting_system and do have the same meaning
324
+                if ($selectid != '' && $selectid == $select_value_in) {
325
+                    //var_dump("Found ".$selectid." ".$select_value_in);
326
+                    $selected = $select_value_out;
327
+                }
328
+
329
+                $options[$select_value_out] = $label;
330
+            }
331
+            $this->db->free($resql);
332
+
333
+            if ($usecache)
334
+            {
335 335
                 $this->options_cache[$usecache] = $options;
336
-    		}
337
-		}
336
+            }
337
+        }
338 338
 
339
-		if ($showempty == 2)
340
-		{
341
-			$options['0'] = $langs->trans("None");
342
-		}
339
+        if ($showempty == 2)
340
+        {
341
+            $options['0'] = $langs->trans("None");
342
+        }
343 343
 
344
-		$out .= Form::selectarray($htmlname, $options, $selected, ($showempty > 0 ? 1 : 0), 0, 0, '', 0, 0, 0, '', $morecss, 1);
344
+        $out .= Form::selectarray($htmlname, $options, $selected, ($showempty > 0 ? 1 : 0), 0, 0, '', 0, 0, 0, '', $morecss, 1);
345 345
 
346
-		return $out;
347
-	}
346
+        return $out;
347
+    }
348 348
 
349 349
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
350
-	/**
351
-	 * Return list of auxilary thirdparty accounts
352
-	 *
353
-	 * @param string   $selectid       Preselected pcg_type
354
-	 * @param string   $htmlname       Name of field in html form
355
-	 * @param int      $showempty      Add an empty field
356
-	 * @param string   $morecss        More css
357
-	 * @return string                  String with HTML select
358
-	 */
350
+    /**
351
+     * Return list of auxilary thirdparty accounts
352
+     *
353
+     * @param string   $selectid       Preselected pcg_type
354
+     * @param string   $htmlname       Name of field in html form
355
+     * @param int      $showempty      Add an empty field
356
+     * @param string   $morecss        More css
357
+     * @return string                  String with HTML select
358
+     */
359 359
     function select_auxaccount($selectid, $htmlname='account_num_aux', $showempty=0, $morecss='maxwidth200')
360 360
     {
361 361
         // phpcs:enable
362 362
 
363
-		$aux_account = array();
364
-
365
-		// Auxiliary customer account
366
-		$sql = "SELECT DISTINCT code_compta, nom ";
367
-		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
368
-	    $sql .= " WHERE entity IN (" . getEntity('societe') . ")";
369
-		$sql .= " ORDER BY code_compta";
370
-		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
371
-		$resql = $this->db->query($sql);
372
-		if ($resql) {
373
-			while ($obj = $this->db->fetch_object($resql)) {
374
-				if (!empty($obj->code_compta)) {
375
-					$aux_account[$obj->code_compta] = $obj->code_compta.' ('.$obj->nom.')';
376
-				}
377
-			}
378
-		} else {
379
-			$this->error = "Error ".$this->db->lasterror();
380
-			dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
381
-			return -1;
382
-		}
383
-		$this->db->free($resql);
384
-
385
-		// Auxiliary supplier account
386
-		$sql = "SELECT DISTINCT code_compta_fournisseur, nom ";
387
-		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
388
-		$sql .= " WHERE entity IN (" . getEntity('societe') . ")";
389
-		$sql .= " ORDER BY code_compta_fournisseur";
390
-		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
391
-		$resql = $this->db->query($sql);
392
-		if ($resql) {
393
-			while ($obj = $this->db->fetch_object($resql)) {
394
-				if (!empty($obj->code_compta_fournisseur)) {
395
-					$aux_account[$obj->code_compta_fournisseur] = $obj->code_compta_fournisseur.' ('.$obj->nom.')';
396
-				}
397
-			}
398
-		} else {
399
-			$this->error = "Error ".$this->db->lasterror();
400
-			dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
401
-			return -1;
402
-		}
403
-		$this->db->free($resql);
404
-
405
-		// Build select
406
-		$out .= Form::selectarray($htmlname, $aux_account, $selectid, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1);
407
-
408
-		return $out;
409
-	}
363
+        $aux_account = array();
364
+
365
+        // Auxiliary customer account
366
+        $sql = "SELECT DISTINCT code_compta, nom ";
367
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe";
368
+        $sql .= " WHERE entity IN (" . getEntity('societe') . ")";
369
+        $sql .= " ORDER BY code_compta";
370
+        dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
371
+        $resql = $this->db->query($sql);
372
+        if ($resql) {
373
+            while ($obj = $this->db->fetch_object($resql)) {
374
+                if (!empty($obj->code_compta)) {
375
+                    $aux_account[$obj->code_compta] = $obj->code_compta.' ('.$obj->nom.')';
376
+                }
377
+            }
378
+        } else {
379
+            $this->error = "Error ".$this->db->lasterror();
380
+            dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
381
+            return -1;
382
+        }
383
+        $this->db->free($resql);
384
+
385
+        // Auxiliary supplier account
386
+        $sql = "SELECT DISTINCT code_compta_fournisseur, nom ";
387
+        $sql .= " FROM ".MAIN_DB_PREFIX."societe";
388
+        $sql .= " WHERE entity IN (" . getEntity('societe') . ")";
389
+        $sql .= " ORDER BY code_compta_fournisseur";
390
+        dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
391
+        $resql = $this->db->query($sql);
392
+        if ($resql) {
393
+            while ($obj = $this->db->fetch_object($resql)) {
394
+                if (!empty($obj->code_compta_fournisseur)) {
395
+                    $aux_account[$obj->code_compta_fournisseur] = $obj->code_compta_fournisseur.' ('.$obj->nom.')';
396
+                }
397
+            }
398
+        } else {
399
+            $this->error = "Error ".$this->db->lasterror();
400
+            dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
401
+            return -1;
402
+        }
403
+        $this->db->free($resql);
404
+
405
+        // Build select
406
+        $out .= Form::selectarray($htmlname, $aux_account, $selectid, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1);
407
+
408
+        return $out;
409
+    }
410 410
 
411 411
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
412
-	/**
413
-	 * Return HTML combo list of years existing into book keepping
414
-	 *
415
-	 * @param string $selected Preselected value
416
-	 * @param string $htmlname Name of HTML select object
417
-	 * @param int $useempty Affiche valeur vide dans liste
418
-	 * @param string $output_format (html/opton (for option html only)/array (to return options arrays
419
-	 * @return string/array
420
-	 */
421
-	function selectyear_accountancy_bookkepping($selected = '', $htmlname = 'yearid', $useempty = 0, $output_format = 'html')
422
-	{
412
+    /**
413
+     * Return HTML combo list of years existing into book keepping
414
+     *
415
+     * @param string $selected Preselected value
416
+     * @param string $htmlname Name of HTML select object
417
+     * @param int $useempty Affiche valeur vide dans liste
418
+     * @param string $output_format (html/opton (for option html only)/array (to return options arrays
419
+     * @return string/array
420
+     */
421
+    function selectyear_accountancy_bookkepping($selected = '', $htmlname = 'yearid', $useempty = 0, $output_format = 'html')
422
+    {
423 423
         // phpcs:enable
424
-	    global $conf;
425
-
426
-		$out_array = array();
427
-
428
-		$sql = "SELECT DISTINCT date_format(doc_date,'%Y') as dtyear";
429
-		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
430
-	    $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
431
-		$sql .= " ORDER BY date_format(doc_date,'%Y')";
432
-		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
433
-		$resql = $this->db->query($sql);
434
-
435
-		if (!$resql) {
436
-			$this->error = "Error ".$this->db->lasterror();
437
-			dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
438
-			return -1;
439
-		}
440
-		while ($obj = $this->db->fetch_object($resql)) {
441
-			$out_array[$obj->dtyear] = $obj->dtyear;
442
-		}
443
-		$this->db->free($resql);
444
-
445
-		if ($output_format == 'html') {
446
-			return Form::selectarray($htmlname, $out_array, $selected, $useempty, 0, 0, 'placeholder="aa"');
447
-		} else {
448
-			return $out_array;
449
-		}
450
-	}
424
+        global $conf;
425
+
426
+        $out_array = array();
427
+
428
+        $sql = "SELECT DISTINCT date_format(doc_date,'%Y') as dtyear";
429
+        $sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
430
+        $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
431
+        $sql .= " ORDER BY date_format(doc_date,'%Y')";
432
+        dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
433
+        $resql = $this->db->query($sql);
434
+
435
+        if (!$resql) {
436
+            $this->error = "Error ".$this->db->lasterror();
437
+            dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
438
+            return -1;
439
+        }
440
+        while ($obj = $this->db->fetch_object($resql)) {
441
+            $out_array[$obj->dtyear] = $obj->dtyear;
442
+        }
443
+        $this->db->free($resql);
444
+
445
+        if ($output_format == 'html') {
446
+            return Form::selectarray($htmlname, $out_array, $selected, $useempty, 0, 0, 'placeholder="aa"');
447
+        } else {
448
+            return $out_array;
449
+        }
450
+    }
451 451
 }
Please login to merge, or discard this patch.
Spacing   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  *  \ingroup    Advanced accountancy
25 25
  *	\brief      File of class with all html predefined components
26 26
  */
27
-require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
27
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
28 28
 
29 29
 
30 30
 /**
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 	/**
44 44
 	 * @var string Error code (or message)
45 45
 	 */
46
-	public $error='';
46
+	public $error = '';
47 47
 
48 48
    /**
49 49
 	* Constructor
@@ -70,29 +70,29 @@  discard block
 block discarded – undo
70 70
 	 * @param   int     $disabledajaxcombo Disable ajax combo box.
71 71
 	 * @return	string				String with HTML select
72 72
 	 */
73
-	function select_journal($selectid, $htmlname = 'journal', $nature=0, $showempty = 0, $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='', $disabledajaxcombo=0)
73
+	function select_journal($selectid, $htmlname = 'journal', $nature = 0, $showempty = 0, $select_in = 0, $select_out = 0, $morecss = 'maxwidth300 maxwidthonsmartphone', $usecache = '', $disabledajaxcombo = 0)
74 74
 	{
75 75
         // phpcs:enable
76
-		global $conf,$langs;
76
+		global $conf, $langs;
77 77
 
78 78
 		$out = '';
79 79
 
80 80
     	$options = array();
81
-		if ($usecache && ! empty($this->options_cache[$usecache]))
81
+		if ($usecache && !empty($this->options_cache[$usecache]))
82 82
 		{
83 83
 		    $options = $this->options_cache[$usecache];
84
-		    $selected=$selectid;
84
+		    $selected = $selectid;
85 85
 		}
86 86
 		else
87 87
 		{
88 88
 			$sql = "SELECT rowid, code, label, nature, entity, active";
89
-			$sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
90
-			$sql.= " WHERE active = 1";
91
-			$sql.= " AND entity = ".$conf->entity;
89
+			$sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal";
90
+			$sql .= " WHERE active = 1";
91
+			$sql .= " AND entity = ".$conf->entity;
92 92
 			//if ($nature && is_numeric($nature))   $sql .= " AND nature = ".$nature;
93
-			$sql.= " ORDER BY code";
93
+			$sql .= " ORDER BY code";
94 94
 
95
-			dol_syslog(get_class($this) . "::select_journal", LOG_DEBUG);
95
+			dol_syslog(get_class($this)."::select_journal", LOG_DEBUG);
96 96
 			$resql = $this->db->query($sql);
97 97
 
98 98
 			if (!$resql) {
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 			$langs->load('accountancy');
106 106
 			while ($obj = $this->db->fetch_object($resql))
107 107
 			{
108
-				$label = $obj->code . ' - ' . $langs->trans($obj->label);
108
+				$label = $obj->code.' - '.$langs->trans($obj->label);
109 109
 
110 110
     			$select_value_in = $obj->rowid;
111 111
 				$select_value_out = $obj->rowid;
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 			}
134 134
 		}
135 135
 
136
-		$out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, ($disabledajaxcombo?0:1));
136
+		$out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, ($disabledajaxcombo ? 0 : 1));
137 137
 
138 138
 		return $out;
139 139
 	}
@@ -151,39 +151,39 @@  discard block
 block discarded – undo
151 151
      *  @param  int     $allcountries   All countries
152 152
      * 	@return	void
153 153
      */
154
-    function select_accounting_category($selected='',$htmlname='account_category', $useempty=0, $maxlen=0, $help=1, $allcountries=0)
154
+    function select_accounting_category($selected = '', $htmlname = 'account_category', $useempty = 0, $maxlen = 0, $help = 1, $allcountries = 0)
155 155
     {
156 156
         // phpcs:enable
157
-        global $db,$langs,$user,$mysoc;
157
+        global $db, $langs, $user, $mysoc;
158 158
 
159 159
         if (empty($mysoc->country_id) && empty($mysoc->country_code) && empty($allcountries))
160 160
         {
161
-            dol_print_error('','Call to select_accounting_account with mysoc country not yet defined');
161
+            dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined');
162 162
             exit;
163 163
         }
164 164
 
165
-        if (! empty($mysoc->country_id))
165
+        if (!empty($mysoc->country_id))
166 166
         {
167 167
             $sql = "SELECT c.rowid, c.label as type, c.range_account";
168
-            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
169
-            $sql.= " WHERE c.active = 1";
170
-			$sql.= " AND c.category_type = 0";
171
-            if (empty($allcountries)) $sql.= " AND c.fk_country = ".$mysoc->country_id;
172
-            $sql.= " ORDER BY c.label ASC";
168
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
169
+            $sql .= " WHERE c.active = 1";
170
+			$sql .= " AND c.category_type = 0";
171
+            if (empty($allcountries)) $sql .= " AND c.fk_country = ".$mysoc->country_id;
172
+            $sql .= " ORDER BY c.label ASC";
173 173
         }
174 174
         else
175 175
         {
176 176
             $sql = "SELECT c.rowid, c.label as type, c.range_account";
177
-            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
178
-            $sql.= " WHERE c.active = 1";
179
-			$sql.= " AND c.category_type = 0";
180
-			$sql.= " AND c.fk_country = co.rowid";
181
-            if (empty($allcountries)) $sql.= " AND co.code = '".$mysoc->country_code."'";
182
-            $sql.= " ORDER BY c.label ASC";
177
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
178
+            $sql .= " WHERE c.active = 1";
179
+			$sql .= " AND c.category_type = 0";
180
+			$sql .= " AND c.fk_country = co.rowid";
181
+            if (empty($allcountries)) $sql .= " AND co.code = '".$mysoc->country_code."'";
182
+            $sql .= " ORDER BY c.label ASC";
183 183
         }
184 184
 
185 185
         dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
186
-        $resql=$db->query($sql);
186
+        $resql = $db->query($sql);
187 187
         if ($resql)
188 188
         {
189 189
             $num = $db->num_rows($resql);
@@ -192,27 +192,27 @@  discard block
 block discarded – undo
192 192
                 $out = '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'">';
193 193
                 $i = 0;
194 194
 
195
-                if ($useempty) $out.= '<option value="0">&nbsp;</option>';
195
+                if ($useempty) $out .= '<option value="0">&nbsp;</option>';
196 196
                 while ($i < $num)
197 197
                 {
198 198
                     $obj = $db->fetch_object($resql);
199 199
                     $out .= '<option value="'.$obj->rowid.'"';
200 200
                     if ($obj->rowid == $selected) $out .= ' selected';
201
-                    $out .= '>'.($maxlen ? dol_trunc($obj->type,$maxlen) : $obj->type);
201
+                    $out .= '>'.($maxlen ? dol_trunc($obj->type, $maxlen) : $obj->type);
202 202
 					$out .= ' ('.$obj->range_account.')';
203 203
                     $i++;
204 204
                 }
205
-                $out .=  '</select>';
205
+                $out .= '</select>';
206 206
                 //if ($user->admin && $help) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
207 207
             }
208 208
             else
209 209
             {
210
-                $out .= $langs->trans("ErrorNoAccountingCategoryForThisCountry",$mysoc->country_code);
210
+                $out .= $langs->trans("ErrorNoAccountingCategoryForThisCountry", $mysoc->country_code);
211 211
             }
212 212
         }
213 213
         else
214 214
         {
215
-            dol_print_error($db,$db->lasterror());
215
+            dol_print_error($db, $db->lasterror());
216 216
         }
217 217
 
218 218
         $out .= ajax_combobox($htmlname, array());
@@ -233,17 +233,17 @@  discard block
 block discarded – undo
233 233
         // phpcs:enable
234 234
 		$options = array();
235 235
 
236
-		$sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping';
236
+		$sql = 'SELECT DISTINCT import_key from '.MAIN_DB_PREFIX.'accounting_bookkeeping';
237 237
 	    $sql .= " WHERE entity IN (".getEntity('accountancy').")";
238 238
 		$sql .= ' ORDER BY import_key DESC';
239 239
 
240
-		dol_syslog(get_class($this) . "::select_bookkeeping_importkey", LOG_DEBUG);
240
+		dol_syslog(get_class($this)."::select_bookkeeping_importkey", LOG_DEBUG);
241 241
 		$resql = $this->db->query($sql);
242 242
 
243 243
 		if (!$resql) {
244
-			$this->error = "Error " . $this->db->lasterror();
245
-			dol_syslog(get_class($this) . "::select_bookkeeping_importkey " . $this->error, LOG_ERR);
246
-			return - 1;
244
+			$this->error = "Error ".$this->db->lasterror();
245
+			dol_syslog(get_class($this)."::select_bookkeeping_importkey ".$this->error, LOG_ERR);
246
+			return -1;
247 247
 		}
248 248
 
249 249
 		while ($obj = $this->db->fetch_object($resql)) {
@@ -267,46 +267,46 @@  discard block
 block discarded – undo
267 267
 	 * @param string   $usecache           Key to use to store result into a cache. Next call with same key will reuse the cache.
268 268
 	 * @return string                      String with HTML select
269 269
 	 */
270
-	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
270
+	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss = 'maxwidth300 maxwidthonsmartphone', $usecache = '')
271 271
 	{
272 272
         // phpcs:enable
273 273
 		global $conf, $langs;
274 274
 
275
-		require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
275
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
276 276
 
277 277
 		$out = '';
278 278
 
279 279
     	$options = array();
280
-		if ($usecache && ! empty($this->options_cache[$usecache]))
280
+		if ($usecache && !empty($this->options_cache[$usecache]))
281 281
 		{
282 282
 		    $options = $this->options_cache[$usecache];
283
-		    $selected=$selectid;
283
+		    $selected = $selectid;
284 284
 		}
285 285
 		else
286 286
 		{
287 287
     		$trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT) ? 50 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT;
288 288
 
289 289
     		$sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version";
290
-    		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
291
-    		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
292
-    		$sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
290
+    		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_account as aa";
291
+    		$sql .= " INNER JOIN ".MAIN_DB_PREFIX."accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
292
+    		$sql .= " AND asy.rowid = ".$conf->global->CHARTOFACCOUNTS;
293 293
     		$sql .= " AND aa.active = 1";
294 294
     		$sql .= " AND aa.entity=".$conf->entity;
295 295
     		$sql .= " ORDER BY aa.account_number";
296 296
 
297
-    		dol_syslog(get_class($this) . "::select_account", LOG_DEBUG);
297
+    		dol_syslog(get_class($this)."::select_account", LOG_DEBUG);
298 298
     		$resql = $this->db->query($sql);
299 299
 
300 300
     		if (!$resql) {
301
-    			$this->error = "Error " . $this->db->lasterror();
302
-    			dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR);
301
+    			$this->error = "Error ".$this->db->lasterror();
302
+    			dol_syslog(get_class($this)."::select_account ".$this->error, LOG_ERR);
303 303
     			return -1;
304 304
     		}
305 305
 
306 306
     		$selected = 0;
307 307
     		while ($obj = $this->db->fetch_object($resql))
308 308
     		{
309
-    			$label = length_accountg($obj->account_number) . ' - ' . $obj->label;
309
+    			$label = length_accountg($obj->account_number).' - '.$obj->label;
310 310
     			$label = dol_trunc($label, $trunclength);
311 311
 
312 312
     			$select_value_in = $obj->rowid;
@@ -356,7 +356,7 @@  discard block
 block discarded – undo
356 356
 	 * @param string   $morecss        More css
357 357
 	 * @return string                  String with HTML select
358 358
 	 */
359
-    function select_auxaccount($selectid, $htmlname='account_num_aux', $showempty=0, $morecss='maxwidth200')
359
+    function select_auxaccount($selectid, $htmlname = 'account_num_aux', $showempty = 0, $morecss = 'maxwidth200')
360 360
     {
361 361
         // phpcs:enable
362 362
 
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
 		// Auxiliary customer account
366 366
 		$sql = "SELECT DISTINCT code_compta, nom ";
367 367
 		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
368
-	    $sql .= " WHERE entity IN (" . getEntity('societe') . ")";
368
+	    $sql .= " WHERE entity IN (".getEntity('societe').")";
369 369
 		$sql .= " ORDER BY code_compta";
370 370
 		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
371 371
 		$resql = $this->db->query($sql);
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 		// Auxiliary supplier account
386 386
 		$sql = "SELECT DISTINCT code_compta_fournisseur, nom ";
387 387
 		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
388
-		$sql .= " WHERE entity IN (" . getEntity('societe') . ")";
388
+		$sql .= " WHERE entity IN (".getEntity('societe').")";
389 389
 		$sql .= " ORDER BY code_compta_fournisseur";
390 390
 		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
391 391
 		$resql = $this->db->query($sql);
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
 
428 428
 		$sql = "SELECT DISTINCT date_format(doc_date,'%Y') as dtyear";
429 429
 		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
430
-	    $sql .= " WHERE entity IN (" . getEntity('accountancy') . ")";
430
+	    $sql .= " WHERE entity IN (".getEntity('accountancy').")";
431 431
 		$sql .= " ORDER BY date_format(doc_date,'%Y')";
432 432
 		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
433 433
 		$resql = $this->db->query($sql);
Please login to merge, or discard this patch.
Braces   +17 added lines, -14 removed lines patch added patch discarded remove patch
@@ -82,8 +82,7 @@  discard block
 block discarded – undo
82 82
 		{
83 83
 		    $options = $this->options_cache[$usecache];
84 84
 		    $selected=$selectid;
85
-		}
86
-		else
85
+		} else
87 86
 		{
88 87
 			$sql = "SELECT rowid, code, label, nature, entity, active";
89 88
 			$sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
@@ -168,17 +167,20 @@  discard block
 block discarded – undo
168 167
             $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
169 168
             $sql.= " WHERE c.active = 1";
170 169
 			$sql.= " AND c.category_type = 0";
171
-            if (empty($allcountries)) $sql.= " AND c.fk_country = ".$mysoc->country_id;
170
+            if (empty($allcountries)) {
171
+                $sql.= " AND c.fk_country = ".$mysoc->country_id;
172
+            }
172 173
             $sql.= " ORDER BY c.label ASC";
173
-        }
174
-        else
174
+        } else
175 175
         {
176 176
             $sql = "SELECT c.rowid, c.label as type, c.range_account";
177 177
             $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
178 178
             $sql.= " WHERE c.active = 1";
179 179
 			$sql.= " AND c.category_type = 0";
180 180
 			$sql.= " AND c.fk_country = co.rowid";
181
-            if (empty($allcountries)) $sql.= " AND co.code = '".$mysoc->country_code."'";
181
+            if (empty($allcountries)) {
182
+                $sql.= " AND co.code = '".$mysoc->country_code."'";
183
+            }
182 184
             $sql.= " ORDER BY c.label ASC";
183 185
         }
184 186
 
@@ -192,25 +194,27 @@  discard block
 block discarded – undo
192 194
                 $out = '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'">';
193 195
                 $i = 0;
194 196
 
195
-                if ($useempty) $out.= '<option value="0">&nbsp;</option>';
197
+                if ($useempty) {
198
+                    $out.= '<option value="0">&nbsp;</option>';
199
+                }
196 200
                 while ($i < $num)
197 201
                 {
198 202
                     $obj = $db->fetch_object($resql);
199 203
                     $out .= '<option value="'.$obj->rowid.'"';
200
-                    if ($obj->rowid == $selected) $out .= ' selected';
204
+                    if ($obj->rowid == $selected) {
205
+                        $out .= ' selected';
206
+                    }
201 207
                     $out .= '>'.($maxlen ? dol_trunc($obj->type,$maxlen) : $obj->type);
202 208
 					$out .= ' ('.$obj->range_account.')';
203 209
                     $i++;
204 210
                 }
205 211
                 $out .=  '</select>';
206 212
                 //if ($user->admin && $help) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
207
-            }
208
-            else
213
+            } else
209 214
             {
210 215
                 $out .= $langs->trans("ErrorNoAccountingCategoryForThisCountry",$mysoc->country_code);
211 216
             }
212
-        }
213
-        else
217
+        } else
214 218
         {
215 219
             dol_print_error($db,$db->lasterror());
216 220
         }
@@ -281,8 +285,7 @@  discard block
 block discarded – undo
281 285
 		{
282 286
 		    $options = $this->options_cache[$usecache];
283 287
 		    $selected=$selectid;
284
-		}
285
-		else
288
+		} else
286 289
 		{
287 290
     		$trunclength = empty($conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT) ? 50 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT;
288 291
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/vcard.class.php 2 patches
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -30,7 +30,7 @@  discard block
 block discarded – undo
30 30
  */
31 31
 function encode($string)
32 32
 {
33
-    return str_replace(";","\;",(dol_quoted_printable_encode(utf8_decode($string))));
33
+    return str_replace(";", "\;", (dol_quoted_printable_encode(utf8_decode($string))));
34 34
 }
35 35
 
36 36
 
@@ -42,9 +42,9 @@  discard block
 block discarded – undo
42 42
  * @param	int		$line_max	Max length of lines
43 43
  * @return	string				Encoded string
44 44
  */
45
-function dol_quoted_printable_encode($input, $line_max=76)
45
+function dol_quoted_printable_encode($input, $line_max = 76)
46 46
 {
47
-    $hex = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F');
47
+    $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
48 48
     $lines = preg_split("/(\?:\r\n|\r|\n)/", $input);
49 49
     $eol = "\r\n";
50 50
     $linebreak = "=0D=0A";
@@ -57,23 +57,23 @@  discard block
 block discarded – undo
57 57
         $line = $lines[$j];
58 58
         $linlen = strlen($line);
59 59
         $newline = "";
60
-        for($i = 0; $i < $linlen; $i++) {
60
+        for ($i = 0; $i < $linlen; $i++) {
61 61
             $c = substr($line, $i, 1);
62 62
             $dec = ord($c);
63
-            if ( ($dec == 32) && ($i == ($linlen - 1)) ) { // convert space at eol only
63
+            if (($dec == 32) && ($i == ($linlen - 1))) { // convert space at eol only
64 64
                 $c = "=20";
65
-            } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required
66
-                $h2 = floor($dec/16); $h1 = floor($dec%16);
65
+            } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) { // always encode "\t", which is *not* required
66
+                $h2 = floor($dec / 16); $h1 = floor($dec % 16);
67 67
                 $c = $escape.$hex["$h2"].$hex["$h1"];
68 68
             }
69
-            if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted
69
+            if ((strlen($newline) + strlen($c)) >= $line_max) { // CRLF is not counted
70 70
                 $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay
71 71
                 $newline = "    ";
72 72
             }
73 73
             $newline .= $c;
74 74
         } // end of for
75 75
         $output .= $newline;
76
-        if ($j<count($lines)-1) $output .= $linebreak;
76
+        if ($j < count($lines) - 1) $output .= $linebreak;
77 77
     }
78 78
     return trim($output);
79 79
 }
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
     var $filename;
89 89
 
90 90
     //var $encoding="UTF-8";
91
-    var $encoding="ISO-8859-1;ENCODING=QUOTED-PRINTABLE";
91
+    var $encoding = "ISO-8859-1;ENCODING=QUOTED-PRINTABLE";
92 92
 
93 93
 
94 94
     /**
@@ -98,12 +98,12 @@  discard block
 block discarded – undo
98 98
      *	@param	string	$type		Type
99 99
      *	@return	void
100 100
      */
101
-    function setPhoneNumber($number, $type="")
101
+    function setPhoneNumber($number, $type = "")
102 102
     {
103 103
         // type may be PREF | WORK | HOME | VOICE | FAX | MSG | CELL | PAGER | BBS | CAR | MODEM | ISDN | VIDEO or any senseful combination, e.g. "PREF;WORK;VOICE"
104 104
         $key = "TEL";
105
-        if ($type!="") $key .= ";".$type;
106
-        $key.= ";CHARSET=".$this->encoding;
105
+        if ($type != "") $key .= ";".$type;
106
+        $key .= ";CHARSET=".$this->encoding;
107 107
         $this->properties[$key] = encode($number);
108 108
     }
109 109
 
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
      *	@param	string	$suffix			Suffix
143 143
      *	@return	void
144 144
      */
145
-    function setName($family="", $first="", $additional="", $prefix="", $suffix="")
145
+    function setName($family = "", $first = "", $additional = "", $prefix = "", $suffix = "")
146 146
     {
147 147
         $this->properties["N;CHARSET=".$this->encoding] = encode($family).";".encode($first).";".encode($additional).";".encode($prefix).";".encode($suffix);
148 148
         $this->filename = "$first%20$family.vcf";
@@ -174,12 +174,12 @@  discard block
 block discarded – undo
174 174
      *	@param	string	$type			Type
175 175
      *	@return	void
176 176
      */
177
-    function setAddress($postoffice="", $extended="", $street="", $city="", $region="", $zip="", $country="", $type="HOME;POSTAL")
177
+    function setAddress($postoffice = "", $extended = "", $street = "", $city = "", $region = "", $zip = "", $country = "", $type = "HOME;POSTAL")
178 178
     {
179 179
         // $type may be DOM | INTL | POSTAL | PARCEL | HOME | WORK or any combination of these: e.g. "WORK;PARCEL;POSTAL"
180 180
         $key = "ADR";
181
-        if ($type!="") $key.= ";$type";
182
-        $key.= ";CHARSET=".$this->encoding;
181
+        if ($type != "") $key .= ";$type";
182
+        $key .= ";CHARSET=".$this->encoding;
183 183
         $this->properties[$key] = ";".encode($extended).";".encode($street).";".encode($city).";".encode($region).";".encode($zip).";".encode($country);
184 184
 
185 185
         if ($this->properties["LABEL;$type;CHARSET=".$this->encoding] == "")
@@ -201,16 +201,16 @@  discard block
 block discarded – undo
201 201
      *	@param	string	$type			Type
202 202
      *	@return	void
203 203
      */
204
-    function setLabel($postoffice="", $extended="", $street="", $city="", $region="", $zip="", $country="", $type="HOME;POSTAL")
204
+    function setLabel($postoffice = "", $extended = "", $street = "", $city = "", $region = "", $zip = "", $country = "", $type = "HOME;POSTAL")
205 205
     {
206 206
         $label = "";
207
-        if ($postoffice!="") $label.= "$postoffice\r\n";
208
-        if ($extended!="") $label.= "$extended\r\n";
209
-        if ($street!="") $label.= "$street\r\n";
210
-        if ($zip!="") $label.= "$zip ";
211
-        if ($city!="") $label.= "$city\r\n";
212
-        if ($region!="") $label.= "$region\r\n";
213
-        if ($country!="") $country.= "$country\r\n";
207
+        if ($postoffice != "") $label .= "$postoffice\r\n";
208
+        if ($extended != "") $label .= "$extended\r\n";
209
+        if ($street != "") $label .= "$street\r\n";
210
+        if ($zip != "") $label .= "$zip ";
211
+        if ($city != "") $label .= "$city\r\n";
212
+        if ($region != "") $label .= "$region\r\n";
213
+        if ($country != "") $country .= "$country\r\n";
214 214
 
215 215
         $this->properties["LABEL;$type;CHARSET=".$this->encoding] = encode($label);
216 216
     }
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
      *	@param	string	$type			Vcard type
223 223
      *	@return	void
224 224
      */
225
-    function setEmail($address,$type="internet,pref")
225
+    function setEmail($address, $type = "internet,pref")
226 226
     {
227 227
         $this->properties["EMAIL;TYPE=".$type] = $address;
228 228
     }
@@ -293,11 +293,11 @@  discard block
 block discarded – undo
293 293
      *  @param	string	$type		Type
294 294
      *	@return	void
295 295
      */
296
-    function setURL($url, $type="")
296
+    function setURL($url, $type = "")
297 297
     {
298 298
         // $type may be WORK | HOME
299 299
         $key = "URL";
300
-        if ($type!="") $key.= ";$type";
300
+        if ($type != "") $key .= ";$type";
301 301
         $this->properties[$key] = $url;
302 302
     }
303 303
 
@@ -309,15 +309,15 @@  discard block
 block discarded – undo
309 309
     function getVCard()
310 310
     {
311 311
         $text = "BEGIN:VCARD\r\n";
312
-        $text.= "VERSION:3.0\r\n";
312
+        $text .= "VERSION:3.0\r\n";
313 313
         //$text.= "VERSION:2.1\r\n";
314
-        foreach($this->properties as $key => $value)
314
+        foreach ($this->properties as $key => $value)
315 315
         {
316
-            $text.= "$key:$value\r\n";
316
+            $text .= "$key:$value\r\n";
317 317
         }
318
-        $text.= "REV:".date("Y-m-d")."T".date("H:i:s")."Z\r\n";
319
-        $text.= "MAILER: Dolibarr\r\n";
320
-        $text.= "END:VCARD\r\n";
318
+        $text .= "REV:".date("Y-m-d")."T".date("H:i:s")."Z\r\n";
319
+        $text .= "MAILER: Dolibarr\r\n";
320
+        $text .= "END:VCARD\r\n";
321 321
         return $text;
322 322
     }
323 323
 
Please login to merge, or discard this patch.
Braces   +36 added lines, -12 removed lines patch added patch discarded remove patch
@@ -73,7 +73,9 @@  discard block
 block discarded – undo
73 73
             $newline .= $c;
74 74
         } // end of for
75 75
         $output .= $newline;
76
-        if ($j<count($lines)-1) $output .= $linebreak;
76
+        if ($j<count($lines)-1) {
77
+            $output .= $linebreak;
78
+        }
77 79
     }
78 80
     return trim($output);
79 81
 }
@@ -102,7 +104,9 @@  discard block
 block discarded – undo
102 104
     {
103 105
         // type may be PREF | WORK | HOME | VOICE | FAX | MSG | CELL | PAGER | BBS | CAR | MODEM | ISDN | VIDEO or any senseful combination, e.g. "PREF;WORK;VOICE"
104 106
         $key = "TEL";
105
-        if ($type!="") $key .= ";".$type;
107
+        if ($type!="") {
108
+            $key .= ";".$type;
109
+        }
106 110
         $key.= ";CHARSET=".$this->encoding;
107 111
         $this->properties[$key] = encode($number);
108 112
     }
@@ -146,7 +150,9 @@  discard block
 block discarded – undo
146 150
     {
147 151
         $this->properties["N;CHARSET=".$this->encoding] = encode($family).";".encode($first).";".encode($additional).";".encode($prefix).";".encode($suffix);
148 152
         $this->filename = "$first%20$family.vcf";
149
-        if (empty($this->properties["FN"])) $this->setFormattedName(trim("$prefix $first $additional $family $suffix"));
153
+        if (empty($this->properties["FN"])) {
154
+            $this->setFormattedName(trim("$prefix $first $additional $family $suffix"));
155
+        }
150 156
     }
151 157
 
152 158
     /**
@@ -178,7 +184,9 @@  discard block
 block discarded – undo
178 184
     {
179 185
         // $type may be DOM | INTL | POSTAL | PARCEL | HOME | WORK or any combination of these: e.g. "WORK;PARCEL;POSTAL"
180 186
         $key = "ADR";
181
-        if ($type!="") $key.= ";$type";
187
+        if ($type!="") {
188
+            $key.= ";$type";
189
+        }
182 190
         $key.= ";CHARSET=".$this->encoding;
183 191
         $this->properties[$key] = ";".encode($extended).";".encode($street).";".encode($city).";".encode($region).";".encode($zip).";".encode($country);
184 192
 
@@ -204,13 +212,27 @@  discard block
 block discarded – undo
204 212
     function setLabel($postoffice="", $extended="", $street="", $city="", $region="", $zip="", $country="", $type="HOME;POSTAL")
205 213
     {
206 214
         $label = "";
207
-        if ($postoffice!="") $label.= "$postoffice\r\n";
208
-        if ($extended!="") $label.= "$extended\r\n";
209
-        if ($street!="") $label.= "$street\r\n";
210
-        if ($zip!="") $label.= "$zip ";
211
-        if ($city!="") $label.= "$city\r\n";
212
-        if ($region!="") $label.= "$region\r\n";
213
-        if ($country!="") $country.= "$country\r\n";
215
+        if ($postoffice!="") {
216
+            $label.= "$postoffice\r\n";
217
+        }
218
+        if ($extended!="") {
219
+            $label.= "$extended\r\n";
220
+        }
221
+        if ($street!="") {
222
+            $label.= "$street\r\n";
223
+        }
224
+        if ($zip!="") {
225
+            $label.= "$zip ";
226
+        }
227
+        if ($city!="") {
228
+            $label.= "$city\r\n";
229
+        }
230
+        if ($region!="") {
231
+            $label.= "$region\r\n";
232
+        }
233
+        if ($country!="") {
234
+            $country.= "$country\r\n";
235
+        }
214 236
 
215 237
         $this->properties["LABEL;$type;CHARSET=".$this->encoding] = encode($label);
216 238
     }
@@ -297,7 +319,9 @@  discard block
 block discarded – undo
297 319
     {
298 320
         // $type may be WORK | HOME
299 321
         $key = "URL";
300
-        if ($type!="") $key.= ";$type";
322
+        if ($type!="") {
323
+            $key.= ";$type";
324
+        }
301 325
         $this->properties[$key] = $url;
302 326
     }
303 327
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/commonstickergenerator.class.php 3 patches
Indentation   +192 added lines, -192 removed lines patch added patch discarded remove patch
@@ -61,226 +61,226 @@
 block discarded – undo
61 61
  */
62 62
 abstract class CommonStickerGenerator
63 63
 {
64
-	public $code;   // Code of format
64
+    public $code;   // Code of format
65 65
 
66
-	/**
66
+    /**
67 67
      * @var array format Array with informations
68 68
      */
69 69
     public $format;
70 70
 
71
-	// protected
72
-	var $_Avery_Name	= '';	// Nom du format de l'etiquette
73
-	var $_Margin_Left	= 0;	// Marge de gauche de l'etiquette
74
-	var $_Margin_Top	= 0;	// marge en haut de la page avant la premiere etiquette
75
-	var $_X_Space 	= 0;	// Espace horizontal entre 2 bandes d'etiquettes
76
-	var $_Y_Space 	= 0;	// Espace vertical entre 2 bandes d'etiquettes
77
-	var $_X_Number 	= 0;	// NX Nombre d'etiquettes sur la largeur de la page
78
-	var $_Y_Number 	= 0;	// NY Nombre d'etiquettes sur la hauteur de la page
79
-	var $_Width 		= 0;	// Largeur de chaque etiquette
80
-	var $_Height 		= 0;	// Hauteur de chaque etiquette
81
-	var $_Char_Size	= 10;	// Hauteur des caracteres
82
-	var $_Line_Height	= 10;	// Hauteur par defaut d'une ligne
83
-	var $_Metric 		= 'mm';	// Type of metric.. Will help to calculate good values
84
-	var $_Metric_Doc 	= 'mm';	// Type of metric for the doc..
85
-	var $_COUNTX = 1;
86
-	var $_COUNTY = 1;
87
-	var $_First = 1;
88
-	var $Tformat;
71
+    // protected
72
+    var $_Avery_Name	= '';	// Nom du format de l'etiquette
73
+    var $_Margin_Left	= 0;	// Marge de gauche de l'etiquette
74
+    var $_Margin_Top	= 0;	// marge en haut de la page avant la premiere etiquette
75
+    var $_X_Space 	= 0;	// Espace horizontal entre 2 bandes d'etiquettes
76
+    var $_Y_Space 	= 0;	// Espace vertical entre 2 bandes d'etiquettes
77
+    var $_X_Number 	= 0;	// NX Nombre d'etiquettes sur la largeur de la page
78
+    var $_Y_Number 	= 0;	// NY Nombre d'etiquettes sur la hauteur de la page
79
+    var $_Width 		= 0;	// Largeur de chaque etiquette
80
+    var $_Height 		= 0;	// Hauteur de chaque etiquette
81
+    var $_Char_Size	= 10;	// Hauteur des caracteres
82
+    var $_Line_Height	= 10;	// Hauteur par defaut d'une ligne
83
+    var $_Metric 		= 'mm';	// Type of metric.. Will help to calculate good values
84
+    var $_Metric_Doc 	= 'mm';	// Type of metric for the doc..
85
+    var $_COUNTX = 1;
86
+    var $_COUNTY = 1;
87
+    var $_First = 1;
88
+    var $Tformat;
89 89
 
90
-	/**
91
-	 *	Constructor
92
-	 *
93
-	 *  @param		DoliDB		$db      Database handler
94
-	 */
95
-	function __construct($db)
96
-	{
97
-		$this->db = $db;
98
-	}
90
+    /**
91
+     *	Constructor
92
+     *
93
+     *  @param		DoliDB		$db      Database handler
94
+     */
95
+    function __construct($db)
96
+    {
97
+        $this->db = $db;
98
+    }
99 99
 
100 100
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
101
-	/**
102
-	 *  Function to build PDF on disk, then output on HTTP strem.
103
-	 *
104
-	 *  @param	array		$arrayofrecords  	Array of record informations (array('textleft'=>,'textheader'=>, ..., 'id'=>,'photo'=>)
105
-	 *  @param  Translate	$outputlangs     	Lang object for output language
106
-	 *  @param	string		$srctemplatepath	Full path of source filename for generator using a template file
107
-	 *	@param	string		$outputdir			Output directory for pdf file
108
-	 *  @return int             				1=OK, 0=KO
109
-	 */
110
-	abstract function write_file($arrayofrecords,$outputlangs,$srctemplatepath,$outputdir='');
101
+    /**
102
+     *  Function to build PDF on disk, then output on HTTP strem.
103
+     *
104
+     *  @param	array		$arrayofrecords  	Array of record informations (array('textleft'=>,'textheader'=>, ..., 'id'=>,'photo'=>)
105
+     *  @param  Translate	$outputlangs     	Lang object for output language
106
+     *  @param	string		$srctemplatepath	Full path of source filename for generator using a template file
107
+     *	@param	string		$outputdir			Output directory for pdf file
108
+     *  @return int             				1=OK, 0=KO
109
+     */
110
+    abstract function write_file($arrayofrecords,$outputlangs,$srctemplatepath,$outputdir='');
111 111
     // phpcs:enable
112 112
 
113
-	/**
114
-	 * Output a sticker on page at position _COUNTX, _COUNTY (_COUNTX and _COUNTY start from 0)
115
-	 *
116
-	 * @param   PDF         $pdf            PDF reference
117
-	 * @param   Translate  	$outputlangs    Output langs
118
-	 * @param   array     	$param          Associative array containing label content and optional parameters
119
-	 * @return  void
120
-	 */
121
-	abstract function addSticker(&$pdf,$outputlangs,$param);
113
+    /**
114
+     * Output a sticker on page at position _COUNTX, _COUNTY (_COUNTX and _COUNTY start from 0)
115
+     *
116
+     * @param   PDF         $pdf            PDF reference
117
+     * @param   Translate  	$outputlangs    Output langs
118
+     * @param   array     	$param          Associative array containing label content and optional parameters
119
+     * @return  void
120
+     */
121
+    abstract function addSticker(&$pdf,$outputlangs,$param);
122 122
 
123 123
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
124
-	/**
125
-	 * Methode qui permet de modifier la taille des caracteres
126
-	 * Cela modiera aussi l'espace entre chaque ligne
127
-	 *
128
-	 * @param    PDF        $pdf   PDF reference
129
-	 * @param    int        $pt    point
130
-	 * @return   void
131
-	 */
132
-	function Set_Char_Size(&$pdf,$pt)
133
-	{
124
+    /**
125
+     * Methode qui permet de modifier la taille des caracteres
126
+     * Cela modiera aussi l'espace entre chaque ligne
127
+     *
128
+     * @param    PDF        $pdf   PDF reference
129
+     * @param    int        $pt    point
130
+     * @return   void
131
+     */
132
+    function Set_Char_Size(&$pdf,$pt)
133
+    {
134 134
         // phpcs:enable
135
-		if ($pt > 3) {
136
-			$this->_Char_Size = $pt;
137
-			$this->_Line_Height = $this->_Get_Height_Chars($pt);
138
-			$pdf->SetFont('','',$pt);
139
-		}
140
-	}
135
+        if ($pt > 3) {
136
+            $this->_Char_Size = $pt;
137
+            $this->_Line_Height = $this->_Get_Height_Chars($pt);
138
+            $pdf->SetFont('','',$pt);
139
+        }
140
+    }
141 141
 
142 142
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
143
-	/**
144
-	 * protected Print dot line
145
-	 *
146
-	 * @param	PDF     $pdf                PDF reference
147
-	 * @param 	int		$x1					X1
148
-	 * @param 	int		$y1					Y1
149
-	 * @param 	int		$x2					X2
150
-	 * @param 	int		$y2					Y2
151
-	 * @param 	int		$epaisseur			Epaisseur
152
-	 * @param 	int		$nbPointilles		Nb pointilles
153
-	 * @return	void
154
-	 */
143
+    /**
144
+     * protected Print dot line
145
+     *
146
+     * @param	PDF     $pdf                PDF reference
147
+     * @param 	int		$x1					X1
148
+     * @param 	int		$y1					Y1
149
+     * @param 	int		$x2					X2
150
+     * @param 	int		$y2					Y2
151
+     * @param 	int		$epaisseur			Epaisseur
152
+     * @param 	int		$nbPointilles		Nb pointilles
153
+     * @return	void
154
+     */
155 155
     function _Pointille(&$pdf,$x1=0,$y1=0,$x2=210,$y2=297,$epaisseur=1,$nbPointilles=15)
156
-	{
156
+    {
157 157
         // phpcs:enable
158
-		$pdf->SetLineWidth($epaisseur);
159
-		$length=abs($x1-$x2);
160
-		$hauteur=abs($y1-$y2);
161
-		if($length>$hauteur) {
162
-			$Pointilles=($length/$nbPointilles)/2; // taille des pointilles
163
-		}
164
-		else {
165
-			$Pointilles=($hauteur/$nbPointilles)/2;
166
-		}
167
-		for($i=$x1;$i<=$x2;$i+=$Pointilles+$Pointilles) {
168
-			for($j=$i;$j<=($i+$Pointilles);$j++) {
169
-				if($j<=($x2-1)) {
170
-		$pdf->Line($j,$y1,$j+1,$y1); // on trace le pointill? du haut, point par point
171
-		$pdf->Line($j,$y2,$j+1,$y2); // on trace le pointill? du bas, point par point
172
-				}
173
-			}
174
-		}
175
-		for($i=$y1;$i<=$y2;$i+=$Pointilles+$Pointilles) {
176
-			for($j=$i;$j<=($i+$Pointilles);$j++) {
177
-				if($j<=($y2-1)) {
178
-		$pdf->Line($x1,$j,$x1,$j+1); // on trace le pointill? du haut, point par point
179
-		$pdf->Line($x2,$j,$x2,$j+1); // on trace le pointill? du bas, point par point
180
-				}
181
-			}
182
-		}
183
-	}
158
+        $pdf->SetLineWidth($epaisseur);
159
+        $length=abs($x1-$x2);
160
+        $hauteur=abs($y1-$y2);
161
+        if($length>$hauteur) {
162
+            $Pointilles=($length/$nbPointilles)/2; // taille des pointilles
163
+        }
164
+        else {
165
+            $Pointilles=($hauteur/$nbPointilles)/2;
166
+        }
167
+        for($i=$x1;$i<=$x2;$i+=$Pointilles+$Pointilles) {
168
+            for($j=$i;$j<=($i+$Pointilles);$j++) {
169
+                if($j<=($x2-1)) {
170
+        $pdf->Line($j,$y1,$j+1,$y1); // on trace le pointill? du haut, point par point
171
+        $pdf->Line($j,$y2,$j+1,$y2); // on trace le pointill? du bas, point par point
172
+                }
173
+            }
174
+        }
175
+        for($i=$y1;$i<=$y2;$i+=$Pointilles+$Pointilles) {
176
+            for($j=$i;$j<=($i+$Pointilles);$j++) {
177
+                if($j<=($y2-1)) {
178
+        $pdf->Line($x1,$j,$x1,$j+1); // on trace le pointill? du haut, point par point
179
+        $pdf->Line($x2,$j,$x2,$j+1); // on trace le pointill? du bas, point par point
180
+                }
181
+            }
182
+        }
183
+    }
184 184
 
185 185
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
186
-	/**
187
-	 * protected Function realisant une croix aux 4 coins des cartes
188
-	 *
189
-	 * @param PDF   $pdf                PDF reference
190
-	 * @param int   $x1					X1
191
-	 * @param int	$y1					Y1
192
-	 * @param int	$x2					X2
193
-	 * @param int	$y2					Y2
194
-	 * @param int	$epaisseur			Epaisseur
195
-	 * @param int	$taille             Size
196
-	 * @return void
197
-	 */
198
-	function _Croix(&$pdf,$x1=0,$y1=0,$x2=210,$y2=297,$epaisseur=1,$taille=4)
199
-	{
186
+    /**
187
+     * protected Function realisant une croix aux 4 coins des cartes
188
+     *
189
+     * @param PDF   $pdf                PDF reference
190
+     * @param int   $x1					X1
191
+     * @param int	$y1					Y1
192
+     * @param int	$x2					X2
193
+     * @param int	$y2					Y2
194
+     * @param int	$epaisseur			Epaisseur
195
+     * @param int	$taille             Size
196
+     * @return void
197
+     */
198
+    function _Croix(&$pdf,$x1=0,$y1=0,$x2=210,$y2=297,$epaisseur=1,$taille=4)
199
+    {
200 200
         // phpcs:enable
201
-		$pdf->SetDrawColor(192,192,192);
201
+        $pdf->SetDrawColor(192,192,192);
202 202
 
203
-		$pdf->SetLineWidth($epaisseur);
204
-		$lg=$taille/2;
205
-		// croix haut gauche
206
-		$pdf->Line($x1,$y1-$lg,$x1,$y1+$lg);
207
-		$pdf->Line($x1-$lg,$y1,$x1+$lg,$y1);
208
-		// croix bas gauche
209
-		$pdf->Line($x1,$y2-$lg,$x1,$y2+$lg);
210
-		$pdf->Line($x1-$lg,$y2,$x1+$lg,$y2);
211
-		// croix haut droit
212
-		$pdf->Line($x2,$y1-$lg,$x2,$y1+$lg);
213
-		$pdf->Line($x2-$lg,$y1,$x2+$lg,$y1);
214
-		// croix bas droit
215
-		$pdf->Line($x2,$y2-$lg,$x2,$y2+$lg);
216
-		$pdf->Line($x2-$lg,$y2,$x2+$lg,$y2);
203
+        $pdf->SetLineWidth($epaisseur);
204
+        $lg=$taille/2;
205
+        // croix haut gauche
206
+        $pdf->Line($x1,$y1-$lg,$x1,$y1+$lg);
207
+        $pdf->Line($x1-$lg,$y1,$x1+$lg,$y1);
208
+        // croix bas gauche
209
+        $pdf->Line($x1,$y2-$lg,$x1,$y2+$lg);
210
+        $pdf->Line($x1-$lg,$y2,$x1+$lg,$y2);
211
+        // croix haut droit
212
+        $pdf->Line($x2,$y1-$lg,$x2,$y1+$lg);
213
+        $pdf->Line($x2-$lg,$y1,$x2+$lg,$y1);
214
+        // croix bas droit
215
+        $pdf->Line($x2,$y2-$lg,$x2,$y2+$lg);
216
+        $pdf->Line($x2-$lg,$y2,$x2+$lg,$y2);
217 217
 
218
-		$pdf->SetDrawColor(0,0,0);
219
-	}
218
+        $pdf->SetDrawColor(0,0,0);
219
+    }
220 220
 
221
-	/**
222
-	 * Convert units (in to mm, mm to in)
223
-	 * $src and $dest must be 'in' or 'mm'
224
-	 *
225
-	 * @param int       $value  value
226
-	 * @param string    $src    from ('in' or 'mm')
227
-	 * @param string    $dest   to ('in' or 'mm')
228
-	 * @return float    value   value after conversion
229
-	 */
230
-	private function convertMetric($value, $src, $dest)
231
-	{
232
-		if ($src != $dest) {
233
-			$tab = array(
234
-				'in'=>39.37008,
235
-				'mm'=>1000
236
-			);
237
-			return $value * $tab[$dest] / $tab[$src];
238
-		}
221
+    /**
222
+     * Convert units (in to mm, mm to in)
223
+     * $src and $dest must be 'in' or 'mm'
224
+     *
225
+     * @param int       $value  value
226
+     * @param string    $src    from ('in' or 'mm')
227
+     * @param string    $dest   to ('in' or 'mm')
228
+     * @return float    value   value after conversion
229
+     */
230
+    private function convertMetric($value, $src, $dest)
231
+    {
232
+        if ($src != $dest) {
233
+            $tab = array(
234
+                'in'=>39.37008,
235
+                'mm'=>1000
236
+            );
237
+            return $value * $tab[$dest] / $tab[$src];
238
+        }
239 239
 
240
-		return $value;
241
-	}
240
+        return $value;
241
+    }
242 242
 
243 243
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
244
-	/**
245
-	 * protected Give the height for a char size given.
246
-	 *
247
-	 * @param  int    $pt    Point
248
-	 * @return int           Height chars
249
-	 */
250
-	function _Get_Height_Chars($pt)
251
-	{
244
+    /**
245
+     * protected Give the height for a char size given.
246
+     *
247
+     * @param  int    $pt    Point
248
+     * @return int           Height chars
249
+     */
250
+    function _Get_Height_Chars($pt)
251
+    {
252 252
         // phpcs:enable
253
-		// Tableau de concordance entre la hauteur des caracteres et de l'espacement entre les lignes
254
-		$_Table_Hauteur_Chars = array(6=>2, 7=>2.5, 8=>3, 9=>3.5, 10=>4, 11=>6, 12=>7, 13=>8, 14=>9, 15=>10);
255
-		if (in_array($pt, array_keys($_Table_Hauteur_Chars))) {
256
-			return $_Table_Hauteur_Chars[$pt];
257
-		} else {
258
-			return 100; // There is a prob..
259
-		}
260
-	}
253
+        // Tableau de concordance entre la hauteur des caracteres et de l'espacement entre les lignes
254
+        $_Table_Hauteur_Chars = array(6=>2, 7=>2.5, 8=>3, 9=>3.5, 10=>4, 11=>6, 12=>7, 13=>8, 14=>9, 15=>10);
255
+        if (in_array($pt, array_keys($_Table_Hauteur_Chars))) {
256
+            return $_Table_Hauteur_Chars[$pt];
257
+        } else {
258
+            return 100; // There is a prob..
259
+        }
260
+    }
261 261
 
262 262
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
263
-	/**
264
-	 * protected Set format
265
-	 *
266
-	 * @param    PDF       $pdf     PDF reference
267
-	 * @param    string    $format  Format
268
-	 * @return   void
269
-	 */
270
-	function _Set_Format(&$pdf, $format)
271
-	{
263
+    /**
264
+     * protected Set format
265
+     *
266
+     * @param    PDF       $pdf     PDF reference
267
+     * @param    string    $format  Format
268
+     * @return   void
269
+     */
270
+    function _Set_Format(&$pdf, $format)
271
+    {
272 272
         // phpcs:enable
273
-		$this->_Metric = $format['metric'];
274
-		$this->_Avery_Name = $format['name'];
275
-		$this->_Avery_Code = $format['code'];
276
-		$this->_Margin_Left	= $this->convertMetric($format['marginLeft'], $this->_Metric, $this->_Metric_Doc);
277
-		$this->_Margin_Top = $this->convertMetric($format['marginTop'], $this->_Metric, $this->_Metric_Doc);
278
-		$this->_X_Space = $this->convertMetric($format['SpaceX'], $this->_Metric, $this->_Metric_Doc);
279
-		$this->_Y_Space = $this->convertMetric($format['SpaceY'], $this->_Metric, $this->_Metric_Doc);
280
-		$this->_X_Number = $format['NX'];
281
-		$this->_Y_Number = $format['NY'];
282
-		$this->_Width = $this->convertMetric($format['width'], $this->_Metric, $this->_Metric_Doc);
283
-		$this->_Height = $this->convertMetric($format['height'], $this->_Metric, $this->_Metric_Doc);
284
-		$this->Set_Char_Size($pdf, $format['font-size']);
285
-	}
273
+        $this->_Metric = $format['metric'];
274
+        $this->_Avery_Name = $format['name'];
275
+        $this->_Avery_Code = $format['code'];
276
+        $this->_Margin_Left	= $this->convertMetric($format['marginLeft'], $this->_Metric, $this->_Metric_Doc);
277
+        $this->_Margin_Top = $this->convertMetric($format['marginTop'], $this->_Metric, $this->_Metric_Doc);
278
+        $this->_X_Space = $this->convertMetric($format['SpaceX'], $this->_Metric, $this->_Metric_Doc);
279
+        $this->_Y_Space = $this->convertMetric($format['SpaceY'], $this->_Metric, $this->_Metric_Doc);
280
+        $this->_X_Number = $format['NX'];
281
+        $this->_Y_Number = $format['NY'];
282
+        $this->_Width = $this->convertMetric($format['width'], $this->_Metric, $this->_Metric_Doc);
283
+        $this->_Height = $this->convertMetric($format['height'], $this->_Metric, $this->_Metric_Doc);
284
+        $this->Set_Char_Size($pdf, $format['font-size']);
285
+    }
286 286
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
  */
62 62
 abstract class CommonStickerGenerator
63 63
 {
64
-	public $code;   // Code of format
64
+	public $code; // Code of format
65 65
 
66 66
 	/**
67 67
      * @var array format Array with informations
@@ -69,19 +69,19 @@  discard block
 block discarded – undo
69 69
     public $format;
70 70
 
71 71
 	// protected
72
-	var $_Avery_Name	= '';	// Nom du format de l'etiquette
73
-	var $_Margin_Left	= 0;	// Marge de gauche de l'etiquette
74
-	var $_Margin_Top	= 0;	// marge en haut de la page avant la premiere etiquette
75
-	var $_X_Space 	= 0;	// Espace horizontal entre 2 bandes d'etiquettes
76
-	var $_Y_Space 	= 0;	// Espace vertical entre 2 bandes d'etiquettes
77
-	var $_X_Number 	= 0;	// NX Nombre d'etiquettes sur la largeur de la page
78
-	var $_Y_Number 	= 0;	// NY Nombre d'etiquettes sur la hauteur de la page
79
-	var $_Width 		= 0;	// Largeur de chaque etiquette
80
-	var $_Height 		= 0;	// Hauteur de chaque etiquette
81
-	var $_Char_Size	= 10;	// Hauteur des caracteres
82
-	var $_Line_Height	= 10;	// Hauteur par defaut d'une ligne
83
-	var $_Metric 		= 'mm';	// Type of metric.. Will help to calculate good values
84
-	var $_Metric_Doc 	= 'mm';	// Type of metric for the doc..
72
+	var $_Avery_Name	= ''; // Nom du format de l'etiquette
73
+	var $_Margin_Left = 0; // Marge de gauche de l'etiquette
74
+	var $_Margin_Top	= 0; // marge en haut de la page avant la premiere etiquette
75
+	var $_X_Space 	= 0; // Espace horizontal entre 2 bandes d'etiquettes
76
+	var $_Y_Space 	= 0; // Espace vertical entre 2 bandes d'etiquettes
77
+	var $_X_Number 	= 0; // NX Nombre d'etiquettes sur la largeur de la page
78
+	var $_Y_Number 	= 0; // NY Nombre d'etiquettes sur la hauteur de la page
79
+	var $_Width = 0; // Largeur de chaque etiquette
80
+	var $_Height 		= 0; // Hauteur de chaque etiquette
81
+	var $_Char_Size	= 10; // Hauteur des caracteres
82
+	var $_Line_Height	= 10; // Hauteur par defaut d'une ligne
83
+	var $_Metric 		= 'mm'; // Type of metric.. Will help to calculate good values
84
+	var $_Metric_Doc 	= 'mm'; // Type of metric for the doc..
85 85
 	var $_COUNTX = 1;
86 86
 	var $_COUNTY = 1;
87 87
 	var $_First = 1;
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 	 *	@param	string		$outputdir			Output directory for pdf file
108 108
 	 *  @return int             				1=OK, 0=KO
109 109
 	 */
110
-	abstract function write_file($arrayofrecords,$outputlangs,$srctemplatepath,$outputdir='');
110
+	abstract function write_file($arrayofrecords, $outputlangs, $srctemplatepath, $outputdir = '');
111 111
     // phpcs:enable
112 112
 
113 113
 	/**
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
 	 * @param   array     	$param          Associative array containing label content and optional parameters
119 119
 	 * @return  void
120 120
 	 */
121
-	abstract function addSticker(&$pdf,$outputlangs,$param);
121
+	abstract function addSticker(&$pdf, $outputlangs, $param);
122 122
 
123 123
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
124 124
 	/**
@@ -129,13 +129,13 @@  discard block
 block discarded – undo
129 129
 	 * @param    int        $pt    point
130 130
 	 * @return   void
131 131
 	 */
132
-	function Set_Char_Size(&$pdf,$pt)
132
+	function Set_Char_Size(&$pdf, $pt)
133 133
 	{
134 134
         // phpcs:enable
135 135
 		if ($pt > 3) {
136 136
 			$this->_Char_Size = $pt;
137 137
 			$this->_Line_Height = $this->_Get_Height_Chars($pt);
138
-			$pdf->SetFont('','',$pt);
138
+			$pdf->SetFont('', '', $pt);
139 139
 		}
140 140
 	}
141 141
 
@@ -152,31 +152,31 @@  discard block
 block discarded – undo
152 152
 	 * @param 	int		$nbPointilles		Nb pointilles
153 153
 	 * @return	void
154 154
 	 */
155
-    function _Pointille(&$pdf,$x1=0,$y1=0,$x2=210,$y2=297,$epaisseur=1,$nbPointilles=15)
155
+    function _Pointille(&$pdf, $x1 = 0, $y1 = 0, $x2 = 210, $y2 = 297, $epaisseur = 1, $nbPointilles = 15)
156 156
 	{
157 157
         // phpcs:enable
158 158
 		$pdf->SetLineWidth($epaisseur);
159
-		$length=abs($x1-$x2);
160
-		$hauteur=abs($y1-$y2);
161
-		if($length>$hauteur) {
162
-			$Pointilles=($length/$nbPointilles)/2; // taille des pointilles
159
+		$length = abs($x1 - $x2);
160
+		$hauteur = abs($y1 - $y2);
161
+		if ($length > $hauteur) {
162
+			$Pointilles = ($length / $nbPointilles) / 2; // taille des pointilles
163 163
 		}
164 164
 		else {
165
-			$Pointilles=($hauteur/$nbPointilles)/2;
165
+			$Pointilles = ($hauteur / $nbPointilles) / 2;
166 166
 		}
167
-		for($i=$x1;$i<=$x2;$i+=$Pointilles+$Pointilles) {
168
-			for($j=$i;$j<=($i+$Pointilles);$j++) {
169
-				if($j<=($x2-1)) {
170
-		$pdf->Line($j,$y1,$j+1,$y1); // on trace le pointill? du haut, point par point
171
-		$pdf->Line($j,$y2,$j+1,$y2); // on trace le pointill? du bas, point par point
167
+		for ($i = $x1; $i <= $x2; $i += $Pointilles + $Pointilles) {
168
+			for ($j = $i; $j <= ($i + $Pointilles); $j++) {
169
+				if ($j <= ($x2 - 1)) {
170
+		$pdf->Line($j, $y1, $j + 1, $y1); // on trace le pointill? du haut, point par point
171
+		$pdf->Line($j, $y2, $j + 1, $y2); // on trace le pointill? du bas, point par point
172 172
 				}
173 173
 			}
174 174
 		}
175
-		for($i=$y1;$i<=$y2;$i+=$Pointilles+$Pointilles) {
176
-			for($j=$i;$j<=($i+$Pointilles);$j++) {
177
-				if($j<=($y2-1)) {
178
-		$pdf->Line($x1,$j,$x1,$j+1); // on trace le pointill? du haut, point par point
179
-		$pdf->Line($x2,$j,$x2,$j+1); // on trace le pointill? du bas, point par point
175
+		for ($i = $y1; $i <= $y2; $i += $Pointilles + $Pointilles) {
176
+			for ($j = $i; $j <= ($i + $Pointilles); $j++) {
177
+				if ($j <= ($y2 - 1)) {
178
+		$pdf->Line($x1, $j, $x1, $j + 1); // on trace le pointill? du haut, point par point
179
+		$pdf->Line($x2, $j, $x2, $j + 1); // on trace le pointill? du bas, point par point
180 180
 				}
181 181
 			}
182 182
 		}
@@ -195,27 +195,27 @@  discard block
 block discarded – undo
195 195
 	 * @param int	$taille             Size
196 196
 	 * @return void
197 197
 	 */
198
-	function _Croix(&$pdf,$x1=0,$y1=0,$x2=210,$y2=297,$epaisseur=1,$taille=4)
198
+	function _Croix(&$pdf, $x1 = 0, $y1 = 0, $x2 = 210, $y2 = 297, $epaisseur = 1, $taille = 4)
199 199
 	{
200 200
         // phpcs:enable
201
-		$pdf->SetDrawColor(192,192,192);
201
+		$pdf->SetDrawColor(192, 192, 192);
202 202
 
203 203
 		$pdf->SetLineWidth($epaisseur);
204
-		$lg=$taille/2;
204
+		$lg = $taille / 2;
205 205
 		// croix haut gauche
206
-		$pdf->Line($x1,$y1-$lg,$x1,$y1+$lg);
207
-		$pdf->Line($x1-$lg,$y1,$x1+$lg,$y1);
206
+		$pdf->Line($x1, $y1 - $lg, $x1, $y1 + $lg);
207
+		$pdf->Line($x1 - $lg, $y1, $x1 + $lg, $y1);
208 208
 		// croix bas gauche
209
-		$pdf->Line($x1,$y2-$lg,$x1,$y2+$lg);
210
-		$pdf->Line($x1-$lg,$y2,$x1+$lg,$y2);
209
+		$pdf->Line($x1, $y2 - $lg, $x1, $y2 + $lg);
210
+		$pdf->Line($x1 - $lg, $y2, $x1 + $lg, $y2);
211 211
 		// croix haut droit
212
-		$pdf->Line($x2,$y1-$lg,$x2,$y1+$lg);
213
-		$pdf->Line($x2-$lg,$y1,$x2+$lg,$y1);
212
+		$pdf->Line($x2, $y1 - $lg, $x2, $y1 + $lg);
213
+		$pdf->Line($x2 - $lg, $y1, $x2 + $lg, $y1);
214 214
 		// croix bas droit
215
-		$pdf->Line($x2,$y2-$lg,$x2,$y2+$lg);
216
-		$pdf->Line($x2-$lg,$y2,$x2+$lg,$y2);
215
+		$pdf->Line($x2, $y2 - $lg, $x2, $y2 + $lg);
216
+		$pdf->Line($x2 - $lg, $y2, $x2 + $lg, $y2);
217 217
 
218
-		$pdf->SetDrawColor(0,0,0);
218
+		$pdf->SetDrawColor(0, 0, 0);
219 219
 	}
220 220
 
221 221
 	/**
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 		$this->_Metric = $format['metric'];
274 274
 		$this->_Avery_Name = $format['name'];
275 275
 		$this->_Avery_Code = $format['code'];
276
-		$this->_Margin_Left	= $this->convertMetric($format['marginLeft'], $this->_Metric, $this->_Metric_Doc);
276
+		$this->_Margin_Left = $this->convertMetric($format['marginLeft'], $this->_Metric, $this->_Metric_Doc);
277 277
 		$this->_Margin_Top = $this->convertMetric($format['marginTop'], $this->_Metric, $this->_Metric_Doc);
278 278
 		$this->_X_Space = $this->convertMetric($format['SpaceX'], $this->_Metric, $this->_Metric_Doc);
279 279
 		$this->_Y_Space = $this->convertMetric($format['SpaceY'], $this->_Metric, $this->_Metric_Doc);
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -160,8 +160,7 @@
 block discarded – undo
160 160
 		$hauteur=abs($y1-$y2);
161 161
 		if($length>$hauteur) {
162 162
 			$Pointilles=($length/$nbPointilles)/2; // taille des pointilles
163
-		}
164
-		else {
163
+		} else {
165 164
 			$Pointilles=($hauteur/$nbPointilles)/2;
166 165
 		}
167 166
 		for($i=$x1;$i<=$x2;$i+=$Pointilles+$Pointilles) {
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formsocialcontrib.class.php 3 patches
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -27,26 +27,26 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class FormSocialContrib
29 29
 {
30
-	/**
30
+    /**
31 31
      * @var DoliDB Database handler.
32 32
      */
33 33
     public $db;
34 34
 
35
-	/**
36
-	 * @var string Error code (or message)
37
-	 */
38
-	public $error='';
35
+    /**
36
+     * @var string Error code (or message)
37
+     */
38
+    public $error='';
39 39
 
40 40
 
41
-	/**
42
-	* Constructor
43
-	*
44
-	* @param		DoliDB		$db      Database handler
45
-	*/
46
-	public function __construct($db)
47
-	{
48
-	    $this->db = $db;
49
-	}
41
+    /**
42
+     * Constructor
43
+     *
44
+     * @param		DoliDB		$db      Database handler
45
+     */
46
+    public function __construct($db)
47
+    {
48
+        $this->db = $db;
49
+    }
50 50
 
51 51
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
52 52
     /**
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
             $num = $db->num_rows($resql);
97 97
             if ($num)
98 98
             {
99
-            	print '<select class="'.($morecss?$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
99
+                print '<select class="'.($morecss?$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
100 100
                 $i = 0;
101 101
 
102 102
                 if ($useempty) print '<option value="0">&nbsp;</option>';
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	/**
36 36
 	 * @var string Error code (or message)
37 37
 	 */
38
-	public $error='';
38
+	public $error = '';
39 39
 
40 40
 
41 41
 	/**
@@ -61,42 +61,42 @@  discard block
 block discarded – undo
61 61
      *  @param	string	$morecss		Add more CSS on select
62 62
      * 	@return	void
63 63
      */
64
-    function select_type_socialcontrib($selected='',$htmlname='actioncode', $useempty=0, $maxlen=40, $help=1, $morecss='minwidth300')
64
+    function select_type_socialcontrib($selected = '', $htmlname = 'actioncode', $useempty = 0, $maxlen = 40, $help = 1, $morecss = 'minwidth300')
65 65
     {
66 66
         // phpcs:enable
67
-        global $conf,$db,$langs,$user,$mysoc;
67
+        global $conf, $db, $langs, $user, $mysoc;
68 68
 
69 69
         if (empty($mysoc->country_id) && empty($mysoc->country_code))
70 70
         {
71
-            dol_print_error('','Call to select_type_socialcontrib with mysoc country not yet defined');
71
+            dol_print_error('', 'Call to select_type_socialcontrib with mysoc country not yet defined');
72 72
             exit;
73 73
         }
74 74
 
75
-        if (! empty($mysoc->country_id))
75
+        if (!empty($mysoc->country_id))
76 76
         {
77 77
             $sql = "SELECT c.id, c.libelle as type";
78
-            $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c";
79
-            $sql.= " WHERE c.active = 1";
80
-            $sql.= " AND c.fk_pays = ".$mysoc->country_id;
81
-            $sql.= " ORDER BY c.libelle ASC";
78
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c";
79
+            $sql .= " WHERE c.active = 1";
80
+            $sql .= " AND c.fk_pays = ".$mysoc->country_id;
81
+            $sql .= " ORDER BY c.libelle ASC";
82 82
         }
83 83
         else
84 84
         {
85 85
             $sql = "SELECT c.id, c.libelle as type";
86
-            $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_country as co";
87
-            $sql.= " WHERE c.active = 1 AND c.fk_pays = co.rowid";
88
-            $sql.= " AND co.code = '".$mysoc->country_code."'";
89
-            $sql.= " ORDER BY c.libelle ASC";
86
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_country as co";
87
+            $sql .= " WHERE c.active = 1 AND c.fk_pays = co.rowid";
88
+            $sql .= " AND co.code = '".$mysoc->country_code."'";
89
+            $sql .= " ORDER BY c.libelle ASC";
90 90
         }
91 91
 
92 92
         dol_syslog("Form::select_type_socialcontrib", LOG_DEBUG);
93
-        $resql=$db->query($sql);
93
+        $resql = $db->query($sql);
94 94
         if ($resql)
95 95
         {
96 96
             $num = $db->num_rows($resql);
97 97
             if ($num)
98 98
             {
99
-            	print '<select class="'.($morecss?$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
99
+            	print '<select class="'.($morecss ? $morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
100 100
                 $i = 0;
101 101
 
102 102
                 if ($useempty) print '<option value="0">&nbsp;</option>';
@@ -105,21 +105,21 @@  discard block
 block discarded – undo
105 105
                     $obj = $db->fetch_object($resql);
106 106
                     print '<option value="'.$obj->id.'"';
107 107
                     if ($obj->id == $selected) print ' selected';
108
-                    print '>'.dol_trunc($obj->type,$maxlen);
108
+                    print '>'.dol_trunc($obj->type, $maxlen);
109 109
                     $i++;
110 110
                 }
111 111
                 print '</select>';
112
-                if ($user->admin && $help) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
113
-                if (! empty($conf->use_javascript_ajax)) print ajax_combobox($htmlname);
112
+                if ($user->admin && $help) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1);
113
+                if (!empty($conf->use_javascript_ajax)) print ajax_combobox($htmlname);
114 114
             }
115 115
             else
116 116
             {
117
-                print $langs->trans("ErrorNoSocialContributionForSellerCountry",$mysoc->country_code);
117
+                print $langs->trans("ErrorNoSocialContributionForSellerCountry", $mysoc->country_code);
118 118
             }
119 119
         }
120 120
         else
121 121
         {
122
-            dol_print_error($db,$db->lasterror());
122
+            dol_print_error($db, $db->lasterror());
123 123
         }
124 124
     }
125 125
 }
Please login to merge, or discard this patch.
Braces   +15 added lines, -10 removed lines patch added patch discarded remove patch
@@ -79,8 +79,7 @@  discard block
 block discarded – undo
79 79
             $sql.= " WHERE c.active = 1";
80 80
             $sql.= " AND c.fk_pays = ".$mysoc->country_id;
81 81
             $sql.= " ORDER BY c.libelle ASC";
82
-        }
83
-        else
82
+        } else
84 83
         {
85 84
             $sql = "SELECT c.id, c.libelle as type";
86 85
             $sql.= " FROM ".MAIN_DB_PREFIX."c_chargesociales as c, ".MAIN_DB_PREFIX."c_country as co";
@@ -99,25 +98,31 @@  discard block
 block discarded – undo
99 98
             	print '<select class="'.($morecss?$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
100 99
                 $i = 0;
101 100
 
102
-                if ($useempty) print '<option value="0">&nbsp;</option>';
101
+                if ($useempty) {
102
+                    print '<option value="0">&nbsp;</option>';
103
+                }
103 104
                 while ($i < $num)
104 105
                 {
105 106
                     $obj = $db->fetch_object($resql);
106 107
                     print '<option value="'.$obj->id.'"';
107
-                    if ($obj->id == $selected) print ' selected';
108
+                    if ($obj->id == $selected) {
109
+                        print ' selected';
110
+                    }
108 111
                     print '>'.dol_trunc($obj->type,$maxlen);
109 112
                     $i++;
110 113
                 }
111 114
                 print '</select>';
112
-                if ($user->admin && $help) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
113
-                if (! empty($conf->use_javascript_ajax)) print ajax_combobox($htmlname);
114
-            }
115
-            else
115
+                if ($user->admin && $help) {
116
+                    print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
117
+                }
118
+                if (! empty($conf->use_javascript_ajax)) {
119
+                    print ajax_combobox($htmlname);
120
+                }
121
+            } else
116 122
             {
117 123
                 print $langs->trans("ErrorNoSocialContributionForSellerCountry",$mysoc->country_code);
118 124
             }
119
-        }
120
-        else
125
+        } else
121 126
         {
122 127
             dol_print_error($db,$db->lasterror());
123 128
         }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/ccountry.class.php 3 patches
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -32,38 +32,38 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class Ccountry // extends CommonObject
34 34
 {
35
-	/**
35
+    /**
36 36
      * @var DoliDB Database handler.
37 37
      */
38 38
     public $db;
39 39
 
40
-	/**
41
-	 * @var string Error code (or message)
42
-	 */
43
-	public $error='';
40
+    /**
41
+     * @var string Error code (or message)
42
+     */
43
+    public $error='';
44 44
 
45
-	/**
46
-	 * @var string[] Error codes (or messages)
47
-	 */
48
-	public $errors = array();
45
+    /**
46
+     * @var string[] Error codes (or messages)
47
+     */
48
+    public $errors = array();
49 49
 
50
-	//var $element='ccountry';			//!< Id that identify managed objects
51
-	//var $table_element='ccountry';	//!< Name of table without prefix where object is stored
50
+    //var $element='ccountry';			//!< Id that identify managed objects
51
+    //var $table_element='ccountry';	//!< Name of table without prefix where object is stored
52 52
 
53 53
     /**
54
-	 * @var int ID
55
-	 */
56
-	public $id;
54
+     * @var int ID
55
+     */
56
+    public $id;
57 57
 
58
-	public $code;
59
-	public $code_iso;
58
+    public $code;
59
+    public $code_iso;
60 60
 
61
-	/**
61
+    /**
62 62
      * @var string Countries label
63 63
      */
64 64
     public $label;
65 65
 
66
-	public $active;
66
+    public $active;
67 67
 
68 68
 
69 69
 
@@ -88,73 +88,73 @@  discard block
 block discarded – undo
88 88
      */
89 89
     function create($user, $notrigger=0)
90 90
     {
91
-    	global $conf, $langs;
92
-		$error=0;
91
+        global $conf, $langs;
92
+        $error=0;
93 93
 
94
-		// Clean parameters
95
-		if (isset($this->code)) $this->code=trim($this->code);
96
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
97
-		if (isset($this->label)) $this->label=trim($this->label);
98
-		if (isset($this->active)) $this->active=trim($this->active);
94
+        // Clean parameters
95
+        if (isset($this->code)) $this->code=trim($this->code);
96
+        if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
97
+        if (isset($this->label)) $this->label=trim($this->label);
98
+        if (isset($this->active)) $this->active=trim($this->active);
99 99
 
100
-		// Check parameters
101
-		// Put here code to add control on parameters values
100
+        // Check parameters
101
+        // Put here code to add control on parameters values
102 102
 
103 103
         // Insert request
104
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country(";
105
-		$sql.= "rowid,";
106
-		$sql.= "code,";
107
-		$sql.= "code_iso,";
108
-		$sql.= "label,";
109
-		$sql.= "active";
104
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country(";
105
+        $sql.= "rowid,";
106
+        $sql.= "code,";
107
+        $sql.= "code_iso,";
108
+        $sql.= "label,";
109
+        $sql.= "active";
110 110
         $sql.= ") VALUES (";
111
-		$sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").",";
112
-		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
113
-		$sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").",";
114
-		$sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
115
-		$sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'")."";
116
-		$sql.= ")";
111
+        $sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").",";
112
+        $sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
113
+        $sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").",";
114
+        $sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
115
+        $sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'")."";
116
+        $sql.= ")";
117 117
 
118
-		$this->db->begin();
118
+        $this->db->begin();
119 119
 
120
-	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
120
+            dol_syslog(get_class($this)."::create", LOG_DEBUG);
121 121
         $resql=$this->db->query($sql);
122
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
122
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
123 123
 
124
-		if (! $error)
124
+        if (! $error)
125 125
         {
126 126
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country");
127 127
 
128
-			if (! $notrigger)
129
-			{
130
-	            // Uncomment this and change MYOBJECT to your own tag if you
131
-	            // want this action call a trigger.
132
-
133
-	            //// Call triggers
134
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
135
-	            //$interface=new Interfaces($this->db);
136
-	            //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
137
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
138
-	            //// End call triggers
139
-			}
128
+            if (! $notrigger)
129
+            {
130
+                // Uncomment this and change MYOBJECT to your own tag if you
131
+                // want this action call a trigger.
132
+
133
+                //// Call triggers
134
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
135
+                //$interface=new Interfaces($this->db);
136
+                //$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
137
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
138
+                //// End call triggers
139
+            }
140 140
         }
141 141
 
142 142
         // Commit or rollback
143 143
         if ($error)
144
-		{
145
-			foreach($this->errors as $errmsg)
146
-			{
147
-	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
149
-			}
150
-			$this->db->rollback();
151
-			return -1*$error;
152
-		}
153
-		else
154
-		{
155
-			$this->db->commit();
144
+        {
145
+            foreach($this->errors as $errmsg)
146
+            {
147
+                dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
149
+            }
150
+            $this->db->rollback();
151
+            return -1*$error;
152
+        }
153
+        else
154
+        {
155
+            $this->db->commit();
156 156
             return $this->id;
157
-		}
157
+        }
158 158
     }
159 159
 
160 160
 
@@ -167,18 +167,18 @@  discard block
 block discarded – undo
167 167
      */
168 168
     function fetch($id,$code='')
169 169
     {
170
-    	global $langs;
170
+        global $langs;
171 171
         $sql = "SELECT";
172
-		$sql.= " t.rowid,";
173
-		$sql.= " t.code,";
174
-		$sql.= " t.code_iso,";
175
-		$sql.= " t.label,";
176
-		$sql.= " t.active";
172
+        $sql.= " t.rowid,";
173
+        $sql.= " t.code,";
174
+        $sql.= " t.code_iso,";
175
+        $sql.= " t.label,";
176
+        $sql.= " t.active";
177 177
         $sql.= " FROM ".MAIN_DB_PREFIX."c_country as t";
178 178
         if ($id)   $sql.= " WHERE t.rowid = ".$id;
179 179
         elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
180 180
 
181
-    	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
181
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
182 182
         $resql=$this->db->query($sql);
183 183
         if ($resql)
184 184
         {
@@ -187,10 +187,10 @@  discard block
 block discarded – undo
187 187
                 $obj = $this->db->fetch_object($resql);
188 188
 
189 189
                 $this->id    = $obj->rowid;
190
-				$this->code = $obj->code;
191
-				$this->code_iso = $obj->code_iso;
192
-				$this->label = $obj->label;
193
-				$this->active = $obj->active;
190
+                $this->code = $obj->code;
191
+                $this->code_iso = $obj->code_iso;
192
+                $this->label = $obj->label;
193
+                $this->active = $obj->active;
194 194
 
195 195
                 $this->db->free($resql);
196 196
                 return 1;
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
         }
202 202
         else
203 203
         {
204
-      	    $this->error="Error ".$this->db->lasterror();
204
+                $this->error="Error ".$this->db->lasterror();
205 205
             return -1;
206 206
         }
207 207
     }
@@ -216,120 +216,120 @@  discard block
 block discarded – undo
216 216
      */
217 217
     function update($user=null, $notrigger=0)
218 218
     {
219
-    	global $conf, $langs;
220
-		$error=0;
219
+        global $conf, $langs;
220
+        $error=0;
221 221
 
222
-		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
225
-		if (isset($this->label)) $this->label=trim($this->label);
226
-		if (isset($this->active)) $this->active=trim($this->active);
222
+        // Clean parameters
223
+        if (isset($this->code)) $this->code=trim($this->code);
224
+        if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
225
+        if (isset($this->label)) $this->label=trim($this->label);
226
+        if (isset($this->active)) $this->active=trim($this->active);
227 227
 
228 228
 
229
-		// Check parameters
230
-		// Put here code to add control on parameters values
229
+        // Check parameters
230
+        // Put here code to add control on parameters values
231 231
 
232 232
         // Update request
233 233
         $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET";
234
-		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
-		$sql.= " code_iso=".(isset($this->code_iso)?"'".$this->db->escape($this->code_iso)."'":"null").",";
236
-		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
237
-		$sql.= " active=".(isset($this->active)?$this->active:"null")."";
234
+        $sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
+        $sql.= " code_iso=".(isset($this->code_iso)?"'".$this->db->escape($this->code_iso)."'":"null").",";
236
+        $sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
237
+        $sql.= " active=".(isset($this->active)?$this->active:"null")."";
238 238
         $sql.= " WHERE rowid=".$this->id;
239 239
 
240
-		$this->db->begin();
240
+        $this->db->begin();
241 241
 
242
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
242
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
243 243
         $resql = $this->db->query($sql);
244
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
245
-
246
-		if (! $error)
247
-		{
248
-			if (! $notrigger)
249
-			{
250
-	            // Uncomment this and change MYOBJECT to your own tag if you
251
-	            // want this action call a trigger.
252
-
253
-	            //// Call triggers
254
-	            //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
255
-	            //$interface=new Interfaces($this->db);
256
-	            //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
257
-	            //if ($result < 0) { $error++; $this->errors=$interface->errors; }
258
-	            //// End call triggers
259
-	    	}
260
-		}
244
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
245
+
246
+        if (! $error)
247
+        {
248
+            if (! $notrigger)
249
+            {
250
+                // Uncomment this and change MYOBJECT to your own tag if you
251
+                // want this action call a trigger.
252
+
253
+                //// Call triggers
254
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
255
+                //$interface=new Interfaces($this->db);
256
+                //$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
257
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
258
+                //// End call triggers
259
+            }
260
+        }
261 261
 
262 262
         // Commit or rollback
263
-		if ($error)
264
-		{
265
-			foreach($this->errors as $errmsg)
266
-			{
267
-	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
269
-			}
270
-			$this->db->rollback();
271
-			return -1*$error;
272
-		}
273
-		else
274
-		{
275
-			$this->db->commit();
276
-			return 1;
277
-		}
263
+        if ($error)
264
+        {
265
+            foreach($this->errors as $errmsg)
266
+            {
267
+                dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
269
+            }
270
+            $this->db->rollback();
271
+            return -1*$error;
272
+        }
273
+        else
274
+        {
275
+            $this->db->commit();
276
+            return 1;
277
+        }
278 278
     }
279 279
 
280 280
 
281
- 	/**
282
- 	 *  Delete object in database
283
-	 *
284
-     *	@param  User	$user        User that delete
285
-     *  @param	int		$notrigger	 0=launch triggers after, 1=disable triggers
286
-	 *  @return	int					 <0 if KO, >0 if OK
287
-	 */
288
-	function delete($user, $notrigger=0)
289
-	{
290
-		global $conf, $langs;
291
-		$error=0;
292
-
293
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country";
294
-		$sql.= " WHERE rowid=".$this->id;
295
-
296
-		$this->db->begin();
297
-
298
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299
-		$resql = $this->db->query($sql);
300
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
301
-
302
-		if (! $error)
303
-		{
304
-			if (! $notrigger)
305
-			{
306
-				// Uncomment this and change MYOBJECT to your own tag if you
307
-		        // want this action call a trigger.
308
-
309
-		        //// Call triggers
310
-		        //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
311
-		        //$interface=new Interfaces($this->db);
312
-		        //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
313
-		        //if ($result < 0) { $error++; $this->errors=$interface->errors; }
314
-		        //// End call triggers
315
-			}
316
-		}
281
+        /**
282
+         *  Delete object in database
283
+         *
284
+         *	@param  User	$user        User that delete
285
+         *  @param	int		$notrigger	 0=launch triggers after, 1=disable triggers
286
+         *  @return	int					 <0 if KO, >0 if OK
287
+         */
288
+    function delete($user, $notrigger=0)
289
+    {
290
+        global $conf, $langs;
291
+        $error=0;
292
+
293
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country";
294
+        $sql.= " WHERE rowid=".$this->id;
295
+
296
+        $this->db->begin();
297
+
298
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299
+        $resql = $this->db->query($sql);
300
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
301
+
302
+        if (! $error)
303
+        {
304
+            if (! $notrigger)
305
+            {
306
+                // Uncomment this and change MYOBJECT to your own tag if you
307
+                // want this action call a trigger.
308
+
309
+                //// Call triggers
310
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
311
+                //$interface=new Interfaces($this->db);
312
+                //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
313
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
314
+                //// End call triggers
315
+            }
316
+        }
317 317
 
318 318
         // Commit or rollback
319
-		if ($error)
320
-		{
321
-			foreach($this->errors as $errmsg)
322
-			{
323
-	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
325
-			}
326
-			$this->db->rollback();
327
-			return -1*$error;
328
-		}
329
-		else
330
-		{
331
-			$this->db->commit();
332
-			return 1;
333
-		}
334
-	}
319
+        if ($error)
320
+        {
321
+            foreach($this->errors as $errmsg)
322
+            {
323
+                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
325
+            }
326
+            $this->db->rollback();
327
+            return -1*$error;
328
+        }
329
+        else
330
+        {
331
+            $this->db->commit();
332
+            return 1;
333
+        }
334
+    }
335 335
 }
Please login to merge, or discard this patch.
Spacing   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -40,7 +40,7 @@  discard block
 block discarded – undo
40 40
 	/**
41 41
 	 * @var string Error code (or message)
42 42
 	 */
43
-	public $error='';
43
+	public $error = '';
44 44
 
45 45
 	/**
46 46
 	 * @var string[] Error codes (or messages)
@@ -86,46 +86,46 @@  discard block
 block discarded – undo
86 86
      *  @param      int		$notrigger   0=launch triggers after, 1=disable triggers
87 87
      *  @return     int      		   	 <0 if KO, Id of created object if OK
88 88
      */
89
-    function create($user, $notrigger=0)
89
+    function create($user, $notrigger = 0)
90 90
     {
91 91
     	global $conf, $langs;
92
-		$error=0;
92
+		$error = 0;
93 93
 
94 94
 		// Clean parameters
95
-		if (isset($this->code)) $this->code=trim($this->code);
96
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
97
-		if (isset($this->label)) $this->label=trim($this->label);
98
-		if (isset($this->active)) $this->active=trim($this->active);
95
+		if (isset($this->code)) $this->code = trim($this->code);
96
+		if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso);
97
+		if (isset($this->label)) $this->label = trim($this->label);
98
+		if (isset($this->active)) $this->active = trim($this->active);
99 99
 
100 100
 		// Check parameters
101 101
 		// Put here code to add control on parameters values
102 102
 
103 103
         // Insert request
104 104
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_country(";
105
-		$sql.= "rowid,";
106
-		$sql.= "code,";
107
-		$sql.= "code_iso,";
108
-		$sql.= "label,";
109
-		$sql.= "active";
110
-        $sql.= ") VALUES (";
111
-		$sql.= " ".(! isset($this->rowid)?'NULL':"'".$this->db->escape($this->rowid)."'").",";
112
-		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
113
-		$sql.= " ".(! isset($this->code_iso)?'NULL':"'".$this->db->escape($this->code_iso)."'").",";
114
-		$sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
115
-		$sql.= " ".(! isset($this->active)?'NULL':"'".$this->db->escape($this->active)."'")."";
116
-		$sql.= ")";
105
+		$sql .= "rowid,";
106
+		$sql .= "code,";
107
+		$sql .= "code_iso,";
108
+		$sql .= "label,";
109
+		$sql .= "active";
110
+        $sql .= ") VALUES (";
111
+		$sql .= " ".(!isset($this->rowid) ? 'NULL' : "'".$this->db->escape($this->rowid)."'").",";
112
+		$sql .= " ".(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").",";
113
+		$sql .= " ".(!isset($this->code_iso) ? 'NULL' : "'".$this->db->escape($this->code_iso)."'").",";
114
+		$sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").",";
115
+		$sql .= " ".(!isset($this->active) ? 'NULL' : "'".$this->db->escape($this->active)."'")."";
116
+		$sql .= ")";
117 117
 
118 118
 		$this->db->begin();
119 119
 
120 120
 	   	dol_syslog(get_class($this)."::create", LOG_DEBUG);
121
-        $resql=$this->db->query($sql);
122
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
121
+        $resql = $this->db->query($sql);
122
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
123 123
 
124
-		if (! $error)
124
+		if (!$error)
125 125
         {
126 126
             $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_country");
127 127
 
128
-			if (! $notrigger)
128
+			if (!$notrigger)
129 129
 			{
130 130
 	            // Uncomment this and change MYOBJECT to your own tag if you
131 131
 	            // want this action call a trigger.
@@ -142,13 +142,13 @@  discard block
 block discarded – undo
142 142
         // Commit or rollback
143 143
         if ($error)
144 144
 		{
145
-			foreach($this->errors as $errmsg)
145
+			foreach ($this->errors as $errmsg)
146 146
 			{
147 147
 	            dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
148
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
148
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
149 149
 			}
150 150
 			$this->db->rollback();
151
-			return -1*$error;
151
+			return -1 * $error;
152 152
 		}
153 153
 		else
154 154
 		{
@@ -165,28 +165,28 @@  discard block
 block discarded – undo
165 165
      *  @param		string	$code	Code
166 166
      *  @return     int          	>0 if OK, 0 if not found, <0 if KO
167 167
      */
168
-    function fetch($id,$code='')
168
+    function fetch($id, $code = '')
169 169
     {
170 170
     	global $langs;
171 171
         $sql = "SELECT";
172
-		$sql.= " t.rowid,";
173
-		$sql.= " t.code,";
174
-		$sql.= " t.code_iso,";
175
-		$sql.= " t.label,";
176
-		$sql.= " t.active";
177
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_country as t";
178
-        if ($id)   $sql.= " WHERE t.rowid = ".$id;
179
-        elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
172
+		$sql .= " t.rowid,";
173
+		$sql .= " t.code,";
174
+		$sql .= " t.code_iso,";
175
+		$sql .= " t.label,";
176
+		$sql .= " t.active";
177
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_country as t";
178
+        if ($id)   $sql .= " WHERE t.rowid = ".$id;
179
+        elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
180 180
 
181 181
     	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
182
-        $resql=$this->db->query($sql);
182
+        $resql = $this->db->query($sql);
183 183
         if ($resql)
184 184
         {
185 185
             if ($this->db->num_rows($resql))
186 186
             {
187 187
                 $obj = $this->db->fetch_object($resql);
188 188
 
189
-                $this->id    = $obj->rowid;
189
+                $this->id = $obj->rowid;
190 190
 				$this->code = $obj->code;
191 191
 				$this->code_iso = $obj->code_iso;
192 192
 				$this->label = $obj->label;
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
         }
202 202
         else
203 203
         {
204
-      	    $this->error="Error ".$this->db->lasterror();
204
+      	    $this->error = "Error ".$this->db->lasterror();
205 205
             return -1;
206 206
         }
207 207
     }
@@ -214,16 +214,16 @@  discard block
 block discarded – undo
214 214
      *  @param      int		$notrigger	 0=launch triggers after, 1=disable triggers
215 215
      *  @return     int     		   	 <0 if KO, >0 if OK
216 216
      */
217
-    function update($user=null, $notrigger=0)
217
+    function update($user = null, $notrigger = 0)
218 218
     {
219 219
     	global $conf, $langs;
220
-		$error=0;
220
+		$error = 0;
221 221
 
222 222
 		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
225
-		if (isset($this->label)) $this->label=trim($this->label);
226
-		if (isset($this->active)) $this->active=trim($this->active);
223
+		if (isset($this->code)) $this->code = trim($this->code);
224
+		if (isset($this->code_iso)) $this->code_iso = trim($this->code_iso);
225
+		if (isset($this->label)) $this->label = trim($this->label);
226
+		if (isset($this->active)) $this->active = trim($this->active);
227 227
 
228 228
 
229 229
 		// Check parameters
@@ -231,21 +231,21 @@  discard block
 block discarded – undo
231 231
 
232 232
         // Update request
233 233
         $sql = "UPDATE ".MAIN_DB_PREFIX."c_country SET";
234
-		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
235
-		$sql.= " code_iso=".(isset($this->code_iso)?"'".$this->db->escape($this->code_iso)."'":"null").",";
236
-		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
237
-		$sql.= " active=".(isset($this->active)?$this->active:"null")."";
238
-        $sql.= " WHERE rowid=".$this->id;
234
+		$sql .= " code=".(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").",";
235
+		$sql .= " code_iso=".(isset($this->code_iso) ? "'".$this->db->escape($this->code_iso)."'" : "null").",";
236
+		$sql .= " label=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").",";
237
+		$sql .= " active=".(isset($this->active) ? $this->active : "null")."";
238
+        $sql .= " WHERE rowid=".$this->id;
239 239
 
240 240
 		$this->db->begin();
241 241
 
242 242
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
243 243
         $resql = $this->db->query($sql);
244
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
244
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
245 245
 
246
-		if (! $error)
246
+		if (!$error)
247 247
 		{
248
-			if (! $notrigger)
248
+			if (!$notrigger)
249 249
 			{
250 250
 	            // Uncomment this and change MYOBJECT to your own tag if you
251 251
 	            // want this action call a trigger.
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
         // Commit or rollback
263 263
 		if ($error)
264 264
 		{
265
-			foreach($this->errors as $errmsg)
265
+			foreach ($this->errors as $errmsg)
266 266
 			{
267 267
 	            dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
268
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
268
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
269 269
 			}
270 270
 			$this->db->rollback();
271
-			return -1*$error;
271
+			return -1 * $error;
272 272
 		}
273 273
 		else
274 274
 		{
@@ -285,23 +285,23 @@  discard block
 block discarded – undo
285 285
      *  @param	int		$notrigger	 0=launch triggers after, 1=disable triggers
286 286
 	 *  @return	int					 <0 if KO, >0 if OK
287 287
 	 */
288
-	function delete($user, $notrigger=0)
288
+	function delete($user, $notrigger = 0)
289 289
 	{
290 290
 		global $conf, $langs;
291
-		$error=0;
291
+		$error = 0;
292 292
 
293 293
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_country";
294
-		$sql.= " WHERE rowid=".$this->id;
294
+		$sql .= " WHERE rowid=".$this->id;
295 295
 
296 296
 		$this->db->begin();
297 297
 
298 298
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
299 299
 		$resql = $this->db->query($sql);
300
-    	if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
300
+    	if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
301 301
 
302
-		if (! $error)
302
+		if (!$error)
303 303
 		{
304
-			if (! $notrigger)
304
+			if (!$notrigger)
305 305
 			{
306 306
 				// Uncomment this and change MYOBJECT to your own tag if you
307 307
 		        // want this action call a trigger.
@@ -318,13 +318,13 @@  discard block
 block discarded – undo
318 318
         // Commit or rollback
319 319
 		if ($error)
320 320
 		{
321
-			foreach($this->errors as $errmsg)
321
+			foreach ($this->errors as $errmsg)
322 322
 			{
323 323
 	            dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
324
-	            $this->error.=($this->error?', '.$errmsg:$errmsg);
324
+	            $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
325 325
 			}
326 326
 			$this->db->rollback();
327
-			return -1*$error;
327
+			return -1 * $error;
328 328
 		}
329 329
 		else
330 330
 		{
Please login to merge, or discard this patch.
Braces   +34 added lines, -20 removed lines patch added patch discarded remove patch
@@ -92,10 +92,18 @@  discard block
 block discarded – undo
92 92
 		$error=0;
93 93
 
94 94
 		// Clean parameters
95
-		if (isset($this->code)) $this->code=trim($this->code);
96
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
97
-		if (isset($this->label)) $this->label=trim($this->label);
98
-		if (isset($this->active)) $this->active=trim($this->active);
95
+		if (isset($this->code)) {
96
+		    $this->code=trim($this->code);
97
+		}
98
+		if (isset($this->code_iso)) {
99
+		    $this->code_iso=trim($this->code_iso);
100
+		}
101
+		if (isset($this->label)) {
102
+		    $this->label=trim($this->label);
103
+		}
104
+		if (isset($this->active)) {
105
+		    $this->active=trim($this->active);
106
+		}
99 107
 
100 108
 		// Check parameters
101 109
 		// Put here code to add control on parameters values
@@ -149,8 +157,7 @@  discard block
 block discarded – undo
149 157
 			}
150 158
 			$this->db->rollback();
151 159
 			return -1*$error;
152
-		}
153
-		else
160
+		} else
154 161
 		{
155 162
 			$this->db->commit();
156 163
             return $this->id;
@@ -175,8 +182,11 @@  discard block
 block discarded – undo
175 182
 		$sql.= " t.label,";
176 183
 		$sql.= " t.active";
177 184
         $sql.= " FROM ".MAIN_DB_PREFIX."c_country as t";
178
-        if ($id)   $sql.= " WHERE t.rowid = ".$id;
179
-        elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
185
+        if ($id) {
186
+            $sql.= " WHERE t.rowid = ".$id;
187
+        } elseif ($code) {
188
+            $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
189
+        }
180 190
 
181 191
     	dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
182 192
         $resql=$this->db->query($sql);
@@ -194,12 +204,10 @@  discard block
 block discarded – undo
194 204
 
195 205
                 $this->db->free($resql);
196 206
                 return 1;
197
-            }
198
-            else {
207
+            } else {
199 208
                 return 0;
200 209
             }
201
-        }
202
-        else
210
+        } else
203 211
         {
204 212
       	    $this->error="Error ".$this->db->lasterror();
205 213
             return -1;
@@ -220,10 +228,18 @@  discard block
 block discarded – undo
220 228
 		$error=0;
221 229
 
222 230
 		// Clean parameters
223
-		if (isset($this->code)) $this->code=trim($this->code);
224
-		if (isset($this->code_iso)) $this->code_iso=trim($this->code_iso);
225
-		if (isset($this->label)) $this->label=trim($this->label);
226
-		if (isset($this->active)) $this->active=trim($this->active);
231
+		if (isset($this->code)) {
232
+		    $this->code=trim($this->code);
233
+		}
234
+		if (isset($this->code_iso)) {
235
+		    $this->code_iso=trim($this->code_iso);
236
+		}
237
+		if (isset($this->label)) {
238
+		    $this->label=trim($this->label);
239
+		}
240
+		if (isset($this->active)) {
241
+		    $this->active=trim($this->active);
242
+		}
227 243
 
228 244
 
229 245
 		// Check parameters
@@ -269,8 +285,7 @@  discard block
 block discarded – undo
269 285
 			}
270 286
 			$this->db->rollback();
271 287
 			return -1*$error;
272
-		}
273
-		else
288
+		} else
274 289
 		{
275 290
 			$this->db->commit();
276 291
 			return 1;
@@ -325,8 +340,7 @@  discard block
 block discarded – undo
325 340
 			}
326 341
 			$this->db->rollback();
327 342
 			return -1*$error;
328
-		}
329
-		else
343
+		} else
330 344
 		{
331 345
 			$this->db->commit();
332 346
 			return 1;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/commondocgenerator.class.php 3 patches
Indentation   +490 added lines, -490 removed lines patch added patch discarded remove patch
@@ -34,27 +34,27 @@  discard block
 block discarded – undo
34 34
  */
35 35
 abstract class CommonDocGenerator
36 36
 {
37
-	/**
38
-	 * @var string Error code (or message)
39
-	 */
40
-	public $error='';
37
+    /**
38
+     * @var string Error code (or message)
39
+     */
40
+    public $error='';
41 41
 
42 42
     /**
43 43
      * @var string[]    Array of error strings
44 44
      */
45 45
     public $errors = array();
46 46
 
47
-	/**
47
+    /**
48 48
      * @var DoliDB Database handler.
49 49
      */
50
-	protected $db;
50
+    protected $db;
51 51
 
52 52
 
53
-	/**
54
-	 *	Constructor
55
-	 *
56
-	 *  @param		DoliDB		$db      Database handler
57
-	*/
53
+    /**
54
+     *	Constructor
55
+     *
56
+     *  @param		DoliDB		$db      Database handler
57
+     */
58 58
     public function __construct($db)
59 59
     {
60 60
         $this->db = $db;
@@ -82,18 +82,18 @@  discard block
 block discarded – undo
82 82
             'myuser_fullname'=>$user->getFullName($outputlangs,1),
83 83
             'myuser_login'=>$user->login,
84 84
             'myuser_phone'=>$user->office_phone,
85
-       		'myuser_address'=>$user->address,
86
-       		'myuser_zip'=>$user->zip,
87
-       		'myuser_town'=>$user->town,
88
-       		'myuser_country'=>$user->country,
89
-        	'myuser_country_code'=>$user->country_code,
90
-       		'myuser_state'=>$user->state,
91
-        	'myuser_state_code'=>$user->state_code,
92
-        	'myuser_fax'=>$user->office_fax,
85
+                'myuser_address'=>$user->address,
86
+                'myuser_zip'=>$user->zip,
87
+                'myuser_town'=>$user->town,
88
+                'myuser_country'=>$user->country,
89
+            'myuser_country_code'=>$user->country_code,
90
+                'myuser_state'=>$user->state,
91
+            'myuser_state_code'=>$user->state_code,
92
+            'myuser_fax'=>$user->office_fax,
93 93
             'myuser_mobile'=>$user->user_mobile,
94 94
             'myuser_email'=>$user->email,
95
-        	'myuser_logo'=>$logotouse,
96
-        	'myuser_job'=>$user->job,
95
+            'myuser_logo'=>$logotouse,
96
+            'myuser_job'=>$user->job,
97 97
             'myuser_web'=>''	// url not exist in $user object
98 98
         );
99 99
     }
@@ -118,11 +118,11 @@  discard block
 block discarded – undo
118 118
         }
119 119
         if (empty($mysoc->country) && ! empty($mysoc->country_code))
120 120
         {
121
-        	$mysoc->country=$outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
121
+            $mysoc->country=$outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
122 122
         }
123 123
         if (empty($mysoc->state) && ! empty($mysoc->state_code))
124 124
         {
125
-        	$mysoc->state=getState($mysoc->state_code,0);
125
+            $mysoc->state=getState($mysoc->state_code,0);
126 126
         }
127 127
 
128 128
         $logotouse=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
             'mycompany_country_code'=>$mysoc->country_code,
141 141
             'mycompany_state'=>$mysoc->state,
142 142
             'mycompany_state_code'=>$mysoc->state_code,
143
-        	'mycompany_web'=>$mysoc->url,
143
+            'mycompany_web'=>$mysoc->url,
144 144
             'mycompany_juridicalstatus'=>$mysoc->forme_juridique,
145 145
             'mycompany_managers'=>$mysoc->managers,
146 146
             'mycompany_capital'=>$mysoc->capital,
@@ -151,8 +151,8 @@  discard block
 block discarded – undo
151 151
             'mycompany_idprof4'=>$mysoc->idprof4,
152 152
             'mycompany_idprof5'=>$mysoc->idprof5,
153 153
             'mycompany_idprof6'=>$mysoc->idprof6,
154
-        	'mycompany_vatnumber'=>$mysoc->tva_intra,
155
-			'mycompany_object'=>$mysoc->object,
154
+            'mycompany_vatnumber'=>$mysoc->tva_intra,
155
+            'mycompany_object'=>$mysoc->object,
156 156
             'mycompany_note_private'=>$mysoc->note_private,
157 157
             //'mycompany_note_public'=>$mysoc->note_public,        // Only private not exists for "mysoc" but both for thirdparties
158 158
         );
@@ -174,16 +174,16 @@  discard block
 block discarded – undo
174 174
 
175 175
         if (empty($object->country) && ! empty($object->country_code))
176 176
         {
177
-        	$object->country=$outputlangs->transnoentitiesnoconv("Country".$object->country_code);
177
+            $object->country=$outputlangs->transnoentitiesnoconv("Country".$object->country_code);
178 178
         }
179 179
         if (empty($object->state) && ! empty($object->state_code))
180 180
         {
181
-        	$object->state=getState($object->state_code,0);
181
+            $object->state=getState($object->state_code,0);
182 182
         }
183 183
 
184 184
         $array_thirdparty = array(
185 185
             'company_name'=>$object->name,
186
-	        'company_name_alias' => $object->name_alias,
186
+            'company_name_alias' => $object->name_alias,
187 187
             'company_email'=>$object->email,
188 188
             'company_phone'=>$object->phone,
189 189
             'company_fax'=>$object->fax,
@@ -191,10 +191,10 @@  discard block
 block discarded – undo
191 191
             'company_zip'=>$object->zip,
192 192
             'company_town'=>$object->town,
193 193
             'company_country'=>$object->country,
194
-        	'company_country_code'=>$object->country_code,
194
+            'company_country_code'=>$object->country_code,
195 195
             'company_state'=>$object->state,
196
-        	'company_state_code'=>$object->state_code,
197
-        	'company_web'=>$object->url,
196
+            'company_state_code'=>$object->state_code,
197
+            'company_web'=>$object->url,
198 198
             'company_barcode'=>$object->barcode,
199 199
             'company_vatnumber'=>$object->tva_intra,
200 200
             'company_customercode'=>$object->code_client,
@@ -219,52 +219,52 @@  discard block
 block discarded – undo
219 219
         // Retrieve extrafields
220 220
         if(is_array($object->array_options) && count($object->array_options))
221 221
         {
222
-        	require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
223
-        	$extrafields = new ExtraFields($this->db);
224
-        	$extralabels = $extrafields->fetch_name_optionals_label('societe',true);
225
-        	$object->fetch_optionals();
226
-
227
-        	foreach($extrafields->attribute_label as $key=>$label)
228
-        	{
229
-        		if($extrafields->attribute_type[$key] == 'price')
230
-        		{
231
-        			$object->array_options['options_'.$key] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
232
-        		}
233
-        		else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
234
-        		{
235
-        			$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
236
-        		}
237
-        		$array_thirdparty = array_merge($array_thirdparty, array ('company_options_'.$key => $object->array_options ['options_' . $key]));
238
-			}
239
-		}
240
-		return $array_thirdparty;
241
-	}
222
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
223
+            $extrafields = new ExtraFields($this->db);
224
+            $extralabels = $extrafields->fetch_name_optionals_label('societe',true);
225
+            $object->fetch_optionals();
226
+
227
+            foreach($extrafields->attribute_label as $key=>$label)
228
+            {
229
+                if($extrafields->attribute_type[$key] == 'price')
230
+                {
231
+                    $object->array_options['options_'.$key] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
232
+                }
233
+                else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
234
+                {
235
+                    $object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
236
+                }
237
+                $array_thirdparty = array_merge($array_thirdparty, array ('company_options_'.$key => $object->array_options ['options_' . $key]));
238
+            }
239
+        }
240
+        return $array_thirdparty;
241
+    }
242 242
 
243 243
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
244
-	/**
245
-	 * Define array with couple subtitution key => subtitution value
246
-	 *
247
-	 * @param	Contact 	$object        	contact
248
-	 * @param	Translate 	$outputlangs   	object for output
249
-	 * @param   array		$array_key	    Name of the key for return array
250
-	 * @return	array 						Array of substitution key->code
251
-	 */
244
+    /**
245
+     * Define array with couple subtitution key => subtitution value
246
+     *
247
+     * @param	Contact 	$object        	contact
248
+     * @param	Translate 	$outputlangs   	object for output
249
+     * @param   array		$array_key	    Name of the key for return array
250
+     * @return	array 						Array of substitution key->code
251
+     */
252 252
     function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object')
253 253
     {
254 254
         // phpcs:enable
255
-		global $conf;
256
-
257
-		if(empty($object->country) && ! empty($object->country_code))
258
-		{
259
-			$object->country = $outputlangs->transnoentitiesnoconv("Country" . $object->country_code);
260
-		}
261
-		if(empty($object->state) && ! empty($object->state_code))
262
-		{
263
-			$object->state = getState($object->state_code, 0);
264
-		}
265
-
266
-		$array_contact = array (
267
-		    $array_key . '_fullname' => $object->getFullName($outputlangs, 1),
255
+        global $conf;
256
+
257
+        if(empty($object->country) && ! empty($object->country_code))
258
+        {
259
+            $object->country = $outputlangs->transnoentitiesnoconv("Country" . $object->country_code);
260
+        }
261
+        if(empty($object->state) && ! empty($object->state_code))
262
+        {
263
+            $object->state = getState($object->state_code, 0);
264
+        }
265
+
266
+        $array_contact = array (
267
+            $array_key . '_fullname' => $object->getFullName($outputlangs, 1),
268 268
             $array_key . '_lastname' => $object->lastname,
269 269
             $array_key . '_firstname' => $object->firstname,
270 270
             $array_key . '_address' => $object->address,
@@ -290,28 +290,28 @@  discard block
 block discarded – undo
290 290
             $array_key . '_default_lang' => $object->default_lang,
291 291
             $array_key . '_note_public' => $object->note_public,
292 292
             $array_key . '_note_private' => $object->note_private
293
-		);
294
-
295
-		// Retrieve extrafields
296
-		require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
297
-		$extrafields = new ExtraFields($this->db);
298
-		$extralabels = $extrafields->fetch_name_optionals_label('socpeople', true);
299
-		$object->fetch_optionals();
300
-
301
-		foreach($extrafields->attribute_label as $key => $label)
302
-		{
303
-			if ($extrafields->attribute_type[$key] == 'price')
304
-			{
305
-				$object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency);
306
-			}
307
-			elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
308
-			{
309
-				$object->array_options['options_' . $key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_' . $key]];
310
-			}
311
-			$array_contact = array_merge($array_contact, array($array_key.'_options_' . $key => $object->array_options['options_'. $key]));
312
-		}
313
-		return $array_contact;
314
-	}
293
+        );
294
+
295
+        // Retrieve extrafields
296
+        require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
297
+        $extrafields = new ExtraFields($this->db);
298
+        $extralabels = $extrafields->fetch_name_optionals_label('socpeople', true);
299
+        $object->fetch_optionals();
300
+
301
+        foreach($extrafields->attribute_label as $key => $label)
302
+        {
303
+            if ($extrafields->attribute_type[$key] == 'price')
304
+            {
305
+                $object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency);
306
+            }
307
+            elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
308
+            {
309
+                $object->array_options['options_' . $key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_' . $key]];
310
+            }
311
+            $array_contact = array_merge($array_contact, array($array_key.'_options_' . $key => $object->array_options['options_'. $key]));
312
+        }
313
+        return $array_contact;
314
+    }
315 315
 
316 316
 
317 317
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -324,260 +324,260 @@  discard block
 block discarded – undo
324 324
     function get_substitutionarray_other($outputlangs)
325 325
     {
326 326
         // phpcs:enable
327
-    	global $conf;
328
-
329
-    	$now=dol_now('gmt');	// gmt
330
-    	$array_other = array(
331
-    	    // Date in default language
332
-    	    'current_date'=>dol_print_date($now,'day','tzuser'),
333
-    	    'current_datehour'=>dol_print_date($now,'dayhour','tzuser'),
334
-   			'current_server_date'=>dol_print_date($now,'day','tzserver'),
335
-   			'current_server_datehour'=>dol_print_date($now,'dayhour','tzserver'),
336
-    	    // Date in requested output language
337
-    	    'current_date_locale'=>dol_print_date($now,'day','tzuser',$outputlangs),
338
-   			'current_datehour_locale'=>dol_print_date($now,'dayhour','tzuser',$outputlangs),
339
-   			'current_server_date_locale'=>dol_print_date($now,'day','tzserver',$outputlangs),
340
-   			'current_server_datehour_locale'=>dol_print_date($now,'dayhour','tzserver',$outputlangs),
341
-    	);
342
-
343
-
344
-    	foreach($conf->global as $key => $val)
345
-    	{
346
-    		if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****';
347
-    		else $newval = $val;
348
-    		$array_other['__['.$key.']__'] = $newval;
349
-    	}
350
-
351
-    	return $array_other;
327
+        global $conf;
328
+
329
+        $now=dol_now('gmt');	// gmt
330
+        $array_other = array(
331
+            // Date in default language
332
+            'current_date'=>dol_print_date($now,'day','tzuser'),
333
+            'current_datehour'=>dol_print_date($now,'dayhour','tzuser'),
334
+                'current_server_date'=>dol_print_date($now,'day','tzserver'),
335
+                'current_server_datehour'=>dol_print_date($now,'dayhour','tzserver'),
336
+            // Date in requested output language
337
+            'current_date_locale'=>dol_print_date($now,'day','tzuser',$outputlangs),
338
+                'current_datehour_locale'=>dol_print_date($now,'dayhour','tzuser',$outputlangs),
339
+                'current_server_date_locale'=>dol_print_date($now,'day','tzserver',$outputlangs),
340
+                'current_server_datehour_locale'=>dol_print_date($now,'dayhour','tzserver',$outputlangs),
341
+        );
342
+
343
+
344
+        foreach($conf->global as $key => $val)
345
+        {
346
+            if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****';
347
+            else $newval = $val;
348
+            $array_other['__['.$key.']__'] = $newval;
349
+        }
350
+
351
+        return $array_other;
352 352
     }
353 353
 
354 354
 
355 355
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
356
-	/**
357
-	 * Define array with couple substitution key => substitution value
358
-	 *
359
-	 * @param   Object			$object             Main object to use as data source
360
-	 * @param   Translate		$outputlangs        Lang object to use for output
356
+    /**
357
+     * Define array with couple substitution key => substitution value
358
+     *
359
+     * @param   Object			$object             Main object to use as data source
360
+     * @param   Translate		$outputlangs        Lang object to use for output
361 361
      * @param   string		    $array_key	        Name of the key for return array
362
-	 * @return	array								Array of substitution
363
-	 */
364
-	function get_substitutionarray_object($object,$outputlangs,$array_key='object')
365
-	{
362
+     * @return	array								Array of substitution
363
+     */
364
+    function get_substitutionarray_object($object,$outputlangs,$array_key='object')
365
+    {
366 366
         // phpcs:enable
367
-		global $conf;
368
-
369
-		$sumpayed=$sumdeposit=$sumcreditnote='';
370
-		if ($object->element == 'facture')
371
-		{
372
-			$invoice_source=new Facture($this->db);
373
-			if ($object->fk_facture_source > 0)
374
-			{
375
-				$invoice_source->fetch($object->fk_facture_source);
376
-			}
377
-			$sumpayed = $object->getSommePaiement();
378
-			$sumdeposit = $object->getSumDepositsUsed();
379
-			$sumcreditnote = $object->getSumCreditNotesUsed();
380
-		}
381
-
382
-		$date = ($object->element == 'contrat' ? $object->date_contrat : $object->date);
383
-
384
-		$resarray=array(
385
-		$array_key.'_id'=>$object->id,
386
-		$array_key.'_ref'=>$object->ref,
387
-		$array_key.'_ref_ext'=>$object->ref_ext,
388
-		$array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
389
-		$array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
390
-		$array_key.'_source_invoice_ref'=>$invoice_source->ref,
391
-		// Dates
367
+        global $conf;
368
+
369
+        $sumpayed=$sumdeposit=$sumcreditnote='';
370
+        if ($object->element == 'facture')
371
+        {
372
+            $invoice_source=new Facture($this->db);
373
+            if ($object->fk_facture_source > 0)
374
+            {
375
+                $invoice_source->fetch($object->fk_facture_source);
376
+            }
377
+            $sumpayed = $object->getSommePaiement();
378
+            $sumdeposit = $object->getSumDepositsUsed();
379
+            $sumcreditnote = $object->getSumCreditNotesUsed();
380
+        }
381
+
382
+        $date = ($object->element == 'contrat' ? $object->date_contrat : $object->date);
383
+
384
+        $resarray=array(
385
+        $array_key.'_id'=>$object->id,
386
+        $array_key.'_ref'=>$object->ref,
387
+        $array_key.'_ref_ext'=>$object->ref_ext,
388
+        $array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
389
+        $array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
390
+        $array_key.'_source_invoice_ref'=>$invoice_source->ref,
391
+        // Dates
392 392
         $array_key.'_hour'=>dol_print_date($date,'hour'),
393
-		$array_key.'_date'=>dol_print_date($date,'day'),
394
-		$array_key.'_date_rfc'=>dol_print_date($date,'dayrfc'),
395
-		$array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement,'day'):''),
396
-	    $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite,'day'):''),
397
-		$array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
398
-		$array_key.'_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
399
-		$array_key.'_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
400
-		$array_key.'_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
401
-		$array_key.'_date_close'=>(! empty($object->date_cloture)?dol_print_date($object->date_cloture,'dayhour'):''),
402
-
403
-		$array_key.'_payment_mode_code'=>$object->mode_reglement_code,
404
-		$array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
405
-		$array_key.'_payment_term_code'=>$object->cond_reglement_code,
406
-		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):($object->cond_reglement_doc?$object->cond_reglement_doc:$object->cond_reglement)),
407
-
408
-		$array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
409
-		$array_key.'_total_vat_locale'=>(! empty($object->total_vat)?price($object->total_vat, 0, $outputlangs):price($object->total_tva, 0, $outputlangs)),
410
-		$array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
411
-		$array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
412
-		$array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
413
-
414
-		$array_key.'_total_ht'=>price2num($object->total_ht),
415
-		$array_key.'_total_vat'=>(! empty($object->total_vat)?price2num($object->total_vat):price2num($object->total_tva)),
416
-		$array_key.'_total_localtax1'=>price2num($object->total_localtax1),
417
-		$array_key.'_total_localtax2'=>price2num($object->total_localtax2),
418
-		$array_key.'_total_ttc'=>price2num($object->total_ttc),
419
-
420
-		$array_key.'_multicurrency_code' => price2num($object->multicurrency_code),
421
-		$array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx),
422
-	    $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
423
-	    $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
424
-		$array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc),
425
-		$array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs),
426
-		$array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs),
427
-		$array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs),
428
-
429
-		$array_key.'_note_private'=>$object->note,
430
-		$array_key.'_note_public'=>$object->note_public,
431
-		$array_key.'_note'=>$object->note_public,			// For backward compatibility
432
-
433
-		// Payments
434
-		$array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
435
-		$array_key.'_already_payed'=>price2num($sumpayed),
436
-		$array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs),
437
-		$array_key.'_already_deposit'=>price2num($sumdeposit),
438
-		$array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs),
439
-		$array_key.'_already_creditnote'=>price2num($sumcreditnote),
440
-
441
-		$array_key.'_already_payed_all_locale'=>price(price2num($sumpayed + $sumdeposit + $sumcreditnote, 'MT'), 0, $outputlangs),
442
-		$array_key.'_already_payed_all'=> price2num(($sumpayed + $sumdeposit + $sumcreditnote), 'MT'),
443
-
444
-		// Remain to pay with all know infrmation (except open direct debit requests)
445
-		$array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT'), 0, $outputlangs),
446
-		$array_key.'_remain_to_pay'=>price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT')
447
-		);
448
-
449
-		if (method_exists($object, 'getTotalDiscount')) {
450
-			$resarray[$array_key.'_total_discount_ht_locale'] = price($object->getTotalDiscount(), 0, $outputlangs);
451
-			$resarray[$array_key.'_total_discount_ht'] = price2num($object->getTotalDiscount());
452
-		} else {
453
-			$resarray[$array_key.'_total_discount_ht_locale'] = '';
454
-			$resarray[$array_key.'_total_discount_ht'] = '';
455
-		}
456
-
457
-		// Fetch project information if there is a project assigned to this object
458
-		if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0)
459
-		{
460
-			if (! is_object($object->project))
461
-			{
462
-				$object->fetch_projet();
463
-			}
464
-
465
-			$resarray[$array_key.'_project_ref'] = $object->project->ref;
466
-			$resarray[$array_key.'_project_title'] = $object->project->title;
467
-			$resarray[$array_key.'_project_description'] = $object->project->description;
468
-			$resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day');
469
-			$resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day');
470
-		}
471
-
472
-		// Add vat by rates
473
-		if (is_array($object->lines) && count($object->lines)>0)
474
-		{
475
-			foreach ($object->lines as $line)
476
-			{
477
-			    // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility
478
-				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0;
479
-				$resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
480
-				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
481
-			    // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
482
-				$vatformated=vatrate($line->tva_tx);
483
-				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated]=0;
484
-				$resarray[$array_key.'_total_vat_'.$vatformated]+=$line->total_tva;
485
-				$resarray[$array_key.'_total_vat_locale_'.$vatformated]=price($resarray[$array_key.'_total_vat_'.$vatformated]);
486
-			}
487
-		}
488
-		// Retrieve extrafields
489
-		if (is_array($object->array_options) && count($object->array_options))
490
-		{
491
-			$extrafieldkey=$object->element;
492
-
493
-			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
494
-			$extrafields = new ExtraFields($this->db);
495
-			$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
496
-			$object->fetch_optionals();
497
-
498
-			$resarray = $this->fill_substitutionarray_with_extrafields($object,$resarray,$extrafields,$array_key,$outputlangs);
499
-		}
500
-		return $resarray;
501
-	}
393
+        $array_key.'_date'=>dol_print_date($date,'day'),
394
+        $array_key.'_date_rfc'=>dol_print_date($date,'dayrfc'),
395
+        $array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement,'day'):''),
396
+        $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite,'day'):''),
397
+        $array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
398
+        $array_key.'_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
399
+        $array_key.'_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
400
+        $array_key.'_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
401
+        $array_key.'_date_close'=>(! empty($object->date_cloture)?dol_print_date($object->date_cloture,'dayhour'):''),
402
+
403
+        $array_key.'_payment_mode_code'=>$object->mode_reglement_code,
404
+        $array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
405
+        $array_key.'_payment_term_code'=>$object->cond_reglement_code,
406
+        $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):($object->cond_reglement_doc?$object->cond_reglement_doc:$object->cond_reglement)),
407
+
408
+        $array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
409
+        $array_key.'_total_vat_locale'=>(! empty($object->total_vat)?price($object->total_vat, 0, $outputlangs):price($object->total_tva, 0, $outputlangs)),
410
+        $array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
411
+        $array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
412
+        $array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
413
+
414
+        $array_key.'_total_ht'=>price2num($object->total_ht),
415
+        $array_key.'_total_vat'=>(! empty($object->total_vat)?price2num($object->total_vat):price2num($object->total_tva)),
416
+        $array_key.'_total_localtax1'=>price2num($object->total_localtax1),
417
+        $array_key.'_total_localtax2'=>price2num($object->total_localtax2),
418
+        $array_key.'_total_ttc'=>price2num($object->total_ttc),
419
+
420
+        $array_key.'_multicurrency_code' => price2num($object->multicurrency_code),
421
+        $array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx),
422
+        $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht),
423
+        $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva),
424
+        $array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc),
425
+        $array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs),
426
+        $array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs),
427
+        $array_key.'_multicurrency_total_ttc_locale' => price($object->multicurrency_total_ttc, 0, $outputlangs),
428
+
429
+        $array_key.'_note_private'=>$object->note,
430
+        $array_key.'_note_public'=>$object->note_public,
431
+        $array_key.'_note'=>$object->note_public,			// For backward compatibility
432
+
433
+        // Payments
434
+        $array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
435
+        $array_key.'_already_payed'=>price2num($sumpayed),
436
+        $array_key.'_already_deposit_locale'=>price($sumdeposit, 0, $outputlangs),
437
+        $array_key.'_already_deposit'=>price2num($sumdeposit),
438
+        $array_key.'_already_creditnote_locale'=>price($sumcreditnote, 0, $outputlangs),
439
+        $array_key.'_already_creditnote'=>price2num($sumcreditnote),
440
+
441
+        $array_key.'_already_payed_all_locale'=>price(price2num($sumpayed + $sumdeposit + $sumcreditnote, 'MT'), 0, $outputlangs),
442
+        $array_key.'_already_payed_all'=> price2num(($sumpayed + $sumdeposit + $sumcreditnote), 'MT'),
443
+
444
+        // Remain to pay with all know infrmation (except open direct debit requests)
445
+        $array_key.'_remain_to_pay_locale'=>price(price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT'), 0, $outputlangs),
446
+        $array_key.'_remain_to_pay'=>price2num($object->total_ttc - $sumpayed - $sumdeposit - $sumcreditnote, 'MT')
447
+        );
448
+
449
+        if (method_exists($object, 'getTotalDiscount')) {
450
+            $resarray[$array_key.'_total_discount_ht_locale'] = price($object->getTotalDiscount(), 0, $outputlangs);
451
+            $resarray[$array_key.'_total_discount_ht'] = price2num($object->getTotalDiscount());
452
+        } else {
453
+            $resarray[$array_key.'_total_discount_ht_locale'] = '';
454
+            $resarray[$array_key.'_total_discount_ht'] = '';
455
+        }
456
+
457
+        // Fetch project information if there is a project assigned to this object
458
+        if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0)
459
+        {
460
+            if (! is_object($object->project))
461
+            {
462
+                $object->fetch_projet();
463
+            }
464
+
465
+            $resarray[$array_key.'_project_ref'] = $object->project->ref;
466
+            $resarray[$array_key.'_project_title'] = $object->project->title;
467
+            $resarray[$array_key.'_project_description'] = $object->project->description;
468
+            $resarray[$array_key.'_project_date_start'] = dol_print_date($object->project->date_start, 'day');
469
+            $resarray[$array_key.'_project_date_end'] = dol_print_date($object->project->date_end, 'day');
470
+        }
471
+
472
+        // Add vat by rates
473
+        if (is_array($object->lines) && count($object->lines)>0)
474
+        {
475
+            foreach ($object->lines as $line)
476
+            {
477
+                // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility
478
+                if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0;
479
+                $resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
480
+                $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
481
+                // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
482
+                $vatformated=vatrate($line->tva_tx);
483
+                if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated]=0;
484
+                $resarray[$array_key.'_total_vat_'.$vatformated]+=$line->total_tva;
485
+                $resarray[$array_key.'_total_vat_locale_'.$vatformated]=price($resarray[$array_key.'_total_vat_'.$vatformated]);
486
+            }
487
+        }
488
+        // Retrieve extrafields
489
+        if (is_array($object->array_options) && count($object->array_options))
490
+        {
491
+            $extrafieldkey=$object->element;
492
+
493
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
494
+            $extrafields = new ExtraFields($this->db);
495
+            $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
496
+            $object->fetch_optionals();
497
+
498
+            $resarray = $this->fill_substitutionarray_with_extrafields($object,$resarray,$extrafields,$array_key,$outputlangs);
499
+        }
500
+        return $resarray;
501
+    }
502 502
 
503 503
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
504
-	/**
505
-	 *	Define array with couple substitution key => substitution value
506
-	 *
507
-	 *	@param  Object			$line				Object line
508
-	 *	@param  Translate		$outputlangs        Lang object to use for output
509
-	 *  @return	array								Return a substitution array
510
-	 */
511
-	function get_substitutionarray_lines($line, $outputlangs)
512
-	{
504
+    /**
505
+     *	Define array with couple substitution key => substitution value
506
+     *
507
+     *	@param  Object			$line				Object line
508
+     *	@param  Translate		$outputlangs        Lang object to use for output
509
+     *  @return	array								Return a substitution array
510
+     */
511
+    function get_substitutionarray_lines($line, $outputlangs)
512
+    {
513 513
         // phpcs:enable
514
-		global $conf;
515
-
516
-		$resarray= array(
517
-			'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
518
-			'line_product_ref'=>$line->product_ref,
519
-			'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines
520
-			'line_product_label'=>$line->product_label,
521
-			'line_product_type'=>$line->product_type,
522
-			'line_desc'=>$line->desc,
523
-			'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
524
-			'line_up'=>price2num($line->subprice),
525
-			'line_up_locale'=>price($line->subprice, 0, $outputlangs),
526
-			'line_qty'=>$line->qty,
527
-			'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
528
-			'line_price_ht'=>price2num($line->total_ht),
529
-			'line_price_ttc'=>price2num($line->total_ttc),
530
-			'line_price_vat'=>price2num($line->total_tva),
531
-			'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs),
532
-			'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs),
533
-			'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs),
534
-		    // Dates
535
-			'line_date_start'=>dol_print_date($line->date_start, 'day', 'tzuser'),
536
-			'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzuser', $outputlangs),
537
-		    'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc', 'tzuser'),
538
-		    'line_date_end'=>dol_print_date($line->date_end, 'day', 'tzuser'),
539
-		    'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzuser', $outputlangs),
540
-		    'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc', 'tzuser'),
541
-
542
-		    'line_multicurrency_code' => price2num($line->multicurrency_code),
543
-		    'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
544
-		    'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
545
-		    'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
546
-		    'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
547
-		    'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
548
-		    'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
549
-		    'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
550
-		    'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
551
-		);
552
-
553
-		    // Units
554
-		if ($conf->global->PRODUCT_USE_UNITS)
555
-		{
556
-		      $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long'));
557
-		      $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short'));
558
-		}
559
-
560
-		// Retrieve extrafields
561
-		$extrafieldkey=$line->element;
562
-		$array_key="line";
563
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
564
-		$extrafields = new ExtraFields($this->db);
565
-		$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
566
-		$line->fetch_optionals();
567
-
568
-		$resarray = $this->fill_substitutionarray_with_extrafields($line,$resarray,$extrafields,$array_key=$array_key,$outputlangs);
569
-
570
-		// Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
571
-		if (isset($line->fk_product) && $line->fk_product > 0)
572
-		{
573
-			$tmpproduct = new Product($this->db);
574
-			$result = $tmpproduct->fetch($line->fk_product);
575
-			foreach($tmpproduct->array_options as $key=>$label)
576
-				$resarray["line_product_".$key] = $label;
577
-		}
578
-
579
-		return $resarray;
580
-	}
514
+        global $conf;
515
+
516
+        $resarray= array(
517
+            'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
518
+            'line_product_ref'=>$line->product_ref,
519
+            'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines
520
+            'line_product_label'=>$line->product_label,
521
+            'line_product_type'=>$line->product_type,
522
+            'line_desc'=>$line->desc,
523
+            'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
524
+            'line_up'=>price2num($line->subprice),
525
+            'line_up_locale'=>price($line->subprice, 0, $outputlangs),
526
+            'line_qty'=>$line->qty,
527
+            'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
528
+            'line_price_ht'=>price2num($line->total_ht),
529
+            'line_price_ttc'=>price2num($line->total_ttc),
530
+            'line_price_vat'=>price2num($line->total_tva),
531
+            'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs),
532
+            'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs),
533
+            'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs),
534
+            // Dates
535
+            'line_date_start'=>dol_print_date($line->date_start, 'day', 'tzuser'),
536
+            'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzuser', $outputlangs),
537
+            'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc', 'tzuser'),
538
+            'line_date_end'=>dol_print_date($line->date_end, 'day', 'tzuser'),
539
+            'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzuser', $outputlangs),
540
+            'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc', 'tzuser'),
541
+
542
+            'line_multicurrency_code' => price2num($line->multicurrency_code),
543
+            'line_multicurrency_subprice' => price2num($line->multicurrency_subprice),
544
+            'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht),
545
+            'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva),
546
+            'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc),
547
+            'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs),
548
+            'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs),
549
+            'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs),
550
+            'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs),
551
+        );
552
+
553
+            // Units
554
+        if ($conf->global->PRODUCT_USE_UNITS)
555
+        {
556
+                $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long'));
557
+                $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short'));
558
+        }
559
+
560
+        // Retrieve extrafields
561
+        $extrafieldkey=$line->element;
562
+        $array_key="line";
563
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
564
+        $extrafields = new ExtraFields($this->db);
565
+        $extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
566
+        $line->fetch_optionals();
567
+
568
+        $resarray = $this->fill_substitutionarray_with_extrafields($line,$resarray,$extrafields,$array_key=$array_key,$outputlangs);
569
+
570
+        // Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
571
+        if (isset($line->fk_product) && $line->fk_product > 0)
572
+        {
573
+            $tmpproduct = new Product($this->db);
574
+            $result = $tmpproduct->fetch($line->fk_product);
575
+            foreach($tmpproduct->array_options as $key=>$label)
576
+                $resarray["line_product_".$key] = $label;
577
+        }
578
+
579
+        return $resarray;
580
+    }
581 581
 
582 582
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
583 583
     /**
@@ -591,54 +591,54 @@  discard block
 block discarded – undo
591 591
     function get_substitutionarray_shipment($object,$outputlangs,$array_key='object')
592 592
     {
593 593
         // phpcs:enable
594
-    	global $conf;
595
-		dol_include_once('/core/lib/product.lib.php');
596
-		$object->list_delivery_methods($object->shipping_method_id);
597
-		$calculatedVolume=($object->trueWidth * $object->trueHeight * $object->trueDepth);
598
-
599
-    	$array_shipment=array(
600
-	    	$array_key.'_id'=>$object->id,
601
-	    	$array_key.'_ref'=>$object->ref,
602
-	    	$array_key.'_ref_ext'=>$object->ref_ext,
603
-	    	$array_key.'_ref_customer'=>$object->ref_customer,
604
-	    	$array_key.'_date_delivery'=>dol_print_date($object->date_delivery,'day'),
605
-	    	$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery,'hour'),
606
-	    	$array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
607
-	    	$array_key.'_total_ht'=>price($object->total_ht),
608
-	    	$array_key.'_total_vat'=>price($object->total_tva),
609
-	    	$array_key.'_total_ttc'=>price($object->total_ttc),
610
-	    	$array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
611
-	    	$array_key.'_note_private'=>$object->note_private,
612
-	    	$array_key.'_note'=>$object->note_public,
613
-	    	$array_key.'_tracking_number'=>$object->tracking_number,
614
-	    	$array_key.'_tracking_url'=>$object->tracking_url,
615
-	    	$array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
616
-	    	$array_key.'_weight'=>$object->trueWeight.' '.measuring_units_string($object->weight_units, 'weight'),
617
-	    	$array_key.'_width'=>$object->trueWidth.' '.measuring_units_string($object->width_units, 'size'),
618
-	    	$array_key.'_height'=>$object->trueHeight.' '.measuring_units_string($object->height_units, 'size'),
619
-	    	$array_key.'_depth'=>$object->trueDepth.' '.measuring_units_string($object->depth_units, 'size'),
620
-	    	$array_key.'_size'=>$calculatedVolume.' '.measuring_units_string(0, 'volume'),
621
-    	);
622
-
623
-    	// Add vat by rates
624
-    	foreach ($object->lines as $line)
625
-    	{
626
-    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
627
-    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
628
-    	}
629
-
630
-    	// Retrieve extrafields
631
-    	if (is_array($object->array_options) && count($object->array_options))
632
-    	{
633
-    		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
634
-    		$extrafields = new ExtraFields($this->db);
635
-    		$extralabels = $extrafields->fetch_name_optionals_label('expedition',true);
636
-    		$object->fetch_optionals();
637
-
638
-    		$array_shipment = $this->fill_substitutionarray_with_extrafields($object,$array_shipment,$extrafields,$array_key,$outputlangs);
639
-    	}
640
-
641
-    	return $array_shipment;
594
+        global $conf;
595
+        dol_include_once('/core/lib/product.lib.php');
596
+        $object->list_delivery_methods($object->shipping_method_id);
597
+        $calculatedVolume=($object->trueWidth * $object->trueHeight * $object->trueDepth);
598
+
599
+        $array_shipment=array(
600
+            $array_key.'_id'=>$object->id,
601
+            $array_key.'_ref'=>$object->ref,
602
+            $array_key.'_ref_ext'=>$object->ref_ext,
603
+            $array_key.'_ref_customer'=>$object->ref_customer,
604
+            $array_key.'_date_delivery'=>dol_print_date($object->date_delivery,'day'),
605
+            $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery,'hour'),
606
+            $array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
607
+            $array_key.'_total_ht'=>price($object->total_ht),
608
+            $array_key.'_total_vat'=>price($object->total_tva),
609
+            $array_key.'_total_ttc'=>price($object->total_ttc),
610
+            $array_key.'_total_discount_ht' => price($object->getTotalDiscount()),
611
+            $array_key.'_note_private'=>$object->note_private,
612
+            $array_key.'_note'=>$object->note_public,
613
+            $array_key.'_tracking_number'=>$object->tracking_number,
614
+            $array_key.'_tracking_url'=>$object->tracking_url,
615
+            $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'],
616
+            $array_key.'_weight'=>$object->trueWeight.' '.measuring_units_string($object->weight_units, 'weight'),
617
+            $array_key.'_width'=>$object->trueWidth.' '.measuring_units_string($object->width_units, 'size'),
618
+            $array_key.'_height'=>$object->trueHeight.' '.measuring_units_string($object->height_units, 'size'),
619
+            $array_key.'_depth'=>$object->trueDepth.' '.measuring_units_string($object->depth_units, 'size'),
620
+            $array_key.'_size'=>$calculatedVolume.' '.measuring_units_string(0, 'volume'),
621
+        );
622
+
623
+        // Add vat by rates
624
+        foreach ($object->lines as $line)
625
+        {
626
+            if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
627
+            $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
628
+        }
629
+
630
+        // Retrieve extrafields
631
+        if (is_array($object->array_options) && count($object->array_options))
632
+        {
633
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
634
+            $extrafields = new ExtraFields($this->db);
635
+            $extralabels = $extrafields->fetch_name_optionals_label('expedition',true);
636
+            $object->fetch_optionals();
637
+
638
+            $array_shipment = $this->fill_substitutionarray_with_extrafields($object,$array_shipment,$extrafields,$array_key,$outputlangs);
639
+        }
640
+
641
+        return $array_shipment;
642 642
     }
643 643
 
644 644
 
@@ -657,24 +657,24 @@  discard block
 block discarded – undo
657 657
         dol_include_once('/core/lib/product.lib.php');
658 658
 
659 659
         $resarray = array(
660
-	    	'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
661
-	    	'line_product_ref'=>$line->product_ref,
662
-	    	'line_product_label'=>$line->product_label,
663
-	    	'line_desc'=>$line->desc,
664
-	    	'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
665
-	    	'line_up'=>price($line->subprice),
666
-	    	'line_qty'=>$line->qty,
667
-	    	'line_qty_shipped'=>$line->qty_shipped,
668
-	    	'line_qty_asked'=>$line->qty_asked,
669
-	    	'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
670
-	    	'line_price_ht'=>price($line->total_ht),
671
-	    	'line_price_ttc'=>price($line->total_ttc),
672
-	    	'line_price_vat'=>price($line->total_tva),
673
-	    	'line_weight'=>empty($line->weight) ? '' : $line->weight*$line->qty_shipped.' '.measuring_units_string($line->weight_units, 'weight'),
674
-	    	'line_length'=>empty($line->length) ? '' : $line->length*$line->qty_shipped.' '.measuring_units_string($line->length_units, 'size'),
675
-	    	'line_surface'=>empty($line->surface) ? '' : $line->surface*$line->qty_shipped.' '.measuring_units_string($line->surface_units, 'surface'),
676
-	    	'line_volume'=>empty($line->volume) ? '' : $line->volume*$line->qty_shipped.' '.measuring_units_string($line->volume_units, 'volume'),
677
-    	);
660
+            'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
661
+            'line_product_ref'=>$line->product_ref,
662
+            'line_product_label'=>$line->product_label,
663
+            'line_desc'=>$line->desc,
664
+            'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
665
+            'line_up'=>price($line->subprice),
666
+            'line_qty'=>$line->qty,
667
+            'line_qty_shipped'=>$line->qty_shipped,
668
+            'line_qty_asked'=>$line->qty_asked,
669
+            'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
670
+            'line_price_ht'=>price($line->total_ht),
671
+            'line_price_ttc'=>price($line->total_ttc),
672
+            'line_price_vat'=>price($line->total_tva),
673
+            'line_weight'=>empty($line->weight) ? '' : $line->weight*$line->qty_shipped.' '.measuring_units_string($line->weight_units, 'weight'),
674
+            'line_length'=>empty($line->length) ? '' : $line->length*$line->qty_shipped.' '.measuring_units_string($line->length_units, 'size'),
675
+            'line_surface'=>empty($line->surface) ? '' : $line->surface*$line->qty_shipped.' '.measuring_units_string($line->surface_units, 'surface'),
676
+            'line_volume'=>empty($line->volume) ? '' : $line->volume*$line->qty_shipped.' '.measuring_units_string($line->volume_units, 'volume'),
677
+        );
678 678
 
679 679
         // Retrieve extrafields
680 680
         $extrafieldkey = $line->element;
@@ -731,92 +731,92 @@  discard block
 block discarded – undo
731 731
      *	@return	array								Substitution array
732 732
      */
733 733
     function fill_substitutionarray_with_extrafields($object,$array_to_fill,$extrafields,$array_key,$outputlangs)
734
-	{
734
+    {
735 735
         // phpcs:enable
736
-		global $conf;
737
-		foreach($extrafields->attribute_label as $key=>$label)
738
-		{
739
-			if($extrafields->attribute_type[$key] == 'price')
740
-			{
741
-				$object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]);
742
-				$object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
743
-				//Add value to store price with currency
744
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
745
-			}
746
-			else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
747
-			{
748
-				$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
749
-			}
750
-			else if($extrafields->attribute_type[$key] == 'date')
751
-			{
752
-				if (strlen($object->array_options['options_'.$key])>0)
753
-				{
754
-					$date = $object->array_options['options_'.$key];
755
-					$object->array_options['options_'.$key] = dol_print_date($date,'day');                                       // using company output language
756
-					$object->array_options['options_'.$key.'_locale'] = dol_print_date($date,'day','tzserver',$outputlangs);     // using output language format
757
-					$object->array_options['options_'.$key.'_rfc'] = dol_print_date($date,'dayrfc');                             // international format
758
-				}
759
-				else
760
-				{
761
-					$object->array_options['options_'.$key] = '';
762
-					$object->array_options['options_'.$key.'_locale'] = '';
763
-					$object->array_options['options_'.$key.'_rfc'] = '';
764
-				}
765
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
766
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
767
-			}
768
-			else if($extrafields->attribute_type[$key] == 'datetime')
769
-			{
770
-				$datetime = $object->array_options['options_'.$key];
771
-				$object->array_options['options_'.$key] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour'):'');                            // using company output language
772
-				$object->array_options['options_'.$key.'_locale'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour','tzserver',$outputlangs):'');    // using output language format
773
-				$object->array_options['options_'.$key.'_rfc'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhourrfc'):'');                             // international format
774
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
775
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
776
-			}
777
-			else if($extrafields->attribute_type[$key] == 'link')
778
-			{
779
-				$id = $object->array_options['options_'.$key];
780
-				if ($id != "")
781
-				{
782
-					$param = $extrafields->attribute_param[$key];
783
-					$param_list=array_keys($param['options']);              // $param_list='ObjectName:classPath'
784
-					$InfoFieldList = explode(":", $param_list[0]);
785
-					$classname=$InfoFieldList[0];
786
-					$classpath=$InfoFieldList[1];
787
-					if (! empty($classpath))
788
-					{
789
-						dol_include_once($InfoFieldList[1]);
790
-						if ($classname && class_exists($classname))
791
-						{
792
-							$tmpobject = new $classname($this->db);
793
-							$tmpobject->fetch($id);
794
-							// completely replace the id with the linked object name
795
-							$object->array_options['options_'.$key] = $tmpobject->name;
796
-						}
797
-					}
798
-				}
799
-			}
800
-
801
-			$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
802
-		}
803
-
804
-		return $array_to_fill;
805
-	}
806
-
807
-
808
-	/**
809
-	 * Rect pdf
810
-	 *
811
-	 * @param	TCPDF	$pdf			Object PDF
812
-	 * @param	float	$x				Abscissa of first point
813
-	 * @param	float	$y		        Ordinate of first point
814
-	 * @param	float	$l				??
815
-	 * @param	float	$h				??
816
-	 * @param	int		$hidetop		1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title
817
-	 * @param	int		$hidebottom		Hide bottom
818
-	 * @return	void
819
-	 */
736
+        global $conf;
737
+        foreach($extrafields->attribute_label as $key=>$label)
738
+        {
739
+            if($extrafields->attribute_type[$key] == 'price')
740
+            {
741
+                $object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]);
742
+                $object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
743
+                //Add value to store price with currency
744
+                $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
745
+            }
746
+            else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
747
+            {
748
+                $object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
749
+            }
750
+            else if($extrafields->attribute_type[$key] == 'date')
751
+            {
752
+                if (strlen($object->array_options['options_'.$key])>0)
753
+                {
754
+                    $date = $object->array_options['options_'.$key];
755
+                    $object->array_options['options_'.$key] = dol_print_date($date,'day');                                       // using company output language
756
+                    $object->array_options['options_'.$key.'_locale'] = dol_print_date($date,'day','tzserver',$outputlangs);     // using output language format
757
+                    $object->array_options['options_'.$key.'_rfc'] = dol_print_date($date,'dayrfc');                             // international format
758
+                }
759
+                else
760
+                {
761
+                    $object->array_options['options_'.$key] = '';
762
+                    $object->array_options['options_'.$key.'_locale'] = '';
763
+                    $object->array_options['options_'.$key.'_rfc'] = '';
764
+                }
765
+                $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
766
+                $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
767
+            }
768
+            else if($extrafields->attribute_type[$key] == 'datetime')
769
+            {
770
+                $datetime = $object->array_options['options_'.$key];
771
+                $object->array_options['options_'.$key] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour'):'');                            // using company output language
772
+                $object->array_options['options_'.$key.'_locale'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour','tzserver',$outputlangs):'');    // using output language format
773
+                $object->array_options['options_'.$key.'_rfc'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhourrfc'):'');                             // international format
774
+                $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
775
+                $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
776
+            }
777
+            else if($extrafields->attribute_type[$key] == 'link')
778
+            {
779
+                $id = $object->array_options['options_'.$key];
780
+                if ($id != "")
781
+                {
782
+                    $param = $extrafields->attribute_param[$key];
783
+                    $param_list=array_keys($param['options']);              // $param_list='ObjectName:classPath'
784
+                    $InfoFieldList = explode(":", $param_list[0]);
785
+                    $classname=$InfoFieldList[0];
786
+                    $classpath=$InfoFieldList[1];
787
+                    if (! empty($classpath))
788
+                    {
789
+                        dol_include_once($InfoFieldList[1]);
790
+                        if ($classname && class_exists($classname))
791
+                        {
792
+                            $tmpobject = new $classname($this->db);
793
+                            $tmpobject->fetch($id);
794
+                            // completely replace the id with the linked object name
795
+                            $object->array_options['options_'.$key] = $tmpobject->name;
796
+                        }
797
+                    }
798
+                }
799
+            }
800
+
801
+            $array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
802
+        }
803
+
804
+        return $array_to_fill;
805
+    }
806
+
807
+
808
+    /**
809
+     * Rect pdf
810
+     *
811
+     * @param	TCPDF	$pdf			Object PDF
812
+     * @param	float	$x				Abscissa of first point
813
+     * @param	float	$y		        Ordinate of first point
814
+     * @param	float	$l				??
815
+     * @param	float	$h				??
816
+     * @param	int		$hidetop		1=Hide top bar of array and title, 0=Hide nothing, -1=Hide only title
817
+     * @param	int		$hidebottom		Hide bottom
818
+     * @return	void
819
+     */
820 820
     function printRect($pdf, $x, $y, $l, $h, $hidetop=0, $hidebottom=0)
821 821
     {
822 822
         if (empty($hidetop) || $hidetop==-1) $pdf->line($x, $y, $x+$l, $y);
Please login to merge, or discard this patch.
Spacing   +196 added lines, -196 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
      * @var string[]    Array of error strings
@@ -69,17 +69,17 @@  discard block
 block discarded – undo
69 69
      * @param   Translate	$outputlangs    Language object for output
70 70
      * @return	array						Array of substitution key->code
71 71
      */
72
-    function get_substitutionarray_user($user,$outputlangs)
72
+    function get_substitutionarray_user($user, $outputlangs)
73 73
     {
74 74
         // phpcs:enable
75 75
         global $conf;
76 76
 
77
-        $logotouse=$conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
77
+        $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo;
78 78
 
79 79
         return array(
80 80
             'myuser_lastname'=>$user->lastname,
81 81
             'myuser_firstname'=>$user->firstname,
82
-            'myuser_fullname'=>$user->getFullName($outputlangs,1),
82
+            'myuser_fullname'=>$user->getFullName($outputlangs, 1),
83 83
             'myuser_login'=>$user->login,
84 84
             'myuser_phone'=>$user->office_phone,
85 85
        		'myuser_address'=>$user->address,
@@ -107,25 +107,25 @@  discard block
 block discarded – undo
107 107
      * @param   Translate	$outputlangs    Language object for output
108 108
      * @return	array						Array of substitution key->code
109 109
      */
110
-    function get_substitutionarray_mysoc($mysoc,$outputlangs)
110
+    function get_substitutionarray_mysoc($mysoc, $outputlangs)
111 111
     {
112 112
         // phpcs:enable
113 113
         global $conf;
114 114
 
115
-        if (empty($mysoc->forme_juridique) && ! empty($mysoc->forme_juridique_code))
115
+        if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code))
116 116
         {
117
-            $mysoc->forme_juridique=getFormeJuridiqueLabel($mysoc->forme_juridique_code);
117
+            $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code);
118 118
         }
119
-        if (empty($mysoc->country) && ! empty($mysoc->country_code))
119
+        if (empty($mysoc->country) && !empty($mysoc->country_code))
120 120
         {
121
-        	$mysoc->country=$outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
121
+        	$mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code);
122 122
         }
123
-        if (empty($mysoc->state) && ! empty($mysoc->state_code))
123
+        if (empty($mysoc->state) && !empty($mysoc->state_code))
124 124
         {
125
-        	$mysoc->state=getState($mysoc->state_code,0);
125
+        	$mysoc->state = getState($mysoc->state_code, 0);
126 126
         }
127 127
 
128
-        $logotouse=$conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
128
+        $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small;
129 129
 
130 130
         return array(
131 131
             'mycompany_logo'=>$logotouse,
@@ -167,18 +167,18 @@  discard block
 block discarded – undo
167 167
      * @param   Translate	$outputlangs    Language object for output
168 168
      * @return	array						Array of substitution key->code
169 169
      */
170
-    function get_substitutionarray_thirdparty($object,$outputlangs)
170
+    function get_substitutionarray_thirdparty($object, $outputlangs)
171 171
     {
172 172
         // phpcs:enable
173 173
         global $conf;
174 174
 
175
-        if (empty($object->country) && ! empty($object->country_code))
175
+        if (empty($object->country) && !empty($object->country_code))
176 176
         {
177
-        	$object->country=$outputlangs->transnoentitiesnoconv("Country".$object->country_code);
177
+        	$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
178 178
         }
179
-        if (empty($object->state) && ! empty($object->state_code))
179
+        if (empty($object->state) && !empty($object->state_code))
180 180
         {
181
-        	$object->state=getState($object->state_code,0);
181
+        	$object->state = getState($object->state_code, 0);
182 182
         }
183 183
 
184 184
         $array_thirdparty = array(
@@ -217,24 +217,24 @@  discard block
 block discarded – undo
217 217
         );
218 218
 
219 219
         // Retrieve extrafields
220
-        if(is_array($object->array_options) && count($object->array_options))
220
+        if (is_array($object->array_options) && count($object->array_options))
221 221
         {
222 222
         	require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
223 223
         	$extrafields = new ExtraFields($this->db);
224
-        	$extralabels = $extrafields->fetch_name_optionals_label('societe',true);
224
+        	$extralabels = $extrafields->fetch_name_optionals_label('societe', true);
225 225
         	$object->fetch_optionals();
226 226
 
227
-        	foreach($extrafields->attribute_label as $key=>$label)
227
+        	foreach ($extrafields->attribute_label as $key=>$label)
228 228
         	{
229
-        		if($extrafields->attribute_type[$key] == 'price')
229
+        		if ($extrafields->attribute_type[$key] == 'price')
230 230
         		{
231
-        			$object->array_options['options_'.$key] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
231
+        			$object->array_options['options_'.$key] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency);
232 232
         		}
233
-        		else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
233
+        		else if ($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
234 234
         		{
235 235
         			$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
236 236
         		}
237
-        		$array_thirdparty = array_merge($array_thirdparty, array ('company_options_'.$key => $object->array_options ['options_' . $key]));
237
+        		$array_thirdparty = array_merge($array_thirdparty, array('company_options_'.$key => $object->array_options ['options_'.$key]));
238 238
 			}
239 239
 		}
240 240
 		return $array_thirdparty;
@@ -254,61 +254,61 @@  discard block
 block discarded – undo
254 254
         // phpcs:enable
255 255
 		global $conf;
256 256
 
257
-		if(empty($object->country) && ! empty($object->country_code))
257
+		if (empty($object->country) && !empty($object->country_code))
258 258
 		{
259
-			$object->country = $outputlangs->transnoentitiesnoconv("Country" . $object->country_code);
259
+			$object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code);
260 260
 		}
261
-		if(empty($object->state) && ! empty($object->state_code))
261
+		if (empty($object->state) && !empty($object->state_code))
262 262
 		{
263 263
 			$object->state = getState($object->state_code, 0);
264 264
 		}
265 265
 
266
-		$array_contact = array (
267
-		    $array_key . '_fullname' => $object->getFullName($outputlangs, 1),
268
-            $array_key . '_lastname' => $object->lastname,
269
-            $array_key . '_firstname' => $object->firstname,
270
-            $array_key . '_address' => $object->address,
271
-            $array_key . '_zip' => $object->zip,
272
-            $array_key . '_town' => $object->town,
273
-            $array_key . '_state_id' => $object->state_id,
274
-            $array_key . '_state_code' => $object->state_code,
275
-            $array_key . '_state' => $object->state,
276
-            $array_key . '_country_id' => $object->country_id,
277
-            $array_key . '_country_code' => $object->country_code,
278
-            $array_key . '_country' => $object->country,
279
-            $array_key . '_poste' => $object->poste,
280
-            $array_key . '_socid' => $object->socid,
281
-            $array_key . '_statut' => $object->statut,
282
-            $array_key . '_code' => $object->code,
283
-            $array_key . '_email' => $object->email,
284
-            $array_key . '_jabberid' => $object->jabberid,
285
-            $array_key . '_phone_pro' => $object->phone_pro,
286
-            $array_key . '_phone_perso' => $object->phone_perso,
287
-            $array_key . '_phone_mobile' => $object->phone_mobile,
288
-            $array_key . '_fax' => $object->fax,
289
-            $array_key . '_birthday' => $object->birthday,
290
-            $array_key . '_default_lang' => $object->default_lang,
291
-            $array_key . '_note_public' => $object->note_public,
292
-            $array_key . '_note_private' => $object->note_private
266
+		$array_contact = array(
267
+		    $array_key.'_fullname' => $object->getFullName($outputlangs, 1),
268
+            $array_key.'_lastname' => $object->lastname,
269
+            $array_key.'_firstname' => $object->firstname,
270
+            $array_key.'_address' => $object->address,
271
+            $array_key.'_zip' => $object->zip,
272
+            $array_key.'_town' => $object->town,
273
+            $array_key.'_state_id' => $object->state_id,
274
+            $array_key.'_state_code' => $object->state_code,
275
+            $array_key.'_state' => $object->state,
276
+            $array_key.'_country_id' => $object->country_id,
277
+            $array_key.'_country_code' => $object->country_code,
278
+            $array_key.'_country' => $object->country,
279
+            $array_key.'_poste' => $object->poste,
280
+            $array_key.'_socid' => $object->socid,
281
+            $array_key.'_statut' => $object->statut,
282
+            $array_key.'_code' => $object->code,
283
+            $array_key.'_email' => $object->email,
284
+            $array_key.'_jabberid' => $object->jabberid,
285
+            $array_key.'_phone_pro' => $object->phone_pro,
286
+            $array_key.'_phone_perso' => $object->phone_perso,
287
+            $array_key.'_phone_mobile' => $object->phone_mobile,
288
+            $array_key.'_fax' => $object->fax,
289
+            $array_key.'_birthday' => $object->birthday,
290
+            $array_key.'_default_lang' => $object->default_lang,
291
+            $array_key.'_note_public' => $object->note_public,
292
+            $array_key.'_note_private' => $object->note_private
293 293
 		);
294 294
 
295 295
 		// Retrieve extrafields
296
-		require_once DOL_DOCUMENT_ROOT . '/core/class/extrafields.class.php';
296
+		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
297 297
 		$extrafields = new ExtraFields($this->db);
298 298
 		$extralabels = $extrafields->fetch_name_optionals_label('socpeople', true);
299 299
 		$object->fetch_optionals();
300 300
 
301
-		foreach($extrafields->attribute_label as $key => $label)
301
+		foreach ($extrafields->attribute_label as $key => $label)
302 302
 		{
303 303
 			if ($extrafields->attribute_type[$key] == 'price')
304 304
 			{
305
-				$object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency);
305
+				$object->array_options['options_'.$key] = price($object->array_options ['options_'.$key], 0, $outputlangs, 0, 0, - 1, $conf->currency);
306 306
 			}
307
-			elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
307
+			elseif ($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
308 308
 			{
309
-				$object->array_options['options_' . $key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_' . $key]];
309
+				$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
310 310
 			}
311
-			$array_contact = array_merge($array_contact, array($array_key.'_options_' . $key => $object->array_options['options_'. $key]));
311
+			$array_contact = array_merge($array_contact, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
312 312
 		}
313 313
 		return $array_contact;
314 314
 	}
@@ -326,22 +326,22 @@  discard block
 block discarded – undo
326 326
         // phpcs:enable
327 327
     	global $conf;
328 328
 
329
-    	$now=dol_now('gmt');	// gmt
329
+    	$now = dol_now('gmt'); // gmt
330 330
     	$array_other = array(
331 331
     	    // Date in default language
332
-    	    'current_date'=>dol_print_date($now,'day','tzuser'),
333
-    	    'current_datehour'=>dol_print_date($now,'dayhour','tzuser'),
334
-   			'current_server_date'=>dol_print_date($now,'day','tzserver'),
335
-   			'current_server_datehour'=>dol_print_date($now,'dayhour','tzserver'),
332
+    	    'current_date'=>dol_print_date($now, 'day', 'tzuser'),
333
+    	    'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'),
334
+   			'current_server_date'=>dol_print_date($now, 'day', 'tzserver'),
335
+   			'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'),
336 336
     	    // Date in requested output language
337
-    	    'current_date_locale'=>dol_print_date($now,'day','tzuser',$outputlangs),
338
-   			'current_datehour_locale'=>dol_print_date($now,'dayhour','tzuser',$outputlangs),
339
-   			'current_server_date_locale'=>dol_print_date($now,'day','tzserver',$outputlangs),
340
-   			'current_server_datehour_locale'=>dol_print_date($now,'dayhour','tzserver',$outputlangs),
337
+    	    'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs),
338
+   			'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs),
339
+   			'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs),
340
+   			'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs),
341 341
     	);
342 342
 
343 343
 
344
-    	foreach($conf->global as $key => $val)
344
+    	foreach ($conf->global as $key => $val)
345 345
     	{
346 346
     		if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****';
347 347
     		else $newval = $val;
@@ -361,15 +361,15 @@  discard block
 block discarded – undo
361 361
      * @param   string		    $array_key	        Name of the key for return array
362 362
 	 * @return	array								Array of substitution
363 363
 	 */
364
-	function get_substitutionarray_object($object,$outputlangs,$array_key='object')
364
+	function get_substitutionarray_object($object, $outputlangs, $array_key = 'object')
365 365
 	{
366 366
         // phpcs:enable
367 367
 		global $conf;
368 368
 
369
-		$sumpayed=$sumdeposit=$sumcreditnote='';
369
+		$sumpayed = $sumdeposit = $sumcreditnote = '';
370 370
 		if ($object->element == 'facture')
371 371
 		{
372
-			$invoice_source=new Facture($this->db);
372
+			$invoice_source = new Facture($this->db);
373 373
 			if ($object->fk_facture_source > 0)
374 374
 			{
375 375
 				$invoice_source->fetch($object->fk_facture_source);
@@ -381,38 +381,38 @@  discard block
 block discarded – undo
381 381
 
382 382
 		$date = ($object->element == 'contrat' ? $object->date_contrat : $object->date);
383 383
 
384
-		$resarray=array(
384
+		$resarray = array(
385 385
 		$array_key.'_id'=>$object->id,
386 386
 		$array_key.'_ref'=>$object->ref,
387 387
 		$array_key.'_ref_ext'=>$object->ref_ext,
388
-		$array_key.'_ref_customer'=>(! empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
389
-		$array_key.'_ref_supplier'=>(! empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
388
+		$array_key.'_ref_customer'=>(!empty($object->ref_client) ? $object->ref_client : (empty($object->ref_customer) ? '' : $object->ref_customer)),
389
+		$array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)),
390 390
 		$array_key.'_source_invoice_ref'=>$invoice_source->ref,
391 391
 		// Dates
392
-        $array_key.'_hour'=>dol_print_date($date,'hour'),
393
-		$array_key.'_date'=>dol_print_date($date,'day'),
394
-		$array_key.'_date_rfc'=>dol_print_date($date,'dayrfc'),
395
-		$array_key.'_date_limit'=>(! empty($object->date_lim_reglement)?dol_print_date($object->date_lim_reglement,'day'):''),
396
-	    $array_key.'_date_end'=>(! empty($object->fin_validite)?dol_print_date($object->fin_validite,'day'):''),
397
-		$array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
398
-		$array_key.'_date_modification'=>(! empty($object->date_modification)?dol_print_date($object->date_modification,'day'):''),
399
-		$array_key.'_date_validation'=>(! empty($object->date_validation)?dol_print_date($object->date_validation,'dayhour'):''),
400
-		$array_key.'_date_delivery_planed'=>(! empty($object->date_livraison)?dol_print_date($object->date_livraison,'day'):''),
401
-		$array_key.'_date_close'=>(! empty($object->date_cloture)?dol_print_date($object->date_cloture,'dayhour'):''),
392
+        $array_key.'_hour'=>dol_print_date($date, 'hour'),
393
+		$array_key.'_date'=>dol_print_date($date, 'day'),
394
+		$array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'),
395
+		$array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''),
396
+	    $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''),
397
+		$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
398
+		$array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''),
399
+		$array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''),
400
+		$array_key.'_date_delivery_planed'=>(!empty($object->date_livraison) ?dol_print_date($object->date_livraison, 'day') : ''),
401
+		$array_key.'_date_close'=>(!empty($object->date_cloture) ?dol_print_date($object->date_cloture, 'dayhour') : ''),
402 402
 
403 403
 		$array_key.'_payment_mode_code'=>$object->mode_reglement_code,
404
-		$array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code)!='PaymentType'.$object->mode_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code):$object->mode_reglement),
404
+		$array_key.'_payment_mode'=>($outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) != 'PaymentType'.$object->mode_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentType'.$object->mode_reglement_code) : $object->mode_reglement),
405 405
 		$array_key.'_payment_term_code'=>$object->cond_reglement_code,
406
-		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code)!='PaymentCondition'.$object->cond_reglement_code?$outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code):($object->cond_reglement_doc?$object->cond_reglement_doc:$object->cond_reglement)),
406
+		$array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)),
407 407
 
408 408
 		$array_key.'_total_ht_locale'=>price($object->total_ht, 0, $outputlangs),
409
-		$array_key.'_total_vat_locale'=>(! empty($object->total_vat)?price($object->total_vat, 0, $outputlangs):price($object->total_tva, 0, $outputlangs)),
409
+		$array_key.'_total_vat_locale'=>(!empty($object->total_vat) ?price($object->total_vat, 0, $outputlangs) : price($object->total_tva, 0, $outputlangs)),
410 410
 		$array_key.'_total_localtax1_locale'=>price($object->total_localtax1, 0, $outputlangs),
411 411
 		$array_key.'_total_localtax2_locale'=>price($object->total_localtax2, 0, $outputlangs),
412 412
 		$array_key.'_total_ttc_locale'=>price($object->total_ttc, 0, $outputlangs),
413 413
 
414 414
 		$array_key.'_total_ht'=>price2num($object->total_ht),
415
-		$array_key.'_total_vat'=>(! empty($object->total_vat)?price2num($object->total_vat):price2num($object->total_tva)),
415
+		$array_key.'_total_vat'=>(!empty($object->total_vat) ?price2num($object->total_vat) : price2num($object->total_tva)),
416 416
 		$array_key.'_total_localtax1'=>price2num($object->total_localtax1),
417 417
 		$array_key.'_total_localtax2'=>price2num($object->total_localtax2),
418 418
 		$array_key.'_total_ttc'=>price2num($object->total_ttc),
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
 
429 429
 		$array_key.'_note_private'=>$object->note,
430 430
 		$array_key.'_note_public'=>$object->note_public,
431
-		$array_key.'_note'=>$object->note_public,			// For backward compatibility
431
+		$array_key.'_note'=>$object->note_public, // For backward compatibility
432 432
 
433 433
 		// Payments
434 434
 		$array_key.'_already_payed_locale'=>price($sumpayed, 0, $outputlangs),
@@ -455,9 +455,9 @@  discard block
 block discarded – undo
455 455
 		}
456 456
 
457 457
 		// Fetch project information if there is a project assigned to this object
458
-		if ($object->element != "project" && ! empty($object->fk_project) && $object->fk_project > 0)
458
+		if ($object->element != "project" && !empty($object->fk_project) && $object->fk_project > 0)
459 459
 		{
460
-			if (! is_object($object->project))
460
+			if (!is_object($object->project))
461 461
 			{
462 462
 				$object->fetch_projet();
463 463
 			}
@@ -470,32 +470,32 @@  discard block
 block discarded – undo
470 470
 		}
471 471
 
472 472
 		// Add vat by rates
473
-		if (is_array($object->lines) && count($object->lines)>0)
473
+		if (is_array($object->lines) && count($object->lines) > 0)
474 474
 		{
475 475
 			foreach ($object->lines as $line)
476 476
 			{
477 477
 			    // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility
478
-				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0;
479
-				$resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
480
-				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
478
+				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0;
479
+				$resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
480
+				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
481 481
 			    // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
482
-				$vatformated=vatrate($line->tva_tx);
483
-				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated]=0;
484
-				$resarray[$array_key.'_total_vat_'.$vatformated]+=$line->total_tva;
485
-				$resarray[$array_key.'_total_vat_locale_'.$vatformated]=price($resarray[$array_key.'_total_vat_'.$vatformated]);
482
+				$vatformated = vatrate($line->tva_tx);
483
+				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0;
484
+				$resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva;
485
+				$resarray[$array_key.'_total_vat_locale_'.$vatformated] = price($resarray[$array_key.'_total_vat_'.$vatformated]);
486 486
 			}
487 487
 		}
488 488
 		// Retrieve extrafields
489 489
 		if (is_array($object->array_options) && count($object->array_options))
490 490
 		{
491
-			$extrafieldkey=$object->element;
491
+			$extrafieldkey = $object->element;
492 492
 
493 493
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
494 494
 			$extrafields = new ExtraFields($this->db);
495
-			$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
495
+			$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey, true);
496 496
 			$object->fetch_optionals();
497 497
 
498
-			$resarray = $this->fill_substitutionarray_with_extrafields($object,$resarray,$extrafields,$array_key,$outputlangs);
498
+			$resarray = $this->fill_substitutionarray_with_extrafields($object, $resarray, $extrafields, $array_key, $outputlangs);
499 499
 		}
500 500
 		return $resarray;
501 501
 	}
@@ -513,18 +513,18 @@  discard block
 block discarded – undo
513 513
         // phpcs:enable
514 514
 		global $conf;
515 515
 
516
-		$resarray= array(
517
-			'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
516
+		$resarray = array(
517
+			'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
518 518
 			'line_product_ref'=>$line->product_ref,
519 519
 			'line_product_ref_fourn'=>$line->ref_fourn, // for supplier doc lines
520 520
 			'line_product_label'=>$line->product_label,
521 521
 			'line_product_type'=>$line->product_type,
522 522
 			'line_desc'=>$line->desc,
523
-			'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
523
+			'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
524 524
 			'line_up'=>price2num($line->subprice),
525 525
 			'line_up_locale'=>price($line->subprice, 0, $outputlangs),
526 526
 			'line_qty'=>$line->qty,
527
-			'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
527
+			'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
528 528
 			'line_price_ht'=>price2num($line->total_ht),
529 529
 			'line_price_ttc'=>price2num($line->total_ttc),
530 530
 			'line_price_vat'=>price2num($line->total_tva),
@@ -553,26 +553,26 @@  discard block
 block discarded – undo
553 553
 		    // Units
554 554
 		if ($conf->global->PRODUCT_USE_UNITS)
555 555
 		{
556
-		      $resarray['line_unit']=$outputlangs->trans($line->getLabelOfUnit('long'));
557
-		      $resarray['line_unit_short']=$outputlangs->trans($line->getLabelOfUnit('short'));
556
+		      $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long'));
557
+		      $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short'));
558 558
 		}
559 559
 
560 560
 		// Retrieve extrafields
561
-		$extrafieldkey=$line->element;
562
-		$array_key="line";
561
+		$extrafieldkey = $line->element;
562
+		$array_key = "line";
563 563
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
564 564
 		$extrafields = new ExtraFields($this->db);
565
-		$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey,true);
565
+		$extralabels = $extrafields->fetch_name_optionals_label($extrafieldkey, true);
566 566
 		$line->fetch_optionals();
567 567
 
568
-		$resarray = $this->fill_substitutionarray_with_extrafields($line,$resarray,$extrafields,$array_key=$array_key,$outputlangs);
568
+		$resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key = $array_key, $outputlangs);
569 569
 
570 570
 		// Load product data optional fields to the line -> enables to use "line_options_{extrafield}"
571 571
 		if (isset($line->fk_product) && $line->fk_product > 0)
572 572
 		{
573 573
 			$tmpproduct = new Product($this->db);
574 574
 			$result = $tmpproduct->fetch($line->fk_product);
575
-			foreach($tmpproduct->array_options as $key=>$label)
575
+			foreach ($tmpproduct->array_options as $key=>$label)
576 576
 				$resarray["line_product_".$key] = $label;
577 577
 		}
578 578
 
@@ -588,22 +588,22 @@  discard block
 block discarded – undo
588 588
      * @param   array			$array_key	        Name of the key for return array
589 589
      * @return	array								Array of substitution
590 590
      */
591
-    function get_substitutionarray_shipment($object,$outputlangs,$array_key='object')
591
+    function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object')
592 592
     {
593 593
         // phpcs:enable
594 594
     	global $conf;
595 595
 		dol_include_once('/core/lib/product.lib.php');
596 596
 		$object->list_delivery_methods($object->shipping_method_id);
597
-		$calculatedVolume=($object->trueWidth * $object->trueHeight * $object->trueDepth);
597
+		$calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth);
598 598
 
599
-    	$array_shipment=array(
599
+    	$array_shipment = array(
600 600
 	    	$array_key.'_id'=>$object->id,
601 601
 	    	$array_key.'_ref'=>$object->ref,
602 602
 	    	$array_key.'_ref_ext'=>$object->ref_ext,
603 603
 	    	$array_key.'_ref_customer'=>$object->ref_customer,
604
-	    	$array_key.'_date_delivery'=>dol_print_date($object->date_delivery,'day'),
605
-	    	$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery,'hour'),
606
-	    	$array_key.'_date_creation'=>dol_print_date($object->date_creation,'day'),
604
+	    	$array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'),
605
+	    	$array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'),
606
+	    	$array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'),
607 607
 	    	$array_key.'_total_ht'=>price($object->total_ht),
608 608
 	    	$array_key.'_total_vat'=>price($object->total_tva),
609 609
 	    	$array_key.'_total_ttc'=>price($object->total_ttc),
@@ -623,8 +623,8 @@  discard block
 block discarded – undo
623 623
     	// Add vat by rates
624 624
     	foreach ($object->lines as $line)
625 625
     	{
626
-    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
627
-    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
626
+    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0;
627
+    		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva;
628 628
     	}
629 629
 
630 630
     	// Retrieve extrafields
@@ -632,10 +632,10 @@  discard block
 block discarded – undo
632 632
     	{
633 633
     		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
634 634
     		$extrafields = new ExtraFields($this->db);
635
-    		$extralabels = $extrafields->fetch_name_optionals_label('expedition',true);
635
+    		$extralabels = $extrafields->fetch_name_optionals_label('expedition', true);
636 636
     		$object->fetch_optionals();
637 637
 
638
-    		$array_shipment = $this->fill_substitutionarray_with_extrafields($object,$array_shipment,$extrafields,$array_key,$outputlangs);
638
+    		$array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs);
639 639
     	}
640 640
 
641 641
     	return $array_shipment;
@@ -657,23 +657,23 @@  discard block
 block discarded – undo
657 657
         dol_include_once('/core/lib/product.lib.php');
658 658
 
659 659
         $resarray = array(
660
-	    	'line_fulldesc'=>doc_getlinedesc($line,$outputlangs),
660
+	    	'line_fulldesc'=>doc_getlinedesc($line, $outputlangs),
661 661
 	    	'line_product_ref'=>$line->product_ref,
662 662
 	    	'line_product_label'=>$line->product_label,
663 663
 	    	'line_desc'=>$line->desc,
664
-	    	'line_vatrate'=>vatrate($line->tva_tx,true,$line->info_bits),
664
+	    	'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits),
665 665
 	    	'line_up'=>price($line->subprice),
666 666
 	    	'line_qty'=>$line->qty,
667 667
 	    	'line_qty_shipped'=>$line->qty_shipped,
668 668
 	    	'line_qty_asked'=>$line->qty_asked,
669
-	    	'line_discount_percent'=>($line->remise_percent?$line->remise_percent.'%':''),
669
+	    	'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''),
670 670
 	    	'line_price_ht'=>price($line->total_ht),
671 671
 	    	'line_price_ttc'=>price($line->total_ttc),
672 672
 	    	'line_price_vat'=>price($line->total_tva),
673
-	    	'line_weight'=>empty($line->weight) ? '' : $line->weight*$line->qty_shipped.' '.measuring_units_string($line->weight_units, 'weight'),
674
-	    	'line_length'=>empty($line->length) ? '' : $line->length*$line->qty_shipped.' '.measuring_units_string($line->length_units, 'size'),
675
-	    	'line_surface'=>empty($line->surface) ? '' : $line->surface*$line->qty_shipped.' '.measuring_units_string($line->surface_units, 'surface'),
676
-	    	'line_volume'=>empty($line->volume) ? '' : $line->volume*$line->qty_shipped.' '.measuring_units_string($line->volume_units, 'volume'),
673
+	    	'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuring_units_string($line->weight_units, 'weight'),
674
+	    	'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuring_units_string($line->length_units, 'size'),
675
+	    	'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuring_units_string($line->surface_units, 'surface'),
676
+	    	'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuring_units_string($line->volume_units, 'volume'),
677 677
     	);
678 678
 
679 679
         // Retrieve extrafields
@@ -699,18 +699,18 @@  discard block
 block discarded – undo
699 699
      * @param   boolean		$recursive    	Want to fetch child array or child object
700 700
      * @return	array						Array of substitution key->code
701 701
      */
702
-    function get_substitutionarray_each_var_object(&$object,$outputlangs,$recursive=true)
702
+    function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true)
703 703
     {
704 704
         // phpcs:enable
705 705
         $array_other = array();
706 706
         if (!empty($object)) {
707
-            foreach($object as $key => $value) {
707
+            foreach ($object as $key => $value) {
708 708
                 if (!empty($value)) {
709 709
                     if (!is_array($value) && !is_object($value)) {
710 710
                         $array_other['object_'.$key] = $value;
711 711
                     }
712 712
                     if (is_array($value) && $recursive) {
713
-                        $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value,$outputlangs,false);
713
+                        $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false);
714 714
                     }
715 715
                 }
716 716
             }
@@ -730,31 +730,31 @@  discard block
 block discarded – undo
730 730
      *  @param  Translate		$outputlangs        Lang object to use for output
731 731
      *	@return	array								Substitution array
732 732
      */
733
-    function fill_substitutionarray_with_extrafields($object,$array_to_fill,$extrafields,$array_key,$outputlangs)
733
+    function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs)
734 734
 	{
735 735
         // phpcs:enable
736 736
 		global $conf;
737
-		foreach($extrafields->attribute_label as $key=>$label)
737
+		foreach ($extrafields->attribute_label as $key=>$label)
738 738
 		{
739
-			if($extrafields->attribute_type[$key] == 'price')
739
+			if ($extrafields->attribute_type[$key] == 'price')
740 740
 			{
741 741
 				$object->array_options['options_'.$key] = price2num($object->array_options['options_'.$key]);
742
-				$object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
742
+				$object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key], 0, $outputlangs, 0, 0, -1, $conf->currency);
743 743
 				//Add value to store price with currency
744
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
744
+				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
745 745
 			}
746
-			else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
746
+			else if ($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
747 747
 			{
748 748
 				$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
749 749
 			}
750
-			else if($extrafields->attribute_type[$key] == 'date')
750
+			else if ($extrafields->attribute_type[$key] == 'date')
751 751
 			{
752
-				if (strlen($object->array_options['options_'.$key])>0)
752
+				if (strlen($object->array_options['options_'.$key]) > 0)
753 753
 				{
754 754
 					$date = $object->array_options['options_'.$key];
755
-					$object->array_options['options_'.$key] = dol_print_date($date,'day');                                       // using company output language
756
-					$object->array_options['options_'.$key.'_locale'] = dol_print_date($date,'day','tzserver',$outputlangs);     // using output language format
757
-					$object->array_options['options_'.$key.'_rfc'] = dol_print_date($date,'dayrfc');                             // international format
755
+					$object->array_options['options_'.$key] = dol_print_date($date, 'day'); // using company output language
756
+					$object->array_options['options_'.$key.'_locale'] = dol_print_date($date, 'day', 'tzserver', $outputlangs); // using output language format
757
+					$object->array_options['options_'.$key.'_rfc'] = dol_print_date($date, 'dayrfc'); // international format
758 758
 				}
759 759
 				else
760 760
 				{
@@ -762,29 +762,29 @@  discard block
 block discarded – undo
762 762
 					$object->array_options['options_'.$key.'_locale'] = '';
763 763
 					$object->array_options['options_'.$key.'_rfc'] = '';
764 764
 				}
765
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
766
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
765
+				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
766
+				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
767 767
 			}
768
-			else if($extrafields->attribute_type[$key] == 'datetime')
768
+			else if ($extrafields->attribute_type[$key] == 'datetime')
769 769
 			{
770 770
 				$datetime = $object->array_options['options_'.$key];
771
-				$object->array_options['options_'.$key] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour'):'');                            // using company output language
772
-				$object->array_options['options_'.$key.'_locale'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour','tzserver',$outputlangs):'');    // using output language format
773
-				$object->array_options['options_'.$key.'_rfc'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhourrfc'):'');                             // international format
774
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
775
-				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
771
+				$object->array_options['options_'.$key] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour') : ''); // using company output language
772
+				$object->array_options['options_'.$key.'_locale'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhour', 'tzserver', $outputlangs) : ''); // using output language format
773
+				$object->array_options['options_'.$key.'_rfc'] = ($datetime != "0000-00-00 00:00:00" ?dol_print_date($object->array_options['options_'.$key], 'dayhourrfc') : ''); // international format
774
+				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
775
+				$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
776 776
 			}
777
-			else if($extrafields->attribute_type[$key] == 'link')
777
+			else if ($extrafields->attribute_type[$key] == 'link')
778 778
 			{
779 779
 				$id = $object->array_options['options_'.$key];
780 780
 				if ($id != "")
781 781
 				{
782 782
 					$param = $extrafields->attribute_param[$key];
783
-					$param_list=array_keys($param['options']);              // $param_list='ObjectName:classPath'
783
+					$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
784 784
 					$InfoFieldList = explode(":", $param_list[0]);
785
-					$classname=$InfoFieldList[0];
786
-					$classpath=$InfoFieldList[1];
787
-					if (! empty($classpath))
785
+					$classname = $InfoFieldList[0];
786
+					$classpath = $InfoFieldList[1];
787
+					if (!empty($classpath))
788 788
 					{
789 789
 						dol_include_once($InfoFieldList[1]);
790 790
 						if ($classname && class_exists($classname))
@@ -798,7 +798,7 @@  discard block
 block discarded – undo
798 798
 				}
799 799
 			}
800 800
 
801
-			$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
801
+			$array_to_fill = array_merge($array_to_fill, array($array_key.'_options_'.$key => $object->array_options['options_'.$key]));
802 802
 		}
803 803
 
804 804
 		return $array_to_fill;
@@ -817,12 +817,12 @@  discard block
 block discarded – undo
817 817
 	 * @param	int		$hidebottom		Hide bottom
818 818
 	 * @return	void
819 819
 	 */
820
-    function printRect($pdf, $x, $y, $l, $h, $hidetop=0, $hidebottom=0)
820
+    function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0)
821 821
     {
822
-        if (empty($hidetop) || $hidetop==-1) $pdf->line($x, $y, $x+$l, $y);
823
-        $pdf->line($x+$l, $y, $x+$l, $y+$h);
824
-        if (empty($hidebottom)) $pdf->line($x+$l, $y+$h, $x, $y+$h);
825
-        $pdf->line($x, $y+$h, $x, $y);
822
+        if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y);
823
+        $pdf->line($x + $l, $y, $x + $l, $y + $h);
824
+        if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h);
825
+        $pdf->line($x, $y + $h, $x, $y);
826 826
     }
827 827
 
828 828
 
@@ -835,8 +835,8 @@  discard block
 block discarded – undo
835 835
      */
836 836
     function columnSort($a, $b)
837 837
     {
838
-        if(empty($a['rank'])){ $a['rank'] = 0; }
839
-        if(empty($b['rank'])){ $b['rank'] = 0; }
838
+        if (empty($a['rank'])) { $a['rank'] = 0; }
839
+        if (empty($b['rank'])) { $b['rank'] = 0; }
840 840
         if ($a['rank'] == $b['rank']) {
841 841
             return 0;
842 842
         }
@@ -853,38 +853,38 @@  discard block
 block discarded – undo
853 853
      *      @param	int				$hideref			Do not show ref
854 854
      *      @return	null
855 855
      */
856
-    function prepareArrayColumnField($object,$outputlangs,$hidedetails=0,$hidedesc=0,$hideref=0)
856
+    function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
857 857
     {
858 858
         global $conf;
859 859
 
860
-        $this->defineColumnField($object,$outputlangs,$hidedetails,$hidedesc,$hideref);
860
+        $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref);
861 861
 
862 862
 
863 863
         // Sorting
864
-        uasort ( $this->cols, array( $this, 'columnSort' ) );
864
+        uasort($this->cols, array($this, 'columnSort'));
865 865
 
866 866
         // Positionning
867
-        $curX = $this->page_largeur-$this->marge_droite; // start from right
867
+        $curX = $this->page_largeur - $this->marge_droite; // start from right
868 868
 
869 869
         // Array witdh
870
-        $arrayWidth = $this->page_largeur-$this->marge_droite-$this->marge_gauche;
870
+        $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche;
871 871
 
872 872
         // Count flexible column
873 873
         $totalDefinedColWidth = 0;
874 874
         $countFlexCol = 0;
875 875
         foreach ($this->cols as $colKey =>& $colDef)
876 876
         {
877
-            if(!$this->getColumnStatus($colKey)) continue; // continue if desable
877
+            if (!$this->getColumnStatus($colKey)) continue; // continue if desable
878 878
 
879
-            if(!empty($colDef['scale'])){
879
+            if (!empty($colDef['scale'])) {
880 880
                 // In case of column widht is defined by percentage
881
-                $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100 );
881
+                $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100);
882 882
             }
883 883
 
884
-            if(empty($colDef['width'])){
884
+            if (empty($colDef['width'])) {
885 885
                 $countFlexCol++;
886 886
             }
887
-            else{
887
+            else {
888 888
                 $totalDefinedColWidth += $colDef['width'];
889 889
             }
890 890
         }
@@ -892,25 +892,25 @@  discard block
 block discarded – undo
892 892
         foreach ($this->cols as $colKey =>& $colDef)
893 893
         {
894 894
             // setting empty conf with default
895
-            if(!empty($colDef['title'])){
895
+            if (!empty($colDef['title'])) {
896 896
                 $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
897 897
             }
898
-            else{
898
+            else {
899 899
                 $colDef['title'] = $this->defaultTitlesFieldsStyle;
900 900
             }
901 901
 
902 902
             // setting empty conf with default
903
-            if(!empty($colDef['content'])){
903
+            if (!empty($colDef['content'])) {
904 904
                 $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
905 905
             }
906
-            else{
906
+            else {
907 907
                 $colDef['content'] = $this->defaultContentsFieldsStyle;
908 908
             }
909 909
 
910
-            if($this->getColumnStatus($colKey))
910
+            if ($this->getColumnStatus($colKey))
911 911
             {
912 912
                 // In case of flexible column
913
-                if(empty($colDef['width'])){
913
+                if (empty($colDef['width'])) {
914 914
                     $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol;
915 915
                 }
916 916
 
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
      */
957 957
     function getColumnRank($colKey)
958 958
     {
959
-        if(!isset($this->cols[$colKey]['rank'])) return -1;
959
+        if (!isset($this->cols[$colKey]['rank'])) return -1;
960 960
         return  $this->cols[$colKey]['rank'];
961 961
     }
962 962
 
@@ -975,22 +975,22 @@  discard block
 block discarded – undo
975 975
         $rank = -1;
976 976
 
977 977
         // try to get rank from target column
978
-        if(!empty($targetCol)){
978
+        if (!empty($targetCol)) {
979 979
             $rank = $this->getColumnRank($targetCol);
980
-            if($rank>=0 && $insertAfterTarget){ $rank++; }
980
+            if ($rank >= 0 && $insertAfterTarget) { $rank++; }
981 981
         }
982 982
 
983 983
         // get rank from new column definition
984
-        if($rank<0 && !empty($defArray['rank'])){
984
+        if ($rank < 0 && !empty($defArray['rank'])) {
985 985
             $rank = $defArray['rank'];
986 986
         }
987 987
 
988 988
         // error: no rank
989
-        if($rank<0){ return -1; }
989
+        if ($rank < 0) { return -1; }
990 990
 
991 991
         foreach ($this->cols as $colKey =>& $colDef)
992 992
         {
993
-            if( $rank <= $colDef['rank'])
993
+            if ($rank <= $colDef['rank'])
994 994
             {
995 995
                 $colDef['rank'] = $colDef['rank'] + 1;
996 996
             }
@@ -1016,19 +1016,19 @@  discard block
 block discarded – undo
1016 1016
     {
1017 1017
         global $hookmanager;
1018 1018
 
1019
-        $parameters=array(
1019
+        $parameters = array(
1020 1020
             'curY' => &$curY,
1021 1021
             'columnText' => $columnText,
1022 1022
             'colKey' => $colKey
1023 1023
         );
1024
-        $reshook=$hookmanager->executeHooks('printStdColumnContent',$parameters,$this);    // Note that $action and $object may have been modified by hook
1025
-        if ($reshook < 0) setEventMessages($hookmanager->error,$hookmanager->errors,'errors');
1024
+        $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook
1025
+        if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1026 1026
         if (!$reshook)
1027 1027
         {
1028
-            if(empty($columnText)) return;
1029
-            $pdf->SetXY($this->getColumnContentXStart($colKey),$curY); // Set curent position
1028
+            if (empty($columnText)) return;
1029
+            $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position
1030 1030
             $colDef = $this->cols[$colKey];
1031
-            $pdf->writeHTMLCell( $this->getColumnContentWidth($colKey),2,$this->getColumnContentXStart($colKey),$curY, $columnText,0,0,0,true,$colDef['content']['align']);
1031
+            $pdf->writeHTMLCell($this->getColumnContentWidth($colKey), 2, $this->getColumnContentXStart($colKey), $curY, $columnText, 0, 0, 0, true, $colDef['content']['align']);
1032 1032
         }
1033 1033
     }
1034 1034
 
@@ -1041,7 +1041,7 @@  discard block
 block discarded – undo
1041 1041
      */
1042 1042
     function getColumnStatus($colKey)
1043 1043
     {
1044
-        if( !empty($this->cols[$colKey]['status'])){
1044
+        if (!empty($this->cols[$colKey]['status'])) {
1045 1045
             return true;
1046 1046
         }
1047 1047
         else  return  false;
Please login to merge, or discard this patch.
Braces   +48 added lines, -34 removed lines patch added patch discarded remove patch
@@ -229,8 +229,7 @@  discard block
 block discarded – undo
229 229
         		if($extrafields->attribute_type[$key] == 'price')
230 230
         		{
231 231
         			$object->array_options['options_'.$key] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
232
-        		}
233
-        		else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
232
+        		} else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
234 233
         		{
235 234
         			$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
236 235
         		}
@@ -303,8 +302,7 @@  discard block
 block discarded – undo
303 302
 			if ($extrafields->attribute_type[$key] == 'price')
304 303
 			{
305 304
 				$object->array_options['options_' . $key] = price($object->array_options ['options_' . $key], 0, $outputlangs, 0, 0, - 1, $conf->currency);
306
-			}
307
-			elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
305
+			} elseif($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
308 306
 			{
309 307
 				$object->array_options['options_' . $key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_' . $key]];
310 308
 			}
@@ -343,8 +341,11 @@  discard block
 block discarded – undo
343 341
 
344 342
     	foreach($conf->global as $key => $val)
345 343
     	{
346
-    		if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) $newval = '*****forbidden*****';
347
-    		else $newval = $val;
344
+    		if (preg_match('/(_pass|password|secret|_key|key$)/i', $key)) {
345
+    		    $newval = '*****forbidden*****';
346
+    		} else {
347
+    		    $newval = $val;
348
+    		}
348 349
     		$array_other['__['.$key.']__'] = $newval;
349 350
     	}
350 351
 
@@ -475,12 +476,16 @@  discard block
 block discarded – undo
475 476
 			foreach ($object->lines as $line)
476 477
 			{
477 478
 			    // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward comaptibility
478
-				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0;
479
+				if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) {
480
+				    $resarray[$array_key.'_total_vat_'.$line->tva_tx]=0;
481
+				}
479 482
 				$resarray[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
480 483
 				$resarray[$array_key.'_total_vat_locale_'.$line->tva_tx]=price($resarray[$array_key.'_total_vat_'.$line->tva_tx]);
481 484
 			    // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example)
482 485
 				$vatformated=vatrate($line->tva_tx);
483
-				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated]=0;
486
+				if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) {
487
+				    $resarray[$array_key.'_total_vat_'.$vatformated]=0;
488
+				}
484 489
 				$resarray[$array_key.'_total_vat_'.$vatformated]+=$line->total_tva;
485 490
 				$resarray[$array_key.'_total_vat_locale_'.$vatformated]=price($resarray[$array_key.'_total_vat_'.$vatformated]);
486 491
 			}
@@ -572,8 +577,9 @@  discard block
 block discarded – undo
572 577
 		{
573 578
 			$tmpproduct = new Product($this->db);
574 579
 			$result = $tmpproduct->fetch($line->fk_product);
575
-			foreach($tmpproduct->array_options as $key=>$label)
576
-				$resarray["line_product_".$key] = $label;
580
+			foreach($tmpproduct->array_options as $key=>$label) {
581
+							$resarray["line_product_".$key] = $label;
582
+			}
577 583
 		}
578 584
 
579 585
 		return $resarray;
@@ -623,7 +629,9 @@  discard block
 block discarded – undo
623 629
     	// Add vat by rates
624 630
     	foreach ($object->lines as $line)
625 631
     	{
626
-    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
632
+    		if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) {
633
+    		    $array_shipment[$array_key.'_total_vat_'.$line->tva_tx]=0;
634
+    		}
627 635
     		$array_shipment[$array_key.'_total_vat_'.$line->tva_tx]+=$line->total_tva;
628 636
     	}
629 637
 
@@ -742,12 +750,10 @@  discard block
 block discarded – undo
742 750
 				$object->array_options['options_'.$key.'_currency'] = price($object->array_options['options_'.$key],0,$outputlangs,0,0,-1,$conf->currency);
743 751
 				//Add value to store price with currency
744 752
 				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_currency' => $object->array_options['options_'.$key.'_currency']));
745
-			}
746
-			else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
753
+			} else if($extrafields->attribute_type[$key] == 'select' || $extrafields->attribute_type[$key] == 'checkbox')
747 754
 			{
748 755
 				$object->array_options['options_'.$key] = $extrafields->attribute_param[$key]['options'][$object->array_options['options_'.$key]];
749
-			}
750
-			else if($extrafields->attribute_type[$key] == 'date')
756
+			} else if($extrafields->attribute_type[$key] == 'date')
751 757
 			{
752 758
 				if (strlen($object->array_options['options_'.$key])>0)
753 759
 				{
@@ -755,8 +761,7 @@  discard block
 block discarded – undo
755 761
 					$object->array_options['options_'.$key] = dol_print_date($date,'day');                                       // using company output language
756 762
 					$object->array_options['options_'.$key.'_locale'] = dol_print_date($date,'day','tzserver',$outputlangs);     // using output language format
757 763
 					$object->array_options['options_'.$key.'_rfc'] = dol_print_date($date,'dayrfc');                             // international format
758
-				}
759
-				else
764
+				} else
760 765
 				{
761 766
 					$object->array_options['options_'.$key] = '';
762 767
 					$object->array_options['options_'.$key.'_locale'] = '';
@@ -764,8 +769,7 @@  discard block
 block discarded – undo
764 769
 				}
765 770
 				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
766 771
 				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
767
-			}
768
-			else if($extrafields->attribute_type[$key] == 'datetime')
772
+			} else if($extrafields->attribute_type[$key] == 'datetime')
769 773
 			{
770 774
 				$datetime = $object->array_options['options_'.$key];
771 775
 				$object->array_options['options_'.$key] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhour'):'');                            // using company output language
@@ -773,8 +777,7 @@  discard block
 block discarded – undo
773 777
 				$object->array_options['options_'.$key.'_rfc'] = ($datetime!="0000-00-00 00:00:00"?dol_print_date($object->array_options['options_'.$key],'dayhourrfc'):'');                             // international format
774 778
 				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_locale' => $object->array_options['options_'.$key.'_locale']));
775 779
 				$array_to_fill=array_merge($array_to_fill,array($array_key.'_options_'.$key.'_rfc' => $object->array_options['options_'.$key.'_rfc']));
776
-			}
777
-			else if($extrafields->attribute_type[$key] == 'link')
780
+			} else if($extrafields->attribute_type[$key] == 'link')
778 781
 			{
779 782
 				$id = $object->array_options['options_'.$key];
780 783
 				if ($id != "")
@@ -819,9 +822,13 @@  discard block
 block discarded – undo
819 822
 	 */
820 823
     function printRect($pdf, $x, $y, $l, $h, $hidetop=0, $hidebottom=0)
821 824
     {
822
-        if (empty($hidetop) || $hidetop==-1) $pdf->line($x, $y, $x+$l, $y);
825
+        if (empty($hidetop) || $hidetop==-1) {
826
+            $pdf->line($x, $y, $x+$l, $y);
827
+        }
823 828
         $pdf->line($x+$l, $y, $x+$l, $y+$h);
824
-        if (empty($hidebottom)) $pdf->line($x+$l, $y+$h, $x, $y+$h);
829
+        if (empty($hidebottom)) {
830
+            $pdf->line($x+$l, $y+$h, $x, $y+$h);
831
+        }
825 832
         $pdf->line($x, $y+$h, $x, $y);
826 833
     }
827 834
 
@@ -874,7 +881,10 @@  discard block
 block discarded – undo
874 881
         $countFlexCol = 0;
875 882
         foreach ($this->cols as $colKey =>& $colDef)
876 883
         {
877
-            if(!$this->getColumnStatus($colKey)) continue; // continue if desable
884
+            if(!$this->getColumnStatus($colKey)) {
885
+                continue;
886
+            }
887
+            // continue if desable
878 888
 
879 889
             if(!empty($colDef['scale'])){
880 890
                 // In case of column widht is defined by percentage
@@ -883,8 +893,7 @@  discard block
 block discarded – undo
883 893
 
884 894
             if(empty($colDef['width'])){
885 895
                 $countFlexCol++;
886
-            }
887
-            else{
896
+            } else{
888 897
                 $totalDefinedColWidth += $colDef['width'];
889 898
             }
890 899
         }
@@ -894,16 +903,14 @@  discard block
 block discarded – undo
894 903
             // setting empty conf with default
895 904
             if(!empty($colDef['title'])){
896 905
                 $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']);
897
-            }
898
-            else{
906
+            } else{
899 907
                 $colDef['title'] = $this->defaultTitlesFieldsStyle;
900 908
             }
901 909
 
902 910
             // setting empty conf with default
903 911
             if(!empty($colDef['content'])){
904 912
                 $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']);
905
-            }
906
-            else{
913
+            } else{
907 914
                 $colDef['content'] = $this->defaultContentsFieldsStyle;
908 915
             }
909 916
 
@@ -956,7 +963,9 @@  discard block
 block discarded – undo
956 963
      */
957 964
     function getColumnRank($colKey)
958 965
     {
959
-        if(!isset($this->cols[$colKey]['rank'])) return -1;
966
+        if(!isset($this->cols[$colKey]['rank'])) {
967
+            return -1;
968
+        }
960 969
         return  $this->cols[$colKey]['rank'];
961 970
     }
962 971
 
@@ -1022,10 +1031,14 @@  discard block
 block discarded – undo
1022 1031
             'colKey' => $colKey
1023 1032
         );
1024 1033
         $reshook=$hookmanager->executeHooks('printStdColumnContent',$parameters,$this);    // Note that $action and $object may have been modified by hook
1025
-        if ($reshook < 0) setEventMessages($hookmanager->error,$hookmanager->errors,'errors');
1034
+        if ($reshook < 0) {
1035
+            setEventMessages($hookmanager->error,$hookmanager->errors,'errors');
1036
+        }
1026 1037
         if (!$reshook)
1027 1038
         {
1028
-            if(empty($columnText)) return;
1039
+            if(empty($columnText)) {
1040
+                return;
1041
+            }
1029 1042
             $pdf->SetXY($this->getColumnContentXStart($colKey),$curY); // Set curent position
1030 1043
             $colDef = $this->cols[$colKey];
1031 1044
             $pdf->writeHTMLCell( $this->getColumnContentWidth($colKey),2,$this->getColumnContentXStart($colKey),$curY, $columnText,0,0,0,true,$colDef['content']['align']);
@@ -1043,7 +1056,8 @@  discard block
 block discarded – undo
1043 1056
     {
1044 1057
         if( !empty($this->cols[$colKey]['status'])){
1045 1058
             return true;
1059
+        } else {
1060
+            return  false;
1046 1061
         }
1047
-        else  return  false;
1048 1062
     }
1049 1063
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/canvas.class.php 3 patches
Indentation   +118 added lines, -118 removed lines patch added patch discarded remove patch
@@ -28,22 +28,22 @@  discard block
 block discarded – undo
28 28
  */
29 29
 class Canvas
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
-	 * @var string[] Error codes (or messages)
43
-	 */
44
-	public $errors = array();
41
+    /**
42
+     * @var string[] Error codes (or messages)
43
+     */
44
+    public $errors = array();
45 45
 
46
-	public $actiontype;
46
+    public $actiontype;
47 47
 
48 48
     public $dirmodule;			// Module directory
49 49
     public $targetmodule;      // Module concerned by canvas (ex: thirdparty, contact, ...)
@@ -54,65 +54,65 @@  discard block
 block discarded – undo
54 54
     public $control;           	// Initialized by getCanvas with controller instance
55 55
 
56 56
 
57
-   /**
58
-	*   Constructor
59
-	*
60
-	*   @param     DoliDB	$db          	Database handler
61
-	*   @param     string   $actiontype		Action type ('create', 'view', 'edit', 'list')
62
-	*/
63
-	function __construct($db, $actiontype='view')
64
-	{
65
-		$this->db = $db;
66
-
67
-		$this->actiontype = $this->_cleanaction($actiontype);
68
-	}
69
-
70
-	/**
71
-	 * Return action code cleaned
72
-	 *
73
-	 * @param	string	$action		Action type ('create', 'view', 'edit', 'list', 'add', 'update')
74
-	 * @return 	string				Cleaned action type ('create', 'view', 'edit', 'list')
75
-	 */
76
-	private function _cleanaction($action)
77
-	{
78
-	    $newaction = $action;
79
-	    if ($newaction == 'add')    $newaction='create';
80
-	    if ($newaction == 'update') $newaction='edit';
81
-	    if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction='view';
82
-	    return $newaction;
83
-	}
84
-
85
-
86
-	/**
87
-	 * 	Initialize properties: ->targetmodule, ->canvas, ->card, ->dirmodule, ->template_dir
88
-	 *
89
-	 * 	@param	string	$module		Name of target module (thirdparty, contact, ...)
90
-	 * 	@param	string	$card	 	Tab name of card (ex: 'card', 'info', 'contactcard', ...) or '' for a list page
91
-	 * 	@param	string	$canvas		Name of canvas (ex: mycanvas, default, or mycanvas@myexternalmodule)
92
-	 * 	@return	void
93
-	 */
94
-	function getCanvas($module, $card, $canvas)
95
-	{
96
-		global $conf, $langs;
97
-
98
-		// Set properties with value specific to dolibarr core: this->targetmodule, this->card, this->canvas
57
+    /**
58
+     *   Constructor
59
+     *
60
+     *   @param     DoliDB	$db          	Database handler
61
+     *   @param     string   $actiontype		Action type ('create', 'view', 'edit', 'list')
62
+     */
63
+    function __construct($db, $actiontype='view')
64
+    {
65
+        $this->db = $db;
66
+
67
+        $this->actiontype = $this->_cleanaction($actiontype);
68
+    }
69
+
70
+    /**
71
+     * Return action code cleaned
72
+     *
73
+     * @param	string	$action		Action type ('create', 'view', 'edit', 'list', 'add', 'update')
74
+     * @return 	string				Cleaned action type ('create', 'view', 'edit', 'list')
75
+     */
76
+    private function _cleanaction($action)
77
+    {
78
+        $newaction = $action;
79
+        if ($newaction == 'add')    $newaction='create';
80
+        if ($newaction == 'update') $newaction='edit';
81
+        if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction='view';
82
+        return $newaction;
83
+    }
84
+
85
+
86
+    /**
87
+     * 	Initialize properties: ->targetmodule, ->canvas, ->card, ->dirmodule, ->template_dir
88
+     *
89
+     * 	@param	string	$module		Name of target module (thirdparty, contact, ...)
90
+     * 	@param	string	$card	 	Tab name of card (ex: 'card', 'info', 'contactcard', ...) or '' for a list page
91
+     * 	@param	string	$canvas		Name of canvas (ex: mycanvas, default, or mycanvas@myexternalmodule)
92
+     * 	@return	void
93
+     */
94
+    function getCanvas($module, $card, $canvas)
95
+    {
96
+        global $conf, $langs;
97
+
98
+        // Set properties with value specific to dolibarr core: this->targetmodule, this->card, this->canvas
99 99
         $this->targetmodule = $module;
100 100
         $this->canvas = $canvas;
101 101
         $this->card = $card;
102 102
         $this->dirmodule = $module;
103 103
         // Correct values if canvas is into an external module
104
-		if (preg_match('/^([^@]+)@([^@]+)$/i',$canvas,$regs))
105
-		{
104
+        if (preg_match('/^([^@]+)@([^@]+)$/i',$canvas,$regs))
105
+        {
106 106
             $this->canvas = $regs[1];
107
-		    $this->dirmodule = $regs[2];
108
-		}
109
-		// For compatibility
107
+            $this->dirmodule = $regs[2];
108
+        }
109
+        // For compatibility
110 110
         if ($this->dirmodule == 'thirdparty') { $this->dirmodule = 'societe'; }
111 111
 
112 112
         // Control file
113
-		$controlclassfile = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/actions_'.$this->card.'_'.$this->canvas.'.class.php');
114
-		if (file_exists($controlclassfile))
115
-		{
113
+        $controlclassfile = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/actions_'.$this->card.'_'.$this->canvas.'.class.php');
114
+        if (file_exists($controlclassfile))
115
+        {
116 116
             // Include actions class (controller)
117 117
             $this->control_file=$controlclassfile;
118 118
             require_once $controlclassfile;
@@ -120,10 +120,10 @@  discard block
 block discarded – undo
120 120
             // Instantiate actions class (controller)
121 121
             $controlclassname = 'Actions'.ucfirst($this->card).ucfirst($this->canvas);
122 122
             $this->control = new $controlclassname($this->db, $this->dirmodule, $this->targetmodule, $this->canvas, $this->card);
123
-		}
123
+        }
124 124
 
125
-		// Template dir
126
-		$this->template_dir = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/');
125
+        // Template dir
126
+        $this->template_dir = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/');
127 127
         if (! is_dir($this->template_dir))
128 128
         {
129 129
             $this->template_dir='';
@@ -131,27 +131,27 @@  discard block
 block discarded – undo
131 131
 
132 132
         //print 'dimodule='.$dirmodule.' canvas='.$this->canvas.'<br>';
133 133
         //print ' => template_dir='.$this->template_dir.'<br>';
134
-	}
134
+    }
135 135
 
136 136
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
137 137
     /**
138
-	 * 	Shared method for canvas to assign values for templates
139
-	 *
140
-	 * 	@param		string		$action	Action string
141
-	 * 	@param		int			$id			Object id (if ref not provided)
142
-	 * 	@param		string		$ref		Object ref (if id not provided)
143
-	 * 	@return		void
144
-	 */
145
-	function assign_values(&$action='view', $id=0, $ref='')
146
-	{
138
+     * 	Shared method for canvas to assign values for templates
139
+     *
140
+     * 	@param		string		$action	Action string
141
+     * 	@param		int			$id			Object id (if ref not provided)
142
+     * 	@param		string		$ref		Object ref (if id not provided)
143
+     * 	@return		void
144
+     */
145
+    function assign_values(&$action='view', $id=0, $ref='')
146
+    {
147 147
         // phpcs:enable
148
-		if (method_exists($this->control,'assign_values')) $this->control->assign_values($action, $id, $ref);
149
-	}
148
+        if (method_exists($this->control,'assign_values')) $this->control->assign_values($action, $id, $ref);
149
+    }
150 150
 
151 151
     /**
152 152
      *	Return the template to display canvas (if it exists)
153
-	 *
154
-	 *	@param	string	$action		Action code
153
+     *
154
+     *	@param	string	$action		Action code
155 155
      *	@return	int		0=Canvas template file does not exist, 1=Canvas template file exists
156 156
      */
157 157
     function displayCanvasExists($action)
@@ -163,53 +163,53 @@  discard block
 block discarded – undo
163 163
     }
164 164
 
165 165
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
166
-	/**
167
-	 *	Display a canvas page. This will include the template for output.
168
-	 *	Variables used by templates may have been defined or loaded before into the assign_values function.
169
-	 *
170
-	 *	@param	string	$action		Action code
171
-	 *	@return	void
172
-	 */
173
-	function display_canvas($action)
174
-	{
166
+    /**
167
+     *	Display a canvas page. This will include the template for output.
168
+     *	Variables used by templates may have been defined or loaded before into the assign_values function.
169
+     *
170
+     *	@param	string	$action		Action code
171
+     *	@return	void
172
+     */
173
+    function display_canvas($action)
174
+    {
175 175
         // phpcs:enable
176
-		global $db, $conf, $langs, $user, $canvas;
177
-		global $form, $formfile;
176
+        global $db, $conf, $langs, $user, $canvas;
177
+        global $form, $formfile;
178 178
 
179
-		include $this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php';        // Include native PHP template
180
-	}
179
+        include $this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php';        // Include native PHP template
180
+    }
181 181
 
182 182
 
183
-	// This functions should not be used anymore because canvas should contains only templates.
184
-	// http://wiki.dolibarr.org/index.php/Canvas_development
183
+    // This functions should not be used anymore because canvas should contains only templates.
184
+    // http://wiki.dolibarr.org/index.php/Canvas_development
185 185
 
186
-	/**
187
-	 * 	Return if a canvas contains an action controller
188
-	 *
189
-	 * 	@return		boolean		Return if canvas contains actions (old feature. now actions should be inside hooks)
190
-	 */
191
-	function hasActions()
192
-	{
186
+    /**
187
+     * 	Return if a canvas contains an action controller
188
+     *
189
+     * 	@return		boolean		Return if canvas contains actions (old feature. now actions should be inside hooks)
190
+     */
191
+    function hasActions()
192
+    {
193 193
         return (is_object($this->control));
194
-	}
194
+    }
195 195
 
196
-	/**
197
-	 * 	Shared method for canvas to execute actions.
196
+    /**
197
+     * 	Shared method for canvas to execute actions.
198 198
      *  @deprecated Use the doActions of hooks instead of this.
199
-	 * 	            This function is called if you add a doActions class inside your canvas. Try to not
200
-	 * 				do that and add action code into a hook instead.
201
-	 *
202
-	 * 	@param		string		$action	Action string
203
-	 * 	@param		int			$id			Object id
204
-	 * 	@return		mixed					Return return code of doActions of canvas
205
-	 * 	@see		http://wiki.dolibarr.org/index.php/Canvas_development
206
-	 */
207
-	function doActions(&$action='view', $id=0)
208
-	{
209
-		if (method_exists($this->control,'doActions'))
210
-		{
211
-			$ret = $this->control->doActions($action, $id);
212
-			return $ret;
213
-		}
214
-	}
199
+     * 	            This function is called if you add a doActions class inside your canvas. Try to not
200
+     * 				do that and add action code into a hook instead.
201
+     *
202
+     * 	@param		string		$action	Action string
203
+     * 	@param		int			$id			Object id
204
+     * 	@return		mixed					Return return code of doActions of canvas
205
+     * 	@see		http://wiki.dolibarr.org/index.php/Canvas_development
206
+     */
207
+    function doActions(&$action='view', $id=0)
208
+    {
209
+        if (method_exists($this->control,'doActions'))
210
+        {
211
+            $ret = $this->control->doActions($action, $id);
212
+            return $ret;
213
+        }
214
+    }
215 215
 }
Please login to merge, or discard this patch.
Spacing   +21 added lines, -21 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
 	 * @var string[] Error codes (or messages)
@@ -45,13 +45,13 @@  discard block
 block discarded – undo
45 45
 
46 46
 	public $actiontype;
47 47
 
48
-    public $dirmodule;			// Module directory
49
-    public $targetmodule;      // Module concerned by canvas (ex: thirdparty, contact, ...)
50
-    public $canvas;            // Name of canvas (ex: company, individual, product, service, ...)
51
-    public $card;              // Tab (sub-canvas)
48
+    public $dirmodule; // Module directory
49
+    public $targetmodule; // Module concerned by canvas (ex: thirdparty, contact, ...)
50
+    public $canvas; // Name of canvas (ex: company, individual, product, service, ...)
51
+    public $card; // Tab (sub-canvas)
52 52
 
53
-    public $template_dir;		// Initialized by getCanvas with templates directory
54
-    public $control;           	// Initialized by getCanvas with controller instance
53
+    public $template_dir; // Initialized by getCanvas with templates directory
54
+    public $control; // Initialized by getCanvas with controller instance
55 55
 
56 56
 
57 57
    /**
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	*   @param     DoliDB	$db          	Database handler
61 61
 	*   @param     string   $actiontype		Action type ('create', 'view', 'edit', 'list')
62 62
 	*/
63
-	function __construct($db, $actiontype='view')
63
+	function __construct($db, $actiontype = 'view')
64 64
 	{
65 65
 		$this->db = $db;
66 66
 
@@ -76,9 +76,9 @@  discard block
 block discarded – undo
76 76
 	private function _cleanaction($action)
77 77
 	{
78 78
 	    $newaction = $action;
79
-	    if ($newaction == 'add')    $newaction='create';
80
-	    if ($newaction == 'update') $newaction='edit';
81
-	    if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction='view';
79
+	    if ($newaction == 'add')    $newaction = 'create';
80
+	    if ($newaction == 'update') $newaction = 'edit';
81
+	    if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction = 'view';
82 82
 	    return $newaction;
83 83
 	}
84 84
 
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
         $this->card = $card;
102 102
         $this->dirmodule = $module;
103 103
         // Correct values if canvas is into an external module
104
-		if (preg_match('/^([^@]+)@([^@]+)$/i',$canvas,$regs))
104
+		if (preg_match('/^([^@]+)@([^@]+)$/i', $canvas, $regs))
105 105
 		{
106 106
             $this->canvas = $regs[1];
107 107
 		    $this->dirmodule = $regs[2];
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 		if (file_exists($controlclassfile))
115 115
 		{
116 116
             // Include actions class (controller)
117
-            $this->control_file=$controlclassfile;
117
+            $this->control_file = $controlclassfile;
118 118
             require_once $controlclassfile;
119 119
 
120 120
             // Instantiate actions class (controller)
@@ -124,9 +124,9 @@  discard block
 block discarded – undo
124 124
 
125 125
 		// Template dir
126 126
 		$this->template_dir = dol_buildpath('/'.$this->dirmodule.'/canvas/'.$this->canvas.'/tpl/');
127
-        if (! is_dir($this->template_dir))
127
+        if (!is_dir($this->template_dir))
128 128
         {
129
-            $this->template_dir='';
129
+            $this->template_dir = '';
130 130
         }
131 131
 
132 132
         //print 'dimodule='.$dirmodule.' canvas='.$this->canvas.'<br>';
@@ -142,10 +142,10 @@  discard block
 block discarded – undo
142 142
 	 * 	@param		string		$ref		Object ref (if id not provided)
143 143
 	 * 	@return		void
144 144
 	 */
145
-	function assign_values(&$action='view', $id=0, $ref='')
145
+	function assign_values(&$action = 'view', $id = 0, $ref = '')
146 146
 	{
147 147
         // phpcs:enable
148
-		if (method_exists($this->control,'assign_values')) $this->control->assign_values($action, $id, $ref);
148
+		if (method_exists($this->control, 'assign_values')) $this->control->assign_values($action, $id, $ref);
149 149
 	}
150 150
 
151 151
     /**
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
     {
159 159
         if (empty($this->template_dir)) return 0;
160 160
 
161
-        if (file_exists($this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php')) return 1;
161
+        if (file_exists($this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php')) return 1;
162 162
         else return 0;
163 163
     }
164 164
 
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		global $db, $conf, $langs, $user, $canvas;
177 177
 		global $form, $formfile;
178 178
 
179
-		include $this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php';        // Include native PHP template
179
+		include $this->template_dir.(!empty($this->card) ? $this->card.'_' : '').$this->_cleanaction($action).'.tpl.php'; // Include native PHP template
180 180
 	}
181 181
 
182 182
 
@@ -204,9 +204,9 @@  discard block
 block discarded – undo
204 204
 	 * 	@return		mixed					Return return code of doActions of canvas
205 205
 	 * 	@see		http://wiki.dolibarr.org/index.php/Canvas_development
206 206
 	 */
207
-	function doActions(&$action='view', $id=0)
207
+	function doActions(&$action = 'view', $id = 0)
208 208
 	{
209
-		if (method_exists($this->control,'doActions'))
209
+		if (method_exists($this->control, 'doActions'))
210 210
 		{
211 211
 			$ret = $this->control->doActions($action, $id);
212 212
 			return $ret;
Please login to merge, or discard this patch.
Braces   +20 added lines, -7 removed lines patch added patch discarded remove patch
@@ -76,9 +76,15 @@  discard block
 block discarded – undo
76 76
 	private function _cleanaction($action)
77 77
 	{
78 78
 	    $newaction = $action;
79
-	    if ($newaction == 'add')    $newaction='create';
80
-	    if ($newaction == 'update') $newaction='edit';
81
-	    if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') $newaction='view';
79
+	    if ($newaction == 'add') {
80
+	        $newaction='create';
81
+	    }
82
+	    if ($newaction == 'update') {
83
+	        $newaction='edit';
84
+	    }
85
+	    if (empty($newaction) || $newaction == 'delete' || $newaction == 'create_user' || $newaction == 'presend' || $newaction == 'send') {
86
+	        $newaction='view';
87
+	    }
82 88
 	    return $newaction;
83 89
 	}
84 90
 
@@ -145,7 +151,9 @@  discard block
 block discarded – undo
145 151
 	function assign_values(&$action='view', $id=0, $ref='')
146 152
 	{
147 153
         // phpcs:enable
148
-		if (method_exists($this->control,'assign_values')) $this->control->assign_values($action, $id, $ref);
154
+		if (method_exists($this->control,'assign_values')) {
155
+		    $this->control->assign_values($action, $id, $ref);
156
+		}
149 157
 	}
150 158
 
151 159
     /**
@@ -156,10 +164,15 @@  discard block
 block discarded – undo
156 164
      */
157 165
     function displayCanvasExists($action)
158 166
     {
159
-        if (empty($this->template_dir)) return 0;
167
+        if (empty($this->template_dir)) {
168
+            return 0;
169
+        }
160 170
 
161
-        if (file_exists($this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php')) return 1;
162
-        else return 0;
171
+        if (file_exists($this->template_dir.(!empty($this->card)?$this->card.'_':'').$this->_cleanaction($action).'.tpl.php')) {
172
+            return 1;
173
+        } else {
174
+            return 0;
175
+        }
163 176
     }
164 177
 
165 178
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
Please login to merge, or discard this patch.