Passed
Pull Request — master (#2)
by
unknown
26:19
created
dolibarr/htdocs/core/class/workboardresponse.class.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -25,51 +25,51 @@
 block discarded – undo
25 25
 class WorkboardResponse
26 26
 {
27 27
 
28
-	/**
29
-	 * Image URL to represent the board item
30
-	 * @var string
31
-	 */
32
-	public $img;
28
+    /**
29
+     * Image URL to represent the board item
30
+     * @var string
31
+     */
32
+    public $img;
33 33
 
34
-	/**
35
-	 * Label of the warning
36
-	 * @var string
37
-	 */
38
-	public $label;
34
+    /**
35
+     * Label of the warning
36
+     * @var string
37
+     */
38
+    public $label;
39 39
 
40
-	/**
41
-	 * URL to list to do items
42
-	 * @var string
43
-	 */
44
-	public $url;
40
+    /**
41
+     * URL to list to do items
42
+     * @var string
43
+     */
44
+    public $url;
45 45
 
46
-	/**
47
-	 * (optional) If set, to do late items will link to this url
48
-	 * @var string
49
-	 */
50
-	public $url_late;
46
+    /**
47
+     * (optional) If set, to do late items will link to this url
48
+     * @var string
49
+     */
50
+    public $url_late;
51 51
 
52
-	/**
53
-	 * Delay time to mark an item as late. In number of days.
54
-	 * @var double
55
-	 */
56
-	public $warning_delay;
52
+    /**
53
+     * Delay time to mark an item as late. In number of days.
54
+     * @var double
55
+     */
56
+    public $warning_delay;
57 57
 
58
-	/**
59
-	 * Number of items to do
60
-	 * @var int
61
-	 */
62
-	public $nbtodo = 0;
58
+    /**
59
+     * Number of items to do
60
+     * @var int
61
+     */
62
+    public $nbtodo = 0;
63 63
 
64
-	/**
65
-	 * Number of to do items which are late
66
-	 * @var int
67
-	 */
68
-	public $nbtodolate = 0;
64
+    /**
65
+     * Number of to do items which are late
66
+     * @var int
67
+     */
68
+    public $nbtodolate = 0;
69 69
 
70
-	/**
71
-	 * total price of items
72
-	 * @var int
73
-	 */
74
-	public $total = 0;
70
+    /**
71
+     * total price of items
72
+     * @var int
73
+     */
74
+    public $total = 0;
75 75
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/dolgraph.class.php 1 patch
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.
dolibarr/htdocs/core/class/extrafields.class.php 1 patch
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.
dolibarr/htdocs/core/class/events.class.php 1 patch
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.
dolibarr/htdocs/core/class/ctyperesource.class.php 1 patch
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.
dolibarr/htdocs/core/class/html.formsms.class.php 1 patch
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.
dolibarr/htdocs/core/class/rssparser.class.php 1 patch
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.
dolibarr/htdocs/core/class/menu.class.php 1 patch
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.
dolibarr/htdocs/core/class/CMailFile.class.php 1 patch
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.