Passed
Push — master ( 49af33...3cffbe )
by Alxarafe
21:21
created
dolibarr/htdocs/core/class/dolgraph.class.php 3 patches
Indentation   +945 added lines, -945 removed lines patch added patch discarded remove patch
@@ -39,941 +39,941 @@  discard block
 block discarded – undo
39 39
  */
40 40
 class DolGraph
41 41
 {
42
-	public $type=array();			// Array with type of each series. Example: array('bars', 'lines', ...)
43
-	public $mode='side';		    // Mode bars graph: side, depth
44
-	private $_library='jflot';	// Graphic library to use (jflot, artichow)
45
-
46
-	//! Array of data
47
-	public $data;				// Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
48
-	public $title;				// Title of graph
49
-	public $cssprefix='';		// To add into css styles
50
-	public $width=380;
51
-	public $height=200;
52
-	public $MaxValue=0;
53
-	public $MinValue=0;
54
-	public $SetShading=0;
55
-
56
-	public $PrecisionY=-1;
57
-
58
-	public $horizTickIncrement=-1;
59
-	public $SetNumXTicks=-1;
60
-	public $labelInterval=-1;
61
-
62
-	public $hideXGrid=false;
63
-	public $hideYGrid=false;
64
-
65
-	public $Legend=array();
66
-	public $LegendWidthMin=0;
67
-	public $showlegend=1;
68
-	public $showpointvalue=1;
69
-	public $showpercent=0;
70
-	public $combine=0;				// 0.05 if you want to combine records < 5% into "other"
71
-	public $graph;     			// Objet Graph (Artichow, Phplot...)
72
-
73
-	/**
74
-	 * @var string Error code (or message)
75
-	 */
76
-	public $error='';
77
-
78
-	public $bordercolor;			// array(R,G,B)
79
-	public $bgcolor;				// array(R,G,B)
80
-	public $bgcolorgrid=array(255,255,255);			// array(R,G,B)
81
-	public $datacolor;				// array(array(R,G,B),...)
82
-
83
-	private $stringtoshow;      // To store string to output graph into HTML page
84
-
85
-
86
-	/**
87
-	 * Constructor
88
-	 *
89
-	 * @param	string	$library		'jflot' (default) or 'artichow' (no more supported)
90
-	 */
91
-	function __construct($library='jflot')
92
-	{
93
-		global $conf;
94
-		global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet;
95
-
96
-		// To use old feature
97
-		if ($library == 'artichow')
98
-		{
99
-			$this->_library='artichow';
100
-
101
-			// Test if module GD present
102
-			$modules_list = get_loaded_extensions();
103
-			$isgdinstalled=0;
104
-			foreach ($modules_list as $module)
105
-			{
106
-				if ($module == 'gd') $isgdinstalled=1;
107
-			}
108
-			if (! $isgdinstalled)
109
-			{
110
-				$this->error="Error: PHP GD module is not available. It is required to build graphics.";
111
-				return -1;
112
-			}
113
-		}
114
-
115
-		$this->bordercolor = array(235,235,224);
116
-		$this->datacolor = array(array(120,130,150), array(160,160,180), array(190,190,220));
117
-		$this->bgcolor = array(235,235,224);
118
-
119
-		$color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/graph-color.php';
120
-		if (is_readable($color_file))
121
-		{
122
-			include_once $color_file;
123
-			if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor;
124
-			if (isset($theme_datacolor))   $this->datacolor   = $theme_datacolor;
125
-			if (isset($theme_bgcolor))     $this->bgcolor     = $theme_bgcolor;
126
-		}
127
-		//print 'bgcolor: '.join(',',$this->bgcolor).'<br>';
128
-	}
42
+    public $type=array();			// Array with type of each series. Example: array('bars', 'lines', ...)
43
+    public $mode='side';		    // Mode bars graph: side, depth
44
+    private $_library='jflot';	// Graphic library to use (jflot, artichow)
45
+
46
+    //! Array of data
47
+    public $data;				// Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
48
+    public $title;				// Title of graph
49
+    public $cssprefix='';		// To add into css styles
50
+    public $width=380;
51
+    public $height=200;
52
+    public $MaxValue=0;
53
+    public $MinValue=0;
54
+    public $SetShading=0;
55
+
56
+    public $PrecisionY=-1;
57
+
58
+    public $horizTickIncrement=-1;
59
+    public $SetNumXTicks=-1;
60
+    public $labelInterval=-1;
61
+
62
+    public $hideXGrid=false;
63
+    public $hideYGrid=false;
64
+
65
+    public $Legend=array();
66
+    public $LegendWidthMin=0;
67
+    public $showlegend=1;
68
+    public $showpointvalue=1;
69
+    public $showpercent=0;
70
+    public $combine=0;				// 0.05 if you want to combine records < 5% into "other"
71
+    public $graph;     			// Objet Graph (Artichow, Phplot...)
72
+
73
+    /**
74
+     * @var string Error code (or message)
75
+     */
76
+    public $error='';
77
+
78
+    public $bordercolor;			// array(R,G,B)
79
+    public $bgcolor;				// array(R,G,B)
80
+    public $bgcolorgrid=array(255,255,255);			// array(R,G,B)
81
+    public $datacolor;				// array(array(R,G,B),...)
82
+
83
+    private $stringtoshow;      // To store string to output graph into HTML page
84
+
85
+
86
+    /**
87
+     * Constructor
88
+     *
89
+     * @param	string	$library		'jflot' (default) or 'artichow' (no more supported)
90
+     */
91
+    function __construct($library='jflot')
92
+    {
93
+        global $conf;
94
+        global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet;
95
+
96
+        // To use old feature
97
+        if ($library == 'artichow')
98
+        {
99
+            $this->_library='artichow';
100
+
101
+            // Test if module GD present
102
+            $modules_list = get_loaded_extensions();
103
+            $isgdinstalled=0;
104
+            foreach ($modules_list as $module)
105
+            {
106
+                if ($module == 'gd') $isgdinstalled=1;
107
+            }
108
+            if (! $isgdinstalled)
109
+            {
110
+                $this->error="Error: PHP GD module is not available. It is required to build graphics.";
111
+                return -1;
112
+            }
113
+        }
114
+
115
+        $this->bordercolor = array(235,235,224);
116
+        $this->datacolor = array(array(120,130,150), array(160,160,180), array(190,190,220));
117
+        $this->bgcolor = array(235,235,224);
118
+
119
+        $color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/graph-color.php';
120
+        if (is_readable($color_file))
121
+        {
122
+            include_once $color_file;
123
+            if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor;
124
+            if (isset($theme_datacolor))   $this->datacolor   = $theme_datacolor;
125
+            if (isset($theme_bgcolor))     $this->bgcolor     = $theme_bgcolor;
126
+        }
127
+        //print 'bgcolor: '.join(',',$this->bgcolor).'<br>';
128
+    }
129 129
 
130 130
 
131 131
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
132
-	/**
133
-	 * Set Y precision
134
-	 *
135
-	 * @param 	float	$which_prec		Precision
136
-	 * @return 	boolean
137
-	 */
138
-	function SetPrecisionY($which_prec)
139
-	{
132
+    /**
133
+     * Set Y precision
134
+     *
135
+     * @param 	float	$which_prec		Precision
136
+     * @return 	boolean
137
+     */
138
+    function SetPrecisionY($which_prec)
139
+    {
140 140
         // phpcs:enable
141
-		$this->PrecisionY = $which_prec;
142
-		return true;
143
-	}
141
+        $this->PrecisionY = $which_prec;
142
+        return true;
143
+    }
144 144
 
145 145
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
146
-	/**
147
-	 * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2
148
-	 *
149
-	 * @param 	float 		$xi		Xi
150
-	 * @return	boolean				True
151
-	 */
152
-	function SetHorizTickIncrement($xi)
153
-	{
146
+    /**
147
+     * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2
148
+     *
149
+     * @param 	float 		$xi		Xi
150
+     * @return	boolean				True
151
+     */
152
+    function SetHorizTickIncrement($xi)
153
+    {
154 154
         // phpcs:enable
155
-		$this->horizTickIncrement = $xi;
156
-		return true;
157
-	}
155
+        $this->horizTickIncrement = $xi;
156
+        return true;
157
+    }
158 158
 
159 159
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
160
-	/**
161
-	 * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2
162
-	 *
163
-	 * @param 	float 		$xt		Xt
164
-	 * @return	boolean				True
165
-	 */
166
-	function SetNumXTicks($xt)
167
-	{
160
+    /**
161
+     * Utiliser SetNumTicks ou SetHorizTickIncrement mais pas les 2
162
+     *
163
+     * @param 	float 		$xt		Xt
164
+     * @return	boolean				True
165
+     */
166
+    function SetNumXTicks($xt)
167
+    {
168 168
         // phpcs:enable
169
-		$this->SetNumXTicks = $xt;
170
-		return true;
171
-	}
169
+        $this->SetNumXTicks = $xt;
170
+        return true;
171
+    }
172 172
 
173 173
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
174
-	/**
175
-	 * Set label interval to reduce number of labels
176
-	 *
177
-	 * @param 	float 		$x		Label interval
178
-	 * @return	boolean				True
179
-	 */
180
-	function SetLabelInterval($x)
181
-	{
174
+    /**
175
+     * Set label interval to reduce number of labels
176
+     *
177
+     * @param 	float 		$x		Label interval
178
+     * @return	boolean				True
179
+     */
180
+    function SetLabelInterval($x)
181
+    {
182 182
         // phpcs:enable
183
-		$this->labelInterval = $x;
184
-		return true;
185
-	}
183
+        $this->labelInterval = $x;
184
+        return true;
185
+    }
186 186
 
187 187
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
188
-	/**
189
-	 * Hide X grid
190
-	 *
191
-	 * @param	boolean		$bool	XGrid or not
192
-	 * @return	boolean				true
193
-	 */
194
-	function SetHideXGrid($bool)
195
-	{
188
+    /**
189
+     * Hide X grid
190
+     *
191
+     * @param	boolean		$bool	XGrid or not
192
+     * @return	boolean				true
193
+     */
194
+    function SetHideXGrid($bool)
195
+    {
196 196
         // phpcs:enable
197
-		$this->hideXGrid = $bool;
198
-		return true;
199
-	}
197
+        $this->hideXGrid = $bool;
198
+        return true;
199
+    }
200 200
 
201 201
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
202
-	/**
203
-	 * Hide Y grid
204
-	 *
205
-	 * @param	boolean		$bool	YGrid or not
206
-	 * @return	boolean				true
207
-	 */
208
-	function SetHideYGrid($bool)
209
-	{
202
+    /**
203
+     * Hide Y grid
204
+     *
205
+     * @param	boolean		$bool	YGrid or not
206
+     * @return	boolean				true
207
+     */
208
+    function SetHideYGrid($bool)
209
+    {
210 210
         // phpcs:enable
211
-		$this->hideYGrid = $bool;
212
-		return true;
213
-	}
211
+        $this->hideYGrid = $bool;
212
+        return true;
213
+    }
214 214
 
215 215
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
216
-	/**
217
-	 * Set y label
218
-	 *
219
-	 * @param 	string	$label		Y label
220
-	 * @return	boolean|null				True
221
-	 */
222
-	function SetYLabel($label)
223
-	{
216
+    /**
217
+     * Set y label
218
+     *
219
+     * @param 	string	$label		Y label
220
+     * @return	boolean|null				True
221
+     */
222
+    function SetYLabel($label)
223
+    {
224 224
         // phpcs:enable
225
-		$this->YLabel = $label;
226
-	}
225
+        $this->YLabel = $label;
226
+    }
227 227
 
228 228
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
229
-	/**
230
-	 * Set width
231
-	 *
232
-	 * @param 	int		$w			Width
233
-	 * @return	boolean|null				True
234
-	 */
235
-	function SetWidth($w)
236
-	{
229
+    /**
230
+     * Set width
231
+     *
232
+     * @param 	int		$w			Width
233
+     * @return	boolean|null				True
234
+     */
235
+    function SetWidth($w)
236
+    {
237 237
         // phpcs:enable
238
-		$this->width = $w;
239
-	}
238
+        $this->width = $w;
239
+    }
240 240
 
241 241
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
242
-	/**
243
-	 * Set title
244
-	 *
245
-	 * @param 	string	$title		Title
246
-	 * @return	void
247
-	 */
248
-	function SetTitle($title)
249
-	{
242
+    /**
243
+     * Set title
244
+     *
245
+     * @param 	string	$title		Title
246
+     * @return	void
247
+     */
248
+    function SetTitle($title)
249
+    {
250 250
         // phpcs:enable
251
-		$this->title = $title;
252
-	}
251
+        $this->title = $title;
252
+    }
253 253
 
254 254
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
255
-	/**
256
-	 * Set data
257
-	 *
258
-	 * @param 	array	$data		Data
259
-	 * @return	void
260
-	 * @see draw_jflot for syntax of data array
261
-	 */
262
-	function SetData($data)
263
-	{
255
+    /**
256
+     * Set data
257
+     *
258
+     * @param 	array	$data		Data
259
+     * @return	void
260
+     * @see draw_jflot for syntax of data array
261
+     */
262
+    function SetData($data)
263
+    {
264 264
         // phpcs:enable
265
-		$this->data = $data;
266
-	}
265
+        $this->data = $data;
266
+    }
267 267
 
268 268
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
269
-	/**
270
-	 * Set data
271
-	 *
272
-	 * @param 	array	$datacolor		Data color array(array(R,G,B),array(R,G,B)...)
273
-	 * @return	void
274
-	 */
275
-	function SetDataColor($datacolor)
276
-	{
269
+    /**
270
+     * Set data
271
+     *
272
+     * @param 	array	$datacolor		Data color array(array(R,G,B),array(R,G,B)...)
273
+     * @return	void
274
+     */
275
+    function SetDataColor($datacolor)
276
+    {
277 277
         // phpcs:enable
278
-		$this->datacolor = $datacolor;
279
-	}
278
+        $this->datacolor = $datacolor;
279
+    }
280 280
 
281 281
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
282
-	/**
283
-	 * Set type
284
-	 *
285
-	 * @param 	array	$type		Array with type for each serie. Example: array('pie'), array('lines',...,'bars')
286
-	 * @return	void
287
-	 */
288
-	function SetType($type)
289
-	{
282
+    /**
283
+     * Set type
284
+     *
285
+     * @param 	array	$type		Array with type for each serie. Example: array('pie'), array('lines',...,'bars')
286
+     * @return	void
287
+     */
288
+    function SetType($type)
289
+    {
290 290
         // phpcs:enable
291
-		$this->type = $type;
292
-	}
291
+        $this->type = $type;
292
+    }
293 293
 
294 294
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
295
-	/**
296
-	 * Set legend
297
-	 *
298
-	 * @param 	array	$legend		Legend. Example: array('seriename1','seriname2',...)
299
-	 * @return	void
300
-	 */
301
-	function SetLegend($legend)
302
-	{
295
+    /**
296
+     * Set legend
297
+     *
298
+     * @param 	array	$legend		Legend. Example: array('seriename1','seriname2',...)
299
+     * @return	void
300
+     */
301
+    function SetLegend($legend)
302
+    {
303 303
         // phpcs:enable
304
-		$this->Legend = $legend;
305
-	}
304
+        $this->Legend = $legend;
305
+    }
306 306
 
307 307
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
308
-	/**
309
-	 * Set min width
310
-	 *
311
-	 * @param 	int		$legendwidthmin		Min width
312
-	 * @return	void
313
-	 */
314
-	function SetLegendWidthMin($legendwidthmin)
315
-	{
308
+    /**
309
+     * Set min width
310
+     *
311
+     * @param 	int		$legendwidthmin		Min width
312
+     * @return	void
313
+     */
314
+    function SetLegendWidthMin($legendwidthmin)
315
+    {
316 316
         // phpcs:enable
317
-		$this->LegendWidthMin = $legendwidthmin;
318
-	}
317
+        $this->LegendWidthMin = $legendwidthmin;
318
+    }
319 319
 
320 320
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
321
-	/**
322
-	 * Set max value
323
-	 *
324
-	 * @param 	int		$max			Max value
325
-	 * @return	void
326
-	 */
327
-	function SetMaxValue($max)
328
-	{
321
+    /**
322
+     * Set max value
323
+     *
324
+     * @param 	int		$max			Max value
325
+     * @return	void
326
+     */
327
+    function SetMaxValue($max)
328
+    {
329 329
         // phpcs:enable
330
-		$this->MaxValue = $max;
331
-	}
330
+        $this->MaxValue = $max;
331
+    }
332 332
 
333 333
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
334
-	/**
335
-	 * Get max value
336
-	 *
337
-	 * @return	int		Max value
338
-	 */
339
-	function GetMaxValue()
340
-	{
334
+    /**
335
+     * Get max value
336
+     *
337
+     * @return	int		Max value
338
+     */
339
+    function GetMaxValue()
340
+    {
341 341
         // phpcs:enable
342
-		return $this->MaxValue;
343
-	}
342
+        return $this->MaxValue;
343
+    }
344 344
 
345 345
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
346
-	/**
347
-	 * Set min value
348
-	 *
349
-	 * @param 	int		$min			Min value
350
-	 * @return	void
351
-	 */
352
-	function SetMinValue($min)
353
-	{
346
+    /**
347
+     * Set min value
348
+     *
349
+     * @param 	int		$min			Min value
350
+     * @return	void
351
+     */
352
+    function SetMinValue($min)
353
+    {
354 354
         // phpcs:enable
355
-		$this->MinValue = $min;
356
-	}
355
+        $this->MinValue = $min;
356
+    }
357 357
 
358 358
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
359
-	/**
360
-	 * Get min value
361
-	 *
362
-	 * @return	int		Max value
363
-	 */
364
-	function GetMinValue()
365
-	{
359
+    /**
360
+     * Get min value
361
+     *
362
+     * @return	int		Max value
363
+     */
364
+    function GetMinValue()
365
+    {
366 366
         // phpcs:enable
367
-		return $this->MinValue;
368
-	}
367
+        return $this->MinValue;
368
+    }
369 369
 
370 370
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
371
-	/**
372
-	 * Set height
373
-	 *
374
-	 * @param 	int		$h				Height
375
-	 * @return	void
376
-	 */
377
-	function SetHeight($h)
378
-	{
371
+    /**
372
+     * Set height
373
+     *
374
+     * @param 	int		$h				Height
375
+     * @return	void
376
+     */
377
+    function SetHeight($h)
378
+    {
379 379
         // phpcs:enable
380
-		$this->height = $h;
381
-	}
380
+        $this->height = $h;
381
+    }
382 382
 
383 383
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
384
-	/**
385
-	 * Set shading
386
-	 *
387
-	 * @param 	string	$s				Shading
388
-	 * @return	void
389
-	 */
390
-	function SetShading($s)
391
-	{
384
+    /**
385
+     * Set shading
386
+     *
387
+     * @param 	string	$s				Shading
388
+     * @return	void
389
+     */
390
+    function SetShading($s)
391
+    {
392 392
         // phpcs:enable
393
-		$this->SetShading = $s;
394
-	}
393
+        $this->SetShading = $s;
394
+    }
395 395
 
396 396
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
397
-	/**
398
-	 * Set shading
399
-	 *
400
-	 * @param 	string	$s				Shading
401
-	 * @return	void
402
-	 */
403
-	function SetCssPrefix($s)
404
-	{
397
+    /**
398
+     * Set shading
399
+     *
400
+     * @param 	string	$s				Shading
401
+     * @return	void
402
+     */
403
+    function SetCssPrefix($s)
404
+    {
405 405
         // phpcs:enable
406
-		$this->cssprefix = $s;
407
-	}
406
+        $this->cssprefix = $s;
407
+    }
408 408
 
409 409
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
410
-	/**
411
-	 * Reset bg color
412
-	 *
413
-	 * @return	void
414
-	 */
415
-	function ResetBgColor()
416
-	{
410
+    /**
411
+     * Reset bg color
412
+     *
413
+     * @return	void
414
+     */
415
+    function ResetBgColor()
416
+    {
417 417
         // phpcs:enable
418
-		unset($this->bgcolor);
419
-	}
418
+        unset($this->bgcolor);
419
+    }
420 420
 
421 421
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
422
-	/**
423
-	 * Reset bgcolorgrid
424
-	 *
425
-	 * @return	void
426
-	 */
427
-	function ResetBgColorGrid()
428
-	{
422
+    /**
423
+     * Reset bgcolorgrid
424
+     *
425
+     * @return	void
426
+     */
427
+    function ResetBgColorGrid()
428
+    {
429 429
         // phpcs:enable
430
-		unset($this->bgcolorgrid);
431
-	}
432
-
433
-	/**
434
-	 * Is graph ko
435
-	 *
436
-	 * @return	string		Error
437
-	 */
438
-	function isGraphKo()
439
-	{
440
-		return $this->error;
441
-	}
442
-
443
-	/**
444
-	 * Show legend or not
445
-	 *
446
-	 * @param	int		$showlegend		1=Show legend (default), 0=Hide legend
447
-	 * @return	void
448
-	 */
449
-	function setShowLegend($showlegend)
450
-	{
451
-		$this->showlegend=$showlegend;
452
-	}
453
-
454
-	/**
455
-	 * Show pointvalue or not
456
-	 *
457
-	 * @param	int		$showpointvalue		1=Show value for each point, as tooltip or inline (default), 0=Hide value
458
-	 * @return	void
459
-	 */
460
-	function setShowPointValue($showpointvalue)
461
-	{
462
-		$this->showpointvalue=$showpointvalue;
463
-	}
464
-
465
-	/**
466
-	 * Show percent or not
467
-	 *
468
-	 * @param	int		$showpercent		1=Show percent for each point, as tooltip or inline, 0=Hide percent (default)
469
-	 * @return	void
470
-	 */
471
-	function setShowPercent($showpercent)
472
-	{
473
-		$this->showpercent=$showpercent;
474
-	}
430
+        unset($this->bgcolorgrid);
431
+    }
432
+
433
+    /**
434
+     * Is graph ko
435
+     *
436
+     * @return	string		Error
437
+     */
438
+    function isGraphKo()
439
+    {
440
+        return $this->error;
441
+    }
442
+
443
+    /**
444
+     * Show legend or not
445
+     *
446
+     * @param	int		$showlegend		1=Show legend (default), 0=Hide legend
447
+     * @return	void
448
+     */
449
+    function setShowLegend($showlegend)
450
+    {
451
+        $this->showlegend=$showlegend;
452
+    }
453
+
454
+    /**
455
+     * Show pointvalue or not
456
+     *
457
+     * @param	int		$showpointvalue		1=Show value for each point, as tooltip or inline (default), 0=Hide value
458
+     * @return	void
459
+     */
460
+    function setShowPointValue($showpointvalue)
461
+    {
462
+        $this->showpointvalue=$showpointvalue;
463
+    }
464
+
465
+    /**
466
+     * Show percent or not
467
+     *
468
+     * @param	int		$showpercent		1=Show percent for each point, as tooltip or inline, 0=Hide percent (default)
469
+     * @return	void
470
+     */
471
+    function setShowPercent($showpercent)
472
+    {
473
+        $this->showpercent=$showpercent;
474
+    }
475 475
 
476 476
 
477 477
 
478 478
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
479
-	/**
480
-	 * Define background color of complete image
481
-	 *
482
-	 * @param	array	$bg_color		array(R,G,B) ou 'onglet' ou 'default'
483
-	 * @return	void
484
-	 */
485
-	function SetBgColor($bg_color = array(255,255,255))
486
-	{
479
+    /**
480
+     * Define background color of complete image
481
+     *
482
+     * @param	array	$bg_color		array(R,G,B) ou 'onglet' ou 'default'
483
+     * @return	void
484
+     */
485
+    function SetBgColor($bg_color = array(255,255,255))
486
+    {
487 487
         // phpcs:enable
488
-		global $theme_bgcolor,$theme_bgcoloronglet;
489
-
490
-		if (! is_array($bg_color))
491
-		{
492
-			if ($bg_color == 'onglet')
493
-			{
494
-				//print 'ee'.join(',',$theme_bgcoloronglet);
495
-				$this->bgcolor = $theme_bgcoloronglet;
496
-			}
497
-			else
498
-			{
499
-				$this->bgcolor = $theme_bgcolor;
500
-			}
501
-		}
502
-		else
503
-		{
504
-			$this->bgcolor = $bg_color;
505
-		}
506
-	}
488
+        global $theme_bgcolor,$theme_bgcoloronglet;
489
+
490
+        if (! is_array($bg_color))
491
+        {
492
+            if ($bg_color == 'onglet')
493
+            {
494
+                //print 'ee'.join(',',$theme_bgcoloronglet);
495
+                $this->bgcolor = $theme_bgcoloronglet;
496
+            }
497
+            else
498
+            {
499
+                $this->bgcolor = $theme_bgcolor;
500
+            }
501
+        }
502
+        else
503
+        {
504
+            $this->bgcolor = $bg_color;
505
+        }
506
+    }
507 507
 
508 508
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
509
-	/**
510
-	 * Define background color of grid
511
-	 *
512
-	 * @param	array	$bg_colorgrid		array(R,G,B) ou 'onglet' ou 'default'
513
-	 * @return	void
514
-	 */
515
-	function SetBgColorGrid($bg_colorgrid = array(255,255,255))
516
-	{
509
+    /**
510
+     * Define background color of grid
511
+     *
512
+     * @param	array	$bg_colorgrid		array(R,G,B) ou 'onglet' ou 'default'
513
+     * @return	void
514
+     */
515
+    function SetBgColorGrid($bg_colorgrid = array(255,255,255))
516
+    {
517 517
         // phpcs:enable
518
-		global $theme_bgcolor,$theme_bgcoloronglet;
519
-
520
-		if (! is_array($bg_colorgrid))
521
-		{
522
-			if ($bg_colorgrid == 'onglet')
523
-			{
524
-				//print 'ee'.join(',',$theme_bgcoloronglet);
525
-				$this->bgcolorgrid = $theme_bgcoloronglet;
526
-			}
527
-			else
528
-			{
529
-				$this->bgcolorgrid = $theme_bgcolor;
530
-			}
531
-		}
532
-		else
533
-		{
534
-			$this->bgcolorgrid = $bg_colorgrid;
535
-		}
536
-	}
518
+        global $theme_bgcolor,$theme_bgcoloronglet;
519
+
520
+        if (! is_array($bg_colorgrid))
521
+        {
522
+            if ($bg_colorgrid == 'onglet')
523
+            {
524
+                //print 'ee'.join(',',$theme_bgcoloronglet);
525
+                $this->bgcolorgrid = $theme_bgcoloronglet;
526
+            }
527
+            else
528
+            {
529
+                $this->bgcolorgrid = $theme_bgcolor;
530
+            }
531
+        }
532
+        else
533
+        {
534
+            $this->bgcolorgrid = $bg_colorgrid;
535
+        }
536
+    }
537 537
 
538 538
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
539
-	/**
540
-	 * Reset data color
541
-	 *
542
-	 * @return	void
543
-	 */
544
-	function ResetDataColor()
545
-	{
539
+    /**
540
+     * Reset data color
541
+     *
542
+     * @return	void
543
+     */
544
+    function ResetDataColor()
545
+    {
546 546
         // phpcs:enable
547
-		unset($this->datacolor);
548
-	}
547
+        unset($this->datacolor);
548
+    }
549 549
 
550 550
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
551
-	/**
552
-	 * Get max value
553
-	 *
554
-	 * @return	int		Max value
555
-	 */
556
-	function GetMaxValueInData()
557
-	{
551
+    /**
552
+     * Get max value
553
+     *
554
+     * @return	int		Max value
555
+     */
556
+    function GetMaxValueInData()
557
+    {
558 558
         // phpcs:enable
559
-		$k = 0;
560
-		$vals = array();
561
-
562
-		$nblines = count($this->data);
563
-		$nbvalues = count($this->data[0]) - 1;
564
-
565
-		for ($j = 0 ; $j < $nblines ; $j++)
566
-		{
567
-			for ($i = 0 ; $i < $nbvalues ; $i++)
568
-			{
569
-				$vals[$k] = $this->data[$j][$i+1];
570
-				$k++;
571
-			}
572
-		}
573
-		rsort($vals);
574
-		return $vals[0];
575
-	}
559
+        $k = 0;
560
+        $vals = array();
561
+
562
+        $nblines = count($this->data);
563
+        $nbvalues = count($this->data[0]) - 1;
564
+
565
+        for ($j = 0 ; $j < $nblines ; $j++)
566
+        {
567
+            for ($i = 0 ; $i < $nbvalues ; $i++)
568
+            {
569
+                $vals[$k] = $this->data[$j][$i+1];
570
+                $k++;
571
+            }
572
+        }
573
+        rsort($vals);
574
+        return $vals[0];
575
+    }
576 576
 
577 577
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
578
-	/**
579
-	 * Return min value of all data
580
-	 *
581
-	 * @return	int		Min value of all data
582
-	 */
583
-	function GetMinValueInData()
584
-	{
578
+    /**
579
+     * Return min value of all data
580
+     *
581
+     * @return	int		Min value of all data
582
+     */
583
+    function GetMinValueInData()
584
+    {
585 585
         // phpcs:enable
586
-		$k = 0;
587
-		$vals = array();
588
-
589
-		$nblines = count($this->data);
590
-		$nbvalues = count($this->data[0]) - 1;
591
-
592
-		for ($j = 0 ; $j < $nblines ; $j++)
593
-		{
594
-			for ($i = 0 ; $i < $nbvalues ; $i++)
595
-			{
596
-				$vals[$k] = $this->data[$j][$i+1];
597
-				$k++;
598
-			}
599
-		}
600
-		sort($vals);
601
-		return $vals[0];
602
-	}
586
+        $k = 0;
587
+        $vals = array();
588
+
589
+        $nblines = count($this->data);
590
+        $nbvalues = count($this->data[0]) - 1;
591
+
592
+        for ($j = 0 ; $j < $nblines ; $j++)
593
+        {
594
+            for ($i = 0 ; $i < $nbvalues ; $i++)
595
+            {
596
+                $vals[$k] = $this->data[$j][$i+1];
597
+                $k++;
598
+            }
599
+        }
600
+        sort($vals);
601
+        return $vals[0];
602
+    }
603 603
 
604 604
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
605
-	/**
606
-	 * Return max value of all data
607
-	 *
608
-	 * @return 	int		Max value of all data
609
-	 */
610
-	function GetCeilMaxValue()
611
-	{
605
+    /**
606
+     * Return max value of all data
607
+     *
608
+     * @return 	int		Max value of all data
609
+     */
610
+    function GetCeilMaxValue()
611
+    {
612 612
         // phpcs:enable
613
-		$max = $this->GetMaxValueInData();
614
-		if ($max != 0) $max++;
615
-		$size=dol_strlen(abs(ceil($max)));
616
-		$factor=1;
617
-		for ($i=0; $i < ($size-1); $i++)
618
-		{
619
-			$factor*=10;
620
-		}
621
-
622
-		$res=0;
623
-		if (is_numeric($max)) $res=ceil($max/$factor)*$factor;
624
-
625
-		//print "max=".$max." res=".$res;
626
-		return $res;
627
-	}
613
+        $max = $this->GetMaxValueInData();
614
+        if ($max != 0) $max++;
615
+        $size=dol_strlen(abs(ceil($max)));
616
+        $factor=1;
617
+        for ($i=0; $i < ($size-1); $i++)
618
+        {
619
+            $factor*=10;
620
+        }
621
+
622
+        $res=0;
623
+        if (is_numeric($max)) $res=ceil($max/$factor)*$factor;
624
+
625
+        //print "max=".$max." res=".$res;
626
+        return $res;
627
+    }
628 628
 
629 629
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
630
-	/**
631
-	 * Return min value of all data
632
-	 *
633
-	 * @return 	double		Max value of all data
634
-	 */
635
-	function GetFloorMinValue()
636
-	{
630
+    /**
631
+     * Return min value of all data
632
+     *
633
+     * @return 	double		Max value of all data
634
+     */
635
+    function GetFloorMinValue()
636
+    {
637 637
         // phpcs:enable
638
-		$min = $this->GetMinValueInData();
639
-		if ($min == '') $min=0;
640
-		if ($min != 0) $min--;
641
-		$size=dol_strlen(abs(floor($min)));
642
-		$factor=1;
643
-		for ($i=0; $i < ($size-1); $i++)
644
-		{
645
-			$factor*=10;
646
-		}
647
-
648
-		$res=floor($min/$factor)*$factor;
649
-
650
-		//print "min=".$min." res=".$res;
651
-		return $res;
652
-	}
653
-
654
-	/**
655
-	 * Build a graph into memory using correct library  (may also be wrote on disk, depending on library used)
656
-	 *
657
-	 * @param	string	$file    	Image file name to use to save onto disk (also used as javascript unique id)
658
-	 * @param	string	$fileurl	Url path to show image if saved onto disk
659
-	 * @return	integer|null
660
-	 */
661
-	function draw($file, $fileurl='')
662
-	{
663
-		if (empty($file))
664
-		{
665
-			$this->error="Call to draw method was made with empty value for parameter file.";
666
-			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
667
-			return -2;
668
-		}
669
-		if (! is_array($this->data))
670
-		{
671
-			$this->error="Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
672
-			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
673
-			return -1;
674
-		}
675
-		if (count($this->data) < 1)
676
-		{
677
-			$this->error="Call to draw method was made but SetData was is an empty dataset";
678
-			dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING);
679
-		}
680
-		$call = "draw_".$this->_library;
681
-		call_user_func_array(array($this,$call), array($file,$fileurl));
682
-	}
638
+        $min = $this->GetMinValueInData();
639
+        if ($min == '') $min=0;
640
+        if ($min != 0) $min--;
641
+        $size=dol_strlen(abs(floor($min)));
642
+        $factor=1;
643
+        for ($i=0; $i < ($size-1); $i++)
644
+        {
645
+            $factor*=10;
646
+        }
647
+
648
+        $res=floor($min/$factor)*$factor;
649
+
650
+        //print "min=".$min." res=".$res;
651
+        return $res;
652
+    }
653
+
654
+    /**
655
+     * Build a graph into memory using correct library  (may also be wrote on disk, depending on library used)
656
+     *
657
+     * @param	string	$file    	Image file name to use to save onto disk (also used as javascript unique id)
658
+     * @param	string	$fileurl	Url path to show image if saved onto disk
659
+     * @return	integer|null
660
+     */
661
+    function draw($file, $fileurl='')
662
+    {
663
+        if (empty($file))
664
+        {
665
+            $this->error="Call to draw method was made with empty value for parameter file.";
666
+            dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
667
+            return -2;
668
+        }
669
+        if (! is_array($this->data))
670
+        {
671
+            $this->error="Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
672
+            dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
673
+            return -1;
674
+        }
675
+        if (count($this->data) < 1)
676
+        {
677
+            $this->error="Call to draw method was made but SetData was is an empty dataset";
678
+            dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING);
679
+        }
680
+        $call = "draw_".$this->_library;
681
+        call_user_func_array(array($this,$call), array($file,$fileurl));
682
+    }
683 683
 
684 684
 
685 685
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
686
-	/**
687
-	 * Build a graph onto disk using Artichow library and return img string to it
688
-	 *
689
-	 * @param	string	$file    	Image file name to use if we save onto disk
690
-	 * @param	string	$fileurl	Url path to show image if saved onto disk
691
-	 * @return	void
692
-	 */
693
-	private function draw_artichow($file,$fileurl)
694
-	{
686
+    /**
687
+     * Build a graph onto disk using Artichow library and return img string to it
688
+     *
689
+     * @param	string	$file    	Image file name to use if we save onto disk
690
+     * @param	string	$fileurl	Url path to show image if saved onto disk
691
+     * @return	void
692
+     */
693
+    private function draw_artichow($file,$fileurl)
694
+    {
695 695
         // phpcs:enable
696
-		global $artichow_defaultfont;
697
-
698
-		dol_syslog(get_class($this)."::draw_artichow this->type=".join(',',$this->type));
699
-
700
-		if (! defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP',3);
701
-		if (! defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND',2);
702
-		if (! defined('LEGEND_LINE'))       define('LEGEND_LINE',1);
703
-
704
-		// Create graph
705
-		$classname='';
706
-		if (! isset($this->type[0]) || $this->type[0] == 'bars')  $classname='BarPlot';    // Only one type (first one) is supported by artichow
707
-		else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname='LinePlot';
708
-		else $classname='TypeUnknown';
709
-		include_once ARTICHOW_PATH.$classname.'.class.php';
710
-
711
-		// Definition de couleurs
712
-		$bgcolor=new Color($this->bgcolor[0],$this->bgcolor[1],$this->bgcolor[2]);
713
-		$bgcolorgrid=new Color($this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
714
-		$colortrans=new Color(0,0,0,100);
715
-		$colorsemitrans=new Color(255,255,255,60);
716
-		$colorgradient= new LinearGradient(new Color(235, 235, 235),new Color(255, 255, 255),0);
717
-		$colorwhite=new Color(255,255,255);
718
-
719
-		// Graph
720
-		$graph = new Graph($this->width, $this->height);
721
-		$graph->border->hide();
722
-		$graph->setAntiAliasing(true);
723
-		if (isset($this->title))
724
-		{
725
-			$graph->title->set($this->title);
726
-			//print $artichow_defaultfont;exit;
727
-			$graph->title->setFont(new $artichow_defaultfont(10));
728
-		}
729
-
730
-		if (is_array($this->bgcolor)) $graph->setBackgroundColor($bgcolor);
731
-		else $graph->setBackgroundGradient($colorgradient);
732
-
733
-		$group = new PlotGroup;
734
-		//$group->setSpace(5, 5, 0, 0);
735
-
736
-		$paddleft=50;
737
-		$paddright=10;
738
-		$strl=dol_strlen(max(abs($this->MaxValue),abs($this->MinValue)));
739
-		if ($strl > 6) $paddleft += ($strl * 4);
740
-		$group->setPadding($paddleft, $paddright);		// Width on left and right for Y axis values
741
-		$group->legend->setSpace(0);
742
-		$group->legend->setPadding(2,2,2,2);
743
-		$group->legend->setPosition(null, 0.1);
744
-		$group->legend->setBackgroundColor($colorsemitrans);
745
-
746
-		if (is_array($this->bgcolorgrid)) $group->grid->setBackgroundColor($bgcolorgrid);
747
-		else $group->grid->setBackgroundColor($colortrans);
748
-
749
-		if ($this->hideXGrid)	$group->grid->hideVertical(true);
750
-		if ($this->hideYGrid)	$group->grid->hideHorizontal(true);
751
-
752
-		// On boucle sur chaque lot de donnees
753
-		$legends=array();
754
-		$i=0;
755
-		$nblot=count($this->data[0])-1;
756
-
757
-		while ($i < $nblot)
758
-		{
759
-			$x=0;
760
-			$values=array();
761
-			foreach($this->data as $key => $valarray)
762
-			{
763
-				$legends[$x] = $valarray[0];
764
-				$values[$x]  = $valarray[$i+1];
765
-				$x++;
766
-			}
767
-
768
-			// We fix unknown values to null
769
-			$newvalues=array();
770
-			foreach($values as $val)
771
-			{
772
-				$newvalues[]=(is_numeric($val) ? $val : null);
773
-			}
696
+        global $artichow_defaultfont;
697
+
698
+        dol_syslog(get_class($this)."::draw_artichow this->type=".join(',',$this->type));
699
+
700
+        if (! defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP',3);
701
+        if (! defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND',2);
702
+        if (! defined('LEGEND_LINE'))       define('LEGEND_LINE',1);
703
+
704
+        // Create graph
705
+        $classname='';
706
+        if (! isset($this->type[0]) || $this->type[0] == 'bars')  $classname='BarPlot';    // Only one type (first one) is supported by artichow
707
+        else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname='LinePlot';
708
+        else $classname='TypeUnknown';
709
+        include_once ARTICHOW_PATH.$classname.'.class.php';
710
+
711
+        // Definition de couleurs
712
+        $bgcolor=new Color($this->bgcolor[0],$this->bgcolor[1],$this->bgcolor[2]);
713
+        $bgcolorgrid=new Color($this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
714
+        $colortrans=new Color(0,0,0,100);
715
+        $colorsemitrans=new Color(255,255,255,60);
716
+        $colorgradient= new LinearGradient(new Color(235, 235, 235),new Color(255, 255, 255),0);
717
+        $colorwhite=new Color(255,255,255);
718
+
719
+        // Graph
720
+        $graph = new Graph($this->width, $this->height);
721
+        $graph->border->hide();
722
+        $graph->setAntiAliasing(true);
723
+        if (isset($this->title))
724
+        {
725
+            $graph->title->set($this->title);
726
+            //print $artichow_defaultfont;exit;
727
+            $graph->title->setFont(new $artichow_defaultfont(10));
728
+        }
729
+
730
+        if (is_array($this->bgcolor)) $graph->setBackgroundColor($bgcolor);
731
+        else $graph->setBackgroundGradient($colorgradient);
732
+
733
+        $group = new PlotGroup;
734
+        //$group->setSpace(5, 5, 0, 0);
735
+
736
+        $paddleft=50;
737
+        $paddright=10;
738
+        $strl=dol_strlen(max(abs($this->MaxValue),abs($this->MinValue)));
739
+        if ($strl > 6) $paddleft += ($strl * 4);
740
+        $group->setPadding($paddleft, $paddright);		// Width on left and right for Y axis values
741
+        $group->legend->setSpace(0);
742
+        $group->legend->setPadding(2,2,2,2);
743
+        $group->legend->setPosition(null, 0.1);
744
+        $group->legend->setBackgroundColor($colorsemitrans);
745
+
746
+        if (is_array($this->bgcolorgrid)) $group->grid->setBackgroundColor($bgcolorgrid);
747
+        else $group->grid->setBackgroundColor($colortrans);
748
+
749
+        if ($this->hideXGrid)	$group->grid->hideVertical(true);
750
+        if ($this->hideYGrid)	$group->grid->hideHorizontal(true);
751
+
752
+        // On boucle sur chaque lot de donnees
753
+        $legends=array();
754
+        $i=0;
755
+        $nblot=count($this->data[0])-1;
756
+
757
+        while ($i < $nblot)
758
+        {
759
+            $x=0;
760
+            $values=array();
761
+            foreach($this->data as $key => $valarray)
762
+            {
763
+                $legends[$x] = $valarray[0];
764
+                $values[$x]  = $valarray[$i+1];
765
+                $x++;
766
+            }
767
+
768
+            // We fix unknown values to null
769
+            $newvalues=array();
770
+            foreach($values as $val)
771
+            {
772
+                $newvalues[]=(is_numeric($val) ? $val : null);
773
+            }
774
+
775
+
776
+            if ($this->type[0] == 'bars')
777
+            {
778
+                //print "Lot de donnees $i<br>";
779
+                //print_r($values);
780
+                //print '<br>';
781
+
782
+                $color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
783
+                $colorbis=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),50);
784
+
785
+                $colorgrey=new Color(100,100,100);
786
+                $colorborder=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
787
+
788
+                if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i+1, $nblot);
789
+                if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
790
+
791
+                $plot->barBorder->setColor($colorgrey);
792
+                //$plot->setBarColor($color);
793
+                $plot->setBarGradient(new LinearGradient($colorbis, $color, 90));
794
+
795
+                if ($this->mode == 'side')  $plot->setBarPadding(0.1, 0.1);
796
+                if ($this->mode == 'depth') $plot->setBarPadding(0.1, 0.4);
797
+                if ($this->mode == 'side')  $plot->setBarSpace(5);
798
+                if ($this->mode == 'depth') $plot->setBarSpace(2);
799
+
800
+                $plot->barShadow->setSize($this->SetShading);
801
+                $plot->barShadow->setPosition(SHADOW_RIGHT_TOP);
802
+                $plot->barShadow->setColor(new Color(160, 160, 160, 50));
803
+                $plot->barShadow->smooth(true);
804
+                //$plot->setSize(1, 0.96);
805
+                //$plot->setCenter(0.5, 0.52);
806
+
807
+                // Le mode automatique est plus efficace
808
+                $plot->SetYMax($this->MaxValue);
809
+                $plot->SetYMin($this->MinValue);
810
+            }
811
+
812
+            if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')
813
+            {
814
+                $color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
815
+                $colorbis=new Color(min($this->datacolor[$i][0]+20,255),min($this->datacolor[$i][1]+20,255),min($this->datacolor[$i][2]+20,255),60);
816
+                $colorter=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),90);
817
+
818
+                $plot = new LinePlot($newvalues);
819
+                //$plot->setSize(1, 0.96);
820
+                //$plot->setCenter(0.5, 0.52);
821
+
822
+                $plot->setColor($color);
823
+                $plot->setThickness(1);
824
+
825
+                // Set line background gradient
826
+                $plot->setFillGradient(new LinearGradient($colorter, $colorbis, 90));
827
+
828
+                $plot->xAxis->setLabelText($legends);
829
+
830
+                // Le mode automatique est plus efficace
831
+                $plot->SetYMax($this->MaxValue);
832
+                $plot->SetYMin($this->MinValue);
833
+                //$plot->setYAxis(0);
834
+                //$plot->hideLine(true);
835
+            }
836
+
837
+            //$plot->reduce(80);		// Evite temps d'affichage trop long et nombre de ticks absisce satures
838
+
839
+            $group->legend->setTextFont(new $artichow_defaultfont(10)); // This is to force Artichow to use awFileFontDriver to
840
+            // solve a bug in Artichow with UTF8
841
+            if (count($this->Legend))
842
+            {
843
+                if ($this->type[0] == 'bars')  										$group->legend->add($plot, $this->Legend[$i], LEGEND_BACKGROUND);
844
+                if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')	$group->legend->add($plot, $this->Legend[$i], LEGEND_LINE);
845
+            }
846
+            $group->add($plot);
774 847
 
848
+            $i++;
849
+        }
850
+
851
+        $group->axis->bottom->setLabelText($legends);
852
+        $group->axis->bottom->label->setFont(new $artichow_defaultfont(7));
853
+
854
+        //print $group->axis->bottom->getLabelNumber();
855
+        if ($this->labelInterval > 0) $group->axis->bottom->setLabelInterval($this->labelInterval);
775 856
 
776
-			if ($this->type[0] == 'bars')
777
-			{
778
-				//print "Lot de donnees $i<br>";
779
-				//print_r($values);
780
-				//print '<br>';
781
-
782
-				$color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
783
-				$colorbis=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),50);
784
-
785
-				$colorgrey=new Color(100,100,100);
786
-				$colorborder=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
787
-
788
-				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i+1, $nblot);
789
-				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
790
-
791
-				$plot->barBorder->setColor($colorgrey);
792
-				//$plot->setBarColor($color);
793
-				$plot->setBarGradient(new LinearGradient($colorbis, $color, 90));
794
-
795
-				if ($this->mode == 'side')  $plot->setBarPadding(0.1, 0.1);
796
-				if ($this->mode == 'depth') $plot->setBarPadding(0.1, 0.4);
797
-				if ($this->mode == 'side')  $plot->setBarSpace(5);
798
-				if ($this->mode == 'depth') $plot->setBarSpace(2);
799
-
800
-				$plot->barShadow->setSize($this->SetShading);
801
-				$plot->barShadow->setPosition(SHADOW_RIGHT_TOP);
802
-				$plot->barShadow->setColor(new Color(160, 160, 160, 50));
803
-				$plot->barShadow->smooth(true);
804
-				//$plot->setSize(1, 0.96);
805
-				//$plot->setCenter(0.5, 0.52);
806
-
807
-				// Le mode automatique est plus efficace
808
-				$plot->SetYMax($this->MaxValue);
809
-				$plot->SetYMin($this->MinValue);
810
-			}
857
+        $graph->add($group);
858
+
859
+        // Generate file
860
+        $graph->draw($file);
811 861
 
812
-			if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')
813
-			{
814
-				$color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
815
-				$colorbis=new Color(min($this->datacolor[$i][0]+20,255),min($this->datacolor[$i][1]+20,255),min($this->datacolor[$i][2]+20,255),60);
816
-				$colorter=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),90);
817
-
818
-				$plot = new LinePlot($newvalues);
819
-				//$plot->setSize(1, 0.96);
820
-				//$plot->setCenter(0.5, 0.52);
821
-
822
-				$plot->setColor($color);
823
-				$plot->setThickness(1);
824
-
825
-				// Set line background gradient
826
-				$plot->setFillGradient(new LinearGradient($colorter, $colorbis, 90));
827
-
828
-				$plot->xAxis->setLabelText($legends);
829
-
830
-				// Le mode automatique est plus efficace
831
-				$plot->SetYMax($this->MaxValue);
832
-				$plot->SetYMin($this->MinValue);
833
-				//$plot->setYAxis(0);
834
-				//$plot->hideLine(true);
835
-			}
836
-
837
-			//$plot->reduce(80);		// Evite temps d'affichage trop long et nombre de ticks absisce satures
838
-
839
-			$group->legend->setTextFont(new $artichow_defaultfont(10)); // This is to force Artichow to use awFileFontDriver to
840
-			// solve a bug in Artichow with UTF8
841
-			if (count($this->Legend))
842
-			{
843
-				if ($this->type[0] == 'bars')  										$group->legend->add($plot, $this->Legend[$i], LEGEND_BACKGROUND);
844
-				if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')	$group->legend->add($plot, $this->Legend[$i], LEGEND_LINE);
845
-			}
846
-			$group->add($plot);
847
-
848
-			$i++;
849
-		}
850
-
851
-		$group->axis->bottom->setLabelText($legends);
852
-		$group->axis->bottom->label->setFont(new $artichow_defaultfont(7));
853
-
854
-		//print $group->axis->bottom->getLabelNumber();
855
-		if ($this->labelInterval > 0) $group->axis->bottom->setLabelInterval($this->labelInterval);
856
-
857
-		$graph->add($group);
858
-
859
-		// Generate file
860
-		$graph->draw($file);
861
-
862
-		$this->stringtoshow='<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'" alt="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'">';
863
-	}
862
+        $this->stringtoshow='<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'" alt="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'">';
863
+    }
864 864
 
865 865
 
866 866
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
867
-	/**
868
-	 * Build a graph using JFlot library. Input when calling this method should be:
869
-	 *	$this->data  = array(array(0=>'labelxA',1=>yA),  array('labelxB',yB));
870
-	 *	$this->data  = array(array(0=>'labelxA',1=>yA1,...,n=>yAn), array('labelxB',yB1,...yBn));   // or when there is n series to show for each x
871
-	 *  $this->data  = array(array('label'=>'labelxA','data'=>yA),  array('labelxB',yB));			// Syntax deprecated
872
-	 *  $this->legend= array("Val1",...,"Valn");													// list of n series name
873
-	 *  $this->type  = array('bars',...'lines'); or array('pie')
874
-	 *  $this->mode = 'depth' ???
875
-	 *  $this->bgcolorgrid
876
-	 *  $this->datacolor
877
-	 *  $this->shownodatagraph
878
-	 *
879
-	 * @param	string	$file    	Image file name to use to save onto disk (also used as javascript unique id)
880
-	 * @param	string	$fileurl	Url path to show image if saved onto disk. Never used here.
881
-	 * @return	void
882
-	 */
883
-	private function draw_jflot($file, $fileurl)
884
-	{
867
+    /**
868
+     * Build a graph using JFlot library. Input when calling this method should be:
869
+     *	$this->data  = array(array(0=>'labelxA',1=>yA),  array('labelxB',yB));
870
+     *	$this->data  = array(array(0=>'labelxA',1=>yA1,...,n=>yAn), array('labelxB',yB1,...yBn));   // or when there is n series to show for each x
871
+     *  $this->data  = array(array('label'=>'labelxA','data'=>yA),  array('labelxB',yB));			// Syntax deprecated
872
+     *  $this->legend= array("Val1",...,"Valn");													// list of n series name
873
+     *  $this->type  = array('bars',...'lines'); or array('pie')
874
+     *  $this->mode = 'depth' ???
875
+     *  $this->bgcolorgrid
876
+     *  $this->datacolor
877
+     *  $this->shownodatagraph
878
+     *
879
+     * @param	string	$file    	Image file name to use to save onto disk (also used as javascript unique id)
880
+     * @param	string	$fileurl	Url path to show image if saved onto disk. Never used here.
881
+     * @return	void
882
+     */
883
+    private function draw_jflot($file, $fileurl)
884
+    {
885 885
         // phpcs:enable
886
-		global $artichow_defaultfont;
887
-
888
-		dol_syslog(get_class($this)."::draw_jflot this->type=".join(',',$this->type)." this->MaxValue=".$this->MaxValue);
889
-
890
-		if (empty($this->width) && empty($this->height))
891
-		{
892
-			print 'Error width or height not set';
893
-			return;
894
-		}
895
-
896
-		$legends=array();
897
-		$nblot=count($this->data[0])-1;    // -1 to remove legend
898
-		if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING);
899
-		$firstlot=0;
900
-		// Works with line but not with bars
901
-		//if ($nblot > 2) $firstlot = ($nblot - 2);        // We limit nblot to 2 because jflot can't manage more than 2 bars on same x
902
-
903
-		$i=$firstlot;
904
-		$serie=array();
905
-		while ($i < $nblot)	// Loop on each serie
906
-		{
907
-			$values=array();	// Array with horizontal y values (specific values of a serie) for each abscisse x
908
-			$serie[$i]="var d".$i." = [];\n";
909
-
910
-			// Fill array $values
911
-			$x=0;
912
-			foreach($this->data as $valarray)	// Loop on each x
913
-			{
914
-				$legends[$x] = $valarray[0];
915
-				$values[$x]  = (is_numeric($valarray[$i+1]) ? $valarray[$i+1] : null);
916
-				$x++;
917
-			}
918
-
919
-			// TODO Avoid push by adding generated long array...
920
-			if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
921
-			{
922
-				foreach($values as $x => $y) {
923
-					if (isset($y)) $serie[$i].='d'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
924
-				}
925
-			}
926
-			else
927
-			{
928
-				foreach($values as $x => $y) {
929
-					if (isset($y)) $serie[$i].='d'.$i.'.push(['.$x.', '.$y.']);'."\n";
930
-				}
931
-			}
932
-
933
-			unset($values);
934
-			$i++;
935
-		}
936
-		$tag=dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file),'_',array('-','.'))));
937
-
938
-		$this->stringtoshow ='<!-- Build using '.$this->_library.' -->'."\n";
939
-		if (! empty($this->title)) $this->stringtoshow.='<div align="center" class="dolgraphtitle'.(empty($this->cssprefix)?'':' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
940
-		if (! empty($this->shownographyet))
941
-		{
942
-		  $this->stringtoshow.='<div style="width:'.$this->width.'px;height:'.$this->height.'px;" class="nographyet"></div>';
943
-		  $this->stringtoshow.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
944
-		  return;
945
-		}
946
-		$this->stringtoshow.='<div id="placeholder_'.$tag.'" style="width:'.$this->width.'px;height:'.$this->height.'px;" class="dolgraph'.(empty($this->cssprefix)?'':' dolgraph'.$this->cssprefix).'"></div>'."\n";
947
-
948
-		$this->stringtoshow.='<script id="'.$tag.'">'."\n";
949
-		$this->stringtoshow.='$(function () {'."\n";
950
-		$i=$firstlot;
951
-		if ($nblot < 0)
952
-		{
953
-			$this->stringtoshow.='<!-- No series of data -->';
954
-		}
955
-		else
956
-		{
957
-			while ($i < $nblot)
958
-			{
959
-				$this->stringtoshow.=$serie[$i];
960
-				$i++;
961
-			}
962
-		}
963
-		$this->stringtoshow.="\n";
964
-
965
-		// Special case for Graph of type 'pie'
966
-		if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
967
-		{
968
-			$datacolor=array();
969
-			foreach($this->datacolor as $val) $datacolor[]="#".sprintf("%02x%02x%02x",$val[0],$val[1],$val[2]);
970
-
971
-			$urltemp='';	// TODO Add support for url link into labels
972
-			$showlegend=$this->showlegend;
973
-			$showpointvalue=$this->showpointvalue;
974
-			$showpercent=$this->showpercent;
975
-
976
-			$this->stringtoshow.= '
886
+        global $artichow_defaultfont;
887
+
888
+        dol_syslog(get_class($this)."::draw_jflot this->type=".join(',',$this->type)." this->MaxValue=".$this->MaxValue);
889
+
890
+        if (empty($this->width) && empty($this->height))
891
+        {
892
+            print 'Error width or height not set';
893
+            return;
894
+        }
895
+
896
+        $legends=array();
897
+        $nblot=count($this->data[0])-1;    // -1 to remove legend
898
+        if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING);
899
+        $firstlot=0;
900
+        // Works with line but not with bars
901
+        //if ($nblot > 2) $firstlot = ($nblot - 2);        // We limit nblot to 2 because jflot can't manage more than 2 bars on same x
902
+
903
+        $i=$firstlot;
904
+        $serie=array();
905
+        while ($i < $nblot)	// Loop on each serie
906
+        {
907
+            $values=array();	// Array with horizontal y values (specific values of a serie) for each abscisse x
908
+            $serie[$i]="var d".$i." = [];\n";
909
+
910
+            // Fill array $values
911
+            $x=0;
912
+            foreach($this->data as $valarray)	// Loop on each x
913
+            {
914
+                $legends[$x] = $valarray[0];
915
+                $values[$x]  = (is_numeric($valarray[$i+1]) ? $valarray[$i+1] : null);
916
+                $x++;
917
+            }
918
+
919
+            // TODO Avoid push by adding generated long array...
920
+            if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
921
+            {
922
+                foreach($values as $x => $y) {
923
+                    if (isset($y)) $serie[$i].='d'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
924
+                }
925
+            }
926
+            else
927
+            {
928
+                foreach($values as $x => $y) {
929
+                    if (isset($y)) $serie[$i].='d'.$i.'.push(['.$x.', '.$y.']);'."\n";
930
+                }
931
+            }
932
+
933
+            unset($values);
934
+            $i++;
935
+        }
936
+        $tag=dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file),'_',array('-','.'))));
937
+
938
+        $this->stringtoshow ='<!-- Build using '.$this->_library.' -->'."\n";
939
+        if (! empty($this->title)) $this->stringtoshow.='<div align="center" class="dolgraphtitle'.(empty($this->cssprefix)?'':' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
940
+        if (! empty($this->shownographyet))
941
+        {
942
+            $this->stringtoshow.='<div style="width:'.$this->width.'px;height:'.$this->height.'px;" class="nographyet"></div>';
943
+            $this->stringtoshow.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
944
+            return;
945
+        }
946
+        $this->stringtoshow.='<div id="placeholder_'.$tag.'" style="width:'.$this->width.'px;height:'.$this->height.'px;" class="dolgraph'.(empty($this->cssprefix)?'':' dolgraph'.$this->cssprefix).'"></div>'."\n";
947
+
948
+        $this->stringtoshow.='<script id="'.$tag.'">'."\n";
949
+        $this->stringtoshow.='$(function () {'."\n";
950
+        $i=$firstlot;
951
+        if ($nblot < 0)
952
+        {
953
+            $this->stringtoshow.='<!-- No series of data -->';
954
+        }
955
+        else
956
+        {
957
+            while ($i < $nblot)
958
+            {
959
+                $this->stringtoshow.=$serie[$i];
960
+                $i++;
961
+            }
962
+        }
963
+        $this->stringtoshow.="\n";
964
+
965
+        // Special case for Graph of type 'pie'
966
+        if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
967
+        {
968
+            $datacolor=array();
969
+            foreach($this->datacolor as $val) $datacolor[]="#".sprintf("%02x%02x%02x",$val[0],$val[1],$val[2]);
970
+
971
+            $urltemp='';	// TODO Add support for url link into labels
972
+            $showlegend=$this->showlegend;
973
+            $showpointvalue=$this->showpointvalue;
974
+            $showpercent=$this->showpercent;
975
+
976
+            $this->stringtoshow.= '
977 977
 			function plotWithOptions_'.$tag.'() {
978 978
 			$.plot($("#placeholder_'.$tag.'"), d0,
979 979
 			{
@@ -992,15 +992,15 @@  discard block
 block discarded – undo
992 992
 								var percent=Math.round(series.percent);
993 993
 								var number=series.data[0][1];
994 994
 								return \'';
995
-								$this->stringtoshow.='<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
996
-								if ($urltemp) $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
997
-								$this->stringtoshow.='\'+';
998
-								$this->stringtoshow.=($showlegend?'':'label+\' \'+');	// Hide label if already shown in legend
999
-								$this->stringtoshow.=($showpointvalue?'number+':'');
1000
-								$this->stringtoshow.=($showpercent?'\'<br/>\'+percent+\'%\'+':'');
1001
-								$this->stringtoshow.='\'';
1002
-								if ($urltemp) $this->stringtoshow.='</a>';
1003
-								$this->stringtoshow.='</span>\';
995
+                                $this->stringtoshow.='<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
996
+                                if ($urltemp) $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
997
+                                $this->stringtoshow.='\'+';
998
+                                $this->stringtoshow.=($showlegend?'':'label+\' \'+');	// Hide label if already shown in legend
999
+                                $this->stringtoshow.=($showpointvalue?'number+':'');
1000
+                                $this->stringtoshow.=($showpercent?'\'<br/>\'+percent+\'%\'+':'');
1001
+                                $this->stringtoshow.='\'';
1002
+                                if ($urltemp) $this->stringtoshow.='</a>';
1003
+                                $this->stringtoshow.='</span>\';
1004 1004
 							},
1005 1005
 							background: {
1006 1006
 							opacity: 0.0,
@@ -1015,20 +1015,20 @@  discard block
 block discarded – undo
1015 1015
 			pan: {
1016 1016
 				interactive: true
1017 1017
 			},';
1018
-			if (count($datacolor))
1019
-			{
1020
-				$this->stringtoshow.='colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
1021
-			}
1022
-			$this->stringtoshow.='legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
1018
+            if (count($datacolor))
1019
+            {
1020
+                $this->stringtoshow.='colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
1021
+            }
1022
+            $this->stringtoshow.='legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
1023 1023
 		});
1024 1024
 		}'."\n";
1025
-		}
1026
-		// Other cases, graph of type 'bars', 'lines'
1027
-		else
1028
-		{
1029
-			// Add code to support tooltips
1030
-		    // TODO: remove js css and use graph-tooltip-inner class instead by adding css in each themes
1031
-			$this->stringtoshow.='
1025
+        }
1026
+        // Other cases, graph of type 'bars', 'lines'
1027
+        else
1028
+        {
1029
+            // Add code to support tooltips
1030
+            // TODO: remove js css and use graph-tooltip-inner class instead by adding css in each themes
1031
+            $this->stringtoshow.='
1032 1032
 			function showTooltip_'.$tag.'(x, y, contents) {
1033 1033
 				$(\'<div class="graph-tooltip-inner" id="tooltip_'.$tag.'">\' + contents + \'</div>\').css({
1034 1034
 					position: \'absolute\',
@@ -1060,10 +1060,10 @@  discard block
 block discarded – undo
1060 1060
 						var y = item.datapoint[1].toFixed(2);
1061 1061
 						var z = item.series.xaxis.ticks[item.dataIndex].label;
1062 1062
 						';
1063
-						if ($this->showpointvalue > 0) $this->stringtoshow.='
1063
+                        if ($this->showpointvalue > 0) $this->stringtoshow.='
1064 1064
 							showTooltip_'.$tag.'(item.pageX, item.pageY, item.series.label + "<br>" + z + " => " + y);
1065 1065
 						';
1066
-						$this->stringtoshow.='
1066
+                        $this->stringtoshow.='
1067 1067
 					}
1068 1068
 				}
1069 1069
 				else {
@@ -1073,95 +1073,95 @@  discard block
 block discarded – undo
1073 1073
 			});
1074 1074
 			';
1075 1075
 
1076
-			$this->stringtoshow.='var stack = null, steps = false;'."\n";
1077
-
1078
-			$this->stringtoshow.='function plotWithOptions_'.$tag.'() {'."\n";
1079
-			$this->stringtoshow.='$.plot($("#placeholder_'.$tag.'"), [ '."\n";
1080
-			$i=$firstlot;
1081
-			while ($i < $nblot)
1082
-			{
1083
-				if ($i > $firstlot) $this->stringtoshow.=', '."\n";
1084
-				$color=sprintf("%02x%02x%02x",$this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
1085
-				$this->stringtoshow.='{ ';
1086
-				if (! isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
1087
-				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1088
-				$this->stringtoshow.='color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
1089
-				$i++;
1090
-			}
1091
-			// shadowSize: 0 -> Drawing is faster without shadows
1092
-			$this->stringtoshow.="\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6 } }'."\n";
1093
-
1094
-			// Xaxis
1095
-			$this->stringtoshow.=', xaxis: { ticks: ['."\n";
1096
-			$x=0;
1097
-			foreach($this->data as $key => $valarray)
1098
-			{
1099
-				if ($x > 0) $this->stringtoshow.=', '."\n";
1100
-				$this->stringtoshow.= ' ['.$x.', "'.$valarray[0].'"]';
1101
-				$x++;
1102
-			}
1103
-			$this->stringtoshow.='] }'."\n";
1104
-
1105
-			// Yaxis
1106
-			$this->stringtoshow.=', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
1107
-
1108
-			// Background color
1109
-			$color1=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[0],$this->bgcolorgrid[2]);
1110
-			$color2=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
1111
-			$this->stringtoshow.=', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
1112
-			//$this->stringtoshow.=', shadowSize: 20'."\n";    TODO Uncommet this
1113
-			$this->stringtoshow.='});'."\n";
1114
-			$this->stringtoshow.='}'."\n";
1115
-		}
1116
-
1117
-		$this->stringtoshow.='plotWithOptions_'.$tag.'();'."\n";
1118
-		$this->stringtoshow.='});'."\n";
1119
-		$this->stringtoshow.='</script>'."\n";
1120
-	}
1121
-
1122
-
1123
-
1124
-	/**
1125
-	 * Output HTML string to show graph
1126
-	 *
1127
-	 * @param	int			$shownographyet 	Show graph to say there is not enough data
1128
-	 * @return	string							HTML string to show graph
1129
-	 */
1130
-	function show($shownographyet=0)
1131
-	{
1132
-		global $langs;
1133
-
1134
-		if ($shownographyet)
1135
-		{
1136
-			$s= '<div class="nographyet" style="width:'.(preg_match('/%/',$this->width)?$this->width:$this->width.'px').'; height:'.(preg_match('/%/',$this->height)?$this->height:$this->height.'px').';"></div>';
1137
-			$s.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
1138
-			return $s;
1139
-		}
1140
-
1141
-		return $this->stringtoshow;
1142
-	}
1143
-
1144
-
1145
-	/**
1146
-	 * getDefaultGraphSizeForStats
1147
-	 *
1148
-	 * @param	string	$direction		'width' or 'height'
1149
-	 * @param	string	$defaultsize	Value we want as default size
1150
-	 * @return	int						Value of width or height to use by default
1151
-	 */
1152
-	static function getDefaultGraphSizeForStats($direction,$defaultsize='')
1153
-	{
1154
-		global $conf;
1155
-
1156
-		if ($direction == 'width')
1157
-		{
1158
-			if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500');
1159
-			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
1160
-		}
1161
-		if ($direction == 'height')
1162
-		{
1163
-			return (empty($conf->dol_optimize_smallscreen)?($defaultsize?$defaultsize:'200'):'160');
1164
-		}
1165
-		return 0;
1166
-	}
1076
+            $this->stringtoshow.='var stack = null, steps = false;'."\n";
1077
+
1078
+            $this->stringtoshow.='function plotWithOptions_'.$tag.'() {'."\n";
1079
+            $this->stringtoshow.='$.plot($("#placeholder_'.$tag.'"), [ '."\n";
1080
+            $i=$firstlot;
1081
+            while ($i < $nblot)
1082
+            {
1083
+                if ($i > $firstlot) $this->stringtoshow.=', '."\n";
1084
+                $color=sprintf("%02x%02x%02x",$this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
1085
+                $this->stringtoshow.='{ ';
1086
+                if (! isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
1087
+                if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1088
+                $this->stringtoshow.='color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
1089
+                $i++;
1090
+            }
1091
+            // shadowSize: 0 -> Drawing is faster without shadows
1092
+            $this->stringtoshow.="\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6 } }'."\n";
1093
+
1094
+            // Xaxis
1095
+            $this->stringtoshow.=', xaxis: { ticks: ['."\n";
1096
+            $x=0;
1097
+            foreach($this->data as $key => $valarray)
1098
+            {
1099
+                if ($x > 0) $this->stringtoshow.=', '."\n";
1100
+                $this->stringtoshow.= ' ['.$x.', "'.$valarray[0].'"]';
1101
+                $x++;
1102
+            }
1103
+            $this->stringtoshow.='] }'."\n";
1104
+
1105
+            // Yaxis
1106
+            $this->stringtoshow.=', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
1107
+
1108
+            // Background color
1109
+            $color1=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[0],$this->bgcolorgrid[2]);
1110
+            $color2=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
1111
+            $this->stringtoshow.=', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
1112
+            //$this->stringtoshow.=', shadowSize: 20'."\n";    TODO Uncommet this
1113
+            $this->stringtoshow.='});'."\n";
1114
+            $this->stringtoshow.='}'."\n";
1115
+        }
1116
+
1117
+        $this->stringtoshow.='plotWithOptions_'.$tag.'();'."\n";
1118
+        $this->stringtoshow.='});'."\n";
1119
+        $this->stringtoshow.='</script>'."\n";
1120
+    }
1121
+
1122
+
1123
+
1124
+    /**
1125
+     * Output HTML string to show graph
1126
+     *
1127
+     * @param	int			$shownographyet 	Show graph to say there is not enough data
1128
+     * @return	string							HTML string to show graph
1129
+     */
1130
+    function show($shownographyet=0)
1131
+    {
1132
+        global $langs;
1133
+
1134
+        if ($shownographyet)
1135
+        {
1136
+            $s= '<div class="nographyet" style="width:'.(preg_match('/%/',$this->width)?$this->width:$this->width.'px').'; height:'.(preg_match('/%/',$this->height)?$this->height:$this->height.'px').';"></div>';
1137
+            $s.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
1138
+            return $s;
1139
+        }
1140
+
1141
+        return $this->stringtoshow;
1142
+    }
1143
+
1144
+
1145
+    /**
1146
+     * getDefaultGraphSizeForStats
1147
+     *
1148
+     * @param	string	$direction		'width' or 'height'
1149
+     * @param	string	$defaultsize	Value we want as default size
1150
+     * @return	int						Value of width or height to use by default
1151
+     */
1152
+    static function getDefaultGraphSizeForStats($direction,$defaultsize='')
1153
+    {
1154
+        global $conf;
1155
+
1156
+        if ($direction == 'width')
1157
+        {
1158
+            if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500');
1159
+            else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
1160
+        }
1161
+        if ($direction == 'height')
1162
+        {
1163
+            return (empty($conf->dol_optimize_smallscreen)?($defaultsize?$defaultsize:'200'):'160');
1164
+        }
1165
+        return 0;
1166
+    }
1167 1167
 }
Please login to merge, or discard this patch.
Spacing   +198 added lines, -198 removed lines patch added patch discarded remove patch
@@ -39,48 +39,48 @@  discard block
 block discarded – undo
39 39
  */
40 40
 class DolGraph
41 41
 {
42
-	public $type=array();			// Array with type of each series. Example: array('bars', 'lines', ...)
43
-	public $mode='side';		    // Mode bars graph: side, depth
44
-	private $_library='jflot';	// Graphic library to use (jflot, artichow)
42
+	public $type = array(); // Array with type of each series. Example: array('bars', 'lines', ...)
43
+	public $mode = 'side'; // Mode bars graph: side, depth
44
+	private $_library = 'jflot'; // Graphic library to use (jflot, artichow)
45 45
 
46 46
 	//! Array of data
47
-	public $data;				// Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
48
-	public $title;				// Title of graph
49
-	public $cssprefix='';		// To add into css styles
50
-	public $width=380;
51
-	public $height=200;
52
-	public $MaxValue=0;
53
-	public $MinValue=0;
54
-	public $SetShading=0;
55
-
56
-	public $PrecisionY=-1;
57
-
58
-	public $horizTickIncrement=-1;
59
-	public $SetNumXTicks=-1;
60
-	public $labelInterval=-1;
61
-
62
-	public $hideXGrid=false;
63
-	public $hideYGrid=false;
64
-
65
-	public $Legend=array();
66
-	public $LegendWidthMin=0;
67
-	public $showlegend=1;
68
-	public $showpointvalue=1;
69
-	public $showpercent=0;
70
-	public $combine=0;				// 0.05 if you want to combine records < 5% into "other"
71
-	public $graph;     			// Objet Graph (Artichow, Phplot...)
47
+	public $data; // Data of graph: array(array('abs1',valA1,valB1), array('abs2',valA2,valB2), ...)
48
+	public $title; // Title of graph
49
+	public $cssprefix = ''; // To add into css styles
50
+	public $width = 380;
51
+	public $height = 200;
52
+	public $MaxValue = 0;
53
+	public $MinValue = 0;
54
+	public $SetShading = 0;
55
+
56
+	public $PrecisionY = -1;
57
+
58
+	public $horizTickIncrement = -1;
59
+	public $SetNumXTicks = -1;
60
+	public $labelInterval = -1;
61
+
62
+	public $hideXGrid = false;
63
+	public $hideYGrid = false;
64
+
65
+	public $Legend = array();
66
+	public $LegendWidthMin = 0;
67
+	public $showlegend = 1;
68
+	public $showpointvalue = 1;
69
+	public $showpercent = 0;
70
+	public $combine = 0; // 0.05 if you want to combine records < 5% into "other"
71
+	public $graph; // Objet Graph (Artichow, Phplot...)
72 72
 
73 73
 	/**
74 74
 	 * @var string Error code (or message)
75 75
 	 */
76
-	public $error='';
76
+	public $error = '';
77 77
 
78
-	public $bordercolor;			// array(R,G,B)
79
-	public $bgcolor;				// array(R,G,B)
80
-	public $bgcolorgrid=array(255,255,255);			// array(R,G,B)
81
-	public $datacolor;				// array(array(R,G,B),...)
78
+	public $bordercolor; // array(R,G,B)
79
+	public $bgcolor; // array(R,G,B)
80
+	public $bgcolorgrid = array(255, 255, 255); // array(R,G,B)
81
+	public $datacolor; // array(array(R,G,B),...)
82 82
 
83
-	private $stringtoshow;      // To store string to output graph into HTML page
83
+	private $stringtoshow; // To store string to output graph into HTML page
84 84
 
85 85
 
86 86
 	/**
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	 *
89 89
 	 * @param	string	$library		'jflot' (default) or 'artichow' (no more supported)
90 90
 	 */
91
-	function __construct($library='jflot')
91
+	function __construct($library = 'jflot')
92 92
 	{
93 93
 		global $conf;
94 94
 		global $theme_bordercolor, $theme_datacolor, $theme_bgcolor, $theme_bgcoloronglet;
@@ -96,25 +96,25 @@  discard block
 block discarded – undo
96 96
 		// To use old feature
97 97
 		if ($library == 'artichow')
98 98
 		{
99
-			$this->_library='artichow';
99
+			$this->_library = 'artichow';
100 100
 
101 101
 			// Test if module GD present
102 102
 			$modules_list = get_loaded_extensions();
103
-			$isgdinstalled=0;
103
+			$isgdinstalled = 0;
104 104
 			foreach ($modules_list as $module)
105 105
 			{
106
-				if ($module == 'gd') $isgdinstalled=1;
106
+				if ($module == 'gd') $isgdinstalled = 1;
107 107
 			}
108
-			if (! $isgdinstalled)
108
+			if (!$isgdinstalled)
109 109
 			{
110
-				$this->error="Error: PHP GD module is not available. It is required to build graphics.";
110
+				$this->error = "Error: PHP GD module is not available. It is required to build graphics.";
111 111
 				return -1;
112 112
 			}
113 113
 		}
114 114
 
115
-		$this->bordercolor = array(235,235,224);
116
-		$this->datacolor = array(array(120,130,150), array(160,160,180), array(190,190,220));
117
-		$this->bgcolor = array(235,235,224);
115
+		$this->bordercolor = array(235, 235, 224);
116
+		$this->datacolor = array(array(120, 130, 150), array(160, 160, 180), array(190, 190, 220));
117
+		$this->bgcolor = array(235, 235, 224);
118 118
 
119 119
 		$color_file = DOL_DOCUMENT_ROOT.'/theme/'.$conf->theme.'/graph-color.php';
120 120
 		if (is_readable($color_file))
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
 	 */
449 449
 	function setShowLegend($showlegend)
450 450
 	{
451
-		$this->showlegend=$showlegend;
451
+		$this->showlegend = $showlegend;
452 452
 	}
453 453
 
454 454
 	/**
@@ -459,7 +459,7 @@  discard block
 block discarded – undo
459 459
 	 */
460 460
 	function setShowPointValue($showpointvalue)
461 461
 	{
462
-		$this->showpointvalue=$showpointvalue;
462
+		$this->showpointvalue = $showpointvalue;
463 463
 	}
464 464
 
465 465
 	/**
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 	 */
471 471
 	function setShowPercent($showpercent)
472 472
 	{
473
-		$this->showpercent=$showpercent;
473
+		$this->showpercent = $showpercent;
474 474
 	}
475 475
 
476 476
 
@@ -482,12 +482,12 @@  discard block
 block discarded – undo
482 482
 	 * @param	array	$bg_color		array(R,G,B) ou 'onglet' ou 'default'
483 483
 	 * @return	void
484 484
 	 */
485
-	function SetBgColor($bg_color = array(255,255,255))
485
+	function SetBgColor($bg_color = array(255, 255, 255))
486 486
 	{
487 487
         // phpcs:enable
488
-		global $theme_bgcolor,$theme_bgcoloronglet;
488
+		global $theme_bgcolor, $theme_bgcoloronglet;
489 489
 
490
-		if (! is_array($bg_color))
490
+		if (!is_array($bg_color))
491 491
 		{
492 492
 			if ($bg_color == 'onglet')
493 493
 			{
@@ -512,12 +512,12 @@  discard block
 block discarded – undo
512 512
 	 * @param	array	$bg_colorgrid		array(R,G,B) ou 'onglet' ou 'default'
513 513
 	 * @return	void
514 514
 	 */
515
-	function SetBgColorGrid($bg_colorgrid = array(255,255,255))
515
+	function SetBgColorGrid($bg_colorgrid = array(255, 255, 255))
516 516
 	{
517 517
         // phpcs:enable
518
-		global $theme_bgcolor,$theme_bgcoloronglet;
518
+		global $theme_bgcolor, $theme_bgcoloronglet;
519 519
 
520
-		if (! is_array($bg_colorgrid))
520
+		if (!is_array($bg_colorgrid))
521 521
 		{
522 522
 			if ($bg_colorgrid == 'onglet')
523 523
 			{
@@ -562,11 +562,11 @@  discard block
 block discarded – undo
562 562
 		$nblines = count($this->data);
563 563
 		$nbvalues = count($this->data[0]) - 1;
564 564
 
565
-		for ($j = 0 ; $j < $nblines ; $j++)
565
+		for ($j = 0; $j < $nblines; $j++)
566 566
 		{
567
-			for ($i = 0 ; $i < $nbvalues ; $i++)
567
+			for ($i = 0; $i < $nbvalues; $i++)
568 568
 			{
569
-				$vals[$k] = $this->data[$j][$i+1];
569
+				$vals[$k] = $this->data[$j][$i + 1];
570 570
 				$k++;
571 571
 			}
572 572
 		}
@@ -589,11 +589,11 @@  discard block
 block discarded – undo
589 589
 		$nblines = count($this->data);
590 590
 		$nbvalues = count($this->data[0]) - 1;
591 591
 
592
-		for ($j = 0 ; $j < $nblines ; $j++)
592
+		for ($j = 0; $j < $nblines; $j++)
593 593
 		{
594
-			for ($i = 0 ; $i < $nbvalues ; $i++)
594
+			for ($i = 0; $i < $nbvalues; $i++)
595 595
 			{
596
-				$vals[$k] = $this->data[$j][$i+1];
596
+				$vals[$k] = $this->data[$j][$i + 1];
597 597
 				$k++;
598 598
 			}
599 599
 		}
@@ -612,15 +612,15 @@  discard block
 block discarded – undo
612 612
         // phpcs:enable
613 613
 		$max = $this->GetMaxValueInData();
614 614
 		if ($max != 0) $max++;
615
-		$size=dol_strlen(abs(ceil($max)));
616
-		$factor=1;
617
-		for ($i=0; $i < ($size-1); $i++)
615
+		$size = dol_strlen(abs(ceil($max)));
616
+		$factor = 1;
617
+		for ($i = 0; $i < ($size - 1); $i++)
618 618
 		{
619
-			$factor*=10;
619
+			$factor *= 10;
620 620
 		}
621 621
 
622
-		$res=0;
623
-		if (is_numeric($max)) $res=ceil($max/$factor)*$factor;
622
+		$res = 0;
623
+		if (is_numeric($max)) $res = ceil($max / $factor) * $factor;
624 624
 
625 625
 		//print "max=".$max." res=".$res;
626 626
 		return $res;
@@ -636,16 +636,16 @@  discard block
 block discarded – undo
636 636
 	{
637 637
         // phpcs:enable
638 638
 		$min = $this->GetMinValueInData();
639
-		if ($min == '') $min=0;
639
+		if ($min == '') $min = 0;
640 640
 		if ($min != 0) $min--;
641
-		$size=dol_strlen(abs(floor($min)));
642
-		$factor=1;
643
-		for ($i=0; $i < ($size-1); $i++)
641
+		$size = dol_strlen(abs(floor($min)));
642
+		$factor = 1;
643
+		for ($i = 0; $i < ($size - 1); $i++)
644 644
 		{
645
-			$factor*=10;
645
+			$factor *= 10;
646 646
 		}
647 647
 
648
-		$res=floor($min/$factor)*$factor;
648
+		$res = floor($min / $factor) * $factor;
649 649
 
650 650
 		//print "min=".$min." res=".$res;
651 651
 		return $res;
@@ -658,27 +658,27 @@  discard block
 block discarded – undo
658 658
 	 * @param	string	$fileurl	Url path to show image if saved onto disk
659 659
 	 * @return	integer|null
660 660
 	 */
661
-	function draw($file, $fileurl='')
661
+	function draw($file, $fileurl = '')
662 662
 	{
663 663
 		if (empty($file))
664 664
 		{
665
-			$this->error="Call to draw method was made with empty value for parameter file.";
665
+			$this->error = "Call to draw method was made with empty value for parameter file.";
666 666
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
667 667
 			return -2;
668 668
 		}
669
-		if (! is_array($this->data))
669
+		if (!is_array($this->data))
670 670
 		{
671
-			$this->error="Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
671
+			$this->error = "Call to draw method was made but SetData was not called or called with an empty dataset for parameters";
672 672
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_ERR);
673 673
 			return -1;
674 674
 		}
675 675
 		if (count($this->data) < 1)
676 676
 		{
677
-			$this->error="Call to draw method was made but SetData was is an empty dataset";
677
+			$this->error = "Call to draw method was made but SetData was is an empty dataset";
678 678
 			dol_syslog(get_class($this)."::draw ".$this->error, LOG_WARNING);
679 679
 		}
680 680
 		$call = "draw_".$this->_library;
681
-		call_user_func_array(array($this,$call), array($file,$fileurl));
681
+		call_user_func_array(array($this, $call), array($file, $fileurl));
682 682
 	}
683 683
 
684 684
 
@@ -690,31 +690,31 @@  discard block
 block discarded – undo
690 690
 	 * @param	string	$fileurl	Url path to show image if saved onto disk
691 691
 	 * @return	void
692 692
 	 */
693
-	private function draw_artichow($file,$fileurl)
693
+	private function draw_artichow($file, $fileurl)
694 694
 	{
695 695
         // phpcs:enable
696 696
 		global $artichow_defaultfont;
697 697
 
698
-		dol_syslog(get_class($this)."::draw_artichow this->type=".join(',',$this->type));
698
+		dol_syslog(get_class($this)."::draw_artichow this->type=".join(',', $this->type));
699 699
 
700
-		if (! defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP',3);
701
-		if (! defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND',2);
702
-		if (! defined('LEGEND_LINE'))       define('LEGEND_LINE',1);
700
+		if (!defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP', 3);
701
+		if (!defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND', 2);
702
+		if (!defined('LEGEND_LINE'))       define('LEGEND_LINE', 1);
703 703
 
704 704
 		// Create graph
705
-		$classname='';
706
-		if (! isset($this->type[0]) || $this->type[0] == 'bars')  $classname='BarPlot';    // Only one type (first one) is supported by artichow
707
-		else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname='LinePlot';
708
-		else $classname='TypeUnknown';
705
+		$classname = '';
706
+		if (!isset($this->type[0]) || $this->type[0] == 'bars')  $classname = 'BarPlot'; // Only one type (first one) is supported by artichow
707
+		else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname = 'LinePlot';
708
+		else $classname = 'TypeUnknown';
709 709
 		include_once ARTICHOW_PATH.$classname.'.class.php';
710 710
 
711 711
 		// Definition de couleurs
712
-		$bgcolor=new Color($this->bgcolor[0],$this->bgcolor[1],$this->bgcolor[2]);
713
-		$bgcolorgrid=new Color($this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
714
-		$colortrans=new Color(0,0,0,100);
715
-		$colorsemitrans=new Color(255,255,255,60);
716
-		$colorgradient= new LinearGradient(new Color(235, 235, 235),new Color(255, 255, 255),0);
717
-		$colorwhite=new Color(255,255,255);
712
+		$bgcolor = new Color($this->bgcolor[0], $this->bgcolor[1], $this->bgcolor[2]);
713
+		$bgcolorgrid = new Color($this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
714
+		$colortrans = new Color(0, 0, 0, 100);
715
+		$colorsemitrans = new Color(255, 255, 255, 60);
716
+		$colorgradient = new LinearGradient(new Color(235, 235, 235), new Color(255, 255, 255), 0);
717
+		$colorwhite = new Color(255, 255, 255);
718 718
 
719 719
 		// Graph
720 720
 		$graph = new Graph($this->width, $this->height);
@@ -733,13 +733,13 @@  discard block
 block discarded – undo
733 733
 		$group = new PlotGroup;
734 734
 		//$group->setSpace(5, 5, 0, 0);
735 735
 
736
-		$paddleft=50;
737
-		$paddright=10;
738
-		$strl=dol_strlen(max(abs($this->MaxValue),abs($this->MinValue)));
736
+		$paddleft = 50;
737
+		$paddright = 10;
738
+		$strl = dol_strlen(max(abs($this->MaxValue), abs($this->MinValue)));
739 739
 		if ($strl > 6) $paddleft += ($strl * 4);
740
-		$group->setPadding($paddleft, $paddright);		// Width on left and right for Y axis values
740
+		$group->setPadding($paddleft, $paddright); // Width on left and right for Y axis values
741 741
 		$group->legend->setSpace(0);
742
-		$group->legend->setPadding(2,2,2,2);
742
+		$group->legend->setPadding(2, 2, 2, 2);
743 743
 		$group->legend->setPosition(null, 0.1);
744 744
 		$group->legend->setBackgroundColor($colorsemitrans);
745 745
 
@@ -750,26 +750,26 @@  discard block
 block discarded – undo
750 750
 		if ($this->hideYGrid)	$group->grid->hideHorizontal(true);
751 751
 
752 752
 		// On boucle sur chaque lot de donnees
753
-		$legends=array();
754
-		$i=0;
755
-		$nblot=count($this->data[0])-1;
753
+		$legends = array();
754
+		$i = 0;
755
+		$nblot = count($this->data[0]) - 1;
756 756
 
757 757
 		while ($i < $nblot)
758 758
 		{
759
-			$x=0;
760
-			$values=array();
761
-			foreach($this->data as $key => $valarray)
759
+			$x = 0;
760
+			$values = array();
761
+			foreach ($this->data as $key => $valarray)
762 762
 			{
763 763
 				$legends[$x] = $valarray[0];
764
-				$values[$x]  = $valarray[$i+1];
764
+				$values[$x]  = $valarray[$i + 1];
765 765
 				$x++;
766 766
 			}
767 767
 
768 768
 			// We fix unknown values to null
769
-			$newvalues=array();
770
-			foreach($values as $val)
769
+			$newvalues = array();
770
+			foreach ($values as $val)
771 771
 			{
772
-				$newvalues[]=(is_numeric($val) ? $val : null);
772
+				$newvalues[] = (is_numeric($val) ? $val : null);
773 773
 			}
774 774
 
775 775
 
@@ -779,14 +779,14 @@  discard block
 block discarded – undo
779 779
 				//print_r($values);
780 780
 				//print '<br>';
781 781
 
782
-				$color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
783
-				$colorbis=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),50);
782
+				$color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
783
+				$colorbis = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 50);
784 784
 
785
-				$colorgrey=new Color(100,100,100);
786
-				$colorborder=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
785
+				$colorgrey = new Color(100, 100, 100);
786
+				$colorborder = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
787 787
 
788
-				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i+1, $nblot);
789
-				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
788
+				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i + 1, $nblot);
789
+				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot - $i - 1) * 5);
790 790
 
791 791
 				$plot->barBorder->setColor($colorgrey);
792 792
 				//$plot->setBarColor($color);
@@ -811,9 +811,9 @@  discard block
 block discarded – undo
811 811
 
812 812
 			if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')
813 813
 			{
814
-				$color=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2],20);
815
-				$colorbis=new Color(min($this->datacolor[$i][0]+20,255),min($this->datacolor[$i][1]+20,255),min($this->datacolor[$i][2]+20,255),60);
816
-				$colorter=new Color(min($this->datacolor[$i][0]+50,255),min($this->datacolor[$i][1]+50,255),min($this->datacolor[$i][2]+50,255),90);
814
+				$color = new Color($this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2], 20);
815
+				$colorbis = new Color(min($this->datacolor[$i][0] + 20, 255), min($this->datacolor[$i][1] + 20, 255), min($this->datacolor[$i][2] + 20, 255), 60);
816
+				$colorter = new Color(min($this->datacolor[$i][0] + 50, 255), min($this->datacolor[$i][1] + 50, 255), min($this->datacolor[$i][2] + 50, 255), 90);
817 817
 
818 818
 				$plot = new LinePlot($newvalues);
819 819
 				//$plot->setSize(1, 0.96);
@@ -859,7 +859,7 @@  discard block
 block discarded – undo
859 859
 		// Generate file
860 860
 		$graph->draw($file);
861 861
 
862
-		$this->stringtoshow='<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'" alt="'.dol_escape_htmltag($this->title?$this->title:$this->YLabel).'">';
862
+		$this->stringtoshow = '<!-- Build using '.$this->_library.' --><img src="'.$fileurl.'" title="'.dol_escape_htmltag($this->title ? $this->title : $this->YLabel).'" alt="'.dol_escape_htmltag($this->title ? $this->title : $this->YLabel).'">';
863 863
 	}
864 864
 
865 865
 
@@ -885,7 +885,7 @@  discard block
 block discarded – undo
885 885
         // phpcs:enable
886 886
 		global $artichow_defaultfont;
887 887
 
888
-		dol_syslog(get_class($this)."::draw_jflot this->type=".join(',',$this->type)." this->MaxValue=".$this->MaxValue);
888
+		dol_syslog(get_class($this)."::draw_jflot this->type=".join(',', $this->type)." this->MaxValue=".$this->MaxValue);
889 889
 
890 890
 		if (empty($this->width) && empty($this->height))
891 891
 		{
@@ -893,87 +893,87 @@  discard block
 block discarded – undo
893 893
 			return;
894 894
 		}
895 895
 
896
-		$legends=array();
897
-		$nblot=count($this->data[0])-1;    // -1 to remove legend
896
+		$legends = array();
897
+		$nblot = count($this->data[0]) - 1; // -1 to remove legend
898 898
 		if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING);
899
-		$firstlot=0;
899
+		$firstlot = 0;
900 900
 		// Works with line but not with bars
901 901
 		//if ($nblot > 2) $firstlot = ($nblot - 2);        // We limit nblot to 2 because jflot can't manage more than 2 bars on same x
902 902
 
903
-		$i=$firstlot;
904
-		$serie=array();
903
+		$i = $firstlot;
904
+		$serie = array();
905 905
 		while ($i < $nblot)	// Loop on each serie
906 906
 		{
907
-			$values=array();	// Array with horizontal y values (specific values of a serie) for each abscisse x
908
-			$serie[$i]="var d".$i." = [];\n";
907
+			$values = array(); // Array with horizontal y values (specific values of a serie) for each abscisse x
908
+			$serie[$i] = "var d".$i." = [];\n";
909 909
 
910 910
 			// Fill array $values
911
-			$x=0;
912
-			foreach($this->data as $valarray)	// Loop on each x
911
+			$x = 0;
912
+			foreach ($this->data as $valarray)	// Loop on each x
913 913
 			{
914 914
 				$legends[$x] = $valarray[0];
915
-				$values[$x]  = (is_numeric($valarray[$i+1]) ? $valarray[$i+1] : null);
915
+				$values[$x]  = (is_numeric($valarray[$i + 1]) ? $valarray[$i + 1] : null);
916 916
 				$x++;
917 917
 			}
918 918
 
919 919
 			// TODO Avoid push by adding generated long array...
920 920
 			if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
921 921
 			{
922
-				foreach($values as $x => $y) {
923
-					if (isset($y)) $serie[$i].='d'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
922
+				foreach ($values as $x => $y) {
923
+					if (isset($y)) $serie[$i] .= 'd'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
924 924
 				}
925 925
 			}
926 926
 			else
927 927
 			{
928
-				foreach($values as $x => $y) {
929
-					if (isset($y)) $serie[$i].='d'.$i.'.push(['.$x.', '.$y.']);'."\n";
928
+				foreach ($values as $x => $y) {
929
+					if (isset($y)) $serie[$i] .= 'd'.$i.'.push(['.$x.', '.$y.']);'."\n";
930 930
 				}
931 931
 			}
932 932
 
933 933
 			unset($values);
934 934
 			$i++;
935 935
 		}
936
-		$tag=dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file),'_',array('-','.'))));
936
+		$tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.'))));
937 937
 
938
-		$this->stringtoshow ='<!-- Build using '.$this->_library.' -->'."\n";
939
-		if (! empty($this->title)) $this->stringtoshow.='<div align="center" class="dolgraphtitle'.(empty($this->cssprefix)?'':' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
940
-		if (! empty($this->shownographyet))
938
+		$this->stringtoshow = '<!-- Build using '.$this->_library.' -->'."\n";
939
+		if (!empty($this->title)) $this->stringtoshow .= '<div align="center" class="dolgraphtitle'.(empty($this->cssprefix) ? '' : ' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
940
+		if (!empty($this->shownographyet))
941 941
 		{
942
-		  $this->stringtoshow.='<div style="width:'.$this->width.'px;height:'.$this->height.'px;" class="nographyet"></div>';
943
-		  $this->stringtoshow.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
942
+		  $this->stringtoshow .= '<div style="width:'.$this->width.'px;height:'.$this->height.'px;" class="nographyet"></div>';
943
+		  $this->stringtoshow .= '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
944 944
 		  return;
945 945
 		}
946
-		$this->stringtoshow.='<div id="placeholder_'.$tag.'" style="width:'.$this->width.'px;height:'.$this->height.'px;" class="dolgraph'.(empty($this->cssprefix)?'':' dolgraph'.$this->cssprefix).'"></div>'."\n";
946
+		$this->stringtoshow .= '<div id="placeholder_'.$tag.'" style="width:'.$this->width.'px;height:'.$this->height.'px;" class="dolgraph'.(empty($this->cssprefix) ? '' : ' dolgraph'.$this->cssprefix).'"></div>'."\n";
947 947
 
948
-		$this->stringtoshow.='<script id="'.$tag.'">'."\n";
949
-		$this->stringtoshow.='$(function () {'."\n";
950
-		$i=$firstlot;
948
+		$this->stringtoshow .= '<script id="'.$tag.'">'."\n";
949
+		$this->stringtoshow .= '$(function () {'."\n";
950
+		$i = $firstlot;
951 951
 		if ($nblot < 0)
952 952
 		{
953
-			$this->stringtoshow.='<!-- No series of data -->';
953
+			$this->stringtoshow .= '<!-- No series of data -->';
954 954
 		}
955 955
 		else
956 956
 		{
957 957
 			while ($i < $nblot)
958 958
 			{
959
-				$this->stringtoshow.=$serie[$i];
959
+				$this->stringtoshow .= $serie[$i];
960 960
 				$i++;
961 961
 			}
962 962
 		}
963
-		$this->stringtoshow.="\n";
963
+		$this->stringtoshow .= "\n";
964 964
 
965 965
 		// Special case for Graph of type 'pie'
966 966
 		if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
967 967
 		{
968
-			$datacolor=array();
969
-			foreach($this->datacolor as $val) $datacolor[]="#".sprintf("%02x%02x%02x",$val[0],$val[1],$val[2]);
968
+			$datacolor = array();
969
+			foreach ($this->datacolor as $val) $datacolor[] = "#".sprintf("%02x%02x%02x", $val[0], $val[1], $val[2]);
970 970
 
971
-			$urltemp='';	// TODO Add support for url link into labels
972
-			$showlegend=$this->showlegend;
973
-			$showpointvalue=$this->showpointvalue;
974
-			$showpercent=$this->showpercent;
971
+			$urltemp = ''; // TODO Add support for url link into labels
972
+			$showlegend = $this->showlegend;
973
+			$showpointvalue = $this->showpointvalue;
974
+			$showpercent = $this->showpercent;
975 975
 
976
-			$this->stringtoshow.= '
976
+			$this->stringtoshow .= '
977 977
 			function plotWithOptions_'.$tag.'() {
978 978
 			$.plot($("#placeholder_'.$tag.'"), d0,
979 979
 			{
@@ -984,7 +984,7 @@  discard block
 block discarded – undo
984 984
 						'.($this->combine ? '
985 985
 						combine: {
986 986
 						 	threshold: '.$this->combine.'
987
-						},' : '') . '
987
+						},' : '').'
988 988
 						label: {
989 989
 							show: true,
990 990
 							radius: 0.9,
@@ -992,15 +992,15 @@  discard block
 block discarded – undo
992 992
 								var percent=Math.round(series.percent);
993 993
 								var number=series.data[0][1];
994 994
 								return \'';
995
-								$this->stringtoshow.='<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
996
-								if ($urltemp) $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
997
-								$this->stringtoshow.='\'+';
998
-								$this->stringtoshow.=($showlegend?'':'label+\' \'+');	// Hide label if already shown in legend
999
-								$this->stringtoshow.=($showpointvalue?'number+':'');
1000
-								$this->stringtoshow.=($showpercent?'\'<br/>\'+percent+\'%\'+':'');
1001
-								$this->stringtoshow.='\'';
1002
-								if ($urltemp) $this->stringtoshow.='</a>';
1003
-								$this->stringtoshow.='</span>\';
995
+								$this->stringtoshow .= '<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
996
+								if ($urltemp) $this->stringtoshow .= '<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
997
+								$this->stringtoshow .= '\'+';
998
+								$this->stringtoshow .= ($showlegend ? '' : 'label+\' \'+'); // Hide label if already shown in legend
999
+								$this->stringtoshow .= ($showpointvalue ? 'number+' : '');
1000
+								$this->stringtoshow .= ($showpercent ? '\'<br/>\'+percent+\'%\'+' : '');
1001
+								$this->stringtoshow .= '\'';
1002
+								if ($urltemp) $this->stringtoshow .= '</a>';
1003
+								$this->stringtoshow .= '</span>\';
1004 1004
 							},
1005 1005
 							background: {
1006 1006
 							opacity: 0.0,
@@ -1017,9 +1017,9 @@  discard block
 block discarded – undo
1017 1017
 			},';
1018 1018
 			if (count($datacolor))
1019 1019
 			{
1020
-				$this->stringtoshow.='colors: '.(! empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
1020
+				$this->stringtoshow .= 'colors: '.(!empty($data['seriescolor']) ? json_encode($data['seriescolor']) : json_encode($datacolor)).',';
1021 1021
 			}
1022
-			$this->stringtoshow.='legend: {show: '.($showlegend?'true':'false').', position: \'ne\' }
1022
+			$this->stringtoshow .= 'legend: {show: '.($showlegend ? 'true' : 'false').', position: \'ne\' }
1023 1023
 		});
1024 1024
 		}'."\n";
1025 1025
 		}
@@ -1028,7 +1028,7 @@  discard block
 block discarded – undo
1028 1028
 		{
1029 1029
 			// Add code to support tooltips
1030 1030
 		    // TODO: remove js css and use graph-tooltip-inner class instead by adding css in each themes
1031
-			$this->stringtoshow.='
1031
+			$this->stringtoshow .= '
1032 1032
 			function showTooltip_'.$tag.'(x, y, contents) {
1033 1033
 				$(\'<div class="graph-tooltip-inner" id="tooltip_'.$tag.'">\' + contents + \'</div>\').css({
1034 1034
 					position: \'absolute\',
@@ -1060,10 +1060,10 @@  discard block
 block discarded – undo
1060 1060
 						var y = item.datapoint[1].toFixed(2);
1061 1061
 						var z = item.series.xaxis.ticks[item.dataIndex].label;
1062 1062
 						';
1063
-						if ($this->showpointvalue > 0) $this->stringtoshow.='
1063
+						if ($this->showpointvalue > 0) $this->stringtoshow .= '
1064 1064
 							showTooltip_'.$tag.'(item.pageX, item.pageY, item.series.label + "<br>" + z + " => " + y);
1065 1065
 						';
1066
-						$this->stringtoshow.='
1066
+						$this->stringtoshow .= '
1067 1067
 					}
1068 1068
 				}
1069 1069
 				else {
@@ -1073,50 +1073,50 @@  discard block
 block discarded – undo
1073 1073
 			});
1074 1074
 			';
1075 1075
 
1076
-			$this->stringtoshow.='var stack = null, steps = false;'."\n";
1076
+			$this->stringtoshow .= 'var stack = null, steps = false;'."\n";
1077 1077
 
1078
-			$this->stringtoshow.='function plotWithOptions_'.$tag.'() {'."\n";
1079
-			$this->stringtoshow.='$.plot($("#placeholder_'.$tag.'"), [ '."\n";
1080
-			$i=$firstlot;
1078
+			$this->stringtoshow .= 'function plotWithOptions_'.$tag.'() {'."\n";
1079
+			$this->stringtoshow .= '$.plot($("#placeholder_'.$tag.'"), [ '."\n";
1080
+			$i = $firstlot;
1081 1081
 			while ($i < $nblot)
1082 1082
 			{
1083
-				if ($i > $firstlot) $this->stringtoshow.=', '."\n";
1084
-				$color=sprintf("%02x%02x%02x",$this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
1085
-				$this->stringtoshow.='{ ';
1086
-				if (! isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
1087
-				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1088
-				$this->stringtoshow.='color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
1083
+				if ($i > $firstlot) $this->stringtoshow .= ', '."\n";
1084
+				$color = sprintf("%02x%02x%02x", $this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]);
1085
+				$this->stringtoshow .= '{ ';
1086
+				if (!isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.($i == $firstlot ? 'center' : 'left').'", barWidth: 0.5 }, ';
1087
+				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow .= 'lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1088
+				$this->stringtoshow .= 'color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
1089 1089
 				$i++;
1090 1090
 			}
1091 1091
 			// shadowSize: 0 -> Drawing is faster without shadows
1092
-			$this->stringtoshow.="\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6 } }'."\n";
1092
+			$this->stringtoshow .= "\n".' ], { series: { shadowSize: 0, stack: stack, lines: { fill: false, steps: steps }, bars: { barWidth: 0.6 } }'."\n";
1093 1093
 
1094 1094
 			// Xaxis
1095
-			$this->stringtoshow.=', xaxis: { ticks: ['."\n";
1096
-			$x=0;
1097
-			foreach($this->data as $key => $valarray)
1095
+			$this->stringtoshow .= ', xaxis: { ticks: ['."\n";
1096
+			$x = 0;
1097
+			foreach ($this->data as $key => $valarray)
1098 1098
 			{
1099
-				if ($x > 0) $this->stringtoshow.=', '."\n";
1100
-				$this->stringtoshow.= ' ['.$x.', "'.$valarray[0].'"]';
1099
+				if ($x > 0) $this->stringtoshow .= ', '."\n";
1100
+				$this->stringtoshow .= ' ['.$x.', "'.$valarray[0].'"]';
1101 1101
 				$x++;
1102 1102
 			}
1103
-			$this->stringtoshow.='] }'."\n";
1103
+			$this->stringtoshow .= '] }'."\n";
1104 1104
 
1105 1105
 			// Yaxis
1106
-			$this->stringtoshow.=', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
1106
+			$this->stringtoshow .= ', yaxis: { min: '.$this->MinValue.', max: '.($this->MaxValue).' }'."\n";
1107 1107
 
1108 1108
 			// Background color
1109
-			$color1=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[0],$this->bgcolorgrid[2]);
1110
-			$color2=sprintf("%02x%02x%02x",$this->bgcolorgrid[0],$this->bgcolorgrid[1],$this->bgcolorgrid[2]);
1111
-			$this->stringtoshow.=', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
1109
+			$color1 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[0], $this->bgcolorgrid[2]);
1110
+			$color2 = sprintf("%02x%02x%02x", $this->bgcolorgrid[0], $this->bgcolorgrid[1], $this->bgcolorgrid[2]);
1111
+			$this->stringtoshow .= ', grid: { hoverable: true, backgroundColor: { colors: ["#'.$color1.'", "#'.$color2.'"] }, borderWidth: 1, borderColor: \'#e6e6e6\', tickColor  : \'#e6e6e6\' }'."\n";
1112 1112
 			//$this->stringtoshow.=', shadowSize: 20'."\n";    TODO Uncommet this
1113
-			$this->stringtoshow.='});'."\n";
1114
-			$this->stringtoshow.='}'."\n";
1113
+			$this->stringtoshow .= '});'."\n";
1114
+			$this->stringtoshow .= '}'."\n";
1115 1115
 		}
1116 1116
 
1117
-		$this->stringtoshow.='plotWithOptions_'.$tag.'();'."\n";
1118
-		$this->stringtoshow.='});'."\n";
1119
-		$this->stringtoshow.='</script>'."\n";
1117
+		$this->stringtoshow .= 'plotWithOptions_'.$tag.'();'."\n";
1118
+		$this->stringtoshow .= '});'."\n";
1119
+		$this->stringtoshow .= '</script>'."\n";
1120 1120
 	}
1121 1121
 
1122 1122
 
@@ -1127,14 +1127,14 @@  discard block
 block discarded – undo
1127 1127
 	 * @param	int			$shownographyet 	Show graph to say there is not enough data
1128 1128
 	 * @return	string							HTML string to show graph
1129 1129
 	 */
1130
-	function show($shownographyet=0)
1130
+	function show($shownographyet = 0)
1131 1131
 	{
1132 1132
 		global $langs;
1133 1133
 
1134 1134
 		if ($shownographyet)
1135 1135
 		{
1136
-			$s= '<div class="nographyet" style="width:'.(preg_match('/%/',$this->width)?$this->width:$this->width.'px').'; height:'.(preg_match('/%/',$this->height)?$this->height:$this->height.'px').';"></div>';
1137
-			$s.='<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
1136
+			$s = '<div class="nographyet" style="width:'.(preg_match('/%/', $this->width) ? $this->width : $this->width.'px').'; height:'.(preg_match('/%/', $this->height) ? $this->height : $this->height.'px').';"></div>';
1137
+			$s .= '<div class="nographyettext">'.$langs->trans("NotEnoughDataYet").'</div>';
1138 1138
 			return $s;
1139 1139
 		}
1140 1140
 
@@ -1149,18 +1149,18 @@  discard block
 block discarded – undo
1149 1149
 	 * @param	string	$defaultsize	Value we want as default size
1150 1150
 	 * @return	int						Value of width or height to use by default
1151 1151
 	 */
1152
-	static function getDefaultGraphSizeForStats($direction,$defaultsize='')
1152
+	static function getDefaultGraphSizeForStats($direction, $defaultsize = '')
1153 1153
 	{
1154 1154
 		global $conf;
1155 1155
 
1156 1156
 		if ($direction == 'width')
1157 1157
 		{
1158 1158
 			if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500');
1159
-			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
1159
+			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width'] - 40));
1160 1160
 		}
1161 1161
 		if ($direction == 'height')
1162 1162
 		{
1163
-			return (empty($conf->dol_optimize_smallscreen)?($defaultsize?$defaultsize:'200'):'160');
1163
+			return (empty($conf->dol_optimize_smallscreen) ? ($defaultsize ? $defaultsize : '200') : '160');
1164 1164
 		}
1165 1165
 		return 0;
1166 1166
 	}
Please login to merge, or discard this patch.
Braces   +143 added lines, -59 removed lines patch added patch discarded remove patch
@@ -103,7 +103,9 @@  discard block
 block discarded – undo
103 103
 			$isgdinstalled=0;
104 104
 			foreach ($modules_list as $module)
105 105
 			{
106
-				if ($module == 'gd') $isgdinstalled=1;
106
+				if ($module == 'gd') {
107
+				    $isgdinstalled=1;
108
+				}
107 109
 			}
108 110
 			if (! $isgdinstalled)
109 111
 			{
@@ -120,9 +122,15 @@  discard block
 block discarded – undo
120 122
 		if (is_readable($color_file))
121 123
 		{
122 124
 			include_once $color_file;
123
-			if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor;
124
-			if (isset($theme_datacolor))   $this->datacolor   = $theme_datacolor;
125
-			if (isset($theme_bgcolor))     $this->bgcolor     = $theme_bgcolor;
125
+			if (isset($theme_bordercolor)) {
126
+			    $this->bordercolor = $theme_bordercolor;
127
+			}
128
+			if (isset($theme_datacolor)) {
129
+			    $this->datacolor   = $theme_datacolor;
130
+			}
131
+			if (isset($theme_bgcolor)) {
132
+			    $this->bgcolor     = $theme_bgcolor;
133
+			}
126 134
 		}
127 135
 		//print 'bgcolor: '.join(',',$this->bgcolor).'<br>';
128 136
 	}
@@ -493,13 +501,11 @@  discard block
 block discarded – undo
493 501
 			{
494 502
 				//print 'ee'.join(',',$theme_bgcoloronglet);
495 503
 				$this->bgcolor = $theme_bgcoloronglet;
496
-			}
497
-			else
504
+			} else
498 505
 			{
499 506
 				$this->bgcolor = $theme_bgcolor;
500 507
 			}
501
-		}
502
-		else
508
+		} else
503 509
 		{
504 510
 			$this->bgcolor = $bg_color;
505 511
 		}
@@ -523,13 +529,11 @@  discard block
 block discarded – undo
523 529
 			{
524 530
 				//print 'ee'.join(',',$theme_bgcoloronglet);
525 531
 				$this->bgcolorgrid = $theme_bgcoloronglet;
526
-			}
527
-			else
532
+			} else
528 533
 			{
529 534
 				$this->bgcolorgrid = $theme_bgcolor;
530 535
 			}
531
-		}
532
-		else
536
+		} else
533 537
 		{
534 538
 			$this->bgcolorgrid = $bg_colorgrid;
535 539
 		}
@@ -611,7 +615,9 @@  discard block
 block discarded – undo
611 615
 	{
612 616
         // phpcs:enable
613 617
 		$max = $this->GetMaxValueInData();
614
-		if ($max != 0) $max++;
618
+		if ($max != 0) {
619
+		    $max++;
620
+		}
615 621
 		$size=dol_strlen(abs(ceil($max)));
616 622
 		$factor=1;
617 623
 		for ($i=0; $i < ($size-1); $i++)
@@ -620,7 +626,9 @@  discard block
 block discarded – undo
620 626
 		}
621 627
 
622 628
 		$res=0;
623
-		if (is_numeric($max)) $res=ceil($max/$factor)*$factor;
629
+		if (is_numeric($max)) {
630
+		    $res=ceil($max/$factor)*$factor;
631
+		}
624 632
 
625 633
 		//print "max=".$max." res=".$res;
626 634
 		return $res;
@@ -636,8 +644,12 @@  discard block
 block discarded – undo
636 644
 	{
637 645
         // phpcs:enable
638 646
 		$min = $this->GetMinValueInData();
639
-		if ($min == '') $min=0;
640
-		if ($min != 0) $min--;
647
+		if ($min == '') {
648
+		    $min=0;
649
+		}
650
+		if ($min != 0) {
651
+		    $min--;
652
+		}
641 653
 		$size=dol_strlen(abs(floor($min)));
642 654
 		$factor=1;
643 655
 		for ($i=0; $i < ($size-1); $i++)
@@ -697,15 +709,27 @@  discard block
 block discarded – undo
697 709
 
698 710
 		dol_syslog(get_class($this)."::draw_artichow this->type=".join(',',$this->type));
699 711
 
700
-		if (! defined('SHADOW_RIGHT_TOP'))  define('SHADOW_RIGHT_TOP',3);
701
-		if (! defined('LEGEND_BACKGROUND')) define('LEGEND_BACKGROUND',2);
702
-		if (! defined('LEGEND_LINE'))       define('LEGEND_LINE',1);
712
+		if (! defined('SHADOW_RIGHT_TOP')) {
713
+		    define('SHADOW_RIGHT_TOP',3);
714
+		}
715
+		if (! defined('LEGEND_BACKGROUND')) {
716
+		    define('LEGEND_BACKGROUND',2);
717
+		}
718
+		if (! defined('LEGEND_LINE')) {
719
+		    define('LEGEND_LINE',1);
720
+		}
703 721
 
704 722
 		// Create graph
705 723
 		$classname='';
706
-		if (! isset($this->type[0]) || $this->type[0] == 'bars')  $classname='BarPlot';    // Only one type (first one) is supported by artichow
707
-		else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') $classname='LinePlot';
708
-		else $classname='TypeUnknown';
724
+		if (! isset($this->type[0]) || $this->type[0] == 'bars') {
725
+		    $classname='BarPlot';
726
+		}
727
+		// Only one type (first one) is supported by artichow
728
+		else if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') {
729
+		    $classname='LinePlot';
730
+		} else {
731
+		    $classname='TypeUnknown';
732
+		}
709 733
 		include_once ARTICHOW_PATH.$classname.'.class.php';
710 734
 
711 735
 		// Definition de couleurs
@@ -727,8 +751,11 @@  discard block
 block discarded – undo
727 751
 			$graph->title->setFont(new $artichow_defaultfont(10));
728 752
 		}
729 753
 
730
-		if (is_array($this->bgcolor)) $graph->setBackgroundColor($bgcolor);
731
-		else $graph->setBackgroundGradient($colorgradient);
754
+		if (is_array($this->bgcolor)) {
755
+		    $graph->setBackgroundColor($bgcolor);
756
+		} else {
757
+		    $graph->setBackgroundGradient($colorgradient);
758
+		}
732 759
 
733 760
 		$group = new PlotGroup;
734 761
 		//$group->setSpace(5, 5, 0, 0);
@@ -736,18 +763,27 @@  discard block
 block discarded – undo
736 763
 		$paddleft=50;
737 764
 		$paddright=10;
738 765
 		$strl=dol_strlen(max(abs($this->MaxValue),abs($this->MinValue)));
739
-		if ($strl > 6) $paddleft += ($strl * 4);
766
+		if ($strl > 6) {
767
+		    $paddleft += ($strl * 4);
768
+		}
740 769
 		$group->setPadding($paddleft, $paddright);		// Width on left and right for Y axis values
741 770
 		$group->legend->setSpace(0);
742 771
 		$group->legend->setPadding(2,2,2,2);
743 772
 		$group->legend->setPosition(null, 0.1);
744 773
 		$group->legend->setBackgroundColor($colorsemitrans);
745 774
 
746
-		if (is_array($this->bgcolorgrid)) $group->grid->setBackgroundColor($bgcolorgrid);
747
-		else $group->grid->setBackgroundColor($colortrans);
775
+		if (is_array($this->bgcolorgrid)) {
776
+		    $group->grid->setBackgroundColor($bgcolorgrid);
777
+		} else {
778
+		    $group->grid->setBackgroundColor($colortrans);
779
+		}
748 780
 
749
-		if ($this->hideXGrid)	$group->grid->hideVertical(true);
750
-		if ($this->hideYGrid)	$group->grid->hideHorizontal(true);
781
+		if ($this->hideXGrid) {
782
+		    $group->grid->hideVertical(true);
783
+		}
784
+		if ($this->hideYGrid) {
785
+		    $group->grid->hideHorizontal(true);
786
+		}
751 787
 
752 788
 		// On boucle sur chaque lot de donnees
753 789
 		$legends=array();
@@ -785,17 +821,29 @@  discard block
 block discarded – undo
785 821
 				$colorgrey=new Color(100,100,100);
786 822
 				$colorborder=new Color($this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
787 823
 
788
-				if ($this->mode == 'side')  $plot = new BarPlot($newvalues, $i+1, $nblot);
789
-				if ($this->mode == 'depth') $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
824
+				if ($this->mode == 'side') {
825
+				    $plot = new BarPlot($newvalues, $i+1, $nblot);
826
+				}
827
+				if ($this->mode == 'depth') {
828
+				    $plot = new BarPlot($newvalues, 1, 1, ($nblot-$i-1)*5);
829
+				}
790 830
 
791 831
 				$plot->barBorder->setColor($colorgrey);
792 832
 				//$plot->setBarColor($color);
793 833
 				$plot->setBarGradient(new LinearGradient($colorbis, $color, 90));
794 834
 
795
-				if ($this->mode == 'side')  $plot->setBarPadding(0.1, 0.1);
796
-				if ($this->mode == 'depth') $plot->setBarPadding(0.1, 0.4);
797
-				if ($this->mode == 'side')  $plot->setBarSpace(5);
798
-				if ($this->mode == 'depth') $plot->setBarSpace(2);
835
+				if ($this->mode == 'side') {
836
+				    $plot->setBarPadding(0.1, 0.1);
837
+				}
838
+				if ($this->mode == 'depth') {
839
+				    $plot->setBarPadding(0.1, 0.4);
840
+				}
841
+				if ($this->mode == 'side') {
842
+				    $plot->setBarSpace(5);
843
+				}
844
+				if ($this->mode == 'depth') {
845
+				    $plot->setBarSpace(2);
846
+				}
799 847
 
800 848
 				$plot->barShadow->setSize($this->SetShading);
801 849
 				$plot->barShadow->setPosition(SHADOW_RIGHT_TOP);
@@ -840,8 +888,12 @@  discard block
 block discarded – undo
840 888
 			// solve a bug in Artichow with UTF8
841 889
 			if (count($this->Legend))
842 890
 			{
843
-				if ($this->type[0] == 'bars')  										$group->legend->add($plot, $this->Legend[$i], LEGEND_BACKGROUND);
844
-				if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint')	$group->legend->add($plot, $this->Legend[$i], LEGEND_LINE);
891
+				if ($this->type[0] == 'bars') {
892
+				    $group->legend->add($plot, $this->Legend[$i], LEGEND_BACKGROUND);
893
+				}
894
+				if ($this->type[0] == 'lines' || $this->type[0] == 'linesnopoint') {
895
+				    $group->legend->add($plot, $this->Legend[$i], LEGEND_LINE);
896
+				}
845 897
 			}
846 898
 			$group->add($plot);
847 899
 
@@ -852,7 +904,9 @@  discard block
 block discarded – undo
852 904
 		$group->axis->bottom->label->setFont(new $artichow_defaultfont(7));
853 905
 
854 906
 		//print $group->axis->bottom->getLabelNumber();
855
-		if ($this->labelInterval > 0) $group->axis->bottom->setLabelInterval($this->labelInterval);
907
+		if ($this->labelInterval > 0) {
908
+		    $group->axis->bottom->setLabelInterval($this->labelInterval);
909
+		}
856 910
 
857 911
 		$graph->add($group);
858 912
 
@@ -895,23 +949,30 @@  discard block
 block discarded – undo
895 949
 
896 950
 		$legends=array();
897 951
 		$nblot=count($this->data[0])-1;    // -1 to remove legend
898
-		if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING);
952
+		if ($nblot < 0) {
953
+		    dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING);
954
+		}
899 955
 		$firstlot=0;
900 956
 		// Works with line but not with bars
901 957
 		//if ($nblot > 2) $firstlot = ($nblot - 2);        // We limit nblot to 2 because jflot can't manage more than 2 bars on same x
902 958
 
903 959
 		$i=$firstlot;
904 960
 		$serie=array();
905
-		while ($i < $nblot)	// Loop on each serie
961
+		while ($i < $nblot) {
962
+		    // Loop on each serie
906 963
 		{
907
-			$values=array();	// Array with horizontal y values (specific values of a serie) for each abscisse x
964
+			$values=array();
965
+		}
966
+		// Array with horizontal y values (specific values of a serie) for each abscisse x
908 967
 			$serie[$i]="var d".$i." = [];\n";
909 968
 
910 969
 			// Fill array $values
911 970
 			$x=0;
912
-			foreach($this->data as $valarray)	// Loop on each x
971
+			foreach($this->data as $valarray) {
972
+			    // Loop on each x
913 973
 			{
914 974
 				$legends[$x] = $valarray[0];
975
+			}
915 976
 				$values[$x]  = (is_numeric($valarray[$i+1]) ? $valarray[$i+1] : null);
916 977
 				$x++;
917 978
 			}
@@ -920,13 +981,16 @@  discard block
 block discarded – undo
920 981
 			if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
921 982
 			{
922 983
 				foreach($values as $x => $y) {
923
-					if (isset($y)) $serie[$i].='d'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
984
+					if (isset($y)) {
985
+					    $serie[$i].='d'.$i.'.push({"label":"'.dol_escape_js($legends[$x]).'", "data":'.$y.'});'."\n";
986
+					}
924 987
 				}
925
-			}
926
-			else
988
+			} else
927 989
 			{
928 990
 				foreach($values as $x => $y) {
929
-					if (isset($y)) $serie[$i].='d'.$i.'.push(['.$x.', '.$y.']);'."\n";
991
+					if (isset($y)) {
992
+					    $serie[$i].='d'.$i.'.push(['.$x.', '.$y.']);'."\n";
993
+					}
930 994
 				}
931 995
 			}
932 996
 
@@ -936,7 +1000,9 @@  discard block
 block discarded – undo
936 1000
 		$tag=dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file),'_',array('-','.'))));
937 1001
 
938 1002
 		$this->stringtoshow ='<!-- Build using '.$this->_library.' -->'."\n";
939
-		if (! empty($this->title)) $this->stringtoshow.='<div align="center" class="dolgraphtitle'.(empty($this->cssprefix)?'':' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
1003
+		if (! empty($this->title)) {
1004
+		    $this->stringtoshow.='<div align="center" class="dolgraphtitle'.(empty($this->cssprefix)?'':' dolgraphtitle'.$this->cssprefix).'">'.$this->title.'</div>';
1005
+		}
940 1006
 		if (! empty($this->shownographyet))
941 1007
 		{
942 1008
 		  $this->stringtoshow.='<div style="width:'.$this->width.'px;height:'.$this->height.'px;" class="nographyet"></div>';
@@ -951,8 +1017,7 @@  discard block
 block discarded – undo
951 1017
 		if ($nblot < 0)
952 1018
 		{
953 1019
 			$this->stringtoshow.='<!-- No series of data -->';
954
-		}
955
-		else
1020
+		} else
956 1021
 		{
957 1022
 			while ($i < $nblot)
958 1023
 			{
@@ -966,7 +1031,9 @@  discard block
 block discarded – undo
966 1031
 		if (isset($this->type[$firstlot]) && $this->type[$firstlot] == 'pie')
967 1032
 		{
968 1033
 			$datacolor=array();
969
-			foreach($this->datacolor as $val) $datacolor[]="#".sprintf("%02x%02x%02x",$val[0],$val[1],$val[2]);
1034
+			foreach($this->datacolor as $val) {
1035
+			    $datacolor[]="#".sprintf("%02x%02x%02x",$val[0],$val[1],$val[2]);
1036
+			}
970 1037
 
971 1038
 			$urltemp='';	// TODO Add support for url link into labels
972 1039
 			$showlegend=$this->showlegend;
@@ -993,13 +1060,17 @@  discard block
 block discarded – undo
993 1060
 								var number=series.data[0][1];
994 1061
 								return \'';
995 1062
 								$this->stringtoshow.='<span style="font-size:8pt;text-align:center;padding:2px;color:black;">';
996
-								if ($urltemp) $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
1063
+								if ($urltemp) {
1064
+								    $this->stringtoshow.='<a style="color: #FFFFFF;" border="0" href="'.$urltemp.'">';
1065
+								}
997 1066
 								$this->stringtoshow.='\'+';
998 1067
 								$this->stringtoshow.=($showlegend?'':'label+\' \'+');	// Hide label if already shown in legend
999 1068
 								$this->stringtoshow.=($showpointvalue?'number+':'');
1000 1069
 								$this->stringtoshow.=($showpercent?'\'<br/>\'+percent+\'%\'+':'');
1001 1070
 								$this->stringtoshow.='\'';
1002
-								if ($urltemp) $this->stringtoshow.='</a>';
1071
+								if ($urltemp) {
1072
+								    $this->stringtoshow.='</a>';
1073
+								}
1003 1074
 								$this->stringtoshow.='</span>\';
1004 1075
 							},
1005 1076
 							background: {
@@ -1060,9 +1131,11 @@  discard block
 block discarded – undo
1060 1131
 						var y = item.datapoint[1].toFixed(2);
1061 1132
 						var z = item.series.xaxis.ticks[item.dataIndex].label;
1062 1133
 						';
1063
-						if ($this->showpointvalue > 0) $this->stringtoshow.='
1134
+						if ($this->showpointvalue > 0) {
1135
+						    $this->stringtoshow.='
1064 1136
 							showTooltip_'.$tag.'(item.pageX, item.pageY, item.series.label + "<br>" + z + " => " + y);
1065 1137
 						';
1138
+						}
1066 1139
 						$this->stringtoshow.='
1067 1140
 					}
1068 1141
 				}
@@ -1080,11 +1153,17 @@  discard block
 block discarded – undo
1080 1153
 			$i=$firstlot;
1081 1154
 			while ($i < $nblot)
1082 1155
 			{
1083
-				if ($i > $firstlot) $this->stringtoshow.=', '."\n";
1156
+				if ($i > $firstlot) {
1157
+				    $this->stringtoshow.=', '."\n";
1158
+				}
1084 1159
 				$color=sprintf("%02x%02x%02x",$this->datacolor[$i][0],$this->datacolor[$i][1],$this->datacolor[$i][2]);
1085 1160
 				$this->stringtoshow.='{ ';
1086
-				if (! isset($this->type[$i]) || $this->type[$i] == 'bars') $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
1087
-				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1161
+				if (! isset($this->type[$i]) || $this->type[$i] == 'bars') {
1162
+				    $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, ';
1163
+				}
1164
+				if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) {
1165
+				    $this->stringtoshow.='lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, ';
1166
+				}
1088 1167
 				$this->stringtoshow.='color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }';
1089 1168
 				$i++;
1090 1169
 			}
@@ -1096,7 +1175,9 @@  discard block
 block discarded – undo
1096 1175
 			$x=0;
1097 1176
 			foreach($this->data as $key => $valarray)
1098 1177
 			{
1099
-				if ($x > 0) $this->stringtoshow.=', '."\n";
1178
+				if ($x > 0) {
1179
+				    $this->stringtoshow.=', '."\n";
1180
+				}
1100 1181
 				$this->stringtoshow.= ' ['.$x.', "'.$valarray[0].'"]';
1101 1182
 				$x++;
1102 1183
 			}
@@ -1155,8 +1236,11 @@  discard block
 block discarded – undo
1155 1236
 
1156 1237
 		if ($direction == 'width')
1157 1238
 		{
1158
-			if (empty($conf->dol_optimize_smallscreen)) return ($defaultsize ? $defaultsize : '500');
1159
-			else return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
1239
+			if (empty($conf->dol_optimize_smallscreen)) {
1240
+			    return ($defaultsize ? $defaultsize : '500');
1241
+			} else {
1242
+			    return (empty($_SESSION['dol_screen_width']) ? '280' : ($_SESSION['dol_screen_width']-40));
1243
+			}
1160 1244
 		}
1161 1245
 		if ($direction == 'height')
1162 1246
 		{
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/extrafields.class.php 3 patches
Indentation   +1967 added lines, -1967 removed lines patch added patch discarded remove patch
@@ -37,2020 +37,2020 @@
 block discarded – undo
37 37
  */
38 38
 class ExtraFields
39 39
 {
40
-	/**
40
+    /**
41 41
      * @var DoliDB Database handler.
42 42
      */
43 43
     public $db;
44 44
 
45
-	// type of element (for what object is the extrafield)
46
-	// @deprecated
47
-	var $attribute_elementtype;
48
-	// Array with type of the extra field
49
-	// @deprecated
50
-	var $attribute_type;
51
-	// Array with label of extra field
52
-	// @deprecated
53
-	var $attribute_label;
54
-	// Array with size of extra field
55
-	// @deprecated
56
-	var $attribute_size;
57
-	// array with list of possible values for some types of extra fields
58
-	// @deprecated
59
-	var $attribute_choice;
60
-	// Array to store compute formula for computed fields
61
-	// @deprecated
62
-	var $attribute_computed;
63
-	// Array to store default value
64
-	// @deprecated
65
-	var $attribute_default;
66
-	// Array to store if attribute is unique or not
67
-	// @deprecated
68
-	var $attribute_unique;
69
-	// Array to store if attribute is required or not
70
-	// @deprecated
71
-	var $attribute_required;
72
-	// Array to store parameters of attribute (used in select type)
73
-	// @deprecated
74
-	var $attribute_param;
75
-	// Array to store position of attribute
76
-	// @deprecated
77
-	var $attribute_pos;
78
-	// Array to store if attribute is editable regardless of the document status
79
-	// @deprecated
80
-	var $attribute_alwayseditable;
81
-	// Array to store permission to check
82
-	// @deprecated
83
-	var $attribute_perms;
84
-	// Array to store language file to translate label of values
85
-	// @deprecated
86
-	var $attribute_langfile;
87
-	// Array to store if field is visible by default on list
88
-	// @deprecated
89
-	var $attribute_list;
90
-
91
-	// New array to store extrafields definition
92
-	var $attributes;
93
-
94
-	/**
95
-	 * @var string Error code (or message)
96
-	 */
97
-	public $error='';
98
-
99
-	var $errno;
100
-
101
-
102
-	public static $type2label=array(
103
-	'varchar'=>'String',
104
-	'text'=>'TextLong',
105
-	'html'=>'HtmlText',
106
-	'int'=>'Int',
107
-	'double'=>'Float',
108
-	'date'=>'Date',
109
-	'datetime'=>'DateAndTime',
110
-	'boolean'=>'Boolean',
111
-	'price'=>'ExtrafieldPrice',
112
-	'phone'=>'ExtrafieldPhone',
113
-	'mail'=>'ExtrafieldMail',
114
-	'url'=>'ExtrafieldUrl',
115
-	'password' => 'ExtrafieldPassword',
116
-	'select' => 'ExtrafieldSelect',
117
-	'sellist' => 'ExtrafieldSelectList',
118
-	'radio' => 'ExtrafieldRadio',
119
-	'checkbox' => 'ExtrafieldCheckBox',
120
-	'chkbxlst' => 'ExtrafieldCheckBoxFromList',
121
-	'link' => 'ExtrafieldLink',
122
-	'separate' => 'ExtrafieldSeparator',
123
-	);
124
-
125
-
126
-	/**
127
-	 *	Constructor
128
-	 *
129
-	 *  @param		DoliDB		$db      Database handler
130
-	*/
131
-	function __construct($db)
132
-	{
133
-		$this->db = $db;
134
-		$this->error = array();
135
-		$this->attributes = array();
136
-
137
-		// For old usage
138
-		$this->attribute_elementtype = array();
139
-		$this->attribute_type = array();
140
-		$this->attribute_label = array();
141
-		$this->attribute_size = array();
142
-		$this->attribute_computed = array();
143
-		$this->attribute_default = array();
144
-		$this->attribute_unique = array();
145
-		$this->attribute_required = array();
146
-		$this->attribute_perms = array();
147
-		$this->attribute_langfile = array();
148
-		$this->attribute_list = array();
149
-	}
150
-
151
-	/**
152
-	 *  Add a new extra field parameter
153
-	 *
154
-	 *  @param	string			$attrname           Code of attribute
155
-	 *  @param  string			$label              label of attribute
156
-	 *  @param  int				$type               Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...)
157
-	 *  @param  int				$pos                Position of attribute
158
-	 *  @param  string			$size               Size/length of attribute
159
-	 *  @param  string			$elementtype        Element type. Same value than object->table_element (Example 'member', 'product', 'thirdparty', ...)
160
-	 *  @param	int				$unique				Is field unique or not
161
-	 *  @param	int				$required			Is field required or not
162
-	 *  @param	string			$default_value		Defaulted value (In database. use the default_value feature for default value on screen. Example: '', '0', 'null', 'avalue')
163
-	 *  @param  array|string	$param				Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
164
-	 *  @param  int				$alwayseditable		Is attribute always editable regardless of the document status
165
-	 *  @param	string			$perms				Permission to check
166
-	 *  @param	string			$list				Visibilty ('0'=never visible, '1'=visible on list+forms, '2'=list only, '3'=form only or 'eval string')
167
-	 *  @param	string			$help				Text with help tooltip
168
-	 *  @param  string  		$computed           Computed value
169
-	 *  @param  string  		$entity    		 	Entity of extrafields (for multicompany modules)
170
-	 *  @param  string  		$langfile  		 	Language file
171
-	 *  @param  string  		$enabled  		 	Condition to have the field enabled or not
172
-	 *  @return int      							<=0 if KO, >0 if OK
173
-	 */
174
-	function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $computed='', $entity='', $langfile='', $enabled='1')
175
-	{
176
-		if (empty($attrname)) return -1;
177
-		if (empty($label)) return -1;
178
-
179
-		if ($elementtype == 'thirdparty') $elementtype='societe';
180
-		if ($elementtype == 'contact') $elementtype='socpeople';
181
-
182
-		// Create field into database except for separator type which is not stored in database
183
-		if ($type != 'separate')
184
-		{
185
-			$result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
186
-		}
187
-		$err1=$this->errno;
188
-		if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate')
189
-		{
190
-			// Add declaration of field into table
191
-			$result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled);
192
-			$err2=$this->errno;
193
-			if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS'))
194
-			{
195
-				$this->error='';
196
-				$this->errno=0;
197
-				return 1;
198
-			}
199
-			else return -2;
200
-		}
201
-		else
202
-		{
203
-			return -1;
204
-		}
205
-	}
206
-
207
-	/**
208
-	 *	Add a new optional attribute.
209
-	 *  This is a private method. For public method, use addExtraField.
210
-	 *
211
-	 *	@param	string	$attrname			code of attribute
212
-	 *  @param	int		$type				Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
213
-	 *  @param	string	$length				Size/length of attribute ('5', '24,8', ...)
214
-	 *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', 'contact', ...)
215
-	 *  @param	int		$unique				Is field unique or not
216
-	 *  @param	int		$required			Is field required or not
217
-	 *  @param  string  $default_value		Default value for field (in database)
218
-	 *  @param  array	$param				Params for field  (ex for select list : array('options'=>array('value'=>'label of option'))
219
-	 *  @param	string	$perms				Permission
220
-	 *	@param	string	$list				Into list view by default
221
-	 *  @param  string  $computed           Computed value
222
-	 *  @return int      	           		<=0 if KO, >0 if OK
223
-	 */
224
-	private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list='0', $computed='')
225
-	{
226
-		if ($elementtype == 'thirdparty') $elementtype='societe';
227
-		if ($elementtype == 'contact') $elementtype='socpeople';
228
-
229
-		$table=$elementtype.'_extrafields';
230
-		if ($elementtype == 'categorie') $table='categories_extrafields';
231
-
232
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/",$attrname) && ! is_numeric($attrname))
233
-		{
234
-			if ($type=='boolean') {
235
-				$typedb='int';
236
-				$lengthdb='1';
237
-			} elseif($type=='price') {
238
-				$typedb='double';
239
-				$lengthdb='24,8';
240
-			} elseif($type=='phone') {
241
-				$typedb='varchar';
242
-				$lengthdb='20';
243
-			} elseif($type=='mail') {
244
-				$typedb='varchar';
245
-				$lengthdb='128';
246
-			} elseif($type=='url') {
247
-				$typedb='varchar';
248
-				$lengthdb='255';
249
-			} elseif (($type=='select') || ($type=='sellist') || ($type=='radio') ||($type=='checkbox') ||($type=='chkbxlst')){
250
-				$typedb='varchar';
251
-				$lengthdb='255';
252
-			} elseif ($type=='link') {
253
-				$typedb='int';
254
-				$lengthdb='11';
255
-			} elseif ($type=='html') {
256
-				$typedb='text';
257
-				$lengthdb=$length;
258
-			} elseif($type=='password') {
259
-				$typedb='varchar';
260
-				$lengthdb='128';
261
-			} else {
262
-				$typedb=$type;
263
-				$lengthdb=$length;
264
-				if ($type == 'varchar' && empty($lengthdb)) $lengthdb='255';
265
-			}
266
-			$field_desc = array(
267
-				'type'=>$typedb,
268
-				'value'=>$lengthdb,
269
-				'null'=>($required?'NOT NULL':'NULL'),
270
-				'default' => $default_value
271
-			);
272
-
273
-			$result=$this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
274
-			if ($result > 0)
275
-			{
276
-				if ($unique)
277
-				{
278
-					$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
279
-					$resql=$this->db->query($sql,1,'dml');
280
-				}
281
-				return 1;
282
-			}
283
-			else
284
-			{
285
-				$this->error=$this->db->lasterror();
286
-				$this->errno=$this->db->lasterrno();
287
-				return -1;
288
-			}
289
-		}
290
-		else
291
-		{
292
-			return 0;
293
-		}
294
-	}
45
+    // type of element (for what object is the extrafield)
46
+    // @deprecated
47
+    var $attribute_elementtype;
48
+    // Array with type of the extra field
49
+    // @deprecated
50
+    var $attribute_type;
51
+    // Array with label of extra field
52
+    // @deprecated
53
+    var $attribute_label;
54
+    // Array with size of extra field
55
+    // @deprecated
56
+    var $attribute_size;
57
+    // array with list of possible values for some types of extra fields
58
+    // @deprecated
59
+    var $attribute_choice;
60
+    // Array to store compute formula for computed fields
61
+    // @deprecated
62
+    var $attribute_computed;
63
+    // Array to store default value
64
+    // @deprecated
65
+    var $attribute_default;
66
+    // Array to store if attribute is unique or not
67
+    // @deprecated
68
+    var $attribute_unique;
69
+    // Array to store if attribute is required or not
70
+    // @deprecated
71
+    var $attribute_required;
72
+    // Array to store parameters of attribute (used in select type)
73
+    // @deprecated
74
+    var $attribute_param;
75
+    // Array to store position of attribute
76
+    // @deprecated
77
+    var $attribute_pos;
78
+    // Array to store if attribute is editable regardless of the document status
79
+    // @deprecated
80
+    var $attribute_alwayseditable;
81
+    // Array to store permission to check
82
+    // @deprecated
83
+    var $attribute_perms;
84
+    // Array to store language file to translate label of values
85
+    // @deprecated
86
+    var $attribute_langfile;
87
+    // Array to store if field is visible by default on list
88
+    // @deprecated
89
+    var $attribute_list;
90
+
91
+    // New array to store extrafields definition
92
+    var $attributes;
93
+
94
+    /**
95
+     * @var string Error code (or message)
96
+     */
97
+    public $error='';
98
+
99
+    var $errno;
100
+
101
+
102
+    public static $type2label=array(
103
+    'varchar'=>'String',
104
+    'text'=>'TextLong',
105
+    'html'=>'HtmlText',
106
+    'int'=>'Int',
107
+    'double'=>'Float',
108
+    'date'=>'Date',
109
+    'datetime'=>'DateAndTime',
110
+    'boolean'=>'Boolean',
111
+    'price'=>'ExtrafieldPrice',
112
+    'phone'=>'ExtrafieldPhone',
113
+    'mail'=>'ExtrafieldMail',
114
+    'url'=>'ExtrafieldUrl',
115
+    'password' => 'ExtrafieldPassword',
116
+    'select' => 'ExtrafieldSelect',
117
+    'sellist' => 'ExtrafieldSelectList',
118
+    'radio' => 'ExtrafieldRadio',
119
+    'checkbox' => 'ExtrafieldCheckBox',
120
+    'chkbxlst' => 'ExtrafieldCheckBoxFromList',
121
+    'link' => 'ExtrafieldLink',
122
+    'separate' => 'ExtrafieldSeparator',
123
+    );
124
+
125
+
126
+    /**
127
+     *	Constructor
128
+     *
129
+     *  @param		DoliDB		$db      Database handler
130
+     */
131
+    function __construct($db)
132
+    {
133
+        $this->db = $db;
134
+        $this->error = array();
135
+        $this->attributes = array();
136
+
137
+        // For old usage
138
+        $this->attribute_elementtype = array();
139
+        $this->attribute_type = array();
140
+        $this->attribute_label = array();
141
+        $this->attribute_size = array();
142
+        $this->attribute_computed = array();
143
+        $this->attribute_default = array();
144
+        $this->attribute_unique = array();
145
+        $this->attribute_required = array();
146
+        $this->attribute_perms = array();
147
+        $this->attribute_langfile = array();
148
+        $this->attribute_list = array();
149
+    }
150
+
151
+    /**
152
+     *  Add a new extra field parameter
153
+     *
154
+     *  @param	string			$attrname           Code of attribute
155
+     *  @param  string			$label              label of attribute
156
+     *  @param  int				$type               Type of attribute ('boolean','int','varchar','text','html','date','datehour','price','phone','mail','password','url','select','checkbox','separate',...)
157
+     *  @param  int				$pos                Position of attribute
158
+     *  @param  string			$size               Size/length of attribute
159
+     *  @param  string			$elementtype        Element type. Same value than object->table_element (Example 'member', 'product', 'thirdparty', ...)
160
+     *  @param	int				$unique				Is field unique or not
161
+     *  @param	int				$required			Is field required or not
162
+     *  @param	string			$default_value		Defaulted value (In database. use the default_value feature for default value on screen. Example: '', '0', 'null', 'avalue')
163
+     *  @param  array|string	$param				Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
164
+     *  @param  int				$alwayseditable		Is attribute always editable regardless of the document status
165
+     *  @param	string			$perms				Permission to check
166
+     *  @param	string			$list				Visibilty ('0'=never visible, '1'=visible on list+forms, '2'=list only, '3'=form only or 'eval string')
167
+     *  @param	string			$help				Text with help tooltip
168
+     *  @param  string  		$computed           Computed value
169
+     *  @param  string  		$entity    		 	Entity of extrafields (for multicompany modules)
170
+     *  @param  string  		$langfile  		 	Language file
171
+     *  @param  string  		$enabled  		 	Condition to have the field enabled or not
172
+     *  @return int      							<=0 if KO, >0 if OK
173
+     */
174
+    function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $computed='', $entity='', $langfile='', $enabled='1')
175
+    {
176
+        if (empty($attrname)) return -1;
177
+        if (empty($label)) return -1;
178
+
179
+        if ($elementtype == 'thirdparty') $elementtype='societe';
180
+        if ($elementtype == 'contact') $elementtype='socpeople';
181
+
182
+        // Create field into database except for separator type which is not stored in database
183
+        if ($type != 'separate')
184
+        {
185
+            $result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
186
+        }
187
+        $err1=$this->errno;
188
+        if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate')
189
+        {
190
+            // Add declaration of field into table
191
+            $result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled);
192
+            $err2=$this->errno;
193
+            if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS'))
194
+            {
195
+                $this->error='';
196
+                $this->errno=0;
197
+                return 1;
198
+            }
199
+            else return -2;
200
+        }
201
+        else
202
+        {
203
+            return -1;
204
+        }
205
+    }
206
+
207
+    /**
208
+     *	Add a new optional attribute.
209
+     *  This is a private method. For public method, use addExtraField.
210
+     *
211
+     *	@param	string	$attrname			code of attribute
212
+     *  @param	int		$type				Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
213
+     *  @param	string	$length				Size/length of attribute ('5', '24,8', ...)
214
+     *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', 'contact', ...)
215
+     *  @param	int		$unique				Is field unique or not
216
+     *  @param	int		$required			Is field required or not
217
+     *  @param  string  $default_value		Default value for field (in database)
218
+     *  @param  array	$param				Params for field  (ex for select list : array('options'=>array('value'=>'label of option'))
219
+     *  @param	string	$perms				Permission
220
+     *	@param	string	$list				Into list view by default
221
+     *  @param  string  $computed           Computed value
222
+     *  @return int      	           		<=0 if KO, >0 if OK
223
+     */
224
+    private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list='0', $computed='')
225
+    {
226
+        if ($elementtype == 'thirdparty') $elementtype='societe';
227
+        if ($elementtype == 'contact') $elementtype='socpeople';
228
+
229
+        $table=$elementtype.'_extrafields';
230
+        if ($elementtype == 'categorie') $table='categories_extrafields';
231
+
232
+        if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/",$attrname) && ! is_numeric($attrname))
233
+        {
234
+            if ($type=='boolean') {
235
+                $typedb='int';
236
+                $lengthdb='1';
237
+            } elseif($type=='price') {
238
+                $typedb='double';
239
+                $lengthdb='24,8';
240
+            } elseif($type=='phone') {
241
+                $typedb='varchar';
242
+                $lengthdb='20';
243
+            } elseif($type=='mail') {
244
+                $typedb='varchar';
245
+                $lengthdb='128';
246
+            } elseif($type=='url') {
247
+                $typedb='varchar';
248
+                $lengthdb='255';
249
+            } elseif (($type=='select') || ($type=='sellist') || ($type=='radio') ||($type=='checkbox') ||($type=='chkbxlst')){
250
+                $typedb='varchar';
251
+                $lengthdb='255';
252
+            } elseif ($type=='link') {
253
+                $typedb='int';
254
+                $lengthdb='11';
255
+            } elseif ($type=='html') {
256
+                $typedb='text';
257
+                $lengthdb=$length;
258
+            } elseif($type=='password') {
259
+                $typedb='varchar';
260
+                $lengthdb='128';
261
+            } else {
262
+                $typedb=$type;
263
+                $lengthdb=$length;
264
+                if ($type == 'varchar' && empty($lengthdb)) $lengthdb='255';
265
+            }
266
+            $field_desc = array(
267
+                'type'=>$typedb,
268
+                'value'=>$lengthdb,
269
+                'null'=>($required?'NOT NULL':'NULL'),
270
+                'default' => $default_value
271
+            );
272
+
273
+            $result=$this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
274
+            if ($result > 0)
275
+            {
276
+                if ($unique)
277
+                {
278
+                    $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
279
+                    $resql=$this->db->query($sql,1,'dml');
280
+                }
281
+                return 1;
282
+            }
283
+            else
284
+            {
285
+                $this->error=$this->db->lasterror();
286
+                $this->errno=$this->db->lasterrno();
287
+                return -1;
288
+            }
289
+        }
290
+        else
291
+        {
292
+            return 0;
293
+        }
294
+    }
295 295
 
296 296
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
297
-	/**
298
-	 *	Add description of a new optional attribute
299
-	 *
300
-	 *	@param	string			$attrname		code of attribute
301
-	 *	@param	string			$label			label of attribute
302
-	 *  @param	int				$type			Type of attribute ('int', 'varchar', 'text', 'html', 'date', 'datehour', 'float')
303
-	 *  @param	int				$pos			Position of attribute
304
-	 *  @param	string			$size			Size/length of attribute ('5', '24,8', ...)
305
-	 *  @param  string			$elementtype	Element type ('member', 'product', 'thirdparty', ...)
306
-	 *  @param	int				$unique			Is field unique or not
307
-	 *  @param	int				$required		Is field required or not
308
-	 *  @param  array|string	$param			Params for field  (ex for select list : array('options' => array(value'=>'label of option')) )
309
-	 *  @param  int				$alwayseditable	Is attribute always editable regardless of the document status
310
-	 *  @param	string			$perms			Permission to check
311
-	 *  @param	string			$list			Visibily
312
-	 *  @param	string			$help			Help on tooltip
313
-	 *  @param  string          $default        Default value (in database. use the default_value feature for default value on screen).
314
-	 *  @param  string          $computed       Computed value
315
-	 *  @param  string          $entity     	Entity of extrafields
316
-	 *  @param	string			$langfile		Language file
317
-	 *  @param  string  		$enabled  		Condition to have the field enabled or not
318
-	 *  @return	int								<=0 if KO, >0 if OK
319
-	 */
320
-	private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $default='', $computed='',$entity='', $langfile='', $enabled='1')
321
-	{
297
+    /**
298
+     *	Add description of a new optional attribute
299
+     *
300
+     *	@param	string			$attrname		code of attribute
301
+     *	@param	string			$label			label of attribute
302
+     *  @param	int				$type			Type of attribute ('int', 'varchar', 'text', 'html', 'date', 'datehour', 'float')
303
+     *  @param	int				$pos			Position of attribute
304
+     *  @param	string			$size			Size/length of attribute ('5', '24,8', ...)
305
+     *  @param  string			$elementtype	Element type ('member', 'product', 'thirdparty', ...)
306
+     *  @param	int				$unique			Is field unique or not
307
+     *  @param	int				$required		Is field required or not
308
+     *  @param  array|string	$param			Params for field  (ex for select list : array('options' => array(value'=>'label of option')) )
309
+     *  @param  int				$alwayseditable	Is attribute always editable regardless of the document status
310
+     *  @param	string			$perms			Permission to check
311
+     *  @param	string			$list			Visibily
312
+     *  @param	string			$help			Help on tooltip
313
+     *  @param  string          $default        Default value (in database. use the default_value feature for default value on screen).
314
+     *  @param  string          $computed       Computed value
315
+     *  @param  string          $entity     	Entity of extrafields
316
+     *  @param	string			$langfile		Language file
317
+     *  @param  string  		$enabled  		Condition to have the field enabled or not
318
+     *  @return	int								<=0 if KO, >0 if OK
319
+     */
320
+    private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $default='', $computed='',$entity='', $langfile='', $enabled='1')
321
+    {
322 322
         // phpcs:enable
323
-		global $conf,$user;
324
-
325
-		if ($elementtype == 'thirdparty') $elementtype='societe';
326
-		if ($elementtype == 'contact') $elementtype='socpeople';
327
-
328
-		// Clean parameters
329
-		if (empty($pos)) $pos=0;
330
-		if (empty($list)) $list='0';
331
-		if (empty($required)) $required=0;
332
-		if (empty($unique)) $unique=0;
333
-		if (empty($alwayseditable)) $alwayseditable=0;
334
-
335
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname) && ! is_numeric($attrname))
336
-		{
337
-			if (is_array($param) && count($param) > 0)
338
-			{
339
-				$params = serialize($param);
340
-			}
341
-			elseif (strlen($param) > 0)
342
-			{
343
-				$params = trim($param);
344
-			}
345
-			else
346
-			{
347
-				$params='';
348
-			}
349
-
350
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
351
-			$sql.= " name,";
352
-			$sql.= " label,";
353
-			$sql.= " type,";
354
-			$sql.= " pos,";
355
-			$sql.= " size,";
356
-			$sql.= " entity,";
357
-			$sql.= " elementtype,";
358
-			$sql.= " fieldunique,";
359
-			$sql.= " fieldrequired,";
360
-			$sql.= " param,";
361
-			$sql.= " alwayseditable,";
362
-			$sql.= " perms,";
363
-			$sql.= " langs,";
364
-			$sql.= " list,";
365
-			$sql.= " fielddefault,";
366
-			$sql.= " fieldcomputed,";
367
-			$sql.= " fk_user_author,";
368
-			$sql.= " fk_user_modif,";
369
-			$sql.= " datec,";
370
-			$sql.= " enabled,";
371
-			$sql.= " help";
372
-			$sql.= " )";
373
-			$sql.= " VALUES('".$attrname."',";
374
-			$sql.= " '".$this->db->escape($label)."',";
375
-			$sql.= " '".$this->db->escape($type)."',";
376
-			$sql.= " ".$pos.",";
377
-			$sql.= " '".$this->db->escape($size)."',";
378
-			$sql.= " ".($entity===''?$conf->entity:$entity).",";
379
-			$sql.= " '".$this->db->escape($elementtype)."',";
380
-			$sql.= " ".$unique.",";
381
-			$sql.= " ".$required.",";
382
-			$sql.= " '".$this->db->escape($params)."',";
383
-			$sql.= " ".$alwayseditable.",";
384
-			$sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
385
-			$sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
386
-			$sql.= " '".$this->db->escape($list)."',";
387
-			$sql.= " ".($default?"'".$this->db->escape($default)."'":"null").",";
388
-			$sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
389
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
390
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
391
-			$sql .= "'" . $this->db->idate(dol_now()) . "',";
392
-			$sql.= " ".($enabled?"'".$this->db->escape($enabled)."'":"1").",";
393
-			$sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
394
-			$sql.=')';
395
-
396
-			dol_syslog(get_class($this)."::create_label", LOG_DEBUG);
397
-			if ($this->db->query($sql))
398
-			{
399
-				return 1;
400
-			}
401
-			else
402
-			{
403
-				$this->error=$this->db->lasterror();
404
-				$this->errno=$this->db->lasterrno();
405
-				return -1;
406
-			}
407
-		}
408
-	}
409
-
410
-	/**
411
-	 *	Delete an optional attribute
412
-	 *
413
-	 *	@param	string	$attrname		Code of attribute to delete
414
-	 *  @param  string	$elementtype    Element type ('member', 'product', 'thirdparty', 'contact', ...)
415
-	 *  @return int              		< 0 if KO, 0 if nothing is done, 1 if OK
416
-	 */
417
-	function delete($attrname, $elementtype='member')
418
-	{
419
-		if ($elementtype == 'thirdparty') $elementtype='societe';
420
-		if ($elementtype == 'contact') $elementtype='socpeople';
421
-
422
-		$table=$elementtype.'_extrafields';
423
-		if ($elementtype == 'categorie') $table='categories_extrafields';
424
-
425
-		$error=0;
426
-
427
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
428
-		{
429
-			$result=$this->delete_label($attrname,$elementtype);
430
-			if ($result < 0)
431
-			{
432
-			    $this->error=$this->db->lasterror();
433
-			    $error++;
434
-			}
435
-
436
-			if (! $error)
437
-			{
438
-        		$sql = "SELECT COUNT(rowid) as nb";
439
-        		$sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
440
-        		$sql.= " WHERE elementtype = '".$elementtype."'";
441
-        		$sql.= " AND name = '".$attrname."'";
442
-        		//$sql.= " AND entity IN (0,".$conf->entity.")";      Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table
323
+        global $conf,$user;
324
+
325
+        if ($elementtype == 'thirdparty') $elementtype='societe';
326
+        if ($elementtype == 'contact') $elementtype='socpeople';
327
+
328
+        // Clean parameters
329
+        if (empty($pos)) $pos=0;
330
+        if (empty($list)) $list='0';
331
+        if (empty($required)) $required=0;
332
+        if (empty($unique)) $unique=0;
333
+        if (empty($alwayseditable)) $alwayseditable=0;
334
+
335
+        if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname) && ! is_numeric($attrname))
336
+        {
337
+            if (is_array($param) && count($param) > 0)
338
+            {
339
+                $params = serialize($param);
340
+            }
341
+            elseif (strlen($param) > 0)
342
+            {
343
+                $params = trim($param);
344
+            }
345
+            else
346
+            {
347
+                $params='';
348
+            }
349
+
350
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
351
+            $sql.= " name,";
352
+            $sql.= " label,";
353
+            $sql.= " type,";
354
+            $sql.= " pos,";
355
+            $sql.= " size,";
356
+            $sql.= " entity,";
357
+            $sql.= " elementtype,";
358
+            $sql.= " fieldunique,";
359
+            $sql.= " fieldrequired,";
360
+            $sql.= " param,";
361
+            $sql.= " alwayseditable,";
362
+            $sql.= " perms,";
363
+            $sql.= " langs,";
364
+            $sql.= " list,";
365
+            $sql.= " fielddefault,";
366
+            $sql.= " fieldcomputed,";
367
+            $sql.= " fk_user_author,";
368
+            $sql.= " fk_user_modif,";
369
+            $sql.= " datec,";
370
+            $sql.= " enabled,";
371
+            $sql.= " help";
372
+            $sql.= " )";
373
+            $sql.= " VALUES('".$attrname."',";
374
+            $sql.= " '".$this->db->escape($label)."',";
375
+            $sql.= " '".$this->db->escape($type)."',";
376
+            $sql.= " ".$pos.",";
377
+            $sql.= " '".$this->db->escape($size)."',";
378
+            $sql.= " ".($entity===''?$conf->entity:$entity).",";
379
+            $sql.= " '".$this->db->escape($elementtype)."',";
380
+            $sql.= " ".$unique.",";
381
+            $sql.= " ".$required.",";
382
+            $sql.= " '".$this->db->escape($params)."',";
383
+            $sql.= " ".$alwayseditable.",";
384
+            $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
385
+            $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
386
+            $sql.= " '".$this->db->escape($list)."',";
387
+            $sql.= " ".($default?"'".$this->db->escape($default)."'":"null").",";
388
+            $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
389
+            $sql .= " " . (is_object($user) ? $user->id : 0). ",";
390
+            $sql .= " " . (is_object($user) ? $user->id : 0). ",";
391
+            $sql .= "'" . $this->db->idate(dol_now()) . "',";
392
+            $sql.= " ".($enabled?"'".$this->db->escape($enabled)."'":"1").",";
393
+            $sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
394
+            $sql.=')';
395
+
396
+            dol_syslog(get_class($this)."::create_label", LOG_DEBUG);
397
+            if ($this->db->query($sql))
398
+            {
399
+                return 1;
400
+            }
401
+            else
402
+            {
403
+                $this->error=$this->db->lasterror();
404
+                $this->errno=$this->db->lasterrno();
405
+                return -1;
406
+            }
407
+        }
408
+    }
409
+
410
+    /**
411
+     *	Delete an optional attribute
412
+     *
413
+     *	@param	string	$attrname		Code of attribute to delete
414
+     *  @param  string	$elementtype    Element type ('member', 'product', 'thirdparty', 'contact', ...)
415
+     *  @return int              		< 0 if KO, 0 if nothing is done, 1 if OK
416
+     */
417
+    function delete($attrname, $elementtype='member')
418
+    {
419
+        if ($elementtype == 'thirdparty') $elementtype='societe';
420
+        if ($elementtype == 'contact') $elementtype='socpeople';
421
+
422
+        $table=$elementtype.'_extrafields';
423
+        if ($elementtype == 'categorie') $table='categories_extrafields';
424
+
425
+        $error=0;
426
+
427
+        if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
428
+        {
429
+            $result=$this->delete_label($attrname,$elementtype);
430
+            if ($result < 0)
431
+            {
432
+                $this->error=$this->db->lasterror();
433
+                $error++;
434
+            }
435
+
436
+            if (! $error)
437
+            {
438
+                $sql = "SELECT COUNT(rowid) as nb";
439
+                $sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
440
+                $sql.= " WHERE elementtype = '".$elementtype."'";
441
+                $sql.= " AND name = '".$attrname."'";
442
+                //$sql.= " AND entity IN (0,".$conf->entity.")";      Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table
443 443
                 $resql = $this->db->query($sql);
444 444
                 if ($resql)
445 445
                 {
446 446
                     $obj = $this->db->fetch_object($resql);
447 447
                     if ($obj->nb <= 0)
448 448
                     {
449
-            			$result=$this->db->DDLDropField(MAIN_DB_PREFIX.$table,$attrname);	// This also drop the unique key
450
-            			if ($result < 0)
451
-            			{
452
-            				$this->error=$this->db->lasterror();
453
-            				$error++;
454
-            			}
449
+                        $result=$this->db->DDLDropField(MAIN_DB_PREFIX.$table,$attrname);	// This also drop the unique key
450
+                        if ($result < 0)
451
+                        {
452
+                            $this->error=$this->db->lasterror();
453
+                            $error++;
454
+                        }
455 455
                     }
456 456
                 }
457
-			}
457
+            }
458 458
 
459
-			return $result;
460
-		}
461
-		else
462
-		{
463
-			return 0;
464
-		}
465
-	}
459
+            return $result;
460
+        }
461
+        else
462
+        {
463
+            return 0;
464
+        }
465
+    }
466 466
 
467 467
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
468
-	/**
469
-	 *	Delete description of an optional attribute
470
-	 *
471
-	 *	@param	string	$attrname			Code of attribute to delete
472
-	 *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', ...)
473
-	 *  @return int              			< 0 if KO, 0 if nothing is done, 1 if OK
474
-	 */
475
-	private function delete_label($attrname, $elementtype='member')
476
-	{
468
+    /**
469
+     *	Delete description of an optional attribute
470
+     *
471
+     *	@param	string	$attrname			Code of attribute to delete
472
+     *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', ...)
473
+     *  @return int              			< 0 if KO, 0 if nothing is done, 1 if OK
474
+     */
475
+    private function delete_label($attrname, $elementtype='member')
476
+    {
477 477
         // phpcs:enable
478
-		global $conf;
479
-
480
-		if ($elementtype == 'thirdparty') $elementtype='societe';
481
-		if ($elementtype == 'contact') $elementtype='socpeople';
482
-
483
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
484
-		{
485
-			$sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
486
-			$sql.= " WHERE name = '".$attrname."'";
487
-			$sql.= " AND entity IN  (0,".$conf->entity.')';
488
-			$sql.= " AND elementtype = '".$elementtype."'";
489
-
490
-			dol_syslog(get_class($this)."::delete_label", LOG_DEBUG);
491
-			$resql=$this->db->query($sql);
492
-			if ($resql)
493
-			{
494
-				return 1;
495
-			}
496
-			else
497
-			{
498
-				print dol_print_error($this->db);
499
-				return -1;
500
-			}
501
-		}
502
-		else
503
-		{
504
-			return 0;
505
-		}
506
-	}
507
-
508
-	/**
509
-	 * 	Modify type of a personalized attribute
510
-	 *
511
-	 *  @param	string	$attrname			Name of attribute
512
-	 *  @param	string	$label				Label of attribute
513
-	 *  @param	string	$type				Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
514
-	 *  @param	int		$length				Length of attribute
515
-	 *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', 'contact', ...)
516
-	 *  @param	int		$unique				Is field unique or not
517
-	 *  @param	int		$required			Is field required or not
518
-	 *  @param	int		$pos				Position of attribute
519
-	 *  @param  array	$param				Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
520
-	 *  @param  int		$alwayseditable		Is attribute always editable regardless of the document status
521
-	 *  @param	string	$perms				Permission to check
522
-	 *  @param	string	$list				Visibility
523
-	 *  @param	string	$help				Help on tooltip
524
-	 *  @param  string  $default            Default value (in database. use the default_value feature for default value on screen).
525
-	 *  @param  string  $computed           Computed value
526
-	 *  @param  string  $entity	            Entity of extrafields
527
-	 *  @param	string	$langfile			Language file
528
-	 *  @param  string  $enabled  			Condition to have the field enabled or not
478
+        global $conf;
479
+
480
+        if ($elementtype == 'thirdparty') $elementtype='societe';
481
+        if ($elementtype == 'contact') $elementtype='socpeople';
482
+
483
+        if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
484
+        {
485
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
486
+            $sql.= " WHERE name = '".$attrname."'";
487
+            $sql.= " AND entity IN  (0,".$conf->entity.')';
488
+            $sql.= " AND elementtype = '".$elementtype."'";
489
+
490
+            dol_syslog(get_class($this)."::delete_label", LOG_DEBUG);
491
+            $resql=$this->db->query($sql);
492
+            if ($resql)
493
+            {
494
+                return 1;
495
+            }
496
+            else
497
+            {
498
+                print dol_print_error($this->db);
499
+                return -1;
500
+            }
501
+        }
502
+        else
503
+        {
504
+            return 0;
505
+        }
506
+    }
507
+
508
+    /**
509
+     * 	Modify type of a personalized attribute
510
+     *
511
+     *  @param	string	$attrname			Name of attribute
512
+     *  @param	string	$label				Label of attribute
513
+     *  @param	string	$type				Type of attribute ('boolean', 'int', 'varchar', 'text', 'html', 'date', 'datehour','price','phone','mail','password','url','select','checkbox', ...)
514
+     *  @param	int		$length				Length of attribute
515
+     *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', 'contact', ...)
516
+     *  @param	int		$unique				Is field unique or not
517
+     *  @param	int		$required			Is field required or not
518
+     *  @param	int		$pos				Position of attribute
519
+     *  @param  array	$param				Params for field (ex for select list : array('options' => array(value'=>'label of option')) )
520
+     *  @param  int		$alwayseditable		Is attribute always editable regardless of the document status
521
+     *  @param	string	$perms				Permission to check
522
+     *  @param	string	$list				Visibility
523
+     *  @param	string	$help				Help on tooltip
524
+     *  @param  string  $default            Default value (in database. use the default_value feature for default value on screen).
525
+     *  @param  string  $computed           Computed value
526
+     *  @param  string  $entity	            Entity of extrafields
527
+     *  @param	string	$langfile			Language file
528
+     *  @param  string  $enabled  			Condition to have the field enabled or not
529 529
      *  @param  int     $totalizable        Is extrafield totalizable on list
530
-	 * 	@return	int							>0 if OK, <=0 if KO
531
-	 */
532
-	function update($attrname, $label, $type, $length, $elementtype, $unique=0, $required=0, $pos=0, $param='', $alwayseditable=0, $perms='', $list='', $help='', $default='', $computed='', $entity='', $langfile='', $enabled='1', $totalizable=0)
533
-	{
534
-		if ($elementtype == 'thirdparty') $elementtype='societe';
535
-		if ($elementtype == 'contact') $elementtype='socpeople';
530
+     * 	@return	int							>0 if OK, <=0 if KO
531
+     */
532
+    function update($attrname, $label, $type, $length, $elementtype, $unique=0, $required=0, $pos=0, $param='', $alwayseditable=0, $perms='', $list='', $help='', $default='', $computed='', $entity='', $langfile='', $enabled='1', $totalizable=0)
533
+    {
534
+        if ($elementtype == 'thirdparty') $elementtype='societe';
535
+        if ($elementtype == 'contact') $elementtype='socpeople';
536 536
 
537 537
         $table=$elementtype.'_extrafields';
538
-		if ($elementtype == 'categorie') $table='categories_extrafields';
539
-
540
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
541
-		{
542
-			if ($type=='boolean') {
543
-				$typedb='int';
544
-				$lengthdb='1';
545
-			} elseif($type=='price') {
546
-				$typedb='double';
547
-				$lengthdb='24,8';
548
-			} elseif($type=='phone') {
549
-				$typedb='varchar';
550
-				$lengthdb='20';
551
-			} elseif($type=='mail') {
552
-				$typedb='varchar';
553
-				$lengthdb='128';
554
-			} elseif($type=='url') {
555
-				$typedb='varchar';
556
-				$lengthdb='255';
557
-			} elseif (($type=='select') || ($type=='sellist') || ($type=='radio') || ($type=='checkbox') || ($type=='chkbxlst')) {
558
-				$typedb='varchar';
559
-				$lengthdb='255';
560
-			} elseif ($type == 'html') {
561
-				$typedb='text';
562
-			} elseif ($type=='link') {
563
-				$typedb='int';
564
-				$lengthdb='11';
565
-			} elseif($type=='password') {
566
-				$typedb='varchar';
567
-				$lengthdb='50';
568
-			} else {
569
-				$typedb=$type;
570
-				$lengthdb=$length;
571
-			}
572
-			$field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default);
573
-
574
-			if ($type != 'separate') // No table update when separate type
575
-			{
576
-				$result=$this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
577
-			}
578
-			if ($result > 0 || $type == 'separate')
579
-			{
580
-				if ($label)
581
-				{
582
-					$result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$help,$default,$computed,$entity,$langfile,$enabled, $totalizable);
583
-				}
584
-				if ($result > 0)
585
-				{
586
-					$sql='';
587
-					if ($unique)
588
-					{
589
-						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
590
-					}
591
-					else
592
-					{
593
-						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
594
-					}
595
-					dol_syslog(get_class($this).'::update', LOG_DEBUG);
596
-					$resql=$this->db->query($sql,1,'dml');
597
-					return 1;
598
-				}
599
-				else
600
-				{
601
-					$this->error=$this->db->lasterror();
602
-					return -1;
603
-				}
604
-			}
605
-			else
606
-			{
607
-				$this->error=$this->db->lasterror();
608
-				return -1;
609
-			}
610
-		}
611
-		else
612
-		{
613
-			return 0;
614
-		}
615
-	}
538
+        if ($elementtype == 'categorie') $table='categories_extrafields';
539
+
540
+        if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
541
+        {
542
+            if ($type=='boolean') {
543
+                $typedb='int';
544
+                $lengthdb='1';
545
+            } elseif($type=='price') {
546
+                $typedb='double';
547
+                $lengthdb='24,8';
548
+            } elseif($type=='phone') {
549
+                $typedb='varchar';
550
+                $lengthdb='20';
551
+            } elseif($type=='mail') {
552
+                $typedb='varchar';
553
+                $lengthdb='128';
554
+            } elseif($type=='url') {
555
+                $typedb='varchar';
556
+                $lengthdb='255';
557
+            } elseif (($type=='select') || ($type=='sellist') || ($type=='radio') || ($type=='checkbox') || ($type=='chkbxlst')) {
558
+                $typedb='varchar';
559
+                $lengthdb='255';
560
+            } elseif ($type == 'html') {
561
+                $typedb='text';
562
+            } elseif ($type=='link') {
563
+                $typedb='int';
564
+                $lengthdb='11';
565
+            } elseif($type=='password') {
566
+                $typedb='varchar';
567
+                $lengthdb='50';
568
+            } else {
569
+                $typedb=$type;
570
+                $lengthdb=$length;
571
+            }
572
+            $field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default);
573
+
574
+            if ($type != 'separate') // No table update when separate type
575
+            {
576
+                $result=$this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
577
+            }
578
+            if ($result > 0 || $type == 'separate')
579
+            {
580
+                if ($label)
581
+                {
582
+                    $result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$help,$default,$computed,$entity,$langfile,$enabled, $totalizable);
583
+                }
584
+                if ($result > 0)
585
+                {
586
+                    $sql='';
587
+                    if ($unique)
588
+                    {
589
+                        $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
590
+                    }
591
+                    else
592
+                    {
593
+                        $sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
594
+                    }
595
+                    dol_syslog(get_class($this).'::update', LOG_DEBUG);
596
+                    $resql=$this->db->query($sql,1,'dml');
597
+                    return 1;
598
+                }
599
+                else
600
+                {
601
+                    $this->error=$this->db->lasterror();
602
+                    return -1;
603
+                }
604
+            }
605
+            else
606
+            {
607
+                $this->error=$this->db->lasterror();
608
+                return -1;
609
+            }
610
+        }
611
+        else
612
+        {
613
+            return 0;
614
+        }
615
+    }
616 616
 
617 617
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
618
-	/**
619
-	 *  Modify description of personalized attribute
620
-	 *
621
-	 *  @param	string	$attrname			Name of attribute
622
-	 *  @param	string	$label				Label of attribute
623
-	 *  @param  string	$type               Type of attribute
624
-	 *  @param  int		$size		        Length of attribute
625
-	 *  @param  string	$elementtype		Element type ('member', 'product', 'thirdparty', ...)
626
-	 *  @param	int		$unique				Is field unique or not
627
-	 *  @param	int		$required			Is field required or not
628
-	 *  @param	int		$pos				Position of attribute
629
-	 *  @param  array	$param				Params for field  (ex for select list : array('options' => array(value'=>'label of option')) )
630
-	 *  @param  int		$alwayseditable		Is attribute always editable regardless of the document status
631
-	 *  @param	string	$perms				Permission to check
632
-	 *  @param	string	$list				Visiblity
633
-	 *  @param	string	$help				Help on tooltip.
634
-	 *  @param  string  $default            Default value (in database. use the default_value feature for default value on screen).
635
-	 *  @param  string  $computed           Computed value
636
-	 *  @param  string  $entity     		Entity of extrafields
637
-	 *  @param	string	$langfile			Language file
638
-	 *  @param  string  $enabled  			Condition to have the field enabled or not
618
+    /**
619
+     *  Modify description of personalized attribute
620
+     *
621
+     *  @param	string	$attrname			Name of attribute
622
+     *  @param	string	$label				Label of attribute
623
+     *  @param  string	$type               Type of attribute
624
+     *  @param  int		$size		        Length of attribute
625
+     *  @param  string	$elementtype		Element type ('member', 'product', 'thirdparty', ...)
626
+     *  @param	int		$unique				Is field unique or not
627
+     *  @param	int		$required			Is field required or not
628
+     *  @param	int		$pos				Position of attribute
629
+     *  @param  array	$param				Params for field  (ex for select list : array('options' => array(value'=>'label of option')) )
630
+     *  @param  int		$alwayseditable		Is attribute always editable regardless of the document status
631
+     *  @param	string	$perms				Permission to check
632
+     *  @param	string	$list				Visiblity
633
+     *  @param	string	$help				Help on tooltip.
634
+     *  @param  string  $default            Default value (in database. use the default_value feature for default value on screen).
635
+     *  @param  string  $computed           Computed value
636
+     *  @param  string  $entity     		Entity of extrafields
637
+     *  @param	string	$langfile			Language file
638
+     *  @param  string  $enabled  			Condition to have the field enabled or not
639 639
      *  @param  int     $totalizable        Is extrafield totalizable on list
640 640
      *  @return	int							<=0 if KO, >0 if OK
641
-	 */
642
-	private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0,$perms='',$list='0',$help='',$default='',$computed='',$entity='',$langfile='',$enabled='1', $totalizable=0)
643
-	{
641
+     */
642
+    private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0,$perms='',$list='0',$help='',$default='',$computed='',$entity='',$langfile='',$enabled='1', $totalizable=0)
643
+    {
644 644
         // phpcs:enable
645
-		global $conf, $user;
646
-		dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable);
645
+        global $conf, $user;
646
+        dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable);
647 647
 
648
-		// Clean parameters
649
-		if ($elementtype == 'thirdparty') $elementtype='societe';
650
-		if ($elementtype == 'contact') $elementtype='socpeople';
648
+        // Clean parameters
649
+        if ($elementtype == 'thirdparty') $elementtype='societe';
650
+        if ($elementtype == 'contact') $elementtype='socpeople';
651 651
 
652
-		if (empty($pos)) $pos=0;
653
-		if (empty($list)) $list='0';
652
+        if (empty($pos)) $pos=0;
653
+        if (empty($list)) $list='0';
654 654
         if (empty($totalizable)) {
655 655
             $totalizable = 0;
656 656
         }
657
-		if (empty($required)) $required=0;
658
-		if (empty($unique)) $unique=0;
659
-		if (empty($alwayseditable)) $alwayseditable=0;
660
-
661
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
662
-		{
663
-			$this->db->begin();
664
-
665
-			if (is_array($param) && count($param) > 0)
666
-			{
667
-				$params = serialize($param);
668
-			}
669
-			elseif (strlen($param) > 0)
670
-			{
671
-				$params = trim($param);
672
-			}
673
-			else
674
-			{
675
-				$params='';
676
-			}
677
-
678
-			if ($entity === '' || $entity != '0')
679
-			{
680
-				// We dont want on all entities, we delete all and current
681
-				$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
682
-				$sql_del.= " WHERE name = '".$attrname."'";
683
-				$sql_del.= " AND entity IN (0, ".($entity===''?$conf->entity:$entity).")";
684
-				$sql_del.= " AND elementtype = '".$elementtype."'";
685
-			}
686
-			else
687
-			{
688
-				// We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity)
689
-				$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
690
-				$sql_del.= " WHERE name = '".$attrname."'";
691
-				$sql_del.= " AND entity = 0";
692
-				$sql_del.= " AND elementtype = '".$elementtype."'";
693
-			}
694
-			$resql1=$this->db->query($sql_del);
695
-
696
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
697
-			$sql.= " name,";		// This is code
698
-			$sql.= " entity,";
699
-			$sql.= " label,";
700
-			$sql.= " type,";
701
-			$sql.= " size,";
702
-			$sql.= " elementtype,";
703
-			$sql.= " fieldunique,";
704
-			$sql.= " fieldrequired,";
705
-			$sql.= " perms,";
706
-			$sql.= " langs,";
707
-			$sql.= " pos,";
708
-			$sql.= " alwayseditable,";
709
-			$sql.= " param,";
710
-			$sql.= " list,";
657
+        if (empty($required)) $required=0;
658
+        if (empty($unique)) $unique=0;
659
+        if (empty($alwayseditable)) $alwayseditable=0;
660
+
661
+        if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
662
+        {
663
+            $this->db->begin();
664
+
665
+            if (is_array($param) && count($param) > 0)
666
+            {
667
+                $params = serialize($param);
668
+            }
669
+            elseif (strlen($param) > 0)
670
+            {
671
+                $params = trim($param);
672
+            }
673
+            else
674
+            {
675
+                $params='';
676
+            }
677
+
678
+            if ($entity === '' || $entity != '0')
679
+            {
680
+                // We dont want on all entities, we delete all and current
681
+                $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
682
+                $sql_del.= " WHERE name = '".$attrname."'";
683
+                $sql_del.= " AND entity IN (0, ".($entity===''?$conf->entity:$entity).")";
684
+                $sql_del.= " AND elementtype = '".$elementtype."'";
685
+            }
686
+            else
687
+            {
688
+                // We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity)
689
+                $sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
690
+                $sql_del.= " WHERE name = '".$attrname."'";
691
+                $sql_del.= " AND entity = 0";
692
+                $sql_del.= " AND elementtype = '".$elementtype."'";
693
+            }
694
+            $resql1=$this->db->query($sql_del);
695
+
696
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
697
+            $sql.= " name,";		// This is code
698
+            $sql.= " entity,";
699
+            $sql.= " label,";
700
+            $sql.= " type,";
701
+            $sql.= " size,";
702
+            $sql.= " elementtype,";
703
+            $sql.= " fieldunique,";
704
+            $sql.= " fieldrequired,";
705
+            $sql.= " perms,";
706
+            $sql.= " langs,";
707
+            $sql.= " pos,";
708
+            $sql.= " alwayseditable,";
709
+            $sql.= " param,";
710
+            $sql.= " list,";
711 711
             $sql.= " totalizable,";
712
-			$sql.= " fielddefault,";
713
-			$sql.= " fieldcomputed,";
714
-			$sql.= " fk_user_author,";
715
-			$sql.= " fk_user_modif,";
716
-			$sql.= " datec,";
717
-			$sql.= " enabled,";
718
-			$sql.= " help";
719
-			$sql.= ") VALUES (";
720
-			$sql.= "'".$attrname."',";
721
-			$sql.= " ".($entity===''?$conf->entity:$entity).",";
722
-			$sql.= " '".$this->db->escape($label)."',";
723
-			$sql.= " '".$this->db->escape($type)."',";
724
-			$sql.= " '".$this->db->escape($size)."',";
725
-			$sql.= " '".$this->db->escape($elementtype)."',";
726
-			$sql.= " ".$unique.",";
727
-			$sql.= " ".$required.",";
728
-			$sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
729
-			$sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
730
-			$sql.= " ".$pos.",";
731
-			$sql.= " '".$this->db->escape($alwayseditable)."',";
732
-			$sql.= " '".$this->db->escape($params)."',";
733
-			$sql.= " '".$this->db->escape($list)."', ";
712
+            $sql.= " fielddefault,";
713
+            $sql.= " fieldcomputed,";
714
+            $sql.= " fk_user_author,";
715
+            $sql.= " fk_user_modif,";
716
+            $sql.= " datec,";
717
+            $sql.= " enabled,";
718
+            $sql.= " help";
719
+            $sql.= ") VALUES (";
720
+            $sql.= "'".$attrname."',";
721
+            $sql.= " ".($entity===''?$conf->entity:$entity).",";
722
+            $sql.= " '".$this->db->escape($label)."',";
723
+            $sql.= " '".$this->db->escape($type)."',";
724
+            $sql.= " '".$this->db->escape($size)."',";
725
+            $sql.= " '".$this->db->escape($elementtype)."',";
726
+            $sql.= " ".$unique.",";
727
+            $sql.= " ".$required.",";
728
+            $sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
729
+            $sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
730
+            $sql.= " ".$pos.",";
731
+            $sql.= " '".$this->db->escape($alwayseditable)."',";
732
+            $sql.= " '".$this->db->escape($params)."',";
733
+            $sql.= " '".$this->db->escape($list)."', ";
734 734
             $sql.= " ".$totalizable.",";
735
-			$sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").",";
736
-			$sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
737
-			$sql .= " " . $user->id . ",";
738
-			$sql .= " " . $user->id . ",";
739
-			$sql .= "'" . $this->db->idate(dol_now()) . "',";
740
-			$sql .= "'" . $this->db->escape($enabled). "',";
741
-			$sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
742
-			$sql.= ")";
743
-
744
-			$resql2=$this->db->query($sql);
745
-
746
-			if ($resql1 && $resql2)
747
-			{
748
-				$this->db->commit();
749
-				return 1;
750
-			}
751
-			else
752
-			{
753
-				$this->db->rollback();
754
-				print dol_print_error($this->db);
755
-				return -1;
756
-			}
757
-		}
758
-		else
759
-		{
760
-			return 0;
761
-		}
762
-	}
735
+            $sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").",";
736
+            $sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
737
+            $sql .= " " . $user->id . ",";
738
+            $sql .= " " . $user->id . ",";
739
+            $sql .= "'" . $this->db->idate(dol_now()) . "',";
740
+            $sql .= "'" . $this->db->escape($enabled). "',";
741
+            $sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
742
+            $sql.= ")";
743
+
744
+            $resql2=$this->db->query($sql);
745
+
746
+            if ($resql1 && $resql2)
747
+            {
748
+                $this->db->commit();
749
+                return 1;
750
+            }
751
+            else
752
+            {
753
+                $this->db->rollback();
754
+                print dol_print_error($this->db);
755
+                return -1;
756
+            }
757
+        }
758
+        else
759
+        {
760
+            return 0;
761
+        }
762
+    }
763 763
 
764 764
 
765 765
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
766
-	/**
767
-	 * 	Load array this->attributes, or old this->attribute_xxx like attribute_label, attribute_type, ...
768
-	 *
769
-	 * 	@param	string		$elementtype		Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...).
770
-	 * 	@param	boolean		$forceload			Force load of extra fields whatever is option MAIN_EXTRAFIELDS_DISABLED. Deprecated. Should not be required.
771
-	 * 	@return	array							Array of attributes keys+label for all extra fields.
772
-	 */
773
-	function fetch_name_optionals_label($elementtype,$forceload=false)
774
-	{
766
+    /**
767
+     * 	Load array this->attributes, or old this->attribute_xxx like attribute_label, attribute_type, ...
768
+     *
769
+     * 	@param	string		$elementtype		Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...).
770
+     * 	@param	boolean		$forceload			Force load of extra fields whatever is option MAIN_EXTRAFIELDS_DISABLED. Deprecated. Should not be required.
771
+     * 	@return	array							Array of attributes keys+label for all extra fields.
772
+     */
773
+    function fetch_name_optionals_label($elementtype,$forceload=false)
774
+    {
775 775
         // phpcs:enable
776
-		global $conf;
777
-
778
-		if (empty($elementtype)) return array();
779
-
780
-		if ($elementtype == 'thirdparty') $elementtype='societe';
781
-		if ($elementtype == 'contact') $elementtype='socpeople';
782
-		if ($elementtype == 'order_supplier') $elementtype='commande_fournisseur';
783
-
784
-		$array_name_label=array();
785
-
786
-		// To avoid conflicts with external modules. TODO Remove this.
787
-		if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label;
788
-
789
-		// Set array of label of entity
790
-		// TODO Remove completely loading of label. This should be done by presentation.
791
-		$labelmulticompany=array();
792
-		if (!empty($conf->multicompany->enabled))
793
-		{
794
-			$sql_entity_name='SELECT rowid, label FROM '.MAIN_DB_PREFIX.'entity WHERE rowid in (0,'.$conf->entity.')';
795
-			$resql_entity_name=$this->db->query($sql_entity_name);
796
-			if ($resql_entity_name)
797
-			{
798
-				while ($obj = $this->db->fetch_object($resql_entity_name))
799
-				{
800
-					$labelmulticompany[$obj->rowid]=$obj->label;
801
-				}
802
-			}
803
-		}
804
-
805
-		// We should not have several time this log. If we have, there is some optimization to do by calling a simple $object->fetch_optionals() that include cache management.
806
-		dol_syslog("fetch_name_optionals_label elementtype=".$elementtype);
807
-
808
-		$sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help";
809
-		$sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
810
-		$sql.= " WHERE entity IN (0,".$conf->entity.")";
811
-		if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'";	// Filed with object->table_element
812
-		$sql.= " ORDER BY pos";
813
-
814
-		$resql=$this->db->query($sql);
815
-		if ($resql)
816
-		{
817
-			if ($this->db->num_rows($resql))
818
-			{
819
-				while ($tab = $this->db->fetch_object($resql))
820
-				{
821
-					// We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label']
822
-					if ($tab->type != 'separate')
823
-					{
824
-						$array_name_label[$tab->name]=$tab->label;
825
-					}
826
-
827
-					// Old usage
828
-					$this->attribute_type[$tab->name]=$tab->type;
829
-					$this->attribute_label[$tab->name]=$tab->label;
830
-					$this->attribute_size[$tab->name]=$tab->size;
831
-					$this->attribute_elementtype[$tab->name]=$tab->elementtype;
832
-					$this->attribute_default[$tab->name]=$tab->fielddefault;
833
-					$this->attribute_computed[$tab->name]=$tab->fieldcomputed;
834
-					$this->attribute_unique[$tab->name]=$tab->fieldunique;
835
-					$this->attribute_required[$tab->name]=$tab->fieldrequired;
836
-					$this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : '');
837
-					$this->attribute_pos[$tab->name]=$tab->pos;
838
-					$this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable;
839
-					$this->attribute_perms[$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
840
-					$this->attribute_langfile[$tab->name]=$tab->langs;
841
-					$this->attribute_list[$tab->name]=$tab->list;
842
-					$this->attribute_totalizable[$tab->name]=$tab->totalizable;
843
-					$this->attribute_entityid[$tab->name]=$tab->entity;
844
-					$this->attribute_entitylabel[$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
845
-
846
-					// New usage
847
-					$this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type;
848
-					$this->attributes[$tab->elementtype]['label'][$tab->name]=$tab->label;
849
-					$this->attributes[$tab->elementtype]['size'][$tab->name]=$tab->size;
850
-					$this->attributes[$tab->elementtype]['elementtype'][$tab->name]=$tab->elementtype;
851
-					$this->attributes[$tab->elementtype]['default'][$tab->name]=$tab->fielddefault;
852
-					$this->attributes[$tab->elementtype]['computed'][$tab->name]=$tab->fieldcomputed;
853
-					$this->attributes[$tab->elementtype]['unique'][$tab->name]=$tab->fieldunique;
854
-					$this->attributes[$tab->elementtype]['required'][$tab->name]=$tab->fieldrequired;
855
-					$this->attributes[$tab->elementtype]['param'][$tab->name]=($tab->param ? unserialize($tab->param) : '');
856
-					$this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos;
857
-					$this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable;
858
-					$this->attributes[$tab->elementtype]['perms'][$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
859
-					$this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs;
860
-					$this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list;
776
+        global $conf;
777
+
778
+        if (empty($elementtype)) return array();
779
+
780
+        if ($elementtype == 'thirdparty') $elementtype='societe';
781
+        if ($elementtype == 'contact') $elementtype='socpeople';
782
+        if ($elementtype == 'order_supplier') $elementtype='commande_fournisseur';
783
+
784
+        $array_name_label=array();
785
+
786
+        // To avoid conflicts with external modules. TODO Remove this.
787
+        if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label;
788
+
789
+        // Set array of label of entity
790
+        // TODO Remove completely loading of label. This should be done by presentation.
791
+        $labelmulticompany=array();
792
+        if (!empty($conf->multicompany->enabled))
793
+        {
794
+            $sql_entity_name='SELECT rowid, label FROM '.MAIN_DB_PREFIX.'entity WHERE rowid in (0,'.$conf->entity.')';
795
+            $resql_entity_name=$this->db->query($sql_entity_name);
796
+            if ($resql_entity_name)
797
+            {
798
+                while ($obj = $this->db->fetch_object($resql_entity_name))
799
+                {
800
+                    $labelmulticompany[$obj->rowid]=$obj->label;
801
+                }
802
+            }
803
+        }
804
+
805
+        // We should not have several time this log. If we have, there is some optimization to do by calling a simple $object->fetch_optionals() that include cache management.
806
+        dol_syslog("fetch_name_optionals_label elementtype=".$elementtype);
807
+
808
+        $sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help";
809
+        $sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
810
+        $sql.= " WHERE entity IN (0,".$conf->entity.")";
811
+        if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'";	// Filed with object->table_element
812
+        $sql.= " ORDER BY pos";
813
+
814
+        $resql=$this->db->query($sql);
815
+        if ($resql)
816
+        {
817
+            if ($this->db->num_rows($resql))
818
+            {
819
+                while ($tab = $this->db->fetch_object($resql))
820
+                {
821
+                    // We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label']
822
+                    if ($tab->type != 'separate')
823
+                    {
824
+                        $array_name_label[$tab->name]=$tab->label;
825
+                    }
826
+
827
+                    // Old usage
828
+                    $this->attribute_type[$tab->name]=$tab->type;
829
+                    $this->attribute_label[$tab->name]=$tab->label;
830
+                    $this->attribute_size[$tab->name]=$tab->size;
831
+                    $this->attribute_elementtype[$tab->name]=$tab->elementtype;
832
+                    $this->attribute_default[$tab->name]=$tab->fielddefault;
833
+                    $this->attribute_computed[$tab->name]=$tab->fieldcomputed;
834
+                    $this->attribute_unique[$tab->name]=$tab->fieldunique;
835
+                    $this->attribute_required[$tab->name]=$tab->fieldrequired;
836
+                    $this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : '');
837
+                    $this->attribute_pos[$tab->name]=$tab->pos;
838
+                    $this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable;
839
+                    $this->attribute_perms[$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
840
+                    $this->attribute_langfile[$tab->name]=$tab->langs;
841
+                    $this->attribute_list[$tab->name]=$tab->list;
842
+                    $this->attribute_totalizable[$tab->name]=$tab->totalizable;
843
+                    $this->attribute_entityid[$tab->name]=$tab->entity;
844
+                    $this->attribute_entitylabel[$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
845
+
846
+                    // New usage
847
+                    $this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type;
848
+                    $this->attributes[$tab->elementtype]['label'][$tab->name]=$tab->label;
849
+                    $this->attributes[$tab->elementtype]['size'][$tab->name]=$tab->size;
850
+                    $this->attributes[$tab->elementtype]['elementtype'][$tab->name]=$tab->elementtype;
851
+                    $this->attributes[$tab->elementtype]['default'][$tab->name]=$tab->fielddefault;
852
+                    $this->attributes[$tab->elementtype]['computed'][$tab->name]=$tab->fieldcomputed;
853
+                    $this->attributes[$tab->elementtype]['unique'][$tab->name]=$tab->fieldunique;
854
+                    $this->attributes[$tab->elementtype]['required'][$tab->name]=$tab->fieldrequired;
855
+                    $this->attributes[$tab->elementtype]['param'][$tab->name]=($tab->param ? unserialize($tab->param) : '');
856
+                    $this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos;
857
+                    $this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable;
858
+                    $this->attributes[$tab->elementtype]['perms'][$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
859
+                    $this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs;
860
+                    $this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list;
861 861
                     $this->attributes[$tab->elementtype]['totalizable'][$tab->name]=$tab->totalizable;
862
-					$this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity;
863
-					$this->attributes[$tab->elementtype]['entitylabel'][$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
864
-					$this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled;
865
-					$this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help;
866
-
867
-					$this->attributes[$tab->elementtype]['loaded']=1;
868
-				}
869
-			}
870
-			if ($elementtype) $this->attributes[$elementtype]['loaded']=1;	// If nothing found, we also save tag 'loaded'
871
-		}
872
-		else
873
-		{
874
-			$this->error=$this->db->lasterror();
875
-			dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
876
-		}
877
-
878
-		return $array_name_label;
879
-	}
880
-
881
-
882
-	/**
883
-	 * Return HTML string to put an input field into a page
884
-	 * Code very similar with showInputField of common object
885
-	 *
886
-	 * @param  string  $key            			Key of attribute
887
-	 * @param  string  $value          			Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
888
-	 * @param  string  $moreparam      			To add more parametes on html input tag
889
-	 * @param  string  $keysuffix      			Prefix string to add after name and id of field (can be used to avoid duplicate names)
890
-	 * @param  string  $keyprefix      			Suffix string to add before name and id of field (can be used to avoid duplicate names)
891
-	 * @param  string  $morecss        			More css (to defined size of field. Old behaviour: may also be a numeric)
892
-	 * @param  int     $objectid       			Current object id
893
-	 * @param  string  $extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
894
-	 * @return string
895
-	 */
896
-	function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss='', $objectid=0, $extrafieldsobjectkey='')
897
-	{
898
-		global $conf,$langs,$form;
899
-
900
-		if (! is_object($form))
901
-		{
902
-			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
903
-			$form=new Form($this->db);
904
-		}
905
-
906
-		$out='';
907
-
908
-		$keyprefix = $keyprefix.'options_';		// Because we work on extrafields
909
-
910
-		if (! empty($extrafieldsobjectkey))
911
-		{
912
-			$label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
913
-			$type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
914
-			$size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
915
-			$default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
916
-			$computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
917
-			$unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
918
-			$required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
919
-			$param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
920
-			$perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
921
-			$langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
922
-			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
923
-			$totalizable=$this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
924
-			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
925
-			$hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
926
-		}
927
-		else	// Old usage
928
-		{
929
-			$label=$this->attribute_label[$key];
930
-			$type =$this->attribute_type[$key];
931
-			$size =$this->attribute_size[$key];
932
-			$elementtype=$this->attribute_elementtype[$key];	// Seems not used
933
-			$default=$this->attribute_default[$key];
934
-			$computed=$this->attribute_computed[$key];
935
-			$unique=$this->attribute_unique[$key];
936
-			$required=$this->attribute_required[$key];
937
-			$param=$this->attribute_param[$key];
938
-			$langfile=$this->attribute_langfile[$key];
939
-			$list=$this->attribute_list[$key];
940
-			$totalizable=$this->attribute_totalizable[$key];
941
-			$hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
942
-		}
943
-
944
-		if ($computed)
945
-		{
946
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
947
-			else return '';
948
-		}
949
-
950
-		if (empty($morecss))
951
-		{
952
-			if ($type == 'date')
953
-			{
954
-				$morecss = 'minwidth100imp';
955
-			}
956
-			elseif ($type == 'datetime')
957
-			{
958
-				$morecss = 'minwidth200imp';
959
-			}
960
-			elseif (in_array($type,array('int','integer','double','price')))
961
-			{
962
-				$morecss = 'maxwidth75';
963
-			}
964
-			elseif ($type == 'password')
965
-			{
966
-				$morecss='maxwidth100';
967
-			}
968
-			elseif ($type == 'url')
969
-			{
970
-				$morecss='minwidth400';
971
-			}
972
-			elseif ($type == 'boolean')
973
-			{
974
-				$morecss='';
975
-			}
976
-			else
977
-			{
978
-				if (round($size) < 12)
979
-				{
980
-					$morecss = 'minwidth100';
981
-				}
982
-				else if (round($size) <= 48)
983
-				{
984
-					$morecss = 'minwidth200';
985
-				}
986
-				else
987
-				{
988
-					$morecss = 'minwidth400';
989
-				}
990
-			}
991
-		}
992
-
993
-		if (in_array($type,array('date','datetime')))
994
-		{
995
-			$tmp=explode(',',$size);
996
-			$newsize=$tmp[0];
997
-
998
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
999
-
1000
-			// Do not show current date when field not required (see selectDate() method)
1001
-			if (!$required && $value == '') $value = '-1';
1002
-
1003
-			// TODO Must also support $moreparam
1004
-			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
1005
-		}
1006
-		elseif (in_array($type,array('int','integer')))
1007
-		{
1008
-			$tmp=explode(',',$size);
1009
-			$newsize=$tmp[0];
1010
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1011
-		}
1012
-		elseif (preg_match('/varchar/', $type))
1013
-		{
1014
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1015
-		}
1016
-		elseif (in_array($type, array('mail', 'phone', 'url')))
1017
-		{
1018
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1019
-		}
1020
-		elseif ($type == 'text')
1021
-		{
1022
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1023
-			{
1024
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1025
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
1026
-				$out=$doleditor->Create(1);
1027
-			}
1028
-			else
1029
-			{
1030
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1031
-			}
1032
-		}
1033
-		elseif ($type == 'html')
1034
-		{
1035
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1036
-			{
1037
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1038
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
1039
-				$out=$doleditor->Create(1);
1040
-			}
1041
-			else
1042
-			{
1043
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1044
-			}
1045
-		}
1046
-		elseif ($type == 'boolean')
1047
-		{
1048
-			$checked='';
1049
-			if (!empty($value)) {
1050
-				$checked=' checked value="1" ';
1051
-			} else {
1052
-				$checked=' value="1" ';
1053
-			}
1054
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
1055
-		}
1056
-		elseif ($type == 'price')
1057
-		{
1058
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1059
-				$value=price($value);
1060
-			}
1061
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
1062
-		}
1063
-		elseif ($type == 'double')
1064
-		{
1065
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1066
-				$value=price($value);
1067
-			}
1068
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
1069
-		}
1070
-		elseif ($type == 'select')
1071
-		{
1072
-			$out = '';
1073
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1074
-			{
1075
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1076
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1077
-			}
1078
-
1079
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1080
-			$out.='<option value="0">&nbsp;</option>';
1081
-			foreach ($param['options'] as $key => $val)
1082
-			{
1083
-				if ((string) $key == '') continue;
1084
-				list($val, $parent) = explode('|', $val);
1085
-				$out.='<option value="'.$key.'"';
1086
-				$out.= (((string) $value == (string) $key)?' selected':'');
1087
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
1088
-				$out.='>';
1089
-				if ($langfile && $val) $out.=$langs->trans($val);
1090
-				else $out.=$val;
1091
-				$out.='</option>';
1092
-			}
1093
-			$out.='</select>';
1094
-		}
1095
-		elseif ($type == 'sellist')
1096
-		{
1097
-			$out = '';
1098
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1099
-			{
1100
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1101
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1102
-			}
1103
-
1104
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1105
-			if (is_array($param['options']))
1106
-			{
1107
-				$param_list=array_keys($param['options']);
1108
-				$InfoFieldList = explode(":", $param_list[0]);
1109
-				$parentName='';
1110
-				$parentField='';
1111
-				// 0 : tableName
1112
-				// 1 : label field name
1113
-				// 2 : key fields name (if differ of rowid)
1114
-				// 3 : key field parent (for dependent lists)
1115
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1116
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
1117
-
1118
-
1119
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
1120
-				{
1121
-					if (strpos($InfoFieldList[4], 'extra.') !== false)
1122
-					{
1123
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
1124
-					} else {
1125
-						$keyList=$InfoFieldList[2].' as rowid';
1126
-					}
1127
-				}
1128
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
1129
-				{
1130
-					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
1131
-					$keyList.= ', '.$parentField;
1132
-				}
1133
-
1134
-				$fields_label = explode('|',$InfoFieldList[1]);
1135
-				if (is_array($fields_label))
1136
-				{
1137
-					$keyList .=', ';
1138
-					$keyList .= implode(', ', $fields_label);
1139
-				}
1140
-
1141
-				$sqlwhere='';
1142
-				$sql = 'SELECT '.$keyList;
1143
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1144
-				if (!empty($InfoFieldList[4]))
1145
-				{
1146
-				    // can use curent entity filter
1147
-				    if (strpos($InfoFieldList[4], '$ENTITY$')!==false) {
1148
-				        $InfoFieldList[4]=str_replace('$ENTITY$',$conf->entity,$InfoFieldList[4]);
1149
-				    }
1150
-					// can use SELECT request
1151
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1152
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1153
-					}
1154
-
1155
-					// current object id can be use into filter
1156
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1157
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1158
-					} else {
1159
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1160
-					}
1161
-					//We have to join on extrafield table
1162
-					if (strpos($InfoFieldList[4], 'extra')!==false)
1163
-					{
1164
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
1165
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
1166
-					}
1167
-					else
1168
-					{
1169
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
1170
-					}
1171
-				}
1172
-				else
1173
-				{
1174
-					$sqlwhere.= ' WHERE 1=1';
1175
-				}
1176
-				// Some tables may have field, some other not. For the moment we disable it.
1177
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
1178
-				{
1179
-					$sqlwhere.= ' AND entity = '.$conf->entity;
1180
-				}
1181
-				$sql.=$sqlwhere;
1182
-				//print $sql;
1183
-
1184
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
1185
-
1186
-				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
1187
-				$resql = $this->db->query($sql);
1188
-				if ($resql)
1189
-				{
1190
-					$out.='<option value="0">&nbsp;</option>';
1191
-					$num = $this->db->num_rows($resql);
1192
-					$i = 0;
1193
-					while ($i < $num)
1194
-					{
1195
-						$labeltoshow='';
1196
-						$obj = $this->db->fetch_object($resql);
1197
-
1198
-						// Several field into label (eq table:code|libelle:rowid)
1199
-						$notrans = false;
1200
-						$fields_label = explode('|',$InfoFieldList[1]);
1201
-						if (is_array($fields_label))
1202
-						{
1203
-							$notrans = true;
1204
-							foreach ($fields_label as $field_toshow)
1205
-							{
1206
-								$labeltoshow.= $obj->$field_toshow.' ';
1207
-							}
1208
-						}
1209
-						else
1210
-						{
1211
-							$labeltoshow=$obj->{$InfoFieldList[1]};
1212
-						}
1213
-						$labeltoshow=dol_trunc($labeltoshow,45);
1214
-
1215
-						if ($value == $obj->rowid)
1216
-						{
1217
-							foreach ($fields_label as $field_toshow)
1218
-							{
1219
-								$translabel=$langs->trans($obj->$field_toshow);
1220
-								if ($translabel!=$obj->$field_toshow) {
1221
-									$labeltoshow=dol_trunc($translabel,18).' ';
1222
-								}else {
1223
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
1224
-								}
1225
-							}
1226
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1227
-						}
1228
-						else
1229
-						{
1230
-							if (! $notrans)
1231
-							{
1232
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
1233
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
1234
-									$labeltoshow=dol_trunc($translabel,18);
1235
-								}
1236
-								else {
1237
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
1238
-								}
1239
-							}
1240
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
1241
-							if ($value==$obj->rowid)
1242
-							{
1243
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1244
-							}
1245
-
1246
-							if (!empty($InfoFieldList[3]) && $parentField)
1247
-							{
1248
-								$parent = $parentName.':'.$obj->{$parentField};
1249
-							}
1250
-
1251
-							$out.='<option value="'.$obj->rowid.'"';
1252
-							$out.= ($value==$obj->rowid?' selected':'');
1253
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
1254
-							$out.='>'.$labeltoshow.'</option>';
1255
-						}
1256
-
1257
-						$i++;
1258
-					}
1259
-					$this->db->free($resql);
1260
-				}
1261
-				else {
1262
-					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
1263
-				}
1264
-			}
1265
-			$out.='</select>';
1266
-		}
1267
-		elseif ($type == 'checkbox')
1268
-		{
1269
-			$value_arr=explode(',',$value);
1270
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
1271
-		}
1272
-		elseif ($type == 'radio')
1273
-		{
1274
-			$out='';
1275
-			foreach ($param['options'] as $keyopt => $val)
1276
-			{
1277
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
1278
-				$out.=' value="'.$keyopt.'"';
1279
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
1280
-				$out.= ($value==$keyopt?'checked':'');
1281
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
1282
-			}
1283
-		}
1284
-		elseif ($type == 'chkbxlst')
1285
-		{
1286
-			if (is_array($value)) {
1287
-				$value_arr = $value;
1288
-			}
1289
-			else {
1290
-				$value_arr = explode(',', $value);
1291
-			}
1292
-
1293
-			if (is_array($param['options'])) {
1294
-				$param_list = array_keys($param['options']);
1295
-				$InfoFieldList = explode(":", $param_list[0]);
1296
-				$parentName='';
1297
-				$parentField='';
1298
-				// 0 : tableName
1299
-				// 1 : label field name
1300
-				// 2 : key fields name (if differ of rowid)
1301
-				// 3 : key field parent (for dependent lists)
1302
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1303
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
1304
-
1305
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
1306
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
1307
-					$keyList .= ', ' . $parentField;
1308
-				}
1309
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
1310
-					if (strpos($InfoFieldList[4], 'extra.') !== false) {
1311
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
1312
-					} else {
1313
-						$keyList = $InfoFieldList[2] . ' as rowid';
1314
-					}
1315
-				}
1316
-
1317
-				$fields_label = explode('|', $InfoFieldList[1]);
1318
-				if (is_array($fields_label)) {
1319
-					$keyList .= ', ';
1320
-					$keyList .= implode(', ', $fields_label);
1321
-				}
1322
-
1323
-				$sqlwhere = '';
1324
-				$sql = 'SELECT ' . $keyList;
1325
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1326
-				if (! empty($InfoFieldList[4])) {
1327
-
1328
-					// can use SELECT request
1329
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1330
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1331
-					}
1332
-
1333
-					// current object id can be use into filter
1334
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1335
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1336
-					} else if (preg_match("#^.*list.php$#",$_SERVER["DOCUMENT_URI"])) {
1337
-						// Pattern for word=$ID$
1338
-						$word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$';
862
+                    $this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity;
863
+                    $this->attributes[$tab->elementtype]['entitylabel'][$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
864
+                    $this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled;
865
+                    $this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help;
866
+
867
+                    $this->attributes[$tab->elementtype]['loaded']=1;
868
+                }
869
+            }
870
+            if ($elementtype) $this->attributes[$elementtype]['loaded']=1;	// If nothing found, we also save tag 'loaded'
871
+        }
872
+        else
873
+        {
874
+            $this->error=$this->db->lasterror();
875
+            dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
876
+        }
877
+
878
+        return $array_name_label;
879
+    }
880
+
881
+
882
+    /**
883
+     * Return HTML string to put an input field into a page
884
+     * Code very similar with showInputField of common object
885
+     *
886
+     * @param  string  $key            			Key of attribute
887
+     * @param  string  $value          			Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
888
+     * @param  string  $moreparam      			To add more parametes on html input tag
889
+     * @param  string  $keysuffix      			Prefix string to add after name and id of field (can be used to avoid duplicate names)
890
+     * @param  string  $keyprefix      			Suffix string to add before name and id of field (can be used to avoid duplicate names)
891
+     * @param  string  $morecss        			More css (to defined size of field. Old behaviour: may also be a numeric)
892
+     * @param  int     $objectid       			Current object id
893
+     * @param  string  $extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
894
+     * @return string
895
+     */
896
+    function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss='', $objectid=0, $extrafieldsobjectkey='')
897
+    {
898
+        global $conf,$langs,$form;
899
+
900
+        if (! is_object($form))
901
+        {
902
+            require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
903
+            $form=new Form($this->db);
904
+        }
905
+
906
+        $out='';
907
+
908
+        $keyprefix = $keyprefix.'options_';		// Because we work on extrafields
909
+
910
+        if (! empty($extrafieldsobjectkey))
911
+        {
912
+            $label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
913
+            $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
914
+            $size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
915
+            $default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
916
+            $computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
917
+            $unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
918
+            $required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
919
+            $param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
920
+            $perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
921
+            $langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
922
+            $list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
923
+            $totalizable=$this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
924
+            $help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
925
+            $hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
926
+        }
927
+        else	// Old usage
928
+        {
929
+            $label=$this->attribute_label[$key];
930
+            $type =$this->attribute_type[$key];
931
+            $size =$this->attribute_size[$key];
932
+            $elementtype=$this->attribute_elementtype[$key];	// Seems not used
933
+            $default=$this->attribute_default[$key];
934
+            $computed=$this->attribute_computed[$key];
935
+            $unique=$this->attribute_unique[$key];
936
+            $required=$this->attribute_required[$key];
937
+            $param=$this->attribute_param[$key];
938
+            $langfile=$this->attribute_langfile[$key];
939
+            $list=$this->attribute_list[$key];
940
+            $totalizable=$this->attribute_totalizable[$key];
941
+            $hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
942
+        }
943
+
944
+        if ($computed)
945
+        {
946
+            if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
947
+            else return '';
948
+        }
949
+
950
+        if (empty($morecss))
951
+        {
952
+            if ($type == 'date')
953
+            {
954
+                $morecss = 'minwidth100imp';
955
+            }
956
+            elseif ($type == 'datetime')
957
+            {
958
+                $morecss = 'minwidth200imp';
959
+            }
960
+            elseif (in_array($type,array('int','integer','double','price')))
961
+            {
962
+                $morecss = 'maxwidth75';
963
+            }
964
+            elseif ($type == 'password')
965
+            {
966
+                $morecss='maxwidth100';
967
+            }
968
+            elseif ($type == 'url')
969
+            {
970
+                $morecss='minwidth400';
971
+            }
972
+            elseif ($type == 'boolean')
973
+            {
974
+                $morecss='';
975
+            }
976
+            else
977
+            {
978
+                if (round($size) < 12)
979
+                {
980
+                    $morecss = 'minwidth100';
981
+                }
982
+                else if (round($size) <= 48)
983
+                {
984
+                    $morecss = 'minwidth200';
985
+                }
986
+                else
987
+                {
988
+                    $morecss = 'minwidth400';
989
+                }
990
+            }
991
+        }
992
+
993
+        if (in_array($type,array('date','datetime')))
994
+        {
995
+            $tmp=explode(',',$size);
996
+            $newsize=$tmp[0];
997
+
998
+            $showtime = in_array($type,array('datetime')) ? 1 : 0;
999
+
1000
+            // Do not show current date when field not required (see selectDate() method)
1001
+            if (!$required && $value == '') $value = '-1';
1002
+
1003
+            // TODO Must also support $moreparam
1004
+            $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
1005
+        }
1006
+        elseif (in_array($type,array('int','integer')))
1007
+        {
1008
+            $tmp=explode(',',$size);
1009
+            $newsize=$tmp[0];
1010
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1011
+        }
1012
+        elseif (preg_match('/varchar/', $type))
1013
+        {
1014
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1015
+        }
1016
+        elseif (in_array($type, array('mail', 'phone', 'url')))
1017
+        {
1018
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1019
+        }
1020
+        elseif ($type == 'text')
1021
+        {
1022
+            if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1023
+            {
1024
+                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1025
+                $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
1026
+                $out=$doleditor->Create(1);
1027
+            }
1028
+            else
1029
+            {
1030
+                $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1031
+            }
1032
+        }
1033
+        elseif ($type == 'html')
1034
+        {
1035
+            if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1036
+            {
1037
+                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1038
+                $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
1039
+                $out=$doleditor->Create(1);
1040
+            }
1041
+            else
1042
+            {
1043
+                $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1044
+            }
1045
+        }
1046
+        elseif ($type == 'boolean')
1047
+        {
1048
+            $checked='';
1049
+            if (!empty($value)) {
1050
+                $checked=' checked value="1" ';
1051
+            } else {
1052
+                $checked=' value="1" ';
1053
+            }
1054
+            $out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
1055
+        }
1056
+        elseif ($type == 'price')
1057
+        {
1058
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1059
+                $value=price($value);
1060
+            }
1061
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
1062
+        }
1063
+        elseif ($type == 'double')
1064
+        {
1065
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1066
+                $value=price($value);
1067
+            }
1068
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
1069
+        }
1070
+        elseif ($type == 'select')
1071
+        {
1072
+            $out = '';
1073
+            if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1074
+            {
1075
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1076
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1077
+            }
1078
+
1079
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1080
+            $out.='<option value="0">&nbsp;</option>';
1081
+            foreach ($param['options'] as $key => $val)
1082
+            {
1083
+                if ((string) $key == '') continue;
1084
+                list($val, $parent) = explode('|', $val);
1085
+                $out.='<option value="'.$key.'"';
1086
+                $out.= (((string) $value == (string) $key)?' selected':'');
1087
+                $out.= (!empty($parent)?' parent="'.$parent.'"':'');
1088
+                $out.='>';
1089
+                if ($langfile && $val) $out.=$langs->trans($val);
1090
+                else $out.=$val;
1091
+                $out.='</option>';
1092
+            }
1093
+            $out.='</select>';
1094
+        }
1095
+        elseif ($type == 'sellist')
1096
+        {
1097
+            $out = '';
1098
+            if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1099
+            {
1100
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1101
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1102
+            }
1103
+
1104
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1105
+            if (is_array($param['options']))
1106
+            {
1107
+                $param_list=array_keys($param['options']);
1108
+                $InfoFieldList = explode(":", $param_list[0]);
1109
+                $parentName='';
1110
+                $parentField='';
1111
+                // 0 : tableName
1112
+                // 1 : label field name
1113
+                // 2 : key fields name (if differ of rowid)
1114
+                // 3 : key field parent (for dependent lists)
1115
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1116
+                $keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
1117
+
1118
+
1119
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
1120
+                {
1121
+                    if (strpos($InfoFieldList[4], 'extra.') !== false)
1122
+                    {
1123
+                        $keyList='main.'.$InfoFieldList[2].' as rowid';
1124
+                    } else {
1125
+                        $keyList=$InfoFieldList[2].' as rowid';
1126
+                    }
1127
+                }
1128
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
1129
+                {
1130
+                    list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
1131
+                    $keyList.= ', '.$parentField;
1132
+                }
1133
+
1134
+                $fields_label = explode('|',$InfoFieldList[1]);
1135
+                if (is_array($fields_label))
1136
+                {
1137
+                    $keyList .=', ';
1138
+                    $keyList .= implode(', ', $fields_label);
1139
+                }
1140
+
1141
+                $sqlwhere='';
1142
+                $sql = 'SELECT '.$keyList;
1143
+                $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1144
+                if (!empty($InfoFieldList[4]))
1145
+                {
1146
+                    // can use curent entity filter
1147
+                    if (strpos($InfoFieldList[4], '$ENTITY$')!==false) {
1148
+                        $InfoFieldList[4]=str_replace('$ENTITY$',$conf->entity,$InfoFieldList[4]);
1149
+                    }
1150
+                    // can use SELECT request
1151
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1152
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1153
+                    }
1154
+
1155
+                    // current object id can be use into filter
1156
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1157
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1158
+                    } else {
1159
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1160
+                    }
1161
+                    //We have to join on extrafield table
1162
+                    if (strpos($InfoFieldList[4], 'extra')!==false)
1163
+                    {
1164
+                        $sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
1165
+                        $sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
1166
+                    }
1167
+                    else
1168
+                    {
1169
+                        $sqlwhere.= ' WHERE '.$InfoFieldList[4];
1170
+                    }
1171
+                }
1172
+                else
1173
+                {
1174
+                    $sqlwhere.= ' WHERE 1=1';
1175
+                }
1176
+                // Some tables may have field, some other not. For the moment we disable it.
1177
+                if (in_array($InfoFieldList[0],array('tablewithentity')))
1178
+                {
1179
+                    $sqlwhere.= ' AND entity = '.$conf->entity;
1180
+                }
1181
+                $sql.=$sqlwhere;
1182
+                //print $sql;
1183
+
1184
+                $sql .= ' ORDER BY ' . implode(', ', $fields_label);
1185
+
1186
+                dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
1187
+                $resql = $this->db->query($sql);
1188
+                if ($resql)
1189
+                {
1190
+                    $out.='<option value="0">&nbsp;</option>';
1191
+                    $num = $this->db->num_rows($resql);
1192
+                    $i = 0;
1193
+                    while ($i < $num)
1194
+                    {
1195
+                        $labeltoshow='';
1196
+                        $obj = $this->db->fetch_object($resql);
1197
+
1198
+                        // Several field into label (eq table:code|libelle:rowid)
1199
+                        $notrans = false;
1200
+                        $fields_label = explode('|',$InfoFieldList[1]);
1201
+                        if (is_array($fields_label))
1202
+                        {
1203
+                            $notrans = true;
1204
+                            foreach ($fields_label as $field_toshow)
1205
+                            {
1206
+                                $labeltoshow.= $obj->$field_toshow.' ';
1207
+                            }
1208
+                        }
1209
+                        else
1210
+                        {
1211
+                            $labeltoshow=$obj->{$InfoFieldList[1]};
1212
+                        }
1213
+                        $labeltoshow=dol_trunc($labeltoshow,45);
1214
+
1215
+                        if ($value == $obj->rowid)
1216
+                        {
1217
+                            foreach ($fields_label as $field_toshow)
1218
+                            {
1219
+                                $translabel=$langs->trans($obj->$field_toshow);
1220
+                                if ($translabel!=$obj->$field_toshow) {
1221
+                                    $labeltoshow=dol_trunc($translabel,18).' ';
1222
+                                }else {
1223
+                                    $labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
1224
+                                }
1225
+                            }
1226
+                            $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1227
+                        }
1228
+                        else
1229
+                        {
1230
+                            if (! $notrans)
1231
+                            {
1232
+                                $translabel=$langs->trans($obj->{$InfoFieldList[1]});
1233
+                                if ($translabel!=$obj->{$InfoFieldList[1]}) {
1234
+                                    $labeltoshow=dol_trunc($translabel,18);
1235
+                                }
1236
+                                else {
1237
+                                    $labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
1238
+                                }
1239
+                            }
1240
+                            if (empty($labeltoshow)) $labeltoshow='(not defined)';
1241
+                            if ($value==$obj->rowid)
1242
+                            {
1243
+                                $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1244
+                            }
1245
+
1246
+                            if (!empty($InfoFieldList[3]) && $parentField)
1247
+                            {
1248
+                                $parent = $parentName.':'.$obj->{$parentField};
1249
+                            }
1250
+
1251
+                            $out.='<option value="'.$obj->rowid.'"';
1252
+                            $out.= ($value==$obj->rowid?' selected':'');
1253
+                            $out.= (!empty($parent)?' parent="'.$parent.'"':'');
1254
+                            $out.='>'.$labeltoshow.'</option>';
1255
+                        }
1256
+
1257
+                        $i++;
1258
+                    }
1259
+                    $this->db->free($resql);
1260
+                }
1261
+                else {
1262
+                    print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
1263
+                }
1264
+            }
1265
+            $out.='</select>';
1266
+        }
1267
+        elseif ($type == 'checkbox')
1268
+        {
1269
+            $value_arr=explode(',',$value);
1270
+            $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
1271
+        }
1272
+        elseif ($type == 'radio')
1273
+        {
1274
+            $out='';
1275
+            foreach ($param['options'] as $keyopt => $val)
1276
+            {
1277
+                $out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
1278
+                $out.=' value="'.$keyopt.'"';
1279
+                $out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
1280
+                $out.= ($value==$keyopt?'checked':'');
1281
+                $out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
1282
+            }
1283
+        }
1284
+        elseif ($type == 'chkbxlst')
1285
+        {
1286
+            if (is_array($value)) {
1287
+                $value_arr = $value;
1288
+            }
1289
+            else {
1290
+                $value_arr = explode(',', $value);
1291
+            }
1292
+
1293
+            if (is_array($param['options'])) {
1294
+                $param_list = array_keys($param['options']);
1295
+                $InfoFieldList = explode(":", $param_list[0]);
1296
+                $parentName='';
1297
+                $parentField='';
1298
+                // 0 : tableName
1299
+                // 1 : label field name
1300
+                // 2 : key fields name (if differ of rowid)
1301
+                // 3 : key field parent (for dependent lists)
1302
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1303
+                $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
1304
+
1305
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
1306
+                    list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
1307
+                    $keyList .= ', ' . $parentField;
1308
+                }
1309
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
1310
+                    if (strpos($InfoFieldList[4], 'extra.') !== false) {
1311
+                        $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
1312
+                    } else {
1313
+                        $keyList = $InfoFieldList[2] . ' as rowid';
1314
+                    }
1315
+                }
1316
+
1317
+                $fields_label = explode('|', $InfoFieldList[1]);
1318
+                if (is_array($fields_label)) {
1319
+                    $keyList .= ', ';
1320
+                    $keyList .= implode(', ', $fields_label);
1321
+                }
1322
+
1323
+                $sqlwhere = '';
1324
+                $sql = 'SELECT ' . $keyList;
1325
+                $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1326
+                if (! empty($InfoFieldList[4])) {
1327
+
1328
+                    // can use SELECT request
1329
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1330
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1331
+                    }
1332
+
1333
+                    // current object id can be use into filter
1334
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1335
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1336
+                    } else if (preg_match("#^.*list.php$#",$_SERVER["DOCUMENT_URI"])) {
1337
+                        // Pattern for word=$ID$
1338
+                        $word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$';
1339 1339
 						
1340
-						// Removing space arount =, ( and )
1341
-						$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1340
+                        // Removing space arount =, ( and )
1341
+                        $InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1342 1342
 						
1343
-						$nbPreg = 1;
1344
-						// While we have parenthesis
1345
-						while ($nbPreg!=0) {
1346
-							// Init des compteurs
1347
-							$nbPregRepl = $nbPregSel = 0;
1348
-							// On retire toutes les parenthèses sans = avant
1349
-							$InfoFieldList[4]=preg_replace( '#([^=])(\([^)^(]*(' . $word .   ')[^)^(]*\))#','$1 $3 ',$InfoFieldList[4],-1,$nbPregRepl);
1350
-							// On retire les espaces autour des = et parenthèses
1351
-							$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1352
-							// On retire toutes les parenthèses avec = avant
1353
-							$InfoFieldList[4]=preg_replace(  '#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*(' . $word .   ')[^)^(]*\)#','$1 ',$InfoFieldList[4], -1, $nbPregSel);
1354
-							// On retire les espaces autour des = et parenthèses
1355
-							$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1343
+                        $nbPreg = 1;
1344
+                        // While we have parenthesis
1345
+                        while ($nbPreg!=0) {
1346
+                            // Init des compteurs
1347
+                            $nbPregRepl = $nbPregSel = 0;
1348
+                            // On retire toutes les parenthèses sans = avant
1349
+                            $InfoFieldList[4]=preg_replace( '#([^=])(\([^)^(]*(' . $word .   ')[^)^(]*\))#','$1 $3 ',$InfoFieldList[4],-1,$nbPregRepl);
1350
+                            // On retire les espaces autour des = et parenthèses
1351
+                            $InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1352
+                            // On retire toutes les parenthèses avec = avant
1353
+                            $InfoFieldList[4]=preg_replace(  '#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*(' . $word .   ')[^)^(]*\)#','$1 ',$InfoFieldList[4], -1, $nbPregSel);
1354
+                            // On retire les espaces autour des = et parenthèses
1355
+                            $InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1356 1356
 							
1357
-							// Calcul du compteur général pour la boucle
1358
-							$nbPreg = $nbPregRepl + $nbPregSel;
1359
-						}
1357
+                            // Calcul du compteur général pour la boucle
1358
+                            $nbPreg = $nbPregRepl + $nbPregSel;
1359
+                        }
1360 1360
 						
1361
-						// Si l'on a un AND ou un OR, avant ou après
1362
-						preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1363
-						while(!empty($matchCondition[0])) {
1364
-							// If the two sides differ but are not empty
1365
-							if (! empty($matchCondition[1]) && ! empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3] ) {
1366
-								// Nobody sain would do that without parentheses
1367
-								$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1368
-							}
1369
-							else {
1370
-								if (! empty($matchCondition[1])) {
1371
-									$boolCond =(( $matchCondition[1] == "AND" )?' AND 1 ':' OR 0 ');
1372
-									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond.$matchCondition[3],$InfoFieldList[4]);
1373
-								}
1374
-								else if (! empty($matchCondition[3])) {
1375
-									$boolCond =(( $matchCondition[3] == "AND" )?' 1 AND ':' 0 OR');
1376
-									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond,$InfoFieldList[4]);
1377
-								}
1378
-								else {
1379
-									$InfoFieldList[4] = 1;
1380
-								}
1381
-							}
1361
+                        // Si l'on a un AND ou un OR, avant ou après
1362
+                        preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1363
+                        while(!empty($matchCondition[0])) {
1364
+                            // If the two sides differ but are not empty
1365
+                            if (! empty($matchCondition[1]) && ! empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3] ) {
1366
+                                // Nobody sain would do that without parentheses
1367
+                                $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1368
+                            }
1369
+                            else {
1370
+                                if (! empty($matchCondition[1])) {
1371
+                                    $boolCond =(( $matchCondition[1] == "AND" )?' AND 1 ':' OR 0 ');
1372
+                                    $InfoFieldList[4]=str_replace($matchCondition[0],$boolCond.$matchCondition[3],$InfoFieldList[4]);
1373
+                                }
1374
+                                else if (! empty($matchCondition[3])) {
1375
+                                    $boolCond =(( $matchCondition[3] == "AND" )?' 1 AND ':' 0 OR');
1376
+                                    $InfoFieldList[4]=str_replace($matchCondition[0],$boolCond,$InfoFieldList[4]);
1377
+                                }
1378
+                                else {
1379
+                                    $InfoFieldList[4] = 1;
1380
+                                }
1381
+                            }
1382 1382
 							
1383
-							// Si l'on a un AND ou un OR, avant ou après
1384
-							preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1385
-						}
1386
-					}
1387
-					else {
1388
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1389
-					}
1390
-
1391
-					// We have to join on extrafield table
1392
-					if (strpos($InfoFieldList[4], 'extra') !== false) {
1393
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
1394
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
1395
-					} else {
1396
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
1397
-					}
1398
-				} else {
1399
-					$sqlwhere .= ' WHERE 1=1';
1400
-				}
1401
-				// Some tables may have field, some other not. For the moment we disable it.
1402
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
1403
-				{
1404
-					$sqlwhere .= ' AND entity = ' . $conf->entity;
1405
-				}
1406
-				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
1407
-				// print $sql;
1408
-
1409
-				$sql .= $sqlwhere;
1410
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
1411
-				$resql = $this->db->query($sql);
1412
-				if ($resql) {
1413
-					$num = $this->db->num_rows($resql);
1414
-					$i = 0;
1415
-
1416
-					$data=array();
1417
-
1418
-					while ( $i < $num ) {
1419
-						$labeltoshow = '';
1420
-						$obj = $this->db->fetch_object($resql);
1421
-
1422
-						$notrans = false;
1423
-						// Several field into label (eq table:code|libelle:rowid)
1424
-						$fields_label = explode('|', $InfoFieldList[1]);
1425
-						if (is_array($fields_label)) {
1426
-							$notrans = true;
1427
-							foreach ( $fields_label as $field_toshow ) {
1428
-								$labeltoshow .= $obj->$field_toshow . ' ';
1429
-							}
1430
-						} else {
1431
-							$labeltoshow = $obj->{$InfoFieldList[1]};
1432
-						}
1433
-						$labeltoshow = dol_trunc($labeltoshow, 45);
1434
-
1435
-						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1436
-							foreach ( $fields_label as $field_toshow ) {
1437
-								$translabel = $langs->trans($obj->$field_toshow);
1438
-								if ($translabel != $obj->$field_toshow) {
1439
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
1440
-								} else {
1441
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
1442
-								}
1443
-							}
1444
-
1445
-							$data[$obj->rowid]=$labeltoshow;
1446
-						} else {
1447
-							if (! $notrans) {
1448
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1449
-								if ($translabel != $obj->{$InfoFieldList[1]}) {
1450
-									$labeltoshow = dol_trunc($translabel, 18);
1451
-								} else {
1452
-									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
1453
-								}
1454
-							}
1455
-							if (empty($labeltoshow))
1456
-								$labeltoshow = '(not defined)';
1457
-
1458
-								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1459
-									$data[$obj->rowid]=$labeltoshow;
1460
-								}
1461
-
1462
-								if (! empty($InfoFieldList[3]) && $parentField) {
1463
-									$parent = $parentName . ':' . $obj->{$parentField};
1464
-								}
1465
-
1466
-								$data[$obj->rowid]=$labeltoshow;
1467
-						}
1468
-
1469
-						$i ++;
1470
-					}
1471
-					$this->db->free($resql);
1472
-
1473
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
1474
-				} else {
1475
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
1476
-				}
1477
-			}
1478
-		}
1479
-		elseif ($type == 'link')
1480
-		{
1481
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1482
-			$showempty=(($required && $default != '')?0:1);
1483
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
1484
-		}
1485
-		elseif ($type == 'password')
1486
-		{
1487
-			// If prefix is 'search_', field is used as a filter, we use a common text field.
1488
-			$out='<input style="display:none" type="text" name="fakeusernameremembered">';	// Hidden field to reduce impact of evil Google Chrome autopopulate bug.
1489
-			$out.='<input autocomplete="new-password" type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
1490
-		}
1491
-		if (!empty($hidden)) {
1492
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
1493
-		}
1494
-		/* Add comments
1383
+                            // Si l'on a un AND ou un OR, avant ou après
1384
+                            preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1385
+                        }
1386
+                    }
1387
+                    else {
1388
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1389
+                    }
1390
+
1391
+                    // We have to join on extrafield table
1392
+                    if (strpos($InfoFieldList[4], 'extra') !== false) {
1393
+                        $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
1394
+                        $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
1395
+                    } else {
1396
+                        $sqlwhere .= ' WHERE ' . $InfoFieldList[4];
1397
+                    }
1398
+                } else {
1399
+                    $sqlwhere .= ' WHERE 1=1';
1400
+                }
1401
+                // Some tables may have field, some other not. For the moment we disable it.
1402
+                if (in_array($InfoFieldList[0], array ('tablewithentity')))
1403
+                {
1404
+                    $sqlwhere .= ' AND entity = ' . $conf->entity;
1405
+                }
1406
+                // $sql.=preg_replace('/^ AND /','',$sqlwhere);
1407
+                // print $sql;
1408
+
1409
+                $sql .= $sqlwhere;
1410
+                dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
1411
+                $resql = $this->db->query($sql);
1412
+                if ($resql) {
1413
+                    $num = $this->db->num_rows($resql);
1414
+                    $i = 0;
1415
+
1416
+                    $data=array();
1417
+
1418
+                    while ( $i < $num ) {
1419
+                        $labeltoshow = '';
1420
+                        $obj = $this->db->fetch_object($resql);
1421
+
1422
+                        $notrans = false;
1423
+                        // Several field into label (eq table:code|libelle:rowid)
1424
+                        $fields_label = explode('|', $InfoFieldList[1]);
1425
+                        if (is_array($fields_label)) {
1426
+                            $notrans = true;
1427
+                            foreach ( $fields_label as $field_toshow ) {
1428
+                                $labeltoshow .= $obj->$field_toshow . ' ';
1429
+                            }
1430
+                        } else {
1431
+                            $labeltoshow = $obj->{$InfoFieldList[1]};
1432
+                        }
1433
+                        $labeltoshow = dol_trunc($labeltoshow, 45);
1434
+
1435
+                        if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1436
+                            foreach ( $fields_label as $field_toshow ) {
1437
+                                $translabel = $langs->trans($obj->$field_toshow);
1438
+                                if ($translabel != $obj->$field_toshow) {
1439
+                                    $labeltoshow = dol_trunc($translabel, 18) . ' ';
1440
+                                } else {
1441
+                                    $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
1442
+                                }
1443
+                            }
1444
+
1445
+                            $data[$obj->rowid]=$labeltoshow;
1446
+                        } else {
1447
+                            if (! $notrans) {
1448
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
1449
+                                if ($translabel != $obj->{$InfoFieldList[1]}) {
1450
+                                    $labeltoshow = dol_trunc($translabel, 18);
1451
+                                } else {
1452
+                                    $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
1453
+                                }
1454
+                            }
1455
+                            if (empty($labeltoshow))
1456
+                                $labeltoshow = '(not defined)';
1457
+
1458
+                                if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1459
+                                    $data[$obj->rowid]=$labeltoshow;
1460
+                                }
1461
+
1462
+                                if (! empty($InfoFieldList[3]) && $parentField) {
1463
+                                    $parent = $parentName . ':' . $obj->{$parentField};
1464
+                                }
1465
+
1466
+                                $data[$obj->rowid]=$labeltoshow;
1467
+                        }
1468
+
1469
+                        $i ++;
1470
+                    }
1471
+                    $this->db->free($resql);
1472
+
1473
+                    $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
1474
+                } else {
1475
+                    print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
1476
+                }
1477
+            }
1478
+        }
1479
+        elseif ($type == 'link')
1480
+        {
1481
+            $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1482
+            $showempty=(($required && $default != '')?0:1);
1483
+            $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
1484
+        }
1485
+        elseif ($type == 'password')
1486
+        {
1487
+            // If prefix is 'search_', field is used as a filter, we use a common text field.
1488
+            $out='<input style="display:none" type="text" name="fakeusernameremembered">';	// Hidden field to reduce impact of evil Google Chrome autopopulate bug.
1489
+            $out.='<input autocomplete="new-password" type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
1490
+        }
1491
+        if (!empty($hidden)) {
1492
+            $out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
1493
+        }
1494
+        /* Add comments
1495 1495
 		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
1496 1496
 		 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
1497 1497
 		 */
1498
-		return $out;
1499
-	}
1500
-
1501
-
1502
-	/**
1503
-	 * Return HTML string to put an output field into a page
1504
-	 *
1505
-	 * @param   string	$key            		Key of attribute
1506
-	 * @param   string	$value          		Value to show
1507
-	 * @param	string	$moreparam				To add more parameters on html input tag (only checkbox use html input for output rendering)
1508
-	 * @param	string	$extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
1509
-	 * @return	string							Formated value
1510
-	 */
1511
-	function showOutputField($key, $value, $moreparam='', $extrafieldsobjectkey='')
1512
-	{
1513
-		global $conf,$langs;
1514
-
1515
-		if (! empty($extrafieldsobjectkey))
1516
-		{
1517
-			$label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
1518
-			$type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1519
-			$size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
1520
-			$default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
1521
-			$computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
1522
-			$unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
1523
-			$required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
1524
-			$param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
1525
-			$perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
1526
-			$langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
1527
-			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
1528
-			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
1529
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1530
-		}
1531
-		else	// Old usage
1532
-		{
1533
-			$label=$this->attribute_label[$key];
1534
-			$type=$this->attribute_type[$key];
1535
-			$size=$this->attribute_size[$key];
1536
-			$default=$this->attribute_default[$key];
1537
-			$computed=$this->attribute_computed[$key];
1538
-			$unique=$this->attribute_unique[$key];
1539
-			$required=$this->attribute_required[$key];
1540
-			$param=$this->attribute_param[$key];
1541
-			$perms=dol_eval($this->attribute_perms[$key], 1);
1542
-			$langfile=$this->attribute_langfile[$key];
1543
-			$list=dol_eval($this->attribute_list[$key], 1);
1544
-			$help='';	// Not supported with old syntax
1545
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1546
-		}
1547
-
1548
-		if ($hidden) return '';		// This is a protection. If field is hidden, we should just not call this method.
1549
-
1550
-		// If field is a computed field, value must become result of compute
1551
-		if ($computed)
1552
-		{
1553
-		    // Make the eval of compute string
1554
-		    //var_dump($computed);
1555
-		    $value = dol_eval($computed, 1, 0);
1556
-		}
1557
-
1558
-		$showsize=0;
1559
-		if ($type == 'date')
1560
-		{
1561
-			$showsize=10;
1562
-			$value=dol_print_date($value, 'day');
1563
-		}
1564
-		elseif ($type == 'datetime')
1565
-		{
1566
-			$showsize=19;
1567
-			$value=dol_print_date($value, 'dayhour');
1568
-		}
1569
-		elseif ($type == 'int')
1570
-		{
1571
-			$showsize=10;
1572
-		}
1573
-		elseif ($type == 'double')
1574
-		{
1575
-			if (!empty($value)) {
1576
-				$value=price($value);
1577
-			}
1578
-		}
1579
-		elseif ($type == 'boolean')
1580
-		{
1581
-			$checked='';
1582
-			if (!empty($value)) {
1583
-				$checked=' checked ';
1584
-			}
1585
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
1586
-		}
1587
-		elseif ($type == 'mail')
1588
-		{
1589
-			$value=dol_print_email($value, 0, 0, 0, 64, 1, 1);
1590
-		}
1591
-		elseif ($type == 'url')
1592
-		{
1593
-			$value=dol_print_url($value,'_blank',32,1);
1594
-		}
1595
-		elseif ($type == 'phone')
1596
-		{
1597
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
1598
-		}
1599
-		elseif ($type == 'price')
1600
-		{
1601
-			$value=price($value, 0, $langs, 0, 0, -1, $conf->currency);
1602
-		}
1603
-		elseif ($type == 'select')
1604
-		{
1605
-			if ($langfile && $param['options'][$value]) $value=$langs->trans($param['options'][$value]);
1606
-			else $value=$param['options'][$value];
1607
-		}
1608
-		elseif ($type == 'sellist')
1609
-		{
1610
-			$param_list=array_keys($param['options']);
1611
-			$InfoFieldList = explode(":", $param_list[0]);
1612
-
1613
-			$selectkey="rowid";
1614
-			$keyList='rowid';
1615
-
1616
-			if (count($InfoFieldList)>=3)
1617
-			{
1618
-				$selectkey = $InfoFieldList[2];
1619
-				$keyList=$InfoFieldList[2].' as rowid';
1620
-			}
1621
-
1622
-			$fields_label = explode('|',$InfoFieldList[1]);
1623
-			if(is_array($fields_label)) {
1624
-				$keyList .=', ';
1625
-				$keyList .= implode(', ', $fields_label);
1626
-			}
1627
-
1628
-			$sql = 'SELECT '.$keyList;
1629
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1630
-			if (strpos($InfoFieldList[4], 'extra')!==false)
1631
-			{
1632
-				$sql.= ' as main';
1633
-			}
1634
-			if ($selectkey=='rowid' && empty($value)) {
1635
-				$sql.= " WHERE ".$selectkey."=0";
1636
-			} elseif ($selectkey=='rowid') {
1637
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
1638
-			}else {
1639
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1640
-			}
1641
-
1642
-			//$sql.= ' AND entity = '.$conf->entity;
1643
-
1644
-			dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
1645
-			$resql = $this->db->query($sql);
1646
-			if ($resql)
1647
-			{
1648
-				$value='';	// value was used, so now we reste it to use it to build final output
1649
-
1650
-				$obj = $this->db->fetch_object($resql);
1651
-
1652
-				// Several field into label (eq table:code|libelle:rowid)
1653
-				$fields_label = explode('|',$InfoFieldList[1]);
1654
-
1655
-				if(is_array($fields_label) && count($fields_label)>1)
1656
-				{
1657
-					foreach ($fields_label as $field_toshow)
1658
-					{
1659
-						$translabel='';
1660
-						if (!empty($obj->$field_toshow)) {
1661
-							$translabel=$langs->trans($obj->$field_toshow);
1662
-						}
1663
-						if ($translabel!=$field_toshow) {
1664
-							$value.=dol_trunc($translabel,18).' ';
1665
-						}else {
1666
-							$value.=$obj->$field_toshow.' ';
1667
-						}
1668
-					}
1669
-				}
1670
-				else
1671
-				{
1672
-					$translabel='';
1673
-					if (!empty($obj->{$InfoFieldList[1]})) {
1674
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
1675
-					}
1676
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
1677
-						$value=dol_trunc($translabel,18);
1678
-					}else {
1679
-						$value=$obj->{$InfoFieldList[1]};
1680
-					}
1681
-				}
1682
-			}
1683
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
1684
-		}
1685
-		elseif ($type == 'radio')
1686
-		{
1687
-			$value=$param['options'][$value];
1688
-		}
1689
-		elseif ($type == 'checkbox')
1690
-		{
1691
-			$value_arr=explode(',',$value);
1692
-			$value='';
1693
-			$toprint=array();
1694
-			if (is_array($value_arr))
1695
-			{
1696
-				foreach ($value_arr as $keyval=>$valueval) {
1697
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
1698
-				}
1699
-			}
1700
-			$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1701
-		}
1702
-		elseif ($type == 'chkbxlst')
1703
-		{
1704
-			$value_arr = explode(',', $value);
1705
-
1706
-			$param_list = array_keys($param['options']);
1707
-			$InfoFieldList = explode(":", $param_list[0]);
1708
-
1709
-			$selectkey = "rowid";
1710
-			$keyList = 'rowid';
1711
-
1712
-			if (count($InfoFieldList) >= 3) {
1713
-				$selectkey = $InfoFieldList[2];
1714
-				$keyList = $InfoFieldList[2] . ' as rowid';
1715
-			}
1716
-
1717
-			$fields_label = explode('|', $InfoFieldList[1]);
1718
-			if (is_array($fields_label)) {
1719
-				$keyList .= ', ';
1720
-				$keyList .= implode(', ', $fields_label);
1721
-			}
1722
-
1723
-			$sql = 'SELECT ' . $keyList;
1724
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1725
-			if (strpos($InfoFieldList[4], 'extra') !== false) {
1726
-				$sql .= ' as main';
1727
-			}
1728
-			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1729
-			// $sql.= ' AND entity = '.$conf->entity;
1730
-
1731
-			dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
1732
-			$resql = $this->db->query($sql);
1733
-			if ($resql) {
1734
-				$value = ''; // value was used, so now we reste it to use it to build final output
1735
-				$toprint=array();
1736
-				while ( $obj = $this->db->fetch_object($resql) ) {
1737
-
1738
-					// Several field into label (eq table:code|libelle:rowid)
1739
-					$fields_label = explode('|', $InfoFieldList[1]);
1740
-					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1741
-						if (is_array($fields_label) && count($fields_label) > 1) {
1742
-							foreach ( $fields_label as $field_toshow ) {
1743
-								$translabel = '';
1744
-								if (! empty($obj->$field_toshow)) {
1745
-									$translabel = $langs->trans($obj->$field_toshow);
1746
-								}
1747
-								if ($translabel != $field_toshow) {
1748
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1749
-								} else {
1750
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
1751
-								}
1752
-							}
1753
-						} else {
1754
-							$translabel = '';
1755
-							if (! empty($obj->{$InfoFieldList[1]})) {
1756
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1757
-							}
1758
-							if ($translabel != $obj->{$InfoFieldList[1]}) {
1759
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1760
-							} else {
1761
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
1762
-							}
1763
-						}
1764
-					}
1765
-				}
1766
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1767
-			} else {
1768
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
1769
-			}
1770
-		}
1771
-		elseif ($type == 'link')
1772
-		{
1773
-			$out='';
1774
-
1775
-			// Only if something to display (perf)
1776
-			if ($value)		// If we have -1 here, pb is into sert, not into ouptu
1777
-			{
1778
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1779
-
1780
-				$InfoFieldList = explode(":", $param_list[0]);
1781
-				$classname=$InfoFieldList[0];
1782
-				$classpath=$InfoFieldList[1];
1783
-				if (! empty($classpath))
1784
-				{
1785
-					dol_include_once($InfoFieldList[1]);
1786
-					if ($classname && class_exists($classname))
1787
-					{
1788
-						$object = new $classname($this->db);
1789
-						$object->fetch($value);
1790
-						$value=$object->getNomUrl(3);
1791
-					}
1792
-				}
1793
-				else
1794
-				{
1795
-					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
1796
-					return 'Error bad setup of extrafield';
1797
-				}
1798
-			}
1799
-		}
1800
-		elseif ($type == 'text')
1801
-		{
1802
-			$value=dol_htmlentitiesbr($value);
1803
-		}
1804
-		elseif ($type == 'html')
1805
-		{
1806
-			$value=dol_htmlentitiesbr($value);
1807
-		}
1808
-		elseif ($type == 'password')
1809
-		{
1810
-			$value=dol_trunc(preg_replace('/./i','*',$value), 8, 'right', 'UTF-8', 1);
1811
-		}
1812
-		else
1813
-		{
1814
-			$showsize=round($size);
1815
-			if ($showsize > 48) $showsize=48;
1816
-		}
1817
-
1818
-		//print $type.'-'.$size;
1819
-		$out=$value;
1820
-
1821
-		return $out;
1822
-	}
1823
-
1824
-	/**
1825
-	 * Return tag to describe alignement to use for this extrafield
1826
-	 *
1827
-	 * @param   string	$key            		Key of attribute
1828
-	 * @param	string	$extrafieldsobjectkey	If defined, use the new method to get extrafields data
1829
-	 * @return	string							Formated value
1830
-	 */
1831
-	function getAlignFlag($key, $extrafieldsobjectkey='')
1832
-	{
1833
-		global $conf,$langs;
1834
-
1835
-		if (! empty($extrafieldsobjectkey)) $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1836
-		else $type=$this->attribute_type[$key];
1837
-
1838
-		$align='';
1498
+        return $out;
1499
+    }
1500
+
1501
+
1502
+    /**
1503
+     * Return HTML string to put an output field into a page
1504
+     *
1505
+     * @param   string	$key            		Key of attribute
1506
+     * @param   string	$value          		Value to show
1507
+     * @param	string	$moreparam				To add more parameters on html input tag (only checkbox use html input for output rendering)
1508
+     * @param	string	$extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
1509
+     * @return	string							Formated value
1510
+     */
1511
+    function showOutputField($key, $value, $moreparam='', $extrafieldsobjectkey='')
1512
+    {
1513
+        global $conf,$langs;
1514
+
1515
+        if (! empty($extrafieldsobjectkey))
1516
+        {
1517
+            $label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
1518
+            $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1519
+            $size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
1520
+            $default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
1521
+            $computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
1522
+            $unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
1523
+            $required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
1524
+            $param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
1525
+            $perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
1526
+            $langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
1527
+            $list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
1528
+            $help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
1529
+            $hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1530
+        }
1531
+        else	// Old usage
1532
+        {
1533
+            $label=$this->attribute_label[$key];
1534
+            $type=$this->attribute_type[$key];
1535
+            $size=$this->attribute_size[$key];
1536
+            $default=$this->attribute_default[$key];
1537
+            $computed=$this->attribute_computed[$key];
1538
+            $unique=$this->attribute_unique[$key];
1539
+            $required=$this->attribute_required[$key];
1540
+            $param=$this->attribute_param[$key];
1541
+            $perms=dol_eval($this->attribute_perms[$key], 1);
1542
+            $langfile=$this->attribute_langfile[$key];
1543
+            $list=dol_eval($this->attribute_list[$key], 1);
1544
+            $help='';	// Not supported with old syntax
1545
+            $hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1546
+        }
1547
+
1548
+        if ($hidden) return '';		// This is a protection. If field is hidden, we should just not call this method.
1839 1549
 
1550
+        // If field is a computed field, value must become result of compute
1551
+        if ($computed)
1552
+        {
1553
+            // Make the eval of compute string
1554
+            //var_dump($computed);
1555
+            $value = dol_eval($computed, 1, 0);
1556
+        }
1557
+
1558
+        $showsize=0;
1840 1559
         if ($type == 'date')
1841
-		{
1842
-			$align="center";
1843
-		}
1844
-		elseif ($type == 'datetime')
1845
-		{
1846
-			$align="center";
1847
-		}
1848
-		elseif ($type == 'int')
1849
-		{
1850
-			$align="right";
1851
-		}
1852
-		elseif ($type == 'double')
1853
-		{
1854
-			$align="right";
1855
-		}
1856
-		elseif ($type == 'boolean')
1857
-		{
1858
-			$align="center";
1859
-		}
1860
-		elseif ($type == 'radio')
1861
-		{
1862
-			$align="center";
1863
-		}
1864
-		elseif ($type == 'checkbox')
1865
-		{
1866
-			$align="center";
1867
-		}
1868
-		elseif ($type == 'price')
1869
-		{
1870
-			$align="right";
1871
-		}
1872
-
1873
-		return $align;
1874
-	}
1875
-
1876
-	/**
1877
-	 * Return HTML string to print separator extrafield
1878
-	 *
1879
-	 * @param   string	$key            Key of attribute
1880
-	 * @param	string	$object			Object
1881
-	 * @return 	string					HTML code with line for separator
1882
-	 */
1883
-	function showSeparator($key, $object)
1884
-	{
1885
-		global $langs;
1886
-
1887
-		$out = '<tr class="trextrafieldseparator trextrafieldseparator'.$key.'"><td colspan="2"><strong>';
1888
-		$out.= $langs->trans($this->attributes[$object->table_element]['label'][$key]);
1889
-		$out.= '</strong></td></tr>';
1890
-		return $out;
1891
-	}
1892
-
1893
-	/**
1894
-	 * Fill array_options property of object by extrafields value (using for data sent by forms)
1895
-	 *
1896
-	 * @param   array	$extralabels    $array of extrafields (@deprecated)
1897
-	 * @param   object	$object         Object
1898
-	 * @param	string	$onlykey		Only following key is filled. When we make update of only one extrafield ($action = 'update_extras'), calling page must must set this to avoid to have other extrafields being reset.
1899
-	 * @return	int						1 if array_options set, 0 if no value, -1 if error (field required missing for example)
1900
-	 */
1901
-	function setOptionalsFromPost($extralabels, &$object, $onlykey='')
1902
-	{
1903
-		global $_POST, $langs;
1904
-		$nofillrequired='';// For error when required field left blank
1905
-		$error_field_required = array();
1906
-
1907
-		if (is_array($this->attributes[$object->table_element]['label'])) $extralabels=$this->attributes[$object->table_element]['label'];
1908
-
1909
-		if (is_array($extralabels))
1910
-		{
1911
-			// Get extra fields
1912
-			foreach ($extralabels as $key => $value)
1913
-			{
1914
-				if (! empty($onlykey) && $key != $onlykey) continue;
1915
-
1916
-				$key_type = $this->attributes[$object->table_element]['type'][$key];
1917
-				if ($key_type == 'separate') continue;
1918
-
1919
-				$enabled = 1;
1920
-				if (isset($this->attributes[$object->table_element]['list'][$key]))
1921
-				{
1922
-					$enabled = dol_eval($this->attributes[$object->table_element]['list'][$key], 1);
1923
-				}
1924
-				$perms = 1;
1925
-				if (isset($this->attributes[$object->table_element]['perms'][$key]))
1926
-				{
1927
-					$perms = dol_eval($this->attributes[$object->table_element]['perms'][$key], 1);
1928
-				}
1929
-				if (empty($enabled)) continue;
1930
-				if (empty($perms)) continue;
1931
-
1932
-				if ($this->attributes[$object->table_element]['required'][$key])	// Value is required
1933
-				{
1934
-					// Check if empty without using GETPOST, value can be alpha, int, array, etc...
1935
-					if ((! is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $_POST["options_".$key] != '0')
1936
-						|| (is_array($_POST["options_".$key]) && empty($_POST["options_".$key])))
1937
-					{
1938
-						//print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
1939
-						$nofillrequired++;
1940
-						$error_field_required[] = $langs->transnoentitiesnoconv($value);
1941
-					}
1942
-				}
1943
-
1944
-				if (in_array($key_type,array('date')))
1945
-				{
1946
-					// Clean parameters
1947
-					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1948
-					$value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1949
-				}
1950
-				elseif (in_array($key_type,array('datetime')))
1951
-				{
1952
-					// Clean parameters
1953
-					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1954
-					$value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1955
-				}
1956
-				else if (in_array($key_type,array('checkbox','chkbxlst')))
1957
-				{
1958
-					$value_arr=GETPOST("options_".$key, 'array'); // check if an array
1959
-					if (!empty($value_arr)) {
1960
-						$value_key=implode($value_arr,',');
1961
-					}else {
1962
-						$value_key='';
1963
-					}
1964
-				}
1965
-				else if (in_array($key_type,array('price','double')))
1966
-				{
1967
-					$value_arr=GETPOST("options_".$key, 'alpha');
1968
-					$value_key=price2num($value_arr);
1969
-				}
1970
-				else
1971
-				{
1972
-					$value_key=GETPOST("options_".$key);
1973
-				}
1974
-
1975
-				$object->array_options["options_".$key]=$value_key;
1976
-			}
1977
-
1978
-			if ($nofillrequired) {
1979
-				$langs->load('errors');
1980
-				setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ',$error_field_required), null, 'errors');
1981
-				return -1;
1982
-			}
1983
-			else {
1984
-				return 1;
1985
-			}
1986
-		}
1987
-		else {
1988
-			return 0;
1989
-		}
1990
-	}
1991
-
1992
-	/**
1993
-	 * return array_options array of data of extrafields value of object sent by a search form
1994
-	 *
1995
-	 * @param  array|string		$extrafieldsobjectkey  	array of extrafields (old usage) or value of object->table_element (new usage)
1996
-	 * @param  string			$keyprefix      		Prefix string to add into name and id of field (can be used to avoid duplicate names)
1997
-	 * @param  string			$keysuffix      		Suffix string to add into name and id of field (can be used to avoid duplicate names)
1998
-	 * @return array|int								array_options set or 0 if no value
1999
-	 */
2000
-	function getOptionalsFromPost($extrafieldsobjectkey, $keyprefix='', $keysuffix='')
2001
-	{
2002
-		global $_POST;
2003
-
2004
-		if (is_string($extrafieldsobjectkey) && is_array($this->attributes[$extrafieldsobjectkey]['label']))
2005
-		{
2006
-			$extralabels = $this->attributes[$extrafieldsobjectkey]['label'];
2007
-		}
2008
-		else
2009
-		{
2010
-			$extralabels = $extrafieldsobjectkey;
2011
-		}
2012
-
2013
-		if (is_array($extralabels))
2014
-		{
2015
-			$array_options = array();
2016
-
2017
-			// Get extra fields
2018
-			foreach ($extralabels as $key => $value)
2019
-			{
2020
-				$key_type = '';
2021
-				if (is_string($extrafieldsobjectkey))
2022
-				{
2023
-					$key_type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
2024
-				}
2025
-
2026
-				if (in_array($key_type,array('date','datetime')))
2027
-				{
2028
-					// Clean parameters
2029
-					$value_key=dol_mktime($_POST[$keysuffix."options_".$key.$keyprefix."hour"], $_POST[$keysuffix."options_".$key.$keyprefix."min"], 0, $_POST[$keysuffix."options_".$key.$keyprefix."month"], $_POST[$keysuffix."options_".$key.$keyprefix."day"], $_POST[$keysuffix."options_".$key.$keyprefix."year"]);
2030
-				}
2031
-				else if (in_array($key_type,array('checkbox', 'chkbxlst')))
2032
-				{
2033
-					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2034
-					// Make sure we get an array even if there's only one checkbox
2035
-					$value_arr=(array) $value_arr;
2036
-					$value_key=implode(',', $value_arr);
2037
-				}
2038
-				else if (in_array($key_type,array('price','double')))
2039
-				{
2040
-					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2041
-					$value_key=price2num($value_arr);
2042
-				}
2043
-				else
2044
-				{
2045
-					$value_key=GETPOST($keysuffix."options_".$key.$keyprefix);
2046
-				}
2047
-
2048
-				$array_options[$keysuffix."options_".$key]=$value_key;	// No keyprefix here. keyprefix is used only for read.
2049
-			}
2050
-
2051
-			return $array_options;
2052
-		}
2053
-
2054
-		return 0;
2055
-	}
1560
+        {
1561
+            $showsize=10;
1562
+            $value=dol_print_date($value, 'day');
1563
+        }
1564
+        elseif ($type == 'datetime')
1565
+        {
1566
+            $showsize=19;
1567
+            $value=dol_print_date($value, 'dayhour');
1568
+        }
1569
+        elseif ($type == 'int')
1570
+        {
1571
+            $showsize=10;
1572
+        }
1573
+        elseif ($type == 'double')
1574
+        {
1575
+            if (!empty($value)) {
1576
+                $value=price($value);
1577
+            }
1578
+        }
1579
+        elseif ($type == 'boolean')
1580
+        {
1581
+            $checked='';
1582
+            if (!empty($value)) {
1583
+                $checked=' checked ';
1584
+            }
1585
+            $value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
1586
+        }
1587
+        elseif ($type == 'mail')
1588
+        {
1589
+            $value=dol_print_email($value, 0, 0, 0, 64, 1, 1);
1590
+        }
1591
+        elseif ($type == 'url')
1592
+        {
1593
+            $value=dol_print_url($value,'_blank',32,1);
1594
+        }
1595
+        elseif ($type == 'phone')
1596
+        {
1597
+            $value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
1598
+        }
1599
+        elseif ($type == 'price')
1600
+        {
1601
+            $value=price($value, 0, $langs, 0, 0, -1, $conf->currency);
1602
+        }
1603
+        elseif ($type == 'select')
1604
+        {
1605
+            if ($langfile && $param['options'][$value]) $value=$langs->trans($param['options'][$value]);
1606
+            else $value=$param['options'][$value];
1607
+        }
1608
+        elseif ($type == 'sellist')
1609
+        {
1610
+            $param_list=array_keys($param['options']);
1611
+            $InfoFieldList = explode(":", $param_list[0]);
1612
+
1613
+            $selectkey="rowid";
1614
+            $keyList='rowid';
1615
+
1616
+            if (count($InfoFieldList)>=3)
1617
+            {
1618
+                $selectkey = $InfoFieldList[2];
1619
+                $keyList=$InfoFieldList[2].' as rowid';
1620
+            }
1621
+
1622
+            $fields_label = explode('|',$InfoFieldList[1]);
1623
+            if(is_array($fields_label)) {
1624
+                $keyList .=', ';
1625
+                $keyList .= implode(', ', $fields_label);
1626
+            }
1627
+
1628
+            $sql = 'SELECT '.$keyList;
1629
+            $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1630
+            if (strpos($InfoFieldList[4], 'extra')!==false)
1631
+            {
1632
+                $sql.= ' as main';
1633
+            }
1634
+            if ($selectkey=='rowid' && empty($value)) {
1635
+                $sql.= " WHERE ".$selectkey."=0";
1636
+            } elseif ($selectkey=='rowid') {
1637
+                $sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
1638
+            }else {
1639
+                $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1640
+            }
1641
+
1642
+            //$sql.= ' AND entity = '.$conf->entity;
1643
+
1644
+            dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
1645
+            $resql = $this->db->query($sql);
1646
+            if ($resql)
1647
+            {
1648
+                $value='';	// value was used, so now we reste it to use it to build final output
1649
+
1650
+                $obj = $this->db->fetch_object($resql);
1651
+
1652
+                // Several field into label (eq table:code|libelle:rowid)
1653
+                $fields_label = explode('|',$InfoFieldList[1]);
1654
+
1655
+                if(is_array($fields_label) && count($fields_label)>1)
1656
+                {
1657
+                    foreach ($fields_label as $field_toshow)
1658
+                    {
1659
+                        $translabel='';
1660
+                        if (!empty($obj->$field_toshow)) {
1661
+                            $translabel=$langs->trans($obj->$field_toshow);
1662
+                        }
1663
+                        if ($translabel!=$field_toshow) {
1664
+                            $value.=dol_trunc($translabel,18).' ';
1665
+                        }else {
1666
+                            $value.=$obj->$field_toshow.' ';
1667
+                        }
1668
+                    }
1669
+                }
1670
+                else
1671
+                {
1672
+                    $translabel='';
1673
+                    if (!empty($obj->{$InfoFieldList[1]})) {
1674
+                        $translabel=$langs->trans($obj->{$InfoFieldList[1]});
1675
+                    }
1676
+                    if ($translabel!=$obj->{$InfoFieldList[1]}) {
1677
+                        $value=dol_trunc($translabel,18);
1678
+                    }else {
1679
+                        $value=$obj->{$InfoFieldList[1]};
1680
+                    }
1681
+                }
1682
+            }
1683
+            else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
1684
+        }
1685
+        elseif ($type == 'radio')
1686
+        {
1687
+            $value=$param['options'][$value];
1688
+        }
1689
+        elseif ($type == 'checkbox')
1690
+        {
1691
+            $value_arr=explode(',',$value);
1692
+            $value='';
1693
+            $toprint=array();
1694
+            if (is_array($value_arr))
1695
+            {
1696
+                foreach ($value_arr as $keyval=>$valueval) {
1697
+                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
1698
+                }
1699
+            }
1700
+            $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1701
+        }
1702
+        elseif ($type == 'chkbxlst')
1703
+        {
1704
+            $value_arr = explode(',', $value);
1705
+
1706
+            $param_list = array_keys($param['options']);
1707
+            $InfoFieldList = explode(":", $param_list[0]);
1708
+
1709
+            $selectkey = "rowid";
1710
+            $keyList = 'rowid';
1711
+
1712
+            if (count($InfoFieldList) >= 3) {
1713
+                $selectkey = $InfoFieldList[2];
1714
+                $keyList = $InfoFieldList[2] . ' as rowid';
1715
+            }
1716
+
1717
+            $fields_label = explode('|', $InfoFieldList[1]);
1718
+            if (is_array($fields_label)) {
1719
+                $keyList .= ', ';
1720
+                $keyList .= implode(', ', $fields_label);
1721
+            }
1722
+
1723
+            $sql = 'SELECT ' . $keyList;
1724
+            $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1725
+            if (strpos($InfoFieldList[4], 'extra') !== false) {
1726
+                $sql .= ' as main';
1727
+            }
1728
+            // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1729
+            // $sql.= ' AND entity = '.$conf->entity;
1730
+
1731
+            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
1732
+            $resql = $this->db->query($sql);
1733
+            if ($resql) {
1734
+                $value = ''; // value was used, so now we reste it to use it to build final output
1735
+                $toprint=array();
1736
+                while ( $obj = $this->db->fetch_object($resql) ) {
1737
+
1738
+                    // Several field into label (eq table:code|libelle:rowid)
1739
+                    $fields_label = explode('|', $InfoFieldList[1]);
1740
+                    if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1741
+                        if (is_array($fields_label) && count($fields_label) > 1) {
1742
+                            foreach ( $fields_label as $field_toshow ) {
1743
+                                $translabel = '';
1744
+                                if (! empty($obj->$field_toshow)) {
1745
+                                    $translabel = $langs->trans($obj->$field_toshow);
1746
+                                }
1747
+                                if ($translabel != $field_toshow) {
1748
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1749
+                                } else {
1750
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
1751
+                                }
1752
+                            }
1753
+                        } else {
1754
+                            $translabel = '';
1755
+                            if (! empty($obj->{$InfoFieldList[1]})) {
1756
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
1757
+                            }
1758
+                            if ($translabel != $obj->{$InfoFieldList[1]}) {
1759
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1760
+                            } else {
1761
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
1762
+                            }
1763
+                        }
1764
+                    }
1765
+                }
1766
+                $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1767
+            } else {
1768
+                dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
1769
+            }
1770
+        }
1771
+        elseif ($type == 'link')
1772
+        {
1773
+            $out='';
1774
+
1775
+            // Only if something to display (perf)
1776
+            if ($value)		// If we have -1 here, pb is into sert, not into ouptu
1777
+            {
1778
+                $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1779
+
1780
+                $InfoFieldList = explode(":", $param_list[0]);
1781
+                $classname=$InfoFieldList[0];
1782
+                $classpath=$InfoFieldList[1];
1783
+                if (! empty($classpath))
1784
+                {
1785
+                    dol_include_once($InfoFieldList[1]);
1786
+                    if ($classname && class_exists($classname))
1787
+                    {
1788
+                        $object = new $classname($this->db);
1789
+                        $object->fetch($value);
1790
+                        $value=$object->getNomUrl(3);
1791
+                    }
1792
+                }
1793
+                else
1794
+                {
1795
+                    dol_syslog('Error bad setup of extrafield', LOG_WARNING);
1796
+                    return 'Error bad setup of extrafield';
1797
+                }
1798
+            }
1799
+        }
1800
+        elseif ($type == 'text')
1801
+        {
1802
+            $value=dol_htmlentitiesbr($value);
1803
+        }
1804
+        elseif ($type == 'html')
1805
+        {
1806
+            $value=dol_htmlentitiesbr($value);
1807
+        }
1808
+        elseif ($type == 'password')
1809
+        {
1810
+            $value=dol_trunc(preg_replace('/./i','*',$value), 8, 'right', 'UTF-8', 1);
1811
+        }
1812
+        else
1813
+        {
1814
+            $showsize=round($size);
1815
+            if ($showsize > 48) $showsize=48;
1816
+        }
1817
+
1818
+        //print $type.'-'.$size;
1819
+        $out=$value;
1820
+
1821
+        return $out;
1822
+    }
1823
+
1824
+    /**
1825
+     * Return tag to describe alignement to use for this extrafield
1826
+     *
1827
+     * @param   string	$key            		Key of attribute
1828
+     * @param	string	$extrafieldsobjectkey	If defined, use the new method to get extrafields data
1829
+     * @return	string							Formated value
1830
+     */
1831
+    function getAlignFlag($key, $extrafieldsobjectkey='')
1832
+    {
1833
+        global $conf,$langs;
1834
+
1835
+        if (! empty($extrafieldsobjectkey)) $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1836
+        else $type=$this->attribute_type[$key];
1837
+
1838
+        $align='';
1839
+
1840
+        if ($type == 'date')
1841
+        {
1842
+            $align="center";
1843
+        }
1844
+        elseif ($type == 'datetime')
1845
+        {
1846
+            $align="center";
1847
+        }
1848
+        elseif ($type == 'int')
1849
+        {
1850
+            $align="right";
1851
+        }
1852
+        elseif ($type == 'double')
1853
+        {
1854
+            $align="right";
1855
+        }
1856
+        elseif ($type == 'boolean')
1857
+        {
1858
+            $align="center";
1859
+        }
1860
+        elseif ($type == 'radio')
1861
+        {
1862
+            $align="center";
1863
+        }
1864
+        elseif ($type == 'checkbox')
1865
+        {
1866
+            $align="center";
1867
+        }
1868
+        elseif ($type == 'price')
1869
+        {
1870
+            $align="right";
1871
+        }
1872
+
1873
+        return $align;
1874
+    }
1875
+
1876
+    /**
1877
+     * Return HTML string to print separator extrafield
1878
+     *
1879
+     * @param   string	$key            Key of attribute
1880
+     * @param	string	$object			Object
1881
+     * @return 	string					HTML code with line for separator
1882
+     */
1883
+    function showSeparator($key, $object)
1884
+    {
1885
+        global $langs;
1886
+
1887
+        $out = '<tr class="trextrafieldseparator trextrafieldseparator'.$key.'"><td colspan="2"><strong>';
1888
+        $out.= $langs->trans($this->attributes[$object->table_element]['label'][$key]);
1889
+        $out.= '</strong></td></tr>';
1890
+        return $out;
1891
+    }
1892
+
1893
+    /**
1894
+     * Fill array_options property of object by extrafields value (using for data sent by forms)
1895
+     *
1896
+     * @param   array	$extralabels    $array of extrafields (@deprecated)
1897
+     * @param   object	$object         Object
1898
+     * @param	string	$onlykey		Only following key is filled. When we make update of only one extrafield ($action = 'update_extras'), calling page must must set this to avoid to have other extrafields being reset.
1899
+     * @return	int						1 if array_options set, 0 if no value, -1 if error (field required missing for example)
1900
+     */
1901
+    function setOptionalsFromPost($extralabels, &$object, $onlykey='')
1902
+    {
1903
+        global $_POST, $langs;
1904
+        $nofillrequired='';// For error when required field left blank
1905
+        $error_field_required = array();
1906
+
1907
+        if (is_array($this->attributes[$object->table_element]['label'])) $extralabels=$this->attributes[$object->table_element]['label'];
1908
+
1909
+        if (is_array($extralabels))
1910
+        {
1911
+            // Get extra fields
1912
+            foreach ($extralabels as $key => $value)
1913
+            {
1914
+                if (! empty($onlykey) && $key != $onlykey) continue;
1915
+
1916
+                $key_type = $this->attributes[$object->table_element]['type'][$key];
1917
+                if ($key_type == 'separate') continue;
1918
+
1919
+                $enabled = 1;
1920
+                if (isset($this->attributes[$object->table_element]['list'][$key]))
1921
+                {
1922
+                    $enabled = dol_eval($this->attributes[$object->table_element]['list'][$key], 1);
1923
+                }
1924
+                $perms = 1;
1925
+                if (isset($this->attributes[$object->table_element]['perms'][$key]))
1926
+                {
1927
+                    $perms = dol_eval($this->attributes[$object->table_element]['perms'][$key], 1);
1928
+                }
1929
+                if (empty($enabled)) continue;
1930
+                if (empty($perms)) continue;
1931
+
1932
+                if ($this->attributes[$object->table_element]['required'][$key])	// Value is required
1933
+                {
1934
+                    // Check if empty without using GETPOST, value can be alpha, int, array, etc...
1935
+                    if ((! is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $_POST["options_".$key] != '0')
1936
+                        || (is_array($_POST["options_".$key]) && empty($_POST["options_".$key])))
1937
+                    {
1938
+                        //print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
1939
+                        $nofillrequired++;
1940
+                        $error_field_required[] = $langs->transnoentitiesnoconv($value);
1941
+                    }
1942
+                }
1943
+
1944
+                if (in_array($key_type,array('date')))
1945
+                {
1946
+                    // Clean parameters
1947
+                    // TODO GMT date in memory must be GMT so we should add gm=true in parameters
1948
+                    $value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1949
+                }
1950
+                elseif (in_array($key_type,array('datetime')))
1951
+                {
1952
+                    // Clean parameters
1953
+                    // TODO GMT date in memory must be GMT so we should add gm=true in parameters
1954
+                    $value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1955
+                }
1956
+                else if (in_array($key_type,array('checkbox','chkbxlst')))
1957
+                {
1958
+                    $value_arr=GETPOST("options_".$key, 'array'); // check if an array
1959
+                    if (!empty($value_arr)) {
1960
+                        $value_key=implode($value_arr,',');
1961
+                    }else {
1962
+                        $value_key='';
1963
+                    }
1964
+                }
1965
+                else if (in_array($key_type,array('price','double')))
1966
+                {
1967
+                    $value_arr=GETPOST("options_".$key, 'alpha');
1968
+                    $value_key=price2num($value_arr);
1969
+                }
1970
+                else
1971
+                {
1972
+                    $value_key=GETPOST("options_".$key);
1973
+                }
1974
+
1975
+                $object->array_options["options_".$key]=$value_key;
1976
+            }
1977
+
1978
+            if ($nofillrequired) {
1979
+                $langs->load('errors');
1980
+                setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ',$error_field_required), null, 'errors');
1981
+                return -1;
1982
+            }
1983
+            else {
1984
+                return 1;
1985
+            }
1986
+        }
1987
+        else {
1988
+            return 0;
1989
+        }
1990
+    }
1991
+
1992
+    /**
1993
+     * return array_options array of data of extrafields value of object sent by a search form
1994
+     *
1995
+     * @param  array|string		$extrafieldsobjectkey  	array of extrafields (old usage) or value of object->table_element (new usage)
1996
+     * @param  string			$keyprefix      		Prefix string to add into name and id of field (can be used to avoid duplicate names)
1997
+     * @param  string			$keysuffix      		Suffix string to add into name and id of field (can be used to avoid duplicate names)
1998
+     * @return array|int								array_options set or 0 if no value
1999
+     */
2000
+    function getOptionalsFromPost($extrafieldsobjectkey, $keyprefix='', $keysuffix='')
2001
+    {
2002
+        global $_POST;
2003
+
2004
+        if (is_string($extrafieldsobjectkey) && is_array($this->attributes[$extrafieldsobjectkey]['label']))
2005
+        {
2006
+            $extralabels = $this->attributes[$extrafieldsobjectkey]['label'];
2007
+        }
2008
+        else
2009
+        {
2010
+            $extralabels = $extrafieldsobjectkey;
2011
+        }
2012
+
2013
+        if (is_array($extralabels))
2014
+        {
2015
+            $array_options = array();
2016
+
2017
+            // Get extra fields
2018
+            foreach ($extralabels as $key => $value)
2019
+            {
2020
+                $key_type = '';
2021
+                if (is_string($extrafieldsobjectkey))
2022
+                {
2023
+                    $key_type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
2024
+                }
2025
+
2026
+                if (in_array($key_type,array('date','datetime')))
2027
+                {
2028
+                    // Clean parameters
2029
+                    $value_key=dol_mktime($_POST[$keysuffix."options_".$key.$keyprefix."hour"], $_POST[$keysuffix."options_".$key.$keyprefix."min"], 0, $_POST[$keysuffix."options_".$key.$keyprefix."month"], $_POST[$keysuffix."options_".$key.$keyprefix."day"], $_POST[$keysuffix."options_".$key.$keyprefix."year"]);
2030
+                }
2031
+                else if (in_array($key_type,array('checkbox', 'chkbxlst')))
2032
+                {
2033
+                    $value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2034
+                    // Make sure we get an array even if there's only one checkbox
2035
+                    $value_arr=(array) $value_arr;
2036
+                    $value_key=implode(',', $value_arr);
2037
+                }
2038
+                else if (in_array($key_type,array('price','double')))
2039
+                {
2040
+                    $value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2041
+                    $value_key=price2num($value_arr);
2042
+                }
2043
+                else
2044
+                {
2045
+                    $value_key=GETPOST($keysuffix."options_".$key.$keyprefix);
2046
+                }
2047
+
2048
+                $array_options[$keysuffix."options_".$key]=$value_key;	// No keyprefix here. keyprefix is used only for read.
2049
+            }
2050
+
2051
+            return $array_options;
2052
+        }
2053
+
2054
+        return 0;
2055
+    }
2056 2056
 }
Please login to merge, or discard this patch.
Spacing   +668 added lines, -668 removed lines patch added patch discarded remove patch
@@ -94,12 +94,12 @@  discard block
 block discarded – undo
94 94
 	/**
95 95
 	 * @var string Error code (or message)
96 96
 	 */
97
-	public $error='';
97
+	public $error = '';
98 98
 
99 99
 	var $errno;
100 100
 
101 101
 
102
-	public static $type2label=array(
102
+	public static $type2label = array(
103 103
 	'varchar'=>'String',
104 104
 	'text'=>'TextLong',
105 105
 	'html'=>'HtmlText',
@@ -171,29 +171,29 @@  discard block
 block discarded – undo
171 171
 	 *  @param  string  		$enabled  		 	Condition to have the field enabled or not
172 172
 	 *  @return int      							<=0 if KO, >0 if OK
173 173
 	 */
174
-	function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $computed='', $entity='', $langfile='', $enabled='1')
174
+	function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique = 0, $required = 0, $default_value = '', $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $computed = '', $entity = '', $langfile = '', $enabled = '1')
175 175
 	{
176 176
 		if (empty($attrname)) return -1;
177 177
 		if (empty($label)) return -1;
178 178
 
179
-		if ($elementtype == 'thirdparty') $elementtype='societe';
180
-		if ($elementtype == 'contact') $elementtype='socpeople';
179
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
180
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
181 181
 
182 182
 		// Create field into database except for separator type which is not stored in database
183 183
 		if ($type != 'separate')
184 184
 		{
185
-			$result=$this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
185
+			$result = $this->create($attrname, $type, $size, $elementtype, $unique, $required, $default_value, $param, $perms, $list, $computed, $help);
186 186
 		}
187
-		$err1=$this->errno;
187
+		$err1 = $this->errno;
188 188
 		if ($result > 0 || $err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' || $type == 'separate')
189 189
 		{
190 190
 			// Add declaration of field into table
191
-			$result2=$this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled);
192
-			$err2=$this->errno;
191
+			$result2 = $this->create_label($attrname, $label, $type, $pos, $size, $elementtype, $unique, $required, $param, $alwayseditable, $perms, $list, $help, $default_value, $computed, $entity, $langfile, $enabled);
192
+			$err2 = $this->errno;
193 193
 			if ($result2 > 0 || ($err1 == 'DB_ERROR_COLUMN_ALREADY_EXISTS' && $err2 == 'DB_ERROR_RECORD_ALREADY_EXISTS'))
194 194
 			{
195
-				$this->error='';
196
-				$this->errno=0;
195
+				$this->error = '';
196
+				$this->errno = 0;
197 197
 				return 1;
198 198
 			}
199 199
 			else return -2;
@@ -221,69 +221,69 @@  discard block
 block discarded – undo
221 221
 	 *  @param  string  $computed           Computed value
222 222
 	 *  @return int      	           		<=0 if KO, >0 if OK
223 223
 	 */
224
-	private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list='0', $computed='')
224
+	private function create($attrname, $type = 'varchar', $length = 255, $elementtype = 'member', $unique = 0, $required = 0, $default_value = '', $param = '', $perms = '', $list = '0', $computed = '')
225 225
 	{
226
-		if ($elementtype == 'thirdparty') $elementtype='societe';
227
-		if ($elementtype == 'contact') $elementtype='socpeople';
228
-
229
-		$table=$elementtype.'_extrafields';
230
-		if ($elementtype == 'categorie') $table='categories_extrafields';
231
-
232
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/",$attrname) && ! is_numeric($attrname))
233
-		{
234
-			if ($type=='boolean') {
235
-				$typedb='int';
236
-				$lengthdb='1';
237
-			} elseif($type=='price') {
238
-				$typedb='double';
239
-				$lengthdb='24,8';
240
-			} elseif($type=='phone') {
241
-				$typedb='varchar';
242
-				$lengthdb='20';
243
-			} elseif($type=='mail') {
244
-				$typedb='varchar';
245
-				$lengthdb='128';
246
-			} elseif($type=='url') {
247
-				$typedb='varchar';
248
-				$lengthdb='255';
249
-			} elseif (($type=='select') || ($type=='sellist') || ($type=='radio') ||($type=='checkbox') ||($type=='chkbxlst')){
250
-				$typedb='varchar';
251
-				$lengthdb='255';
252
-			} elseif ($type=='link') {
253
-				$typedb='int';
254
-				$lengthdb='11';
255
-			} elseif ($type=='html') {
256
-				$typedb='text';
257
-				$lengthdb=$length;
258
-			} elseif($type=='password') {
259
-				$typedb='varchar';
260
-				$lengthdb='128';
226
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
227
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
228
+
229
+		$table = $elementtype.'_extrafields';
230
+		if ($elementtype == 'categorie') $table = 'categories_extrafields';
231
+
232
+		if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/", $attrname) && !is_numeric($attrname))
233
+		{
234
+			if ($type == 'boolean') {
235
+				$typedb = 'int';
236
+				$lengthdb = '1';
237
+			} elseif ($type == 'price') {
238
+				$typedb = 'double';
239
+				$lengthdb = '24,8';
240
+			} elseif ($type == 'phone') {
241
+				$typedb = 'varchar';
242
+				$lengthdb = '20';
243
+			} elseif ($type == 'mail') {
244
+				$typedb = 'varchar';
245
+				$lengthdb = '128';
246
+			} elseif ($type == 'url') {
247
+				$typedb = 'varchar';
248
+				$lengthdb = '255';
249
+			} elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
250
+				$typedb = 'varchar';
251
+				$lengthdb = '255';
252
+			} elseif ($type == 'link') {
253
+				$typedb = 'int';
254
+				$lengthdb = '11';
255
+			} elseif ($type == 'html') {
256
+				$typedb = 'text';
257
+				$lengthdb = $length;
258
+			} elseif ($type == 'password') {
259
+				$typedb = 'varchar';
260
+				$lengthdb = '128';
261 261
 			} else {
262
-				$typedb=$type;
263
-				$lengthdb=$length;
264
-				if ($type == 'varchar' && empty($lengthdb)) $lengthdb='255';
262
+				$typedb = $type;
263
+				$lengthdb = $length;
264
+				if ($type == 'varchar' && empty($lengthdb)) $lengthdb = '255';
265 265
 			}
266 266
 			$field_desc = array(
267 267
 				'type'=>$typedb,
268 268
 				'value'=>$lengthdb,
269
-				'null'=>($required?'NOT NULL':'NULL'),
269
+				'null'=>($required ? 'NOT NULL' : 'NULL'),
270 270
 				'default' => $default_value
271 271
 			);
272 272
 
273
-			$result=$this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
273
+			$result = $this->db->DDLAddField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
274 274
 			if ($result > 0)
275 275
 			{
276 276
 				if ($unique)
277 277
 				{
278
-					$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
279
-					$resql=$this->db->query($sql,1,'dml');
278
+					$sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
279
+					$resql = $this->db->query($sql, 1, 'dml');
280 280
 				}
281 281
 				return 1;
282 282
 			}
283 283
 			else
284 284
 			{
285
-				$this->error=$this->db->lasterror();
286
-				$this->errno=$this->db->lasterrno();
285
+				$this->error = $this->db->lasterror();
286
+				$this->errno = $this->db->lasterrno();
287 287
 				return -1;
288 288
 			}
289 289
 		}
@@ -317,22 +317,22 @@  discard block
 block discarded – undo
317 317
 	 *  @param  string  		$enabled  		Condition to have the field enabled or not
318 318
 	 *  @return	int								<=0 if KO, >0 if OK
319 319
 	 */
320
-	private function create_label($attrname, $label='', $type='', $pos=0, $size=0, $elementtype='member', $unique=0, $required=0, $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $default='', $computed='',$entity='', $langfile='', $enabled='1')
320
+	private function create_label($attrname, $label = '', $type = '', $pos = 0, $size = 0, $elementtype = 'member', $unique = 0, $required = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '-1', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1')
321 321
 	{
322 322
         // phpcs:enable
323
-		global $conf,$user;
323
+		global $conf, $user;
324 324
 
325
-		if ($elementtype == 'thirdparty') $elementtype='societe';
326
-		if ($elementtype == 'contact') $elementtype='socpeople';
325
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
326
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
327 327
 
328 328
 		// Clean parameters
329
-		if (empty($pos)) $pos=0;
330
-		if (empty($list)) $list='0';
331
-		if (empty($required)) $required=0;
332
-		if (empty($unique)) $unique=0;
333
-		if (empty($alwayseditable)) $alwayseditable=0;
329
+		if (empty($pos)) $pos = 0;
330
+		if (empty($list)) $list = '0';
331
+		if (empty($required)) $required = 0;
332
+		if (empty($unique)) $unique = 0;
333
+		if (empty($alwayseditable)) $alwayseditable = 0;
334 334
 
335
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname) && ! is_numeric($attrname))
335
+		if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname) && !is_numeric($attrname))
336 336
 		{
337 337
 			if (is_array($param) && count($param) > 0)
338 338
 			{
@@ -344,54 +344,54 @@  discard block
 block discarded – undo
344 344
 			}
345 345
 			else
346 346
 			{
347
-				$params='';
347
+				$params = '';
348 348
 			}
349 349
 
350 350
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
351
-			$sql.= " name,";
352
-			$sql.= " label,";
353
-			$sql.= " type,";
354
-			$sql.= " pos,";
355
-			$sql.= " size,";
356
-			$sql.= " entity,";
357
-			$sql.= " elementtype,";
358
-			$sql.= " fieldunique,";
359
-			$sql.= " fieldrequired,";
360
-			$sql.= " param,";
361
-			$sql.= " alwayseditable,";
362
-			$sql.= " perms,";
363
-			$sql.= " langs,";
364
-			$sql.= " list,";
365
-			$sql.= " fielddefault,";
366
-			$sql.= " fieldcomputed,";
367
-			$sql.= " fk_user_author,";
368
-			$sql.= " fk_user_modif,";
369
-			$sql.= " datec,";
370
-			$sql.= " enabled,";
371
-			$sql.= " help";
372
-			$sql.= " )";
373
-			$sql.= " VALUES('".$attrname."',";
374
-			$sql.= " '".$this->db->escape($label)."',";
375
-			$sql.= " '".$this->db->escape($type)."',";
376
-			$sql.= " ".$pos.",";
377
-			$sql.= " '".$this->db->escape($size)."',";
378
-			$sql.= " ".($entity===''?$conf->entity:$entity).",";
379
-			$sql.= " '".$this->db->escape($elementtype)."',";
380
-			$sql.= " ".$unique.",";
381
-			$sql.= " ".$required.",";
382
-			$sql.= " '".$this->db->escape($params)."',";
383
-			$sql.= " ".$alwayseditable.",";
384
-			$sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
385
-			$sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
386
-			$sql.= " '".$this->db->escape($list)."',";
387
-			$sql.= " ".($default?"'".$this->db->escape($default)."'":"null").",";
388
-			$sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
389
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
390
-			$sql .= " " . (is_object($user) ? $user->id : 0). ",";
391
-			$sql .= "'" . $this->db->idate(dol_now()) . "',";
392
-			$sql.= " ".($enabled?"'".$this->db->escape($enabled)."'":"1").",";
393
-			$sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
394
-			$sql.=')';
351
+			$sql .= " name,";
352
+			$sql .= " label,";
353
+			$sql .= " type,";
354
+			$sql .= " pos,";
355
+			$sql .= " size,";
356
+			$sql .= " entity,";
357
+			$sql .= " elementtype,";
358
+			$sql .= " fieldunique,";
359
+			$sql .= " fieldrequired,";
360
+			$sql .= " param,";
361
+			$sql .= " alwayseditable,";
362
+			$sql .= " perms,";
363
+			$sql .= " langs,";
364
+			$sql .= " list,";
365
+			$sql .= " fielddefault,";
366
+			$sql .= " fieldcomputed,";
367
+			$sql .= " fk_user_author,";
368
+			$sql .= " fk_user_modif,";
369
+			$sql .= " datec,";
370
+			$sql .= " enabled,";
371
+			$sql .= " help";
372
+			$sql .= " )";
373
+			$sql .= " VALUES('".$attrname."',";
374
+			$sql .= " '".$this->db->escape($label)."',";
375
+			$sql .= " '".$this->db->escape($type)."',";
376
+			$sql .= " ".$pos.",";
377
+			$sql .= " '".$this->db->escape($size)."',";
378
+			$sql .= " ".($entity === '' ? $conf->entity : $entity).",";
379
+			$sql .= " '".$this->db->escape($elementtype)."',";
380
+			$sql .= " ".$unique.",";
381
+			$sql .= " ".$required.",";
382
+			$sql .= " '".$this->db->escape($params)."',";
383
+			$sql .= " ".$alwayseditable.",";
384
+			$sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").",";
385
+			$sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").",";
386
+			$sql .= " '".$this->db->escape($list)."',";
387
+			$sql .= " ".($default ? "'".$this->db->escape($default)."'" : "null").",";
388
+			$sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").",";
389
+			$sql .= " ".(is_object($user) ? $user->id : 0).",";
390
+			$sql .= " ".(is_object($user) ? $user->id : 0).",";
391
+			$sql .= "'".$this->db->idate(dol_now())."',";
392
+			$sql .= " ".($enabled ? "'".$this->db->escape($enabled)."'" : "1").",";
393
+			$sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null");
394
+			$sql .= ')';
395 395
 
396 396
 			dol_syslog(get_class($this)."::create_label", LOG_DEBUG);
397 397
 			if ($this->db->query($sql))
@@ -400,8 +400,8 @@  discard block
 block discarded – undo
400 400
 			}
401 401
 			else
402 402
 			{
403
-				$this->error=$this->db->lasterror();
404
-				$this->errno=$this->db->lasterrno();
403
+				$this->error = $this->db->lasterror();
404
+				$this->errno = $this->db->lasterrno();
405 405
 				return -1;
406 406
 			}
407 407
 		}
@@ -414,31 +414,31 @@  discard block
 block discarded – undo
414 414
 	 *  @param  string	$elementtype    Element type ('member', 'product', 'thirdparty', 'contact', ...)
415 415
 	 *  @return int              		< 0 if KO, 0 if nothing is done, 1 if OK
416 416
 	 */
417
-	function delete($attrname, $elementtype='member')
417
+	function delete($attrname, $elementtype = 'member')
418 418
 	{
419
-		if ($elementtype == 'thirdparty') $elementtype='societe';
420
-		if ($elementtype == 'contact') $elementtype='socpeople';
419
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
420
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
421 421
 
422
-		$table=$elementtype.'_extrafields';
423
-		if ($elementtype == 'categorie') $table='categories_extrafields';
422
+		$table = $elementtype.'_extrafields';
423
+		if ($elementtype == 'categorie') $table = 'categories_extrafields';
424 424
 
425
-		$error=0;
425
+		$error = 0;
426 426
 
427
-		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
427
+		if (!empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname))
428 428
 		{
429
-			$result=$this->delete_label($attrname,$elementtype);
429
+			$result = $this->delete_label($attrname, $elementtype);
430 430
 			if ($result < 0)
431 431
 			{
432
-			    $this->error=$this->db->lasterror();
432
+			    $this->error = $this->db->lasterror();
433 433
 			    $error++;
434 434
 			}
435 435
 
436
-			if (! $error)
436
+			if (!$error)
437 437
 			{
438 438
         		$sql = "SELECT COUNT(rowid) as nb";
439
-        		$sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
440
-        		$sql.= " WHERE elementtype = '".$elementtype."'";
441
-        		$sql.= " AND name = '".$attrname."'";
439
+        		$sql .= " FROM ".MAIN_DB_PREFIX."extrafields";
440
+        		$sql .= " WHERE elementtype = '".$elementtype."'";
441
+        		$sql .= " AND name = '".$attrname."'";
442 442
         		//$sql.= " AND entity IN (0,".$conf->entity.")";      Do not test on entity here. We want to see if there is still on field remaning in other entities before deleting field in table
443 443
                 $resql = $this->db->query($sql);
444 444
                 if ($resql)
@@ -446,10 +446,10 @@  discard block
 block discarded – undo
446 446
                     $obj = $this->db->fetch_object($resql);
447 447
                     if ($obj->nb <= 0)
448 448
                     {
449
-            			$result=$this->db->DDLDropField(MAIN_DB_PREFIX.$table,$attrname);	// This also drop the unique key
449
+            			$result = $this->db->DDLDropField(MAIN_DB_PREFIX.$table, $attrname); // This also drop the unique key
450 450
             			if ($result < 0)
451 451
             			{
452
-            				$this->error=$this->db->lasterror();
452
+            				$this->error = $this->db->lasterror();
453 453
             				$error++;
454 454
             			}
455 455
                     }
@@ -472,23 +472,23 @@  discard block
 block discarded – undo
472 472
 	 *  @param  string	$elementtype        Element type ('member', 'product', 'thirdparty', ...)
473 473
 	 *  @return int              			< 0 if KO, 0 if nothing is done, 1 if OK
474 474
 	 */
475
-	private function delete_label($attrname, $elementtype='member')
475
+	private function delete_label($attrname, $elementtype = 'member')
476 476
 	{
477 477
         // phpcs:enable
478 478
 		global $conf;
479 479
 
480
-		if ($elementtype == 'thirdparty') $elementtype='societe';
481
-		if ($elementtype == 'contact') $elementtype='socpeople';
480
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
481
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
482 482
 
483
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
483
+		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname))
484 484
 		{
485 485
 			$sql = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
486
-			$sql.= " WHERE name = '".$attrname."'";
487
-			$sql.= " AND entity IN  (0,".$conf->entity.')';
488
-			$sql.= " AND elementtype = '".$elementtype."'";
486
+			$sql .= " WHERE name = '".$attrname."'";
487
+			$sql .= " AND entity IN  (0,".$conf->entity.')';
488
+			$sql .= " AND elementtype = '".$elementtype."'";
489 489
 
490 490
 			dol_syslog(get_class($this)."::delete_label", LOG_DEBUG);
491
-			$resql=$this->db->query($sql);
491
+			$resql = $this->db->query($sql);
492 492
 			if ($resql)
493 493
 			{
494 494
 				return 1;
@@ -529,82 +529,82 @@  discard block
 block discarded – undo
529 529
      *  @param  int     $totalizable        Is extrafield totalizable on list
530 530
 	 * 	@return	int							>0 if OK, <=0 if KO
531 531
 	 */
532
-	function update($attrname, $label, $type, $length, $elementtype, $unique=0, $required=0, $pos=0, $param='', $alwayseditable=0, $perms='', $list='', $help='', $default='', $computed='', $entity='', $langfile='', $enabled='1', $totalizable=0)
532
+	function update($attrname, $label, $type, $length, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0)
533 533
 	{
534
-		if ($elementtype == 'thirdparty') $elementtype='societe';
535
-		if ($elementtype == 'contact') $elementtype='socpeople';
536
-
537
-        $table=$elementtype.'_extrafields';
538
-		if ($elementtype == 'categorie') $table='categories_extrafields';
539
-
540
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
541
-		{
542
-			if ($type=='boolean') {
543
-				$typedb='int';
544
-				$lengthdb='1';
545
-			} elseif($type=='price') {
546
-				$typedb='double';
547
-				$lengthdb='24,8';
548
-			} elseif($type=='phone') {
549
-				$typedb='varchar';
550
-				$lengthdb='20';
551
-			} elseif($type=='mail') {
552
-				$typedb='varchar';
553
-				$lengthdb='128';
554
-			} elseif($type=='url') {
555
-				$typedb='varchar';
556
-				$lengthdb='255';
557
-			} elseif (($type=='select') || ($type=='sellist') || ($type=='radio') || ($type=='checkbox') || ($type=='chkbxlst')) {
558
-				$typedb='varchar';
559
-				$lengthdb='255';
534
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
535
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
536
+
537
+        $table = $elementtype.'_extrafields';
538
+		if ($elementtype == 'categorie') $table = 'categories_extrafields';
539
+
540
+		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname))
541
+		{
542
+			if ($type == 'boolean') {
543
+				$typedb = 'int';
544
+				$lengthdb = '1';
545
+			} elseif ($type == 'price') {
546
+				$typedb = 'double';
547
+				$lengthdb = '24,8';
548
+			} elseif ($type == 'phone') {
549
+				$typedb = 'varchar';
550
+				$lengthdb = '20';
551
+			} elseif ($type == 'mail') {
552
+				$typedb = 'varchar';
553
+				$lengthdb = '128';
554
+			} elseif ($type == 'url') {
555
+				$typedb = 'varchar';
556
+				$lengthdb = '255';
557
+			} elseif (($type == 'select') || ($type == 'sellist') || ($type == 'radio') || ($type == 'checkbox') || ($type == 'chkbxlst')) {
558
+				$typedb = 'varchar';
559
+				$lengthdb = '255';
560 560
 			} elseif ($type == 'html') {
561
-				$typedb='text';
562
-			} elseif ($type=='link') {
563
-				$typedb='int';
564
-				$lengthdb='11';
565
-			} elseif($type=='password') {
566
-				$typedb='varchar';
567
-				$lengthdb='50';
561
+				$typedb = 'text';
562
+			} elseif ($type == 'link') {
563
+				$typedb = 'int';
564
+				$lengthdb = '11';
565
+			} elseif ($type == 'password') {
566
+				$typedb = 'varchar';
567
+				$lengthdb = '50';
568 568
 			} else {
569
-				$typedb=$type;
570
-				$lengthdb=$length;
569
+				$typedb = $type;
570
+				$lengthdb = $length;
571 571
 			}
572
-			$field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default);
572
+			$field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required ? 'NOT NULL' : 'NULL'), 'default'=>$default);
573 573
 
574 574
 			if ($type != 'separate') // No table update when separate type
575 575
 			{
576
-				$result=$this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
576
+				$result = $this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
577 577
 			}
578 578
 			if ($result > 0 || $type == 'separate')
579 579
 			{
580 580
 				if ($label)
581 581
 				{
582
-					$result=$this->update_label($attrname,$label,$type,$length,$elementtype,$unique,$required,$pos,$param,$alwayseditable,$perms,$list,$help,$default,$computed,$entity,$langfile,$enabled, $totalizable);
582
+					$result = $this->update_label($attrname, $label, $type, $length, $elementtype, $unique, $required, $pos, $param, $alwayseditable, $perms, $list, $help, $default, $computed, $entity, $langfile, $enabled, $totalizable);
583 583
 				}
584 584
 				if ($result > 0)
585 585
 				{
586
-					$sql='';
586
+					$sql = '';
587 587
 					if ($unique)
588 588
 					{
589
-						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
589
+						$sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
590 590
 					}
591 591
 					else
592 592
 					{
593
-						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
593
+						$sql = "ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
594 594
 					}
595 595
 					dol_syslog(get_class($this).'::update', LOG_DEBUG);
596
-					$resql=$this->db->query($sql,1,'dml');
596
+					$resql = $this->db->query($sql, 1, 'dml');
597 597
 					return 1;
598 598
 				}
599 599
 				else
600 600
 				{
601
-					$this->error=$this->db->lasterror();
601
+					$this->error = $this->db->lasterror();
602 602
 					return -1;
603 603
 				}
604 604
 			}
605 605
 			else
606 606
 			{
607
-				$this->error=$this->db->lasterror();
607
+				$this->error = $this->db->lasterror();
608 608
 				return -1;
609 609
 			}
610 610
 		}
@@ -639,26 +639,26 @@  discard block
 block discarded – undo
639 639
      *  @param  int     $totalizable        Is extrafield totalizable on list
640 640
      *  @return	int							<=0 if KO, >0 if OK
641 641
 	 */
642
-	private function update_label($attrname,$label,$type,$size,$elementtype,$unique=0,$required=0,$pos=0,$param='',$alwayseditable=0,$perms='',$list='0',$help='',$default='',$computed='',$entity='',$langfile='',$enabled='1', $totalizable=0)
642
+	private function update_label($attrname, $label, $type, $size, $elementtype, $unique = 0, $required = 0, $pos = 0, $param = '', $alwayseditable = 0, $perms = '', $list = '0', $help = '', $default = '', $computed = '', $entity = '', $langfile = '', $enabled = '1', $totalizable = 0)
643 643
 	{
644 644
         // phpcs:enable
645 645
 		global $conf, $user;
646 646
 		dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable);
647 647
 
648 648
 		// Clean parameters
649
-		if ($elementtype == 'thirdparty') $elementtype='societe';
650
-		if ($elementtype == 'contact') $elementtype='socpeople';
649
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
650
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
651 651
 
652
-		if (empty($pos)) $pos=0;
653
-		if (empty($list)) $list='0';
652
+		if (empty($pos)) $pos = 0;
653
+		if (empty($list)) $list = '0';
654 654
         if (empty($totalizable)) {
655 655
             $totalizable = 0;
656 656
         }
657
-		if (empty($required)) $required=0;
658
-		if (empty($unique)) $unique=0;
659
-		if (empty($alwayseditable)) $alwayseditable=0;
657
+		if (empty($required)) $required = 0;
658
+		if (empty($unique)) $unique = 0;
659
+		if (empty($alwayseditable)) $alwayseditable = 0;
660 660
 
661
-		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
661
+		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/", $attrname))
662 662
 		{
663 663
 			$this->db->begin();
664 664
 
@@ -672,76 +672,76 @@  discard block
 block discarded – undo
672 672
 			}
673 673
 			else
674 674
 			{
675
-				$params='';
675
+				$params = '';
676 676
 			}
677 677
 
678 678
 			if ($entity === '' || $entity != '0')
679 679
 			{
680 680
 				// We dont want on all entities, we delete all and current
681 681
 				$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
682
-				$sql_del.= " WHERE name = '".$attrname."'";
683
-				$sql_del.= " AND entity IN (0, ".($entity===''?$conf->entity:$entity).")";
684
-				$sql_del.= " AND elementtype = '".$elementtype."'";
682
+				$sql_del .= " WHERE name = '".$attrname."'";
683
+				$sql_del .= " AND entity IN (0, ".($entity === '' ? $conf->entity : $entity).")";
684
+				$sql_del .= " AND elementtype = '".$elementtype."'";
685 685
 			}
686 686
 			else
687 687
 			{
688 688
 				// We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity)
689 689
 				$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
690
-				$sql_del.= " WHERE name = '".$attrname."'";
691
-				$sql_del.= " AND entity = 0";
692
-				$sql_del.= " AND elementtype = '".$elementtype."'";
690
+				$sql_del .= " WHERE name = '".$attrname."'";
691
+				$sql_del .= " AND entity = 0";
692
+				$sql_del .= " AND elementtype = '".$elementtype."'";
693 693
 			}
694
-			$resql1=$this->db->query($sql_del);
694
+			$resql1 = $this->db->query($sql_del);
695 695
 
696 696
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."extrafields(";
697
-			$sql.= " name,";		// This is code
698
-			$sql.= " entity,";
699
-			$sql.= " label,";
700
-			$sql.= " type,";
701
-			$sql.= " size,";
702
-			$sql.= " elementtype,";
703
-			$sql.= " fieldunique,";
704
-			$sql.= " fieldrequired,";
705
-			$sql.= " perms,";
706
-			$sql.= " langs,";
707
-			$sql.= " pos,";
708
-			$sql.= " alwayseditable,";
709
-			$sql.= " param,";
710
-			$sql.= " list,";
711
-            $sql.= " totalizable,";
712
-			$sql.= " fielddefault,";
713
-			$sql.= " fieldcomputed,";
714
-			$sql.= " fk_user_author,";
715
-			$sql.= " fk_user_modif,";
716
-			$sql.= " datec,";
717
-			$sql.= " enabled,";
718
-			$sql.= " help";
719
-			$sql.= ") VALUES (";
720
-			$sql.= "'".$attrname."',";
721
-			$sql.= " ".($entity===''?$conf->entity:$entity).",";
722
-			$sql.= " '".$this->db->escape($label)."',";
723
-			$sql.= " '".$this->db->escape($type)."',";
724
-			$sql.= " '".$this->db->escape($size)."',";
725
-			$sql.= " '".$this->db->escape($elementtype)."',";
726
-			$sql.= " ".$unique.",";
727
-			$sql.= " ".$required.",";
728
-			$sql.= " ".($perms?"'".$this->db->escape($perms)."'":"null").",";
729
-			$sql.= " ".($langfile?"'".$this->db->escape($langfile)."'":"null").",";
730
-			$sql.= " ".$pos.",";
731
-			$sql.= " '".$this->db->escape($alwayseditable)."',";
732
-			$sql.= " '".$this->db->escape($params)."',";
733
-			$sql.= " '".$this->db->escape($list)."', ";
734
-            $sql.= " ".$totalizable.",";
735
-			$sql.= " ".(($default!='')?"'".$this->db->escape($default)."'":"null").",";
736
-			$sql.= " ".($computed?"'".$this->db->escape($computed)."'":"null").",";
737
-			$sql .= " " . $user->id . ",";
738
-			$sql .= " " . $user->id . ",";
739
-			$sql .= "'" . $this->db->idate(dol_now()) . "',";
740
-			$sql .= "'" . $this->db->escape($enabled). "',";
741
-			$sql.= " ".($help?"'".$this->db->escape($help)."'":"null");
742
-			$sql.= ")";
743
-
744
-			$resql2=$this->db->query($sql);
697
+			$sql .= " name,"; // This is code
698
+			$sql .= " entity,";
699
+			$sql .= " label,";
700
+			$sql .= " type,";
701
+			$sql .= " size,";
702
+			$sql .= " elementtype,";
703
+			$sql .= " fieldunique,";
704
+			$sql .= " fieldrequired,";
705
+			$sql .= " perms,";
706
+			$sql .= " langs,";
707
+			$sql .= " pos,";
708
+			$sql .= " alwayseditable,";
709
+			$sql .= " param,";
710
+			$sql .= " list,";
711
+            $sql .= " totalizable,";
712
+			$sql .= " fielddefault,";
713
+			$sql .= " fieldcomputed,";
714
+			$sql .= " fk_user_author,";
715
+			$sql .= " fk_user_modif,";
716
+			$sql .= " datec,";
717
+			$sql .= " enabled,";
718
+			$sql .= " help";
719
+			$sql .= ") VALUES (";
720
+			$sql .= "'".$attrname."',";
721
+			$sql .= " ".($entity === '' ? $conf->entity : $entity).",";
722
+			$sql .= " '".$this->db->escape($label)."',";
723
+			$sql .= " '".$this->db->escape($type)."',";
724
+			$sql .= " '".$this->db->escape($size)."',";
725
+			$sql .= " '".$this->db->escape($elementtype)."',";
726
+			$sql .= " ".$unique.",";
727
+			$sql .= " ".$required.",";
728
+			$sql .= " ".($perms ? "'".$this->db->escape($perms)."'" : "null").",";
729
+			$sql .= " ".($langfile ? "'".$this->db->escape($langfile)."'" : "null").",";
730
+			$sql .= " ".$pos.",";
731
+			$sql .= " '".$this->db->escape($alwayseditable)."',";
732
+			$sql .= " '".$this->db->escape($params)."',";
733
+			$sql .= " '".$this->db->escape($list)."', ";
734
+            $sql .= " ".$totalizable.",";
735
+			$sql .= " ".(($default != '') ? "'".$this->db->escape($default)."'" : "null").",";
736
+			$sql .= " ".($computed ? "'".$this->db->escape($computed)."'" : "null").",";
737
+			$sql .= " ".$user->id.",";
738
+			$sql .= " ".$user->id.",";
739
+			$sql .= "'".$this->db->idate(dol_now())."',";
740
+			$sql .= "'".$this->db->escape($enabled)."',";
741
+			$sql .= " ".($help ? "'".$this->db->escape($help)."'" : "null");
742
+			$sql .= ")";
743
+
744
+			$resql2 = $this->db->query($sql);
745 745
 
746 746
 			if ($resql1 && $resql2)
747 747
 			{
@@ -770,34 +770,34 @@  discard block
 block discarded – undo
770 770
 	 * 	@param	boolean		$forceload			Force load of extra fields whatever is option MAIN_EXTRAFIELDS_DISABLED. Deprecated. Should not be required.
771 771
 	 * 	@return	array							Array of attributes keys+label for all extra fields.
772 772
 	 */
773
-	function fetch_name_optionals_label($elementtype,$forceload=false)
773
+	function fetch_name_optionals_label($elementtype, $forceload = false)
774 774
 	{
775 775
         // phpcs:enable
776 776
 		global $conf;
777 777
 
778 778
 		if (empty($elementtype)) return array();
779 779
 
780
-		if ($elementtype == 'thirdparty') $elementtype='societe';
781
-		if ($elementtype == 'contact') $elementtype='socpeople';
782
-		if ($elementtype == 'order_supplier') $elementtype='commande_fournisseur';
780
+		if ($elementtype == 'thirdparty') $elementtype = 'societe';
781
+		if ($elementtype == 'contact') $elementtype = 'socpeople';
782
+		if ($elementtype == 'order_supplier') $elementtype = 'commande_fournisseur';
783 783
 
784
-		$array_name_label=array();
784
+		$array_name_label = array();
785 785
 
786 786
 		// To avoid conflicts with external modules. TODO Remove this.
787 787
 		if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label;
788 788
 
789 789
 		// Set array of label of entity
790 790
 		// TODO Remove completely loading of label. This should be done by presentation.
791
-		$labelmulticompany=array();
791
+		$labelmulticompany = array();
792 792
 		if (!empty($conf->multicompany->enabled))
793 793
 		{
794
-			$sql_entity_name='SELECT rowid, label FROM '.MAIN_DB_PREFIX.'entity WHERE rowid in (0,'.$conf->entity.')';
795
-			$resql_entity_name=$this->db->query($sql_entity_name);
794
+			$sql_entity_name = 'SELECT rowid, label FROM '.MAIN_DB_PREFIX.'entity WHERE rowid in (0,'.$conf->entity.')';
795
+			$resql_entity_name = $this->db->query($sql_entity_name);
796 796
 			if ($resql_entity_name)
797 797
 			{
798 798
 				while ($obj = $this->db->fetch_object($resql_entity_name))
799 799
 				{
800
-					$labelmulticompany[$obj->rowid]=$obj->label;
800
+					$labelmulticompany[$obj->rowid] = $obj->label;
801 801
 				}
802 802
 			}
803 803
 		}
@@ -806,12 +806,12 @@  discard block
 block discarded – undo
806 806
 		dol_syslog("fetch_name_optionals_label elementtype=".$elementtype);
807 807
 
808 808
 		$sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help";
809
-		$sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
810
-		$sql.= " WHERE entity IN (0,".$conf->entity.")";
811
-		if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'";	// Filed with object->table_element
812
-		$sql.= " ORDER BY pos";
809
+		$sql .= " FROM ".MAIN_DB_PREFIX."extrafields";
810
+		$sql .= " WHERE entity IN (0,".$conf->entity.")";
811
+		if ($elementtype) $sql .= " AND elementtype = '".$elementtype."'"; // Filed with object->table_element
812
+		$sql .= " ORDER BY pos";
813 813
 
814
-		$resql=$this->db->query($sql);
814
+		$resql = $this->db->query($sql);
815 815
 		if ($resql)
816 816
 		{
817 817
 			if ($this->db->num_rows($resql))
@@ -821,57 +821,57 @@  discard block
 block discarded – undo
821 821
 					// We can add this attribute to object. TODO Remove this and return $this->attributes[$elementtype]['label']
822 822
 					if ($tab->type != 'separate')
823 823
 					{
824
-						$array_name_label[$tab->name]=$tab->label;
824
+						$array_name_label[$tab->name] = $tab->label;
825 825
 					}
826 826
 
827 827
 					// Old usage
828
-					$this->attribute_type[$tab->name]=$tab->type;
829
-					$this->attribute_label[$tab->name]=$tab->label;
830
-					$this->attribute_size[$tab->name]=$tab->size;
831
-					$this->attribute_elementtype[$tab->name]=$tab->elementtype;
832
-					$this->attribute_default[$tab->name]=$tab->fielddefault;
833
-					$this->attribute_computed[$tab->name]=$tab->fieldcomputed;
834
-					$this->attribute_unique[$tab->name]=$tab->fieldunique;
835
-					$this->attribute_required[$tab->name]=$tab->fieldrequired;
836
-					$this->attribute_param[$tab->name]=($tab->param ? unserialize($tab->param) : '');
837
-					$this->attribute_pos[$tab->name]=$tab->pos;
838
-					$this->attribute_alwayseditable[$tab->name]=$tab->alwayseditable;
839
-					$this->attribute_perms[$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
840
-					$this->attribute_langfile[$tab->name]=$tab->langs;
841
-					$this->attribute_list[$tab->name]=$tab->list;
842
-					$this->attribute_totalizable[$tab->name]=$tab->totalizable;
843
-					$this->attribute_entityid[$tab->name]=$tab->entity;
844
-					$this->attribute_entitylabel[$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
828
+					$this->attribute_type[$tab->name] = $tab->type;
829
+					$this->attribute_label[$tab->name] = $tab->label;
830
+					$this->attribute_size[$tab->name] = $tab->size;
831
+					$this->attribute_elementtype[$tab->name] = $tab->elementtype;
832
+					$this->attribute_default[$tab->name] = $tab->fielddefault;
833
+					$this->attribute_computed[$tab->name] = $tab->fieldcomputed;
834
+					$this->attribute_unique[$tab->name] = $tab->fieldunique;
835
+					$this->attribute_required[$tab->name] = $tab->fieldrequired;
836
+					$this->attribute_param[$tab->name] = ($tab->param ? unserialize($tab->param) : '');
837
+					$this->attribute_pos[$tab->name] = $tab->pos;
838
+					$this->attribute_alwayseditable[$tab->name] = $tab->alwayseditable;
839
+					$this->attribute_perms[$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
840
+					$this->attribute_langfile[$tab->name] = $tab->langs;
841
+					$this->attribute_list[$tab->name] = $tab->list;
842
+					$this->attribute_totalizable[$tab->name] = $tab->totalizable;
843
+					$this->attribute_entityid[$tab->name] = $tab->entity;
844
+					$this->attribute_entitylabel[$tab->name] = (empty($labelmulticompany[$tab->entity]) ? 'Entity'.$tab->entity : $labelmulticompany[$tab->entity]);
845 845
 
846 846
 					// New usage
847
-					$this->attributes[$tab->elementtype]['type'][$tab->name]=$tab->type;
848
-					$this->attributes[$tab->elementtype]['label'][$tab->name]=$tab->label;
849
-					$this->attributes[$tab->elementtype]['size'][$tab->name]=$tab->size;
850
-					$this->attributes[$tab->elementtype]['elementtype'][$tab->name]=$tab->elementtype;
851
-					$this->attributes[$tab->elementtype]['default'][$tab->name]=$tab->fielddefault;
852
-					$this->attributes[$tab->elementtype]['computed'][$tab->name]=$tab->fieldcomputed;
853
-					$this->attributes[$tab->elementtype]['unique'][$tab->name]=$tab->fieldunique;
854
-					$this->attributes[$tab->elementtype]['required'][$tab->name]=$tab->fieldrequired;
855
-					$this->attributes[$tab->elementtype]['param'][$tab->name]=($tab->param ? unserialize($tab->param) : '');
856
-					$this->attributes[$tab->elementtype]['pos'][$tab->name]=$tab->pos;
857
-					$this->attributes[$tab->elementtype]['alwayseditable'][$tab->name]=$tab->alwayseditable;
858
-					$this->attributes[$tab->elementtype]['perms'][$tab->name]=(strlen($tab->perms) == 0 ? 1 : $tab->perms);
859
-					$this->attributes[$tab->elementtype]['langfile'][$tab->name]=$tab->langs;
860
-					$this->attributes[$tab->elementtype]['list'][$tab->name]=$tab->list;
861
-                    $this->attributes[$tab->elementtype]['totalizable'][$tab->name]=$tab->totalizable;
862
-					$this->attributes[$tab->elementtype]['entityid'][$tab->name]=$tab->entity;
863
-					$this->attributes[$tab->elementtype]['entitylabel'][$tab->name]=(empty($labelmulticompany[$tab->entity])?'Entity'.$tab->entity:$labelmulticompany[$tab->entity]);
864
-					$this->attributes[$tab->elementtype]['enabled'][$tab->name]=$tab->enabled;
865
-					$this->attributes[$tab->elementtype]['help'][$tab->name]=$tab->help;
866
-
867
-					$this->attributes[$tab->elementtype]['loaded']=1;
847
+					$this->attributes[$tab->elementtype]['type'][$tab->name] = $tab->type;
848
+					$this->attributes[$tab->elementtype]['label'][$tab->name] = $tab->label;
849
+					$this->attributes[$tab->elementtype]['size'][$tab->name] = $tab->size;
850
+					$this->attributes[$tab->elementtype]['elementtype'][$tab->name] = $tab->elementtype;
851
+					$this->attributes[$tab->elementtype]['default'][$tab->name] = $tab->fielddefault;
852
+					$this->attributes[$tab->elementtype]['computed'][$tab->name] = $tab->fieldcomputed;
853
+					$this->attributes[$tab->elementtype]['unique'][$tab->name] = $tab->fieldunique;
854
+					$this->attributes[$tab->elementtype]['required'][$tab->name] = $tab->fieldrequired;
855
+					$this->attributes[$tab->elementtype]['param'][$tab->name] = ($tab->param ? unserialize($tab->param) : '');
856
+					$this->attributes[$tab->elementtype]['pos'][$tab->name] = $tab->pos;
857
+					$this->attributes[$tab->elementtype]['alwayseditable'][$tab->name] = $tab->alwayseditable;
858
+					$this->attributes[$tab->elementtype]['perms'][$tab->name] = (strlen($tab->perms) == 0 ? 1 : $tab->perms);
859
+					$this->attributes[$tab->elementtype]['langfile'][$tab->name] = $tab->langs;
860
+					$this->attributes[$tab->elementtype]['list'][$tab->name] = $tab->list;
861
+                    $this->attributes[$tab->elementtype]['totalizable'][$tab->name] = $tab->totalizable;
862
+					$this->attributes[$tab->elementtype]['entityid'][$tab->name] = $tab->entity;
863
+					$this->attributes[$tab->elementtype]['entitylabel'][$tab->name] = (empty($labelmulticompany[$tab->entity]) ? 'Entity'.$tab->entity : $labelmulticompany[$tab->entity]);
864
+					$this->attributes[$tab->elementtype]['enabled'][$tab->name] = $tab->enabled;
865
+					$this->attributes[$tab->elementtype]['help'][$tab->name] = $tab->help;
866
+
867
+					$this->attributes[$tab->elementtype]['loaded'] = 1;
868 868
 				}
869 869
 			}
870
-			if ($elementtype) $this->attributes[$elementtype]['loaded']=1;	// If nothing found, we also save tag 'loaded'
870
+			if ($elementtype) $this->attributes[$elementtype]['loaded'] = 1; // If nothing found, we also save tag 'loaded'
871 871
 		}
872 872
 		else
873 873
 		{
874
-			$this->error=$this->db->lasterror();
874
+			$this->error = $this->db->lasterror();
875 875
 			dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
876 876
 		}
877 877
 
@@ -893,57 +893,57 @@  discard block
 block discarded – undo
893 893
 	 * @param  string  $extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
894 894
 	 * @return string
895 895
 	 */
896
-	function showInputField($key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss='', $objectid=0, $extrafieldsobjectkey='')
896
+	function showInputField($key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = '', $objectid = 0, $extrafieldsobjectkey = '')
897 897
 	{
898
-		global $conf,$langs,$form;
898
+		global $conf, $langs, $form;
899 899
 
900
-		if (! is_object($form))
900
+		if (!is_object($form))
901 901
 		{
902 902
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
903
-			$form=new Form($this->db);
903
+			$form = new Form($this->db);
904 904
 		}
905 905
 
906
-		$out='';
906
+		$out = '';
907 907
 
908
-		$keyprefix = $keyprefix.'options_';		// Because we work on extrafields
908
+		$keyprefix = $keyprefix.'options_'; // Because we work on extrafields
909 909
 
910
-		if (! empty($extrafieldsobjectkey))
910
+		if (!empty($extrafieldsobjectkey))
911 911
 		{
912
-			$label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
913
-			$type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
914
-			$size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
915
-			$default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
916
-			$computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
917
-			$unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
918
-			$required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
919
-			$param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
920
-			$perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
921
-			$langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
922
-			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
923
-			$totalizable=$this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
924
-			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
925
-			$hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
912
+			$label = $this->attributes[$extrafieldsobjectkey]['label'][$key];
913
+			$type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
914
+			$size = $this->attributes[$extrafieldsobjectkey]['size'][$key];
915
+			$default = $this->attributes[$extrafieldsobjectkey]['default'][$key];
916
+			$computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key];
917
+			$unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key];
918
+			$required = $this->attributes[$extrafieldsobjectkey]['required'][$key];
919
+			$param = $this->attributes[$extrafieldsobjectkey]['param'][$key];
920
+			$perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
921
+			$langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key];
922
+			$list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
923
+			$totalizable = $this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
924
+			$help = $this->attributes[$extrafieldsobjectkey]['help'][$key];
925
+			$hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
926 926
 		}
927 927
 		else	// Old usage
928 928
 		{
929
-			$label=$this->attribute_label[$key];
930
-			$type =$this->attribute_type[$key];
931
-			$size =$this->attribute_size[$key];
932
-			$elementtype=$this->attribute_elementtype[$key];	// Seems not used
933
-			$default=$this->attribute_default[$key];
934
-			$computed=$this->attribute_computed[$key];
935
-			$unique=$this->attribute_unique[$key];
936
-			$required=$this->attribute_required[$key];
937
-			$param=$this->attribute_param[$key];
938
-			$langfile=$this->attribute_langfile[$key];
939
-			$list=$this->attribute_list[$key];
940
-			$totalizable=$this->attribute_totalizable[$key];
941
-			$hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
929
+			$label = $this->attribute_label[$key];
930
+			$type = $this->attribute_type[$key];
931
+			$size = $this->attribute_size[$key];
932
+			$elementtype = $this->attribute_elementtype[$key]; // Seems not used
933
+			$default = $this->attribute_default[$key];
934
+			$computed = $this->attribute_computed[$key];
935
+			$unique = $this->attribute_unique[$key];
936
+			$required = $this->attribute_required[$key];
937
+			$param = $this->attribute_param[$key];
938
+			$langfile = $this->attribute_langfile[$key];
939
+			$list = $this->attribute_list[$key];
940
+			$totalizable = $this->attribute_totalizable[$key];
941
+			$hidden = (empty($list) ? 1 : 0); // If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
942 942
 		}
943 943
 
944 944
 		if ($computed)
945 945
 		{
946
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
946
+			if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
947 947
 			else return '';
948 948
 		}
949 949
 
@@ -957,21 +957,21 @@  discard block
 block discarded – undo
957 957
 			{
958 958
 				$morecss = 'minwidth200imp';
959 959
 			}
960
-			elseif (in_array($type,array('int','integer','double','price')))
960
+			elseif (in_array($type, array('int', 'integer', 'double', 'price')))
961 961
 			{
962 962
 				$morecss = 'maxwidth75';
963 963
 			}
964 964
 			elseif ($type == 'password')
965 965
 			{
966
-				$morecss='maxwidth100';
966
+				$morecss = 'maxwidth100';
967 967
 			}
968 968
 			elseif ($type == 'url')
969 969
 			{
970
-				$morecss='minwidth400';
970
+				$morecss = 'minwidth400';
971 971
 			}
972 972
 			elseif ($type == 'boolean')
973 973
 			{
974
-				$morecss='';
974
+				$morecss = '';
975 975
 			}
976 976
 			else
977 977
 			{
@@ -990,12 +990,12 @@  discard block
 block discarded – undo
990 990
 			}
991 991
 		}
992 992
 
993
-		if (in_array($type,array('date','datetime')))
993
+		if (in_array($type, array('date', 'datetime')))
994 994
 		{
995
-			$tmp=explode(',',$size);
996
-			$newsize=$tmp[0];
995
+			$tmp = explode(',', $size);
996
+			$newsize = $tmp[0];
997 997
 
998
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
998
+			$showtime = in_array($type, array('datetime')) ? 1 : 0;
999 999
 
1000 1000
 			// Do not show current date when field not required (see selectDate() method)
1001 1001
 			if (!$required && $value == '') $value = '-1';
@@ -1003,244 +1003,244 @@  discard block
 block discarded – undo
1003 1003
 			// TODO Must also support $moreparam
1004 1004
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
1005 1005
 		}
1006
-		elseif (in_array($type,array('int','integer')))
1006
+		elseif (in_array($type, array('int', 'integer')))
1007 1007
 		{
1008
-			$tmp=explode(',',$size);
1009
-			$newsize=$tmp[0];
1010
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1008
+			$tmp = explode(',', $size);
1009
+			$newsize = $tmp[0];
1010
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
1011 1011
 		}
1012 1012
 		elseif (preg_match('/varchar/', $type))
1013 1013
 		{
1014
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1014
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
1015 1015
 		}
1016 1016
 		elseif (in_array($type, array('mail', 'phone', 'url')))
1017 1017
 		{
1018
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1018
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
1019 1019
 		}
1020 1020
 		elseif ($type == 'text')
1021 1021
 		{
1022
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1022
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1023 1023
 			{
1024 1024
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1025
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
1026
-				$out=$doleditor->Create(1);
1025
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
1026
+				$out = $doleditor->Create(1);
1027 1027
 			}
1028 1028
 			else
1029 1029
 			{
1030
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1030
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
1031 1031
 			}
1032 1032
 		}
1033 1033
 		elseif ($type == 'html')
1034 1034
 		{
1035
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1035
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1036 1036
 			{
1037 1037
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1038
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
1039
-				$out=$doleditor->Create(1);
1038
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
1039
+				$out = $doleditor->Create(1);
1040 1040
 			}
1041 1041
 			else
1042 1042
 			{
1043
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1043
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
1044 1044
 			}
1045 1045
 		}
1046 1046
 		elseif ($type == 'boolean')
1047 1047
 		{
1048
-			$checked='';
1048
+			$checked = '';
1049 1049
 			if (!empty($value)) {
1050
-				$checked=' checked value="1" ';
1050
+				$checked = ' checked value="1" ';
1051 1051
 			} else {
1052
-				$checked=' value="1" ';
1052
+				$checked = ' value="1" ';
1053 1053
 			}
1054
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
1054
+			$out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
1055 1055
 		}
1056 1056
 		elseif ($type == 'price')
1057 1057
 		{
1058 1058
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1059
-				$value=price($value);
1059
+				$value = price($value);
1060 1060
 			}
1061
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
1061
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
1062 1062
 		}
1063 1063
 		elseif ($type == 'double')
1064 1064
 		{
1065 1065
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1066
-				$value=price($value);
1066
+				$value = price($value);
1067 1067
 			}
1068
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
1068
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
1069 1069
 		}
1070 1070
 		elseif ($type == 'select')
1071 1071
 		{
1072 1072
 			$out = '';
1073
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1073
+			if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1074 1074
 			{
1075
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1076
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1075
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1076
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1077 1077
 			}
1078 1078
 
1079
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1080
-			$out.='<option value="0">&nbsp;</option>';
1079
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
1080
+			$out .= '<option value="0">&nbsp;</option>';
1081 1081
 			foreach ($param['options'] as $key => $val)
1082 1082
 			{
1083 1083
 				if ((string) $key == '') continue;
1084 1084
 				list($val, $parent) = explode('|', $val);
1085
-				$out.='<option value="'.$key.'"';
1086
-				$out.= (((string) $value == (string) $key)?' selected':'');
1087
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
1088
-				$out.='>';
1089
-				if ($langfile && $val) $out.=$langs->trans($val);
1090
-				else $out.=$val;
1091
-				$out.='</option>';
1085
+				$out .= '<option value="'.$key.'"';
1086
+				$out .= (((string) $value == (string) $key) ? ' selected' : '');
1087
+				$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
1088
+				$out .= '>';
1089
+				if ($langfile && $val) $out .= $langs->trans($val);
1090
+				else $out .= $val;
1091
+				$out .= '</option>';
1092 1092
 			}
1093
-			$out.='</select>';
1093
+			$out .= '</select>';
1094 1094
 		}
1095 1095
 		elseif ($type == 'sellist')
1096 1096
 		{
1097 1097
 			$out = '';
1098
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1098
+			if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
1099 1099
 			{
1100
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1101
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1100
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1101
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
1102 1102
 			}
1103 1103
 
1104
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
1104
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
1105 1105
 			if (is_array($param['options']))
1106 1106
 			{
1107
-				$param_list=array_keys($param['options']);
1107
+				$param_list = array_keys($param['options']);
1108 1108
 				$InfoFieldList = explode(":", $param_list[0]);
1109
-				$parentName='';
1110
-				$parentField='';
1109
+				$parentName = '';
1110
+				$parentField = '';
1111 1111
 				// 0 : tableName
1112 1112
 				// 1 : label field name
1113 1113
 				// 2 : key fields name (if differ of rowid)
1114 1114
 				// 3 : key field parent (for dependent lists)
1115 1115
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1116
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
1116
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
1117 1117
 
1118 1118
 
1119
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
1119
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
1120 1120
 				{
1121 1121
 					if (strpos($InfoFieldList[4], 'extra.') !== false)
1122 1122
 					{
1123
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
1123
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
1124 1124
 					} else {
1125
-						$keyList=$InfoFieldList[2].' as rowid';
1125
+						$keyList = $InfoFieldList[2].' as rowid';
1126 1126
 					}
1127 1127
 				}
1128
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
1128
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
1129 1129
 				{
1130 1130
 					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
1131
-					$keyList.= ', '.$parentField;
1131
+					$keyList .= ', '.$parentField;
1132 1132
 				}
1133 1133
 
1134
-				$fields_label = explode('|',$InfoFieldList[1]);
1134
+				$fields_label = explode('|', $InfoFieldList[1]);
1135 1135
 				if (is_array($fields_label))
1136 1136
 				{
1137
-					$keyList .=', ';
1137
+					$keyList .= ', ';
1138 1138
 					$keyList .= implode(', ', $fields_label);
1139 1139
 				}
1140 1140
 
1141
-				$sqlwhere='';
1141
+				$sqlwhere = '';
1142 1142
 				$sql = 'SELECT '.$keyList;
1143
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1143
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
1144 1144
 				if (!empty($InfoFieldList[4]))
1145 1145
 				{
1146 1146
 				    // can use curent entity filter
1147
-				    if (strpos($InfoFieldList[4], '$ENTITY$')!==false) {
1148
-				        $InfoFieldList[4]=str_replace('$ENTITY$',$conf->entity,$InfoFieldList[4]);
1147
+				    if (strpos($InfoFieldList[4], '$ENTITY$') !== false) {
1148
+				        $InfoFieldList[4] = str_replace('$ENTITY$', $conf->entity, $InfoFieldList[4]);
1149 1149
 				    }
1150 1150
 					// can use SELECT request
1151
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1152
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1151
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
1152
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
1153 1153
 					}
1154 1154
 
1155 1155
 					// current object id can be use into filter
1156
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1157
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1156
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
1157
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
1158 1158
 					} else {
1159
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1159
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
1160 1160
 					}
1161 1161
 					//We have to join on extrafield table
1162
-					if (strpos($InfoFieldList[4], 'extra')!==false)
1162
+					if (strpos($InfoFieldList[4], 'extra') !== false)
1163 1163
 					{
1164
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
1165
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
1164
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
1165
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
1166 1166
 					}
1167 1167
 					else
1168 1168
 					{
1169
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
1169
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
1170 1170
 					}
1171 1171
 				}
1172 1172
 				else
1173 1173
 				{
1174
-					$sqlwhere.= ' WHERE 1=1';
1174
+					$sqlwhere .= ' WHERE 1=1';
1175 1175
 				}
1176 1176
 				// Some tables may have field, some other not. For the moment we disable it.
1177
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
1177
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
1178 1178
 				{
1179
-					$sqlwhere.= ' AND entity = '.$conf->entity;
1179
+					$sqlwhere .= ' AND entity = '.$conf->entity;
1180 1180
 				}
1181
-				$sql.=$sqlwhere;
1181
+				$sql .= $sqlwhere;
1182 1182
 				//print $sql;
1183 1183
 
1184
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
1184
+				$sql .= ' ORDER BY '.implode(', ', $fields_label);
1185 1185
 
1186 1186
 				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
1187 1187
 				$resql = $this->db->query($sql);
1188 1188
 				if ($resql)
1189 1189
 				{
1190
-					$out.='<option value="0">&nbsp;</option>';
1190
+					$out .= '<option value="0">&nbsp;</option>';
1191 1191
 					$num = $this->db->num_rows($resql);
1192 1192
 					$i = 0;
1193 1193
 					while ($i < $num)
1194 1194
 					{
1195
-						$labeltoshow='';
1195
+						$labeltoshow = '';
1196 1196
 						$obj = $this->db->fetch_object($resql);
1197 1197
 
1198 1198
 						// Several field into label (eq table:code|libelle:rowid)
1199 1199
 						$notrans = false;
1200
-						$fields_label = explode('|',$InfoFieldList[1]);
1200
+						$fields_label = explode('|', $InfoFieldList[1]);
1201 1201
 						if (is_array($fields_label))
1202 1202
 						{
1203 1203
 							$notrans = true;
1204 1204
 							foreach ($fields_label as $field_toshow)
1205 1205
 							{
1206
-								$labeltoshow.= $obj->$field_toshow.' ';
1206
+								$labeltoshow .= $obj->$field_toshow.' ';
1207 1207
 							}
1208 1208
 						}
1209 1209
 						else
1210 1210
 						{
1211
-							$labeltoshow=$obj->{$InfoFieldList[1]};
1211
+							$labeltoshow = $obj->{$InfoFieldList[1]};
1212 1212
 						}
1213
-						$labeltoshow=dol_trunc($labeltoshow,45);
1213
+						$labeltoshow = dol_trunc($labeltoshow, 45);
1214 1214
 
1215 1215
 						if ($value == $obj->rowid)
1216 1216
 						{
1217 1217
 							foreach ($fields_label as $field_toshow)
1218 1218
 							{
1219
-								$translabel=$langs->trans($obj->$field_toshow);
1220
-								if ($translabel!=$obj->$field_toshow) {
1221
-									$labeltoshow=dol_trunc($translabel,18).' ';
1222
-								}else {
1223
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
1219
+								$translabel = $langs->trans($obj->$field_toshow);
1220
+								if ($translabel != $obj->$field_toshow) {
1221
+									$labeltoshow = dol_trunc($translabel, 18).' ';
1222
+								} else {
1223
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
1224 1224
 								}
1225 1225
 							}
1226
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1226
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1227 1227
 						}
1228 1228
 						else
1229 1229
 						{
1230
-							if (! $notrans)
1230
+							if (!$notrans)
1231 1231
 							{
1232
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
1233
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
1234
-									$labeltoshow=dol_trunc($translabel,18);
1232
+								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1233
+								if ($translabel != $obj->{$InfoFieldList[1]}) {
1234
+									$labeltoshow = dol_trunc($translabel, 18);
1235 1235
 								}
1236 1236
 								else {
1237
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
1237
+									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]},18);
1238 1238
 								}
1239 1239
 							}
1240
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
1241
-							if ($value==$obj->rowid)
1240
+							if (empty($labeltoshow)) $labeltoshow = '(not defined)';
1241
+							if ($value == $obj->rowid)
1242 1242
 							{
1243
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1243
+								$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1244 1244
 							}
1245 1245
 
1246 1246
 							if (!empty($InfoFieldList[3]) && $parentField)
@@ -1248,10 +1248,10 @@  discard block
 block discarded – undo
1248 1248
 								$parent = $parentName.':'.$obj->{$parentField};
1249 1249
 							}
1250 1250
 
1251
-							$out.='<option value="'.$obj->rowid.'"';
1252
-							$out.= ($value==$obj->rowid?' selected':'');
1253
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
1254
-							$out.='>'.$labeltoshow.'</option>';
1251
+							$out .= '<option value="'.$obj->rowid.'"';
1252
+							$out .= ($value == $obj->rowid ? ' selected' : '');
1253
+							$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
1254
+							$out .= '>'.$labeltoshow.'</option>';
1255 1255
 						}
1256 1256
 
1257 1257
 						$i++;
@@ -1262,23 +1262,23 @@  discard block
 block discarded – undo
1262 1262
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
1263 1263
 				}
1264 1264
 			}
1265
-			$out.='</select>';
1265
+			$out .= '</select>';
1266 1266
 		}
1267 1267
 		elseif ($type == 'checkbox')
1268 1268
 		{
1269
-			$value_arr=explode(',',$value);
1270
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
1269
+			$value_arr = explode(',', $value);
1270
+			$out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
1271 1271
 		}
1272 1272
 		elseif ($type == 'radio')
1273 1273
 		{
1274
-			$out='';
1274
+			$out = '';
1275 1275
 			foreach ($param['options'] as $keyopt => $val)
1276 1276
 			{
1277
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
1278
-				$out.=' value="'.$keyopt.'"';
1279
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
1280
-				$out.= ($value==$keyopt?'checked':'');
1281
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
1277
+				$out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
1278
+				$out .= ' value="'.$keyopt.'"';
1279
+				$out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
1280
+				$out .= ($value == $keyopt ? 'checked' : '');
1281
+				$out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
1282 1282
 			}
1283 1283
 		}
1284 1284
 		elseif ($type == 'chkbxlst')
@@ -1293,24 +1293,24 @@  discard block
 block discarded – undo
1293 1293
 			if (is_array($param['options'])) {
1294 1294
 				$param_list = array_keys($param['options']);
1295 1295
 				$InfoFieldList = explode(":", $param_list[0]);
1296
-				$parentName='';
1297
-				$parentField='';
1296
+				$parentName = '';
1297
+				$parentField = '';
1298 1298
 				// 0 : tableName
1299 1299
 				// 1 : label field name
1300 1300
 				// 2 : key fields name (if differ of rowid)
1301 1301
 				// 3 : key field parent (for dependent lists)
1302 1302
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
1303
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
1303
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
1304 1304
 
1305
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
1306
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
1307
-					$keyList .= ', ' . $parentField;
1305
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
1306
+					list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
1307
+					$keyList .= ', '.$parentField;
1308 1308
 				}
1309
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
1309
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
1310 1310
 					if (strpos($InfoFieldList[4], 'extra.') !== false) {
1311
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
1311
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
1312 1312
 					} else {
1313
-						$keyList = $InfoFieldList[2] . ' as rowid';
1313
+						$keyList = $InfoFieldList[2].' as rowid';
1314 1314
 					}
1315 1315
 				}
1316 1316
 
@@ -1321,59 +1321,59 @@  discard block
 block discarded – undo
1321 1321
 				}
1322 1322
 
1323 1323
 				$sqlwhere = '';
1324
-				$sql = 'SELECT ' . $keyList;
1325
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1326
-				if (! empty($InfoFieldList[4])) {
1324
+				$sql = 'SELECT '.$keyList;
1325
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
1326
+				if (!empty($InfoFieldList[4])) {
1327 1327
 
1328 1328
 					// can use SELECT request
1329
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
1330
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
1329
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
1330
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
1331 1331
 					}
1332 1332
 
1333 1333
 					// current object id can be use into filter
1334
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
1335
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
1336
-					} else if (preg_match("#^.*list.php$#",$_SERVER["DOCUMENT_URI"])) {
1334
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
1335
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
1336
+					} else if (preg_match("#^.*list.php$#", $_SERVER["DOCUMENT_URI"])) {
1337 1337
 						// Pattern for word=$ID$
1338 1338
 						$word = '\b[a-zA-Z0-9-\.-_]+\b=\$ID\$';
1339 1339
 						
1340 1340
 						// Removing space arount =, ( and )
1341
-						$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1341
+						$InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
1342 1342
 						
1343 1343
 						$nbPreg = 1;
1344 1344
 						// While we have parenthesis
1345
-						while ($nbPreg!=0) {
1345
+						while ($nbPreg != 0) {
1346 1346
 							// Init des compteurs
1347 1347
 							$nbPregRepl = $nbPregSel = 0;
1348 1348
 							// On retire toutes les parenthèses sans = avant
1349
-							$InfoFieldList[4]=preg_replace( '#([^=])(\([^)^(]*(' . $word .   ')[^)^(]*\))#','$1 $3 ',$InfoFieldList[4],-1,$nbPregRepl);
1349
+							$InfoFieldList[4] = preg_replace('#([^=])(\([^)^(]*('.$word.')[^)^(]*\))#', '$1 $3 ', $InfoFieldList[4], -1, $nbPregRepl);
1350 1350
 							// On retire les espaces autour des = et parenthèses
1351
-							$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1351
+							$InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
1352 1352
 							// On retire toutes les parenthèses avec = avant
1353
-							$InfoFieldList[4]=preg_replace(  '#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*(' . $word .   ')[^)^(]*\)#','$1 ',$InfoFieldList[4], -1, $nbPregSel);
1353
+							$InfoFieldList[4] = preg_replace('#\b[a-zA-Z0-9-\.-_]+\b=\([^)^(]*('.$word.')[^)^(]*\)#', '$1 ', $InfoFieldList[4], -1, $nbPregSel);
1354 1354
 							// On retire les espaces autour des = et parenthèses
1355
-							$InfoFieldList[4]=preg_replace('# *(=|\(|\)) *#','$1', $InfoFieldList[4]);
1355
+							$InfoFieldList[4] = preg_replace('# *(=|\(|\)) *#', '$1', $InfoFieldList[4]);
1356 1356
 							
1357 1357
 							// Calcul du compteur général pour la boucle
1358 1358
 							$nbPreg = $nbPregRepl + $nbPregSel;
1359 1359
 						}
1360 1360
 						
1361 1361
 						// Si l'on a un AND ou un OR, avant ou après
1362
-						preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1363
-						while(!empty($matchCondition[0])) {
1362
+						preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition);
1363
+						while (!empty($matchCondition[0])) {
1364 1364
 							// If the two sides differ but are not empty
1365
-							if (! empty($matchCondition[1]) && ! empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3] ) {
1365
+							if (!empty($matchCondition[1]) && !empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3]) {
1366 1366
 								// Nobody sain would do that without parentheses
1367
-								$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1367
+								$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
1368 1368
 							}
1369 1369
 							else {
1370
-								if (! empty($matchCondition[1])) {
1371
-									$boolCond =(( $matchCondition[1] == "AND" )?' AND 1 ':' OR 0 ');
1372
-									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond.$matchCondition[3],$InfoFieldList[4]);
1370
+								if (!empty($matchCondition[1])) {
1371
+									$boolCond = (($matchCondition[1] == "AND") ? ' AND 1 ' : ' OR 0 ');
1372
+									$InfoFieldList[4] = str_replace($matchCondition[0], $boolCond.$matchCondition[3], $InfoFieldList[4]);
1373 1373
 								}
1374
-								else if (! empty($matchCondition[3])) {
1375
-									$boolCond =(( $matchCondition[3] == "AND" )?' 1 AND ':' 0 OR');
1376
-									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond,$InfoFieldList[4]);
1374
+								else if (!empty($matchCondition[3])) {
1375
+									$boolCond = (($matchCondition[3] == "AND") ? ' 1 AND ' : ' 0 OR');
1376
+									$InfoFieldList[4] = str_replace($matchCondition[0], $boolCond, $InfoFieldList[4]);
1377 1377
 								}
1378 1378
 								else {
1379 1379
 									$InfoFieldList[4] = 1;
@@ -1381,41 +1381,41 @@  discard block
 block discarded – undo
1381 1381
 							}
1382 1382
 							
1383 1383
 							// Si l'on a un AND ou un OR, avant ou après
1384
-							preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1384
+							preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#', $InfoFieldList[4], $matchCondition);
1385 1385
 						}
1386 1386
 					}
1387 1387
 					else {
1388
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1388
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
1389 1389
 					}
1390 1390
 
1391 1391
 					// We have to join on extrafield table
1392 1392
 					if (strpos($InfoFieldList[4], 'extra') !== false) {
1393
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
1394
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
1393
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
1394
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
1395 1395
 					} else {
1396
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
1396
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
1397 1397
 					}
1398 1398
 				} else {
1399 1399
 					$sqlwhere .= ' WHERE 1=1';
1400 1400
 				}
1401 1401
 				// Some tables may have field, some other not. For the moment we disable it.
1402
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
1402
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
1403 1403
 				{
1404
-					$sqlwhere .= ' AND entity = ' . $conf->entity;
1404
+					$sqlwhere .= ' AND entity = '.$conf->entity;
1405 1405
 				}
1406 1406
 				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
1407 1407
 				// print $sql;
1408 1408
 
1409 1409
 				$sql .= $sqlwhere;
1410
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
1410
+				dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
1411 1411
 				$resql = $this->db->query($sql);
1412 1412
 				if ($resql) {
1413 1413
 					$num = $this->db->num_rows($resql);
1414 1414
 					$i = 0;
1415 1415
 
1416
-					$data=array();
1416
+					$data = array();
1417 1417
 
1418
-					while ( $i < $num ) {
1418
+					while ($i < $num) {
1419 1419
 						$labeltoshow = '';
1420 1420
 						$obj = $this->db->fetch_object($resql);
1421 1421
 
@@ -1424,8 +1424,8 @@  discard block
 block discarded – undo
1424 1424
 						$fields_label = explode('|', $InfoFieldList[1]);
1425 1425
 						if (is_array($fields_label)) {
1426 1426
 							$notrans = true;
1427
-							foreach ( $fields_label as $field_toshow ) {
1428
-								$labeltoshow .= $obj->$field_toshow . ' ';
1427
+							foreach ($fields_label as $field_toshow) {
1428
+								$labeltoshow .= $obj->$field_toshow.' ';
1429 1429
 							}
1430 1430
 						} else {
1431 1431
 							$labeltoshow = $obj->{$InfoFieldList[1]};
@@ -1433,18 +1433,18 @@  discard block
 block discarded – undo
1433 1433
 						$labeltoshow = dol_trunc($labeltoshow, 45);
1434 1434
 
1435 1435
 						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1436
-							foreach ( $fields_label as $field_toshow ) {
1436
+							foreach ($fields_label as $field_toshow) {
1437 1437
 								$translabel = $langs->trans($obj->$field_toshow);
1438 1438
 								if ($translabel != $obj->$field_toshow) {
1439
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
1439
+									$labeltoshow = dol_trunc($translabel, 18).' ';
1440 1440
 								} else {
1441
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
1441
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
1442 1442
 								}
1443 1443
 							}
1444 1444
 
1445
-							$data[$obj->rowid]=$labeltoshow;
1445
+							$data[$obj->rowid] = $labeltoshow;
1446 1446
 						} else {
1447
-							if (! $notrans) {
1447
+							if (!$notrans) {
1448 1448
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1449 1449
 								if ($translabel != $obj->{$InfoFieldList[1]}) {
1450 1450
 									$labeltoshow = dol_trunc($translabel, 18);
@@ -1456,40 +1456,40 @@  discard block
 block discarded – undo
1456 1456
 								$labeltoshow = '(not defined)';
1457 1457
 
1458 1458
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1459
-									$data[$obj->rowid]=$labeltoshow;
1459
+									$data[$obj->rowid] = $labeltoshow;
1460 1460
 								}
1461 1461
 
1462
-								if (! empty($InfoFieldList[3]) && $parentField) {
1463
-									$parent = $parentName . ':' . $obj->{$parentField};
1462
+								if (!empty($InfoFieldList[3]) && $parentField) {
1463
+									$parent = $parentName.':'.$obj->{$parentField};
1464 1464
 								}
1465 1465
 
1466
-								$data[$obj->rowid]=$labeltoshow;
1466
+								$data[$obj->rowid] = $labeltoshow;
1467 1467
 						}
1468 1468
 
1469
-						$i ++;
1469
+						$i++;
1470 1470
 					}
1471 1471
 					$this->db->free($resql);
1472 1472
 
1473
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
1473
+					$out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
1474 1474
 				} else {
1475
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
1475
+					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
1476 1476
 				}
1477 1477
 			}
1478 1478
 		}
1479 1479
 		elseif ($type == 'link')
1480 1480
 		{
1481
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1482
-			$showempty=(($required && $default != '')?0:1);
1483
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
1481
+			$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
1482
+			$showempty = (($required && $default != '') ? 0 : 1);
1483
+			$out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
1484 1484
 		}
1485 1485
 		elseif ($type == 'password')
1486 1486
 		{
1487 1487
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
1488
-			$out='<input style="display:none" type="text" name="fakeusernameremembered">';	// Hidden field to reduce impact of evil Google Chrome autopopulate bug.
1489
-			$out.='<input autocomplete="new-password" type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
1488
+			$out = '<input style="display:none" type="text" name="fakeusernameremembered">'; // Hidden field to reduce impact of evil Google Chrome autopopulate bug.
1489
+			$out .= '<input autocomplete="new-password" type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
1490 1490
 		}
1491 1491
 		if (!empty($hidden)) {
1492
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
1492
+			$out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
1493 1493
 		}
1494 1494
 		/* Add comments
1495 1495
 		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
@@ -1508,44 +1508,44 @@  discard block
 block discarded – undo
1508 1508
 	 * @param	string	$extrafieldsobjectkey	If defined (for example $object->table_element), use the new method to get extrafields data
1509 1509
 	 * @return	string							Formated value
1510 1510
 	 */
1511
-	function showOutputField($key, $value, $moreparam='', $extrafieldsobjectkey='')
1511
+	function showOutputField($key, $value, $moreparam = '', $extrafieldsobjectkey = '')
1512 1512
 	{
1513
-		global $conf,$langs;
1514
-
1515
-		if (! empty($extrafieldsobjectkey))
1516
-		{
1517
-			$label=$this->attributes[$extrafieldsobjectkey]['label'][$key];
1518
-			$type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1519
-			$size=$this->attributes[$extrafieldsobjectkey]['size'][$key];
1520
-			$default=$this->attributes[$extrafieldsobjectkey]['default'][$key];
1521
-			$computed=$this->attributes[$extrafieldsobjectkey]['computed'][$key];
1522
-			$unique=$this->attributes[$extrafieldsobjectkey]['unique'][$key];
1523
-			$required=$this->attributes[$extrafieldsobjectkey]['required'][$key];
1524
-			$param=$this->attributes[$extrafieldsobjectkey]['param'][$key];
1525
-			$perms=dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
1526
-			$langfile=$this->attributes[$extrafieldsobjectkey]['langfile'][$key];
1527
-			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
1528
-			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
1529
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1513
+		global $conf, $langs;
1514
+
1515
+		if (!empty($extrafieldsobjectkey))
1516
+		{
1517
+			$label = $this->attributes[$extrafieldsobjectkey]['label'][$key];
1518
+			$type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
1519
+			$size = $this->attributes[$extrafieldsobjectkey]['size'][$key];
1520
+			$default = $this->attributes[$extrafieldsobjectkey]['default'][$key];
1521
+			$computed = $this->attributes[$extrafieldsobjectkey]['computed'][$key];
1522
+			$unique = $this->attributes[$extrafieldsobjectkey]['unique'][$key];
1523
+			$required = $this->attributes[$extrafieldsobjectkey]['required'][$key];
1524
+			$param = $this->attributes[$extrafieldsobjectkey]['param'][$key];
1525
+			$perms = dol_eval($this->attributes[$extrafieldsobjectkey]['perms'][$key], 1);
1526
+			$langfile = $this->attributes[$extrafieldsobjectkey]['langfile'][$key];
1527
+			$list = dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
1528
+			$help = $this->attributes[$extrafieldsobjectkey]['help'][$key];
1529
+			$hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1530 1530
 		}
1531 1531
 		else	// Old usage
1532 1532
 		{
1533
-			$label=$this->attribute_label[$key];
1534
-			$type=$this->attribute_type[$key];
1535
-			$size=$this->attribute_size[$key];
1536
-			$default=$this->attribute_default[$key];
1537
-			$computed=$this->attribute_computed[$key];
1538
-			$unique=$this->attribute_unique[$key];
1539
-			$required=$this->attribute_required[$key];
1540
-			$param=$this->attribute_param[$key];
1541
-			$perms=dol_eval($this->attribute_perms[$key], 1);
1542
-			$langfile=$this->attribute_langfile[$key];
1543
-			$list=dol_eval($this->attribute_list[$key], 1);
1544
-			$help='';	// Not supported with old syntax
1545
-			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1533
+			$label = $this->attribute_label[$key];
1534
+			$type = $this->attribute_type[$key];
1535
+			$size = $this->attribute_size[$key];
1536
+			$default = $this->attribute_default[$key];
1537
+			$computed = $this->attribute_computed[$key];
1538
+			$unique = $this->attribute_unique[$key];
1539
+			$required = $this->attribute_required[$key];
1540
+			$param = $this->attribute_param[$key];
1541
+			$perms = dol_eval($this->attribute_perms[$key], 1);
1542
+			$langfile = $this->attribute_langfile[$key];
1543
+			$list = dol_eval($this->attribute_list[$key], 1);
1544
+			$help = ''; // Not supported with old syntax
1545
+			$hidden = (empty($list) ? 1 : 0); // If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1546 1546
 		}
1547 1547
 
1548
-		if ($hidden) return '';		// This is a protection. If field is hidden, we should just not call this method.
1548
+		if ($hidden) return ''; // This is a protection. If field is hidden, we should just not call this method.
1549 1549
 
1550 1550
 		// If field is a computed field, value must become result of compute
1551 1551
 		if ($computed)
@@ -1555,88 +1555,88 @@  discard block
 block discarded – undo
1555 1555
 		    $value = dol_eval($computed, 1, 0);
1556 1556
 		}
1557 1557
 
1558
-		$showsize=0;
1558
+		$showsize = 0;
1559 1559
 		if ($type == 'date')
1560 1560
 		{
1561
-			$showsize=10;
1562
-			$value=dol_print_date($value, 'day');
1561
+			$showsize = 10;
1562
+			$value = dol_print_date($value, 'day');
1563 1563
 		}
1564 1564
 		elseif ($type == 'datetime')
1565 1565
 		{
1566
-			$showsize=19;
1567
-			$value=dol_print_date($value, 'dayhour');
1566
+			$showsize = 19;
1567
+			$value = dol_print_date($value, 'dayhour');
1568 1568
 		}
1569 1569
 		elseif ($type == 'int')
1570 1570
 		{
1571
-			$showsize=10;
1571
+			$showsize = 10;
1572 1572
 		}
1573 1573
 		elseif ($type == 'double')
1574 1574
 		{
1575 1575
 			if (!empty($value)) {
1576
-				$value=price($value);
1576
+				$value = price($value);
1577 1577
 			}
1578 1578
 		}
1579 1579
 		elseif ($type == 'boolean')
1580 1580
 		{
1581
-			$checked='';
1581
+			$checked = '';
1582 1582
 			if (!empty($value)) {
1583
-				$checked=' checked ';
1583
+				$checked = ' checked ';
1584 1584
 			}
1585
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
1585
+			$value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
1586 1586
 		}
1587 1587
 		elseif ($type == 'mail')
1588 1588
 		{
1589
-			$value=dol_print_email($value, 0, 0, 0, 64, 1, 1);
1589
+			$value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
1590 1590
 		}
1591 1591
 		elseif ($type == 'url')
1592 1592
 		{
1593
-			$value=dol_print_url($value,'_blank',32,1);
1593
+			$value = dol_print_url($value, '_blank', 32, 1);
1594 1594
 		}
1595 1595
 		elseif ($type == 'phone')
1596 1596
 		{
1597
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
1597
+			$value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
1598 1598
 		}
1599 1599
 		elseif ($type == 'price')
1600 1600
 		{
1601
-			$value=price($value, 0, $langs, 0, 0, -1, $conf->currency);
1601
+			$value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
1602 1602
 		}
1603 1603
 		elseif ($type == 'select')
1604 1604
 		{
1605
-			if ($langfile && $param['options'][$value]) $value=$langs->trans($param['options'][$value]);
1606
-			else $value=$param['options'][$value];
1605
+			if ($langfile && $param['options'][$value]) $value = $langs->trans($param['options'][$value]);
1606
+			else $value = $param['options'][$value];
1607 1607
 		}
1608 1608
 		elseif ($type == 'sellist')
1609 1609
 		{
1610
-			$param_list=array_keys($param['options']);
1610
+			$param_list = array_keys($param['options']);
1611 1611
 			$InfoFieldList = explode(":", $param_list[0]);
1612 1612
 
1613
-			$selectkey="rowid";
1614
-			$keyList='rowid';
1613
+			$selectkey = "rowid";
1614
+			$keyList = 'rowid';
1615 1615
 
1616
-			if (count($InfoFieldList)>=3)
1616
+			if (count($InfoFieldList) >= 3)
1617 1617
 			{
1618 1618
 				$selectkey = $InfoFieldList[2];
1619
-				$keyList=$InfoFieldList[2].' as rowid';
1619
+				$keyList = $InfoFieldList[2].' as rowid';
1620 1620
 			}
1621 1621
 
1622
-			$fields_label = explode('|',$InfoFieldList[1]);
1623
-			if(is_array($fields_label)) {
1624
-				$keyList .=', ';
1622
+			$fields_label = explode('|', $InfoFieldList[1]);
1623
+			if (is_array($fields_label)) {
1624
+				$keyList .= ', ';
1625 1625
 				$keyList .= implode(', ', $fields_label);
1626 1626
 			}
1627 1627
 
1628 1628
 			$sql = 'SELECT '.$keyList;
1629
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
1630
-			if (strpos($InfoFieldList[4], 'extra')!==false)
1629
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
1630
+			if (strpos($InfoFieldList[4], 'extra') !== false)
1631 1631
 			{
1632
-				$sql.= ' as main';
1632
+				$sql .= ' as main';
1633 1633
 			}
1634
-			if ($selectkey=='rowid' && empty($value)) {
1635
-				$sql.= " WHERE ".$selectkey."=0";
1636
-			} elseif ($selectkey=='rowid') {
1637
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
1638
-			}else {
1639
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1634
+			if ($selectkey == 'rowid' && empty($value)) {
1635
+				$sql .= " WHERE ".$selectkey."=0";
1636
+			} elseif ($selectkey == 'rowid') {
1637
+				$sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
1638
+			} else {
1639
+				$sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1640 1640
 			}
1641 1641
 
1642 1642
 			//$sql.= ' AND entity = '.$conf->entity;
@@ -1645,38 +1645,38 @@  discard block
 block discarded – undo
1645 1645
 			$resql = $this->db->query($sql);
1646 1646
 			if ($resql)
1647 1647
 			{
1648
-				$value='';	// value was used, so now we reste it to use it to build final output
1648
+				$value = ''; // value was used, so now we reste it to use it to build final output
1649 1649
 
1650 1650
 				$obj = $this->db->fetch_object($resql);
1651 1651
 
1652 1652
 				// Several field into label (eq table:code|libelle:rowid)
1653
-				$fields_label = explode('|',$InfoFieldList[1]);
1653
+				$fields_label = explode('|', $InfoFieldList[1]);
1654 1654
 
1655
-				if(is_array($fields_label) && count($fields_label)>1)
1655
+				if (is_array($fields_label) && count($fields_label) > 1)
1656 1656
 				{
1657 1657
 					foreach ($fields_label as $field_toshow)
1658 1658
 					{
1659
-						$translabel='';
1659
+						$translabel = '';
1660 1660
 						if (!empty($obj->$field_toshow)) {
1661
-							$translabel=$langs->trans($obj->$field_toshow);
1661
+							$translabel = $langs->trans($obj->$field_toshow);
1662 1662
 						}
1663
-						if ($translabel!=$field_toshow) {
1664
-							$value.=dol_trunc($translabel,18).' ';
1665
-						}else {
1666
-							$value.=$obj->$field_toshow.' ';
1663
+						if ($translabel != $field_toshow) {
1664
+							$value .= dol_trunc($translabel, 18).' ';
1665
+						} else {
1666
+							$value .= $obj->$field_toshow.' ';
1667 1667
 						}
1668 1668
 					}
1669 1669
 				}
1670 1670
 				else
1671 1671
 				{
1672
-					$translabel='';
1672
+					$translabel = '';
1673 1673
 					if (!empty($obj->{$InfoFieldList[1]})) {
1674
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
1674
+						$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1675 1675
 					}
1676
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
1677
-						$value=dol_trunc($translabel,18);
1678
-					}else {
1679
-						$value=$obj->{$InfoFieldList[1]};
1676
+					if ($translabel != $obj->{$InfoFieldList[1]}) {
1677
+						$value = dol_trunc($translabel, 18);
1678
+					} else {
1679
+						$value = $obj->{$InfoFieldList[1]};
1680 1680
 					}
1681 1681
 				}
1682 1682
 			}
@@ -1684,20 +1684,20 @@  discard block
 block discarded – undo
1684 1684
 		}
1685 1685
 		elseif ($type == 'radio')
1686 1686
 		{
1687
-			$value=$param['options'][$value];
1687
+			$value = $param['options'][$value];
1688 1688
 		}
1689 1689
 		elseif ($type == 'checkbox')
1690 1690
 		{
1691
-			$value_arr=explode(',',$value);
1692
-			$value='';
1693
-			$toprint=array();
1691
+			$value_arr = explode(',', $value);
1692
+			$value = '';
1693
+			$toprint = array();
1694 1694
 			if (is_array($value_arr))
1695 1695
 			{
1696 1696
 				foreach ($value_arr as $keyval=>$valueval) {
1697
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
1697
+					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
1698 1698
 				}
1699 1699
 			}
1700
-			$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1700
+			$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1701 1701
 		}
1702 1702
 		elseif ($type == 'chkbxlst')
1703 1703
 		{
@@ -1711,7 +1711,7 @@  discard block
 block discarded – undo
1711 1711
 
1712 1712
 			if (count($InfoFieldList) >= 3) {
1713 1713
 				$selectkey = $InfoFieldList[2];
1714
-				$keyList = $InfoFieldList[2] . ' as rowid';
1714
+				$keyList = $InfoFieldList[2].' as rowid';
1715 1715
 			}
1716 1716
 
1717 1717
 			$fields_label = explode('|', $InfoFieldList[1]);
@@ -1720,74 +1720,74 @@  discard block
 block discarded – undo
1720 1720
 				$keyList .= implode(', ', $fields_label);
1721 1721
 			}
1722 1722
 
1723
-			$sql = 'SELECT ' . $keyList;
1724
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
1723
+			$sql = 'SELECT '.$keyList;
1724
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
1725 1725
 			if (strpos($InfoFieldList[4], 'extra') !== false) {
1726 1726
 				$sql .= ' as main';
1727 1727
 			}
1728 1728
 			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1729 1729
 			// $sql.= ' AND entity = '.$conf->entity;
1730 1730
 
1731
-			dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
1731
+			dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
1732 1732
 			$resql = $this->db->query($sql);
1733 1733
 			if ($resql) {
1734 1734
 				$value = ''; // value was used, so now we reste it to use it to build final output
1735
-				$toprint=array();
1736
-				while ( $obj = $this->db->fetch_object($resql) ) {
1735
+				$toprint = array();
1736
+				while ($obj = $this->db->fetch_object($resql)) {
1737 1737
 
1738 1738
 					// Several field into label (eq table:code|libelle:rowid)
1739 1739
 					$fields_label = explode('|', $InfoFieldList[1]);
1740 1740
 					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1741 1741
 						if (is_array($fields_label) && count($fields_label) > 1) {
1742
-							foreach ( $fields_label as $field_toshow ) {
1742
+							foreach ($fields_label as $field_toshow) {
1743 1743
 								$translabel = '';
1744
-								if (! empty($obj->$field_toshow)) {
1744
+								if (!empty($obj->$field_toshow)) {
1745 1745
 									$translabel = $langs->trans($obj->$field_toshow);
1746 1746
 								}
1747 1747
 								if ($translabel != $field_toshow) {
1748
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1748
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1749 1749
 								} else {
1750
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
1750
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
1751 1751
 								}
1752 1752
 							}
1753 1753
 						} else {
1754 1754
 							$translabel = '';
1755
-							if (! empty($obj->{$InfoFieldList[1]})) {
1755
+							if (!empty($obj->{$InfoFieldList[1]})) {
1756 1756
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
1757 1757
 							}
1758 1758
 							if ($translabel != $obj->{$InfoFieldList[1]}) {
1759
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1759
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
1760 1760
 							} else {
1761
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
1761
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
1762 1762
 							}
1763 1763
 						}
1764 1764
 					}
1765 1765
 				}
1766
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1766
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1767 1767
 			} else {
1768
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
1768
+				dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
1769 1769
 			}
1770 1770
 		}
1771 1771
 		elseif ($type == 'link')
1772 1772
 		{
1773
-			$out='';
1773
+			$out = '';
1774 1774
 
1775 1775
 			// Only if something to display (perf)
1776 1776
 			if ($value)		// If we have -1 here, pb is into sert, not into ouptu
1777 1777
 			{
1778
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1778
+				$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
1779 1779
 
1780 1780
 				$InfoFieldList = explode(":", $param_list[0]);
1781
-				$classname=$InfoFieldList[0];
1782
-				$classpath=$InfoFieldList[1];
1783
-				if (! empty($classpath))
1781
+				$classname = $InfoFieldList[0];
1782
+				$classpath = $InfoFieldList[1];
1783
+				if (!empty($classpath))
1784 1784
 				{
1785 1785
 					dol_include_once($InfoFieldList[1]);
1786 1786
 					if ($classname && class_exists($classname))
1787 1787
 					{
1788 1788
 						$object = new $classname($this->db);
1789 1789
 						$object->fetch($value);
1790
-						$value=$object->getNomUrl(3);
1790
+						$value = $object->getNomUrl(3);
1791 1791
 					}
1792 1792
 				}
1793 1793
 				else
@@ -1799,24 +1799,24 @@  discard block
 block discarded – undo
1799 1799
 		}
1800 1800
 		elseif ($type == 'text')
1801 1801
 		{
1802
-			$value=dol_htmlentitiesbr($value);
1802
+			$value = dol_htmlentitiesbr($value);
1803 1803
 		}
1804 1804
 		elseif ($type == 'html')
1805 1805
 		{
1806
-			$value=dol_htmlentitiesbr($value);
1806
+			$value = dol_htmlentitiesbr($value);
1807 1807
 		}
1808 1808
 		elseif ($type == 'password')
1809 1809
 		{
1810
-			$value=dol_trunc(preg_replace('/./i','*',$value), 8, 'right', 'UTF-8', 1);
1810
+			$value = dol_trunc(preg_replace('/./i', '*', $value), 8, 'right', 'UTF-8', 1);
1811 1811
 		}
1812 1812
 		else
1813 1813
 		{
1814
-			$showsize=round($size);
1815
-			if ($showsize > 48) $showsize=48;
1814
+			$showsize = round($size);
1815
+			if ($showsize > 48) $showsize = 48;
1816 1816
 		}
1817 1817
 
1818 1818
 		//print $type.'-'.$size;
1819
-		$out=$value;
1819
+		$out = $value;
1820 1820
 
1821 1821
 		return $out;
1822 1822
 	}
@@ -1828,46 +1828,46 @@  discard block
 block discarded – undo
1828 1828
 	 * @param	string	$extrafieldsobjectkey	If defined, use the new method to get extrafields data
1829 1829
 	 * @return	string							Formated value
1830 1830
 	 */
1831
-	function getAlignFlag($key, $extrafieldsobjectkey='')
1831
+	function getAlignFlag($key, $extrafieldsobjectkey = '')
1832 1832
 	{
1833
-		global $conf,$langs;
1833
+		global $conf, $langs;
1834 1834
 
1835
-		if (! empty($extrafieldsobjectkey)) $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1836
-		else $type=$this->attribute_type[$key];
1835
+		if (!empty($extrafieldsobjectkey)) $type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
1836
+		else $type = $this->attribute_type[$key];
1837 1837
 
1838
-		$align='';
1838
+		$align = '';
1839 1839
 
1840 1840
         if ($type == 'date')
1841 1841
 		{
1842
-			$align="center";
1842
+			$align = "center";
1843 1843
 		}
1844 1844
 		elseif ($type == 'datetime')
1845 1845
 		{
1846
-			$align="center";
1846
+			$align = "center";
1847 1847
 		}
1848 1848
 		elseif ($type == 'int')
1849 1849
 		{
1850
-			$align="right";
1850
+			$align = "right";
1851 1851
 		}
1852 1852
 		elseif ($type == 'double')
1853 1853
 		{
1854
-			$align="right";
1854
+			$align = "right";
1855 1855
 		}
1856 1856
 		elseif ($type == 'boolean')
1857 1857
 		{
1858
-			$align="center";
1858
+			$align = "center";
1859 1859
 		}
1860 1860
 		elseif ($type == 'radio')
1861 1861
 		{
1862
-			$align="center";
1862
+			$align = "center";
1863 1863
 		}
1864 1864
 		elseif ($type == 'checkbox')
1865 1865
 		{
1866
-			$align="center";
1866
+			$align = "center";
1867 1867
 		}
1868 1868
 		elseif ($type == 'price')
1869 1869
 		{
1870
-			$align="right";
1870
+			$align = "right";
1871 1871
 		}
1872 1872
 
1873 1873
 		return $align;
@@ -1885,8 +1885,8 @@  discard block
 block discarded – undo
1885 1885
 		global $langs;
1886 1886
 
1887 1887
 		$out = '<tr class="trextrafieldseparator trextrafieldseparator'.$key.'"><td colspan="2"><strong>';
1888
-		$out.= $langs->trans($this->attributes[$object->table_element]['label'][$key]);
1889
-		$out.= '</strong></td></tr>';
1888
+		$out .= $langs->trans($this->attributes[$object->table_element]['label'][$key]);
1889
+		$out .= '</strong></td></tr>';
1890 1890
 		return $out;
1891 1891
 	}
1892 1892
 
@@ -1898,20 +1898,20 @@  discard block
 block discarded – undo
1898 1898
 	 * @param	string	$onlykey		Only following key is filled. When we make update of only one extrafield ($action = 'update_extras'), calling page must must set this to avoid to have other extrafields being reset.
1899 1899
 	 * @return	int						1 if array_options set, 0 if no value, -1 if error (field required missing for example)
1900 1900
 	 */
1901
-	function setOptionalsFromPost($extralabels, &$object, $onlykey='')
1901
+	function setOptionalsFromPost($extralabels, &$object, $onlykey = '')
1902 1902
 	{
1903 1903
 		global $_POST, $langs;
1904
-		$nofillrequired='';// For error when required field left blank
1904
+		$nofillrequired = ''; // For error when required field left blank
1905 1905
 		$error_field_required = array();
1906 1906
 
1907
-		if (is_array($this->attributes[$object->table_element]['label'])) $extralabels=$this->attributes[$object->table_element]['label'];
1907
+		if (is_array($this->attributes[$object->table_element]['label'])) $extralabels = $this->attributes[$object->table_element]['label'];
1908 1908
 
1909 1909
 		if (is_array($extralabels))
1910 1910
 		{
1911 1911
 			// Get extra fields
1912 1912
 			foreach ($extralabels as $key => $value)
1913 1913
 			{
1914
-				if (! empty($onlykey) && $key != $onlykey) continue;
1914
+				if (!empty($onlykey) && $key != $onlykey) continue;
1915 1915
 
1916 1916
 				$key_type = $this->attributes[$object->table_element]['type'][$key];
1917 1917
 				if ($key_type == 'separate') continue;
@@ -1932,7 +1932,7 @@  discard block
 block discarded – undo
1932 1932
 				if ($this->attributes[$object->table_element]['required'][$key])	// Value is required
1933 1933
 				{
1934 1934
 					// Check if empty without using GETPOST, value can be alpha, int, array, etc...
1935
-					if ((! is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $_POST["options_".$key] != '0')
1935
+					if ((!is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $_POST["options_".$key] != '0')
1936 1936
 						|| (is_array($_POST["options_".$key]) && empty($_POST["options_".$key])))
1937 1937
 					{
1938 1938
 						//print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
@@ -1941,43 +1941,43 @@  discard block
 block discarded – undo
1941 1941
 					}
1942 1942
 				}
1943 1943
 
1944
-				if (in_array($key_type,array('date')))
1944
+				if (in_array($key_type, array('date')))
1945 1945
 				{
1946 1946
 					// Clean parameters
1947 1947
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1948
-					$value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1948
+					$value_key = dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1949 1949
 				}
1950
-				elseif (in_array($key_type,array('datetime')))
1950
+				elseif (in_array($key_type, array('datetime')))
1951 1951
 				{
1952 1952
 					// Clean parameters
1953 1953
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1954
-					$value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1954
+					$value_key = dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1955 1955
 				}
1956
-				else if (in_array($key_type,array('checkbox','chkbxlst')))
1956
+				else if (in_array($key_type, array('checkbox', 'chkbxlst')))
1957 1957
 				{
1958
-					$value_arr=GETPOST("options_".$key, 'array'); // check if an array
1958
+					$value_arr = GETPOST("options_".$key, 'array'); // check if an array
1959 1959
 					if (!empty($value_arr)) {
1960
-						$value_key=implode($value_arr,',');
1961
-					}else {
1962
-						$value_key='';
1960
+						$value_key = implode($value_arr, ',');
1961
+					} else {
1962
+						$value_key = '';
1963 1963
 					}
1964 1964
 				}
1965
-				else if (in_array($key_type,array('price','double')))
1965
+				else if (in_array($key_type, array('price', 'double')))
1966 1966
 				{
1967
-					$value_arr=GETPOST("options_".$key, 'alpha');
1968
-					$value_key=price2num($value_arr);
1967
+					$value_arr = GETPOST("options_".$key, 'alpha');
1968
+					$value_key = price2num($value_arr);
1969 1969
 				}
1970 1970
 				else
1971 1971
 				{
1972
-					$value_key=GETPOST("options_".$key);
1972
+					$value_key = GETPOST("options_".$key);
1973 1973
 				}
1974 1974
 
1975
-				$object->array_options["options_".$key]=$value_key;
1975
+				$object->array_options["options_".$key] = $value_key;
1976 1976
 			}
1977 1977
 
1978 1978
 			if ($nofillrequired) {
1979 1979
 				$langs->load('errors');
1980
-				setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ',$error_field_required), null, 'errors');
1980
+				setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ', $error_field_required), null, 'errors');
1981 1981
 				return -1;
1982 1982
 			}
1983 1983
 			else {
@@ -1997,7 +1997,7 @@  discard block
 block discarded – undo
1997 1997
 	 * @param  string			$keysuffix      		Suffix string to add into name and id of field (can be used to avoid duplicate names)
1998 1998
 	 * @return array|int								array_options set or 0 if no value
1999 1999
 	 */
2000
-	function getOptionalsFromPost($extrafieldsobjectkey, $keyprefix='', $keysuffix='')
2000
+	function getOptionalsFromPost($extrafieldsobjectkey, $keyprefix = '', $keysuffix = '')
2001 2001
 	{
2002 2002
 		global $_POST;
2003 2003
 
@@ -2023,29 +2023,29 @@  discard block
 block discarded – undo
2023 2023
 					$key_type = $this->attributes[$extrafieldsobjectkey]['type'][$key];
2024 2024
 				}
2025 2025
 
2026
-				if (in_array($key_type,array('date','datetime')))
2026
+				if (in_array($key_type, array('date', 'datetime')))
2027 2027
 				{
2028 2028
 					// Clean parameters
2029
-					$value_key=dol_mktime($_POST[$keysuffix."options_".$key.$keyprefix."hour"], $_POST[$keysuffix."options_".$key.$keyprefix."min"], 0, $_POST[$keysuffix."options_".$key.$keyprefix."month"], $_POST[$keysuffix."options_".$key.$keyprefix."day"], $_POST[$keysuffix."options_".$key.$keyprefix."year"]);
2029
+					$value_key = dol_mktime($_POST[$keysuffix."options_".$key.$keyprefix."hour"], $_POST[$keysuffix."options_".$key.$keyprefix."min"], 0, $_POST[$keysuffix."options_".$key.$keyprefix."month"], $_POST[$keysuffix."options_".$key.$keyprefix."day"], $_POST[$keysuffix."options_".$key.$keyprefix."year"]);
2030 2030
 				}
2031
-				else if (in_array($key_type,array('checkbox', 'chkbxlst')))
2031
+				else if (in_array($key_type, array('checkbox', 'chkbxlst')))
2032 2032
 				{
2033
-					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2033
+					$value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
2034 2034
 					// Make sure we get an array even if there's only one checkbox
2035
-					$value_arr=(array) $value_arr;
2036
-					$value_key=implode(',', $value_arr);
2035
+					$value_arr = (array) $value_arr;
2036
+					$value_key = implode(',', $value_arr);
2037 2037
 				}
2038
-				else if (in_array($key_type,array('price','double')))
2038
+				else if (in_array($key_type, array('price', 'double')))
2039 2039
 				{
2040
-					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2041
-					$value_key=price2num($value_arr);
2040
+					$value_arr = GETPOST($keysuffix."options_".$key.$keyprefix);
2041
+					$value_key = price2num($value_arr);
2042 2042
 				}
2043 2043
 				else
2044 2044
 				{
2045
-					$value_key=GETPOST($keysuffix."options_".$key.$keyprefix);
2045
+					$value_key = GETPOST($keysuffix."options_".$key.$keyprefix);
2046 2046
 				}
2047 2047
 
2048
-				$array_options[$keysuffix."options_".$key]=$value_key;	// No keyprefix here. keyprefix is used only for read.
2048
+				$array_options[$keysuffix."options_".$key] = $value_key; // No keyprefix here. keyprefix is used only for read.
2049 2049
 			}
2050 2050
 
2051 2051
 			return $array_options;
Please login to merge, or discard this patch.
Braces   +287 added lines, -258 removed lines patch added patch discarded remove patch
@@ -173,11 +173,19 @@  discard block
 block discarded – undo
173 173
 	 */
174 174
 	function addExtraField($attrname, $label, $type, $pos, $size, $elementtype, $unique=0, $required=0, $default_value='', $param='', $alwayseditable=0, $perms='', $list='-1', $help='', $computed='', $entity='', $langfile='', $enabled='1')
175 175
 	{
176
-		if (empty($attrname)) return -1;
177
-		if (empty($label)) return -1;
176
+		if (empty($attrname)) {
177
+		    return -1;
178
+		}
179
+		if (empty($label)) {
180
+		    return -1;
181
+		}
178 182
 
179
-		if ($elementtype == 'thirdparty') $elementtype='societe';
180
-		if ($elementtype == 'contact') $elementtype='socpeople';
183
+		if ($elementtype == 'thirdparty') {
184
+		    $elementtype='societe';
185
+		}
186
+		if ($elementtype == 'contact') {
187
+		    $elementtype='socpeople';
188
+		}
181 189
 
182 190
 		// Create field into database except for separator type which is not stored in database
183 191
 		if ($type != 'separate')
@@ -195,10 +203,10 @@  discard block
 block discarded – undo
195 203
 				$this->error='';
196 204
 				$this->errno=0;
197 205
 				return 1;
206
+			} else {
207
+			    return -2;
198 208
 			}
199
-			else return -2;
200
-		}
201
-		else
209
+		} else
202 210
 		{
203 211
 			return -1;
204 212
 		}
@@ -223,11 +231,17 @@  discard block
 block discarded – undo
223 231
 	 */
224 232
 	private function create($attrname, $type='varchar', $length=255, $elementtype='member', $unique=0, $required=0, $default_value='',$param='', $perms='', $list='0', $computed='')
225 233
 	{
226
-		if ($elementtype == 'thirdparty') $elementtype='societe';
227
-		if ($elementtype == 'contact') $elementtype='socpeople';
234
+		if ($elementtype == 'thirdparty') {
235
+		    $elementtype='societe';
236
+		}
237
+		if ($elementtype == 'contact') {
238
+		    $elementtype='socpeople';
239
+		}
228 240
 
229 241
 		$table=$elementtype.'_extrafields';
230
-		if ($elementtype == 'categorie') $table='categories_extrafields';
242
+		if ($elementtype == 'categorie') {
243
+		    $table='categories_extrafields';
244
+		}
231 245
 
232 246
 		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9_]*$/",$attrname) && ! is_numeric($attrname))
233 247
 		{
@@ -261,7 +275,9 @@  discard block
 block discarded – undo
261 275
 			} else {
262 276
 				$typedb=$type;
263 277
 				$lengthdb=$length;
264
-				if ($type == 'varchar' && empty($lengthdb)) $lengthdb='255';
278
+				if ($type == 'varchar' && empty($lengthdb)) {
279
+				    $lengthdb='255';
280
+				}
265 281
 			}
266 282
 			$field_desc = array(
267 283
 				'type'=>$typedb,
@@ -279,15 +295,13 @@  discard block
 block discarded – undo
279 295
 					$resql=$this->db->query($sql,1,'dml');
280 296
 				}
281 297
 				return 1;
282
-			}
283
-			else
298
+			} else
284 299
 			{
285 300
 				$this->error=$this->db->lasterror();
286 301
 				$this->errno=$this->db->lasterrno();
287 302
 				return -1;
288 303
 			}
289
-		}
290
-		else
304
+		} else
291 305
 		{
292 306
 			return 0;
293 307
 		}
@@ -322,27 +336,39 @@  discard block
 block discarded – undo
322 336
         // phpcs:enable
323 337
 		global $conf,$user;
324 338
 
325
-		if ($elementtype == 'thirdparty') $elementtype='societe';
326
-		if ($elementtype == 'contact') $elementtype='socpeople';
339
+		if ($elementtype == 'thirdparty') {
340
+		    $elementtype='societe';
341
+		}
342
+		if ($elementtype == 'contact') {
343
+		    $elementtype='socpeople';
344
+		}
327 345
 
328 346
 		// Clean parameters
329
-		if (empty($pos)) $pos=0;
330
-		if (empty($list)) $list='0';
331
-		if (empty($required)) $required=0;
332
-		if (empty($unique)) $unique=0;
333
-		if (empty($alwayseditable)) $alwayseditable=0;
347
+		if (empty($pos)) {
348
+		    $pos=0;
349
+		}
350
+		if (empty($list)) {
351
+		    $list='0';
352
+		}
353
+		if (empty($required)) {
354
+		    $required=0;
355
+		}
356
+		if (empty($unique)) {
357
+		    $unique=0;
358
+		}
359
+		if (empty($alwayseditable)) {
360
+		    $alwayseditable=0;
361
+		}
334 362
 
335 363
 		if (! empty($attrname) && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname) && ! is_numeric($attrname))
336 364
 		{
337 365
 			if (is_array($param) && count($param) > 0)
338 366
 			{
339 367
 				$params = serialize($param);
340
-			}
341
-			elseif (strlen($param) > 0)
368
+			} elseif (strlen($param) > 0)
342 369
 			{
343 370
 				$params = trim($param);
344
-			}
345
-			else
371
+			} else
346 372
 			{
347 373
 				$params='';
348 374
 			}
@@ -397,8 +423,7 @@  discard block
 block discarded – undo
397 423
 			if ($this->db->query($sql))
398 424
 			{
399 425
 				return 1;
400
-			}
401
-			else
426
+			} else
402 427
 			{
403 428
 				$this->error=$this->db->lasterror();
404 429
 				$this->errno=$this->db->lasterrno();
@@ -416,11 +441,17 @@  discard block
 block discarded – undo
416 441
 	 */
417 442
 	function delete($attrname, $elementtype='member')
418 443
 	{
419
-		if ($elementtype == 'thirdparty') $elementtype='societe';
420
-		if ($elementtype == 'contact') $elementtype='socpeople';
444
+		if ($elementtype == 'thirdparty') {
445
+		    $elementtype='societe';
446
+		}
447
+		if ($elementtype == 'contact') {
448
+		    $elementtype='socpeople';
449
+		}
421 450
 
422 451
 		$table=$elementtype.'_extrafields';
423
-		if ($elementtype == 'categorie') $table='categories_extrafields';
452
+		if ($elementtype == 'categorie') {
453
+		    $table='categories_extrafields';
454
+		}
424 455
 
425 456
 		$error=0;
426 457
 
@@ -457,8 +488,7 @@  discard block
 block discarded – undo
457 488
 			}
458 489
 
459 490
 			return $result;
460
-		}
461
-		else
491
+		} else
462 492
 		{
463 493
 			return 0;
464 494
 		}
@@ -477,8 +507,12 @@  discard block
 block discarded – undo
477 507
         // phpcs:enable
478 508
 		global $conf;
479 509
 
480
-		if ($elementtype == 'thirdparty') $elementtype='societe';
481
-		if ($elementtype == 'contact') $elementtype='socpeople';
510
+		if ($elementtype == 'thirdparty') {
511
+		    $elementtype='societe';
512
+		}
513
+		if ($elementtype == 'contact') {
514
+		    $elementtype='socpeople';
515
+		}
482 516
 
483 517
 		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
484 518
 		{
@@ -492,14 +526,12 @@  discard block
 block discarded – undo
492 526
 			if ($resql)
493 527
 			{
494 528
 				return 1;
495
-			}
496
-			else
529
+			} else
497 530
 			{
498 531
 				print dol_print_error($this->db);
499 532
 				return -1;
500 533
 			}
501
-		}
502
-		else
534
+		} else
503 535
 		{
504 536
 			return 0;
505 537
 		}
@@ -531,11 +563,17 @@  discard block
 block discarded – undo
531 563
 	 */
532 564
 	function update($attrname, $label, $type, $length, $elementtype, $unique=0, $required=0, $pos=0, $param='', $alwayseditable=0, $perms='', $list='', $help='', $default='', $computed='', $entity='', $langfile='', $enabled='1', $totalizable=0)
533 565
 	{
534
-		if ($elementtype == 'thirdparty') $elementtype='societe';
535
-		if ($elementtype == 'contact') $elementtype='socpeople';
566
+		if ($elementtype == 'thirdparty') {
567
+		    $elementtype='societe';
568
+		}
569
+		if ($elementtype == 'contact') {
570
+		    $elementtype='socpeople';
571
+		}
536 572
 
537 573
         $table=$elementtype.'_extrafields';
538
-		if ($elementtype == 'categorie') $table='categories_extrafields';
574
+		if ($elementtype == 'categorie') {
575
+		    $table='categories_extrafields';
576
+		}
539 577
 
540 578
 		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
541 579
 		{
@@ -571,10 +609,12 @@  discard block
 block discarded – undo
571 609
 			}
572 610
 			$field_desc = array('type'=>$typedb, 'value'=>$lengthdb, 'null'=>($required?'NOT NULL':'NULL'), 'default'=>$default);
573 611
 
574
-			if ($type != 'separate') // No table update when separate type
612
+			if ($type != 'separate') {
613
+			    // No table update when separate type
575 614
 			{
576 615
 				$result=$this->db->DDLUpdateField(MAIN_DB_PREFIX.$table, $attrname, $field_desc);
577 616
 			}
617
+			}
578 618
 			if ($result > 0 || $type == 'separate')
579 619
 			{
580 620
 				if ($label)
@@ -587,28 +627,24 @@  discard block
 block discarded – undo
587 627
 					if ($unique)
588 628
 					{
589 629
 						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." ADD UNIQUE INDEX uk_".$table."_".$attrname." (".$attrname.")";
590
-					}
591
-					else
630
+					} else
592 631
 					{
593 632
 						$sql="ALTER TABLE ".MAIN_DB_PREFIX.$table." DROP INDEX uk_".$table."_".$attrname;
594 633
 					}
595 634
 					dol_syslog(get_class($this).'::update', LOG_DEBUG);
596 635
 					$resql=$this->db->query($sql,1,'dml');
597 636
 					return 1;
598
-				}
599
-				else
637
+				} else
600 638
 				{
601 639
 					$this->error=$this->db->lasterror();
602 640
 					return -1;
603 641
 				}
604
-			}
605
-			else
642
+			} else
606 643
 			{
607 644
 				$this->error=$this->db->lasterror();
608 645
 				return -1;
609 646
 			}
610
-		}
611
-		else
647
+		} else
612 648
 		{
613 649
 			return 0;
614 650
 		}
@@ -646,17 +682,31 @@  discard block
 block discarded – undo
646 682
 		dol_syslog(get_class($this)."::update_label ".$attrname.", ".$label.", ".$type.", ".$size.", ".$elementtype.", ".$unique.", ".$required.", ".$pos.", ".$alwayseditable.", ".$perms.", ".$list.", ".$default.", ".$computed.", ".$entity.", ".$langfile.", ".$enabled.", ".$totalizable);
647 683
 
648 684
 		// Clean parameters
649
-		if ($elementtype == 'thirdparty') $elementtype='societe';
650
-		if ($elementtype == 'contact') $elementtype='socpeople';
685
+		if ($elementtype == 'thirdparty') {
686
+		    $elementtype='societe';
687
+		}
688
+		if ($elementtype == 'contact') {
689
+		    $elementtype='socpeople';
690
+		}
651 691
 
652
-		if (empty($pos)) $pos=0;
653
-		if (empty($list)) $list='0';
692
+		if (empty($pos)) {
693
+		    $pos=0;
694
+		}
695
+		if (empty($list)) {
696
+		    $list='0';
697
+		}
654 698
         if (empty($totalizable)) {
655 699
             $totalizable = 0;
656 700
         }
657
-		if (empty($required)) $required=0;
658
-		if (empty($unique)) $unique=0;
659
-		if (empty($alwayseditable)) $alwayseditable=0;
701
+		if (empty($required)) {
702
+		    $required=0;
703
+		}
704
+		if (empty($unique)) {
705
+		    $unique=0;
706
+		}
707
+		if (empty($alwayseditable)) {
708
+		    $alwayseditable=0;
709
+		}
660 710
 
661 711
 		if (isset($attrname) && $attrname != '' && preg_match("/^\w[a-zA-Z0-9-_]*$/",$attrname))
662 712
 		{
@@ -665,12 +715,10 @@  discard block
 block discarded – undo
665 715
 			if (is_array($param) && count($param) > 0)
666 716
 			{
667 717
 				$params = serialize($param);
668
-			}
669
-			elseif (strlen($param) > 0)
718
+			} elseif (strlen($param) > 0)
670 719
 			{
671 720
 				$params = trim($param);
672
-			}
673
-			else
721
+			} else
674 722
 			{
675 723
 				$params='';
676 724
 			}
@@ -682,8 +730,7 @@  discard block
 block discarded – undo
682 730
 				$sql_del.= " WHERE name = '".$attrname."'";
683 731
 				$sql_del.= " AND entity IN (0, ".($entity===''?$conf->entity:$entity).")";
684 732
 				$sql_del.= " AND elementtype = '".$elementtype."'";
685
-			}
686
-			else
733
+			} else
687 734
 			{
688 735
 				// We want on all entities ($entities = '0'), we delete on all only (we keep setup specific to each entity)
689 736
 				$sql_del = "DELETE FROM ".MAIN_DB_PREFIX."extrafields";
@@ -747,15 +794,13 @@  discard block
 block discarded – undo
747 794
 			{
748 795
 				$this->db->commit();
749 796
 				return 1;
750
-			}
751
-			else
797
+			} else
752 798
 			{
753 799
 				$this->db->rollback();
754 800
 				print dol_print_error($this->db);
755 801
 				return -1;
756 802
 			}
757
-		}
758
-		else
803
+		} else
759 804
 		{
760 805
 			return 0;
761 806
 		}
@@ -775,16 +820,26 @@  discard block
 block discarded – undo
775 820
         // phpcs:enable
776 821
 		global $conf;
777 822
 
778
-		if (empty($elementtype)) return array();
823
+		if (empty($elementtype)) {
824
+		    return array();
825
+		}
779 826
 
780
-		if ($elementtype == 'thirdparty') $elementtype='societe';
781
-		if ($elementtype == 'contact') $elementtype='socpeople';
782
-		if ($elementtype == 'order_supplier') $elementtype='commande_fournisseur';
827
+		if ($elementtype == 'thirdparty') {
828
+		    $elementtype='societe';
829
+		}
830
+		if ($elementtype == 'contact') {
831
+		    $elementtype='socpeople';
832
+		}
833
+		if ($elementtype == 'order_supplier') {
834
+		    $elementtype='commande_fournisseur';
835
+		}
783 836
 
784 837
 		$array_name_label=array();
785 838
 
786 839
 		// To avoid conflicts with external modules. TODO Remove this.
787
-		if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return $array_name_label;
840
+		if (!$forceload && !empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
841
+		    return $array_name_label;
842
+		}
788 843
 
789 844
 		// Set array of label of entity
790 845
 		// TODO Remove completely loading of label. This should be done by presentation.
@@ -808,7 +863,10 @@  discard block
 block discarded – undo
808 863
 		$sql = "SELECT rowid,name,label,type,size,elementtype,fieldunique,fieldrequired,param,pos,alwayseditable,perms,langs,list,totalizable,fielddefault,fieldcomputed,entity,enabled,help";
809 864
 		$sql.= " FROM ".MAIN_DB_PREFIX."extrafields";
810 865
 		$sql.= " WHERE entity IN (0,".$conf->entity.")";
811
-		if ($elementtype) $sql.= " AND elementtype = '".$elementtype."'";	// Filed with object->table_element
866
+		if ($elementtype) {
867
+		    $sql.= " AND elementtype = '".$elementtype."'";
868
+		}
869
+		// Filed with object->table_element
812 870
 		$sql.= " ORDER BY pos";
813 871
 
814 872
 		$resql=$this->db->query($sql);
@@ -867,9 +925,11 @@  discard block
 block discarded – undo
867 925
 					$this->attributes[$tab->elementtype]['loaded']=1;
868 926
 				}
869 927
 			}
870
-			if ($elementtype) $this->attributes[$elementtype]['loaded']=1;	// If nothing found, we also save tag 'loaded'
871
-		}
872
-		else
928
+			if ($elementtype) {
929
+			    $this->attributes[$elementtype]['loaded']=1;
930
+			}
931
+			// If nothing found, we also save tag 'loaded'
932
+		} else
873 933
 		{
874 934
 			$this->error=$this->db->lasterror();
875 935
 			dol_syslog(get_class($this)."::fetch_name_optionals_label ".$this->error, LOG_ERR);
@@ -923,8 +983,7 @@  discard block
 block discarded – undo
923 983
 			$totalizable=$this->attributes[$extrafieldsobjectkey]['totalizable'][$key];
924 984
 			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
925 985
 			$hidden=(empty($list) ? 1 : 0);		// If empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
926
-		}
927
-		else	// Old usage
986
+		} else	// Old usage
928 987
 		{
929 988
 			$label=$this->attribute_label[$key];
930 989
 			$type =$this->attribute_type[$key];
@@ -943,8 +1002,11 @@  discard block
 block discarded – undo
943 1002
 
944 1003
 		if ($computed)
945 1004
 		{
946
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
947
-			else return '';
1005
+			if (! preg_match('/^search_/', $keyprefix)) {
1006
+			    return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
1007
+			} else {
1008
+			    return '';
1009
+			}
948 1010
 		}
949 1011
 
950 1012
 		if (empty($morecss))
@@ -952,38 +1014,30 @@  discard block
 block discarded – undo
952 1014
 			if ($type == 'date')
953 1015
 			{
954 1016
 				$morecss = 'minwidth100imp';
955
-			}
956
-			elseif ($type == 'datetime')
1017
+			} elseif ($type == 'datetime')
957 1018
 			{
958 1019
 				$morecss = 'minwidth200imp';
959
-			}
960
-			elseif (in_array($type,array('int','integer','double','price')))
1020
+			} elseif (in_array($type,array('int','integer','double','price')))
961 1021
 			{
962 1022
 				$morecss = 'maxwidth75';
963
-			}
964
-			elseif ($type == 'password')
1023
+			} elseif ($type == 'password')
965 1024
 			{
966 1025
 				$morecss='maxwidth100';
967
-			}
968
-			elseif ($type == 'url')
1026
+			} elseif ($type == 'url')
969 1027
 			{
970 1028
 				$morecss='minwidth400';
971
-			}
972
-			elseif ($type == 'boolean')
1029
+			} elseif ($type == 'boolean')
973 1030
 			{
974 1031
 				$morecss='';
975
-			}
976
-			else
1032
+			} else
977 1033
 			{
978 1034
 				if (round($size) < 12)
979 1035
 				{
980 1036
 					$morecss = 'minwidth100';
981
-				}
982
-				else if (round($size) <= 48)
1037
+				} else if (round($size) <= 48)
983 1038
 				{
984 1039
 					$morecss = 'minwidth200';
985
-				}
986
-				else
1040
+				} else
987 1041
 				{
988 1042
 					$morecss = 'minwidth400';
989 1043
 				}
@@ -998,52 +1052,50 @@  discard block
 block discarded – undo
998 1052
 			$showtime = in_array($type,array('datetime')) ? 1 : 0;
999 1053
 
1000 1054
 			// Do not show current date when field not required (see selectDate() method)
1001
-			if (!$required && $value == '') $value = '-1';
1055
+			if (!$required && $value == '') {
1056
+			    $value = '-1';
1057
+			}
1002 1058
 
1003 1059
 			// TODO Must also support $moreparam
1004 1060
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
1005
-		}
1006
-		elseif (in_array($type,array('int','integer')))
1061
+		} elseif (in_array($type,array('int','integer')))
1007 1062
 		{
1008 1063
 			$tmp=explode(',',$size);
1009 1064
 			$newsize=$tmp[0];
1010 1065
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1011
-		}
1012
-		elseif (preg_match('/varchar/', $type))
1066
+		} elseif (preg_match('/varchar/', $type))
1013 1067
 		{
1014 1068
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
1015
-		}
1016
-		elseif (in_array($type, array('mail', 'phone', 'url')))
1069
+		} elseif (in_array($type, array('mail', 'phone', 'url')))
1017 1070
 		{
1018 1071
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1019
-		}
1020
-		elseif ($type == 'text')
1072
+		} elseif ($type == 'text')
1021 1073
 		{
1022
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1074
+			if (! preg_match('/search_/', $keyprefix)) {
1075
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
1023 1076
 			{
1024 1077
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1078
+			}
1025 1079
 				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
1026 1080
 				$out=$doleditor->Create(1);
1027
-			}
1028
-			else
1081
+			} else
1029 1082
 			{
1030 1083
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1031 1084
 			}
1032
-		}
1033
-		elseif ($type == 'html')
1085
+		} elseif ($type == 'html')
1034 1086
 		{
1035
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
1087
+			if (! preg_match('/search_/', $keyprefix)) {
1088
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
1036 1089
 			{
1037 1090
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1091
+			}
1038 1092
 				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
1039 1093
 				$out=$doleditor->Create(1);
1040
-			}
1041
-			else
1094
+			} else
1042 1095
 			{
1043 1096
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
1044 1097
 			}
1045
-		}
1046
-		elseif ($type == 'boolean')
1098
+		} elseif ($type == 'boolean')
1047 1099
 		{
1048 1100
 			$checked='';
1049 1101
 			if (!empty($value)) {
@@ -1052,22 +1104,19 @@  discard block
 block discarded – undo
1052 1104
 				$checked=' value="1" ';
1053 1105
 			}
1054 1106
 			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
1055
-		}
1056
-		elseif ($type == 'price')
1107
+		} elseif ($type == 'price')
1057 1108
 		{
1058 1109
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1059 1110
 				$value=price($value);
1060 1111
 			}
1061 1112
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
1062
-		}
1063
-		elseif ($type == 'double')
1113
+		} elseif ($type == 'double')
1064 1114
 		{
1065 1115
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
1066 1116
 				$value=price($value);
1067 1117
 			}
1068 1118
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
1069
-		}
1070
-		elseif ($type == 'select')
1119
+		} elseif ($type == 'select')
1071 1120
 		{
1072 1121
 			$out = '';
1073 1122
 			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
@@ -1080,19 +1129,23 @@  discard block
 block discarded – undo
1080 1129
 			$out.='<option value="0">&nbsp;</option>';
1081 1130
 			foreach ($param['options'] as $key => $val)
1082 1131
 			{
1083
-				if ((string) $key == '') continue;
1132
+				if ((string) $key == '') {
1133
+				    continue;
1134
+				}
1084 1135
 				list($val, $parent) = explode('|', $val);
1085 1136
 				$out.='<option value="'.$key.'"';
1086 1137
 				$out.= (((string) $value == (string) $key)?' selected':'');
1087 1138
 				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
1088 1139
 				$out.='>';
1089
-				if ($langfile && $val) $out.=$langs->trans($val);
1090
-				else $out.=$val;
1140
+				if ($langfile && $val) {
1141
+				    $out.=$langs->trans($val);
1142
+				} else {
1143
+				    $out.=$val;
1144
+				}
1091 1145
 				$out.='</option>';
1092 1146
 			}
1093 1147
 			$out.='</select>';
1094
-		}
1095
-		elseif ($type == 'sellist')
1148
+		} elseif ($type == 'sellist')
1096 1149
 		{
1097 1150
 			$out = '';
1098 1151
 			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
@@ -1163,13 +1216,11 @@  discard block
 block discarded – undo
1163 1216
 					{
1164 1217
 						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
1165 1218
 						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
1166
-					}
1167
-					else
1219
+					} else
1168 1220
 					{
1169 1221
 						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
1170 1222
 					}
1171
-				}
1172
-				else
1223
+				} else
1173 1224
 				{
1174 1225
 					$sqlwhere.= ' WHERE 1=1';
1175 1226
 				}
@@ -1205,8 +1256,7 @@  discard block
 block discarded – undo
1205 1256
 							{
1206 1257
 								$labeltoshow.= $obj->$field_toshow.' ';
1207 1258
 							}
1208
-						}
1209
-						else
1259
+						} else
1210 1260
 						{
1211 1261
 							$labeltoshow=$obj->{$InfoFieldList[1]};
1212 1262
 						}
@@ -1219,25 +1269,25 @@  discard block
 block discarded – undo
1219 1269
 								$translabel=$langs->trans($obj->$field_toshow);
1220 1270
 								if ($translabel!=$obj->$field_toshow) {
1221 1271
 									$labeltoshow=dol_trunc($translabel,18).' ';
1222
-								}else {
1272
+								} else {
1223 1273
 									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
1224 1274
 								}
1225 1275
 							}
1226 1276
 							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
1227
-						}
1228
-						else
1277
+						} else
1229 1278
 						{
1230 1279
 							if (! $notrans)
1231 1280
 							{
1232 1281
 								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
1233 1282
 								if ($translabel!=$obj->{$InfoFieldList[1]}) {
1234 1283
 									$labeltoshow=dol_trunc($translabel,18);
1235
-								}
1236
-								else {
1284
+								} else {
1237 1285
 									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
1238 1286
 								}
1239 1287
 							}
1240
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
1288
+							if (empty($labeltoshow)) {
1289
+							    $labeltoshow='(not defined)';
1290
+							}
1241 1291
 							if ($value==$obj->rowid)
1242 1292
 							{
1243 1293
 								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
@@ -1257,19 +1307,16 @@  discard block
 block discarded – undo
1257 1307
 						$i++;
1258 1308
 					}
1259 1309
 					$this->db->free($resql);
1260
-				}
1261
-				else {
1310
+				} else {
1262 1311
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
1263 1312
 				}
1264 1313
 			}
1265 1314
 			$out.='</select>';
1266
-		}
1267
-		elseif ($type == 'checkbox')
1315
+		} elseif ($type == 'checkbox')
1268 1316
 		{
1269 1317
 			$value_arr=explode(',',$value);
1270 1318
 			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
1271
-		}
1272
-		elseif ($type == 'radio')
1319
+		} elseif ($type == 'radio')
1273 1320
 		{
1274 1321
 			$out='';
1275 1322
 			foreach ($param['options'] as $keyopt => $val)
@@ -1280,13 +1327,11 @@  discard block
 block discarded – undo
1280 1327
 				$out.= ($value==$keyopt?'checked':'');
1281 1328
 				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
1282 1329
 			}
1283
-		}
1284
-		elseif ($type == 'chkbxlst')
1330
+		} elseif ($type == 'chkbxlst')
1285 1331
 		{
1286 1332
 			if (is_array($value)) {
1287 1333
 				$value_arr = $value;
1288
-			}
1289
-			else {
1334
+			} else {
1290 1335
 				$value_arr = explode(',', $value);
1291 1336
 			}
1292 1337
 
@@ -1365,17 +1410,14 @@  discard block
 block discarded – undo
1365 1410
 							if (! empty($matchCondition[1]) && ! empty($matchCondition[3]) && $matchCondition[1] != $matchCondition[3] ) {
1366 1411
 								// Nobody sain would do that without parentheses
1367 1412
 								$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1368
-							}
1369
-							else {
1413
+							} else {
1370 1414
 								if (! empty($matchCondition[1])) {
1371 1415
 									$boolCond =(( $matchCondition[1] == "AND" )?' AND 1 ':' OR 0 ');
1372 1416
 									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond.$matchCondition[3],$InfoFieldList[4]);
1373
-								}
1374
-								else if (! empty($matchCondition[3])) {
1417
+								} else if (! empty($matchCondition[3])) {
1375 1418
 									$boolCond =(( $matchCondition[3] == "AND" )?' 1 AND ':' 0 OR');
1376 1419
 									$InfoFieldList[4]=str_replace($matchCondition[0],$boolCond,$InfoFieldList[4]);
1377
-								}
1378
-								else {
1420
+								} else {
1379 1421
 									$InfoFieldList[4] = 1;
1380 1422
 								}
1381 1423
 							}
@@ -1383,8 +1425,7 @@  discard block
 block discarded – undo
1383 1425
 							// Si l'on a un AND ou un OR, avant ou après
1384 1426
 							preg_match('#(AND|OR|) *('.$word.') *(AND|OR|)#',$InfoFieldList[4],$matchCondition);
1385 1427
 						}
1386
-					}
1387
-					else {
1428
+					} else {
1388 1429
 						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
1389 1430
 					}
1390 1431
 
@@ -1452,8 +1493,9 @@  discard block
 block discarded – undo
1452 1493
 									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
1453 1494
 								}
1454 1495
 							}
1455
-							if (empty($labeltoshow))
1456
-								$labeltoshow = '(not defined)';
1496
+							if (empty($labeltoshow)) {
1497
+															$labeltoshow = '(not defined)';
1498
+							}
1457 1499
 
1458 1500
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
1459 1501
 									$data[$obj->rowid]=$labeltoshow;
@@ -1475,14 +1517,12 @@  discard block
 block discarded – undo
1475 1517
 					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
1476 1518
 				}
1477 1519
 			}
1478
-		}
1479
-		elseif ($type == 'link')
1520
+		} elseif ($type == 'link')
1480 1521
 		{
1481 1522
 			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1482 1523
 			$showempty=(($required && $default != '')?0:1);
1483 1524
 			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
1484
-		}
1485
-		elseif ($type == 'password')
1525
+		} elseif ($type == 'password')
1486 1526
 		{
1487 1527
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
1488 1528
 			$out='<input style="display:none" type="text" name="fakeusernameremembered">';	// Hidden field to reduce impact of evil Google Chrome autopopulate bug.
@@ -1527,8 +1567,7 @@  discard block
 block discarded – undo
1527 1567
 			$list=dol_eval($this->attributes[$extrafieldsobjectkey]['list'][$key], 1);
1528 1568
 			$help=$this->attributes[$extrafieldsobjectkey]['help'][$key];
1529 1569
 			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1530
-		}
1531
-		else	// Old usage
1570
+		} else	// Old usage
1532 1571
 		{
1533 1572
 			$label=$this->attribute_label[$key];
1534 1573
 			$type=$this->attribute_type[$key];
@@ -1545,7 +1584,10 @@  discard block
 block discarded – undo
1545 1584
 			$hidden=(empty($list) ? 1 : 0);		// If $list empty, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
1546 1585
 		}
1547 1586
 
1548
-		if ($hidden) return '';		// This is a protection. If field is hidden, we should just not call this method.
1587
+		if ($hidden) {
1588
+		    return '';
1589
+		}
1590
+		// This is a protection. If field is hidden, we should just not call this method.
1549 1591
 
1550 1592
 		// If field is a computed field, value must become result of compute
1551 1593
 		if ($computed)
@@ -1560,52 +1602,45 @@  discard block
 block discarded – undo
1560 1602
 		{
1561 1603
 			$showsize=10;
1562 1604
 			$value=dol_print_date($value, 'day');
1563
-		}
1564
-		elseif ($type == 'datetime')
1605
+		} elseif ($type == 'datetime')
1565 1606
 		{
1566 1607
 			$showsize=19;
1567 1608
 			$value=dol_print_date($value, 'dayhour');
1568
-		}
1569
-		elseif ($type == 'int')
1609
+		} elseif ($type == 'int')
1570 1610
 		{
1571 1611
 			$showsize=10;
1572
-		}
1573
-		elseif ($type == 'double')
1612
+		} elseif ($type == 'double')
1574 1613
 		{
1575 1614
 			if (!empty($value)) {
1576 1615
 				$value=price($value);
1577 1616
 			}
1578
-		}
1579
-		elseif ($type == 'boolean')
1617
+		} elseif ($type == 'boolean')
1580 1618
 		{
1581 1619
 			$checked='';
1582 1620
 			if (!empty($value)) {
1583 1621
 				$checked=' checked ';
1584 1622
 			}
1585 1623
 			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
1586
-		}
1587
-		elseif ($type == 'mail')
1624
+		} elseif ($type == 'mail')
1588 1625
 		{
1589 1626
 			$value=dol_print_email($value, 0, 0, 0, 64, 1, 1);
1590
-		}
1591
-		elseif ($type == 'url')
1627
+		} elseif ($type == 'url')
1592 1628
 		{
1593 1629
 			$value=dol_print_url($value,'_blank',32,1);
1594
-		}
1595
-		elseif ($type == 'phone')
1630
+		} elseif ($type == 'phone')
1596 1631
 		{
1597 1632
 			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
1598
-		}
1599
-		elseif ($type == 'price')
1633
+		} elseif ($type == 'price')
1600 1634
 		{
1601 1635
 			$value=price($value, 0, $langs, 0, 0, -1, $conf->currency);
1602
-		}
1603
-		elseif ($type == 'select')
1636
+		} elseif ($type == 'select')
1604 1637
 		{
1605
-			if ($langfile && $param['options'][$value]) $value=$langs->trans($param['options'][$value]);
1606
-			else $value=$param['options'][$value];
1607
-		}
1608
-		elseif ($type == 'sellist')
1638
+			if ($langfile && $param['options'][$value]) {
1639
+			    $value=$langs->trans($param['options'][$value]);
1640
+			} else {
1641
+			    $value=$param['options'][$value];
1642
+			}
1643
+		} elseif ($type == 'sellist')
1609 1644
 		{
1610 1645
 			$param_list=array_keys($param['options']);
1611 1646
 			$InfoFieldList = explode(":", $param_list[0]);
@@ -1635,7 +1670,7 @@  discard block
 block discarded – undo
1635 1670
 				$sql.= " WHERE ".$selectkey."=0";
1636 1671
 			} elseif ($selectkey=='rowid') {
1637 1672
 				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
1638
-			}else {
1673
+			} else {
1639 1674
 				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
1640 1675
 			}
1641 1676
 
@@ -1662,12 +1697,11 @@  discard block
 block discarded – undo
1662 1697
 						}
1663 1698
 						if ($translabel!=$field_toshow) {
1664 1699
 							$value.=dol_trunc($translabel,18).' ';
1665
-						}else {
1700
+						} else {
1666 1701
 							$value.=$obj->$field_toshow.' ';
1667 1702
 						}
1668 1703
 					}
1669
-				}
1670
-				else
1704
+				} else
1671 1705
 				{
1672 1706
 					$translabel='';
1673 1707
 					if (!empty($obj->{$InfoFieldList[1]})) {
@@ -1675,18 +1709,17 @@  discard block
 block discarded – undo
1675 1709
 					}
1676 1710
 					if ($translabel!=$obj->{$InfoFieldList[1]}) {
1677 1711
 						$value=dol_trunc($translabel,18);
1678
-					}else {
1712
+					} else {
1679 1713
 						$value=$obj->{$InfoFieldList[1]};
1680 1714
 					}
1681 1715
 				}
1716
+			} else {
1717
+			    dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
1682 1718
 			}
1683
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
1684
-		}
1685
-		elseif ($type == 'radio')
1719
+		} elseif ($type == 'radio')
1686 1720
 		{
1687 1721
 			$value=$param['options'][$value];
1688
-		}
1689
-		elseif ($type == 'checkbox')
1722
+		} elseif ($type == 'checkbox')
1690 1723
 		{
1691 1724
 			$value_arr=explode(',',$value);
1692 1725
 			$value='';
@@ -1698,8 +1731,7 @@  discard block
 block discarded – undo
1698 1731
 				}
1699 1732
 			}
1700 1733
 			$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
1701
-		}
1702
-		elseif ($type == 'chkbxlst')
1734
+		} elseif ($type == 'chkbxlst')
1703 1735
 		{
1704 1736
 			$value_arr = explode(',', $value);
1705 1737
 
@@ -1767,15 +1799,17 @@  discard block
 block discarded – undo
1767 1799
 			} else {
1768 1800
 				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
1769 1801
 			}
1770
-		}
1771
-		elseif ($type == 'link')
1802
+		} elseif ($type == 'link')
1772 1803
 		{
1773 1804
 			$out='';
1774 1805
 
1775 1806
 			// Only if something to display (perf)
1776
-			if ($value)		// If we have -1 here, pb is into sert, not into ouptu
1807
+			if ($value) {
1808
+			    // If we have -1 here, pb is into sert, not into ouptu
1777 1809
 			{
1778
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
1810
+				$param_list=array_keys($param['options']);
1811
+			}
1812
+			// $param_list='ObjectName:classPath'
1779 1813
 
1780 1814
 				$InfoFieldList = explode(":", $param_list[0]);
1781 1815
 				$classname=$InfoFieldList[0];
@@ -1789,30 +1823,27 @@  discard block
 block discarded – undo
1789 1823
 						$object->fetch($value);
1790 1824
 						$value=$object->getNomUrl(3);
1791 1825
 					}
1792
-				}
1793
-				else
1826
+				} else
1794 1827
 				{
1795 1828
 					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
1796 1829
 					return 'Error bad setup of extrafield';
1797 1830
 				}
1798 1831
 			}
1799
-		}
1800
-		elseif ($type == 'text')
1832
+		} elseif ($type == 'text')
1801 1833
 		{
1802 1834
 			$value=dol_htmlentitiesbr($value);
1803
-		}
1804
-		elseif ($type == 'html')
1835
+		} elseif ($type == 'html')
1805 1836
 		{
1806 1837
 			$value=dol_htmlentitiesbr($value);
1807
-		}
1808
-		elseif ($type == 'password')
1838
+		} elseif ($type == 'password')
1809 1839
 		{
1810 1840
 			$value=dol_trunc(preg_replace('/./i','*',$value), 8, 'right', 'UTF-8', 1);
1811
-		}
1812
-		else
1841
+		} else
1813 1842
 		{
1814 1843
 			$showsize=round($size);
1815
-			if ($showsize > 48) $showsize=48;
1844
+			if ($showsize > 48) {
1845
+			    $showsize=48;
1846
+			}
1816 1847
 		}
1817 1848
 
1818 1849
 		//print $type.'-'.$size;
@@ -1832,40 +1863,36 @@  discard block
 block discarded – undo
1832 1863
 	{
1833 1864
 		global $conf,$langs;
1834 1865
 
1835
-		if (! empty($extrafieldsobjectkey)) $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1836
-		else $type=$this->attribute_type[$key];
1866
+		if (! empty($extrafieldsobjectkey)) {
1867
+		    $type=$this->attributes[$extrafieldsobjectkey]['type'][$key];
1868
+		} else {
1869
+		    $type=$this->attribute_type[$key];
1870
+		}
1837 1871
 
1838 1872
 		$align='';
1839 1873
 
1840 1874
         if ($type == 'date')
1841 1875
 		{
1842 1876
 			$align="center";
1843
-		}
1844
-		elseif ($type == 'datetime')
1877
+		} elseif ($type == 'datetime')
1845 1878
 		{
1846 1879
 			$align="center";
1847
-		}
1848
-		elseif ($type == 'int')
1880
+		} elseif ($type == 'int')
1849 1881
 		{
1850 1882
 			$align="right";
1851
-		}
1852
-		elseif ($type == 'double')
1883
+		} elseif ($type == 'double')
1853 1884
 		{
1854 1885
 			$align="right";
1855
-		}
1856
-		elseif ($type == 'boolean')
1886
+		} elseif ($type == 'boolean')
1857 1887
 		{
1858 1888
 			$align="center";
1859
-		}
1860
-		elseif ($type == 'radio')
1889
+		} elseif ($type == 'radio')
1861 1890
 		{
1862 1891
 			$align="center";
1863
-		}
1864
-		elseif ($type == 'checkbox')
1892
+		} elseif ($type == 'checkbox')
1865 1893
 		{
1866 1894
 			$align="center";
1867
-		}
1868
-		elseif ($type == 'price')
1895
+		} elseif ($type == 'price')
1869 1896
 		{
1870 1897
 			$align="right";
1871 1898
 		}
@@ -1904,17 +1931,23 @@  discard block
 block discarded – undo
1904 1931
 		$nofillrequired='';// For error when required field left blank
1905 1932
 		$error_field_required = array();
1906 1933
 
1907
-		if (is_array($this->attributes[$object->table_element]['label'])) $extralabels=$this->attributes[$object->table_element]['label'];
1934
+		if (is_array($this->attributes[$object->table_element]['label'])) {
1935
+		    $extralabels=$this->attributes[$object->table_element]['label'];
1936
+		}
1908 1937
 
1909 1938
 		if (is_array($extralabels))
1910 1939
 		{
1911 1940
 			// Get extra fields
1912 1941
 			foreach ($extralabels as $key => $value)
1913 1942
 			{
1914
-				if (! empty($onlykey) && $key != $onlykey) continue;
1943
+				if (! empty($onlykey) && $key != $onlykey) {
1944
+				    continue;
1945
+				}
1915 1946
 
1916 1947
 				$key_type = $this->attributes[$object->table_element]['type'][$key];
1917
-				if ($key_type == 'separate') continue;
1948
+				if ($key_type == 'separate') {
1949
+				    continue;
1950
+				}
1918 1951
 
1919 1952
 				$enabled = 1;
1920 1953
 				if (isset($this->attributes[$object->table_element]['list'][$key]))
@@ -1926,10 +1959,15 @@  discard block
 block discarded – undo
1926 1959
 				{
1927 1960
 					$perms = dol_eval($this->attributes[$object->table_element]['perms'][$key], 1);
1928 1961
 				}
1929
-				if (empty($enabled)) continue;
1930
-				if (empty($perms)) continue;
1962
+				if (empty($enabled)) {
1963
+				    continue;
1964
+				}
1965
+				if (empty($perms)) {
1966
+				    continue;
1967
+				}
1931 1968
 
1932
-				if ($this->attributes[$object->table_element]['required'][$key])	// Value is required
1969
+				if ($this->attributes[$object->table_element]['required'][$key]) {
1970
+				    // Value is required
1933 1971
 				{
1934 1972
 					// Check if empty without using GETPOST, value can be alpha, int, array, etc...
1935 1973
 					if ((! is_array($_POST["options_".$key]) && empty($_POST["options_".$key]) && $_POST["options_".$key] != '0')
@@ -1937,6 +1975,7 @@  discard block
 block discarded – undo
1937 1975
 					{
1938 1976
 						//print 'ccc'.$value.'-'.$this->attributes[$object->table_element]['required'][$key];
1939 1977
 						$nofillrequired++;
1978
+				}
1940 1979
 						$error_field_required[] = $langs->transnoentitiesnoconv($value);
1941 1980
 					}
1942 1981
 				}
@@ -1946,28 +1985,24 @@  discard block
 block discarded – undo
1946 1985
 					// Clean parameters
1947 1986
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1948 1987
 					$value_key=dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1949
-				}
1950
-				elseif (in_array($key_type,array('datetime')))
1988
+				} elseif (in_array($key_type,array('datetime')))
1951 1989
 				{
1952 1990
 					// Clean parameters
1953 1991
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
1954 1992
 					$value_key=dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
1955
-				}
1956
-				else if (in_array($key_type,array('checkbox','chkbxlst')))
1993
+				} else if (in_array($key_type,array('checkbox','chkbxlst')))
1957 1994
 				{
1958 1995
 					$value_arr=GETPOST("options_".$key, 'array'); // check if an array
1959 1996
 					if (!empty($value_arr)) {
1960 1997
 						$value_key=implode($value_arr,',');
1961
-					}else {
1998
+					} else {
1962 1999
 						$value_key='';
1963 2000
 					}
1964
-				}
1965
-				else if (in_array($key_type,array('price','double')))
2001
+				} else if (in_array($key_type,array('price','double')))
1966 2002
 				{
1967 2003
 					$value_arr=GETPOST("options_".$key, 'alpha');
1968 2004
 					$value_key=price2num($value_arr);
1969
-				}
1970
-				else
2005
+				} else
1971 2006
 				{
1972 2007
 					$value_key=GETPOST("options_".$key);
1973 2008
 				}
@@ -1979,12 +2014,10 @@  discard block
 block discarded – undo
1979 2014
 				$langs->load('errors');
1980 2015
 				setEventMessages($langs->trans('ErrorFieldsRequired').' : '.implode(', ',$error_field_required), null, 'errors');
1981 2016
 				return -1;
1982
-			}
1983
-			else {
2017
+			} else {
1984 2018
 				return 1;
1985 2019
 			}
1986
-		}
1987
-		else {
2020
+		} else {
1988 2021
 			return 0;
1989 2022
 		}
1990 2023
 	}
@@ -2004,8 +2037,7 @@  discard block
 block discarded – undo
2004 2037
 		if (is_string($extrafieldsobjectkey) && is_array($this->attributes[$extrafieldsobjectkey]['label']))
2005 2038
 		{
2006 2039
 			$extralabels = $this->attributes[$extrafieldsobjectkey]['label'];
2007
-		}
2008
-		else
2040
+		} else
2009 2041
 		{
2010 2042
 			$extralabels = $extrafieldsobjectkey;
2011 2043
 		}
@@ -2027,20 +2059,17 @@  discard block
 block discarded – undo
2027 2059
 				{
2028 2060
 					// Clean parameters
2029 2061
 					$value_key=dol_mktime($_POST[$keysuffix."options_".$key.$keyprefix."hour"], $_POST[$keysuffix."options_".$key.$keyprefix."min"], 0, $_POST[$keysuffix."options_".$key.$keyprefix."month"], $_POST[$keysuffix."options_".$key.$keyprefix."day"], $_POST[$keysuffix."options_".$key.$keyprefix."year"]);
2030
-				}
2031
-				else if (in_array($key_type,array('checkbox', 'chkbxlst')))
2062
+				} else if (in_array($key_type,array('checkbox', 'chkbxlst')))
2032 2063
 				{
2033 2064
 					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2034 2065
 					// Make sure we get an array even if there's only one checkbox
2035 2066
 					$value_arr=(array) $value_arr;
2036 2067
 					$value_key=implode(',', $value_arr);
2037
-				}
2038
-				else if (in_array($key_type,array('price','double')))
2068
+				} else if (in_array($key_type,array('price','double')))
2039 2069
 				{
2040 2070
 					$value_arr=GETPOST($keysuffix."options_".$key.$keyprefix);
2041 2071
 					$value_key=price2num($value_arr);
2042
-				}
2043
-				else
2072
+				} else
2044 2073
 				{
2045 2074
 					$value_key=GETPOST($keysuffix."options_".$key.$keyprefix);
2046 2075
 				}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/events.class.php 3 patches
Indentation   +237 added lines, -237 removed lines patch added patch discarded remove patch
@@ -34,62 +34,62 @@  discard block
 block discarded – undo
34 34
  */
35 35
 class Events // extends CommonObject
36 36
 {
37
-	/**
38
-	 * @var string ID to identify managed object
39
-	 */
40
-	public $element='events';
37
+    /**
38
+     * @var string ID to identify managed object
39
+     */
40
+    public $element='events';
41 41
 
42
-	/**
43
-	 * @var string Name of table without prefix where object is stored
44
-	 */
45
-	public $table_element='events';
42
+    /**
43
+     * @var string Name of table without prefix where object is stored
44
+     */
45
+    public $table_element='events';
46 46
 
47
-	/**
48
-	 * @var int ID
49
-	 */
50
-	public $id;
47
+    /**
48
+     * @var int ID
49
+     */
50
+    public $id;
51 51
 
52 52
     /**
53 53
      * @var DoliDB Database handler.
54 54
      */
55 55
     public $db;
56 56
 
57
-	/**
58
-	 * @var string Error code (or message)
59
-	 */
60
-	public $error='';
61
-
62
-	public $tms;
63
-	public $type;
64
-
65
-	/**
66
-	 * @var int Entity
67
-	 */
68
-	public $entity;
69
-
70
-	public $dateevent;
71
-
72
-	/**
73
-	 * @var string description
74
-	 */
75
-	public $description;
76
-
77
-	// List of all Audit/Security events supported by triggers
78
-	public $eventstolog=array(
79
-		array('id'=>'USER_LOGIN',             'test'=>1),
80
-		array('id'=>'USER_LOGIN_FAILED',      'test'=>1),
81
-	    array('id'=>'USER_LOGOUT',            'test'=>1),
82
-		array('id'=>'USER_CREATE',            'test'=>1),
83
-		array('id'=>'USER_MODIFY',            'test'=>1),
84
-		array('id'=>'USER_NEW_PASSWORD',      'test'=>1),
85
-		array('id'=>'USER_ENABLEDISABLE',     'test'=>1),
86
-		array('id'=>'USER_DELETE',            'test'=>1),
87
-	/*    array('id'=>'USER_SETINGROUP',        'test'=>1), deprecated. Replace with USER_MODIFY
57
+    /**
58
+     * @var string Error code (or message)
59
+     */
60
+    public $error='';
61
+
62
+    public $tms;
63
+    public $type;
64
+
65
+    /**
66
+     * @var int Entity
67
+     */
68
+    public $entity;
69
+
70
+    public $dateevent;
71
+
72
+    /**
73
+     * @var string description
74
+     */
75
+    public $description;
76
+
77
+    // List of all Audit/Security events supported by triggers
78
+    public $eventstolog=array(
79
+        array('id'=>'USER_LOGIN',             'test'=>1),
80
+        array('id'=>'USER_LOGIN_FAILED',      'test'=>1),
81
+        array('id'=>'USER_LOGOUT',            'test'=>1),
82
+        array('id'=>'USER_CREATE',            'test'=>1),
83
+        array('id'=>'USER_MODIFY',            'test'=>1),
84
+        array('id'=>'USER_NEW_PASSWORD',      'test'=>1),
85
+        array('id'=>'USER_ENABLEDISABLE',     'test'=>1),
86
+        array('id'=>'USER_DELETE',            'test'=>1),
87
+    /*    array('id'=>'USER_SETINGROUP',        'test'=>1), deprecated. Replace with USER_MODIFY
88 88
 	    array('id'=>'USER_REMOVEFROMGROUP',   'test'=>1), deprecated. Replace with USER_MODIFY */
89
-		array('id'=>'GROUP_CREATE',           'test'=>1),
90
-		array('id'=>'GROUP_MODIFY',           'test'=>1),
91
-		array('id'=>'GROUP_DELETE',           'test'=>1),
92
-	/*	array('id'=>'ACTION_CREATE',          'test'=>$conf->societe->enabled),
89
+        array('id'=>'GROUP_CREATE',           'test'=>1),
90
+        array('id'=>'GROUP_MODIFY',           'test'=>1),
91
+        array('id'=>'GROUP_DELETE',           'test'=>1),
92
+    /*	array('id'=>'ACTION_CREATE',          'test'=>$conf->societe->enabled),
93 93
 		array('id'=>'COMPANY_CREATE',         'test'=>$conf->societe->enabled),
94 94
 		array('id'=>'CONTRACT_VALIDATE',      'test'=>$conf->contrat->enabled),
95 95
 		array('id'=>'PROPAL_VALIDATE',        'test'=>$conf->propal->enabled),
@@ -111,199 +111,199 @@  discard block
 block discarded – undo
111 111
 		array('id'=>'MEMBER_RESILIATE',       'test'=>$conf->adherent->enabled),
112 112
 		array('id'=>'MEMBER_DELETE',          'test'=>$conf->adherent->enabled),
113 113
 	*/
114
-	);
115
-
116
-
117
-	/**
118
-	 *	Constructor
119
-	 *
120
-	 *  @param		DoliDB		$db      Database handler
121
-	 */
122
-	function __construct($db)
123
-	{
124
-		$this->db = $db;
125
-	}
126
-
127
-
128
-	/**
129
-	 *   Create in database
130
-	 *
131
-	 *   @param      User	$user       User that create
132
-	 *   @return     int     		    <0 if KO, >0 if OK
133
-	 */
134
-	function create($user)
135
-	{
136
-		global $conf, $langs;
137
-
138
-		// Clean parameters
139
-		$this->description=trim($this->description);
140
-		if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
141
-
142
-		// Check parameters
143
-		if (empty($this->description)) { $this->error='ErrorBadValueForParameterCreateEventDesc'; return -1; }
144
-
145
-		// Insert request
146
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."events(";
147
-		$sql.= "type,";
148
-		$sql.= "entity,";
149
-		$sql.= "ip,";
150
-		$sql.= "user_agent,";
151
-		$sql.= "dateevent,";
152
-		$sql.= "fk_user,";
153
-		$sql.= "description";
154
-		$sql.= ") VALUES (";
155
-		$sql.= " '".$this->db->escape($this->type)."',";
156
-		$sql.= " ".$conf->entity.",";
157
-		$sql.= " '".$this->db->escape(getUserRemoteIP())."',";
158
-		$sql.= " ".($this->user_agent ? "'".$this->db->escape(dol_trunc($this->user_agent,250))."'" : 'NULL').",";
159
-		$sql.= " '".$this->db->idate($this->dateevent)."',";
160
-		$sql.= " ".($user->id?"'".$this->db->escape($user->id)."'":'NULL').",";
161
-		$sql.= " '".$this->db->escape(dol_trunc($this->description,250))."'";
162
-		$sql.= ")";
163
-
164
-		dol_syslog(get_class($this)."::create", LOG_DEBUG);
165
-		$resql=$this->db->query($sql);
166
-		if ($resql)
167
-		{
168
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."events");
169
-			return $this->id;
170
-		}
171
-		else
172
-		{
173
-			$this->error="Error ".$this->db->lasterror();
174
-			return -1;
175
-		}
176
-	}
177
-
178
-
179
-	/**
180
-	 * Update database
181
-	 *
182
-	 * @param	User    $user        	User that modify
183
-	 * @param   int		$notrigger	    0=no, 1=yes (no update trigger)
184
-	 * @return  int         			<0 if KO, >0 if OK
185
-	 */
186
-	function update($user=null, $notrigger=0)
187
-	{
188
-		global $conf, $langs;
189
-
190
-		// Clean parameters
191
-		$this->id=trim($this->id);
192
-		$this->type=trim($this->type);
193
-		$this->description=trim($this->description);
194
-
195
-		// Check parameters
196
-		// Put here code to add control on parameters values
197
-
198
-		// Update request
199
-		$sql = "UPDATE ".MAIN_DB_PREFIX."events SET";
200
-		$sql.= " type='".$this->db->escape($this->type)."',";
201
-		$sql.= " dateevent='".$this->db->idate($this->dateevent)."',";
202
-		$sql.= " description='".$this->db->escape($this->description)."'";
203
-		$sql.= " WHERE rowid=".$this->id;
204
-
205
-		dol_syslog(get_class($this)."::update", LOG_DEBUG);
206
-		$resql = $this->db->query($sql);
207
-		if (! $resql)
208
-		{
209
-			$this->error="Error ".$this->db->lasterror();
210
-			return -1;
211
-		}
212
-		return 1;
213
-	}
214
-
215
-
216
-	/**
217
-	 *  Load object in memory from database
218
-	 *
219
-	 *  @param	int		$id         Id object
220
-	 *  @param  User	$user       User that load
221
-	 *  @return int         		<0 if KO, >0 if OK
222
-	 */
223
-	function fetch($id, $user=null)
224
-	{
225
-		global $langs;
226
-
227
-		$sql = "SELECT";
228
-		$sql.= " t.rowid,";
229
-		$sql.= " t.tms,";
230
-		$sql.= " t.type,";
231
-		$sql.= " t.entity,";
232
-		$sql.= " t.dateevent,";
233
-		$sql.= " t.description,";
234
-		$sql.= " t.ip,";
235
-		$sql.= " t.user_agent";
236
-		$sql.= " FROM ".MAIN_DB_PREFIX."events as t";
237
-		$sql.= " WHERE t.rowid = ".$id;
238
-
239
-		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
240
-		$resql=$this->db->query($sql);
241
-		if ($resql)
242
-		{
243
-			if ($this->db->num_rows($resql))
244
-			{
245
-				$obj = $this->db->fetch_object($resql);
246
-
247
-				$this->id    = $obj->rowid;
248
-				$this->tms = $this->db->jdate($obj->tms);
249
-				$this->type = $obj->type;
250
-				$this->entity = $obj->entity;
251
-				$this->dateevent = $this->db->jdate($obj->dateevent);
252
-				$this->description = $obj->description;
253
-				$this->ip = $obj->ip;
254
-				$this->user_agent = $obj->user_agent;
255
-			}
256
-			$this->db->free($resql);
257
-
258
-			return 1;
259
-		}
260
-		else
261
-		{
262
-			$this->error="Error ".$this->db->lasterror();
263
-			return -1;
264
-		}
265
-	}
266
-
267
-
268
-	/**
269
-	 *  Delete object in database
270
-	 *
271
-	 *	@param	User	$user       User that delete
272
-	 *	@return	int					<0 if KO, >0 if OK
273
-	 */
274
-	function delete($user)
275
-	{
276
-		global $conf, $langs;
277
-
278
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."events";
279
-		$sql.= " WHERE rowid=".$this->id;
280
-
281
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
282
-		$resql = $this->db->query($sql);
283
-		if (! $resql)
284
-		{
285
-			$this->error="Error ".$this->db->lasterror();
286
-			return -1;
287
-		}
288
-
289
-		return 1;
290
-	}
291
-
292
-
293
-	/**
114
+    );
115
+
116
+
117
+    /**
118
+     *	Constructor
119
+     *
120
+     *  @param		DoliDB		$db      Database handler
121
+     */
122
+    function __construct($db)
123
+    {
124
+        $this->db = $db;
125
+    }
126
+
127
+
128
+    /**
129
+     *   Create in database
130
+     *
131
+     *   @param      User	$user       User that create
132
+     *   @return     int     		    <0 if KO, >0 if OK
133
+     */
134
+    function create($user)
135
+    {
136
+        global $conf, $langs;
137
+
138
+        // Clean parameters
139
+        $this->description=trim($this->description);
140
+        if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
141
+
142
+        // Check parameters
143
+        if (empty($this->description)) { $this->error='ErrorBadValueForParameterCreateEventDesc'; return -1; }
144
+
145
+        // Insert request
146
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."events(";
147
+        $sql.= "type,";
148
+        $sql.= "entity,";
149
+        $sql.= "ip,";
150
+        $sql.= "user_agent,";
151
+        $sql.= "dateevent,";
152
+        $sql.= "fk_user,";
153
+        $sql.= "description";
154
+        $sql.= ") VALUES (";
155
+        $sql.= " '".$this->db->escape($this->type)."',";
156
+        $sql.= " ".$conf->entity.",";
157
+        $sql.= " '".$this->db->escape(getUserRemoteIP())."',";
158
+        $sql.= " ".($this->user_agent ? "'".$this->db->escape(dol_trunc($this->user_agent,250))."'" : 'NULL').",";
159
+        $sql.= " '".$this->db->idate($this->dateevent)."',";
160
+        $sql.= " ".($user->id?"'".$this->db->escape($user->id)."'":'NULL').",";
161
+        $sql.= " '".$this->db->escape(dol_trunc($this->description,250))."'";
162
+        $sql.= ")";
163
+
164
+        dol_syslog(get_class($this)."::create", LOG_DEBUG);
165
+        $resql=$this->db->query($sql);
166
+        if ($resql)
167
+        {
168
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."events");
169
+            return $this->id;
170
+        }
171
+        else
172
+        {
173
+            $this->error="Error ".$this->db->lasterror();
174
+            return -1;
175
+        }
176
+    }
177
+
178
+
179
+    /**
180
+     * Update database
181
+     *
182
+     * @param	User    $user        	User that modify
183
+     * @param   int		$notrigger	    0=no, 1=yes (no update trigger)
184
+     * @return  int         			<0 if KO, >0 if OK
185
+     */
186
+    function update($user=null, $notrigger=0)
187
+    {
188
+        global $conf, $langs;
189
+
190
+        // Clean parameters
191
+        $this->id=trim($this->id);
192
+        $this->type=trim($this->type);
193
+        $this->description=trim($this->description);
194
+
195
+        // Check parameters
196
+        // Put here code to add control on parameters values
197
+
198
+        // Update request
199
+        $sql = "UPDATE ".MAIN_DB_PREFIX."events SET";
200
+        $sql.= " type='".$this->db->escape($this->type)."',";
201
+        $sql.= " dateevent='".$this->db->idate($this->dateevent)."',";
202
+        $sql.= " description='".$this->db->escape($this->description)."'";
203
+        $sql.= " WHERE rowid=".$this->id;
204
+
205
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
206
+        $resql = $this->db->query($sql);
207
+        if (! $resql)
208
+        {
209
+            $this->error="Error ".$this->db->lasterror();
210
+            return -1;
211
+        }
212
+        return 1;
213
+    }
214
+
215
+
216
+    /**
217
+     *  Load object in memory from database
218
+     *
219
+     *  @param	int		$id         Id object
220
+     *  @param  User	$user       User that load
221
+     *  @return int         		<0 if KO, >0 if OK
222
+     */
223
+    function fetch($id, $user=null)
224
+    {
225
+        global $langs;
226
+
227
+        $sql = "SELECT";
228
+        $sql.= " t.rowid,";
229
+        $sql.= " t.tms,";
230
+        $sql.= " t.type,";
231
+        $sql.= " t.entity,";
232
+        $sql.= " t.dateevent,";
233
+        $sql.= " t.description,";
234
+        $sql.= " t.ip,";
235
+        $sql.= " t.user_agent";
236
+        $sql.= " FROM ".MAIN_DB_PREFIX."events as t";
237
+        $sql.= " WHERE t.rowid = ".$id;
238
+
239
+        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
240
+        $resql=$this->db->query($sql);
241
+        if ($resql)
242
+        {
243
+            if ($this->db->num_rows($resql))
244
+            {
245
+                $obj = $this->db->fetch_object($resql);
246
+
247
+                $this->id    = $obj->rowid;
248
+                $this->tms = $this->db->jdate($obj->tms);
249
+                $this->type = $obj->type;
250
+                $this->entity = $obj->entity;
251
+                $this->dateevent = $this->db->jdate($obj->dateevent);
252
+                $this->description = $obj->description;
253
+                $this->ip = $obj->ip;
254
+                $this->user_agent = $obj->user_agent;
255
+            }
256
+            $this->db->free($resql);
257
+
258
+            return 1;
259
+        }
260
+        else
261
+        {
262
+            $this->error="Error ".$this->db->lasterror();
263
+            return -1;
264
+        }
265
+    }
266
+
267
+
268
+    /**
269
+     *  Delete object in database
270
+     *
271
+     *	@param	User	$user       User that delete
272
+     *	@return	int					<0 if KO, >0 if OK
273
+     */
274
+    function delete($user)
275
+    {
276
+        global $conf, $langs;
277
+
278
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."events";
279
+        $sql.= " WHERE rowid=".$this->id;
280
+
281
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
282
+        $resql = $this->db->query($sql);
283
+        if (! $resql)
284
+        {
285
+            $this->error="Error ".$this->db->lasterror();
286
+            return -1;
287
+        }
288
+
289
+        return 1;
290
+    }
291
+
292
+
293
+    /**
294 294
      *  Initialise an instance with random values.
295 295
      *  Used to build previews or test instances.
296 296
      *	id must be 0 if object instance is a specimen.
297 297
      *
298 298
      *  @return	void
299
-	 */
300
-	function initAsSpecimen()
301
-	{
302
-		$this->id=0;
303
-
304
-		$this->tms=time();
305
-		$this->type='';
306
-		$this->dateevent=time();
307
-		$this->description='This is a specimen event';
308
-	}
299
+     */
300
+    function initAsSpecimen()
301
+    {
302
+        $this->id=0;
303
+
304
+        $this->tms=time();
305
+        $this->type='';
306
+        $this->dateevent=time();
307
+        $this->description='This is a specimen event';
308
+    }
309 309
 }
Please login to merge, or discard this patch.
Spacing   +68 added lines, -68 removed lines patch added patch discarded remove patch
@@ -37,12 +37,12 @@  discard block
 block discarded – undo
37 37
 	/**
38 38
 	 * @var string ID to identify managed object
39 39
 	 */
40
-	public $element='events';
40
+	public $element = 'events';
41 41
 
42 42
 	/**
43 43
 	 * @var string Name of table without prefix where object is stored
44 44
 	 */
45
-	public $table_element='events';
45
+	public $table_element = 'events';
46 46
 
47 47
 	/**
48 48
 	 * @var int ID
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 	/**
58 58
 	 * @var string Error code (or message)
59 59
 	 */
60
-	public $error='';
60
+	public $error = '';
61 61
 
62 62
 	public $tms;
63 63
 	public $type;
@@ -75,20 +75,20 @@  discard block
 block discarded – undo
75 75
 	public $description;
76 76
 
77 77
 	// List of all Audit/Security events supported by triggers
78
-	public $eventstolog=array(
79
-		array('id'=>'USER_LOGIN',             'test'=>1),
80
-		array('id'=>'USER_LOGIN_FAILED',      'test'=>1),
81
-	    array('id'=>'USER_LOGOUT',            'test'=>1),
82
-		array('id'=>'USER_CREATE',            'test'=>1),
83
-		array('id'=>'USER_MODIFY',            'test'=>1),
84
-		array('id'=>'USER_NEW_PASSWORD',      'test'=>1),
85
-		array('id'=>'USER_ENABLEDISABLE',     'test'=>1),
86
-		array('id'=>'USER_DELETE',            'test'=>1),
78
+	public $eventstolog = array(
79
+		array('id'=>'USER_LOGIN', 'test'=>1),
80
+		array('id'=>'USER_LOGIN_FAILED', 'test'=>1),
81
+	    array('id'=>'USER_LOGOUT', 'test'=>1),
82
+		array('id'=>'USER_CREATE', 'test'=>1),
83
+		array('id'=>'USER_MODIFY', 'test'=>1),
84
+		array('id'=>'USER_NEW_PASSWORD', 'test'=>1),
85
+		array('id'=>'USER_ENABLEDISABLE', 'test'=>1),
86
+		array('id'=>'USER_DELETE', 'test'=>1),
87 87
 	/*    array('id'=>'USER_SETINGROUP',        'test'=>1), deprecated. Replace with USER_MODIFY
88 88
 	    array('id'=>'USER_REMOVEFROMGROUP',   'test'=>1), deprecated. Replace with USER_MODIFY */
89
-		array('id'=>'GROUP_CREATE',           'test'=>1),
90
-		array('id'=>'GROUP_MODIFY',           'test'=>1),
91
-		array('id'=>'GROUP_DELETE',           'test'=>1),
89
+		array('id'=>'GROUP_CREATE', 'test'=>1),
90
+		array('id'=>'GROUP_MODIFY', 'test'=>1),
91
+		array('id'=>'GROUP_DELETE', 'test'=>1),
92 92
 	/*	array('id'=>'ACTION_CREATE',          'test'=>$conf->societe->enabled),
93 93
 		array('id'=>'COMPANY_CREATE',         'test'=>$conf->societe->enabled),
94 94
 		array('id'=>'CONTRACT_VALIDATE',      'test'=>$conf->contrat->enabled),
@@ -136,33 +136,33 @@  discard block
 block discarded – undo
136 136
 		global $conf, $langs;
137 137
 
138 138
 		// Clean parameters
139
-		$this->description=trim($this->description);
140
-		if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
139
+		$this->description = trim($this->description);
140
+		if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent = $_SERVER['HTTP_USER_AGENT'];
141 141
 
142 142
 		// Check parameters
143
-		if (empty($this->description)) { $this->error='ErrorBadValueForParameterCreateEventDesc'; return -1; }
143
+		if (empty($this->description)) { $this->error = 'ErrorBadValueForParameterCreateEventDesc'; return -1; }
144 144
 
145 145
 		// Insert request
146 146
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."events(";
147
-		$sql.= "type,";
148
-		$sql.= "entity,";
149
-		$sql.= "ip,";
150
-		$sql.= "user_agent,";
151
-		$sql.= "dateevent,";
152
-		$sql.= "fk_user,";
153
-		$sql.= "description";
154
-		$sql.= ") VALUES (";
155
-		$sql.= " '".$this->db->escape($this->type)."',";
156
-		$sql.= " ".$conf->entity.",";
157
-		$sql.= " '".$this->db->escape(getUserRemoteIP())."',";
158
-		$sql.= " ".($this->user_agent ? "'".$this->db->escape(dol_trunc($this->user_agent,250))."'" : 'NULL').",";
159
-		$sql.= " '".$this->db->idate($this->dateevent)."',";
160
-		$sql.= " ".($user->id?"'".$this->db->escape($user->id)."'":'NULL').",";
161
-		$sql.= " '".$this->db->escape(dol_trunc($this->description,250))."'";
162
-		$sql.= ")";
147
+		$sql .= "type,";
148
+		$sql .= "entity,";
149
+		$sql .= "ip,";
150
+		$sql .= "user_agent,";
151
+		$sql .= "dateevent,";
152
+		$sql .= "fk_user,";
153
+		$sql .= "description";
154
+		$sql .= ") VALUES (";
155
+		$sql .= " '".$this->db->escape($this->type)."',";
156
+		$sql .= " ".$conf->entity.",";
157
+		$sql .= " '".$this->db->escape(getUserRemoteIP())."',";
158
+		$sql .= " ".($this->user_agent ? "'".$this->db->escape(dol_trunc($this->user_agent, 250))."'" : 'NULL').",";
159
+		$sql .= " '".$this->db->idate($this->dateevent)."',";
160
+		$sql .= " ".($user->id ? "'".$this->db->escape($user->id)."'" : 'NULL').",";
161
+		$sql .= " '".$this->db->escape(dol_trunc($this->description, 250))."'";
162
+		$sql .= ")";
163 163
 
164 164
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
165
-		$resql=$this->db->query($sql);
165
+		$resql = $this->db->query($sql);
166 166
 		if ($resql)
167 167
 		{
168 168
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."events");
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 		}
171 171
 		else
172 172
 		{
173
-			$this->error="Error ".$this->db->lasterror();
173
+			$this->error = "Error ".$this->db->lasterror();
174 174
 			return -1;
175 175
 		}
176 176
 	}
@@ -183,30 +183,30 @@  discard block
 block discarded – undo
183 183
 	 * @param   int		$notrigger	    0=no, 1=yes (no update trigger)
184 184
 	 * @return  int         			<0 if KO, >0 if OK
185 185
 	 */
186
-	function update($user=null, $notrigger=0)
186
+	function update($user = null, $notrigger = 0)
187 187
 	{
188 188
 		global $conf, $langs;
189 189
 
190 190
 		// Clean parameters
191
-		$this->id=trim($this->id);
192
-		$this->type=trim($this->type);
193
-		$this->description=trim($this->description);
191
+		$this->id = trim($this->id);
192
+		$this->type = trim($this->type);
193
+		$this->description = trim($this->description);
194 194
 
195 195
 		// Check parameters
196 196
 		// Put here code to add control on parameters values
197 197
 
198 198
 		// Update request
199 199
 		$sql = "UPDATE ".MAIN_DB_PREFIX."events SET";
200
-		$sql.= " type='".$this->db->escape($this->type)."',";
201
-		$sql.= " dateevent='".$this->db->idate($this->dateevent)."',";
202
-		$sql.= " description='".$this->db->escape($this->description)."'";
203
-		$sql.= " WHERE rowid=".$this->id;
200
+		$sql .= " type='".$this->db->escape($this->type)."',";
201
+		$sql .= " dateevent='".$this->db->idate($this->dateevent)."',";
202
+		$sql .= " description='".$this->db->escape($this->description)."'";
203
+		$sql .= " WHERE rowid=".$this->id;
204 204
 
205 205
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
206 206
 		$resql = $this->db->query($sql);
207
-		if (! $resql)
207
+		if (!$resql)
208 208
 		{
209
-			$this->error="Error ".$this->db->lasterror();
209
+			$this->error = "Error ".$this->db->lasterror();
210 210
 			return -1;
211 211
 		}
212 212
 		return 1;
@@ -220,31 +220,31 @@  discard block
 block discarded – undo
220 220
 	 *  @param  User	$user       User that load
221 221
 	 *  @return int         		<0 if KO, >0 if OK
222 222
 	 */
223
-	function fetch($id, $user=null)
223
+	function fetch($id, $user = null)
224 224
 	{
225 225
 		global $langs;
226 226
 
227 227
 		$sql = "SELECT";
228
-		$sql.= " t.rowid,";
229
-		$sql.= " t.tms,";
230
-		$sql.= " t.type,";
231
-		$sql.= " t.entity,";
232
-		$sql.= " t.dateevent,";
233
-		$sql.= " t.description,";
234
-		$sql.= " t.ip,";
235
-		$sql.= " t.user_agent";
236
-		$sql.= " FROM ".MAIN_DB_PREFIX."events as t";
237
-		$sql.= " WHERE t.rowid = ".$id;
228
+		$sql .= " t.rowid,";
229
+		$sql .= " t.tms,";
230
+		$sql .= " t.type,";
231
+		$sql .= " t.entity,";
232
+		$sql .= " t.dateevent,";
233
+		$sql .= " t.description,";
234
+		$sql .= " t.ip,";
235
+		$sql .= " t.user_agent";
236
+		$sql .= " FROM ".MAIN_DB_PREFIX."events as t";
237
+		$sql .= " WHERE t.rowid = ".$id;
238 238
 
239 239
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
240
-		$resql=$this->db->query($sql);
240
+		$resql = $this->db->query($sql);
241 241
 		if ($resql)
242 242
 		{
243 243
 			if ($this->db->num_rows($resql))
244 244
 			{
245 245
 				$obj = $this->db->fetch_object($resql);
246 246
 
247
-				$this->id    = $obj->rowid;
247
+				$this->id = $obj->rowid;
248 248
 				$this->tms = $this->db->jdate($obj->tms);
249 249
 				$this->type = $obj->type;
250 250
 				$this->entity = $obj->entity;
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 		}
260 260
 		else
261 261
 		{
262
-			$this->error="Error ".$this->db->lasterror();
262
+			$this->error = "Error ".$this->db->lasterror();
263 263
 			return -1;
264 264
 		}
265 265
 	}
@@ -276,13 +276,13 @@  discard block
 block discarded – undo
276 276
 		global $conf, $langs;
277 277
 
278 278
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."events";
279
-		$sql.= " WHERE rowid=".$this->id;
279
+		$sql .= " WHERE rowid=".$this->id;
280 280
 
281 281
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
282 282
 		$resql = $this->db->query($sql);
283
-		if (! $resql)
283
+		if (!$resql)
284 284
 		{
285
-			$this->error="Error ".$this->db->lasterror();
285
+			$this->error = "Error ".$this->db->lasterror();
286 286
 			return -1;
287 287
 		}
288 288
 
@@ -299,11 +299,11 @@  discard block
 block discarded – undo
299 299
 	 */
300 300
 	function initAsSpecimen()
301 301
 	{
302
-		$this->id=0;
302
+		$this->id = 0;
303 303
 
304
-		$this->tms=time();
305
-		$this->type='';
306
-		$this->dateevent=time();
307
-		$this->description='This is a specimen event';
304
+		$this->tms = time();
305
+		$this->type = '';
306
+		$this->dateevent = time();
307
+		$this->description = 'This is a specimen event';
308 308
 	}
309 309
 }
Please login to merge, or discard this patch.
Braces   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -137,7 +137,9 @@  discard block
 block discarded – undo
137 137
 
138 138
 		// Clean parameters
139 139
 		$this->description=trim($this->description);
140
-		if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
140
+		if (empty($this->user_agent) && !empty($_SERVER['HTTP_USER_AGENT'])) {
141
+		    $this->user_agent=$_SERVER['HTTP_USER_AGENT'];
142
+		}
141 143
 
142 144
 		// Check parameters
143 145
 		if (empty($this->description)) { $this->error='ErrorBadValueForParameterCreateEventDesc'; return -1; }
@@ -167,8 +169,7 @@  discard block
 block discarded – undo
167 169
 		{
168 170
 			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."events");
169 171
 			return $this->id;
170
-		}
171
-		else
172
+		} else
172 173
 		{
173 174
 			$this->error="Error ".$this->db->lasterror();
174 175
 			return -1;
@@ -256,8 +257,7 @@  discard block
 block discarded – undo
256 257
 			$this->db->free($resql);
257 258
 
258 259
 			return 1;
259
-		}
260
-		else
260
+		} else
261 261
 		{
262 262
 			$this->error="Error ".$this->db->lasterror();
263 263
 			return -1;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/ctyperesource.class.php 3 patches
Indentation   +418 added lines, -418 removed lines patch added patch discarded remove patch
@@ -32,436 +32,436 @@  discard block
 block discarded – undo
32 32
  */
33 33
 class Ctyperesource
34 34
 {
35
-	/**
36
-	 * @var string Id to identify managed objects
37
-	 */
38
-	public $element = 'ctyperesource';
35
+    /**
36
+     * @var string Id to identify managed objects
37
+     */
38
+    public $element = 'ctyperesource';
39 39
 
40
-	/**
41
-	 * @var string Name of table without prefix where object is stored
42
-	 */
43
-	public $table_element = 'c_type_resource';
40
+    /**
41
+     * @var string Name of table without prefix where object is stored
42
+     */
43
+    public $table_element = 'c_type_resource';
44 44
 
45
-	/**
46
-	 * @var CtyperesourceLine[] Lines
47
-	 */
48
-	public $lines = array();
45
+    /**
46
+     * @var CtyperesourceLine[] Lines
47
+     */
48
+    public $lines = array();
49 49
 
50
-	public $code;
50
+    public $code;
51 51
 
52
-	/**
52
+    /**
53 53
      * @var string Type resource label
54 54
      */
55 55
     public $label;
56 56
 
57
-	public $active;
57
+    public $active;
58
+
59
+
60
+    /**
61
+     * Constructor
62
+     *
63
+     * @param DoliDb $db Database handler
64
+     */
65
+    public function __construct(DoliDB $db)
66
+    {
67
+        $this->db = $db;
68
+    }
69
+
70
+    /**
71
+     * Create object into database
72
+     *
73
+     * @param  User $user      User that creates
74
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
75
+     *
76
+     * @return int <0 if KO, Id of created object if OK
77
+     */
78
+    public function create(User $user, $notrigger = false)
79
+    {
80
+        dol_syslog(__METHOD__, LOG_DEBUG);
81
+
82
+        $error = 0;
83
+
84
+        // Clean parameters
85
+
86
+        if (isset($this->code)) {
87
+                $this->code = trim($this->code);
88
+        }
89
+        if (isset($this->label)) {
90
+                $this->label = trim($this->label);
91
+        }
92
+        if (isset($this->active)) {
93
+                $this->active = trim($this->active);
94
+        }
95
+
58 96
 
59 97
 
60
-	/**
61
-	 * Constructor
62
-	 *
63
-	 * @param DoliDb $db Database handler
64
-	 */
65
-	public function __construct(DoliDB $db)
66
-	{
67
-		$this->db = $db;
68
-	}
98
+        // Check parameters
99
+        // Put here code to add control on parameters values
69 100
 
70
-	/**
71
-	 * Create object into database
72
-	 *
73
-	 * @param  User $user      User that creates
74
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
75
-	 *
76
-	 * @return int <0 if KO, Id of created object if OK
77
-	 */
78
-	public function create(User $user, $notrigger = false)
79
-	{
80
-		dol_syslog(__METHOD__, LOG_DEBUG);
101
+        // Insert request
102
+        $sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
81 103
 
82
-		$error = 0;
104
+        $sql.= 'code,';
105
+        $sql.= 'label';
106
+        $sql.= 'active';
83 107
 
84
-		// Clean parameters
85 108
 
86
-		if (isset($this->code)) {
87
-			 $this->code = trim($this->code);
88
-		}
89
-		if (isset($this->label)) {
90
-			 $this->label = trim($this->label);
91
-		}
92
-		if (isset($this->active)) {
93
-			 $this->active = trim($this->active);
94
-		}
109
+        $sql .= ') VALUES (';
95 110
 
111
+        $sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").',';
112
+        $sql .= ' '.(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").',';
113
+        $sql .= ' '.(! isset($this->active)?'NULL':$this->active);
96 114
 
97 115
 
98
-		// Check parameters
99
-		// Put here code to add control on parameters values
116
+        $sql .= ')';
100 117
 
101
-		// Insert request
102
-		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
118
+        $this->db->begin();
103 119
 
104
-		$sql.= 'code,';
105
-		$sql.= 'label';
106
-		$sql.= 'active';
120
+        $resql = $this->db->query($sql);
121
+        if (!$resql) {
122
+            $error ++;
123
+            $this->errors[] = 'Error ' . $this->db->lasterror();
124
+            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
125
+        }
107 126
 
127
+        if (!$error) {
128
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
108 129
 
109
-		$sql .= ') VALUES (';
130
+            // Uncomment this and change MYOBJECT to your own tag if you
131
+            // want this action to call a trigger.
132
+            //if (!$notrigger) {
110 133
 
111
-		$sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").',';
112
-		$sql .= ' '.(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").',';
113
-		$sql .= ' '.(! isset($this->active)?'NULL':$this->active);
134
+            //  // Call triggers
135
+            //  $result=$this->call_trigger('MYOBJECT_CREATE',$user);
136
+            //  if ($result < 0) $error++;
137
+            //  // End call triggers
138
+            //}
139
+        }
114 140
 
141
+        // Commit or rollback
142
+        if ($error) {
143
+            $this->db->rollback();
115 144
 
116
-		$sql .= ')';
145
+            return - 1 * $error;
146
+        } else {
147
+            $this->db->commit();
117 148
 
118
-		$this->db->begin();
119
-
120
-		$resql = $this->db->query($sql);
121
-		if (!$resql) {
122
-			$error ++;
123
-			$this->errors[] = 'Error ' . $this->db->lasterror();
124
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
125
-		}
126
-
127
-		if (!$error) {
128
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
129
-
130
-			// Uncomment this and change MYOBJECT to your own tag if you
131
-			// want this action to call a trigger.
132
-			//if (!$notrigger) {
133
-
134
-			//  // Call triggers
135
-			//  $result=$this->call_trigger('MYOBJECT_CREATE',$user);
136
-			//  if ($result < 0) $error++;
137
-			//  // End call triggers
138
-			//}
139
-		}
140
-
141
-		// Commit or rollback
142
-		if ($error) {
143
-			$this->db->rollback();
144
-
145
-			return - 1 * $error;
146
-		} else {
147
-			$this->db->commit();
148
-
149
-			return $this->id;
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * Load object in memory from the database
155
-	 *
156
-	 * @param int    $id  Id object
157
-	 * @param string $code code
158
-	 * @param string $label Label
159
-	 *
160
-	 * @return int <0 if KO, 0 if not found, >0 if OK
161
-	 */
162
-	public function fetch($id,$code='',$label='')
163
-	{
164
-		dol_syslog(__METHOD__, LOG_DEBUG);
165
-
166
-		$sql = 'SELECT';
167
-		$sql .= ' t.rowid,';
168
-
169
-		$sql .= " t.code,";
170
-		$sql .= " t.label,";
171
-		$sql .= " t.active";
172
-
173
-
174
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
175
-		if ($id)   $sql.= " WHERE t.id = ".$id;
176
-		elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
177
-		elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
178
-
179
-
180
-		$resql = $this->db->query($sql);
181
-		if ($resql) {
182
-			$numrows = $this->db->num_rows($resql);
183
-			if ($numrows) {
184
-				$obj = $this->db->fetch_object($resql);
185
-
186
-				$this->id = $obj->rowid;
187
-
188
-				$this->code = $obj->code;
189
-				$this->label = $obj->label;
190
-				$this->active = $obj->active;
191
-			}
192
-
193
-			// Retrieve all extrafields for invoice
194
-			// fetch optionals attributes and labels
195
-			// $this->fetch_optionals();
196
-
197
-			// $this->fetch_lines();
198
-
199
-			$this->db->free($resql);
200
-
201
-			if ($numrows) {
202
-				return 1;
203
-			} else {
204
-				return 0;
205
-			}
206
-		} else {
207
-			$this->errors[] = 'Error ' . $this->db->lasterror();
208
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
209
-
210
-			return - 1;
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * Load object in memory from the database
216
-	 *
217
-	 * @param string $sortorder Sort Order
218
-	 * @param string $sortfield Sort field
219
-	 * @param int    $limit     offset limit
220
-	 * @param int    $offset    offset limit
221
-	 * @param array  $filter    filter array
222
-	 * @param string $filtermode filter mode (AND or OR)
223
-	 *
224
-	 * @return int <0 if KO, >0 if OK
225
-	 */
226
-	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
227
-	{
228
-		dol_syslog(__METHOD__, LOG_DEBUG);
229
-
230
-		$sql = 'SELECT';
231
-		$sql .= ' t.rowid,';
232
-
233
-		$sql .= " t.code,";
234
-		$sql .= " t.label,";
235
-		$sql .= " t.active";
236
-
237
-
238
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
239
-
240
-		// Manage filter
241
-		$sqlwhere = array();
242
-		if (count($filter) > 0) {
243
-			foreach ($filter as $key => $value) {
244
-				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
245
-			}
246
-		}
247
-
248
-		if (count($sqlwhere) > 0) {
249
-			$sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere);
250
-		}
251
-		if (!empty($sortfield)) {
252
-			$sql .= $this->db->order($sortfield,$sortorder);
253
-		}
254
-		if (!empty($limit)) {
255
-		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
256
-		}
257
-
258
-		$resql = $this->db->query($sql);
259
-		if ($resql) {
260
-			$num = $this->db->num_rows($resql);
261
-
262
-			while ($obj = $this->db->fetch_object($resql)) {
263
-				$line = new self($this->db);
264
-
265
-				$line->id = $obj->rowid;
266
-
267
-				$line->code = $obj->code;
268
-				$line->label = $obj->label;
269
-				$line->active = $obj->active;
270
-			}
271
-			$this->db->free($resql);
272
-
273
-			return $num;
274
-		} else {
275
-			$this->errors[] = 'Error ' . $this->db->lasterror();
276
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
277
-
278
-			return - 1;
279
-		}
280
-	}
281
-
282
-	/**
283
-	 * Update object into database
284
-	 *
285
-	 * @param  User $user      User that modifies
286
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
287
-	 *
288
-	 * @return int <0 if KO, >0 if OK
289
-	 */
290
-	public function update(User $user, $notrigger = false)
291
-	{
292
-		$error = 0;
293
-
294
-		dol_syslog(__METHOD__, LOG_DEBUG);
295
-
296
-		// Clean parameters
297
-
298
-		if (isset($this->code)) {
299
-			 $this->code = trim($this->code);
300
-		}
301
-		if (isset($this->label)) {
302
-			 $this->label = trim($this->label);
303
-		}
304
-		if (isset($this->active)) {
305
-			 $this->active = trim($this->active);
306
-		}
307
-
308
-		// Check parameters
309
-		// Put here code to add a control on parameters values
310
-
311
-		// Update request
312
-		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
313
-
314
-		$sql .= ' code = '.(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").',';
315
-		$sql .= ' label = '.(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").',';
316
-		$sql .= ' active = '.(isset($this->active)?$this->active:"null");
317
-
318
-
319
-		$sql .= ' WHERE rowid=' . $this->id;
320
-
321
-		$this->db->begin();
322
-
323
-		$resql = $this->db->query($sql);
324
-		if (!$resql) {
325
-			$error ++;
326
-			$this->errors[] = 'Error ' . $this->db->lasterror();
327
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
328
-		}
329
-
330
-		// Uncomment this and change MYOBJECT to your own tag if you
331
-		// want this action calls a trigger.
332
-		//if (!$error && !$notrigger) {
333
-
334
-		//  // Call triggers
335
-		//  $result=$this->call_trigger('MYOBJECT_MODIFY',$user);
336
-		//  if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
337
-		//  // End call triggers
338
-		//}
339
-
340
-		// Commit or rollback
341
-		if ($error) {
342
-			$this->db->rollback();
343
-
344
-			return - 1 * $error;
345
-		} else {
346
-			$this->db->commit();
347
-
348
-			return 1;
349
-		}
350
-	}
351
-
352
-	/**
353
-	 * Delete object in database
354
-	 *
355
-	 * @param User $user      User that deletes
356
-	 * @param bool $notrigger false=launch triggers after, true=disable triggers
357
-	 *
358
-	 * @return int <0 if KO, >0 if OK
359
-	 */
360
-	public function delete(User $user, $notrigger = false)
361
-	{
362
-		dol_syslog(__METHOD__, LOG_DEBUG);
363
-
364
-		$error = 0;
365
-
366
-		$this->db->begin();
367
-
368
-		// Uncomment this and change MYOBJECT to your own tag if you
369
-		// want this action calls a trigger.
370
-		//if (!$error && !$notrigger) {
371
-
372
-		//  // Call triggers
373
-		//  $result=$this->call_trigger('MYOBJECT_DELETE',$user);
374
-		//  if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
375
-		//  // End call triggers
376
-		//}
377
-
378
-		// If you need to delete child tables to, you can insert them here
379
-
380
-		if (!$error) {
381
-			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
382
-			$sql .= ' WHERE rowid=' . $this->id;
383
-
384
-			$resql = $this->db->query($sql);
385
-			if (!$resql) {
386
-				$error ++;
387
-				$this->errors[] = 'Error ' . $this->db->lasterror();
388
-				dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
389
-			}
390
-		}
391
-
392
-		// Commit or rollback
393
-		if ($error) {
394
-			$this->db->rollback();
395
-
396
-			return - 1 * $error;
397
-		} else {
398
-			$this->db->commit();
399
-
400
-			return 1;
401
-		}
402
-	}
403
-
404
-	/**
405
-	 * Load an object from its id and create a new one in database
406
-	 *
407
-	 * @param int $fromid Id of object to clone
408
-	 *
409
-	 * @return int New id of clone
410
-	 */
411
-	public function createFromClone($fromid)
412
-	{
413
-		dol_syslog(__METHOD__, LOG_DEBUG);
414
-
415
-		global $user;
416
-		$error = 0;
417
-		$object = new Ctyperesource($this->db);
418
-
419
-		$this->db->begin();
420
-
421
-		// Load source object
422
-		$object->fetch($fromid);
423
-		// Reset object
424
-		$object->id = 0;
425
-
426
-		// Clear fields
427
-		// ...
428
-
429
-		// Create clone
430
-		$result = $object->create($user);
431
-
432
-		// Other options
433
-		if ($result < 0) {
434
-			$error ++;
435
-			$this->errors = $object->errors;
436
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
437
-		}
438
-
439
-		// End
440
-		if (!$error) {
441
-			$this->db->commit();
442
-
443
-			return $object->id;
444
-		} else {
445
-			$this->db->rollback();
446
-
447
-			return - 1;
448
-		}
449
-	}
450
-
451
-	/**
452
-	 * Initialise object with example values
453
-	 * Id must be 0 if object instance is a specimen
454
-	 *
455
-	 * @return void
456
-	 */
457
-	public function initAsSpecimen()
458
-	{
459
-		$this->id = 0;
460
-
461
-		$this->code = '';
462
-		$this->label = '';
463
-		$this->active = '';
464
-	}
149
+            return $this->id;
150
+        }
151
+    }
152
+
153
+    /**
154
+     * Load object in memory from the database
155
+     *
156
+     * @param int    $id  Id object
157
+     * @param string $code code
158
+     * @param string $label Label
159
+     *
160
+     * @return int <0 if KO, 0 if not found, >0 if OK
161
+     */
162
+    public function fetch($id,$code='',$label='')
163
+    {
164
+        dol_syslog(__METHOD__, LOG_DEBUG);
165
+
166
+        $sql = 'SELECT';
167
+        $sql .= ' t.rowid,';
168
+
169
+        $sql .= " t.code,";
170
+        $sql .= " t.label,";
171
+        $sql .= " t.active";
172
+
173
+
174
+        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
175
+        if ($id)   $sql.= " WHERE t.id = ".$id;
176
+        elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
177
+        elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
178
+
179
+
180
+        $resql = $this->db->query($sql);
181
+        if ($resql) {
182
+            $numrows = $this->db->num_rows($resql);
183
+            if ($numrows) {
184
+                $obj = $this->db->fetch_object($resql);
185
+
186
+                $this->id = $obj->rowid;
187
+
188
+                $this->code = $obj->code;
189
+                $this->label = $obj->label;
190
+                $this->active = $obj->active;
191
+            }
192
+
193
+            // Retrieve all extrafields for invoice
194
+            // fetch optionals attributes and labels
195
+            // $this->fetch_optionals();
196
+
197
+            // $this->fetch_lines();
198
+
199
+            $this->db->free($resql);
200
+
201
+            if ($numrows) {
202
+                return 1;
203
+            } else {
204
+                return 0;
205
+            }
206
+        } else {
207
+            $this->errors[] = 'Error ' . $this->db->lasterror();
208
+            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
209
+
210
+            return - 1;
211
+        }
212
+    }
213
+
214
+    /**
215
+     * Load object in memory from the database
216
+     *
217
+     * @param string $sortorder Sort Order
218
+     * @param string $sortfield Sort field
219
+     * @param int    $limit     offset limit
220
+     * @param int    $offset    offset limit
221
+     * @param array  $filter    filter array
222
+     * @param string $filtermode filter mode (AND or OR)
223
+     *
224
+     * @return int <0 if KO, >0 if OK
225
+     */
226
+    public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
227
+    {
228
+        dol_syslog(__METHOD__, LOG_DEBUG);
229
+
230
+        $sql = 'SELECT';
231
+        $sql .= ' t.rowid,';
232
+
233
+        $sql .= " t.code,";
234
+        $sql .= " t.label,";
235
+        $sql .= " t.active";
236
+
237
+
238
+        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
239
+
240
+        // Manage filter
241
+        $sqlwhere = array();
242
+        if (count($filter) > 0) {
243
+            foreach ($filter as $key => $value) {
244
+                $sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
245
+            }
246
+        }
247
+
248
+        if (count($sqlwhere) > 0) {
249
+            $sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere);
250
+        }
251
+        if (!empty($sortfield)) {
252
+            $sql .= $this->db->order($sortfield,$sortorder);
253
+        }
254
+        if (!empty($limit)) {
255
+            $sql .=  ' ' . $this->db->plimit($limit, $offset);
256
+        }
257
+
258
+        $resql = $this->db->query($sql);
259
+        if ($resql) {
260
+            $num = $this->db->num_rows($resql);
261
+
262
+            while ($obj = $this->db->fetch_object($resql)) {
263
+                $line = new self($this->db);
264
+
265
+                $line->id = $obj->rowid;
266
+
267
+                $line->code = $obj->code;
268
+                $line->label = $obj->label;
269
+                $line->active = $obj->active;
270
+            }
271
+            $this->db->free($resql);
272
+
273
+            return $num;
274
+        } else {
275
+            $this->errors[] = 'Error ' . $this->db->lasterror();
276
+            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
277
+
278
+            return - 1;
279
+        }
280
+    }
281
+
282
+    /**
283
+     * Update object into database
284
+     *
285
+     * @param  User $user      User that modifies
286
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
287
+     *
288
+     * @return int <0 if KO, >0 if OK
289
+     */
290
+    public function update(User $user, $notrigger = false)
291
+    {
292
+        $error = 0;
293
+
294
+        dol_syslog(__METHOD__, LOG_DEBUG);
295
+
296
+        // Clean parameters
297
+
298
+        if (isset($this->code)) {
299
+                $this->code = trim($this->code);
300
+        }
301
+        if (isset($this->label)) {
302
+                $this->label = trim($this->label);
303
+        }
304
+        if (isset($this->active)) {
305
+                $this->active = trim($this->active);
306
+        }
307
+
308
+        // Check parameters
309
+        // Put here code to add a control on parameters values
310
+
311
+        // Update request
312
+        $sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
313
+
314
+        $sql .= ' code = '.(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").',';
315
+        $sql .= ' label = '.(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").',';
316
+        $sql .= ' active = '.(isset($this->active)?$this->active:"null");
317
+
318
+
319
+        $sql .= ' WHERE rowid=' . $this->id;
320
+
321
+        $this->db->begin();
322
+
323
+        $resql = $this->db->query($sql);
324
+        if (!$resql) {
325
+            $error ++;
326
+            $this->errors[] = 'Error ' . $this->db->lasterror();
327
+            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
328
+        }
329
+
330
+        // Uncomment this and change MYOBJECT to your own tag if you
331
+        // want this action calls a trigger.
332
+        //if (!$error && !$notrigger) {
333
+
334
+        //  // Call triggers
335
+        //  $result=$this->call_trigger('MYOBJECT_MODIFY',$user);
336
+        //  if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
337
+        //  // End call triggers
338
+        //}
339
+
340
+        // Commit or rollback
341
+        if ($error) {
342
+            $this->db->rollback();
343
+
344
+            return - 1 * $error;
345
+        } else {
346
+            $this->db->commit();
347
+
348
+            return 1;
349
+        }
350
+    }
351
+
352
+    /**
353
+     * Delete object in database
354
+     *
355
+     * @param User $user      User that deletes
356
+     * @param bool $notrigger false=launch triggers after, true=disable triggers
357
+     *
358
+     * @return int <0 if KO, >0 if OK
359
+     */
360
+    public function delete(User $user, $notrigger = false)
361
+    {
362
+        dol_syslog(__METHOD__, LOG_DEBUG);
363
+
364
+        $error = 0;
365
+
366
+        $this->db->begin();
367
+
368
+        // Uncomment this and change MYOBJECT to your own tag if you
369
+        // want this action calls a trigger.
370
+        //if (!$error && !$notrigger) {
371
+
372
+        //  // Call triggers
373
+        //  $result=$this->call_trigger('MYOBJECT_DELETE',$user);
374
+        //  if ($result < 0) { $error++; //Do also what you must do to rollback action if trigger fail}
375
+        //  // End call triggers
376
+        //}
377
+
378
+        // If you need to delete child tables to, you can insert them here
379
+
380
+        if (!$error) {
381
+            $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
382
+            $sql .= ' WHERE rowid=' . $this->id;
383
+
384
+            $resql = $this->db->query($sql);
385
+            if (!$resql) {
386
+                $error ++;
387
+                $this->errors[] = 'Error ' . $this->db->lasterror();
388
+                dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
389
+            }
390
+        }
391
+
392
+        // Commit or rollback
393
+        if ($error) {
394
+            $this->db->rollback();
395
+
396
+            return - 1 * $error;
397
+        } else {
398
+            $this->db->commit();
399
+
400
+            return 1;
401
+        }
402
+    }
403
+
404
+    /**
405
+     * Load an object from its id and create a new one in database
406
+     *
407
+     * @param int $fromid Id of object to clone
408
+     *
409
+     * @return int New id of clone
410
+     */
411
+    public function createFromClone($fromid)
412
+    {
413
+        dol_syslog(__METHOD__, LOG_DEBUG);
414
+
415
+        global $user;
416
+        $error = 0;
417
+        $object = new Ctyperesource($this->db);
418
+
419
+        $this->db->begin();
420
+
421
+        // Load source object
422
+        $object->fetch($fromid);
423
+        // Reset object
424
+        $object->id = 0;
425
+
426
+        // Clear fields
427
+        // ...
428
+
429
+        // Create clone
430
+        $result = $object->create($user);
431
+
432
+        // Other options
433
+        if ($result < 0) {
434
+            $error ++;
435
+            $this->errors = $object->errors;
436
+            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
437
+        }
438
+
439
+        // End
440
+        if (!$error) {
441
+            $this->db->commit();
442
+
443
+            return $object->id;
444
+        } else {
445
+            $this->db->rollback();
446
+
447
+            return - 1;
448
+        }
449
+    }
450
+
451
+    /**
452
+     * Initialise object with example values
453
+     * Id must be 0 if object instance is a specimen
454
+     *
455
+     * @return void
456
+     */
457
+    public function initAsSpecimen()
458
+    {
459
+        $this->id = 0;
460
+
461
+        $this->code = '';
462
+        $this->label = '';
463
+        $this->active = '';
464
+    }
465 465
 }
466 466
 
467 467
 /**
@@ -469,24 +469,24 @@  discard block
 block discarded – undo
469 469
  */
470 470
 class CtyperesourceLine
471 471
 {
472
-	/**
473
-	 * @var int ID
474
-	 */
475
-	public $id;
472
+    /**
473
+     * @var int ID
474
+     */
475
+    public $id;
476 476
 
477
-	/**
478
-	 * @var mixed Sample line property 1
479
-	 */
480
-	public $code;
477
+    /**
478
+     * @var mixed Sample line property 1
479
+     */
480
+    public $code;
481 481
 
482
-	/**
482
+    /**
483 483
      * @var string Type resource line label
484 484
      */
485 485
     public $label;
486 486
 
487
-	public $active;
487
+    public $active;
488 488
 
489
-	/**
490
-	 * @var mixed Sample line property 2
491
-	 */
489
+    /**
490
+     * @var mixed Sample line property 2
491
+     */
492 492
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -99,18 +99,18 @@  discard block
 block discarded – undo
99 99
 		// Put here code to add control on parameters values
100 100
 
101 101
 		// Insert request
102
-		$sql = 'INSERT INTO ' . MAIN_DB_PREFIX . $this->table_element . '(';
102
+		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.'(';
103 103
 
104
-		$sql.= 'code,';
105
-		$sql.= 'label';
106
-		$sql.= 'active';
104
+		$sql .= 'code,';
105
+		$sql .= 'label';
106
+		$sql .= 'active';
107 107
 
108 108
 
109 109
 		$sql .= ') VALUES (';
110 110
 
111
-		$sql .= ' '.(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").',';
112
-		$sql .= ' '.(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").',';
113
-		$sql .= ' '.(! isset($this->active)?'NULL':$this->active);
111
+		$sql .= ' '.(!isset($this->code) ? 'NULL' : "'".$this->db->escape($this->code)."'").',';
112
+		$sql .= ' '.(!isset($this->label) ? 'NULL' : "'".$this->db->escape($this->label)."'").',';
113
+		$sql .= ' '.(!isset($this->active) ? 'NULL' : $this->active);
114 114
 
115 115
 
116 116
 		$sql .= ')';
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
 
120 120
 		$resql = $this->db->query($sql);
121 121
 		if (!$resql) {
122
-			$error ++;
123
-			$this->errors[] = 'Error ' . $this->db->lasterror();
124
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
122
+			$error++;
123
+			$this->errors[] = 'Error '.$this->db->lasterror();
124
+			dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
125 125
 		}
126 126
 
127 127
 		if (!$error) {
128
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
128
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
129 129
 
130 130
 			// Uncomment this and change MYOBJECT to your own tag if you
131 131
 			// want this action to call a trigger.
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		if ($error) {
143 143
 			$this->db->rollback();
144 144
 
145
-			return - 1 * $error;
145
+			return -1 * $error;
146 146
 		} else {
147 147
 			$this->db->commit();
148 148
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 	 *
160 160
 	 * @return int <0 if KO, 0 if not found, >0 if OK
161 161
 	 */
162
-	public function fetch($id,$code='',$label='')
162
+	public function fetch($id, $code = '', $label = '')
163 163
 	{
164 164
 		dol_syslog(__METHOD__, LOG_DEBUG);
165 165
 
@@ -171,10 +171,10 @@  discard block
 block discarded – undo
171 171
 		$sql .= " t.active";
172 172
 
173 173
 
174
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
175
-		if ($id)   $sql.= " WHERE t.id = ".$id;
176
-		elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
177
-		elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
174
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
175
+		if ($id)   $sql .= " WHERE t.id = ".$id;
176
+		elseif ($code) $sql .= " WHERE t.code = '".$this->db->escape($code)."'";
177
+		elseif ($label) $sql .= " WHERE t.label = '".$this->db->escape($label)."'";
178 178
 
179 179
 
180 180
 		$resql = $this->db->query($sql);
@@ -204,10 +204,10 @@  discard block
 block discarded – undo
204 204
 				return 0;
205 205
 			}
206 206
 		} else {
207
-			$this->errors[] = 'Error ' . $this->db->lasterror();
208
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
207
+			$this->errors[] = 'Error '.$this->db->lasterror();
208
+			dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
209 209
 
210
-			return - 1;
210
+			return -1;
211 211
 		}
212 212
 	}
213 213
 
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 *
224 224
 	 * @return int <0 if KO, >0 if OK
225 225
 	 */
226
-	public function fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter = array(), $filtermode='AND')
226
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
227 227
 	{
228 228
 		dol_syslog(__METHOD__, LOG_DEBUG);
229 229
 
@@ -235,24 +235,24 @@  discard block
 block discarded – undo
235 235
 		$sql .= " t.active";
236 236
 
237 237
 
238
-		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element. ' as t';
238
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
239 239
 
240 240
 		// Manage filter
241 241
 		$sqlwhere = array();
242 242
 		if (count($filter) > 0) {
243 243
 			foreach ($filter as $key => $value) {
244
-				$sqlwhere [] = $key . ' LIKE \'%' . $this->db->escape($value) . '%\'';
244
+				$sqlwhere [] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
245 245
 			}
246 246
 		}
247 247
 
248 248
 		if (count($sqlwhere) > 0) {
249
-			$sql .= ' WHERE ' . implode(' '.$filtermode.' ', $sqlwhere);
249
+			$sql .= ' WHERE '.implode(' '.$filtermode.' ', $sqlwhere);
250 250
 		}
251 251
 		if (!empty($sortfield)) {
252
-			$sql .= $this->db->order($sortfield,$sortorder);
252
+			$sql .= $this->db->order($sortfield, $sortorder);
253 253
 		}
254 254
 		if (!empty($limit)) {
255
-		 $sql .=  ' ' . $this->db->plimit($limit, $offset);
255
+		 $sql .= ' '.$this->db->plimit($limit, $offset);
256 256
 		}
257 257
 
258 258
 		$resql = $this->db->query($sql);
@@ -272,10 +272,10 @@  discard block
 block discarded – undo
272 272
 
273 273
 			return $num;
274 274
 		} else {
275
-			$this->errors[] = 'Error ' . $this->db->lasterror();
276
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
275
+			$this->errors[] = 'Error '.$this->db->lasterror();
276
+			dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
277 277
 
278
-			return - 1;
278
+			return -1;
279 279
 		}
280 280
 	}
281 281
 
@@ -309,22 +309,22 @@  discard block
 block discarded – undo
309 309
 		// Put here code to add a control on parameters values
310 310
 
311 311
 		// Update request
312
-		$sql = 'UPDATE ' . MAIN_DB_PREFIX . $this->table_element . ' SET';
312
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
313 313
 
314
-		$sql .= ' code = '.(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").',';
315
-		$sql .= ' label = '.(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").',';
316
-		$sql .= ' active = '.(isset($this->active)?$this->active:"null");
314
+		$sql .= ' code = '.(isset($this->code) ? "'".$this->db->escape($this->code)."'" : "null").',';
315
+		$sql .= ' label = '.(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").',';
316
+		$sql .= ' active = '.(isset($this->active) ? $this->active : "null");
317 317
 
318 318
 
319
-		$sql .= ' WHERE rowid=' . $this->id;
319
+		$sql .= ' WHERE rowid='.$this->id;
320 320
 
321 321
 		$this->db->begin();
322 322
 
323 323
 		$resql = $this->db->query($sql);
324 324
 		if (!$resql) {
325
-			$error ++;
326
-			$this->errors[] = 'Error ' . $this->db->lasterror();
327
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
325
+			$error++;
326
+			$this->errors[] = 'Error '.$this->db->lasterror();
327
+			dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
328 328
 		}
329 329
 
330 330
 		// Uncomment this and change MYOBJECT to your own tag if you
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 		if ($error) {
342 342
 			$this->db->rollback();
343 343
 
344
-			return - 1 * $error;
344
+			return -1 * $error;
345 345
 		} else {
346 346
 			$this->db->commit();
347 347
 
@@ -378,14 +378,14 @@  discard block
 block discarded – undo
378 378
 		// If you need to delete child tables to, you can insert them here
379 379
 
380 380
 		if (!$error) {
381
-			$sql = 'DELETE FROM ' . MAIN_DB_PREFIX . $this->table_element;
382
-			$sql .= ' WHERE rowid=' . $this->id;
381
+			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element;
382
+			$sql .= ' WHERE rowid='.$this->id;
383 383
 
384 384
 			$resql = $this->db->query($sql);
385 385
 			if (!$resql) {
386
-				$error ++;
387
-				$this->errors[] = 'Error ' . $this->db->lasterror();
388
-				dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
386
+				$error++;
387
+				$this->errors[] = 'Error '.$this->db->lasterror();
388
+				dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
389 389
 			}
390 390
 		}
391 391
 
@@ -393,7 +393,7 @@  discard block
 block discarded – undo
393 393
 		if ($error) {
394 394
 			$this->db->rollback();
395 395
 
396
-			return - 1 * $error;
396
+			return -1 * $error;
397 397
 		} else {
398 398
 			$this->db->commit();
399 399
 
@@ -431,9 +431,9 @@  discard block
 block discarded – undo
431 431
 
432 432
 		// Other options
433 433
 		if ($result < 0) {
434
-			$error ++;
434
+			$error++;
435 435
 			$this->errors = $object->errors;
436
-			dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
436
+			dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
437 437
 		}
438 438
 
439 439
 		// End
@@ -444,7 +444,7 @@  discard block
 block discarded – undo
444 444
 		} else {
445 445
 			$this->db->rollback();
446 446
 
447
-			return - 1;
447
+			return -1;
448 448
 		}
449 449
 	}
450 450
 
Please login to merge, or discard this patch.
Braces   +7 added lines, -3 removed lines patch added patch discarded remove patch
@@ -172,9 +172,13 @@
 block discarded – undo
172 172
 
173 173
 
174 174
 		$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
175
-		if ($id)   $sql.= " WHERE t.id = ".$id;
176
-		elseif ($code) $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
177
-		elseif ($label) $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
175
+		if ($id) {
176
+		    $sql.= " WHERE t.id = ".$id;
177
+		} elseif ($code) {
178
+		    $sql.= " WHERE t.code = '".$this->db->escape($code)."'";
179
+		} elseif ($label) {
180
+		    $sql.= " WHERE t.label = '".$this->db->escape($label)."'";
181
+		}
178 182
 
179 183
 
180 184
 		$resql = $this->db->query($sql);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formsms.class.php 3 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
      */
103 103
     function show_form($morecss='titlefield', $showform=1)
104 104
     {
105
-     // phpcs:enable
105
+        // phpcs:enable
106 106
         global $conf, $langs, $user, $form;
107 107
 
108 108
         if (! is_object($form)) $form=new Form($this->db);
@@ -218,13 +218,13 @@  discard block
 block discarded – undo
218 218
                         $classname=ucfirst($classfile);
219 219
                         if (class_exists($classname))
220 220
                         {
221
-                        	$sms = new $classname($this->db);
222
-                        	$resultsender = $sms->SmsSenderList();
221
+                            $sms = new $classname($this->db);
222
+                            $resultsender = $sms->SmsSenderList();
223 223
                         }
224 224
                         else
225 225
                         {
226
-                        	$sms = new stdClass();
227
-                        	$sms->error='The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found';
226
+                            $sms = new stdClass();
227
+                            $sms->error='The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found';
228 228
                         }
229 229
                     }
230 230
                     catch(Exception $e)
@@ -236,7 +236,7 @@  discard block
 block discarded – undo
236 236
                 else
237 237
                 {
238 238
                     dol_syslog("Warning: The SMS sending method has not been defined into MAIN_SMS_SENDMODE", LOG_WARNING);
239
-	                $resultsender=array();
239
+                    $resultsender=array();
240 240
                     $resultsender[0]->number=$this->fromsms;
241 241
                 }
242 242
 
Please login to merge, or discard this patch.
Spacing   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
  *       \ingroup    core
23 23
  *       \brief      Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
24 24
  */
25
-require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
25
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
26 26
 
27 27
 
28 28
 /**
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
     public $toname;
46 46
     public $tomail;
47 47
 
48
-    public $withsubstit;			// Show substitution array
48
+    public $withsubstit; // Show substitution array
49 49
     public $withfrom;
50 50
     public $withto;
51 51
     public $withtopic;
@@ -57,18 +57,18 @@  discard block
 block discarded – undo
57 57
     public $withtopicreadonly;
58 58
     public $withcancel;
59 59
 
60
-    public $substit=array();
61
-    public $param=array();
60
+    public $substit = array();
61
+    public $param = array();
62 62
 
63 63
     /**
64 64
      * @var string Error code (or message)
65 65
      */
66
-    public $error='';
66
+    public $error = '';
67 67
 
68 68
     /**
69 69
      * @var string[]	Array of error strings
70 70
      */
71
-    public $errors=array();
71
+    public $errors = array();
72 72
 
73 73
 
74 74
     /**
@@ -80,16 +80,16 @@  discard block
 block discarded – undo
80 80
     {
81 81
         $this->db = $db;
82 82
 
83
-        $this->withfrom=1;
84
-        $this->withto=1;
85
-        $this->withtopic=1;
86
-        $this->withbody=1;
83
+        $this->withfrom = 1;
84
+        $this->withto = 1;
85
+        $this->withtopic = 1;
86
+        $this->withbody = 1;
87 87
 
88
-        $this->withfromreadonly=1;
89
-        $this->withreplytoreadonly=1;
90
-        $this->withtoreadonly=0;
91
-        $this->withtopicreadonly=0;
92
-        $this->withbodyreadonly=0;
88
+        $this->withfromreadonly = 1;
89
+        $this->withreplytoreadonly = 1;
90
+        $this->withtoreadonly = 0;
91
+        $this->withtopicreadonly = 0;
92
+        $this->withbodyreadonly = 0;
93 93
     }
94 94
 
95 95
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -100,17 +100,17 @@  discard block
 block discarded – undo
100 100
      *  @param int $showform Show form tags and submit button (recommanded is to use with value 0)
101 101
      *	@return	void
102 102
      */
103
-    function show_form($morecss='titlefield', $showform=1)
103
+    function show_form($morecss = 'titlefield', $showform = 1)
104 104
     {
105 105
      // phpcs:enable
106 106
         global $conf, $langs, $user, $form;
107 107
 
108
-        if (! is_object($form)) $form=new Form($this->db);
108
+        if (!is_object($form)) $form = new Form($this->db);
109 109
 
110 110
         // Load translation files required by the page
111 111
         $langs->loadLangs(array('other', 'mails', 'sms'));
112 112
 
113
-        $soc=new Societe($this->db);
113
+        $soc = new Societe($this->db);
114 114
         if (!empty($this->withtosocid) && $this->withtosocid > 0)
115 115
         {
116 116
             $soc->fetch($this->withtosocid);
@@ -141,15 +141,15 @@  discard block
 block discarded – undo
141 141
         print "<table class=\"border centpercent\">\n";
142 142
 
143 143
         // Substitution array
144
-        if (! empty($this->withsubstit))		// Unset or set ->withsubstit=0 to disable this.
144
+        if (!empty($this->withsubstit))		// Unset or set ->withsubstit=0 to disable this.
145 145
         {
146 146
             print "<tr><td colspan=\"2\">";
147
-            $help="";
148
-            foreach($this->substit as $key => $val)
147
+            $help = "";
148
+            foreach ($this->substit as $key => $val)
149 149
             {
150
-                $help.=$key.' -> '.$langs->trans($val).'<br>';
150
+                $help .= $key.' -> '.$langs->trans($val).'<br>';
151 151
             }
152
-            print $form->textwithpicto($langs->trans("SmsTestSubstitutionReplacedByGenericValues"),$help);
152
+            print $form->textwithpicto($langs->trans("SmsTestSubstitutionReplacedByGenericValues"), $help);
153 153
             print "</td></tr>\n";
154 154
         }
155 155
 
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
                 if ($this->fromtype == 'user')
165 165
                 {
166 166
                     $langs->load("users");
167
-                    $fuser=new User($this->db);
167
+                    $fuser = new User($this->db);
168 168
                     $fuser->fetch($this->fromid);
169 169
                     print $fuser->getNomUrl(1);
170 170
                     print ' &nbsp; ';
@@ -203,19 +203,19 @@  discard block
 block discarded – undo
203 203
                             $resultsender = $sms->SmsSenderList();
204 204
                         }
205 205
                     }
206
-                    catch(Exception $e)
206
+                    catch (Exception $e)
207 207
                     {
208
-                        dol_print_error('','Error to get list of senders: '.$e->getMessage());
208
+                        dol_print_error('', 'Error to get list of senders: '.$e->getMessage());
209 209
                     }
210 210
                 }
211 211
                 else if (!empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
212 212
                 {
213
-                    $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
214
-                    $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
213
+                    $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE);
214
+                    $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]);
215 215
                     dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
216 216
                     try
217 217
                     {
218
-                        $classname=ucfirst($classfile);
218
+                        $classname = ucfirst($classfile);
219 219
                         if (class_exists($classname))
220 220
                         {
221 221
                         	$sms = new $classname($this->db);
@@ -224,26 +224,26 @@  discard block
 block discarded – undo
224 224
                         else
225 225
                         {
226 226
                         	$sms = new stdClass();
227
-                        	$sms->error='The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found';
227
+                        	$sms->error = 'The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found';
228 228
                         }
229 229
                     }
230
-                    catch(Exception $e)
230
+                    catch (Exception $e)
231 231
                     {
232
-                        dol_print_error('','Error to get list of senders: '.$e->getMessage());
232
+                        dol_print_error('', 'Error to get list of senders: '.$e->getMessage());
233 233
                         exit;
234 234
                     }
235 235
                 }
236 236
                 else
237 237
                 {
238 238
                     dol_syslog("Warning: The SMS sending method has not been defined into MAIN_SMS_SENDMODE", LOG_WARNING);
239
-	                $resultsender=array();
240
-                    $resultsender[0]->number=$this->fromsms;
239
+	                $resultsender = array();
240
+                    $resultsender[0]->number = $this->fromsms;
241 241
                 }
242 242
 
243 243
                 if (is_array($resultsender) && count($resultsender) > 0)
244 244
                 {
245 245
                     print '<select name="fromsms" id="fromsms" class="flat">';
246
-                    foreach($resultsender as $obj)
246
+                    foreach ($resultsender as $obj)
247 247
                     {
248 248
                         print '<option value="'.$obj->number.'">'.$obj->number.'</option>';
249 249
                     }
@@ -252,7 +252,7 @@  discard block
 block discarded – undo
252 252
                 else
253 253
                 {
254 254
                     print '<span class="error">'.$langs->trans("SmsNoPossibleSenderFound");
255
-                    if (is_object($sms) && ! empty($sms->error)) print ' '.$sms->error;
255
+                    if (is_object($sms) && !empty($sms->error)) print ' '.$sms->error;
256 256
                     print '</span>';
257 257
                 }
258 258
                 print '</td>';
@@ -265,22 +265,22 @@  discard block
 block discarded – undo
265 265
         {
266 266
             print '<tr><td>';
267 267
             //$moretext=$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients");
268
-            $moretext='';
269
-            print $form->textwithpicto($langs->trans("SmsTo"),$moretext);
268
+            $moretext = '';
269
+            print $form->textwithpicto($langs->trans("SmsTo"), $moretext);
270 270
             print '</td><td>';
271 271
             if ($this->withtoreadonly)
272 272
             {
273
-                print (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:"";
273
+                print (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : "";
274 274
             }
275 275
             else
276 276
             {
277
-                print "<input size=\"16\" id=\"sendto\" name=\"sendto\" value=\"".dol_escape_htmltag(! is_array($this->withto) && $this->withto != '1'? (isset($_REQUEST["sendto"])?GETPOST("sendto"):$this->withto):"+")."\">";
278
-                if (! empty($this->withtosocid) && $this->withtosocid > 0)
277
+                print "<input size=\"16\" id=\"sendto\" name=\"sendto\" value=\"".dol_escape_htmltag(!is_array($this->withto) && $this->withto != '1' ? (isset($_REQUEST["sendto"]) ?GETPOST("sendto") : $this->withto) : "+")."\">";
278
+                if (!empty($this->withtosocid) && $this->withtosocid > 0)
279 279
                 {
280
-                    $liste=array();
280
+                    $liste = array();
281 281
                     foreach ($soc->thirdparty_and_contact_phone_array() as $key => $value)
282 282
                     {
283
-                        $liste[$key]=$value;
283
+                        $liste[$key] = $value;
284 284
                     }
285 285
                     print " ".$langs->trans("or")." ";
286 286
                     //var_dump($_REQUEST);exit;
@@ -294,14 +294,14 @@  discard block
 block discarded – undo
294 294
         // Message
295 295
         if ($this->withbody)
296 296
         {
297
-            $defaultmessage='';
298
-            if ($this->param["models"]=='body')
297
+            $defaultmessage = '';
298
+            if ($this->param["models"] == 'body')
299 299
             {
300
-                $defaultmessage=$this->withbody;
300
+                $defaultmessage = $this->withbody;
301 301
             }
302
-            $defaultmessage=make_substitutions($defaultmessage,$this->substit);
303
-            if (isset($_POST["message"])) $defaultmessage=$_POST["message"];
304
-            $defaultmessage=str_replace('\n',"\n",$defaultmessage);
302
+            $defaultmessage = make_substitutions($defaultmessage, $this->substit);
303
+            if (isset($_POST["message"])) $defaultmessage = $_POST["message"];
304
+            $defaultmessage = str_replace('\n', "\n", $defaultmessage);
305 305
 
306 306
             print "<tr>";
307 307
             print '<td class="tdtop">'.$langs->trans("SmsText")."</td>";
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
             else
315 315
             {
316 316
                 print '<textarea class="quatrevingtpercent" name="message" id="message" rows="'.ROWS_4.'" onkeyup="limitChars(this, 160, \'charlimitinfospan\')">'.$defaultmessage.'</textarea>';
317
-                print '<div id="charlimitinfo">'.$langs->trans("SmsInfoCharRemain").': <span id="charlimitinfospan">'.(160-dol_strlen($defaultmessage)).'</span></div></td>';
317
+                print '<div id="charlimitinfo">'.$langs->trans("SmsInfoCharRemain").': <span id="charlimitinfospan">'.(160 - dol_strlen($defaultmessage)).'</span></div></td>';
318 318
             }
319 319
             print "</td></tr>\n";
320 320
         }
Please login to merge, or discard this patch.
Braces   +31 added lines, -28 removed lines patch added patch discarded remove patch
@@ -105,7 +105,9 @@  discard block
 block discarded – undo
105 105
      // phpcs:enable
106 106
         global $conf, $langs, $user, $form;
107 107
 
108
-        if (! is_object($form)) $form=new Form($this->db);
108
+        if (! is_object($form)) {
109
+            $form=new Form($this->db);
110
+        }
109 111
 
110 112
         // Load translation files required by the page
111 113
         $langs->loadLangs(array('other', 'mails', 'sms'));
@@ -131,7 +133,9 @@  discard block
 block discarded – undo
131 133
 }
132 134
 </script>';
133 135
 
134
-        if ($showform) print "<form method=\"POST\" name=\"smsform\" enctype=\"multipart/form-data\" action=\"".$this->param["returnurl"]."\">\n";
136
+        if ($showform) {
137
+            print "<form method=\"POST\" name=\"smsform\" enctype=\"multipart/form-data\" action=\"".$this->param["returnurl"]."\">\n";
138
+        }
135 139
 
136 140
         print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
137 141
         foreach ($this->param as $key=>$value)
@@ -141,9 +145,11 @@  discard block
 block discarded – undo
141 145
         print "<table class=\"border centpercent\">\n";
142 146
 
143 147
         // Substitution array
144
-        if (! empty($this->withsubstit))		// Unset or set ->withsubstit=0 to disable this.
148
+        if (! empty($this->withsubstit)) {
149
+            // Unset or set ->withsubstit=0 to disable this.
145 150
         {
146 151
             print "<tr><td colspan=\"2\">";
152
+        }
147 153
             $help="";
148 154
             foreach($this->substit as $key => $val)
149 155
             {
@@ -172,8 +178,7 @@  discard block
 block discarded – undo
172 178
                 if ($this->fromsms)
173 179
                 {
174 180
                     print $this->fromsms;
175
-                }
176
-                else
181
+                } else
177 182
                 {
178 183
                     if ($this->fromtype)
179 184
                     {
@@ -183,34 +188,34 @@  discard block
 block discarded – undo
183 188
                 }
184 189
                 print "</td></tr>\n";
185 190
                 print "</td></tr>\n";
186
-            }
187
-            else
191
+            } else
188 192
             {
189 193
                 print '<tr><td class="'.$morecss.'">'.$langs->trans("SmsFrom")."</td><td>";
190 194
                 //print '<input type="text" name="fromname" size="30" value="'.$this->fromsms.'">';
191
-                if ($conf->global->MAIN_SMS_SENDMODE == 'ovh')        // For backward compatibility        @deprecated
195
+                if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') {
196
+                    // For backward compatibility        @deprecated
192 197
                 {
193 198
                     dol_include_once('/ovh/class/ovhsms.class.php');
199
+                }
194 200
                     try
195 201
                     {
196 202
                         $sms = new OvhSms($this->db);
197 203
                         if (empty($conf->global->OVHSMS_ACCOUNT))
198 204
                         {
199 205
                             $resultsender = 'ErrorOVHSMS_ACCOUNT not defined';
200
-                        }
201
-                        else
206
+                        } else
202 207
                         {
203 208
                             $resultsender = $sms->SmsSenderList();
204 209
                         }
205
-                    }
206
-                    catch(Exception $e)
210
+                    } catch(Exception $e)
207 211
                     {
208 212
                         dol_print_error('','Error to get list of senders: '.$e->getMessage());
209 213
                     }
210
-                }
211
-                else if (!empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
214
+                } else if (!empty($conf->global->MAIN_SMS_SENDMODE)) {
215
+                    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
212 216
                 {
213 217
                     $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
218
+                }
214 219
                     $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
215 220
                     dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
216 221
                     try
@@ -220,20 +225,17 @@  discard block
 block discarded – undo
220 225
                         {
221 226
                         	$sms = new $classname($this->db);
222 227
                         	$resultsender = $sms->SmsSenderList();
223
-                        }
224
-                        else
228
+                        } else
225 229
                         {
226 230
                         	$sms = new stdClass();
227 231
                         	$sms->error='The SMS manager "'.$classfile.'" defined into SMS setup MAIN_SMS_SENDMODE is not found';
228 232
                         }
229
-                    }
230
-                    catch(Exception $e)
233
+                    } catch(Exception $e)
231 234
                     {
232 235
                         dol_print_error('','Error to get list of senders: '.$e->getMessage());
233 236
                         exit;
234 237
                     }
235
-                }
236
-                else
238
+                } else
237 239
                 {
238 240
                     dol_syslog("Warning: The SMS sending method has not been defined into MAIN_SMS_SENDMODE", LOG_WARNING);
239 241
 	                $resultsender=array();
@@ -248,11 +250,12 @@  discard block
 block discarded – undo
248 250
                         print '<option value="'.$obj->number.'">'.$obj->number.'</option>';
249 251
                     }
250 252
                     print '</select>';
251
-                }
252
-                else
253
+                } else
253 254
                 {
254 255
                     print '<span class="error">'.$langs->trans("SmsNoPossibleSenderFound");
255
-                    if (is_object($sms) && ! empty($sms->error)) print ' '.$sms->error;
256
+                    if (is_object($sms) && ! empty($sms->error)) {
257
+                        print ' '.$sms->error;
258
+                    }
256 259
                     print '</span>';
257 260
                 }
258 261
                 print '</td>';
@@ -271,8 +274,7 @@  discard block
 block discarded – undo
271 274
             if ($this->withtoreadonly)
272 275
             {
273 276
                 print (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:"";
274
-            }
275
-            else
277
+            } else
276 278
             {
277 279
                 print "<input size=\"16\" id=\"sendto\" name=\"sendto\" value=\"".dol_escape_htmltag(! is_array($this->withto) && $this->withto != '1'? (isset($_REQUEST["sendto"])?GETPOST("sendto"):$this->withto):"+")."\">";
278 280
                 if (! empty($this->withtosocid) && $this->withtosocid > 0)
@@ -300,7 +302,9 @@  discard block
 block discarded – undo
300 302
                 $defaultmessage=$this->withbody;
301 303
             }
302 304
             $defaultmessage=make_substitutions($defaultmessage,$this->substit);
303
-            if (isset($_POST["message"])) $defaultmessage=$_POST["message"];
305
+            if (isset($_POST["message"])) {
306
+                $defaultmessage=$_POST["message"];
307
+            }
304 308
             $defaultmessage=str_replace('\n',"\n",$defaultmessage);
305 309
 
306 310
             print "<tr>";
@@ -310,8 +314,7 @@  discard block
 block discarded – undo
310 314
             {
311 315
                 print nl2br($defaultmessage);
312 316
                 print '<input type="hidden" name="message" value="'.dol_escape_htmltag($defaultmessage).'">';
313
-            }
314
-            else
317
+            } else
315 318
             {
316 319
                 print '<textarea class="quatrevingtpercent" name="message" id="message" rows="'.ROWS_4.'" onkeyup="limitChars(this, 160, \'charlimitinfospan\')">'.$defaultmessage.'</textarea>';
317 320
                 print '<div id="charlimitinfo">'.$langs->trans("SmsInfoCharRemain").': <span id="charlimitinfospan">'.(160-dol_strlen($defaultmessage)).'</span></div></td>';
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/rssparser.class.php 3 patches
Indentation   +39 added lines, -39 removed lines patch added patch discarded remove patch
@@ -32,9 +32,9 @@  discard block
 block discarded – undo
32 32
     public $db;
33 33
 
34 34
     /**
35
-	 * @var string Error code (or message)
36
-	 */
37
-	public $error='';
35
+     * @var string Error code (or message)
36
+     */
37
+    public $error='';
38 38
 
39 39
     private $_format='';
40 40
     private $_urlRSS;
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
      */
62 62
     public function __construct($db)
63 63
     {
64
-    	$this->db = $db;
64
+        $this->db = $db;
65 65
     }
66 66
 
67 67
     /**
@@ -252,28 +252,28 @@  discard block
 block discarded – undo
252 252
 
253 253
         if ($str !== false)
254 254
         {
255
-	        // Convert $str into xml
256
-	        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
257
-	        {
258
-	            //print 'xx'.LIBXML_NOCDATA;
259
-	            libxml_use_internal_errors(false);
260
-	            $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
261
-	        }
262
-	        else
263
-	        {
264
-	            $xmlparser=xml_parser_create('');
265
-	            if (!is_resource($xmlparser)) {
266
-	                $this->error="ErrorFailedToCreateParser"; return -1;
267
-	            }
268
-
269
-	            xml_set_object($xmlparser, $this);
270
-	            xml_set_element_handler($xmlparser, 'feed_start_element', 'feed_end_element');
271
-	            xml_set_character_data_handler($xmlparser, 'feed_cdata');
272
-	            $status = xml_parse($xmlparser, $str);
273
-	            xml_parser_free($xmlparser);
274
-	            $rss=$this;
275
-	            //var_dump($rss->_format);exit;
276
-	        }
255
+            // Convert $str into xml
256
+            if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
257
+            {
258
+                //print 'xx'.LIBXML_NOCDATA;
259
+                libxml_use_internal_errors(false);
260
+                $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
261
+            }
262
+            else
263
+            {
264
+                $xmlparser=xml_parser_create('');
265
+                if (!is_resource($xmlparser)) {
266
+                    $this->error="ErrorFailedToCreateParser"; return -1;
267
+                }
268
+
269
+                xml_set_object($xmlparser, $this);
270
+                xml_set_element_handler($xmlparser, 'feed_start_element', 'feed_end_element');
271
+                xml_set_character_data_handler($xmlparser, 'feed_cdata');
272
+                $status = xml_parse($xmlparser, $str);
273
+                xml_parser_free($xmlparser);
274
+                $rss=$this;
275
+                //var_dump($rss->_format);exit;
276
+            }
277 277
         }
278 278
 
279 279
         // If $rss loaded
@@ -287,16 +287,16 @@  discard block
 block discarded – undo
287 287
                 $fp = fopen($newpathofdestfile, 'w');
288 288
                 if ($fp)
289 289
                 {
290
-                	fwrite($fp, $str);
291
-                	fclose($fp);
292
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
293
-                	@chmod($newpathofdestfile, octdec($newmask));
290
+                    fwrite($fp, $str);
291
+                    fclose($fp);
292
+                    if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
293
+                    @chmod($newpathofdestfile, octdec($newmask));
294 294
 
295
-	                $this->_lastfetchdate=$nowgmt;
295
+                    $this->_lastfetchdate=$nowgmt;
296 296
                 }
297 297
                 else
298 298
                 {
299
-                	print 'Error, failed to open file '.$newpathofdestfile.' for write';
299
+                    print 'Error, failed to open file '.$newpathofdestfile.' for write';
300 300
                 }
301 301
             }
302 302
 
@@ -435,13 +435,13 @@  discard block
 block discarded – undo
435 435
 
436 436
                     // Add record to result array
437 437
                     $this->_rssarray[$i] = array(
438
-    					'link'=>$itemLink,
439
-    					'title'=>$itemTitle,
440
-    					'description'=>$itemDescription,
441
-    					'pubDate'=>$itemPubDate,
442
-    					'category'=>$itemCategory,
443
-    				    'id'=>$itemId,
444
-    				    'author'=>$itemAuthor);
438
+                        'link'=>$itemLink,
439
+                        'title'=>$itemTitle,
440
+                        'description'=>$itemDescription,
441
+                        'pubDate'=>$itemPubDate,
442
+                        'category'=>$itemCategory,
443
+                        'id'=>$itemId,
444
+                        'author'=>$itemAuthor);
445 445
                     //var_dump($this->_rssarray);
446 446
 
447 447
                     $i++;
Please login to merge, or discard this patch.
Spacing   +86 added lines, -86 removed lines patch added patch discarded remove patch
@@ -34,9 +34,9 @@  discard block
 block discarded – undo
34 34
     /**
35 35
 	 * @var string Error code (or message)
36 36
 	 */
37
-	public $error='';
37
+	public $error = '';
38 38
 
39
-    private $_format='';
39
+    private $_format = '';
40 40
     private $_urlRSS;
41 41
     private $_language;
42 42
     private $_generator;
@@ -46,8 +46,8 @@  discard block
 block discarded – undo
46 46
     private $_link;
47 47
     private $_title;
48 48
     private $_description;
49
-    private $_lastfetchdate;    // Last successful fetch
50
-    private $_rssarray=array();
49
+    private $_lastfetchdate; // Last successful fetch
50
+    private $_rssarray = array();
51 51
 
52 52
     // For parsing with xmlparser
53 53
     var $stack               = array(); // parser stack
@@ -184,40 +184,40 @@  discard block
 block discarded – undo
184 184
      * 	@param	string	$cachedir	Directory where to save cache file
185 185
      *	@return	int					<0 if KO, >0 if OK
186 186
      */
187
-    public function parser($urlRSS, $maxNb=0, $cachedelay=60, $cachedir='')
187
+    public function parser($urlRSS, $maxNb = 0, $cachedelay = 60, $cachedir = '')
188 188
     {
189 189
         global $conf;
190 190
 
191 191
         include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
192 192
 
193
-        $rss='';
194
-        $str='';    // This will contain content of feed
193
+        $rss = '';
194
+        $str = ''; // This will contain content of feed
195 195
 
196 196
         // Check parameters
197
-        if (! dol_is_url($urlRSS))
197
+        if (!dol_is_url($urlRSS))
198 198
         {
199
-            $this->error="ErrorBadUrl";
199
+            $this->error = "ErrorBadUrl";
200 200
             return -1;
201 201
         }
202 202
 
203 203
         $this->_urlRSS = $urlRSS;
204
-        $newpathofdestfile=$cachedir.'/'.dol_hash($this->_urlRSS,3);	// Force md5 hash (does not contains special chars)
205
-        $newmask='0644';
204
+        $newpathofdestfile = $cachedir.'/'.dol_hash($this->_urlRSS, 3); // Force md5 hash (does not contains special chars)
205
+        $newmask = '0644';
206 206
 
207 207
         //dol_syslog("RssPArser::parser parse url=".$urlRSS." => cache file=".$newpathofdestfile);
208 208
         $nowgmt = dol_now();
209 209
 
210 210
         // Search into cache
211
-        $foundintocache=0;
211
+        $foundintocache = 0;
212 212
         if ($cachedelay > 0 && $cachedir)
213 213
         {
214
-            $filedate=dol_filemtime($newpathofdestfile);
214
+            $filedate = dol_filemtime($newpathofdestfile);
215 215
             if ($filedate >= ($nowgmt - $cachedelay))
216 216
             {
217 217
                 //dol_syslog("RssParser::parser cache file ".$newpathofdestfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we use it.");
218
-                $foundintocache=1;
218
+                $foundintocache = 1;
219 219
 
220
-                $this->_lastfetchdate=$filedate;
220
+                $this->_lastfetchdate = $filedate;
221 221
             }
222 222
             else
223 223
             {
@@ -233,13 +233,13 @@  discard block
 block discarded – undo
233 233
         else
234 234
         {
235 235
             try {
236
-                ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
236
+                ini_set("user_agent", "Dolibarr ERP-CRM RSS reader");
237 237
                 ini_set("max_execution_time", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
238 238
                 ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
239 239
 
240 240
                 $opts = array('http'=>array('method'=>"GET"));
241
-                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
242
-                if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
241
+                if (!empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout'] = $conf->global->MAIN_USE_CONNECT_TIMEOUT;
242
+                if (!empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy'] = 'tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
243 243
                 //var_dump($opts);exit;
244 244
                 $context = stream_context_create($opts);
245 245
 
@@ -253,7 +253,7 @@  discard block
 block discarded – undo
253 253
         if ($str !== false)
254 254
         {
255 255
 	        // Convert $str into xml
256
-	        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
256
+	        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
257 257
 	        {
258 258
 	            //print 'xx'.LIBXML_NOCDATA;
259 259
 	            libxml_use_internal_errors(false);
@@ -261,9 +261,9 @@  discard block
 block discarded – undo
261 261
 	        }
262 262
 	        else
263 263
 	        {
264
-	            $xmlparser=xml_parser_create('');
264
+	            $xmlparser = xml_parser_create('');
265 265
 	            if (!is_resource($xmlparser)) {
266
-	                $this->error="ErrorFailedToCreateParser"; return -1;
266
+	                $this->error = "ErrorFailedToCreateParser"; return -1;
267 267
 	            }
268 268
 
269 269
 	            xml_set_object($xmlparser, $this);
@@ -271,7 +271,7 @@  discard block
 block discarded – undo
271 271
 	            xml_set_character_data_handler($xmlparser, 'feed_cdata');
272 272
 	            $status = xml_parse($xmlparser, $str);
273 273
 	            xml_parser_free($xmlparser);
274
-	            $rss=$this;
274
+	            $rss = $this;
275 275
 	            //var_dump($rss->_format);exit;
276 276
 	        }
277 277
         }
@@ -283,16 +283,16 @@  discard block
 block discarded – undo
283 283
             if (empty($foundintocache) && $cachedir)
284 284
             {
285 285
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
286
-                if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
286
+                if (!dol_is_dir($cachedir)) dol_mkdir($cachedir);
287 287
                 $fp = fopen($newpathofdestfile, 'w');
288 288
                 if ($fp)
289 289
                 {
290 290
                 	fwrite($fp, $str);
291 291
                 	fclose($fp);
292
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
292
+                	if (!empty($conf->global->MAIN_UMASK)) $newmask = $conf->global->MAIN_UMASK;
293 293
                 	@chmod($newpathofdestfile, octdec($newmask));
294 294
 
295
-	                $this->_lastfetchdate=$nowgmt;
295
+	                $this->_lastfetchdate = $nowgmt;
296 296
                 }
297 297
                 else
298 298
                 {
@@ -300,21 +300,21 @@  discard block
 block discarded – undo
300 300
                 }
301 301
             }
302 302
 
303
-            unset($str);    // Free memory
303
+            unset($str); // Free memory
304 304
 
305 305
             if (empty($rss->_format))    // If format not detected automatically
306 306
             {
307
-                $rss->_format='rss';
308
-                if (empty($rss->channel)) $rss->_format='atom';
307
+                $rss->_format = 'rss';
308
+                if (empty($rss->channel)) $rss->_format = 'atom';
309 309
             }
310 310
 
311
-            $items=array();
311
+            $items = array();
312 312
 
313 313
             // Save description entries
314 314
             if ($rss->_format == 'rss')
315 315
             {
316 316
                 //var_dump($rss);
317
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
317
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
318 318
                 {
319 319
                     if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
320 320
                     if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
@@ -338,14 +338,14 @@  discard block
 block discarded – undo
338 338
                     if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
339 339
                 }
340 340
 
341
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
342
-                else $items=$rss->items;                                                              // With xmlparse
341
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items = $rss->channel->item; // With simplexml
342
+                else $items = $rss->items; // With xmlparse
343 343
                 //var_dump($items);exit;
344 344
             }
345 345
             else if ($rss->_format == 'atom')
346 346
             {
347 347
                 //var_dump($rss);
348
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
348
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
349 349
                 {
350 350
                     if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
351 351
                     if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
@@ -364,10 +364,10 @@  discard block
 block discarded – undo
364 364
                     if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
365 365
                     //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
366 366
                 }
367
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
368
-                    $tmprss=xml2php($rss); $items=$tmprss['entry'];
367
+                if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
368
+                    $tmprss = xml2php($rss); $items = $tmprss['entry'];
369 369
                 } // With simplexml
370
-                else $items=$rss->items;                                                              // With xmlparse
370
+                else $items = $rss->items; // With xmlparse
371 371
                 //var_dump($items);exit;
372 372
             }
373 373
 
@@ -376,12 +376,12 @@  discard block
 block discarded – undo
376 376
             // Loop on each record
377 377
             if (is_array($items))
378 378
             {
379
-                foreach($items as $item)
379
+                foreach ($items as $item)
380 380
                 {
381 381
                     //var_dump($item);exit;
382 382
                     if ($rss->_format == 'rss')
383 383
                     {
384
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
384
+                        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
385 385
                         {
386 386
                             $itemLink = (string) $item->link;
387 387
                             $itemTitle = (string) $item->title;
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
                         }
402 402
 
403 403
                         // Loop on each category
404
-                        $itemCategory=array();
404
+                        $itemCategory = array();
405 405
                         if (is_array($item->category))
406 406
                         {
407 407
                             foreach ($item->category as $cat)
@@ -412,14 +412,14 @@  discard block
 block discarded – undo
412 412
                     }
413 413
                     else if ($rss->_format == 'atom')
414 414
                     {
415
-                        if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
415
+                        if (!empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
416 416
                         {
417 417
                             $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
418 418
                             $itemTitle = (string) $item['title'];
419 419
                             $itemDescription = (string) $item['summary'];
420 420
                             $itemPubDate = (string) $item['created'];
421 421
                             $itemId = (string) $item['id'];
422
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
422
+                            $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
423 423
                         }
424 424
                         else
425 425
                         {
@@ -428,7 +428,7 @@  discard block
 block discarded – undo
428 428
                             $itemDescription = (string) $item['summary'];
429 429
                             $itemPubDate = (string) $item['created'];
430 430
                             $itemId = (string) $item['id'];
431
-                            $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
431
+                            $itemAuthor = (string) ($item['author'] ? $item['author'] : $item['author_name']);
432 432
                         }
433 433
                     }
434 434
                     else print 'ErrorBadFeedFormat';
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 
447 447
                     $i++;
448 448
 
449
-                    if ($i > $maxNb)    break;    // We get all records we want
449
+                    if ($i > $maxNb)    break; // We get all records we want
450 450
                 }
451 451
             }
452 452
 
@@ -454,7 +454,7 @@  discard block
 block discarded – undo
454 454
         }
455 455
         else
456 456
         {
457
-            $this->error='ErrorFailedToLoadRSSFile';
457
+            $this->error = 'ErrorFailedToLoadRSSFile';
458 458
             return -1;
459 459
         }
460 460
     }
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
         {
483 483
             list($ns, $el) = explode(':', $element, 2);
484 484
         }
485
-        if ( $ns and $ns != 'rdf' )
485
+        if ($ns and $ns != 'rdf')
486 486
         {
487 487
             $this->current_namespace = $ns;
488 488
         }
@@ -490,15 +490,15 @@  discard block
 block discarded – undo
490 490
         // if feed type isn't set, then this is first element of feed identify feed from root element
491 491
         if (empty($this->_format))
492 492
         {
493
-            if ( $el == 'rdf' ) {
493
+            if ($el == 'rdf') {
494 494
                 $this->_format = 'rss';
495 495
                 $this->feed_version = '1.0';
496 496
             }
497
-            elseif ( $el == 'rss' ) {
497
+            elseif ($el == 'rss') {
498 498
                 $this->_format = 'rss';
499 499
                 $this->feed_version = $attrs['version'];
500 500
             }
501
-            elseif ( $el == 'feed' ) {
501
+            elseif ($el == 'feed') {
502 502
                 $this->_format = 'atom';
503 503
                 $this->feed_version = $attrs['version'];
504 504
                 $this->inchannel = true;
@@ -506,14 +506,14 @@  discard block
 block discarded – undo
506 506
             return;
507 507
         }
508 508
 
509
-        if ( $el == 'channel' )
509
+        if ($el == 'channel')
510 510
         {
511 511
             $this->inchannel = true;
512 512
         }
513
-        elseif ($el == 'item' or $el == 'entry' )
513
+        elseif ($el == 'item' or $el == 'entry')
514 514
         {
515 515
             $this->initem = true;
516
-            if ( isset($attrs['rdf:about']) ) {
516
+            if (isset($attrs['rdf:about'])) {
517 517
                 $this->current_item['about'] = $attrs['rdf:about'];
518 518
             }
519 519
         }
@@ -537,10 +537,10 @@  discard block
 block discarded – undo
537 537
         }
538 538
 
539 539
         // handle atom content constructs
540
-        elseif ( $this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
540
+        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
541 541
         {
542 542
             // avoid clashing w/ RSS mod_content
543
-            if ($el == 'content' ) {
543
+            if ($el == 'content') {
544 544
                 $el = 'atom_content';
545 545
             }
546 546
 
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
         }
549 549
 
550 550
         // if inside an Atom content construct (e.g. content or summary) field treat tags as text
551
-        elseif ($this->_format == 'atom' and $this->incontent )
551
+        elseif ($this->_format == 'atom' and $this->incontent)
552 552
         {
553 553
             // if tags are inlined, then flatten
554 554
             $attrs_str = join(' ', array_map('map_attrs', array_keys($attrs), array_values($attrs)));
@@ -562,14 +562,14 @@  discard block
 block discarded – undo
562 562
         // Magpie treats link elements of type rel='alternate'
563 563
         // as being equivalent to RSS's simple link element.
564 564
         //
565
-        elseif ($this->_format == 'atom' and $el == 'link' )
565
+        elseif ($this->_format == 'atom' and $el == 'link')
566 566
         {
567
-            if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
567
+            if (isset($attrs['rel']) && $attrs['rel'] == 'alternate')
568 568
             {
569 569
                 $link_el = 'link';
570 570
             }
571 571
             else {
572
-                $link_el = 'link_' . $attrs['rel'];
572
+                $link_el = 'link_'.$attrs['rel'];
573 573
             }
574 574
 
575 575
             $this->append($link_el, $attrs['href']);
@@ -622,26 +622,26 @@  discard block
 block discarded – undo
622 622
             $this->current_item = array();
623 623
             $this->initem = false;
624 624
         }
625
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
625
+        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput')
626 626
         {
627 627
             $this->intextinput = false;
628 628
         }
629
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
629
+        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image')
630 630
         {
631 631
             $this->inimage = false;
632 632
         }
633
-        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
633
+        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS))
634 634
         {
635 635
             $this->incontent = false;
636 636
         }
637
-        elseif ($el == 'channel' or $el == 'feed' )
637
+        elseif ($el == 'channel' or $el == 'feed')
638 638
         {
639 639
             $this->inchannel = false;
640 640
         }
641
-        elseif ($this->_format == 'atom' and $this->incontent  ) {
641
+        elseif ($this->_format == 'atom' and $this->incontent) {
642 642
             // balance tags properly
643 643
             // note:  i don't think this is actually neccessary
644
-            if ( $this->stack[0] == $el )
644
+            if ($this->stack[0] == $el)
645 645
             {
646 646
                 $this->append_content("</$el>");
647 647
             }
@@ -666,10 +666,10 @@  discard block
 block discarded – undo
666 666
      *  @param	string	$str2		Str2
667 667
      *  @return	string				String cancatenated
668 668
      */
669
-    function concat(&$str1, $str2="")
669
+    function concat(&$str1, $str2 = "")
670 670
     {
671
-        if (!isset($str1) ) {
672
-            $str1="";
671
+        if (!isset($str1)) {
672
+            $str1 = "";
673 673
         }
674 674
         $str1 .= $str2;
675 675
     }
@@ -684,11 +684,11 @@  discard block
 block discarded – undo
684 684
     function append_content($text)
685 685
     {
686 686
         // phpcs:enable
687
-        if ( $this->initem ) {
688
-            $this->concat($this->current_item[ $this->incontent ], $text);
687
+        if ($this->initem) {
688
+            $this->concat($this->current_item[$this->incontent], $text);
689 689
         }
690
-        elseif ( $this->inchannel ) {
691
-            $this->concat($this->channel[ $this->incontent ], $text);
690
+        elseif ($this->inchannel) {
691
+            $this->concat($this->channel[$this->incontent], $text);
692 692
         }
693 693
     }
694 694
 
@@ -704,33 +704,33 @@  discard block
 block discarded – undo
704 704
         if (!$el) {
705 705
             return;
706 706
         }
707
-        if ( $this->current_namespace )
707
+        if ($this->current_namespace)
708 708
         {
709
-            if ( $this->initem ) {
710
-                $this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
709
+            if ($this->initem) {
710
+                $this->concat($this->current_item[$this->current_namespace][$el], $text);
711 711
             }
712 712
             elseif ($this->inchannel) {
713
-                $this->concat($this->channel[ $this->current_namespace][ $el ], $text);
713
+                $this->concat($this->channel[$this->current_namespace][$el], $text);
714 714
             }
715 715
             elseif ($this->intextinput) {
716
-                $this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
716
+                $this->concat($this->textinput[$this->current_namespace][$el], $text);
717 717
             }
718 718
             elseif ($this->inimage) {
719
-                $this->concat($this->image[ $this->current_namespace ][ $el ], $text);
719
+                $this->concat($this->image[$this->current_namespace][$el], $text);
720 720
             }
721 721
         }
722 722
         else {
723
-            if ( $this->initem ) {
724
-                $this->concat($this->current_item[ $el ], $text);
723
+            if ($this->initem) {
724
+                $this->concat($this->current_item[$el], $text);
725 725
             }
726 726
             elseif ($this->intextinput) {
727
-                $this->concat($this->textinput[ $el ], $text);
727
+                $this->concat($this->textinput[$el], $text);
728 728
             }
729 729
             elseif ($this->inimage) {
730
-                $this->concat($this->image[ $el ], $text);
730
+                $this->concat($this->image[$el], $text);
731 731
             }
732 732
             elseif ($this->inchannel) {
733
-                $this->concat($this->channel[ $el ], $text);
733
+                $this->concat($this->channel[$el], $text);
734 734
             }
735 735
         }
736 736
     }
@@ -748,18 +748,18 @@  discard block
 block discarded – undo
748 748
     $fils = 0;
749 749
     $tab = false;
750 750
     $array = array();
751
-    foreach($xml->children() as $key => $value)
751
+    foreach ($xml->children() as $key => $value)
752 752
     {
753 753
         $child = xml2php($value);
754 754
 
755 755
         //To deal with the attributes
756
-        foreach($value->attributes() as $ak=>$av)
756
+        foreach ($value->attributes() as $ak=>$av)
757 757
         {
758 758
             $child[$ak] = (string) $av;
759 759
         }
760 760
 
761 761
         //Let see if the new child is not in the array
762
-        if ($tab === false && in_array($key,array_keys($array)))
762
+        if ($tab === false && in_array($key, array_keys($array)))
763 763
         {
764 764
             //If this element is already in the array we will create an indexed array
765 765
             $tmp = $array[$key];
@@ -768,7 +768,7 @@  discard block
 block discarded – undo
768 768
             $array[$key][] = $child;
769 769
             $tab = true;
770 770
         }
771
-        elseif($tab === true)
771
+        elseif ($tab === true)
772 772
         {
773 773
             //Add an element in an existing array
774 774
             $array[$key][] = $child;
@@ -783,7 +783,7 @@  discard block
 block discarded – undo
783 783
     }
784 784
 
785 785
 
786
-    if ($fils==0)
786
+    if ($fils == 0)
787 787
     {
788 788
         return (string) $xml;
789 789
     }
Please login to merge, or discard this patch.
Braces   +148 added lines, -107 removed lines patch added patch discarded remove patch
@@ -218,19 +218,19 @@  discard block
 block discarded – undo
218 218
                 $foundintocache=1;
219 219
 
220 220
                 $this->_lastfetchdate=$filedate;
221
-            }
222
-            else
221
+            } else
223 222
             {
224 223
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is not found or older than now - cachedelay (".$nowgmt." - ".$cachedelay.") so we can't use it.");
225 224
             }
226 225
         }
227 226
 
228 227
         // Load file into $str
229
-        if ($foundintocache)    // Cache file found and is not too old
228
+        if ($foundintocache) {
229
+            // Cache file found and is not too old
230 230
         {
231 231
             $str = file_get_contents($newpathofdestfile);
232 232
         }
233
-        else
233
+        } else
234 234
         {
235 235
             try {
236 236
                 ini_set("user_agent","Dolibarr ERP-CRM RSS reader");
@@ -238,14 +238,17 @@  discard block
 block discarded – undo
238 238
                 ini_set("default_socket_timeout", $conf->global->MAIN_USE_RESPONSE_TIMEOUT);
239 239
 
240 240
                 $opts = array('http'=>array('method'=>"GET"));
241
-                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
242
-                if (! empty($conf->global->MAIN_PROXY_USE))           $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
241
+                if (! empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)) {
242
+                    $opts['http']['timeout']=$conf->global->MAIN_USE_CONNECT_TIMEOUT;
243
+                }
244
+                if (! empty($conf->global->MAIN_PROXY_USE)) {
245
+                    $opts['http']['proxy']='tcp://'.$conf->global->MAIN_PROXY_HOST.':'.$conf->global->MAIN_PROXY_PORT;
246
+                }
243 247
                 //var_dump($opts);exit;
244 248
                 $context = stream_context_create($opts);
245 249
 
246 250
                 $str = file_get_contents($this->_urlRSS, false, $context);
247
-            }
248
-            catch (Exception $e) {
251
+            } catch (Exception $e) {
249 252
                 print 'Error retrieving URL '.$this->urlRSS.' - '.$e->getMessage();
250 253
             }
251 254
         }
@@ -258,8 +261,7 @@  discard block
 block discarded – undo
258 261
 	            //print 'xx'.LIBXML_NOCDATA;
259 262
 	            libxml_use_internal_errors(false);
260 263
 	            $rss = simplexml_load_string($str, "SimpleXMLElement", LIBXML_NOCDATA);
261
-	        }
262
-	        else
264
+	        } else
263 265
 	        {
264 266
 	            $xmlparser=xml_parser_create('');
265 267
 	            if (!is_resource($xmlparser)) {
@@ -283,18 +285,21 @@  discard block
 block discarded – undo
283 285
             if (empty($foundintocache) && $cachedir)
284 286
             {
285 287
                 dol_syslog(get_class($this)."::parser cache file ".$newpathofdestfile." is saved onto disk.");
286
-                if (! dol_is_dir($cachedir)) dol_mkdir($cachedir);
288
+                if (! dol_is_dir($cachedir)) {
289
+                    dol_mkdir($cachedir);
290
+                }
287 291
                 $fp = fopen($newpathofdestfile, 'w');
288 292
                 if ($fp)
289 293
                 {
290 294
                 	fwrite($fp, $str);
291 295
                 	fclose($fp);
292
-                	if (! empty($conf->global->MAIN_UMASK)) $newmask=$conf->global->MAIN_UMASK;
296
+                	if (! empty($conf->global->MAIN_UMASK)) {
297
+                	    $newmask=$conf->global->MAIN_UMASK;
298
+                	}
293 299
                 	@chmod($newpathofdestfile, octdec($newmask));
294 300
 
295 301
 	                $this->_lastfetchdate=$nowgmt;
296
-                }
297
-                else
302
+                } else
298 303
                 {
299 304
                 	print 'Error, failed to open file '.$newpathofdestfile.' for write';
300 305
                 }
@@ -302,10 +307,14 @@  discard block
 block discarded – undo
302 307
 
303 308
             unset($str);    // Free memory
304 309
 
305
-            if (empty($rss->_format))    // If format not detected automatically
310
+            if (empty($rss->_format)) {
311
+                // If format not detected automatically
306 312
             {
307 313
                 $rss->_format='rss';
308
-                if (empty($rss->channel)) $rss->_format='atom';
314
+            }
315
+                if (empty($rss->channel)) {
316
+                    $rss->_format='atom';
317
+                }
309 318
             }
310 319
 
311 320
             $items=array();
@@ -316,58 +325,114 @@  discard block
 block discarded – undo
316 325
                 //var_dump($rss);
317 326
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
318 327
                 {
319
-                    if (!empty($rss->channel->language))      $this->_language = (string) $rss->channel->language;
320
-                    if (!empty($rss->channel->generator))     $this->_generator = (string) $rss->channel->generator;
321
-                    if (!empty($rss->channel->copyright))     $this->_copyright = (string) $rss->channel->copyright;
322
-                    if (!empty($rss->channel->lastbuilddate)) $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
323
-                    if (!empty($rss->channel->image->url[0])) $this->_imageurl = (string) $rss->channel->image->url[0];
324
-                    if (!empty($rss->channel->link))		  $this->_link = (string) $rss->channel->link;
325
-                    if (!empty($rss->channel->title))         $this->_title = (string) $rss->channel->title;
326
-                    if (!empty($rss->channel->description))	  $this->_description = (string) $rss->channel->description;
327
-                }
328
-                else
328
+                    if (!empty($rss->channel->language)) {
329
+                        $this->_language = (string) $rss->channel->language;
330
+                    }
331
+                    if (!empty($rss->channel->generator)) {
332
+                        $this->_generator = (string) $rss->channel->generator;
333
+                    }
334
+                    if (!empty($rss->channel->copyright)) {
335
+                        $this->_copyright = (string) $rss->channel->copyright;
336
+                    }
337
+                    if (!empty($rss->channel->lastbuilddate)) {
338
+                        $this->_lastbuilddate = (string) $rss->channel->lastbuilddate;
339
+                    }
340
+                    if (!empty($rss->channel->image->url[0])) {
341
+                        $this->_imageurl = (string) $rss->channel->image->url[0];
342
+                    }
343
+                    if (!empty($rss->channel->link)) {
344
+                        $this->_link = (string) $rss->channel->link;
345
+                    }
346
+                    if (!empty($rss->channel->title)) {
347
+                        $this->_title = (string) $rss->channel->title;
348
+                    }
349
+                    if (!empty($rss->channel->description)) {
350
+                        $this->_description = (string) $rss->channel->description;
351
+                    }
352
+                } else
329 353
                 {
330 354
                     //var_dump($rss->channel);
331
-                    if (!empty($rss->channel['language']))      $this->_language = (string) $rss->channel['language'];
332
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
333
-                    if (!empty($rss->channel['copyright']))     $this->_copyright = (string) $rss->channel['copyright'];
334
-                    if (!empty($rss->channel['lastbuilddate'])) $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
335
-                    if (!empty($rss->image['url']))             $this->_imageurl = (string) $rss->image['url'];
336
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
337
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
338
-                    if (!empty($rss->channel['description']))   $this->_description = (string) $rss->channel['description'];
355
+                    if (!empty($rss->channel['language'])) {
356
+                        $this->_language = (string) $rss->channel['language'];
357
+                    }
358
+                    if (!empty($rss->channel['generator'])) {
359
+                        $this->_generator = (string) $rss->channel['generator'];
360
+                    }
361
+                    if (!empty($rss->channel['copyright'])) {
362
+                        $this->_copyright = (string) $rss->channel['copyright'];
363
+                    }
364
+                    if (!empty($rss->channel['lastbuilddate'])) {
365
+                        $this->_lastbuilddate = (string) $rss->channel['lastbuilddate'];
366
+                    }
367
+                    if (!empty($rss->image['url'])) {
368
+                        $this->_imageurl = (string) $rss->image['url'];
369
+                    }
370
+                    if (!empty($rss->channel['link'])) {
371
+                        $this->_link = (string) $rss->channel['link'];
372
+                    }
373
+                    if (!empty($rss->channel['title'])) {
374
+                        $this->_title = (string) $rss->channel['title'];
375
+                    }
376
+                    if (!empty($rss->channel['description'])) {
377
+                        $this->_description = (string) $rss->channel['description'];
378
+                    }
339 379
                 }
340 380
 
341
-                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) $items=$rss->channel->item;    // With simplexml
342
-                else $items=$rss->items;                                                              // With xmlparse
381
+                if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML)) {
382
+                    $items=$rss->channel->item;
383
+                }
384
+                // With simplexml
385
+                else {
386
+                    $items=$rss->items;
387
+                }
388
+                // With xmlparse
343 389
                 //var_dump($items);exit;
344
-            }
345
-            else if ($rss->_format == 'atom')
390
+            } else if ($rss->_format == 'atom')
346 391
             {
347 392
                 //var_dump($rss);
348 393
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
349 394
                 {
350
-                    if (!empty($rss->generator))     $this->_generator = (string) $rss->generator;
351
-                    if (!empty($rss->lastbuilddate)) $this->_lastbuilddate = (string) $rss->modified;
352
-                    if (!empty($rss->link->href))    $this->_link = (string) $rss->link->href;
353
-                    if (!empty($rss->title))         $this->_title = (string) $rss->title;
354
-                    if (!empty($rss->description))	 $this->_description = (string) $rss->description;
355
-                }
356
-                else
395
+                    if (!empty($rss->generator)) {
396
+                        $this->_generator = (string) $rss->generator;
397
+                    }
398
+                    if (!empty($rss->lastbuilddate)) {
399
+                        $this->_lastbuilddate = (string) $rss->modified;
400
+                    }
401
+                    if (!empty($rss->link->href)) {
402
+                        $this->_link = (string) $rss->link->href;
403
+                    }
404
+                    if (!empty($rss->title)) {
405
+                        $this->_title = (string) $rss->title;
406
+                    }
407
+                    if (!empty($rss->description)) {
408
+                        $this->_description = (string) $rss->description;
409
+                    }
410
+                } else
357 411
                 {
358 412
                     //if (!empty($rss->channel['rss_language']))      $this->_language = (string) $rss->channel['rss_language'];
359
-                    if (!empty($rss->channel['generator']))     $this->_generator = (string) $rss->channel['generator'];
413
+                    if (!empty($rss->channel['generator'])) {
414
+                        $this->_generator = (string) $rss->channel['generator'];
415
+                    }
360 416
                     //if (!empty($rss->channel['rss_copyright']))     $this->_copyright = (string) $rss->channel['rss_copyright'];
361
-                    if (!empty($rss->channel['modified'])) $this->_lastbuilddate = (string) $rss->channel['modified'];
417
+                    if (!empty($rss->channel['modified'])) {
418
+                        $this->_lastbuilddate = (string) $rss->channel['modified'];
419
+                    }
362 420
                     //if (!empty($rss->image['rss_url']))             $this->_imageurl = (string) $rss->image['rss_url'];
363
-                    if (!empty($rss->channel['link']))		    $this->_link = (string) $rss->channel['link'];
364
-                    if (!empty($rss->channel['title']))         $this->_title = (string) $rss->channel['title'];
421
+                    if (!empty($rss->channel['link'])) {
422
+                        $this->_link = (string) $rss->channel['link'];
423
+                    }
424
+                    if (!empty($rss->channel['title'])) {
425
+                        $this->_title = (string) $rss->channel['title'];
426
+                    }
365 427
                     //if (!empty($rss->channel['rss_description']))   $this->_description = (string) $rss->channel['rss_description'];
366 428
                 }
367 429
                 if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))  {
368 430
                     $tmprss=xml2php($rss); $items=$tmprss['entry'];
369 431
                 } // With simplexml
370
-                else $items=$rss->items;                                                              // With xmlparse
432
+                else {
433
+                    $items=$rss->items;
434
+                }
435
+                // With xmlparse
371 436
                 //var_dump($items);exit;
372 437
             }
373 438
 
@@ -389,8 +454,7 @@  discard block
 block discarded – undo
389 454
                             $itemPubDate = (string) $item->pubDate;
390 455
                             $itemId = '';
391 456
                             $itemAuthor = '';
392
-                        }
393
-                        else
457
+                        } else
394 458
                         {
395 459
                             $itemLink = (string) $item['link'];
396 460
                             $itemTitle = (string) $item['title'];
@@ -409,8 +473,7 @@  discard block
 block discarded – undo
409 473
                                 $itemCategory[] = (string) $cat;
410 474
                             }
411 475
                         }
412
-                    }
413
-                    else if ($rss->_format == 'atom')
476
+                    } else if ($rss->_format == 'atom')
414 477
                     {
415 478
                         if (! empty($conf->global->EXTERNALRSS_USE_SIMPLEXML))
416 479
                         {
@@ -420,8 +483,7 @@  discard block
 block discarded – undo
420 483
                             $itemPubDate = (string) $item['created'];
421 484
                             $itemId = (string) $item['id'];
422 485
                             $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
423
-                        }
424
-                        else
486
+                        } else
425 487
                         {
426 488
                             $itemLink = (isset($item['link']['href']) ? (string) $item['link']['href'] : '');
427 489
                             $itemTitle = (string) $item['title'];
@@ -430,8 +492,9 @@  discard block
 block discarded – undo
430 492
                             $itemId = (string) $item['id'];
431 493
                             $itemAuthor = (string) ($item['author']?$item['author']:$item['author_name']);
432 494
                         }
495
+                    } else {
496
+                        print 'ErrorBadFeedFormat';
433 497
                     }
434
-                    else print 'ErrorBadFeedFormat';
435 498
 
436 499
                     // Add record to result array
437 500
                     $this->_rssarray[$i] = array(
@@ -446,13 +509,15 @@  discard block
 block discarded – undo
446 509
 
447 510
                     $i++;
448 511
 
449
-                    if ($i > $maxNb)    break;    // We get all records we want
512
+                    if ($i > $maxNb) {
513
+                        break;
514
+                    }
515
+                    // We get all records we want
450 516
                 }
451 517
             }
452 518
 
453 519
             return 1;
454
-        }
455
-        else
520
+        } else
456 521
         {
457 522
             $this->error='ErrorFailedToLoadRSSFile';
458 523
             return -1;
@@ -493,12 +558,10 @@  discard block
 block discarded – undo
493 558
             if ( $el == 'rdf' ) {
494 559
                 $this->_format = 'rss';
495 560
                 $this->feed_version = '1.0';
496
-            }
497
-            elseif ( $el == 'rss' ) {
561
+            } elseif ( $el == 'rss' ) {
498 562
                 $this->_format = 'rss';
499 563
                 $this->feed_version = $attrs['version'];
500
-            }
501
-            elseif ( $el == 'feed' ) {
564
+            } elseif ( $el == 'feed' ) {
502 565
                 $this->_format = 'atom';
503 566
                 $this->feed_version = $attrs['version'];
504 567
                 $this->inchannel = true;
@@ -509,8 +572,7 @@  discard block
 block discarded – undo
509 572
         if ( $el == 'channel' )
510 573
         {
511 574
             $this->inchannel = true;
512
-        }
513
-        elseif ($el == 'item' or $el == 'entry' )
575
+        } elseif ($el == 'item' or $el == 'entry' )
514 576
         {
515 577
             $this->initem = true;
516 578
             if ( isset($attrs['rdf:about']) ) {
@@ -526,9 +588,7 @@  discard block
 block discarded – undo
526 588
         $el == 'textinput' )
527 589
         {
528 590
             $this->intextinput = true;
529
-        }
530
-
531
-        elseif (
591
+        } elseif (
532 592
         $this->_format == 'rss' and
533 593
         $this->current_namespace == '' and
534 594
         $el == 'image' )
@@ -567,8 +627,7 @@  discard block
 block discarded – undo
567 627
             if ( isset($attrs['rel']) && $attrs['rel'] == 'alternate' )
568 628
             {
569 629
                 $link_el = 'link';
570
-            }
571
-            else {
630
+            } else {
572 631
                 $link_el = 'link_' . $attrs['rel'];
573 632
             }
574 633
 
@@ -595,8 +654,7 @@  discard block
 block discarded – undo
595 654
         if ($this->_format == 'atom' and $this->incontent)
596 655
         {
597 656
             $this->append_content($text);
598
-        }
599
-        else
657
+        } else
600 658
         {
601 659
             $current_el = join('_', array_reverse($this->stack));
602 660
             $this->append($current_el, $text);
@@ -621,37 +679,30 @@  discard block
 block discarded – undo
621 679
             $this->items[] = $this->current_item;
622 680
             $this->current_item = array();
623 681
             $this->initem = false;
624
-        }
625
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
682
+        } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'textinput' )
626 683
         {
627 684
             $this->intextinput = false;
628
-        }
629
-        elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
685
+        } elseif ($this->_format == 'rss' and $this->current_namespace == '' and $el == 'image' )
630 686
         {
631 687
             $this->inimage = false;
632
-        }
633
-        elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
688
+        } elseif ($this->_format == 'atom' and in_array($el, $this->_CONTENT_CONSTRUCTS) )
634 689
         {
635 690
             $this->incontent = false;
636
-        }
637
-        elseif ($el == 'channel' or $el == 'feed' )
691
+        } elseif ($el == 'channel' or $el == 'feed' )
638 692
         {
639 693
             $this->inchannel = false;
640
-        }
641
-        elseif ($this->_format == 'atom' and $this->incontent  ) {
694
+        } elseif ($this->_format == 'atom' and $this->incontent  ) {
642 695
             // balance tags properly
643 696
             // note:  i don't think this is actually neccessary
644 697
             if ( $this->stack[0] == $el )
645 698
             {
646 699
                 $this->append_content("</$el>");
647
-            }
648
-            else {
700
+            } else {
649 701
                 $this->append_content("<$el />");
650 702
             }
651 703
 
652 704
             array_shift($this->stack);
653
-        }
654
-        else {
705
+        } else {
655 706
             array_shift($this->stack);
656 707
         }
657 708
 
@@ -686,8 +737,7 @@  discard block
 block discarded – undo
686 737
         // phpcs:enable
687 738
         if ( $this->initem ) {
688 739
             $this->concat($this->current_item[ $this->incontent ], $text);
689
-        }
690
-        elseif ( $this->inchannel ) {
740
+        } elseif ( $this->inchannel ) {
691 741
             $this->concat($this->channel[ $this->incontent ], $text);
692 742
         }
693 743
     }
@@ -708,28 +758,21 @@  discard block
 block discarded – undo
708 758
         {
709 759
             if ( $this->initem ) {
710 760
                 $this->concat($this->current_item[ $this->current_namespace ][ $el ], $text);
711
-            }
712
-            elseif ($this->inchannel) {
761
+            } elseif ($this->inchannel) {
713 762
                 $this->concat($this->channel[ $this->current_namespace][ $el ], $text);
714
-            }
715
-            elseif ($this->intextinput) {
763
+            } elseif ($this->intextinput) {
716 764
                 $this->concat($this->textinput[ $this->current_namespace][ $el ], $text);
717
-            }
718
-            elseif ($this->inimage) {
765
+            } elseif ($this->inimage) {
719 766
                 $this->concat($this->image[ $this->current_namespace ][ $el ], $text);
720 767
             }
721
-        }
722
-        else {
768
+        } else {
723 769
             if ( $this->initem ) {
724 770
                 $this->concat($this->current_item[ $el ], $text);
725
-            }
726
-            elseif ($this->intextinput) {
771
+            } elseif ($this->intextinput) {
727 772
                 $this->concat($this->textinput[ $el ], $text);
728
-            }
729
-            elseif ($this->inimage) {
773
+            } elseif ($this->inimage) {
730 774
                 $this->concat($this->image[ $el ], $text);
731
-            }
732
-            elseif ($this->inchannel) {
775
+            } elseif ($this->inchannel) {
733 776
                 $this->concat($this->channel[ $el ], $text);
734 777
             }
735 778
         }
@@ -767,13 +810,11 @@  discard block
 block discarded – undo
767 810
             $array[$key][] = $tmp;
768 811
             $array[$key][] = $child;
769 812
             $tab = true;
770
-        }
771
-        elseif($tab === true)
813
+        } elseif($tab === true)
772 814
         {
773 815
             //Add an element in an existing array
774 816
             $array[$key][] = $child;
775
-        }
776
-        else
817
+        } else
777 818
         {
778 819
             //Add a simple element
779 820
             $array[$key] = $child;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/genericobject.class.php 1 patch
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@  discard block
 block discarded – undo
20 20
  *	\ingroup    core
21 21
  *	\brief      File of class of generic business class
22 22
  */
23
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
23
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
24 24
 
25 25
 
26 26
 /**
@@ -36,6 +36,6 @@  discard block
 block discarded – undo
36 36
      */
37 37
     function __construct($db)
38 38
     {
39
-        $this->db=$db;
39
+        $this->db = $db;
40 40
     }
41 41
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/menu.class.php 3 patches
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -31,11 +31,11 @@  discard block
 block discarded – undo
31 31
     var $liste;
32 32
 
33 33
     /**
34
-	 *	Constructor
34
+     *	Constructor
35 35
      */
36 36
     function __construct()
37 37
     {
38
-      	$this->liste = array();
38
+            $this->liste = array();
39 39
     }
40 40
 
41 41
     /**
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
      */
68 68
     function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
69 69
     {
70
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
70
+        $this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
71 71
     }
72 72
 
73 73
     /**
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
      * @param	string	$prefix		Prefix to title (image or picto)
66 66
      * @return	void
67 67
      */
68
-    function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
68
+    function add($url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
69 69
     {
70
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
70
+    	$this->liste[] = array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
71 71
     }
72 72
 
73 73
     /**
@@ -88,12 +88,12 @@  discard block
 block discarded – undo
88 88
      * @param	string	$prefix		Prefix to title (image or picto)
89 89
      * @return	void
90 90
      */
91
-    function insert($idafter, $url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
91
+    function insert($idafter, $url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
92 92
     {
93
-        $array_start = array_slice($this->liste,0,($idafter+1));
94
-        $array_new   = array(0=>array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu,'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
95
-        $array_end   = array_slice($this->liste,($idafter+1));
96
-        $this->liste=array_merge($array_start,$array_new,$array_end);
93
+        $array_start = array_slice($this->liste, 0, ($idafter + 1));
94
+        $array_new   = array(0=>array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
95
+        $array_end   = array_slice($this->liste, ($idafter + 1));
96
+        $this->liste = array_merge($array_start, $array_new, $array_end);
97 97
     }
98 98
 
99 99
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -117,10 +117,10 @@  discard block
 block discarded – undo
117 117
      */
118 118
     function getNbOfVisibleMenuEntries()
119 119
     {
120
-        $nb=0;
121
-        foreach($this->liste as $val)
120
+        $nb = 0;
121
+        foreach ($this->liste as $val)
122 122
         {
123
-            if (! empty($val['enabled'])) $nb++;
123
+            if (!empty($val['enabled'])) $nb++;
124 124
         }
125 125
         return $nb;
126 126
     }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,9 @@
 block discarded – undo
120 120
         $nb=0;
121 121
         foreach($this->liste as $val)
122 122
         {
123
-            if (! empty($val['enabled'])) $nb++;
123
+            if (! empty($val['enabled'])) {
124
+                $nb++;
125
+            }
124 126
         }
125 127
         return $nb;
126 128
     }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/CMailFile.class.php 3 patches
Indentation   +1425 added lines, -1425 removed lines patch added patch discarded remove patch
@@ -36,323 +36,323 @@  discard block
 block discarded – undo
36 36
  */
37 37
 class CMailFile
38 38
 {
39
-	public $sendcontext;
40
-	public $sendmode;
41
-	public $sendsetup;
42
-
43
-	var $subject;      	// Topic:       Subject of email
44
-	var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45
-	// Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46
-	//              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47
-	// Return-Path: Email where to send bounds.
48
-	var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
-	var $errors_to;		// Errors-To:	Email where to send errors.
50
-	var $addr_to;
51
-	var $addr_cc;
52
-	var $addr_bcc;
53
-	var $trackid;
54
-
55
-	var $mixed_boundary;
56
-	var $related_boundary;
57
-	var $alternative_boundary;
58
-	var $deliveryreceipt;
59
-
60
-	var $eol;
61
-	var $eol2;
62
-
63
-	/**
64
-	 * @var string Error code (or message)
65
-	 */
66
-	public $error='';
67
-
68
-	var $smtps;			// Contains SMTPs object (if this method is used)
69
-	var $phpmailer;		// Contains PHPMailer object (if this method is used)
70
-
71
-	/**
72
-	 * @var string CSS
73
-	 */
74
-	public $css;
75
-	//! Defined css style for body background
76
-	var $styleCSS;
77
-	//! Defined background directly in body tag
78
-	var $bodyCSS;
79
-
80
-	var $headers;
81
-	var $message;
82
-
83
-	// Image
84
-	var $html;
85
-	var $image_boundary;
86
-	var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
-	var $html_images=array();
88
-	var $images_encoded=array();
89
-	var $image_types = array(
39
+    public $sendcontext;
40
+    public $sendmode;
41
+    public $sendsetup;
42
+
43
+    var $subject;      	// Topic:       Subject of email
44
+    var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45
+    // Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46
+    //              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47
+    // Return-Path: Email where to send bounds.
48
+    var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
+    var $errors_to;		// Errors-To:	Email where to send errors.
50
+    var $addr_to;
51
+    var $addr_cc;
52
+    var $addr_bcc;
53
+    var $trackid;
54
+
55
+    var $mixed_boundary;
56
+    var $related_boundary;
57
+    var $alternative_boundary;
58
+    var $deliveryreceipt;
59
+
60
+    var $eol;
61
+    var $eol2;
62
+
63
+    /**
64
+     * @var string Error code (or message)
65
+     */
66
+    public $error='';
67
+
68
+    var $smtps;			// Contains SMTPs object (if this method is used)
69
+    var $phpmailer;		// Contains PHPMailer object (if this method is used)
70
+
71
+    /**
72
+     * @var string CSS
73
+     */
74
+    public $css;
75
+    //! Defined css style for body background
76
+    var $styleCSS;
77
+    //! Defined background directly in body tag
78
+    var $bodyCSS;
79
+
80
+    var $headers;
81
+    var $message;
82
+
83
+    // Image
84
+    var $html;
85
+    var $image_boundary;
86
+    var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
+    var $html_images=array();
88
+    var $images_encoded=array();
89
+    var $image_types = array(
90 90
         'gif'  => 'image/gif',
91
-		'jpg'  => 'image/jpeg',
92
-		'jpeg' => 'image/jpeg',
93
-		'jpe'  => 'image/jpeg',
94
-		'bmp'  => 'image/bmp',
95
-		'png'  => 'image/png',
96
-		'tif'  => 'image/tiff',
91
+        'jpg'  => 'image/jpeg',
92
+        'jpeg' => 'image/jpeg',
93
+        'jpe'  => 'image/jpeg',
94
+        'bmp'  => 'image/bmp',
95
+        'png'  => 'image/png',
96
+        'tif'  => 'image/tiff',
97 97
         'tiff' => 'image/tiff',
98 98
     );
99 99
 
100 100
 
101
-	/**
102
-	 *	CMailFile
103
-	 *
104
-	 *	@param 	string	$subject             Topic/Subject of mail
105
-	 *	@param 	string	$to                  Recipients emails (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]"). Note: the keyword '__SUPERVISOREMAIL__' is not allowed here and must be replaced by caller.
106
-	 *	@param 	string	$from                Sender email      (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
107
-	 *	@param 	string	$msg                 Message
108
-	 *	@param 	array	$filename_list       List of files to attach (full path of filename on file system)
109
-	 *	@param 	array	$mimetype_list       List of MIME type of attached files
110
-	 *	@param 	array	$mimefilename_list   List of attached file name in message
111
-	 *	@param 	string	$addr_cc             Email cc
112
-	 *	@param 	string	$addr_bcc            Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
113
-	 *	@param 	int		$deliveryreceipt     Ask a delivery receipt
114
-	 *	@param 	int		$msgishtml           1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
115
-	 *	@param 	string	$errors_to      	 Email for errors-to
116
-	 *	@param	string	$css                 Css option
117
-	 *	@param	string	$trackid             Tracking string (contains type and id of related element)
118
-	 *  @param  string  $moreinheader        More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment)
119
-	 *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120
-	 *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121
-	 */
122
-	function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
123
-	{
124
-		global $conf, $dolibarr_main_data_root;
125
-
126
-		$this->sendcontext = $sendcontext;
127
-
128
-		if (empty($replyto)) $replyto=$from;
129
-
130
-		// Define this->sendmode
131
-		$this->sendmode = '';
132
-		if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
133
-		{
134
-			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135
-		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
138
-
139
-		// We define end of line (RFC 821).
140
-		$this->eol="\r\n";
141
-		// We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
-		$this->eol2="\r\n";
143
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144
-		{
145
-			$this->eol="\n";
146
-			$this->eol2="\n";
147
-			$moreinheader = str_replace("\r\n","\n",$moreinheader);
148
-		}
149
-
150
-		// On defini mixed_boundary
151
-		$this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
152
-
153
-		// On defini related_boundary
154
-		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
155
-
156
-		// On defini alternative_boundary
157
-		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
158
-
159
-		dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160
-		dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
161
-
162
-		if (empty($subject))
163
-		{
164
-			dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
-			$this->error='ErrorSubjectIsRequired';
166
-			return;
167
-		}
168
-		if (empty($msg))
169
-		{
170
-		    dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
-		    $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
172
-		}
173
-
174
-		// Detect if message is HTML (use fast method)
175
-		if ($msgishtml == -1)
176
-		{
177
-			$this->msgishtml = 0;
178
-			if (dol_textishtml($msg)) $this->msgishtml = 1;
179
-		}
180
-		else
181
-		{
182
-			$this->msgishtml = $msgishtml;
183
-		}
184
-
185
-		global $dolibarr_main_url_root;
186
-
187
-		// Define $urlwithroot
188
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
190
-		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191
-
192
-		// Replace relative /viewimage to absolute path
193
-		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194
-
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
196
-
197
-		// Detect images
198
-		if ($this->msgishtml)
199
-		{
200
-			$this->html = $msg;
201
-
202
-			if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203
-			{
204
-				$findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205
-			}
206
-
207
-			// Define if there is at least one file
208
-			if ($findimg)
209
-			{
210
-				foreach ($this->html_images as $i => $val)
211
-				{
212
-					if ($this->html_images[$i])
213
-					{
214
-						$this->atleastoneimage=1;
215
-						dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		// Define if there is at least one file
222
-		if (is_array($filename_list))
223
-		{
224
-			foreach ($filename_list as $i => $val)
225
-			{
226
-				if ($filename_list[$i])
227
-				{
228
-					$this->atleastonefile=1;
229
-					dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230
-				}
231
-			}
232
-		}
233
-
234
-		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236
-
237
-		// Action according to choosed sending method
238
-		if ($this->sendmode == 'mail')
239
-		{
240
-			// Use mail php function (default PHP method)
241
-			// ------------------------------------------
242
-
243
-			$smtp_headers = "";
244
-			$mime_headers = "";
245
-			$text_body = "";
246
-			$files_encoded = "";
247
-
248
-			// Define smtp_headers
249
-			$this->subject = $subject;
250
-			$this->addr_from = $from;
251
-			$this->reply_to = $replyto;
252
-			$this->errors_to = $errors_to;
253
-			$this->addr_to = $to;
254
-			$this->addr_cc = $addr_cc;
255
-			$this->addr_bcc = $addr_bcc;
256
-			$this->deliveryreceipt = $deliveryreceipt;
257
-			$this->trackid = $trackid;
258
-
259
-			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
261
-
262
-			// Define mime_headers
263
-			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264
-
265
-			if (! empty($this->html))
266
-			{
267
-				if (!empty($css))
268
-				{
269
-					$this->css = $css;
270
-					$this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271
-				}
272
-
273
-				$msg = $this->html;
274
-			}
275
-
276
-			// Define body in text_body
277
-			$text_body = $this->write_body($msg);
278
-
279
-			// Add attachments to text_encoded
280
-			if ($this->atleastonefile)
281
-			{
282
-				$files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
283
-			}
284
-
285
-			// We now define $this->headers and $this->message
286
-			$this->headers = $smtp_headers . $mime_headers;
287
-			// On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288
-			// Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289
-			// comme des injections mail par les serveurs de messagerie.
290
-			$this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
291
-
292
-			//$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293
-			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
-			$this->message.= $text_body . $files_encoded;
295
-			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
-		}
297
-		else if ($this->sendmode == 'smtps')
298
-		{
299
-			// Use SMTPS library
300
-			// ------------------------------------------
301
-
302
-			require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
303
-			$smtps = new SMTPs();
304
-			$smtps->setCharSet($conf->file->character_set_client);
305
-
306
-			$smtps->setSubject($this->encodetorfc2822($subject));
307
-			$smtps->setTO($this->getValidAddress($to,0,1));
308
-			$smtps->setFrom($this->getValidAddress($from,0,1));
309
-			$smtps->setTrackId($trackid);
310
-			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311
-
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313
-
314
-			if (! empty($this->html))
315
-			{
316
-				if (!empty($css))
317
-				{
318
-					$this->css = $css;
319
-					$this->buildCSS();
320
-				}
321
-				$msg = $this->html;
322
-				$msg = $this->checkIfHTML($msg);
323
-			}
324
-
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
327
-
328
-			if ($this->atleastoneimage)
329
-			{
330
-				foreach ($this->images_encoded as $img)
331
-				{
332
-					$smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
333
-				}
334
-			}
335
-
336
-			if ($this->atleastonefile)
337
-			{
338
-				foreach ($filename_list as $i => $val)
339
-				{
340
-					$content=file_get_contents($filename_list[$i]);
341
-					$smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
342
-				}
343
-			}
344
-
345
-			$smtps->setCC($addr_cc);
346
-			$smtps->setBCC($addr_bcc);
347
-			$smtps->setErrorsTo($errors_to);
348
-			$smtps->setDeliveryReceipt($deliveryreceipt);
349
-
350
-			$this->smtps=$smtps;
351
-		}
352
-		else if ($this->sendmode == 'swiftmailer')
353
-		{
354
-			// Use Swift Mailer library
355
-			// ------------------------------------------
101
+    /**
102
+     *	CMailFile
103
+     *
104
+     *	@param 	string	$subject             Topic/Subject of mail
105
+     *	@param 	string	$to                  Recipients emails (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]"). Note: the keyword '__SUPERVISOREMAIL__' is not allowed here and must be replaced by caller.
106
+     *	@param 	string	$from                Sender email      (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
107
+     *	@param 	string	$msg                 Message
108
+     *	@param 	array	$filename_list       List of files to attach (full path of filename on file system)
109
+     *	@param 	array	$mimetype_list       List of MIME type of attached files
110
+     *	@param 	array	$mimefilename_list   List of attached file name in message
111
+     *	@param 	string	$addr_cc             Email cc
112
+     *	@param 	string	$addr_bcc            Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
113
+     *	@param 	int		$deliveryreceipt     Ask a delivery receipt
114
+     *	@param 	int		$msgishtml           1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
115
+     *	@param 	string	$errors_to      	 Email for errors-to
116
+     *	@param	string	$css                 Css option
117
+     *	@param	string	$trackid             Tracking string (contains type and id of related element)
118
+     *  @param  string  $moreinheader        More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment)
119
+     *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120
+     *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121
+     */
122
+    function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
123
+    {
124
+        global $conf, $dolibarr_main_data_root;
125
+
126
+        $this->sendcontext = $sendcontext;
127
+
128
+        if (empty($replyto)) $replyto=$from;
129
+
130
+        // Define this->sendmode
131
+        $this->sendmode = '';
132
+        if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
133
+        {
134
+            $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135
+        }
136
+        if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
+        if (empty($this->sendmode)) $this->sendmode='mail';
138
+
139
+        // We define end of line (RFC 821).
140
+        $this->eol="\r\n";
141
+        // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
+        $this->eol2="\r\n";
143
+        if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144
+        {
145
+            $this->eol="\n";
146
+            $this->eol2="\n";
147
+            $moreinheader = str_replace("\r\n","\n",$moreinheader);
148
+        }
149
+
150
+        // On defini mixed_boundary
151
+        $this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
152
+
153
+        // On defini related_boundary
154
+        $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
155
+
156
+        // On defini alternative_boundary
157
+        $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
158
+
159
+        dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160
+        dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
161
+
162
+        if (empty($subject))
163
+        {
164
+            dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
+            $this->error='ErrorSubjectIsRequired';
166
+            return;
167
+        }
168
+        if (empty($msg))
169
+        {
170
+            dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
+            $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
172
+        }
173
+
174
+        // Detect if message is HTML (use fast method)
175
+        if ($msgishtml == -1)
176
+        {
177
+            $this->msgishtml = 0;
178
+            if (dol_textishtml($msg)) $this->msgishtml = 1;
179
+        }
180
+        else
181
+        {
182
+            $this->msgishtml = $msgishtml;
183
+        }
184
+
185
+        global $dolibarr_main_url_root;
186
+
187
+        // Define $urlwithroot
188
+        $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
+        $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
190
+        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191
+
192
+        // Replace relative /viewimage to absolute path
193
+        $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194
+
195
+        if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
196
+
197
+        // Detect images
198
+        if ($this->msgishtml)
199
+        {
200
+            $this->html = $msg;
201
+
202
+            if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203
+            {
204
+                $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205
+            }
206
+
207
+            // Define if there is at least one file
208
+            if ($findimg)
209
+            {
210
+                foreach ($this->html_images as $i => $val)
211
+                {
212
+                    if ($this->html_images[$i])
213
+                    {
214
+                        $this->atleastoneimage=1;
215
+                        dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        // Define if there is at least one file
222
+        if (is_array($filename_list))
223
+        {
224
+            foreach ($filename_list as $i => $val)
225
+            {
226
+                if ($filename_list[$i])
227
+                {
228
+                    $this->atleastonefile=1;
229
+                    dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230
+                }
231
+            }
232
+        }
233
+
234
+        // Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
+        if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236
+
237
+        // Action according to choosed sending method
238
+        if ($this->sendmode == 'mail')
239
+        {
240
+            // Use mail php function (default PHP method)
241
+            // ------------------------------------------
242
+
243
+            $smtp_headers = "";
244
+            $mime_headers = "";
245
+            $text_body = "";
246
+            $files_encoded = "";
247
+
248
+            // Define smtp_headers
249
+            $this->subject = $subject;
250
+            $this->addr_from = $from;
251
+            $this->reply_to = $replyto;
252
+            $this->errors_to = $errors_to;
253
+            $this->addr_to = $to;
254
+            $this->addr_cc = $addr_cc;
255
+            $this->addr_bcc = $addr_bcc;
256
+            $this->deliveryreceipt = $deliveryreceipt;
257
+            $this->trackid = $trackid;
258
+
259
+            $smtp_headers = $this->write_smtpheaders();
260
+            if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
261
+
262
+            // Define mime_headers
263
+            $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264
+
265
+            if (! empty($this->html))
266
+            {
267
+                if (!empty($css))
268
+                {
269
+                    $this->css = $css;
270
+                    $this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271
+                }
272
+
273
+                $msg = $this->html;
274
+            }
275
+
276
+            // Define body in text_body
277
+            $text_body = $this->write_body($msg);
278
+
279
+            // Add attachments to text_encoded
280
+            if ($this->atleastonefile)
281
+            {
282
+                $files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
283
+            }
284
+
285
+            // We now define $this->headers and $this->message
286
+            $this->headers = $smtp_headers . $mime_headers;
287
+            // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288
+            // Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289
+            // comme des injections mail par les serveurs de messagerie.
290
+            $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
291
+
292
+            //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293
+            $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
+            $this->message.= $text_body . $files_encoded;
295
+            $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
+        }
297
+        else if ($this->sendmode == 'smtps')
298
+        {
299
+            // Use SMTPS library
300
+            // ------------------------------------------
301
+
302
+            require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
303
+            $smtps = new SMTPs();
304
+            $smtps->setCharSet($conf->file->character_set_client);
305
+
306
+            $smtps->setSubject($this->encodetorfc2822($subject));
307
+            $smtps->setTO($this->getValidAddress($to,0,1));
308
+            $smtps->setFrom($this->getValidAddress($from,0,1));
309
+            $smtps->setTrackId($trackid);
310
+            $smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311
+
312
+            if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313
+
314
+            if (! empty($this->html))
315
+            {
316
+                if (!empty($css))
317
+                {
318
+                    $this->css = $css;
319
+                    $this->buildCSS();
320
+                }
321
+                $msg = $this->html;
322
+                $msg = $this->checkIfHTML($msg);
323
+            }
324
+
325
+            if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
+            else $smtps->setBodyContent($msg,'plain');
327
+
328
+            if ($this->atleastoneimage)
329
+            {
330
+                foreach ($this->images_encoded as $img)
331
+                {
332
+                    $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
333
+                }
334
+            }
335
+
336
+            if ($this->atleastonefile)
337
+            {
338
+                foreach ($filename_list as $i => $val)
339
+                {
340
+                    $content=file_get_contents($filename_list[$i]);
341
+                    $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
342
+                }
343
+            }
344
+
345
+            $smtps->setCC($addr_cc);
346
+            $smtps->setBCC($addr_bcc);
347
+            $smtps->setErrorsTo($errors_to);
348
+            $smtps->setDeliveryReceipt($deliveryreceipt);
349
+
350
+            $this->smtps=$smtps;
351
+        }
352
+        else if ($this->sendmode == 'swiftmailer')
353
+        {
354
+            // Use Swift Mailer library
355
+            // ------------------------------------------
356 356
 
357 357
             $host = dol_getprefix('email');
358 358
 
@@ -361,419 +361,419 @@  discard block
 block discarded – undo
361 361
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php';
362 362
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php';
363 363
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php';
364
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php';
365
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php';
366
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php';
367
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php';
368
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php';
369
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php';
370
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php';
371
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php';
372
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php';
364
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php';
365
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php';
366
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php';
367
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php';
368
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php';
369
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php';
370
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php';
371
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php';
372
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php';
373 373
 
374 374
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/InputByteStream.php';
375
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php';
376
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php';
377
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php';
378
-			//require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php';
379
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
380
-			// Create the message
381
-			//$this->message = Swift_Message::newInstance();
382
-			$this->message = new Swift_Message();
375
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php';
376
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php';
377
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php';
378
+            //require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php';
379
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
380
+            // Create the message
381
+            //$this->message = Swift_Message::newInstance();
382
+            $this->message = new Swift_Message();
383 383
             //$this->message = new Swift_SignedMessage();
384 384
             // Adding a trackid header to a message
385
-			$headers = $this->message->getHeaders();
386
-			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
-			$headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
388
-			$msgid = $headers->get('Message-ID');
389
-			$msgid->setId($headerID);
390
-			$headers->addIdHeader('References', $headerID);
391
-			// TODO if (! empty($moreinheader)) ...
392
-
393
-			// Give the message a subject
394
-			try {
395
-				$result = $this->message->setSubject($subject);
396
-			} catch (Exception $e) {
397
-				$this->errors[] =  $e->getMessage();
398
-			}
399
-
400
-			// Set the From address with an associative array
401
-			//$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
-			if (! empty($from)) {
385
+            $headers = $this->message->getHeaders();
386
+            $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
+            $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
388
+            $msgid = $headers->get('Message-ID');
389
+            $msgid->setId($headerID);
390
+            $headers->addIdHeader('References', $headerID);
391
+            // TODO if (! empty($moreinheader)) ...
392
+
393
+            // Give the message a subject
394
+            try {
395
+                $result = $this->message->setSubject($subject);
396
+            } catch (Exception $e) {
397
+                $this->errors[] =  $e->getMessage();
398
+            }
399
+
400
+            // Set the From address with an associative array
401
+            //$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
+            if (! empty($from)) {
403 403
                 try {
404
-                	$result = $this->message->setFrom($this->getArrayAddress($from));
404
+                    $result = $this->message->setFrom($this->getArrayAddress($from));
405 405
                 } catch (Exception $e) {
406 406
                     $this->errors[] = $e->getMessage();
407 407
                 }
408 408
             }
409 409
 
410
-			// Set the To addresses with an associative array
411
-			if (! empty($to)) {
410
+            // Set the To addresses with an associative array
411
+            if (! empty($to)) {
412 412
                 try {
413
-                	$result = $this->message->setTo($this->getArrayAddress($to));
413
+                    $result = $this->message->setTo($this->getArrayAddress($to));
414 414
                 } catch (Exception $e) {
415 415
                     $this->errors[] = $e->getMessage();
416 416
                 }
417 417
             }
418 418
 
419
-			if (! empty($replyto)) {
419
+            if (! empty($replyto)) {
420 420
                 try {
421
-                	$result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
421
+                    $result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
422 422
                 } catch (Exception $e) {
423 423
                     $this->errors[] = $e->getMessage();
424 424
                 }
425 425
             }
426 426
 
427
-			try {
428
-				$result = $this->message->setCharSet($conf->file->character_set_client);
429
-			} catch (Exception $e) {
430
-				$this->errors[] =  $e->getMessage();
431
-			}
432
-
433
-			if (! empty($this->html))
434
-			{
435
-				if (!empty($css))
436
-				{
437
-					$this->css = $css;
438
-					$this->buildCSS();
439
-				}
440
-				$msg = $this->html;
441
-				$msg = $this->checkIfHTML($msg);
442
-			}
443
-
444
-			if ($this->atleastoneimage)
445
-			{
446
-				foreach ($this->images_encoded as $img)
447
-				{
448
-					//$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
449
-					$attachment = Swift_Image::fromPath($img['fullpath'], $img['content_type']);
450
-					// embed image
451
-					$imgcid = $this->message->embed($attachment);
452
-					// replace cid by the one created by swiftmail in html message
453
-					$msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
454
-				}
455
-			}
456
-
457
-			if ($this->msgishtml) {
458
-				$this->message->setBody($msg,'text/html');
459
-				// And optionally an alternative body
460
-				$this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461
-			} else {
462
-				$this->message->setBody($msg,'text/plain');
463
-				// And optionally an alternative body
464
-				$this->message->addPart($msg, 'text/html');
465
-			}
466
-
467
-			if ($this->atleastonefile)
468
-			{
469
-				foreach ($filename_list as $i => $val)
470
-				{
471
-					//$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
-					$attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
473
-					$this->message->attach($attachment);
474
-				}
475
-			}
476
-
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479
-			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
-			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
-		}
482
-		else
483
-		{
484
-			// Send mail method not correctly defined
485
-			// --------------------------------------
486
-			$this->error = 'Bad value for sendmode';
487
-		}
488
-	}
489
-
490
-
491
-	/**
492
-	 * Send mail that was prepared by constructor.
493
-	 *
494
-	 * @return    boolean     True if mail sent, false otherwise
495
-	 */
496
-	function sendfile()
497
-	{
498
-		global $conf,$db,$langs;
499
-
500
-		$errorlevel=error_reporting();
501
-		//error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502
-
503
-		$res=false;
504
-
505
-		if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506
-		{
507
-			require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
508
-			$hookmanager = new HookManager($db);
509
-			$hookmanager->initHooks(array('mail'));
510
-
511
-			$parameters=array(); $action='';
512
-			$reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513
-			if ($reshook < 0)
514
-			{
515
-				$this->error = "Error in hook maildao sendMail " . $reshook;
516
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
517
-
518
-				return $reshook;
519
-			}
520
-			if ($reshook == 1)	// Hook replace standard code
521
-			{
522
-				return true;
523
-			}
524
-
525
-			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
527
-			$tmparray1 = explode(',', $this->addr_to);
528
-			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529
-			{
530
-				$this->error = 'Too much recipients in to:';
531
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532
-				return false;
533
-			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
535
-			$tmparray2 = explode(',', $this->addr_cc);
536
-			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537
-			{
538
-				$this->error = 'Too much recipients in cc:';
539
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540
-				return false;
541
-			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
543
-			$tmparray3 = explode(',', $this->addr_bcc);
544
-			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545
-			{
546
-				$this->error = 'Too much recipients in bcc:';
547
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548
-				return false;
549
-			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
-			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552
-			{
553
-				$this->error = 'Too much recipients in to:, cc:, bcc:';
554
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
555
-				return false;
556
-			}
557
-
558
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
564
-			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565
-			{
566
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572
-			}
573
-
574
-			if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
575
-			{
576
-				$this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO;
577
-				$this->addr_cc = '';
578
-				$this->addr_bcc = '';
579
-			}
580
-
581
-			// Action according to choosed sending method
582
-			if ($this->sendmode == 'mail')
583
-			{
584
-				// Use mail php function (default PHP method)
585
-				// ------------------------------------------
586
-				dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
587
-				dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
588
-				//dol_syslog("CMailFile::sendfile message=\n".$message);
589
-
590
-				// If Windows, sendmail_from must be defined
591
-				if (isset($_SERVER["WINDIR"]))
592
-				{
593
-					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
-					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595
-				}
596
-
597
-				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
600
-
601
-				$res=true;
602
-				if ($res && ! $this->subject)
603
-				{
604
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
-					$res=false;
607
-				}
608
-				$dest=$this->getValidAddress($this->addr_to,2);
609
-				if ($res && ! $dest)
610
-				{
611
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
-					$res=false;
614
-				}
615
-
616
-				if ($res)
617
-				{
618
-					$additionnalparam = '';	// By default
619
-					if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620
-					{
621
-						// le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622
-						// Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623
-						// Having this variable defined may create problems with some sendmail (option -f refused)
624
-						// Having this variable not defined may create problems with some other sendmail (option -f required)
625
-						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626
-					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628
-					{
629
-						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
630
-					}
631
-
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
633
-
634
-					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635
-
636
-					$this->message=stripslashes($this->message);
637
-
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639
-
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
-					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642
-
643
-					if (! $res)
644
-					{
645
-						$langs->load("errors");
646
-						$this->error="Failed to send mail with php mail";
647
-						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
-						if (! $linuxlike)
651
-						{
652
-							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
653
-						}
654
-						$this->error.=".<br>";
655
-						$this->error.=$langs->trans("ErrorPhpMailDelivery");
656
-						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
-					}
658
-					else
659
-					{
660
-						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661
-					}
662
-				}
663
-
664
-				if (isset($_SERVER["WINDIR"]))
665
-				{
666
-					@ini_restore('sendmail_from');
667
-				}
668
-
669
-				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
-			}
673
-			else if ($this->sendmode == 'smtps')
674
-			{
675
-				if (! is_object($this->smtps))
676
-				{
677
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679
-					return false;
680
-				}
681
-
682
-				// Use SMTPS library
683
-				// ------------------------------------------
684
-				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685
-
686
-				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
689
-
690
-				// If we use SSL/TLS
691
-				$server=$conf->global->$keyforsmtpserver;
692
-				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
-				$server=($secure?$secure.'://':'').$server;
696
-
697
-				$port=$conf->global->$keyforsmtpport;
698
-
699
-				$this->smtps->setHost($server);
700
-				$this->smtps->setPort($port); // 25, 465...;
701
-
702
-				$loginid=''; $loginpass='';
703
-				if (! empty($conf->global->$keyforsmtpid))
704
-				{
705
-					$loginid = $conf->global->$keyforsmtpid;
706
-					$this->smtps->setID($loginid);
707
-				}
708
-				if (! empty($conf->global->$keyforsmtppw))
709
-				{
710
-					$loginpass = $conf->global->$keyforsmtppw;
711
-					$this->smtps->setPW($loginpass);
712
-				}
713
-
714
-				$res=true;
715
-				$from=$this->smtps->getFrom('org');
716
-				if ($res && ! $from)
717
-				{
718
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
-					$res=false;
721
-				}
722
-				$dest=$this->smtps->getTo();
723
-				if ($res && ! $dest)
724
-				{
725
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
-					$res=false;
728
-				}
729
-
730
-				if ($res)
731
-				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733
-
734
-					$result=$this->smtps->sendMsg();
735
-					//print $result;
736
-
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738
-
739
-					$result=$this->smtps->getErrors();
740
-					if (empty($this->error) && empty($result))
741
-					{
742
-						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
-						$res=true;
744
-					}
745
-					else
746
-					{
747
-						if (empty($this->error)) $this->error=$result;
748
-						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
-						$res=false;
750
-					}
751
-				}
752
-			}
753
-			else if ($this->sendmode == 'swiftmailer')
754
-			{
755
-				// Use Swift Mailer library
756
-				// ------------------------------------------
757
-				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758
-
759
-				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
762
-
763
-				// If we use SSL/TLS
764
-				$server = $conf->global->$keyforsmtpserver;
765
-				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
768
-
769
-				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770
-
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773
-				//$smtps->_msgReplyTo  = '[email protected]';
774
-
775
-				// Create the Mailer using your created Transport
776
-				$this->mailer = new Swift_Mailer($this->transport);
427
+            try {
428
+                $result = $this->message->setCharSet($conf->file->character_set_client);
429
+            } catch (Exception $e) {
430
+                $this->errors[] =  $e->getMessage();
431
+            }
432
+
433
+            if (! empty($this->html))
434
+            {
435
+                if (!empty($css))
436
+                {
437
+                    $this->css = $css;
438
+                    $this->buildCSS();
439
+                }
440
+                $msg = $this->html;
441
+                $msg = $this->checkIfHTML($msg);
442
+            }
443
+
444
+            if ($this->atleastoneimage)
445
+            {
446
+                foreach ($this->images_encoded as $img)
447
+                {
448
+                    //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
449
+                    $attachment = Swift_Image::fromPath($img['fullpath'], $img['content_type']);
450
+                    // embed image
451
+                    $imgcid = $this->message->embed($attachment);
452
+                    // replace cid by the one created by swiftmail in html message
453
+                    $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
454
+                }
455
+            }
456
+
457
+            if ($this->msgishtml) {
458
+                $this->message->setBody($msg,'text/html');
459
+                // And optionally an alternative body
460
+                $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461
+            } else {
462
+                $this->message->setBody($msg,'text/plain');
463
+                // And optionally an alternative body
464
+                $this->message->addPart($msg, 'text/html');
465
+            }
466
+
467
+            if ($this->atleastonefile)
468
+            {
469
+                foreach ($filename_list as $i => $val)
470
+                {
471
+                    //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
+                    $attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
473
+                    $this->message->attach($attachment);
474
+                }
475
+            }
476
+
477
+            if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
+            if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479
+            //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
+            if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
+        }
482
+        else
483
+        {
484
+            // Send mail method not correctly defined
485
+            // --------------------------------------
486
+            $this->error = 'Bad value for sendmode';
487
+        }
488
+    }
489
+
490
+
491
+    /**
492
+     * Send mail that was prepared by constructor.
493
+     *
494
+     * @return    boolean     True if mail sent, false otherwise
495
+     */
496
+    function sendfile()
497
+    {
498
+        global $conf,$db,$langs;
499
+
500
+        $errorlevel=error_reporting();
501
+        //error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502
+
503
+        $res=false;
504
+
505
+        if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506
+        {
507
+            require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
508
+            $hookmanager = new HookManager($db);
509
+            $hookmanager->initHooks(array('mail'));
510
+
511
+            $parameters=array(); $action='';
512
+            $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513
+            if ($reshook < 0)
514
+            {
515
+                $this->error = "Error in hook maildao sendMail " . $reshook;
516
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
517
+
518
+                return $reshook;
519
+            }
520
+            if ($reshook == 1)	// Hook replace standard code
521
+            {
522
+                return true;
523
+            }
524
+
525
+            // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
527
+            $tmparray1 = explode(',', $this->addr_to);
528
+            if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529
+            {
530
+                $this->error = 'Too much recipients in to:';
531
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532
+                return false;
533
+            }
534
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
535
+            $tmparray2 = explode(',', $this->addr_cc);
536
+            if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537
+            {
538
+                $this->error = 'Too much recipients in cc:';
539
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540
+                return false;
541
+            }
542
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
543
+            $tmparray3 = explode(',', $this->addr_bcc);
544
+            if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545
+            {
546
+                $this->error = 'Too much recipients in bcc:';
547
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548
+                return false;
549
+            }
550
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
+            if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552
+            {
553
+                $this->error = 'Too much recipients in to:, cc:, bcc:';
554
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
555
+                return false;
556
+            }
557
+
558
+            $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
+            $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
+            $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
+            $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
+            $keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
+            $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
564
+            if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565
+            {
566
+                $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
+                $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
+                $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
+                $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
+                $keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
+                $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572
+            }
573
+
574
+            if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
575
+            {
576
+                $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO;
577
+                $this->addr_cc = '';
578
+                $this->addr_bcc = '';
579
+            }
580
+
581
+            // Action according to choosed sending method
582
+            if ($this->sendmode == 'mail')
583
+            {
584
+                // Use mail php function (default PHP method)
585
+                // ------------------------------------------
586
+                dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
587
+                dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
588
+                //dol_syslog("CMailFile::sendfile message=\n".$message);
589
+
590
+                // If Windows, sendmail_from must be defined
591
+                if (isset($_SERVER["WINDIR"]))
592
+                {
593
+                    if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
+                    @ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595
+                }
596
+
597
+                // Force parameters
598
+                if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
+                if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
600
+
601
+                $res=true;
602
+                if ($res && ! $this->subject)
603
+                {
604
+                    $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
+                    $res=false;
607
+                }
608
+                $dest=$this->getValidAddress($this->addr_to,2);
609
+                if ($res && ! $dest)
610
+                {
611
+                    $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
+                    $res=false;
614
+                }
615
+
616
+                if ($res)
617
+                {
618
+                    $additionnalparam = '';	// By default
619
+                    if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620
+                    {
621
+                        // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622
+                        // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623
+                        // Having this variable defined may create problems with some sendmail (option -f refused)
624
+                        // Having this variable not defined may create problems with some other sendmail (option -f required)
625
+                        $additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626
+                    }
627
+                    if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628
+                    {
629
+                        $additionnalparam .= ($additionnalparam?' ':'').'-ba';
630
+                    }
631
+
632
+                    if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
633
+
634
+                    dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635
+
636
+                    $this->message=stripslashes($this->message);
637
+
638
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639
+
640
+                    if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
+                    else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642
+
643
+                    if (! $res)
644
+                    {
645
+                        $langs->load("errors");
646
+                        $this->error="Failed to send mail with php mail";
647
+                        $linuxlike=1;
648
+                        if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
+                        if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
+                        if (! $linuxlike)
651
+                        {
652
+                            $this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
653
+                        }
654
+                        $this->error.=".<br>";
655
+                        $this->error.=$langs->trans("ErrorPhpMailDelivery");
656
+                        dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
+                    }
658
+                    else
659
+                    {
660
+                        dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661
+                    }
662
+                }
663
+
664
+                if (isset($_SERVER["WINDIR"]))
665
+                {
666
+                    @ini_restore('sendmail_from');
667
+                }
668
+
669
+                // Restore parameters
670
+                if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
+                if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
+            }
673
+            else if ($this->sendmode == 'smtps')
674
+            {
675
+                if (! is_object($this->smtps))
676
+                {
677
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679
+                    return false;
680
+                }
681
+
682
+                // Use SMTPS library
683
+                // ------------------------------------------
684
+                $this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685
+
686
+                // Clean parameters
687
+                if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
+                if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
689
+
690
+                // If we use SSL/TLS
691
+                $server=$conf->global->$keyforsmtpserver;
692
+                $secure='';
693
+                if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
+                if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
+                $server=($secure?$secure.'://':'').$server;
696
+
697
+                $port=$conf->global->$keyforsmtpport;
698
+
699
+                $this->smtps->setHost($server);
700
+                $this->smtps->setPort($port); // 25, 465...;
701
+
702
+                $loginid=''; $loginpass='';
703
+                if (! empty($conf->global->$keyforsmtpid))
704
+                {
705
+                    $loginid = $conf->global->$keyforsmtpid;
706
+                    $this->smtps->setID($loginid);
707
+                }
708
+                if (! empty($conf->global->$keyforsmtppw))
709
+                {
710
+                    $loginpass = $conf->global->$keyforsmtppw;
711
+                    $this->smtps->setPW($loginpass);
712
+                }
713
+
714
+                $res=true;
715
+                $from=$this->smtps->getFrom('org');
716
+                if ($res && ! $from)
717
+                {
718
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
+                    $res=false;
721
+                }
722
+                $dest=$this->smtps->getTo();
723
+                if ($res && ! $dest)
724
+                {
725
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
+                    $res=false;
728
+                }
729
+
730
+                if ($res)
731
+                {
732
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733
+
734
+                    $result=$this->smtps->sendMsg();
735
+                    //print $result;
736
+
737
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738
+
739
+                    $result=$this->smtps->getErrors();
740
+                    if (empty($this->error) && empty($result))
741
+                    {
742
+                        dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
+                        $res=true;
744
+                    }
745
+                    else
746
+                    {
747
+                        if (empty($this->error)) $this->error=$result;
748
+                        dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
+                        $res=false;
750
+                    }
751
+                }
752
+            }
753
+            else if ($this->sendmode == 'swiftmailer')
754
+            {
755
+                // Use Swift Mailer library
756
+                // ------------------------------------------
757
+                require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758
+
759
+                // Clean parameters
760
+                if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
+                if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
762
+
763
+                // If we use SSL/TLS
764
+                $server = $conf->global->$keyforsmtpserver;
765
+                $secure = '';
766
+                if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
+                if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
768
+
769
+                $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770
+
771
+                if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
+                if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773
+                //$smtps->_msgReplyTo  = '[email protected]';
774
+
775
+                // Create the Mailer using your created Transport
776
+                $this->mailer = new Swift_Mailer($this->transport);
777 777
 
778 778
                 // DKIM SIGN
779 779
                 if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
@@ -785,770 +785,770 @@  discard block
 block discarded – undo
785 785
                 }
786 786
 
787 787
                 if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
788
-					// To use the ArrayLogger
789
-					$this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790
-					// Or to use the Echo Logger
791
-					//$this->logger = new Swift_Plugins_Loggers_EchoLogger();
792
-					$this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
793
-				}
794
-				// send mail
795
-				try {
796
-					$result = $this->mailer->send($this->message);
797
-				} catch (Exception $e) {
798
-					$this->error =  $e->getMessage();
799
-				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801
-
802
-				$res = true;
803
-				if (! empty($this->error) || ! $result) {
804
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
-					$res=false;
806
-				}
807
-				else
808
-				{
809
-					dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810
-				}
811
-			}
812
-			else
813
-			{
814
-				// Send mail method not correctly defined
815
-				// --------------------------------------
816
-
817
-				return 'Bad value for sendmode';
818
-			}
819
-
820
-			$parameters=array(); $action='';
821
-			$reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822
-			if ($reshook < 0)
823
-			{
824
-				$this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
826
-
827
-				return $reshook;
828
-			}
829
-		}
830
-		else
831
-		{
832
-			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833
-			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834
-		}
835
-
836
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
837
-
838
-		return $res;
839
-	}
840
-
841
-	/**
842
-	 * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
843
-	 *
844
-	 * @param string $stringtoencode String to encode
845
-	 * @return string                string encoded
846
-	 */
847
-	static function encodetorfc2822($stringtoencode)
848
-	{
849
-		global $conf;
850
-		return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
851
-	}
788
+                    // To use the ArrayLogger
789
+                    $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790
+                    // Or to use the Echo Logger
791
+                    //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
792
+                    $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
793
+                }
794
+                // send mail
795
+                try {
796
+                    $result = $this->mailer->send($this->message);
797
+                } catch (Exception $e) {
798
+                    $this->error =  $e->getMessage();
799
+                }
800
+                if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801
+
802
+                $res = true;
803
+                if (! empty($this->error) || ! $result) {
804
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
+                    $res=false;
806
+                }
807
+                else
808
+                {
809
+                    dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810
+                }
811
+            }
812
+            else
813
+            {
814
+                // Send mail method not correctly defined
815
+                // --------------------------------------
816
+
817
+                return 'Bad value for sendmode';
818
+            }
819
+
820
+            $parameters=array(); $action='';
821
+            $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822
+            if ($reshook < 0)
823
+            {
824
+                $this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
826
+
827
+                return $reshook;
828
+            }
829
+        }
830
+        else
831
+        {
832
+            $this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833
+            dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834
+        }
835
+
836
+        error_reporting($errorlevel);              // Reactive niveau erreur origine
837
+
838
+        return $res;
839
+    }
840
+
841
+    /**
842
+     * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
843
+     *
844
+     * @param string $stringtoencode String to encode
845
+     * @return string                string encoded
846
+     */
847
+    static function encodetorfc2822($stringtoencode)
848
+    {
849
+        global $conf;
850
+        return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
851
+    }
852 852
 
853 853
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
854
-	/**
855
-	 * Read a file on disk and return encoded content for emails (mode = 'mail')
856
-	 *
857
-	 * @param	string	$sourcefile		Path to file to encode
858
-	 * @return 	int					    <0 if KO, encoded string if OK
859
-	 */
860
-	function _encode_file($sourcefile)
861
-	{
854
+    /**
855
+     * Read a file on disk and return encoded content for emails (mode = 'mail')
856
+     *
857
+     * @param	string	$sourcefile		Path to file to encode
858
+     * @return 	int					    <0 if KO, encoded string if OK
859
+     */
860
+    function _encode_file($sourcefile)
861
+    {
862 862
         // phpcs:enable
863
-		$newsourcefile=dol_osencode($sourcefile);
864
-
865
-		if (is_readable($newsourcefile))
866
-		{
867
-			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
-			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869
-			return $encoded;
870
-		}
871
-		else
872
-		{
873
-			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874
-			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875
-			return -1;
876
-		}
877
-	}
863
+        $newsourcefile=dol_osencode($sourcefile);
864
+
865
+        if (is_readable($newsourcefile))
866
+        {
867
+            $contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
+            $encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869
+            return $encoded;
870
+        }
871
+        else
872
+        {
873
+            $this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874
+            dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875
+            return -1;
876
+        }
877
+    }
878 878
 
879 879
 
880 880
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
881
-	/**
882
-	 *  Write content of a SMTP request into a dump file (mode = all)
883
-	 *  Used for debugging.
884
-	 *  Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
885
-	 *
886
-	 *  @return	void
887
-	 */
888
-	function dump_mail()
889
-	{
881
+    /**
882
+     *  Write content of a SMTP request into a dump file (mode = all)
883
+     *  Used for debugging.
884
+     *  Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
885
+     *
886
+     *  @return	void
887
+     */
888
+    function dump_mail()
889
+    {
890 890
         // phpcs:enable
891
-		global $conf,$dolibarr_main_data_root;
892
-
893
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894
-		{
895
-			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
-			$fp = fopen($outputfile,"w");
897
-
898
-			if ($this->sendmode == 'mail')
899
-			{
900
-				fputs($fp, $this->headers);
901
-				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902
-				fputs($fp, $this->message);
903
-			}
904
-			elseif ($this->sendmode == 'smtps')
905
-			{
906
-				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
-			}
908
-			elseif ($this->sendmode == 'swiftmailer')
909
-			{
910
-				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911
-			}
912
-
913
-			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
915
-				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916
-		}
917
-	}
918
-
919
-
920
-	/**
921
-	 * Correct an uncomplete html string
922
-	 *
923
-	 * @param	string	$msg	String
924
-	 * @return	string			Completed string
925
-	 */
926
-	function checkIfHTML($msg)
927
-	{
928
-		if (!preg_match('/^[\s\t]*<html/i',$msg))
929
-		{
930
-			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
-			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
-			$out.= ">";
935
-			$out.= $msg;
936
-			$out.= "</body></html>";
937
-		}
938
-		else
939
-		{
940
-			$out = $msg;
941
-		}
942
-
943
-		return $out;
944
-	}
945
-
946
-	/**
947
-	 * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
948
-	 *
949
-	 * @return string
950
-	 */
951
-	function buildCSS()
952
-	{
953
-		if (! empty($this->css))
954
-		{
955
-			// Style CSS
956
-			$this->styleCSS = '<style type="text/css">';
957
-			$this->styleCSS.= 'body {';
958
-
959
-			if ($this->css['bgcolor'])
960
-			{
961
-				$this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
-				$this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
963
-			}
964
-			if ($this->css['bgimage'])
965
-			{
966
-				// TODO recuperer cid
967
-				$this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968
-			}
969
-			$this->styleCSS.= '}';
970
-			$this->styleCSS.= '</style>';
971
-		}
972
-	}
891
+        global $conf,$dolibarr_main_data_root;
892
+
893
+        if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894
+        {
895
+            $outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
+            $fp = fopen($outputfile,"w");
897
+
898
+            if ($this->sendmode == 'mail')
899
+            {
900
+                fputs($fp, $this->headers);
901
+                fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902
+                fputs($fp, $this->message);
903
+            }
904
+            elseif ($this->sendmode == 'smtps')
905
+            {
906
+                fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
+            }
908
+            elseif ($this->sendmode == 'swiftmailer')
909
+            {
910
+                fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911
+            }
912
+
913
+            fclose($fp);
914
+            if (! empty($conf->global->MAIN_UMASK))
915
+                @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916
+        }
917
+    }
918
+
919
+
920
+    /**
921
+     * Correct an uncomplete html string
922
+     *
923
+     * @param	string	$msg	String
924
+     * @return	string			Completed string
925
+     */
926
+    function checkIfHTML($msg)
927
+    {
928
+        if (!preg_match('/^[\s\t]*<html/i',$msg))
929
+        {
930
+            $out = "<html><head><title></title>";
931
+            if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
+            $out.= "</head><body";
933
+            if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
+            $out.= ">";
935
+            $out.= $msg;
936
+            $out.= "</body></html>";
937
+        }
938
+        else
939
+        {
940
+            $out = $msg;
941
+        }
942
+
943
+        return $out;
944
+    }
945
+
946
+    /**
947
+     * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
948
+     *
949
+     * @return string
950
+     */
951
+    function buildCSS()
952
+    {
953
+        if (! empty($this->css))
954
+        {
955
+            // Style CSS
956
+            $this->styleCSS = '<style type="text/css">';
957
+            $this->styleCSS.= 'body {';
958
+
959
+            if ($this->css['bgcolor'])
960
+            {
961
+                $this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
+                $this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
963
+            }
964
+            if ($this->css['bgimage'])
965
+            {
966
+                // TODO recuperer cid
967
+                $this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968
+            }
969
+            $this->styleCSS.= '}';
970
+            $this->styleCSS.= '</style>';
971
+        }
972
+    }
973 973
 
974 974
 
975 975
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
976
-	/**
977
-	 * Create SMTP headers (mode = 'mail')
978
-	 *
979
-	 * @return	string headers
980
-	 */
981
-	function write_smtpheaders()
982
-	{
976
+    /**
977
+     * Create SMTP headers (mode = 'mail')
978
+     *
979
+     * @return	string headers
980
+     */
981
+    function write_smtpheaders()
982
+    {
983 983
         // phpcs:enable
984
-		global $conf;
985
-		$out = "";
984
+        global $conf;
985
+        $out = "";
986 986
 
987
-		$host = dol_getprefix('email');
987
+        $host = dol_getprefix('email');
988 988
 
989
-		// Sender
990
-		//$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
-		$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
-		if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993
-		{
994
-			$out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
995
-		}
996
-		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
-		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
989
+        // Sender
990
+        //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
+        $out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
+        if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993
+        {
994
+            $out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
995
+        }
996
+        // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
+        $out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
+        if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
+        if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1000 1000
 
1001
-		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1001
+        // Receiver
1002
+        if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
+        if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1004
 
1005
-		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1005
+        // Delivery receipt
1006
+        if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1007 1007
 
1008
-		//$out.= "X-Priority: 3".$this->eol2;
1008
+        //$out.= "X-Priority: 3".$this->eol2;
1009 1009
 
1010
-		$out.= 'Date: ' . date("r") . $this->eol2;
1010
+        $out.= 'Date: ' . date("r") . $this->eol2;
1011 1011
 
1012
-		$trackid = $this->trackid;
1013
-		if ($trackid)
1014
-		{
1015
-			// References is kept in response and Message-ID is returned into In-Reply-To:
1016
-			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
-			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
-			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
-		}
1020
-		else
1021
-		{
1022
-			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023
-		}
1012
+        $trackid = $this->trackid;
1013
+        if ($trackid)
1014
+        {
1015
+            // References is kept in response and Message-ID is returned into In-Reply-To:
1016
+            $out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
+            $out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
+            $out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
+        }
1020
+        else
1021
+        {
1022
+            $out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023
+        }
1024 1024
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
-		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
-		$out.= "Mime-Version: 1.0".$this->eol2;
1025
+        if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
+        $out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
+        $out.= "Mime-Version: 1.0".$this->eol2;
1028 1028
 
1029
-		//$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1029
+        //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1030 1030
 
1031
-		$out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
-		$out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1031
+        $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
+        $out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1033 1033
 
1034
-		dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035
-		return $out;
1036
-	}
1034
+        dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035
+        return $out;
1036
+    }
1037 1037
 
1038 1038
 
1039 1039
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
-	/**
1041
-	 * Create header MIME (mode = 'mail')
1042
-	 *
1043
-	 * @param	array	$filename_list			Array of filenames
1044
-	 * @param 	array	$mimefilename_list		Array of mime types
1045
-	 * @return	string							mime headers
1046
-	 */
1047
-	function write_mimeheaders($filename_list, $mimefilename_list)
1048
-	{
1040
+    /**
1041
+     * Create header MIME (mode = 'mail')
1042
+     *
1043
+     * @param	array	$filename_list			Array of filenames
1044
+     * @param 	array	$mimefilename_list		Array of mime types
1045
+     * @return	string							mime headers
1046
+     */
1047
+    function write_mimeheaders($filename_list, $mimefilename_list)
1048
+    {
1049 1049
         // phpcs:enable
1050
-		$mimedone=0;
1051
-		$out = "";
1052
-
1053
-		if (is_array($filename_list))
1054
-		{
1055
-			$filename_list_size=count($filename_list);
1056
-			for($i=0;$i < $filename_list_size;$i++)
1057
-			{
1058
-				if ($filename_list[$i])
1059
-				{
1060
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
-					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062
-				}
1063
-			}
1064
-		}
1065
-
1066
-		dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1067
-		return $out;
1068
-	}
1050
+        $mimedone=0;
1051
+        $out = "";
1052
+
1053
+        if (is_array($filename_list))
1054
+        {
1055
+            $filename_list_size=count($filename_list);
1056
+            for($i=0;$i < $filename_list_size;$i++)
1057
+            {
1058
+                if ($filename_list[$i])
1059
+                {
1060
+                    if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
+                    $out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062
+                }
1063
+            }
1064
+        }
1069 1065
 
1070
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1071
-	/**
1072
-	 * Return email content (mode = 'mail')
1073
-	 *
1074
-	 * @param	string		$msgtext		Message string
1075
-	 * @return	string						String content
1076
-	 */
1077
-	function write_body($msgtext)
1078
-	{
1079
-        // phpcs:enable
1080
-		global $conf;
1081
-
1082
-		$out='';
1083
-
1084
-		$out.= "--" . $this->mixed_boundary . $this->eol;
1085
-
1086
-		if ($this->atleastoneimage)
1087
-		{
1088
-			$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
-			$out.= $this->eol;
1090
-			$out.= "--" . $this->alternative_boundary . $this->eol;
1091
-		}
1092
-
1093
-		// Make RFC821 Compliant, replace bare linefeeds
1094
-		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096
-		{
1097
-			$strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1098
-		}
1099
-
1100
-		$strContentAltText = '';
1101
-		if ($this->msgishtml)
1102
-		{
1103
-			// Similar code to forge a text from html is also in CMailFile.class.php
1104
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1105
-			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
-			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1107
-
1108
-			// Check if html header already in message, if not complete the message
1109
-			$strContent = $this->checkIfHTML($strContent);
1110
-		}
1111
-
1112
-		// Make RFC2045 Compliant, split lines
1113
-		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114
-		// TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
-		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1116
-
1117
-		if ($this->msgishtml)
1118
-		{
1119
-			if ($this->atleastoneimage)
1120
-			{
1121
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122
-				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
-				$out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1125
-				$out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
-				$out.= $this->eol;
1127
-				$out.= "--" . $this->related_boundary . $this->eol;
1128
-			}
1129
-
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131
-			{
1132
-				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
-				$out.= $this->eol;
1134
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1135
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136
-				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
-				$out.= $this->eol.$strContentAltText.$this->eol;
1138
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1139
-			}
1140
-
1141
-			$out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142
-			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
-			$out.= $this->eol.$strContent.$this->eol;
1144
-
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146
-			{
1147
-				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148
-			}
1149
-		}
1150
-		else
1151
-		{
1152
-			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153
-			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
-			$out.= $this->eol.$strContent.$this->eol;
1155
-		}
1156
-
1157
-		$out.= $this->eol;
1158
-
1159
-		// Encode images
1160
-		if ($this->atleastoneimage)
1161
-		{
1162
-			$out .= $this->write_images($this->images_encoded);
1163
-			// always end related and end alternative after inline images
1164
-			$out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
-			$out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1166
-			$out .= $this->eol;
1167
-		}
1168
-
1169
-		return $out;
1170
-	}
1066
+        dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1067
+        return $out;
1068
+    }
1171 1069
 
1172 1070
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1173
-	/**
1174
-	 * Attach file to email (mode = 'mail')
1175
-	 *
1176
-	 * @param	array	$filename_list		Tableau
1177
-	 * @param	array	$mimetype_list		Tableau
1178
-	 * @param 	array	$mimefilename_list	Tableau
1179
-	 * @return	string						Chaine fichiers encodes
1180
-	 */
1181
-	function write_files($filename_list,$mimetype_list,$mimefilename_list)
1182
-	{
1071
+    /**
1072
+     * Return email content (mode = 'mail')
1073
+     *
1074
+     * @param	string		$msgtext		Message string
1075
+     * @return	string						String content
1076
+     */
1077
+    function write_body($msgtext)
1078
+    {
1183 1079
         // phpcs:enable
1184
-		$out = '';
1185
-
1186
-		$filename_list_size=count($filename_list);
1187
-		for($i=0;$i < $filename_list_size;$i++)
1188
-		{
1189
-			if ($filename_list[$i])
1190
-			{
1191
-				dol_syslog("CMailFile::write_files: i=$i");
1192
-				$encoded = $this->_encode_file($filename_list[$i]);
1193
-				if ($encoded >= 0)
1194
-				{
1195
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
-					if (! $mimetype_list[$i]) {
1197
-						$mimetype_list[$i] = "application/octet-stream";
1198
-					}
1199
-
1200
-					$out.= "--" . $this->mixed_boundary . $this->eol;
1201
-					$out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
-					$out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
-					$out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
-					$out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
-					$out.= $this->eol;
1206
-					$out.= $encoded;
1207
-					$out.= $this->eol;
1208
-					//$out.= $this->eol;
1209
-				}
1210
-				else
1211
-				{
1212
-					return $encoded;
1213
-				}
1214
-			}
1215
-		}
1216
-
1217
-		return $out;
1218
-	}
1080
+        global $conf;
1081
+
1082
+        $out='';
1083
+
1084
+        $out.= "--" . $this->mixed_boundary . $this->eol;
1085
+
1086
+        if ($this->atleastoneimage)
1087
+        {
1088
+            $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
+            $out.= $this->eol;
1090
+            $out.= "--" . $this->alternative_boundary . $this->eol;
1091
+        }
1092
+
1093
+        // Make RFC821 Compliant, replace bare linefeeds
1094
+        $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
+        if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096
+        {
1097
+            $strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1098
+        }
1099
+
1100
+        $strContentAltText = '';
1101
+        if ($this->msgishtml)
1102
+        {
1103
+            // Similar code to forge a text from html is also in CMailFile.class.php
1104
+            $strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1105
+            $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
+            $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1107
+
1108
+            // Check if html header already in message, if not complete the message
1109
+            $strContent = $this->checkIfHTML($strContent);
1110
+        }
1111
+
1112
+        // Make RFC2045 Compliant, split lines
1113
+        //$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114
+        // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
+        $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1116
+
1117
+        if ($this->msgishtml)
1118
+        {
1119
+            if ($this->atleastoneimage)
1120
+            {
1121
+                $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122
+                //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
+                $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1125
+                $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
+                $out.= $this->eol;
1127
+                $out.= "--" . $this->related_boundary . $this->eol;
1128
+            }
1129
+
1130
+            if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131
+            {
1132
+                $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
+                $out.= $this->eol;
1134
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1135
+                $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136
+                //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
+                $out.= $this->eol.$strContentAltText.$this->eol;
1138
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1139
+            }
1140
+
1141
+            $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142
+            //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
+            $out.= $this->eol.$strContent.$this->eol;
1219 1144
 
1145
+            if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146
+            {
1147
+                $out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148
+            }
1149
+        }
1150
+        else
1151
+        {
1152
+            $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153
+            //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
+            $out.= $this->eol.$strContent.$this->eol;
1155
+        }
1156
+
1157
+        $out.= $this->eol;
1158
+
1159
+        // Encode images
1160
+        if ($this->atleastoneimage)
1161
+        {
1162
+            $out .= $this->write_images($this->images_encoded);
1163
+            // always end related and end alternative after inline images
1164
+            $out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
+            $out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1166
+            $out .= $this->eol;
1167
+        }
1168
+
1169
+        return $out;
1170
+    }
1220 1171
 
1221 1172
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1222
-	/**
1223
-	 * Attach an image to email (mode = 'mail')
1224
-	 *
1225
-	 * @param	array	$images_list	Array of array image
1226
-	 * @return	string					Chaine images encodees
1227
-	 */
1228
-	function write_images($images_list)
1229
-	{
1173
+    /**
1174
+     * Attach file to email (mode = 'mail')
1175
+     *
1176
+     * @param	array	$filename_list		Tableau
1177
+     * @param	array	$mimetype_list		Tableau
1178
+     * @param 	array	$mimefilename_list	Tableau
1179
+     * @return	string						Chaine fichiers encodes
1180
+     */
1181
+    function write_files($filename_list,$mimetype_list,$mimefilename_list)
1182
+    {
1230 1183
         // phpcs:enable
1231
-		$out = '';
1184
+        $out = '';
1185
+
1186
+        $filename_list_size=count($filename_list);
1187
+        for($i=0;$i < $filename_list_size;$i++)
1188
+        {
1189
+            if ($filename_list[$i])
1190
+            {
1191
+                dol_syslog("CMailFile::write_files: i=$i");
1192
+                $encoded = $this->_encode_file($filename_list[$i]);
1193
+                if ($encoded >= 0)
1194
+                {
1195
+                    if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
+                    if (! $mimetype_list[$i]) {
1197
+                        $mimetype_list[$i] = "application/octet-stream";
1198
+                    }
1199
+
1200
+                    $out.= "--" . $this->mixed_boundary . $this->eol;
1201
+                    $out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
+                    $out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
+                    $out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
+                    $out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
+                    $out.= $this->eol;
1206
+                    $out.= $encoded;
1207
+                    $out.= $this->eol;
1208
+                    //$out.= $this->eol;
1209
+                }
1210
+                else
1211
+                {
1212
+                    return $encoded;
1213
+                }
1214
+            }
1215
+        }
1232 1216
 
1233
-		if (is_array($images_list))
1234
-		{
1235
-			foreach ($images_list as $img)
1236
-			{
1237
-				dol_syslog("CMailFile::write_images: ".$img["name"]);
1217
+        return $out;
1218
+    }
1238 1219
 
1239
-				$out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
-				$out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
-				$out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
-				$out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
-				$out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
-				$out.= $this->eol;
1245
-				$out.= $img["image_encoded"];
1246
-				$out.= $this->eol;
1247
-			}
1248
-		}
1249 1220
 
1250
-		return $out;
1251
-	}
1221
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1222
+    /**
1223
+     * Attach an image to email (mode = 'mail')
1224
+     *
1225
+     * @param	array	$images_list	Array of array image
1226
+     * @return	string					Chaine images encodees
1227
+     */
1228
+    function write_images($images_list)
1229
+    {
1230
+        // phpcs:enable
1231
+        $out = '';
1232
+
1233
+        if (is_array($images_list))
1234
+        {
1235
+            foreach ($images_list as $img)
1236
+            {
1237
+                dol_syslog("CMailFile::write_images: ".$img["name"]);
1238
+
1239
+                $out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
+                $out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
+                $out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
+                $out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
+                $out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
+                $out.= $this->eol;
1245
+                $out.= $img["image_encoded"];
1246
+                $out.= $this->eol;
1247
+            }
1248
+        }
1249
+
1250
+        return $out;
1251
+    }
1252 1252
 
1253 1253
 
1254 1254
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1255
-	/**
1256
-	 * Try to create a socket connection
1257
-	 *
1258
-	 * @param 	string		$host		Add ssl:// for SSL/TLS.
1259
-	 * @param 	int			$port		Example: 25, 465
1260
-	 * @return	int						Socket id if ok, 0 if KO
1261
-	 */
1262
-	function check_server_port($host,$port)
1263
-	{
1255
+    /**
1256
+     * Try to create a socket connection
1257
+     *
1258
+     * @param 	string		$host		Add ssl:// for SSL/TLS.
1259
+     * @param 	int			$port		Example: 25, 465
1260
+     * @return	int						Socket id if ok, 0 if KO
1261
+     */
1262
+    function check_server_port($host,$port)
1263
+    {
1264 1264
         // phpcs:enable
1265
-		global $conf;
1266
-
1267
-		$_retVal=0;
1268
-		$timeout=5;	// Timeout in seconds
1269
-
1270
-		if (function_exists('fsockopen'))
1271
-		{
1272
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1278
-			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279
-			{
1280
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286
-			}
1287
-
1288
-			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1290
-			// tls smtp start with no encryption
1291
-			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292
-
1293
-			dol_syslog("Try socket connection to host=".$host." port=".$port);
1294
-			//See if we can connect to the SMTP server
1295
-			if ($socket = @fsockopen(
1296
-					$host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
-					$port,       // which Port number to use
1298
-					$errno,      // actual system level error
1299
-					$errstr,     // and any text that goes with the error
1300
-					$timeout
1301
-			))  // timeout for reading/writing data over the socket
1302
-			{
1303
-				// Windows still does not have support for this timeout function
1304
-				if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1305
-
1306
-				dol_syslog("Now we wait for answer 220");
1307
-
1308
-				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
-			}
1311
-			else
1312
-			{
1313
-				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314
-			}
1315
-		}
1316
-		return $_retVal;
1317
-	}
1265
+        global $conf;
1266
+
1267
+        $_retVal=0;
1268
+        $timeout=5;	// Timeout in seconds
1269
+
1270
+        if (function_exists('fsockopen'))
1271
+        {
1272
+            $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
+            $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
+            $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
+            $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
+            $keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
+            $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1278
+            if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279
+            {
1280
+                $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
+                $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
+                $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
+                $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
+                $keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
+                $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286
+            }
1287
+
1288
+            // If we use SSL/TLS
1289
+            if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1290
+            // tls smtp start with no encryption
1291
+            //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292
+
1293
+            dol_syslog("Try socket connection to host=".$host." port=".$port);
1294
+            //See if we can connect to the SMTP server
1295
+            if ($socket = @fsockopen(
1296
+                    $host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
+                    $port,       // which Port number to use
1298
+                    $errno,      // actual system level error
1299
+                    $errstr,     // and any text that goes with the error
1300
+                    $timeout
1301
+            ))  // timeout for reading/writing data over the socket
1302
+            {
1303
+                // Windows still does not have support for this timeout function
1304
+                if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1305
+
1306
+                dol_syslog("Now we wait for answer 220");
1307
+
1308
+                // Check response from Server
1309
+                if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
+            }
1311
+            else
1312
+            {
1313
+                $this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314
+            }
1315
+        }
1316
+        return $_retVal;
1317
+    }
1318 1318
 
1319 1319
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1320
-	/**
1321
-	 * This function has been modified as provided by SirSir to allow multiline responses when
1322
-	 * using SMTP Extensions.
1323
-	 *
1324
-	 * @param	Socket	$socket			Socket
1325
-	 * @param   string	$response		Response string
1326
-	 * @return  boolean					true if success
1327
-	 */
1328
-	function server_parse($socket, $response)
1329
-	{
1320
+    /**
1321
+     * This function has been modified as provided by SirSir to allow multiline responses when
1322
+     * using SMTP Extensions.
1323
+     *
1324
+     * @param	Socket	$socket			Socket
1325
+     * @param   string	$response		Response string
1326
+     * @return  boolean					true if success
1327
+     */
1328
+    function server_parse($socket, $response)
1329
+    {
1330 1330
         // phpcs:enable
1331
-		$_retVal = true;	// Indicates if Object was created or not
1332
-		$server_response = '';
1333
-
1334
-		while (substr($server_response,3,1) != ' ')
1335
-		{
1336
-			if (! ($server_response = fgets($socket, 256)) )
1337
-			{
1338
-				$this->error="Couldn't get mail server response codes";
1339
-				return false;
1340
-			}
1341
-		}
1342
-
1343
-		if( !( substr($server_response, 0, 3) == $response ) )
1344
-		{
1345
-			$this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1346
-			$_retVal = false;
1347
-		}
1348
-
1349
-		return $_retVal;
1350
-	}
1351
-
1352
-	/**
1353
-	 * Seearch images into html message and init array this->images_encoded if found
1354
-	 *
1355
-	 * @param	string	$images_dir		Location of physical images files
1356
-	 * @return	int 		        	>0 if OK, <0 if KO
1357
-	 */
1358
-	function findHtmlImages($images_dir)
1359
-	{
1360
-		// Build the list of image extensions
1361
-		$extensions = array_keys($this->image_types);
1362
-
1363
-		$matches = array();
1364
-		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1365
-
1366
-		if (! empty($matches))
1367
-		{
1368
-			$i=0;
1369
-			foreach ($matches[1] as $full)
1370
-			{
1371
-
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1373
-				{
1374
-					$img = $regs[1];
1375
-
1376
-					if (file_exists($images_dir.'/'.$img))
1377
-					{
1378
-						// Image path in src
1379
-						$src = preg_quote($full,'/');
1380
-
1381
-						// Image full path
1382
-						$this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
1383
-
1384
-						// Image name
1385
-						$this->html_images[$i]["name"] = $img;
1386
-
1387
-						// Content type
1388
-						if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389
-						{
1390
-							$ext=strtolower($reg[1]);
1391
-							$this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392
-						}
1393
-
1394
-						// cid
1395
-						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1396
-						$this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397
-					}
1398
-					$i++;
1399
-				}
1400
-			}
1401
-
1402
-			if (!empty($this->html_images))
1403
-			{
1404
-				$inline = array();
1405
-
1406
-				$i=0;
1407
-
1408
-				foreach ($this->html_images as $img)
1409
-				{
1410
-					$fullpath = $images_dir.'/'.$img["name"];
1411
-
1412
-					// If duplicate images are embedded, they may show up as attachments, so remove them.
1413
-					if (!in_array($fullpath,$inline))
1414
-					{
1415
-						// Read image file
1416
-						if ($image = file_get_contents($fullpath))
1417
-						{
1418
-							// On garde que le nom de l'image
1419
-							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1420
-							$imgName = $regs[1];
1421
-
1422
-							$this->images_encoded[$i]['name'] = $imgName;
1423
-							$this->images_encoded[$i]['fullpath'] = $fullpath;
1424
-							$this->images_encoded[$i]['content_type'] = $img["content_type"];
1425
-							$this->images_encoded[$i]['cid'] = $img["cid"];
1426
-							// Encodage de l'image
1427
-							$this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1428
-							$inline[] = $fullpath;
1429
-						}
1430
-					}
1431
-					$i++;
1432
-				}
1433
-			}
1434
-			else
1435
-			{
1436
-				return -1;
1437
-			}
1438
-
1439
-			return 1;
1440
-		}
1441
-		else
1442
-		{
1443
-			return 0;
1444
-		}
1445
-	}
1446
-
1447
-	/**
1448
-	 * Return a formatted address string for SMTP protocol
1449
-	 *
1450
-	 * @param	string		$address		     Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1451
-	 * @param	int			$format			     0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between "
1452
-	 * @param	int			$encode			     0=No encode name, 1=Encode name to RFC2822
1453
-	 * @param   int         $maxnumberofemail    0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
1454
-	 * @return	string						     If format 0: '<[email protected]>' or 'John Doe <[email protected]>' or '=?UTF-8?B?Sm9obiBEb2U=?= <[email protected]>'
1455
-	 * 										     If format 1: '<[email protected]>'
1456
-	 *										     If format 2: '[email protected]'
1457
-	 *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458
-	 *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459
-	 */
1460
-	static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1461
-	{
1462
-		global $conf;
1463
-
1464
-		$ret='';
1465
-
1466
-		$arrayaddress=explode(',',$address);
1467
-
1468
-		// Boucle sur chaque composant de l'adresse
1469
-		$i=0;
1470
-		foreach($arrayaddress as $val)
1471
-		{
1472
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1473
-			{
1474
-				$name  = trim($regs[1]);
1475
-				$email = trim($regs[2]);
1476
-			}
1477
-			else
1478
-			{
1479
-				$name  = '';
1480
-				$email = trim($val);
1481
-			}
1482
-
1483
-			if ($email)
1484
-			{
1485
-				$i++;
1486
-
1487
-				$newemail='';
1488
-				if ($format == 4)
1489
-				{
1490
-					$newemail = $name?$name:$email;
1491
-				}
1492
-				if ($format == 2)
1493
-				{
1494
-					$newemail=$email;
1495
-				}
1496
-				if ($format == 1 || $format == 3)
1497
-				{
1498
-					$newemail='<'.$email.'>';
1499
-				}
1500
-				if ($format == 0 || $format == 3)
1501
-				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1505
-				}
1506
-
1507
-				$ret=($ret ? $ret.',' : '').$newemail;
1508
-
1509
-				// Stop if we have too much records
1510
-				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511
-				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1513
-					break;
1514
-				}
1515
-			}
1516
-		}
1517
-
1518
-		return $ret;
1519
-	}
1520
-
1521
-	/**
1522
-	 * Return a formatted array of address string for SMTP protocol
1523
-	 *
1524
-	 * @param   string      $address        Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1525
-	 * @return  array                       array of email => name
1526
-	 */
1527
-	function getArrayAddress($address)
1528
-	{
1529
-		global $conf;
1530
-
1531
-		$ret=array();
1532
-
1533
-		$arrayaddress=explode(',',$address);
1534
-
1535
-		// Boucle sur chaque composant de l'adresse
1536
-		foreach($arrayaddress as $val)
1537
-		{
1538
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1539
-			{
1540
-				$name  = trim($regs[1]);
1541
-				$email = trim($regs[2]);
1542
-			}
1543
-			else
1544
-			{
1545
-				$name  = null;
1546
-				$email = trim($val);
1547
-			}
1548
-
1549
-			$ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1550
-		}
1551
-
1552
-		return $ret;
1553
-	}
1331
+        $_retVal = true;	// Indicates if Object was created or not
1332
+        $server_response = '';
1333
+
1334
+        while (substr($server_response,3,1) != ' ')
1335
+        {
1336
+            if (! ($server_response = fgets($socket, 256)) )
1337
+            {
1338
+                $this->error="Couldn't get mail server response codes";
1339
+                return false;
1340
+            }
1341
+        }
1342
+
1343
+        if( !( substr($server_response, 0, 3) == $response ) )
1344
+        {
1345
+            $this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1346
+            $_retVal = false;
1347
+        }
1348
+
1349
+        return $_retVal;
1350
+    }
1351
+
1352
+    /**
1353
+     * Seearch images into html message and init array this->images_encoded if found
1354
+     *
1355
+     * @param	string	$images_dir		Location of physical images files
1356
+     * @return	int 		        	>0 if OK, <0 if KO
1357
+     */
1358
+    function findHtmlImages($images_dir)
1359
+    {
1360
+        // Build the list of image extensions
1361
+        $extensions = array_keys($this->image_types);
1362
+
1363
+        $matches = array();
1364
+        preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1365
+
1366
+        if (! empty($matches))
1367
+        {
1368
+            $i=0;
1369
+            foreach ($matches[1] as $full)
1370
+            {
1371
+
1372
+                if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1373
+                {
1374
+                    $img = $regs[1];
1375
+
1376
+                    if (file_exists($images_dir.'/'.$img))
1377
+                    {
1378
+                        // Image path in src
1379
+                        $src = preg_quote($full,'/');
1380
+
1381
+                        // Image full path
1382
+                        $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
1383
+
1384
+                        // Image name
1385
+                        $this->html_images[$i]["name"] = $img;
1386
+
1387
+                        // Content type
1388
+                        if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389
+                        {
1390
+                            $ext=strtolower($reg[1]);
1391
+                            $this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392
+                        }
1393
+
1394
+                        // cid
1395
+                        $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1396
+                        $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397
+                    }
1398
+                    $i++;
1399
+                }
1400
+            }
1401
+
1402
+            if (!empty($this->html_images))
1403
+            {
1404
+                $inline = array();
1405
+
1406
+                $i=0;
1407
+
1408
+                foreach ($this->html_images as $img)
1409
+                {
1410
+                    $fullpath = $images_dir.'/'.$img["name"];
1411
+
1412
+                    // If duplicate images are embedded, they may show up as attachments, so remove them.
1413
+                    if (!in_array($fullpath,$inline))
1414
+                    {
1415
+                        // Read image file
1416
+                        if ($image = file_get_contents($fullpath))
1417
+                        {
1418
+                            // On garde que le nom de l'image
1419
+                            preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1420
+                            $imgName = $regs[1];
1421
+
1422
+                            $this->images_encoded[$i]['name'] = $imgName;
1423
+                            $this->images_encoded[$i]['fullpath'] = $fullpath;
1424
+                            $this->images_encoded[$i]['content_type'] = $img["content_type"];
1425
+                            $this->images_encoded[$i]['cid'] = $img["cid"];
1426
+                            // Encodage de l'image
1427
+                            $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1428
+                            $inline[] = $fullpath;
1429
+                        }
1430
+                    }
1431
+                    $i++;
1432
+                }
1433
+            }
1434
+            else
1435
+            {
1436
+                return -1;
1437
+            }
1438
+
1439
+            return 1;
1440
+        }
1441
+        else
1442
+        {
1443
+            return 0;
1444
+        }
1445
+    }
1446
+
1447
+    /**
1448
+     * Return a formatted address string for SMTP protocol
1449
+     *
1450
+     * @param	string		$address		     Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1451
+     * @param	int			$format			     0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between "
1452
+     * @param	int			$encode			     0=No encode name, 1=Encode name to RFC2822
1453
+     * @param   int         $maxnumberofemail    0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
1454
+     * @return	string						     If format 0: '<[email protected]>' or 'John Doe <[email protected]>' or '=?UTF-8?B?Sm9obiBEb2U=?= <[email protected]>'
1455
+     * 										     If format 1: '<[email protected]>'
1456
+     *										     If format 2: '[email protected]'
1457
+     *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458
+     *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459
+     */
1460
+    static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1461
+    {
1462
+        global $conf;
1463
+
1464
+        $ret='';
1465
+
1466
+        $arrayaddress=explode(',',$address);
1467
+
1468
+        // Boucle sur chaque composant de l'adresse
1469
+        $i=0;
1470
+        foreach($arrayaddress as $val)
1471
+        {
1472
+            if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1473
+            {
1474
+                $name  = trim($regs[1]);
1475
+                $email = trim($regs[2]);
1476
+            }
1477
+            else
1478
+            {
1479
+                $name  = '';
1480
+                $email = trim($val);
1481
+            }
1482
+
1483
+            if ($email)
1484
+            {
1485
+                $i++;
1486
+
1487
+                $newemail='';
1488
+                if ($format == 4)
1489
+                {
1490
+                    $newemail = $name?$name:$email;
1491
+                }
1492
+                if ($format == 2)
1493
+                {
1494
+                    $newemail=$email;
1495
+                }
1496
+                if ($format == 1 || $format == 3)
1497
+                {
1498
+                    $newemail='<'.$email.'>';
1499
+                }
1500
+                if ($format == 0 || $format == 3)
1501
+                {
1502
+                    if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
+                    elseif (! $name) $newemail='<'.$email.'>';
1504
+                    else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1505
+                }
1506
+
1507
+                $ret=($ret ? $ret.',' : '').$newemail;
1508
+
1509
+                // Stop if we have too much records
1510
+                if ($maxnumberofemail && $i >= $maxnumberofemail)
1511
+                {
1512
+                    if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1513
+                    break;
1514
+                }
1515
+            }
1516
+        }
1517
+
1518
+        return $ret;
1519
+    }
1520
+
1521
+    /**
1522
+     * Return a formatted array of address string for SMTP protocol
1523
+     *
1524
+     * @param   string      $address        Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1525
+     * @return  array                       array of email => name
1526
+     */
1527
+    function getArrayAddress($address)
1528
+    {
1529
+        global $conf;
1530
+
1531
+        $ret=array();
1532
+
1533
+        $arrayaddress=explode(',',$address);
1534
+
1535
+        // Boucle sur chaque composant de l'adresse
1536
+        foreach($arrayaddress as $val)
1537
+        {
1538
+            if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1539
+            {
1540
+                $name  = trim($regs[1]);
1541
+                $email = trim($regs[2]);
1542
+            }
1543
+            else
1544
+            {
1545
+                $name  = null;
1546
+                $email = trim($val);
1547
+            }
1548
+
1549
+            $ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1550
+        }
1551
+
1552
+        return $ret;
1553
+    }
1554 1554
 }
Please login to merge, or discard this patch.
Spacing   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -40,13 +40,13 @@  discard block
 block discarded – undo
40 40
 	public $sendmode;
41 41
 	public $sendsetup;
42 42
 
43
-	var $subject;      	// Topic:       Subject of email
44
-	var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
43
+	var $subject; // Topic:       Subject of email
44
+	var $addr_from; // From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45 45
 	// Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46 46
 	//              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47 47
 	// Return-Path: Email where to send bounds.
48
-	var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
-	var $errors_to;		// Errors-To:	Email where to send errors.
48
+	var $reply_to; // Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
+	var $errors_to; // Errors-To:	Email where to send errors.
50 50
 	var $addr_to;
51 51
 	var $addr_cc;
52 52
 	var $addr_bcc;
@@ -63,10 +63,10 @@  discard block
 block discarded – undo
63 63
 	/**
64 64
 	 * @var string Error code (or message)
65 65
 	 */
66
-	public $error='';
66
+	public $error = '';
67 67
 
68
-	var $smtps;			// Contains SMTPs object (if this method is used)
69
-	var $phpmailer;		// Contains PHPMailer object (if this method is used)
68
+	var $smtps; // Contains SMTPs object (if this method is used)
69
+	var $phpmailer; // Contains PHPMailer object (if this method is used)
70 70
 
71 71
 	/**
72 72
 	 * @var string CSS
@@ -83,9 +83,9 @@  discard block
 block discarded – undo
83 83
 	// Image
84 84
 	var $html;
85 85
 	var $image_boundary;
86
-	var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
-	var $html_images=array();
88
-	var $images_encoded=array();
86
+	var $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
+	var $html_images = array();
88
+	var $images_encoded = array();
89 89
 	var $image_types = array(
90 90
         'gif'  => 'image/gif',
91 91
 		'jpg'  => 'image/jpeg',
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
 	 *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120 120
 	 *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121 121
 	 */
122
-	function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
122
+	function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = 0, $errors_to = '', $css = '', $trackid = '', $moreinheader = '', $sendcontext = 'standard', $replyto = '')
123 123
 	{
124 124
 		global $conf, $dolibarr_main_data_root;
125 125
 
126 126
 		$this->sendcontext = $sendcontext;
127 127
 
128
-		if (empty($replyto)) $replyto=$from;
128
+		if (empty($replyto)) $replyto = $from;
129 129
 
130 130
 		// Define this->sendmode
131 131
 		$this->sendmode = '';
@@ -133,28 +133,28 @@  discard block
 block discarded – undo
133 133
 		{
134 134
 			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135 135
 		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
136
+		if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE;
137
+		if (empty($this->sendmode)) $this->sendmode = 'mail';
138 138
 
139 139
 		// We define end of line (RFC 821).
140
-		$this->eol="\r\n";
140
+		$this->eol = "\r\n";
141 141
 		// We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
-		$this->eol2="\r\n";
143
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
142
+		$this->eol2 = "\r\n";
143
+		if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144 144
 		{
145
-			$this->eol="\n";
146
-			$this->eol2="\n";
147
-			$moreinheader = str_replace("\r\n","\n",$moreinheader);
145
+			$this->eol = "\n";
146
+			$this->eol2 = "\n";
147
+			$moreinheader = str_replace("\r\n", "\n", $moreinheader);
148 148
 		}
149 149
 
150 150
 		// On defini mixed_boundary
151
-		$this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
151
+		$this->mixed_boundary = "multipart_x.".time().".x_boundary";
152 152
 
153 153
 		// On defini related_boundary
154
-		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
154
+		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars)
155 155
 
156 156
 		// On defini alternative_boundary
157
-		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
157
+		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars)
158 158
 
159 159
 		dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160 160
 		dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
 		if (empty($subject))
163 163
 		{
164 164
 			dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
-			$this->error='ErrorSubjectIsRequired';
165
+			$this->error = 'ErrorSubjectIsRequired';
166 166
 			return;
167 167
 		}
168 168
 		if (empty($msg))
169 169
 		{
170 170
 		    dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
-		    $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
171
+		    $msg = '.'; // Avoid empty message (with empty message conten show a multipart structure)
172 172
 		}
173 173
 
174 174
 		// Detect if message is HTML (use fast method)
@@ -185,21 +185,21 @@  discard block
 block discarded – undo
185 185
 		global $dolibarr_main_url_root;
186 186
 
187 187
 		// Define $urlwithroot
188
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
188
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
189
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
190 190
 		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191 191
 
192 192
 		// Replace relative /viewimage to absolute path
193
-		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
193
+		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194 194
 
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
195
+		if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml = 1; // To force to send everything with content type html.
196 196
 
197 197
 		// Detect images
198 198
 		if ($this->msgishtml)
199 199
 		{
200 200
 			$this->html = $msg;
201 201
 
202
-			if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
202
+			if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203 203
 			{
204 204
 				$findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205 205
 			}
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 				{
212 212
 					if ($this->html_images[$i])
213 213
 					{
214
-						$this->atleastoneimage=1;
214
+						$this->atleastoneimage = 1;
215 215
 						dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216 216
 					}
217 217
 				}
@@ -225,14 +225,14 @@  discard block
 block discarded – undo
225 225
 			{
226 226
 				if ($filename_list[$i])
227 227
 				{
228
-					$this->atleastonefile=1;
228
+					$this->atleastonefile = 1;
229 229
 					dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230 230
 				}
231 231
 			}
232 232
 		}
233 233
 
234 234
 		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
235
+		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236 236
 
237 237
 		// Action according to choosed sending method
238 238
 		if ($this->sendmode == 'mail')
@@ -257,17 +257,17 @@  discard block
 block discarded – undo
257 257
 			$this->trackid = $trackid;
258 258
 
259 259
 			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
260
+			if (!empty($moreinheader)) $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n
261 261
 
262 262
 			// Define mime_headers
263 263
 			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264 264
 
265
-			if (! empty($this->html))
265
+			if (!empty($this->html))
266 266
 			{
267 267
 				if (!empty($css))
268 268
 				{
269 269
 					$this->css = $css;
270
-					$this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
270
+					$this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271 271
 				}
272 272
 
273 273
 				$msg = $this->html;
@@ -279,20 +279,20 @@  discard block
 block discarded – undo
279 279
 			// Add attachments to text_encoded
280 280
 			if ($this->atleastonefile)
281 281
 			{
282
-				$files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
282
+				$files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list);
283 283
 			}
284 284
 
285 285
 			// We now define $this->headers and $this->message
286
-			$this->headers = $smtp_headers . $mime_headers;
286
+			$this->headers = $smtp_headers.$mime_headers;
287 287
 			// On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288 288
 			// Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289 289
 			// comme des injections mail par les serveurs de messagerie.
290
-			$this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
290
+			$this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers);
291 291
 
292 292
 			//$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293 293
 			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
-			$this->message.= $text_body . $files_encoded;
295
-			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
294
+			$this->message .= $text_body.$files_encoded;
295
+			$this->message .= "--".$this->mixed_boundary."--".$this->eol;
296 296
 		}
297 297
 		else if ($this->sendmode == 'smtps')
298 298
 		{
@@ -304,14 +304,14 @@  discard block
 block discarded – undo
304 304
 			$smtps->setCharSet($conf->file->character_set_client);
305 305
 
306 306
 			$smtps->setSubject($this->encodetorfc2822($subject));
307
-			$smtps->setTO($this->getValidAddress($to,0,1));
308
-			$smtps->setFrom($this->getValidAddress($from,0,1));
307
+			$smtps->setTO($this->getValidAddress($to, 0, 1));
308
+			$smtps->setFrom($this->getValidAddress($from, 0, 1));
309 309
 			$smtps->setTrackId($trackid);
310
-			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
310
+			$smtps->setReplyTo($this->getValidAddress($replyto, 0, 1));
311 311
 
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
312
+			if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313 313
 
314
-			if (! empty($this->html))
314
+			if (!empty($this->html))
315 315
 			{
316 316
 				if (!empty($css))
317 317
 				{
@@ -322,14 +322,14 @@  discard block
 block discarded – undo
322 322
 				$msg = $this->checkIfHTML($msg);
323 323
 			}
324 324
 
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
325
+			if ($this->msgishtml) $smtps->setBodyContent($msg, 'html');
326
+			else $smtps->setBodyContent($msg, 'plain');
327 327
 
328 328
 			if ($this->atleastoneimage)
329 329
 			{
330 330
 				foreach ($this->images_encoded as $img)
331 331
 				{
332
-					$smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
332
+					$smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']);
333 333
 				}
334 334
 			}
335 335
 
@@ -337,8 +337,8 @@  discard block
 block discarded – undo
337 337
 			{
338 338
 				foreach ($filename_list as $i => $val)
339 339
 				{
340
-					$content=file_get_contents($filename_list[$i]);
341
-					$smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
340
+					$content = file_get_contents($filename_list[$i]);
341
+					$smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i]);
342 342
 				}
343 343
 			}
344 344
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 			$smtps->setErrorsTo($errors_to);
348 348
 			$smtps->setDeliveryReceipt($deliveryreceipt);
349 349
 
350
-			$this->smtps=$smtps;
350
+			$this->smtps = $smtps;
351 351
 		}
352 352
 		else if ($this->sendmode == 'swiftmailer')
353 353
 		{
@@ -383,8 +383,8 @@  discard block
 block discarded – undo
383 383
             //$this->message = new Swift_SignedMessage();
384 384
             // Adding a trackid header to a message
385 385
 			$headers = $this->message->getHeaders();
386
-			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
-			$headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
386
+			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid.'@'.$host);
387
+			$headerID = time().'.swiftmailer-dolibarr-'.$trackid.'@'.$host;
388 388
 			$msgid = $headers->get('Message-ID');
389 389
 			$msgid->setId($headerID);
390 390
 			$headers->addIdHeader('References', $headerID);
@@ -394,12 +394,12 @@  discard block
 block discarded – undo
394 394
 			try {
395 395
 				$result = $this->message->setSubject($subject);
396 396
 			} catch (Exception $e) {
397
-				$this->errors[] =  $e->getMessage();
397
+				$this->errors[] = $e->getMessage();
398 398
 			}
399 399
 
400 400
 			// Set the From address with an associative array
401 401
 			//$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
-			if (! empty($from)) {
402
+			if (!empty($from)) {
403 403
                 try {
404 404
                 	$result = $this->message->setFrom($this->getArrayAddress($from));
405 405
                 } catch (Exception $e) {
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
             }
409 409
 
410 410
 			// Set the To addresses with an associative array
411
-			if (! empty($to)) {
411
+			if (!empty($to)) {
412 412
                 try {
413 413
                 	$result = $this->message->setTo($this->getArrayAddress($to));
414 414
                 } catch (Exception $e) {
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
                 }
417 417
             }
418 418
 
419
-			if (! empty($replyto)) {
419
+			if (!empty($replyto)) {
420 420
                 try {
421 421
                 	$result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
422 422
                 } catch (Exception $e) {
@@ -427,10 +427,10 @@  discard block
 block discarded – undo
427 427
 			try {
428 428
 				$result = $this->message->setCharSet($conf->file->character_set_client);
429 429
 			} catch (Exception $e) {
430
-				$this->errors[] =  $e->getMessage();
430
+				$this->errors[] = $e->getMessage();
431 431
 			}
432 432
 
433
-			if (! empty($this->html))
433
+			if (!empty($this->html))
434 434
 			{
435 435
 				if (!empty($css))
436 436
 				{
@@ -455,11 +455,11 @@  discard block
 block discarded – undo
455 455
 			}
456 456
 
457 457
 			if ($this->msgishtml) {
458
-				$this->message->setBody($msg,'text/html');
458
+				$this->message->setBody($msg, 'text/html');
459 459
 				// And optionally an alternative body
460 460
 				$this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461 461
 			} else {
462
-				$this->message->setBody($msg,'text/plain');
462
+				$this->message->setBody($msg, 'text/plain');
463 463
 				// And optionally an alternative body
464 464
 				$this->message->addPart($msg, 'text/html');
465 465
 			}
@@ -469,13 +469,13 @@  discard block
 block discarded – undo
469 469
 				foreach ($filename_list as $i => $val)
470 470
 				{
471 471
 					//$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
-					$attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
472
+					$attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
473 473
 					$this->message->attach($attachment);
474 474
 				}
475 475
 			}
476 476
 
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
477
+			if (!empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
+			if (!empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479 479
 			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480 480
 			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481 481
 		}
@@ -495,25 +495,25 @@  discard block
 block discarded – undo
495 495
 	 */
496 496
 	function sendfile()
497 497
 	{
498
-		global $conf,$db,$langs;
498
+		global $conf, $db, $langs;
499 499
 
500
-		$errorlevel=error_reporting();
500
+		$errorlevel = error_reporting();
501 501
 		//error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502 502
 
503
-		$res=false;
503
+		$res = false;
504 504
 
505 505
 		if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506 506
 		{
507
-			require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
507
+			require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
508 508
 			$hookmanager = new HookManager($db);
509 509
 			$hookmanager->initHooks(array('mail'));
510 510
 
511
-			$parameters=array(); $action='';
511
+			$parameters = array(); $action = '';
512 512
 			$reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513 513
 			if ($reshook < 0)
514 514
 			{
515
-				$this->error = "Error in hook maildao sendMail " . $reshook;
516
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
515
+				$this->error = "Error in hook maildao sendMail ".$reshook;
516
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
517 517
 
518 518
 				return $reshook;
519 519
 			}
@@ -523,52 +523,52 @@  discard block
 block discarded – undo
523 523
 			}
524 524
 
525 525
 			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
526
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
527 527
 			$tmparray1 = explode(',', $this->addr_to);
528 528
 			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529 529
 			{
530 530
 				$this->error = 'Too much recipients in to:';
531
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
531
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
532 532
 				return false;
533 533
 			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
534
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
535 535
 			$tmparray2 = explode(',', $this->addr_cc);
536 536
 			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537 537
 			{
538 538
 				$this->error = 'Too much recipients in cc:';
539
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
539
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
540 540
 				return false;
541 541
 			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
542
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
543 543
 			$tmparray3 = explode(',', $this->addr_bcc);
544 544
 			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545 545
 			{
546 546
 				$this->error = 'Too much recipients in bcc:';
547
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
547
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
548 548
 				return false;
549 549
 			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
-			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
550
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
551
+			if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552 552
 			{
553 553
 				$this->error = 'Too much recipients in to:, cc:, bcc:';
554
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
554
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
555 555
 				return false;
556 556
 			}
557 557
 
558
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
558
+			$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
559
+			$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT';
560
+			$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID';
561
+			$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW';
562
+			$keyfortls       = 'MAIN_MAIL_EMAIL_TLS';
563
+			$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS';
564 564
 			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565 565
 			{
566
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
566
+				$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING';
567
+				$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT_EMAILING';
568
+				$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID_EMAILING';
569
+				$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW_EMAILING';
570
+				$keyfortls       = 'MAIN_MAIL_EMAIL_TLS_EMAILING';
571
+				$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572 572
 			}
573 573
 
574 574
 			if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
@@ -591,68 +591,68 @@  discard block
 block discarded – undo
591 591
 				if (isset($_SERVER["WINDIR"]))
592 592
 				{
593 593
 					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
-					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
594
+					@ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
595 595
 				}
596 596
 
597 597
 				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
598
+				if (!empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver);
599
+				if (!empty($conf->global->$keyforsmtpport))   ini_set('smtp_port', $conf->global->$keyforsmtpport);
600 600
 
601
-				$res=true;
602
-				if ($res && ! $this->subject)
601
+				$res = true;
602
+				if ($res && !$this->subject)
603 603
 				{
604
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
604
+					$this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605 605
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
-					$res=false;
606
+					$res = false;
607 607
 				}
608
-				$dest=$this->getValidAddress($this->addr_to,2);
609
-				if ($res && ! $dest)
608
+				$dest = $this->getValidAddress($this->addr_to, 2);
609
+				if ($res && !$dest)
610 610
 				{
611
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
611
+					$this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612 612
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
-					$res=false;
613
+					$res = false;
614 614
 				}
615 615
 
616 616
 				if ($res)
617 617
 				{
618
-					$additionnalparam = '';	// By default
619
-					if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
618
+					$additionnalparam = ''; // By default
619
+					if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620 620
 					{
621 621
 						// le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622 622
 						// Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623 623
 						// Having this variable defined may create problems with some sendmail (option -f refused)
624 624
 						// Having this variable not defined may create problems with some other sendmail (option -f required)
625
-						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
625
+						$additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : ''));
626 626
 					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
627
+					if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628 628
 					{
629
-						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
629
+						$additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
630 630
 					}
631 631
 
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
632
+					if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params
633 633
 
634 634
 					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635 635
 
636
-					$this->message=stripslashes($this->message);
636
+					$this->message = stripslashes($this->message);
637 637
 
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
638
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639 639
 
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
640
+					if (!empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641 641
 					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642 642
 
643
-					if (! $res)
643
+					if (!$res)
644 644
 					{
645 645
 						$langs->load("errors");
646
-						$this->error="Failed to send mail with php mail";
647
-						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
-						if (! $linuxlike)
646
+						$this->error = "Failed to send mail with php mail";
647
+						$linuxlike = 1;
648
+						if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0;
649
+						if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0;
650
+						if (!$linuxlike)
651 651
 						{
652
-							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
652
+							$this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
653 653
 						}
654
-						$this->error.=".<br>";
655
-						$this->error.=$langs->trans("ErrorPhpMailDelivery");
654
+						$this->error .= ".<br>";
655
+						$this->error .= $langs->trans("ErrorPhpMailDelivery");
656 656
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657 657
 					}
658 658
 					else
@@ -667,86 +667,86 @@  discard block
 block discarded – undo
667 667
 				}
668 668
 
669 669
 				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
670
+				if (!empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
+				if (!empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672 672
 			}
673 673
 			else if ($this->sendmode == 'smtps')
674 674
 			{
675
-				if (! is_object($this->smtps))
675
+				if (!is_object($this->smtps))
676 676
 				{
677
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
677
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678 678
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679 679
 					return false;
680 680
 				}
681 681
 
682 682
 				// Use SMTPS library
683 683
 				// ------------------------------------------
684
-				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
684
+				$this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
685 685
 
686 686
 				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
687
+				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP');
688
+				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport = ini_get('smtp_port');
689 689
 
690 690
 				// If we use SSL/TLS
691
-				$server=$conf->global->$keyforsmtpserver;
692
-				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
-				$server=($secure?$secure.'://':'').$server;
691
+				$server = $conf->global->$keyforsmtpserver;
692
+				$secure = '';
693
+				if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl';
694
+				if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls';
695
+				$server = ($secure ? $secure.'://' : '').$server;
696 696
 
697
-				$port=$conf->global->$keyforsmtpport;
697
+				$port = $conf->global->$keyforsmtpport;
698 698
 
699 699
 				$this->smtps->setHost($server);
700 700
 				$this->smtps->setPort($port); // 25, 465...;
701 701
 
702
-				$loginid=''; $loginpass='';
703
-				if (! empty($conf->global->$keyforsmtpid))
702
+				$loginid = ''; $loginpass = '';
703
+				if (!empty($conf->global->$keyforsmtpid))
704 704
 				{
705 705
 					$loginid = $conf->global->$keyforsmtpid;
706 706
 					$this->smtps->setID($loginid);
707 707
 				}
708
-				if (! empty($conf->global->$keyforsmtppw))
708
+				if (!empty($conf->global->$keyforsmtppw))
709 709
 				{
710 710
 					$loginpass = $conf->global->$keyforsmtppw;
711 711
 					$this->smtps->setPW($loginpass);
712 712
 				}
713 713
 
714
-				$res=true;
715
-				$from=$this->smtps->getFrom('org');
716
-				if ($res && ! $from)
714
+				$res = true;
715
+				$from = $this->smtps->getFrom('org');
716
+				if ($res && !$from)
717 717
 				{
718
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
718
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719 719
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
-					$res=false;
720
+					$res = false;
721 721
 				}
722
-				$dest=$this->smtps->getTo();
723
-				if ($res && ! $dest)
722
+				$dest = $this->smtps->getTo();
723
+				if ($res && !$dest)
724 724
 				{
725
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
725
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726 726
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
-					$res=false;
727
+					$res = false;
728 728
 				}
729 729
 
730 730
 				if ($res)
731 731
 				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
732
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733 733
 
734
-					$result=$this->smtps->sendMsg();
734
+					$result = $this->smtps->sendMsg();
735 735
 					//print $result;
736 736
 
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
737
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738 738
 
739
-					$result=$this->smtps->getErrors();
739
+					$result = $this->smtps->getErrors();
740 740
 					if (empty($this->error) && empty($result))
741 741
 					{
742 742
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
-						$res=true;
743
+						$res = true;
744 744
 					}
745 745
 					else
746 746
 					{
747
-						if (empty($this->error)) $this->error=$result;
747
+						if (empty($this->error)) $this->error = $result;
748 748
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
-						$res=false;
749
+						$res = false;
750 750
 					}
751 751
 				}
752 752
 			}
@@ -757,19 +757,19 @@  discard block
 block discarded – undo
757 757
 				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758 758
 
759 759
 				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
760
+				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP');
761
+				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport = ini_get('smtp_port');
762 762
 
763 763
 				// If we use SSL/TLS
764 764
 				$server = $conf->global->$keyforsmtpserver;
765 765
 				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
766
+				if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl';
767
+				if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls';
768 768
 
769 769
 				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770 770
 
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
771
+				if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
+				if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773 773
 				//$smtps->_msgReplyTo  = '[email protected]';
774 774
 
775 775
 				// Create the Mailer using your created Transport
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
                     $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
785 785
                 }
786 786
 
787
-                if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
787
+                if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
788 788
 					// To use the ArrayLogger
789 789
 					$this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790 790
 					// Or to use the Echo Logger
@@ -795,14 +795,14 @@  discard block
 block discarded – undo
795 795
 				try {
796 796
 					$result = $this->mailer->send($this->message);
797 797
 				} catch (Exception $e) {
798
-					$this->error =  $e->getMessage();
798
+					$this->error = $e->getMessage();
799 799
 				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
800
+				if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801 801
 
802 802
 				$res = true;
803
-				if (! empty($this->error) || ! $result) {
803
+				if (!empty($this->error) || !$result) {
804 804
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
-					$res=false;
805
+					$res = false;
806 806
 				}
807 807
 				else
808 808
 				{
@@ -817,23 +817,23 @@  discard block
 block discarded – undo
817 817
 				return 'Bad value for sendmode';
818 818
 			}
819 819
 
820
-			$parameters=array(); $action='';
820
+			$parameters = array(); $action = '';
821 821
 			$reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822 822
 			if ($reshook < 0)
823 823
 			{
824
-				$this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
824
+				$this->error = "Error in hook maildao sendMailAfter ".$reshook;
825
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
826 826
 
827 827
 				return $reshook;
828 828
 			}
829 829
 		}
830 830
 		else
831 831
 		{
832
-			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
832
+			$this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833 833
 			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834 834
 		}
835 835
 
836
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
836
+		error_reporting($errorlevel); // Reactive niveau erreur origine
837 837
 
838 838
 		return $res;
839 839
 	}
@@ -860,17 +860,17 @@  discard block
 block discarded – undo
860 860
 	function _encode_file($sourcefile)
861 861
 	{
862 862
         // phpcs:enable
863
-		$newsourcefile=dol_osencode($sourcefile);
863
+		$newsourcefile = dol_osencode($sourcefile);
864 864
 
865 865
 		if (is_readable($newsourcefile))
866 866
 		{
867
-			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
-			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
867
+			$contents = file_get_contents($newsourcefile); // Need PHP 4.3
868
+			$encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
869 869
 			return $encoded;
870 870
 		}
871 871
 		else
872 872
 		{
873
-			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
873
+			$this->error = "Error: Can't read file '".$sourcefile."' into _encode_file";
874 874
 			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875 875
 			return -1;
876 876
 		}
@@ -888,30 +888,30 @@  discard block
 block discarded – undo
888 888
 	function dump_mail()
889 889
 	{
890 890
         // phpcs:enable
891
-		global $conf,$dolibarr_main_data_root;
891
+		global $conf, $dolibarr_main_data_root;
892 892
 
893 893
 		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894 894
 		{
895
-			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
-			$fp = fopen($outputfile,"w");
895
+			$outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
896
+			$fp = fopen($outputfile, "w");
897 897
 
898 898
 			if ($this->sendmode == 'mail')
899 899
 			{
900 900
 				fputs($fp, $this->headers);
901
-				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
901
+				fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log
902 902
 				fputs($fp, $this->message);
903 903
 			}
904 904
 			elseif ($this->sendmode == 'smtps')
905 905
 			{
906
-				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
906
+				fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907 907
 			}
908 908
 			elseif ($this->sendmode == 'swiftmailer')
909 909
 			{
910
-				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
910
+				fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911 911
 			}
912 912
 
913 913
 			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
914
+			if (!empty($conf->global->MAIN_UMASK))
915 915
 				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916 916
 		}
917 917
 	}
@@ -925,15 +925,15 @@  discard block
 block discarded – undo
925 925
 	 */
926 926
 	function checkIfHTML($msg)
927 927
 	{
928
-		if (!preg_match('/^[\s\t]*<html/i',$msg))
928
+		if (!preg_match('/^[\s\t]*<html/i', $msg))
929 929
 		{
930 930
 			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
-			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
-			$out.= ">";
935
-			$out.= $msg;
936
-			$out.= "</body></html>";
931
+			if (!empty($this->styleCSS)) $out .= $this->styleCSS;
932
+			$out .= "</head><body";
933
+			if (!empty($this->bodyCSS)) $out .= $this->bodyCSS;
934
+			$out .= ">";
935
+			$out .= $msg;
936
+			$out .= "</body></html>";
937 937
 		}
938 938
 		else
939 939
 		{
@@ -950,24 +950,24 @@  discard block
 block discarded – undo
950 950
 	 */
951 951
 	function buildCSS()
952 952
 	{
953
-		if (! empty($this->css))
953
+		if (!empty($this->css))
954 954
 		{
955 955
 			// Style CSS
956 956
 			$this->styleCSS = '<style type="text/css">';
957
-			$this->styleCSS.= 'body {';
957
+			$this->styleCSS .= 'body {';
958 958
 
959 959
 			if ($this->css['bgcolor'])
960 960
 			{
961
-				$this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
-				$this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
961
+				$this->styleCSS .= '  background-color: '.$this->css['bgcolor'].';';
962
+				$this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
963 963
 			}
964 964
 			if ($this->css['bgimage'])
965 965
 			{
966 966
 				// TODO recuperer cid
967
-				$this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
967
+				$this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968 968
 			}
969
-			$this->styleCSS.= '}';
970
-			$this->styleCSS.= '</style>';
969
+			$this->styleCSS .= '}';
970
+			$this->styleCSS .= '</style>';
971 971
 		}
972 972
 	}
973 973
 
@@ -988,48 +988,48 @@  discard block
 block discarded – undo
988 988
 
989 989
 		// Sender
990 990
 		//$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
-		$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
-		if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
991
+		$out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
992
+		if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993 993
 		{
994
-			$out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
994
+			$out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
995 995
 		}
996 996
 		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
-		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
997
+		$out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
998
+		if (isset($this->reply_to) && $this->reply_to)  $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
999
+		if (isset($this->errors_to) && $this->errors_to) $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1000 1000
 
1001 1001
 		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1002
+		if (isset($this->addr_cc) && $this->addr_cc)   $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1003
+		if (isset($this->addr_bcc) && $this->addr_bcc)  $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1004
 
1005 1005
 		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1006
+		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1007 1007
 
1008 1008
 		//$out.= "X-Priority: 3".$this->eol2;
1009 1009
 
1010
-		$out.= 'Date: ' . date("r") . $this->eol2;
1010
+		$out .= 'Date: '.date("r").$this->eol2;
1011 1011
 
1012 1012
 		$trackid = $this->trackid;
1013 1013
 		if ($trackid)
1014 1014
 		{
1015 1015
 			// References is kept in response and Message-ID is returned into In-Reply-To:
1016
-			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
-			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
-			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1016
+			$out .= 'Message-ID: <'.time().'.phpmail-dolibarr-'.$trackid.'@'.$host.">".$this->eol2; // Uppercase seems replaced by phpmail
1017
+			$out .= 'References: <'.time().'.phpmail-dolibarr-'.$trackid.'@'.$host.">".$this->eol2;
1018
+			$out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
1019 1019
 		}
1020 1020
 		else
1021 1021
 		{
1022
-			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1022
+			$out .= 'Message-ID: <'.time().'.phpmail@'.$host.">".$this->eol2;
1023 1023
 		}
1024 1024
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
-		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
-		$out.= "Mime-Version: 1.0".$this->eol2;
1025
+		if (!empty($_SERVER['REMOTE_ADDR'])) $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
1026
+		$out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
1027
+		$out .= "Mime-Version: 1.0".$this->eol2;
1028 1028
 
1029 1029
 		//$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1030 1030
 
1031
-		$out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
-		$out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1031
+		$out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
+		$out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
1033 1033
 
1034 1034
 		dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035 1035
 		return $out;
@@ -1047,18 +1047,18 @@  discard block
 block discarded – undo
1047 1047
 	function write_mimeheaders($filename_list, $mimefilename_list)
1048 1048
 	{
1049 1049
         // phpcs:enable
1050
-		$mimedone=0;
1050
+		$mimedone = 0;
1051 1051
 		$out = "";
1052 1052
 
1053 1053
 		if (is_array($filename_list))
1054 1054
 		{
1055
-			$filename_list_size=count($filename_list);
1056
-			for($i=0;$i < $filename_list_size;$i++)
1055
+			$filename_list_size = count($filename_list);
1056
+			for ($i = 0; $i < $filename_list_size; $i++)
1057 1057
 			{
1058 1058
 				if ($filename_list[$i])
1059 1059
 				{
1060 1060
 					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
-					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1061
+					$out .= "X-attachments: $filename_list[$i]".$this->eol2;
1062 1062
 				}
1063 1063
 			}
1064 1064
 		}
@@ -1079,31 +1079,31 @@  discard block
 block discarded – undo
1079 1079
         // phpcs:enable
1080 1080
 		global $conf;
1081 1081
 
1082
-		$out='';
1082
+		$out = '';
1083 1083
 
1084
-		$out.= "--" . $this->mixed_boundary . $this->eol;
1084
+		$out .= "--".$this->mixed_boundary.$this->eol;
1085 1085
 
1086 1086
 		if ($this->atleastoneimage)
1087 1087
 		{
1088
-			$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
-			$out.= $this->eol;
1090
-			$out.= "--" . $this->alternative_boundary . $this->eol;
1088
+			$out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
+			$out .= $this->eol;
1090
+			$out .= "--".$this->alternative_boundary.$this->eol;
1091 1091
 		}
1092 1092
 
1093 1093
 		// Make RFC821 Compliant, replace bare linefeeds
1094
-		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1094
+		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
1095
+		if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096 1096
 		{
1097
-			$strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1097
+			$strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
1098 1098
 		}
1099 1099
 
1100 1100
 		$strContentAltText = '';
1101 1101
 		if ($this->msgishtml)
1102 1102
 		{
1103 1103
 			// Similar code to forge a text from html is also in CMailFile.class.php
1104
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1104
+			$strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1105 1105
 			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
-			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1106
+			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n"));
1107 1107
 
1108 1108
 			// Check if html header already in message, if not complete the message
1109 1109
 			$strContent = $this->checkIfHTML($strContent);
@@ -1112,57 +1112,57 @@  discard block
 block discarded – undo
1112 1112
 		// Make RFC2045 Compliant, split lines
1113 1113
 		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114 1114
 		// TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
-		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1115
+		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content.
1116 1116
 
1117 1117
 		if ($this->msgishtml)
1118 1118
 		{
1119 1119
 			if ($this->atleastoneimage)
1120 1120
 			{
1121
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1121
+				$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122 1122
 				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
-				$out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1125
-				$out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
-				$out.= $this->eol;
1127
-				$out.= "--" . $this->related_boundary . $this->eol;
1123
+				$out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
1124
+				$out .= "--".$this->alternative_boundary.$this->eol;
1125
+				$out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
+				$out .= $this->eol;
1127
+				$out .= "--".$this->related_boundary.$this->eol;
1128 1128
 			}
1129 1129
 
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1130
+			if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131 1131
 			{
1132
-				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
-				$out.= $this->eol;
1134
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1135
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1132
+				$out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
+				$out .= $this->eol;
1134
+				$out .= "--".$this->alternative_boundary.$this->eol;
1135
+				$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136 1136
 				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
-				$out.= $this->eol.$strContentAltText.$this->eol;
1138
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1137
+				$out .= $this->eol.$strContentAltText.$this->eol;
1138
+				$out .= "--".$this->alternative_boundary.$this->eol;
1139 1139
 			}
1140 1140
 
1141
-			$out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1141
+			$out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142 1142
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
-			$out.= $this->eol.$strContent.$this->eol;
1143
+			$out .= $this->eol.$strContent.$this->eol;
1144 1144
 
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1145
+			if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146 1146
 			{
1147
-				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1147
+				$out .= "--".$this->alternative_boundary."--".$this->eol;
1148 1148
 			}
1149 1149
 		}
1150 1150
 		else
1151 1151
 		{
1152
-			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1152
+			$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153 1153
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
-			$out.= $this->eol.$strContent.$this->eol;
1154
+			$out .= $this->eol.$strContent.$this->eol;
1155 1155
 		}
1156 1156
 
1157
-		$out.= $this->eol;
1157
+		$out .= $this->eol;
1158 1158
 
1159 1159
 		// Encode images
1160 1160
 		if ($this->atleastoneimage)
1161 1161
 		{
1162 1162
 			$out .= $this->write_images($this->images_encoded);
1163 1163
 			// always end related and end alternative after inline images
1164
-			$out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
-			$out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1164
+			$out .= "--".$this->related_boundary."--".$this->eol;
1165
+			$out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
1166 1166
 			$out .= $this->eol;
1167 1167
 		}
1168 1168
 
@@ -1178,13 +1178,13 @@  discard block
 block discarded – undo
1178 1178
 	 * @param 	array	$mimefilename_list	Tableau
1179 1179
 	 * @return	string						Chaine fichiers encodes
1180 1180
 	 */
1181
-	function write_files($filename_list,$mimetype_list,$mimefilename_list)
1181
+	function write_files($filename_list, $mimetype_list, $mimefilename_list)
1182 1182
 	{
1183 1183
         // phpcs:enable
1184 1184
 		$out = '';
1185 1185
 
1186
-		$filename_list_size=count($filename_list);
1187
-		for($i=0;$i < $filename_list_size;$i++)
1186
+		$filename_list_size = count($filename_list);
1187
+		for ($i = 0; $i < $filename_list_size; $i++)
1188 1188
 		{
1189 1189
 			if ($filename_list[$i])
1190 1190
 			{
@@ -1193,18 +1193,18 @@  discard block
 block discarded – undo
1193 1193
 				if ($encoded >= 0)
1194 1194
 				{
1195 1195
 					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
-					if (! $mimetype_list[$i]) {
1196
+					if (!$mimetype_list[$i]) {
1197 1197
 						$mimetype_list[$i] = "application/octet-stream";
1198 1198
 					}
1199 1199
 
1200
-					$out.= "--" . $this->mixed_boundary . $this->eol;
1201
-					$out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
-					$out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
-					$out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
-					$out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
-					$out.= $this->eol;
1206
-					$out.= $encoded;
1207
-					$out.= $this->eol;
1200
+					$out .= "--".$this->mixed_boundary.$this->eol;
1201
+					$out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
+					$out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
1203
+					$out .= "Content-Transfer-Encoding: base64".$this->eol;
1204
+					$out .= "Content-Description: ".$filename_list[$i].$this->eol;
1205
+					$out .= $this->eol;
1206
+					$out .= $encoded;
1207
+					$out .= $this->eol;
1208 1208
 					//$out.= $this->eol;
1209 1209
 				}
1210 1210
 				else
@@ -1236,14 +1236,14 @@  discard block
 block discarded – undo
1236 1236
 			{
1237 1237
 				dol_syslog("CMailFile::write_images: ".$img["name"]);
1238 1238
 
1239
-				$out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
-				$out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
-				$out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
-				$out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
-				$out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
-				$out.= $this->eol;
1245
-				$out.= $img["image_encoded"];
1246
-				$out.= $this->eol;
1239
+				$out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
1240
+				$out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
1241
+				$out .= "Content-Transfer-Encoding: base64".$this->eol;
1242
+				$out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
+				$out .= "Content-ID: <".$img["cid"].">".$this->eol;
1244
+				$out .= $this->eol;
1245
+				$out .= $img["image_encoded"];
1246
+				$out .= $this->eol;
1247 1247
 			}
1248 1248
 		}
1249 1249
 
@@ -1259,44 +1259,44 @@  discard block
 block discarded – undo
1259 1259
 	 * @param 	int			$port		Example: 25, 465
1260 1260
 	 * @return	int						Socket id if ok, 0 if KO
1261 1261
 	 */
1262
-	function check_server_port($host,$port)
1262
+	function check_server_port($host, $port)
1263 1263
 	{
1264 1264
         // phpcs:enable
1265 1265
 		global $conf;
1266 1266
 
1267
-		$_retVal=0;
1268
-		$timeout=5;	// Timeout in seconds
1267
+		$_retVal = 0;
1268
+		$timeout = 5; // Timeout in seconds
1269 1269
 
1270 1270
 		if (function_exists('fsockopen'))
1271 1271
 		{
1272
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1272
+			$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
1273
+			$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT';
1274
+			$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID';
1275
+			$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW';
1276
+			$keyfortls       = 'MAIN_MAIL_EMAIL_TLS';
1277
+			$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS';
1278 1278
 			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279 1279
 			{
1280
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1280
+				$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
+				$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT_EMAILING';
1282
+				$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID_EMAILING';
1283
+				$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW_EMAILING';
1284
+				$keyfortls       = 'MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
+				$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286 1286
 			}
1287 1287
 
1288 1288
 			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1289
+			if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host = 'ssl://'.$host;
1290 1290
 			// tls smtp start with no encryption
1291 1291
 			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292 1292
 
1293 1293
 			dol_syslog("Try socket connection to host=".$host." port=".$port);
1294 1294
 			//See if we can connect to the SMTP server
1295 1295
 			if ($socket = @fsockopen(
1296
-					$host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
-					$port,       // which Port number to use
1298
-					$errno,      // actual system level error
1299
-					$errstr,     // and any text that goes with the error
1296
+					$host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
+					$port, // which Port number to use
1298
+					$errno, // actual system level error
1299
+					$errstr, // and any text that goes with the error
1300 1300
 					$timeout
1301 1301
 			))  // timeout for reading/writing data over the socket
1302 1302
 			{
@@ -1306,11 +1306,11 @@  discard block
 block discarded – undo
1306 1306
 				dol_syslog("Now we wait for answer 220");
1307 1307
 
1308 1308
 				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1309
+				if ($_retVal = $this->server_parse($socket, "220")) $_retVal = $socket;
1310 1310
 			}
1311 1311
 			else
1312 1312
 			{
1313
-				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1313
+				$this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr);
1314 1314
 			}
1315 1315
 		}
1316 1316
 		return $_retVal;
@@ -1328,21 +1328,21 @@  discard block
 block discarded – undo
1328 1328
 	function server_parse($socket, $response)
1329 1329
 	{
1330 1330
         // phpcs:enable
1331
-		$_retVal = true;	// Indicates if Object was created or not
1331
+		$_retVal = true; // Indicates if Object was created or not
1332 1332
 		$server_response = '';
1333 1333
 
1334
-		while (substr($server_response,3,1) != ' ')
1334
+		while (substr($server_response, 3, 1) != ' ')
1335 1335
 		{
1336
-			if (! ($server_response = fgets($socket, 256)) )
1336
+			if (!($server_response = fgets($socket, 256)))
1337 1337
 			{
1338
-				$this->error="Couldn't get mail server response codes";
1338
+				$this->error = "Couldn't get mail server response codes";
1339 1339
 				return false;
1340 1340
 			}
1341 1341
 		}
1342 1342
 
1343
-		if( !( substr($server_response, 0, 3) == $response ) )
1343
+		if (!(substr($server_response, 0, 3) == $response))
1344 1344
 		{
1345
-			$this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1345
+			$this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
1346 1346
 			$_retVal = false;
1347 1347
 		}
1348 1348
 
@@ -1361,22 +1361,22 @@  discard block
 block discarded – undo
1361 1361
 		$extensions = array_keys($this->image_types);
1362 1362
 
1363 1363
 		$matches = array();
1364
-		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1364
+		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
1365 1365
 
1366
-		if (! empty($matches))
1366
+		if (!empty($matches))
1367 1367
 		{
1368
-			$i=0;
1368
+			$i = 0;
1369 1369
 			foreach ($matches[1] as $full)
1370 1370
 			{
1371 1371
 
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1372
+				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs))   // If xxx is 'file=aaa'
1373 1373
 				{
1374 1374
 					$img = $regs[1];
1375 1375
 
1376 1376
 					if (file_exists($images_dir.'/'.$img))
1377 1377
 					{
1378 1378
 						// Image path in src
1379
-						$src = preg_quote($full,'/');
1379
+						$src = preg_quote($full, '/');
1380 1380
 
1381 1381
 						// Image full path
1382 1382
 						$this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
@@ -1387,12 +1387,12 @@  discard block
 block discarded – undo
1387 1387
 						// Content type
1388 1388
 						if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389 1389
 						{
1390
-							$ext=strtolower($reg[1]);
1390
+							$ext = strtolower($reg[1]);
1391 1391
 							$this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392 1392
 						}
1393 1393
 
1394 1394
 						// cid
1395
-						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1395
+						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars)
1396 1396
 						$this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397 1397
 					}
1398 1398
 					$i++;
@@ -1403,20 +1403,20 @@  discard block
 block discarded – undo
1403 1403
 			{
1404 1404
 				$inline = array();
1405 1405
 
1406
-				$i=0;
1406
+				$i = 0;
1407 1407
 
1408 1408
 				foreach ($this->html_images as $img)
1409 1409
 				{
1410 1410
 					$fullpath = $images_dir.'/'.$img["name"];
1411 1411
 
1412 1412
 					// If duplicate images are embedded, they may show up as attachments, so remove them.
1413
-					if (!in_array($fullpath,$inline))
1413
+					if (!in_array($fullpath, $inline))
1414 1414
 					{
1415 1415
 						// Read image file
1416 1416
 						if ($image = file_get_contents($fullpath))
1417 1417
 						{
1418 1418
 							// On garde que le nom de l'image
1419
-							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1419
+							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
1420 1420
 							$imgName = $regs[1];
1421 1421
 
1422 1422
 							$this->images_encoded[$i]['name'] = $imgName;
@@ -1457,19 +1457,19 @@  discard block
 block discarded – undo
1457 1457
 	 *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458 1458
 	 *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459 1459
 	 */
1460
-	static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1460
+	static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
1461 1461
 	{
1462 1462
 		global $conf;
1463 1463
 
1464
-		$ret='';
1464
+		$ret = '';
1465 1465
 
1466
-		$arrayaddress=explode(',',$address);
1466
+		$arrayaddress = explode(',', $address);
1467 1467
 
1468 1468
 		// Boucle sur chaque composant de l'adresse
1469
-		$i=0;
1470
-		foreach($arrayaddress as $val)
1469
+		$i = 0;
1470
+		foreach ($arrayaddress as $val)
1471 1471
 		{
1472
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1472
+			if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs))
1473 1473
 			{
1474 1474
 				$name  = trim($regs[1]);
1475 1475
 				$email = trim($regs[2]);
@@ -1484,32 +1484,32 @@  discard block
 block discarded – undo
1484 1484
 			{
1485 1485
 				$i++;
1486 1486
 
1487
-				$newemail='';
1487
+				$newemail = '';
1488 1488
 				if ($format == 4)
1489 1489
 				{
1490
-					$newemail = $name?$name:$email;
1490
+					$newemail = $name ? $name : $email;
1491 1491
 				}
1492 1492
 				if ($format == 2)
1493 1493
 				{
1494
-					$newemail=$email;
1494
+					$newemail = $email;
1495 1495
 				}
1496 1496
 				if ($format == 1 || $format == 3)
1497 1497
 				{
1498
-					$newemail='<'.$email.'>';
1498
+					$newemail = '<'.$email.'>';
1499 1499
 				}
1500 1500
 				if ($format == 0 || $format == 3)
1501 1501
 				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1502
+					if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail = '<'.$email.'>';
1503
+					elseif (!$name) $newemail = '<'.$email.'>';
1504
+					else $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>';
1505 1505
 				}
1506 1506
 
1507
-				$ret=($ret ? $ret.',' : '').$newemail;
1507
+				$ret = ($ret ? $ret.',' : '').$newemail;
1508 1508
 
1509 1509
 				// Stop if we have too much records
1510 1510
 				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511 1511
 				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1512
+					if (count($arrayaddress) > $maxnumberofemail) $ret .= '...';
1513 1513
 					break;
1514 1514
 				}
1515 1515
 			}
@@ -1528,14 +1528,14 @@  discard block
 block discarded – undo
1528 1528
 	{
1529 1529
 		global $conf;
1530 1530
 
1531
-		$ret=array();
1531
+		$ret = array();
1532 1532
 
1533
-		$arrayaddress=explode(',',$address);
1533
+		$arrayaddress = explode(',', $address);
1534 1534
 
1535 1535
 		// Boucle sur chaque composant de l'adresse
1536
-		foreach($arrayaddress as $val)
1536
+		foreach ($arrayaddress as $val)
1537 1537
 		{
1538
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1538
+			if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs))
1539 1539
 			{
1540 1540
 				$name  = trim($regs[1]);
1541 1541
 				$email = trim($regs[2]);
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
 				$email = trim($val);
1547 1547
 			}
1548 1548
 
1549
-			$ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1549
+			$ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name : null;
1550 1550
 		}
1551 1551
 
1552 1552
 		return $ret;
Please login to merge, or discard this patch.
Braces   +221 added lines, -113 removed lines patch added patch discarded remove patch
@@ -125,7 +125,9 @@  discard block
 block discarded – undo
125 125
 
126 126
 		$this->sendcontext = $sendcontext;
127 127
 
128
-		if (empty($replyto)) $replyto=$from;
128
+		if (empty($replyto)) {
129
+		    $replyto=$from;
130
+		}
129 131
 
130 132
 		// Define this->sendmode
131 133
 		$this->sendmode = '';
@@ -133,8 +135,12 @@  discard block
 block discarded – undo
133 135
 		{
134 136
 			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135 137
 		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
138
+		if (empty($this->sendmode)) {
139
+		    $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
140
+		}
141
+		if (empty($this->sendmode)) {
142
+		    $this->sendmode='mail';
143
+		}
138 144
 
139 145
 		// We define end of line (RFC 821).
140 146
 		$this->eol="\r\n";
@@ -175,9 +181,10 @@  discard block
 block discarded – undo
175 181
 		if ($msgishtml == -1)
176 182
 		{
177 183
 			$this->msgishtml = 0;
178
-			if (dol_textishtml($msg)) $this->msgishtml = 1;
179
-		}
180
-		else
184
+			if (dol_textishtml($msg)) {
185
+			    $this->msgishtml = 1;
186
+			}
187
+		} else
181 188
 		{
182 189
 			$this->msgishtml = $msgishtml;
183 190
 		}
@@ -192,7 +199,10 @@  discard block
 block discarded – undo
192 199
 		// Replace relative /viewimage to absolute path
193 200
 		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194 201
 
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
202
+		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
203
+		    $this->msgishtml=1;
204
+		}
205
+		// To force to send everything with content type html.
196 206
 
197 207
 		// Detect images
198 208
 		if ($this->msgishtml)
@@ -232,7 +242,9 @@  discard block
 block discarded – undo
232 242
 		}
233 243
 
234 244
 		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
245
+		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
246
+		    $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
247
+		}
236 248
 
237 249
 		// Action according to choosed sending method
238 250
 		if ($this->sendmode == 'mail')
@@ -257,7 +269,10 @@  discard block
 block discarded – undo
257 269
 			$this->trackid = $trackid;
258 270
 
259 271
 			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
272
+			if (! empty($moreinheader)) {
273
+			    $smtp_headers.=$moreinheader;
274
+			}
275
+			// $moreinheader contains the \r\n
261 276
 
262 277
 			// Define mime_headers
263 278
 			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
@@ -293,8 +308,7 @@  discard block
 block discarded – undo
293 308
 			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294 309
 			$this->message.= $text_body . $files_encoded;
295 310
 			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
-		}
297
-		else if ($this->sendmode == 'smtps')
311
+		} else if ($this->sendmode == 'smtps')
298 312
 		{
299 313
 			// Use SMTPS library
300 314
 			// ------------------------------------------
@@ -309,7 +323,9 @@  discard block
 block discarded – undo
309 323
 			$smtps->setTrackId($trackid);
310 324
 			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311 325
 
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
326
+			if (! empty($moreinheader)) {
327
+			    $smtps->setMoreInHeader($moreinheader);
328
+			}
313 329
 
314 330
 			if (! empty($this->html))
315 331
 			{
@@ -322,8 +338,11 @@  discard block
 block discarded – undo
322 338
 				$msg = $this->checkIfHTML($msg);
323 339
 			}
324 340
 
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
341
+			if ($this->msgishtml) {
342
+			    $smtps->setBodyContent($msg,'html');
343
+			} else {
344
+			    $smtps->setBodyContent($msg,'plain');
345
+			}
327 346
 
328 347
 			if ($this->atleastoneimage)
329 348
 			{
@@ -348,8 +367,7 @@  discard block
 block discarded – undo
348 367
 			$smtps->setDeliveryReceipt($deliveryreceipt);
349 368
 
350 369
 			$this->smtps=$smtps;
351
-		}
352
-		else if ($this->sendmode == 'swiftmailer')
370
+		} else if ($this->sendmode == 'swiftmailer')
353 371
 		{
354 372
 			// Use Swift Mailer library
355 373
 			// ------------------------------------------
@@ -474,12 +492,17 @@  discard block
 block discarded – undo
474 492
 				}
475 493
 			}
476 494
 
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
495
+			if (! empty($addr_cc)) {
496
+			    $this->message->setCc($this->getArrayAddress($addr_cc));
497
+			}
498
+			if (! empty($addr_bcc)) {
499
+			    $this->message->setBcc($this->getArrayAddress($addr_bcc));
500
+			}
479 501
 			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
-			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
-		}
482
-		else
502
+			if (isset($deliveryreceipt) && $deliveryreceipt == 1) {
503
+			    $this->message->setReadReceiptTo($this->getArrayAddress($from));
504
+			}
505
+		} else
483 506
 		{
484 507
 			// Send mail method not correctly defined
485 508
 			// --------------------------------------
@@ -517,13 +540,17 @@  discard block
 block discarded – undo
517 540
 
518 541
 				return $reshook;
519 542
 			}
520
-			if ($reshook == 1)	// Hook replace standard code
543
+			if ($reshook == 1) {
544
+			    // Hook replace standard code
521 545
 			{
522 546
 				return true;
523 547
 			}
548
+			}
524 549
 
525 550
 			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
551
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
552
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
553
+			}
527 554
 			$tmparray1 = explode(',', $this->addr_to);
528 555
 			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529 556
 			{
@@ -531,7 +558,9 @@  discard block
 block discarded – undo
531 558
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532 559
 				return false;
533 560
 			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
561
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
562
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
563
+			}
535 564
 			$tmparray2 = explode(',', $this->addr_cc);
536 565
 			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537 566
 			{
@@ -539,7 +568,9 @@  discard block
 block discarded – undo
539 568
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540 569
 				return false;
541 570
 			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
571
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
572
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
573
+			}
543 574
 			$tmparray3 = explode(',', $this->addr_bcc);
544 575
 			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545 576
 			{
@@ -547,7 +578,9 @@  discard block
 block discarded – undo
547 578
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548 579
 				return false;
549 580
 			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
581
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
582
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
583
+			}
551 584
 			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552 585
 			{
553 586
 				$this->error = 'Too much recipients in to:, cc:, bcc:';
@@ -590,13 +623,19 @@  discard block
 block discarded – undo
590 623
 				// If Windows, sendmail_from must be defined
591 624
 				if (isset($_SERVER["WINDIR"]))
592 625
 				{
593
-					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
626
+					if (empty($this->addr_from)) {
627
+					    $this->addr_from = '[email protected]';
628
+					}
594 629
 					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595 630
 				}
596 631
 
597 632
 				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
633
+				if (! empty($conf->global->$keyforsmtpserver)) {
634
+				    ini_set('SMTP',$conf->global->$keyforsmtpserver);
635
+				}
636
+				if (! empty($conf->global->$keyforsmtpport)) {
637
+				    ini_set('smtp_port',$conf->global->$keyforsmtpport);
638
+				}
600 639
 
601 640
 				$res=true;
602 641
 				if ($res && ! $this->subject)
@@ -624,29 +663,43 @@  discard block
 block discarded – undo
624 663
 						// Having this variable not defined may create problems with some other sendmail (option -f required)
625 664
 						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626 665
 					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
666
+					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
667
+					    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628 668
 					{
629 669
 						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
630 670
 					}
671
+					}
631 672
 
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
673
+					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
674
+					    $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam;
675
+					}
676
+					// Use -U to add additionnal params
633 677
 
634 678
 					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635 679
 
636 680
 					$this->message=stripslashes($this->message);
637 681
 
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
682
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
683
+					    $this->dump_mail();
684
+					}
639 685
 
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
-					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
686
+					if (! empty($additionnalparam)) {
687
+					    $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
688
+					} else {
689
+					    $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
690
+					}
642 691
 
643 692
 					if (! $res)
644 693
 					{
645 694
 						$langs->load("errors");
646 695
 						$this->error="Failed to send mail with php mail";
647 696
 						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
697
+						if (preg_match('/^win/i',PHP_OS)) {
698
+						    $linuxlike=0;
699
+						}
700
+						if (preg_match('/^mac/i',PHP_OS)) {
701
+						    $linuxlike=0;
702
+						}
650 703
 						if (! $linuxlike)
651 704
 						{
652 705
 							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
@@ -654,8 +707,7 @@  discard block
 block discarded – undo
654 707
 						$this->error.=".<br>";
655 708
 						$this->error.=$langs->trans("ErrorPhpMailDelivery");
656 709
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
-					}
658
-					else
710
+					} else
659 711
 					{
660 712
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661 713
 					}
@@ -667,10 +719,13 @@  discard block
 block discarded – undo
667 719
 				}
668 720
 
669 721
 				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
-			}
673
-			else if ($this->sendmode == 'smtps')
722
+				if (! empty($conf->global->$keyforsmtpserver)) {
723
+				    ini_restore('SMTP');
724
+				}
725
+				if (! empty($conf->global->$keyforsmtpport)) {
726
+				    ini_restore('smtp_port');
727
+				}
728
+			} else if ($this->sendmode == 'smtps')
674 729
 			{
675 730
 				if (! is_object($this->smtps))
676 731
 				{
@@ -684,14 +739,22 @@  discard block
 block discarded – undo
684 739
 				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685 740
 
686 741
 				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
742
+				if (empty($conf->global->$keyforsmtpserver)) {
743
+				    $conf->global->$keyforsmtpserver=ini_get('SMTP');
744
+				}
745
+				if (empty($conf->global->$keyforsmtpport)) {
746
+				    $conf->global->$keyforsmtpport=ini_get('smtp_port');
747
+				}
689 748
 
690 749
 				// If we use SSL/TLS
691 750
 				$server=$conf->global->$keyforsmtpserver;
692 751
 				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
752
+				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
753
+				    $secure='ssl';
754
+				}
755
+				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
756
+				    $secure='tls';
757
+				}
695 758
 				$server=($secure?$secure.'://':'').$server;
696 759
 
697 760
 				$port=$conf->global->$keyforsmtpport;
@@ -729,47 +792,63 @@  discard block
 block discarded – undo
729 792
 
730 793
 				if ($res)
731 794
 				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
795
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
796
+					    $this->smtps->setDebug(true);
797
+					}
733 798
 
734 799
 					$result=$this->smtps->sendMsg();
735 800
 					//print $result;
736 801
 
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
802
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
803
+					    $this->dump_mail();
804
+					}
738 805
 
739 806
 					$result=$this->smtps->getErrors();
740 807
 					if (empty($this->error) && empty($result))
741 808
 					{
742 809
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743 810
 						$res=true;
744
-					}
745
-					else
811
+					} else
746 812
 					{
747
-						if (empty($this->error)) $this->error=$result;
813
+						if (empty($this->error)) {
814
+						    $this->error=$result;
815
+						}
748 816
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749 817
 						$res=false;
750 818
 					}
751 819
 				}
752
-			}
753
-			else if ($this->sendmode == 'swiftmailer')
820
+			} else if ($this->sendmode == 'swiftmailer')
754 821
 			{
755 822
 				// Use Swift Mailer library
756 823
 				// ------------------------------------------
757 824
 				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758 825
 
759 826
 				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
827
+				if (empty($conf->global->$keyforsmtpserver)) {
828
+				    $conf->global->$keyforsmtpserver=ini_get('SMTP');
829
+				}
830
+				if (empty($conf->global->$keyforsmtpport)) {
831
+				    $conf->global->$keyforsmtpport=ini_get('smtp_port');
832
+				}
762 833
 
763 834
 				// If we use SSL/TLS
764 835
 				$server = $conf->global->$keyforsmtpserver;
765 836
 				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
837
+				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
838
+				    $secure='ssl';
839
+				}
840
+				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
841
+				    $secure='tls';
842
+				}
768 843
 
769 844
 				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770 845
 
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
846
+				if (! empty($conf->global->$keyforsmtpid)) {
847
+				    $this->transport->setUsername($conf->global->$keyforsmtpid);
848
+				}
849
+				if (! empty($conf->global->$keyforsmtppw)) {
850
+				    $this->transport->setPassword($conf->global->$keyforsmtppw);
851
+				}
773 852
 				//$smtps->_msgReplyTo  = '[email protected]';
774 853
 
775 854
 				// Create the Mailer using your created Transport
@@ -797,19 +876,19 @@  discard block
 block discarded – undo
797 876
 				} catch (Exception $e) {
798 877
 					$this->error =  $e->getMessage();
799 878
 				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
879
+				if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
880
+				    $this->dump_mail();
881
+				}
801 882
 
802 883
 				$res = true;
803 884
 				if (! empty($this->error) || ! $result) {
804 885
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805 886
 					$res=false;
806
-				}
807
-				else
887
+				} else
808 888
 				{
809 889
 					dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810 890
 				}
811
-			}
812
-			else
891
+			} else
813 892
 			{
814 893
 				// Send mail method not correctly defined
815 894
 				// --------------------------------------
@@ -826,8 +905,7 @@  discard block
 block discarded – undo
826 905
 
827 906
 				return $reshook;
828 907
 			}
829
-		}
830
-		else
908
+		} else
831 909
 		{
832 910
 			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833 911
 			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
@@ -867,8 +945,7 @@  discard block
 block discarded – undo
867 945
 			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868 946
 			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869 947
 			return $encoded;
870
-		}
871
-		else
948
+		} else
872 949
 		{
873 950
 			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874 951
 			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
@@ -890,9 +967,11 @@  discard block
 block discarded – undo
890 967
         // phpcs:enable
891 968
 		global $conf,$dolibarr_main_data_root;
892 969
 
893
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
970
+		if (@is_writeable($dolibarr_main_data_root)) {
971
+		    // Avoid fatal error on fopen with open_basedir
894 972
 		{
895 973
 			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
974
+		}
896 975
 			$fp = fopen($outputfile,"w");
897 976
 
898 977
 			if ($this->sendmode == 'mail')
@@ -900,19 +979,18 @@  discard block
 block discarded – undo
900 979
 				fputs($fp, $this->headers);
901 980
 				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902 981
 				fputs($fp, $this->message);
903
-			}
904
-			elseif ($this->sendmode == 'smtps')
982
+			} elseif ($this->sendmode == 'smtps')
905 983
 			{
906 984
 				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
-			}
908
-			elseif ($this->sendmode == 'swiftmailer')
985
+			} elseif ($this->sendmode == 'swiftmailer')
909 986
 			{
910 987
 				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911 988
 			}
912 989
 
913 990
 			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
915
-				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
991
+			if (! empty($conf->global->MAIN_UMASK)) {
992
+							@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
993
+			}
916 994
 		}
917 995
 	}
918 996
 
@@ -928,14 +1006,17 @@  discard block
 block discarded – undo
928 1006
 		if (!preg_match('/^[\s\t]*<html/i',$msg))
929 1007
 		{
930 1008
 			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
1009
+			if (!empty($this->styleCSS)) {
1010
+			    $out.= $this->styleCSS;
1011
+			}
932 1012
 			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
1013
+			if (!empty($this->bodyCSS)) {
1014
+			    $out.= $this->bodyCSS;
1015
+			}
934 1016
 			$out.= ">";
935 1017
 			$out.= $msg;
936 1018
 			$out.= "</body></html>";
937
-		}
938
-		else
1019
+		} else
939 1020
 		{
940 1021
 			$out = $msg;
941 1022
 		}
@@ -995,15 +1076,26 @@  discard block
 block discarded – undo
995 1076
 		}
996 1077
 		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997 1078
 		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1079
+		if (isset($this->reply_to)  && $this->reply_to) {
1080
+		    $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
1081
+		}
1082
+		if (isset($this->errors_to) && $this->errors_to) {
1083
+		    $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1084
+		}
1000 1085
 
1001 1086
 		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1087
+		if (isset($this->addr_cc)   && $this->addr_cc) {
1088
+		    $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1089
+		}
1090
+		if (isset($this->addr_bcc)  && $this->addr_bcc) {
1091
+		    $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;
1092
+		}
1093
+		// TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1094
 
1005 1095
 		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1096
+		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1097
+		    $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1098
+		}
1007 1099
 
1008 1100
 		//$out.= "X-Priority: 3".$this->eol2;
1009 1101
 
@@ -1016,13 +1108,14 @@  discard block
 block discarded – undo
1016 1108
 			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017 1109
 			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018 1110
 			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
-		}
1020
-		else
1111
+		} else
1021 1112
 		{
1022 1113
 			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023 1114
 		}
1024 1115
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1116
+		if (! empty($_SERVER['REMOTE_ADDR'])) {
1117
+		    $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1118
+		}
1026 1119
 		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027 1120
 		$out.= "Mime-Version: 1.0".$this->eol2;
1028 1121
 
@@ -1057,7 +1150,9 @@  discard block
 block discarded – undo
1057 1150
 			{
1058 1151
 				if ($filename_list[$i])
1059 1152
 				{
1060
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1153
+					if ($mimefilename_list[$i]) {
1154
+					    $filename_list[$i] = $mimefilename_list[$i];
1155
+					}
1061 1156
 					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062 1157
 				}
1063 1158
 			}
@@ -1127,9 +1222,11 @@  discard block
 block discarded – undo
1127 1222
 				$out.= "--" . $this->related_boundary . $this->eol;
1128 1223
 			}
1129 1224
 
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1225
+			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1226
+			    // Add plain text message part before html part
1131 1227
 			{
1132 1228
 				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1229
+			}
1133 1230
 				$out.= $this->eol;
1134 1231
 				$out.= "--" . $this->alternative_boundary . $this->eol;
1135 1232
 				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
@@ -1142,12 +1239,13 @@  discard block
 block discarded – undo
1142 1239
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143 1240
 			$out.= $this->eol.$strContent.$this->eol;
1144 1241
 
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1242
+			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1243
+			    // Add plain text message part after html part
1146 1244
 			{
1147 1245
 				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148 1246
 			}
1149
-		}
1150
-		else
1247
+			}
1248
+		} else
1151 1249
 		{
1152 1250
 			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153 1251
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
@@ -1192,7 +1290,9 @@  discard block
 block discarded – undo
1192 1290
 				$encoded = $this->_encode_file($filename_list[$i]);
1193 1291
 				if ($encoded >= 0)
1194 1292
 				{
1195
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1293
+					if ($mimefilename_list[$i]) {
1294
+					    $filename_list[$i] = $mimefilename_list[$i];
1295
+					}
1196 1296
 					if (! $mimetype_list[$i]) {
1197 1297
 						$mimetype_list[$i] = "application/octet-stream";
1198 1298
 					}
@@ -1206,8 +1306,7 @@  discard block
 block discarded – undo
1206 1306
 					$out.= $encoded;
1207 1307
 					$out.= $this->eol;
1208 1308
 					//$out.= $this->eol;
1209
-				}
1210
-				else
1309
+				} else
1211 1310
 				{
1212 1311
 					return $encoded;
1213 1312
 				}
@@ -1286,7 +1385,9 @@  discard block
 block discarded – undo
1286 1385
 			}
1287 1386
 
1288 1387
 			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1388
+			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
1389
+			    $host='ssl://'.$host;
1390
+			}
1290 1391
 			// tls smtp start with no encryption
1291 1392
 			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292 1393
 
@@ -1298,17 +1399,20 @@  discard block
 block discarded – undo
1298 1399
 					$errno,      // actual system level error
1299 1400
 					$errstr,     // and any text that goes with the error
1300 1401
 					$timeout
1301
-			))  // timeout for reading/writing data over the socket
1402
+			)) {
1403
+			    // timeout for reading/writing data over the socket
1302 1404
 			{
1303 1405
 				// Windows still does not have support for this timeout function
1304 1406
 				if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1407
+			}
1305 1408
 
1306 1409
 				dol_syslog("Now we wait for answer 220");
1307 1410
 
1308 1411
 				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
-			}
1311
-			else
1412
+				if ( $_retVal = $this->server_parse($socket, "220") ) {
1413
+				    $_retVal = $socket;
1414
+				}
1415
+			} else
1312 1416
 			{
1313 1417
 				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314 1418
 			}
@@ -1369,9 +1473,11 @@  discard block
 block discarded – undo
1369 1473
 			foreach ($matches[1] as $full)
1370 1474
 			{
1371 1475
 
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1476
+				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs)) {
1477
+				    // If xxx is 'file=aaa'
1373 1478
 				{
1374 1479
 					$img = $regs[1];
1480
+				}
1375 1481
 
1376 1482
 					if (file_exists($images_dir.'/'.$img))
1377 1483
 					{
@@ -1430,15 +1536,13 @@  discard block
 block discarded – undo
1430 1536
 					}
1431 1537
 					$i++;
1432 1538
 				}
1433
-			}
1434
-			else
1539
+			} else
1435 1540
 			{
1436 1541
 				return -1;
1437 1542
 			}
1438 1543
 
1439 1544
 			return 1;
1440
-		}
1441
-		else
1545
+		} else
1442 1546
 		{
1443 1547
 			return 0;
1444 1548
 		}
@@ -1473,8 +1577,7 @@  discard block
 block discarded – undo
1473 1577
 			{
1474 1578
 				$name  = trim($regs[1]);
1475 1579
 				$email = trim($regs[2]);
1476
-			}
1477
-			else
1580
+			} else
1478 1581
 			{
1479 1582
 				$name  = '';
1480 1583
 				$email = trim($val);
@@ -1499,9 +1602,13 @@  discard block
 block discarded – undo
1499 1602
 				}
1500 1603
 				if ($format == 0 || $format == 3)
1501 1604
 				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1605
+					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
1606
+					    $newemail='<'.$email.'>';
1607
+					} elseif (! $name) {
1608
+					    $newemail='<'.$email.'>';
1609
+					} else {
1610
+					    $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1611
+					}
1505 1612
 				}
1506 1613
 
1507 1614
 				$ret=($ret ? $ret.',' : '').$newemail;
@@ -1509,7 +1616,9 @@  discard block
 block discarded – undo
1509 1616
 				// Stop if we have too much records
1510 1617
 				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511 1618
 				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1619
+					if (count($arrayaddress) > $maxnumberofemail) {
1620
+					    $ret.='...';
1621
+					}
1513 1622
 					break;
1514 1623
 				}
1515 1624
 			}
@@ -1539,8 +1648,7 @@  discard block
 block discarded – undo
1539 1648
 			{
1540 1649
 				$name  = trim($regs[1]);
1541 1650
 				$email = trim($regs[2]);
1542
-			}
1543
-			else
1651
+			} else
1544 1652
 			{
1545 1653
 				$name  = null;
1546 1654
 				$email = trim($val);
Please login to merge, or discard this patch.