Test Failed
Push — master ( e0c20c...b8c830 )
by Alxarafe
39:29
created
dolibarr/htdocs/core/class/menu.class.php 3 patches
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -31,11 +31,11 @@  discard block
 block discarded – undo
31 31
     var $liste;
32 32
 
33 33
     /**
34
-	 *	Constructor
34
+     *	Constructor
35 35
      */
36 36
     function __construct()
37 37
     {
38
-      	$this->liste = array();
38
+            $this->liste = array();
39 39
     }
40 40
 
41 41
     /**
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
      */
68 68
     function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
69 69
     {
70
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
70
+        $this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
71 71
     }
72 72
 
73 73
     /**
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -65,9 +65,9 @@  discard block
 block discarded – undo
65 65
      * @param	string	$prefix		Prefix to title (image or picto)
66 66
      * @return	void
67 67
      */
68
-    function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
68
+    function add($url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
69 69
     {
70
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
70
+    	$this->liste[] = array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
71 71
     }
72 72
 
73 73
     /**
@@ -88,12 +88,12 @@  discard block
 block discarded – undo
88 88
      * @param	string	$prefix		Prefix to title (image or picto)
89 89
      * @return	void
90 90
      */
91
-    function insert($idafter, $url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
91
+    function insert($idafter, $url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
92 92
     {
93
-        $array_start = array_slice($this->liste,0,($idafter+1));
94
-        $array_new   = array(0=>array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu,'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
95
-        $array_end   = array_slice($this->liste,($idafter+1));
96
-        $this->liste=array_merge($array_start,$array_new,$array_end);
93
+        $array_start = array_slice($this->liste, 0, ($idafter + 1));
94
+        $array_new   = array(0=>array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
95
+        $array_end   = array_slice($this->liste, ($idafter + 1));
96
+        $this->liste = array_merge($array_start, $array_new, $array_end);
97 97
     }
98 98
 
99 99
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -117,10 +117,10 @@  discard block
 block discarded – undo
117 117
      */
118 118
     function getNbOfVisibleMenuEntries()
119 119
     {
120
-        $nb=0;
121
-        foreach($this->liste as $val)
120
+        $nb = 0;
121
+        foreach ($this->liste as $val)
122 122
         {
123
-            if (! empty($val['enabled'])) $nb++;
123
+            if (!empty($val['enabled'])) $nb++;
124 124
         }
125 125
         return $nb;
126 126
     }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -120,7 +120,9 @@
 block discarded – undo
120 120
         $nb=0;
121 121
         foreach($this->liste as $val)
122 122
         {
123
-            if (! empty($val['enabled'])) $nb++;
123
+            if (! empty($val['enabled'])) {
124
+                $nb++;
125
+            }
124 126
         }
125 127
         return $nb;
126 128
     }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/CMailFile.class.php 3 patches
Indentation   +1425 added lines, -1425 removed lines patch added patch discarded remove patch
@@ -36,323 +36,323 @@  discard block
 block discarded – undo
36 36
  */
37 37
 class CMailFile
38 38
 {
39
-	public $sendcontext;
40
-	public $sendmode;
41
-	public $sendsetup;
42
-
43
-	var $subject;      	// Topic:       Subject of email
44
-	var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45
-	// Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46
-	//              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47
-	// Return-Path: Email where to send bounds.
48
-	var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
-	var $errors_to;		// Errors-To:	Email where to send errors.
50
-	var $addr_to;
51
-	var $addr_cc;
52
-	var $addr_bcc;
53
-	var $trackid;
54
-
55
-	var $mixed_boundary;
56
-	var $related_boundary;
57
-	var $alternative_boundary;
58
-	var $deliveryreceipt;
59
-
60
-	var $eol;
61
-	var $eol2;
62
-
63
-	/**
64
-	 * @var string Error code (or message)
65
-	 */
66
-	public $error='';
67
-
68
-	var $smtps;			// Contains SMTPs object (if this method is used)
69
-	var $phpmailer;		// Contains PHPMailer object (if this method is used)
70
-
71
-	/**
72
-	 * @var string CSS
73
-	 */
74
-	public $css;
75
-	//! Defined css style for body background
76
-	var $styleCSS;
77
-	//! Defined background directly in body tag
78
-	var $bodyCSS;
79
-
80
-	var $headers;
81
-	var $message;
82
-
83
-	// Image
84
-	var $html;
85
-	var $image_boundary;
86
-	var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
-	var $html_images=array();
88
-	var $images_encoded=array();
89
-	var $image_types = array(
39
+    public $sendcontext;
40
+    public $sendmode;
41
+    public $sendsetup;
42
+
43
+    var $subject;      	// Topic:       Subject of email
44
+    var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45
+    // Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46
+    //              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47
+    // Return-Path: Email where to send bounds.
48
+    var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
+    var $errors_to;		// Errors-To:	Email where to send errors.
50
+    var $addr_to;
51
+    var $addr_cc;
52
+    var $addr_bcc;
53
+    var $trackid;
54
+
55
+    var $mixed_boundary;
56
+    var $related_boundary;
57
+    var $alternative_boundary;
58
+    var $deliveryreceipt;
59
+
60
+    var $eol;
61
+    var $eol2;
62
+
63
+    /**
64
+     * @var string Error code (or message)
65
+     */
66
+    public $error='';
67
+
68
+    var $smtps;			// Contains SMTPs object (if this method is used)
69
+    var $phpmailer;		// Contains PHPMailer object (if this method is used)
70
+
71
+    /**
72
+     * @var string CSS
73
+     */
74
+    public $css;
75
+    //! Defined css style for body background
76
+    var $styleCSS;
77
+    //! Defined background directly in body tag
78
+    var $bodyCSS;
79
+
80
+    var $headers;
81
+    var $message;
82
+
83
+    // Image
84
+    var $html;
85
+    var $image_boundary;
86
+    var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
+    var $html_images=array();
88
+    var $images_encoded=array();
89
+    var $image_types = array(
90 90
         'gif'  => 'image/gif',
91
-		'jpg'  => 'image/jpeg',
92
-		'jpeg' => 'image/jpeg',
93
-		'jpe'  => 'image/jpeg',
94
-		'bmp'  => 'image/bmp',
95
-		'png'  => 'image/png',
96
-		'tif'  => 'image/tiff',
91
+        'jpg'  => 'image/jpeg',
92
+        'jpeg' => 'image/jpeg',
93
+        'jpe'  => 'image/jpeg',
94
+        'bmp'  => 'image/bmp',
95
+        'png'  => 'image/png',
96
+        'tif'  => 'image/tiff',
97 97
         'tiff' => 'image/tiff',
98 98
     );
99 99
 
100 100
 
101
-	/**
102
-	 *	CMailFile
103
-	 *
104
-	 *	@param 	string	$subject             Topic/Subject of mail
105
-	 *	@param 	string	$to                  Recipients emails (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]"). Note: the keyword '__SUPERVISOREMAIL__' is not allowed here and must be replaced by caller.
106
-	 *	@param 	string	$from                Sender email      (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
107
-	 *	@param 	string	$msg                 Message
108
-	 *	@param 	array	$filename_list       List of files to attach (full path of filename on file system)
109
-	 *	@param 	array	$mimetype_list       List of MIME type of attached files
110
-	 *	@param 	array	$mimefilename_list   List of attached file name in message
111
-	 *	@param 	string	$addr_cc             Email cc
112
-	 *	@param 	string	$addr_bcc            Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
113
-	 *	@param 	int		$deliveryreceipt     Ask a delivery receipt
114
-	 *	@param 	int		$msgishtml           1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
115
-	 *	@param 	string	$errors_to      	 Email for errors-to
116
-	 *	@param	string	$css                 Css option
117
-	 *	@param	string	$trackid             Tracking string (contains type and id of related element)
118
-	 *  @param  string  $moreinheader        More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment)
119
-	 *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120
-	 *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121
-	 */
122
-	function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
123
-	{
124
-		global $conf, $dolibarr_main_data_root;
125
-
126
-		$this->sendcontext = $sendcontext;
127
-
128
-		if (empty($replyto)) $replyto=$from;
129
-
130
-		// Define this->sendmode
131
-		$this->sendmode = '';
132
-		if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
133
-		{
134
-			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135
-		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
138
-
139
-		// We define end of line (RFC 821).
140
-		$this->eol="\r\n";
141
-		// We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
-		$this->eol2="\r\n";
143
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144
-		{
145
-			$this->eol="\n";
146
-			$this->eol2="\n";
147
-			$moreinheader = str_replace("\r\n","\n",$moreinheader);
148
-		}
149
-
150
-		// On defini mixed_boundary
151
-		$this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
152
-
153
-		// On defini related_boundary
154
-		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
155
-
156
-		// On defini alternative_boundary
157
-		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
158
-
159
-		dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160
-		dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
161
-
162
-		if (empty($subject))
163
-		{
164
-			dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
-			$this->error='ErrorSubjectIsRequired';
166
-			return;
167
-		}
168
-		if (empty($msg))
169
-		{
170
-		    dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
-		    $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
172
-		}
173
-
174
-		// Detect if message is HTML (use fast method)
175
-		if ($msgishtml == -1)
176
-		{
177
-			$this->msgishtml = 0;
178
-			if (dol_textishtml($msg)) $this->msgishtml = 1;
179
-		}
180
-		else
181
-		{
182
-			$this->msgishtml = $msgishtml;
183
-		}
184
-
185
-		global $dolibarr_main_url_root;
186
-
187
-		// Define $urlwithroot
188
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
190
-		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191
-
192
-		// Replace relative /viewimage to absolute path
193
-		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194
-
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
196
-
197
-		// Detect images
198
-		if ($this->msgishtml)
199
-		{
200
-			$this->html = $msg;
201
-
202
-			if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203
-			{
204
-				$findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205
-			}
206
-
207
-			// Define if there is at least one file
208
-			if ($findimg)
209
-			{
210
-				foreach ($this->html_images as $i => $val)
211
-				{
212
-					if ($this->html_images[$i])
213
-					{
214
-						$this->atleastoneimage=1;
215
-						dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216
-					}
217
-				}
218
-			}
219
-		}
220
-
221
-		// Define if there is at least one file
222
-		if (is_array($filename_list))
223
-		{
224
-			foreach ($filename_list as $i => $val)
225
-			{
226
-				if ($filename_list[$i])
227
-				{
228
-					$this->atleastonefile=1;
229
-					dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230
-				}
231
-			}
232
-		}
233
-
234
-		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236
-
237
-		// Action according to choosed sending method
238
-		if ($this->sendmode == 'mail')
239
-		{
240
-			// Use mail php function (default PHP method)
241
-			// ------------------------------------------
242
-
243
-			$smtp_headers = "";
244
-			$mime_headers = "";
245
-			$text_body = "";
246
-			$files_encoded = "";
247
-
248
-			// Define smtp_headers
249
-			$this->subject = $subject;
250
-			$this->addr_from = $from;
251
-			$this->reply_to = $replyto;
252
-			$this->errors_to = $errors_to;
253
-			$this->addr_to = $to;
254
-			$this->addr_cc = $addr_cc;
255
-			$this->addr_bcc = $addr_bcc;
256
-			$this->deliveryreceipt = $deliveryreceipt;
257
-			$this->trackid = $trackid;
258
-
259
-			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
261
-
262
-			// Define mime_headers
263
-			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264
-
265
-			if (! empty($this->html))
266
-			{
267
-				if (!empty($css))
268
-				{
269
-					$this->css = $css;
270
-					$this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271
-				}
272
-
273
-				$msg = $this->html;
274
-			}
275
-
276
-			// Define body in text_body
277
-			$text_body = $this->write_body($msg);
278
-
279
-			// Add attachments to text_encoded
280
-			if ($this->atleastonefile)
281
-			{
282
-				$files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
283
-			}
284
-
285
-			// We now define $this->headers and $this->message
286
-			$this->headers = $smtp_headers . $mime_headers;
287
-			// On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288
-			// Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289
-			// comme des injections mail par les serveurs de messagerie.
290
-			$this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
291
-
292
-			//$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293
-			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
-			$this->message.= $text_body . $files_encoded;
295
-			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
-		}
297
-		else if ($this->sendmode == 'smtps')
298
-		{
299
-			// Use SMTPS library
300
-			// ------------------------------------------
301
-
302
-			require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
303
-			$smtps = new SMTPs();
304
-			$smtps->setCharSet($conf->file->character_set_client);
305
-
306
-			$smtps->setSubject($this->encodetorfc2822($subject));
307
-			$smtps->setTO($this->getValidAddress($to,0,1));
308
-			$smtps->setFrom($this->getValidAddress($from,0,1));
309
-			$smtps->setTrackId($trackid);
310
-			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311
-
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313
-
314
-			if (! empty($this->html))
315
-			{
316
-				if (!empty($css))
317
-				{
318
-					$this->css = $css;
319
-					$this->buildCSS();
320
-				}
321
-				$msg = $this->html;
322
-				$msg = $this->checkIfHTML($msg);
323
-			}
324
-
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
327
-
328
-			if ($this->atleastoneimage)
329
-			{
330
-				foreach ($this->images_encoded as $img)
331
-				{
332
-					$smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
333
-				}
334
-			}
335
-
336
-			if ($this->atleastonefile)
337
-			{
338
-				foreach ($filename_list as $i => $val)
339
-				{
340
-					$content=file_get_contents($filename_list[$i]);
341
-					$smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
342
-				}
343
-			}
344
-
345
-			$smtps->setCC($addr_cc);
346
-			$smtps->setBCC($addr_bcc);
347
-			$smtps->setErrorsTo($errors_to);
348
-			$smtps->setDeliveryReceipt($deliveryreceipt);
349
-
350
-			$this->smtps=$smtps;
351
-		}
352
-		else if ($this->sendmode == 'swiftmailer')
353
-		{
354
-			// Use Swift Mailer library
355
-			// ------------------------------------------
101
+    /**
102
+     *	CMailFile
103
+     *
104
+     *	@param 	string	$subject             Topic/Subject of mail
105
+     *	@param 	string	$to                  Recipients emails (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]"). Note: the keyword '__SUPERVISOREMAIL__' is not allowed here and must be replaced by caller.
106
+     *	@param 	string	$from                Sender email      (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
107
+     *	@param 	string	$msg                 Message
108
+     *	@param 	array	$filename_list       List of files to attach (full path of filename on file system)
109
+     *	@param 	array	$mimetype_list       List of MIME type of attached files
110
+     *	@param 	array	$mimefilename_list   List of attached file name in message
111
+     *	@param 	string	$addr_cc             Email cc
112
+     *	@param 	string	$addr_bcc            Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
113
+     *	@param 	int		$deliveryreceipt     Ask a delivery receipt
114
+     *	@param 	int		$msgishtml           1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
115
+     *	@param 	string	$errors_to      	 Email for errors-to
116
+     *	@param	string	$css                 Css option
117
+     *	@param	string	$trackid             Tracking string (contains type and id of related element)
118
+     *  @param  string  $moreinheader        More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment)
119
+     *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120
+     *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121
+     */
122
+    function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
123
+    {
124
+        global $conf, $dolibarr_main_data_root;
125
+
126
+        $this->sendcontext = $sendcontext;
127
+
128
+        if (empty($replyto)) $replyto=$from;
129
+
130
+        // Define this->sendmode
131
+        $this->sendmode = '';
132
+        if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
133
+        {
134
+            $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135
+        }
136
+        if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
+        if (empty($this->sendmode)) $this->sendmode='mail';
138
+
139
+        // We define end of line (RFC 821).
140
+        $this->eol="\r\n";
141
+        // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
+        $this->eol2="\r\n";
143
+        if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144
+        {
145
+            $this->eol="\n";
146
+            $this->eol2="\n";
147
+            $moreinheader = str_replace("\r\n","\n",$moreinheader);
148
+        }
149
+
150
+        // On defini mixed_boundary
151
+        $this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
152
+
153
+        // On defini related_boundary
154
+        $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
155
+
156
+        // On defini alternative_boundary
157
+        $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
158
+
159
+        dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160
+        dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
161
+
162
+        if (empty($subject))
163
+        {
164
+            dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
+            $this->error='ErrorSubjectIsRequired';
166
+            return;
167
+        }
168
+        if (empty($msg))
169
+        {
170
+            dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
+            $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
172
+        }
173
+
174
+        // Detect if message is HTML (use fast method)
175
+        if ($msgishtml == -1)
176
+        {
177
+            $this->msgishtml = 0;
178
+            if (dol_textishtml($msg)) $this->msgishtml = 1;
179
+        }
180
+        else
181
+        {
182
+            $this->msgishtml = $msgishtml;
183
+        }
184
+
185
+        global $dolibarr_main_url_root;
186
+
187
+        // Define $urlwithroot
188
+        $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
+        $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
190
+        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191
+
192
+        // Replace relative /viewimage to absolute path
193
+        $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194
+
195
+        if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
196
+
197
+        // Detect images
198
+        if ($this->msgishtml)
199
+        {
200
+            $this->html = $msg;
201
+
202
+            if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203
+            {
204
+                $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205
+            }
206
+
207
+            // Define if there is at least one file
208
+            if ($findimg)
209
+            {
210
+                foreach ($this->html_images as $i => $val)
211
+                {
212
+                    if ($this->html_images[$i])
213
+                    {
214
+                        $this->atleastoneimage=1;
215
+                        dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216
+                    }
217
+                }
218
+            }
219
+        }
220
+
221
+        // Define if there is at least one file
222
+        if (is_array($filename_list))
223
+        {
224
+            foreach ($filename_list as $i => $val)
225
+            {
226
+                if ($filename_list[$i])
227
+                {
228
+                    $this->atleastonefile=1;
229
+                    dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230
+                }
231
+            }
232
+        }
233
+
234
+        // Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
+        if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236
+
237
+        // Action according to choosed sending method
238
+        if ($this->sendmode == 'mail')
239
+        {
240
+            // Use mail php function (default PHP method)
241
+            // ------------------------------------------
242
+
243
+            $smtp_headers = "";
244
+            $mime_headers = "";
245
+            $text_body = "";
246
+            $files_encoded = "";
247
+
248
+            // Define smtp_headers
249
+            $this->subject = $subject;
250
+            $this->addr_from = $from;
251
+            $this->reply_to = $replyto;
252
+            $this->errors_to = $errors_to;
253
+            $this->addr_to = $to;
254
+            $this->addr_cc = $addr_cc;
255
+            $this->addr_bcc = $addr_bcc;
256
+            $this->deliveryreceipt = $deliveryreceipt;
257
+            $this->trackid = $trackid;
258
+
259
+            $smtp_headers = $this->write_smtpheaders();
260
+            if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
261
+
262
+            // Define mime_headers
263
+            $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264
+
265
+            if (! empty($this->html))
266
+            {
267
+                if (!empty($css))
268
+                {
269
+                    $this->css = $css;
270
+                    $this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271
+                }
272
+
273
+                $msg = $this->html;
274
+            }
275
+
276
+            // Define body in text_body
277
+            $text_body = $this->write_body($msg);
278
+
279
+            // Add attachments to text_encoded
280
+            if ($this->atleastonefile)
281
+            {
282
+                $files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
283
+            }
284
+
285
+            // We now define $this->headers and $this->message
286
+            $this->headers = $smtp_headers . $mime_headers;
287
+            // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288
+            // Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289
+            // comme des injections mail par les serveurs de messagerie.
290
+            $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
291
+
292
+            //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293
+            $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
+            $this->message.= $text_body . $files_encoded;
295
+            $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
+        }
297
+        else if ($this->sendmode == 'smtps')
298
+        {
299
+            // Use SMTPS library
300
+            // ------------------------------------------
301
+
302
+            require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
303
+            $smtps = new SMTPs();
304
+            $smtps->setCharSet($conf->file->character_set_client);
305
+
306
+            $smtps->setSubject($this->encodetorfc2822($subject));
307
+            $smtps->setTO($this->getValidAddress($to,0,1));
308
+            $smtps->setFrom($this->getValidAddress($from,0,1));
309
+            $smtps->setTrackId($trackid);
310
+            $smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311
+
312
+            if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313
+
314
+            if (! empty($this->html))
315
+            {
316
+                if (!empty($css))
317
+                {
318
+                    $this->css = $css;
319
+                    $this->buildCSS();
320
+                }
321
+                $msg = $this->html;
322
+                $msg = $this->checkIfHTML($msg);
323
+            }
324
+
325
+            if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
+            else $smtps->setBodyContent($msg,'plain');
327
+
328
+            if ($this->atleastoneimage)
329
+            {
330
+                foreach ($this->images_encoded as $img)
331
+                {
332
+                    $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
333
+                }
334
+            }
335
+
336
+            if ($this->atleastonefile)
337
+            {
338
+                foreach ($filename_list as $i => $val)
339
+                {
340
+                    $content=file_get_contents($filename_list[$i]);
341
+                    $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
342
+                }
343
+            }
344
+
345
+            $smtps->setCC($addr_cc);
346
+            $smtps->setBCC($addr_bcc);
347
+            $smtps->setErrorsTo($errors_to);
348
+            $smtps->setDeliveryReceipt($deliveryreceipt);
349
+
350
+            $this->smtps=$smtps;
351
+        }
352
+        else if ($this->sendmode == 'swiftmailer')
353
+        {
354
+            // Use Swift Mailer library
355
+            // ------------------------------------------
356 356
 
357 357
             $host = dol_getprefix('email');
358 358
 
@@ -361,419 +361,419 @@  discard block
 block discarded – undo
361 361
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/InvalidEmail.php';
362 362
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Exception/NoDomainPart.php';
363 363
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailParser.php';
364
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php';
365
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php';
366
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php';
367
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php';
368
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php';
369
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php';
370
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php';
371
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php';
372
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php';
364
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailLexer.php';
365
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/EmailValidator.php';
366
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/Warning.php';
367
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Warning/LocalTooLong.php';
368
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/Parser.php';
369
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/DomainPart.php';
370
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Parser/LocalPart.php';
371
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/EmailValidation.php';
372
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/egulias/email-validator/EmailValidator/Validation/RFCValidation.php';
373 373
 
374 374
             require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/InputByteStream.php';
375
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php';
376
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php';
377
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php';
378
-			//require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php';
379
-			require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
380
-			// Create the message
381
-			//$this->message = Swift_Message::newInstance();
382
-			$this->message = new Swift_Message();
375
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signer.php';
376
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/HeaderSigner.php';
377
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/Signers/DKIMSigner.php';
378
+            //require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/classes/Swift/SignedMessage.php';
379
+            require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
380
+            // Create the message
381
+            //$this->message = Swift_Message::newInstance();
382
+            $this->message = new Swift_Message();
383 383
             //$this->message = new Swift_SignedMessage();
384 384
             // Adding a trackid header to a message
385
-			$headers = $this->message->getHeaders();
386
-			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
-			$headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
388
-			$msgid = $headers->get('Message-ID');
389
-			$msgid->setId($headerID);
390
-			$headers->addIdHeader('References', $headerID);
391
-			// TODO if (! empty($moreinheader)) ...
392
-
393
-			// Give the message a subject
394
-			try {
395
-				$result = $this->message->setSubject($subject);
396
-			} catch (Exception $e) {
397
-				$this->errors[] =  $e->getMessage();
398
-			}
399
-
400
-			// Set the From address with an associative array
401
-			//$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
-			if (! empty($from)) {
385
+            $headers = $this->message->getHeaders();
386
+            $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
+            $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
388
+            $msgid = $headers->get('Message-ID');
389
+            $msgid->setId($headerID);
390
+            $headers->addIdHeader('References', $headerID);
391
+            // TODO if (! empty($moreinheader)) ...
392
+
393
+            // Give the message a subject
394
+            try {
395
+                $result = $this->message->setSubject($subject);
396
+            } catch (Exception $e) {
397
+                $this->errors[] =  $e->getMessage();
398
+            }
399
+
400
+            // Set the From address with an associative array
401
+            //$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
+            if (! empty($from)) {
403 403
                 try {
404
-                	$result = $this->message->setFrom($this->getArrayAddress($from));
404
+                    $result = $this->message->setFrom($this->getArrayAddress($from));
405 405
                 } catch (Exception $e) {
406 406
                     $this->errors[] = $e->getMessage();
407 407
                 }
408 408
             }
409 409
 
410
-			// Set the To addresses with an associative array
411
-			if (! empty($to)) {
410
+            // Set the To addresses with an associative array
411
+            if (! empty($to)) {
412 412
                 try {
413
-                	$result = $this->message->setTo($this->getArrayAddress($to));
413
+                    $result = $this->message->setTo($this->getArrayAddress($to));
414 414
                 } catch (Exception $e) {
415 415
                     $this->errors[] = $e->getMessage();
416 416
                 }
417 417
             }
418 418
 
419
-			if (! empty($replyto)) {
419
+            if (! empty($replyto)) {
420 420
                 try {
421
-                	$result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
421
+                    $result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
422 422
                 } catch (Exception $e) {
423 423
                     $this->errors[] = $e->getMessage();
424 424
                 }
425 425
             }
426 426
 
427
-			try {
428
-				$result = $this->message->setCharSet($conf->file->character_set_client);
429
-			} catch (Exception $e) {
430
-				$this->errors[] =  $e->getMessage();
431
-			}
432
-
433
-			if (! empty($this->html))
434
-			{
435
-				if (!empty($css))
436
-				{
437
-					$this->css = $css;
438
-					$this->buildCSS();
439
-				}
440
-				$msg = $this->html;
441
-				$msg = $this->checkIfHTML($msg);
442
-			}
443
-
444
-			if ($this->atleastoneimage)
445
-			{
446
-				foreach ($this->images_encoded as $img)
447
-				{
448
-					//$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
449
-					$attachment = Swift_Image::fromPath($img['fullpath'], $img['content_type']);
450
-					// embed image
451
-					$imgcid = $this->message->embed($attachment);
452
-					// replace cid by the one created by swiftmail in html message
453
-					$msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
454
-				}
455
-			}
456
-
457
-			if ($this->msgishtml) {
458
-				$this->message->setBody($msg,'text/html');
459
-				// And optionally an alternative body
460
-				$this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461
-			} else {
462
-				$this->message->setBody($msg,'text/plain');
463
-				// And optionally an alternative body
464
-				$this->message->addPart($msg, 'text/html');
465
-			}
466
-
467
-			if ($this->atleastonefile)
468
-			{
469
-				foreach ($filename_list as $i => $val)
470
-				{
471
-					//$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
-					$attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
473
-					$this->message->attach($attachment);
474
-				}
475
-			}
476
-
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479
-			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
-			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
-		}
482
-		else
483
-		{
484
-			// Send mail method not correctly defined
485
-			// --------------------------------------
486
-			$this->error = 'Bad value for sendmode';
487
-		}
488
-	}
489
-
490
-
491
-	/**
492
-	 * Send mail that was prepared by constructor.
493
-	 *
494
-	 * @return    boolean     True if mail sent, false otherwise
495
-	 */
496
-	function sendfile()
497
-	{
498
-		global $conf,$db,$langs;
499
-
500
-		$errorlevel=error_reporting();
501
-		//error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502
-
503
-		$res=false;
504
-
505
-		if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506
-		{
507
-			require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
508
-			$hookmanager = new HookManager($db);
509
-			$hookmanager->initHooks(array('mail'));
510
-
511
-			$parameters=array(); $action='';
512
-			$reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513
-			if ($reshook < 0)
514
-			{
515
-				$this->error = "Error in hook maildao sendMail " . $reshook;
516
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
517
-
518
-				return $reshook;
519
-			}
520
-			if ($reshook == 1)	// Hook replace standard code
521
-			{
522
-				return true;
523
-			}
524
-
525
-			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
527
-			$tmparray1 = explode(',', $this->addr_to);
528
-			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529
-			{
530
-				$this->error = 'Too much recipients in to:';
531
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532
-				return false;
533
-			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
535
-			$tmparray2 = explode(',', $this->addr_cc);
536
-			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537
-			{
538
-				$this->error = 'Too much recipients in cc:';
539
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540
-				return false;
541
-			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
543
-			$tmparray3 = explode(',', $this->addr_bcc);
544
-			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545
-			{
546
-				$this->error = 'Too much recipients in bcc:';
547
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548
-				return false;
549
-			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
-			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552
-			{
553
-				$this->error = 'Too much recipients in to:, cc:, bcc:';
554
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
555
-				return false;
556
-			}
557
-
558
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
564
-			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565
-			{
566
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572
-			}
573
-
574
-			if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
575
-			{
576
-				$this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO;
577
-				$this->addr_cc = '';
578
-				$this->addr_bcc = '';
579
-			}
580
-
581
-			// Action according to choosed sending method
582
-			if ($this->sendmode == 'mail')
583
-			{
584
-				// Use mail php function (default PHP method)
585
-				// ------------------------------------------
586
-				dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
587
-				dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
588
-				//dol_syslog("CMailFile::sendfile message=\n".$message);
589
-
590
-				// If Windows, sendmail_from must be defined
591
-				if (isset($_SERVER["WINDIR"]))
592
-				{
593
-					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
-					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595
-				}
596
-
597
-				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
600
-
601
-				$res=true;
602
-				if ($res && ! $this->subject)
603
-				{
604
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
-					$res=false;
607
-				}
608
-				$dest=$this->getValidAddress($this->addr_to,2);
609
-				if ($res && ! $dest)
610
-				{
611
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
-					$res=false;
614
-				}
615
-
616
-				if ($res)
617
-				{
618
-					$additionnalparam = '';	// By default
619
-					if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620
-					{
621
-						// le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622
-						// Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623
-						// Having this variable defined may create problems with some sendmail (option -f refused)
624
-						// Having this variable not defined may create problems with some other sendmail (option -f required)
625
-						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626
-					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628
-					{
629
-						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
630
-					}
631
-
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
633
-
634
-					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635
-
636
-					$this->message=stripslashes($this->message);
637
-
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639
-
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
-					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642
-
643
-					if (! $res)
644
-					{
645
-						$langs->load("errors");
646
-						$this->error="Failed to send mail with php mail";
647
-						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
-						if (! $linuxlike)
651
-						{
652
-							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
653
-						}
654
-						$this->error.=".<br>";
655
-						$this->error.=$langs->trans("ErrorPhpMailDelivery");
656
-						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
-					}
658
-					else
659
-					{
660
-						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661
-					}
662
-				}
663
-
664
-				if (isset($_SERVER["WINDIR"]))
665
-				{
666
-					@ini_restore('sendmail_from');
667
-				}
668
-
669
-				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
-			}
673
-			else if ($this->sendmode == 'smtps')
674
-			{
675
-				if (! is_object($this->smtps))
676
-				{
677
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679
-					return false;
680
-				}
681
-
682
-				// Use SMTPS library
683
-				// ------------------------------------------
684
-				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685
-
686
-				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
689
-
690
-				// If we use SSL/TLS
691
-				$server=$conf->global->$keyforsmtpserver;
692
-				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
-				$server=($secure?$secure.'://':'').$server;
696
-
697
-				$port=$conf->global->$keyforsmtpport;
698
-
699
-				$this->smtps->setHost($server);
700
-				$this->smtps->setPort($port); // 25, 465...;
701
-
702
-				$loginid=''; $loginpass='';
703
-				if (! empty($conf->global->$keyforsmtpid))
704
-				{
705
-					$loginid = $conf->global->$keyforsmtpid;
706
-					$this->smtps->setID($loginid);
707
-				}
708
-				if (! empty($conf->global->$keyforsmtppw))
709
-				{
710
-					$loginpass = $conf->global->$keyforsmtppw;
711
-					$this->smtps->setPW($loginpass);
712
-				}
713
-
714
-				$res=true;
715
-				$from=$this->smtps->getFrom('org');
716
-				if ($res && ! $from)
717
-				{
718
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
-					$res=false;
721
-				}
722
-				$dest=$this->smtps->getTo();
723
-				if ($res && ! $dest)
724
-				{
725
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
-					$res=false;
728
-				}
729
-
730
-				if ($res)
731
-				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733
-
734
-					$result=$this->smtps->sendMsg();
735
-					//print $result;
736
-
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738
-
739
-					$result=$this->smtps->getErrors();
740
-					if (empty($this->error) && empty($result))
741
-					{
742
-						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
-						$res=true;
744
-					}
745
-					else
746
-					{
747
-						if (empty($this->error)) $this->error=$result;
748
-						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
-						$res=false;
750
-					}
751
-				}
752
-			}
753
-			else if ($this->sendmode == 'swiftmailer')
754
-			{
755
-				// Use Swift Mailer library
756
-				// ------------------------------------------
757
-				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758
-
759
-				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
762
-
763
-				// If we use SSL/TLS
764
-				$server = $conf->global->$keyforsmtpserver;
765
-				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
768
-
769
-				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770
-
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773
-				//$smtps->_msgReplyTo  = '[email protected]';
774
-
775
-				// Create the Mailer using your created Transport
776
-				$this->mailer = new Swift_Mailer($this->transport);
427
+            try {
428
+                $result = $this->message->setCharSet($conf->file->character_set_client);
429
+            } catch (Exception $e) {
430
+                $this->errors[] =  $e->getMessage();
431
+            }
432
+
433
+            if (! empty($this->html))
434
+            {
435
+                if (!empty($css))
436
+                {
437
+                    $this->css = $css;
438
+                    $this->buildCSS();
439
+                }
440
+                $msg = $this->html;
441
+                $msg = $this->checkIfHTML($msg);
442
+            }
443
+
444
+            if ($this->atleastoneimage)
445
+            {
446
+                foreach ($this->images_encoded as $img)
447
+                {
448
+                    //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
449
+                    $attachment = Swift_Image::fromPath($img['fullpath'], $img['content_type']);
450
+                    // embed image
451
+                    $imgcid = $this->message->embed($attachment);
452
+                    // replace cid by the one created by swiftmail in html message
453
+                    $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
454
+                }
455
+            }
456
+
457
+            if ($this->msgishtml) {
458
+                $this->message->setBody($msg,'text/html');
459
+                // And optionally an alternative body
460
+                $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461
+            } else {
462
+                $this->message->setBody($msg,'text/plain');
463
+                // And optionally an alternative body
464
+                $this->message->addPart($msg, 'text/html');
465
+            }
466
+
467
+            if ($this->atleastonefile)
468
+            {
469
+                foreach ($filename_list as $i => $val)
470
+                {
471
+                    //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
+                    $attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
473
+                    $this->message->attach($attachment);
474
+                }
475
+            }
476
+
477
+            if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
+            if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479
+            //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
+            if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
+        }
482
+        else
483
+        {
484
+            // Send mail method not correctly defined
485
+            // --------------------------------------
486
+            $this->error = 'Bad value for sendmode';
487
+        }
488
+    }
489
+
490
+
491
+    /**
492
+     * Send mail that was prepared by constructor.
493
+     *
494
+     * @return    boolean     True if mail sent, false otherwise
495
+     */
496
+    function sendfile()
497
+    {
498
+        global $conf,$db,$langs;
499
+
500
+        $errorlevel=error_reporting();
501
+        //error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502
+
503
+        $res=false;
504
+
505
+        if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506
+        {
507
+            require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
508
+            $hookmanager = new HookManager($db);
509
+            $hookmanager->initHooks(array('mail'));
510
+
511
+            $parameters=array(); $action='';
512
+            $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513
+            if ($reshook < 0)
514
+            {
515
+                $this->error = "Error in hook maildao sendMail " . $reshook;
516
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
517
+
518
+                return $reshook;
519
+            }
520
+            if ($reshook == 1)	// Hook replace standard code
521
+            {
522
+                return true;
523
+            }
524
+
525
+            // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
527
+            $tmparray1 = explode(',', $this->addr_to);
528
+            if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529
+            {
530
+                $this->error = 'Too much recipients in to:';
531
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532
+                return false;
533
+            }
534
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
535
+            $tmparray2 = explode(',', $this->addr_cc);
536
+            if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537
+            {
538
+                $this->error = 'Too much recipients in cc:';
539
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540
+                return false;
541
+            }
542
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
543
+            $tmparray3 = explode(',', $this->addr_bcc);
544
+            if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545
+            {
546
+                $this->error = 'Too much recipients in bcc:';
547
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548
+                return false;
549
+            }
550
+            if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
+            if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552
+            {
553
+                $this->error = 'Too much recipients in to:, cc:, bcc:';
554
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
555
+                return false;
556
+            }
557
+
558
+            $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
+            $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
+            $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
+            $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
+            $keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
+            $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
564
+            if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565
+            {
566
+                $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
+                $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
+                $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
+                $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
+                $keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
+                $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572
+            }
573
+
574
+            if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
575
+            {
576
+                $this->addr_to = $conf->global->MAIN_MAIL_FORCE_SENDTO;
577
+                $this->addr_cc = '';
578
+                $this->addr_bcc = '';
579
+            }
580
+
581
+            // Action according to choosed sending method
582
+            if ($this->sendmode == 'mail')
583
+            {
584
+                // Use mail php function (default PHP method)
585
+                // ------------------------------------------
586
+                dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
587
+                dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
588
+                //dol_syslog("CMailFile::sendfile message=\n".$message);
589
+
590
+                // If Windows, sendmail_from must be defined
591
+                if (isset($_SERVER["WINDIR"]))
592
+                {
593
+                    if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
+                    @ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595
+                }
596
+
597
+                // Force parameters
598
+                if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
+                if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
600
+
601
+                $res=true;
602
+                if ($res && ! $this->subject)
603
+                {
604
+                    $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
+                    $res=false;
607
+                }
608
+                $dest=$this->getValidAddress($this->addr_to,2);
609
+                if ($res && ! $dest)
610
+                {
611
+                    $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
+                    $res=false;
614
+                }
615
+
616
+                if ($res)
617
+                {
618
+                    $additionnalparam = '';	// By default
619
+                    if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620
+                    {
621
+                        // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622
+                        // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623
+                        // Having this variable defined may create problems with some sendmail (option -f refused)
624
+                        // Having this variable not defined may create problems with some other sendmail (option -f required)
625
+                        $additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626
+                    }
627
+                    if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628
+                    {
629
+                        $additionnalparam .= ($additionnalparam?' ':'').'-ba';
630
+                    }
631
+
632
+                    if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
633
+
634
+                    dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635
+
636
+                    $this->message=stripslashes($this->message);
637
+
638
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639
+
640
+                    if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
+                    else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642
+
643
+                    if (! $res)
644
+                    {
645
+                        $langs->load("errors");
646
+                        $this->error="Failed to send mail with php mail";
647
+                        $linuxlike=1;
648
+                        if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
+                        if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
+                        if (! $linuxlike)
651
+                        {
652
+                            $this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
653
+                        }
654
+                        $this->error.=".<br>";
655
+                        $this->error.=$langs->trans("ErrorPhpMailDelivery");
656
+                        dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
+                    }
658
+                    else
659
+                    {
660
+                        dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661
+                    }
662
+                }
663
+
664
+                if (isset($_SERVER["WINDIR"]))
665
+                {
666
+                    @ini_restore('sendmail_from');
667
+                }
668
+
669
+                // Restore parameters
670
+                if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
+                if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
+            }
673
+            else if ($this->sendmode == 'smtps')
674
+            {
675
+                if (! is_object($this->smtps))
676
+                {
677
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679
+                    return false;
680
+                }
681
+
682
+                // Use SMTPS library
683
+                // ------------------------------------------
684
+                $this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685
+
686
+                // Clean parameters
687
+                if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
+                if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
689
+
690
+                // If we use SSL/TLS
691
+                $server=$conf->global->$keyforsmtpserver;
692
+                $secure='';
693
+                if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
+                if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
+                $server=($secure?$secure.'://':'').$server;
696
+
697
+                $port=$conf->global->$keyforsmtpport;
698
+
699
+                $this->smtps->setHost($server);
700
+                $this->smtps->setPort($port); // 25, 465...;
701
+
702
+                $loginid=''; $loginpass='';
703
+                if (! empty($conf->global->$keyforsmtpid))
704
+                {
705
+                    $loginid = $conf->global->$keyforsmtpid;
706
+                    $this->smtps->setID($loginid);
707
+                }
708
+                if (! empty($conf->global->$keyforsmtppw))
709
+                {
710
+                    $loginpass = $conf->global->$keyforsmtppw;
711
+                    $this->smtps->setPW($loginpass);
712
+                }
713
+
714
+                $res=true;
715
+                $from=$this->smtps->getFrom('org');
716
+                if ($res && ! $from)
717
+                {
718
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
+                    $res=false;
721
+                }
722
+                $dest=$this->smtps->getTo();
723
+                if ($res && ! $dest)
724
+                {
725
+                    $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
+                    $res=false;
728
+                }
729
+
730
+                if ($res)
731
+                {
732
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733
+
734
+                    $result=$this->smtps->sendMsg();
735
+                    //print $result;
736
+
737
+                    if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738
+
739
+                    $result=$this->smtps->getErrors();
740
+                    if (empty($this->error) && empty($result))
741
+                    {
742
+                        dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
+                        $res=true;
744
+                    }
745
+                    else
746
+                    {
747
+                        if (empty($this->error)) $this->error=$result;
748
+                        dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
+                        $res=false;
750
+                    }
751
+                }
752
+            }
753
+            else if ($this->sendmode == 'swiftmailer')
754
+            {
755
+                // Use Swift Mailer library
756
+                // ------------------------------------------
757
+                require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758
+
759
+                // Clean parameters
760
+                if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
+                if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
762
+
763
+                // If we use SSL/TLS
764
+                $server = $conf->global->$keyforsmtpserver;
765
+                $secure = '';
766
+                if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
+                if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
768
+
769
+                $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770
+
771
+                if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
+                if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773
+                //$smtps->_msgReplyTo  = '[email protected]';
774
+
775
+                // Create the Mailer using your created Transport
776
+                $this->mailer = new Swift_Mailer($this->transport);
777 777
 
778 778
                 // DKIM SIGN
779 779
                 if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
@@ -785,770 +785,770 @@  discard block
 block discarded – undo
785 785
                 }
786 786
 
787 787
                 if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
788
-					// To use the ArrayLogger
789
-					$this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790
-					// Or to use the Echo Logger
791
-					//$this->logger = new Swift_Plugins_Loggers_EchoLogger();
792
-					$this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
793
-				}
794
-				// send mail
795
-				try {
796
-					$result = $this->mailer->send($this->message);
797
-				} catch (Exception $e) {
798
-					$this->error =  $e->getMessage();
799
-				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801
-
802
-				$res = true;
803
-				if (! empty($this->error) || ! $result) {
804
-					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
-					$res=false;
806
-				}
807
-				else
808
-				{
809
-					dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810
-				}
811
-			}
812
-			else
813
-			{
814
-				// Send mail method not correctly defined
815
-				// --------------------------------------
816
-
817
-				return 'Bad value for sendmode';
818
-			}
819
-
820
-			$parameters=array(); $action='';
821
-			$reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822
-			if ($reshook < 0)
823
-			{
824
-				$this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
826
-
827
-				return $reshook;
828
-			}
829
-		}
830
-		else
831
-		{
832
-			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833
-			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834
-		}
835
-
836
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
837
-
838
-		return $res;
839
-	}
840
-
841
-	/**
842
-	 * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
843
-	 *
844
-	 * @param string $stringtoencode String to encode
845
-	 * @return string                string encoded
846
-	 */
847
-	static function encodetorfc2822($stringtoencode)
848
-	{
849
-		global $conf;
850
-		return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
851
-	}
788
+                    // To use the ArrayLogger
789
+                    $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790
+                    // Or to use the Echo Logger
791
+                    //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
792
+                    $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
793
+                }
794
+                // send mail
795
+                try {
796
+                    $result = $this->mailer->send($this->message);
797
+                } catch (Exception $e) {
798
+                    $this->error =  $e->getMessage();
799
+                }
800
+                if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801
+
802
+                $res = true;
803
+                if (! empty($this->error) || ! $result) {
804
+                    dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
+                    $res=false;
806
+                }
807
+                else
808
+                {
809
+                    dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810
+                }
811
+            }
812
+            else
813
+            {
814
+                // Send mail method not correctly defined
815
+                // --------------------------------------
816
+
817
+                return 'Bad value for sendmode';
818
+            }
819
+
820
+            $parameters=array(); $action='';
821
+            $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822
+            if ($reshook < 0)
823
+            {
824
+                $this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
+                dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
826
+
827
+                return $reshook;
828
+            }
829
+        }
830
+        else
831
+        {
832
+            $this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833
+            dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834
+        }
835
+
836
+        error_reporting($errorlevel);              // Reactive niveau erreur origine
837
+
838
+        return $res;
839
+    }
840
+
841
+    /**
842
+     * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
843
+     *
844
+     * @param string $stringtoencode String to encode
845
+     * @return string                string encoded
846
+     */
847
+    static function encodetorfc2822($stringtoencode)
848
+    {
849
+        global $conf;
850
+        return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
851
+    }
852 852
 
853 853
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
854
-	/**
855
-	 * Read a file on disk and return encoded content for emails (mode = 'mail')
856
-	 *
857
-	 * @param	string	$sourcefile		Path to file to encode
858
-	 * @return 	int					    <0 if KO, encoded string if OK
859
-	 */
860
-	function _encode_file($sourcefile)
861
-	{
854
+    /**
855
+     * Read a file on disk and return encoded content for emails (mode = 'mail')
856
+     *
857
+     * @param	string	$sourcefile		Path to file to encode
858
+     * @return 	int					    <0 if KO, encoded string if OK
859
+     */
860
+    function _encode_file($sourcefile)
861
+    {
862 862
         // phpcs:enable
863
-		$newsourcefile=dol_osencode($sourcefile);
864
-
865
-		if (is_readable($newsourcefile))
866
-		{
867
-			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
-			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869
-			return $encoded;
870
-		}
871
-		else
872
-		{
873
-			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874
-			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875
-			return -1;
876
-		}
877
-	}
863
+        $newsourcefile=dol_osencode($sourcefile);
864
+
865
+        if (is_readable($newsourcefile))
866
+        {
867
+            $contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
+            $encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869
+            return $encoded;
870
+        }
871
+        else
872
+        {
873
+            $this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874
+            dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875
+            return -1;
876
+        }
877
+    }
878 878
 
879 879
 
880 880
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
881
-	/**
882
-	 *  Write content of a SMTP request into a dump file (mode = all)
883
-	 *  Used for debugging.
884
-	 *  Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
885
-	 *
886
-	 *  @return	void
887
-	 */
888
-	function dump_mail()
889
-	{
881
+    /**
882
+     *  Write content of a SMTP request into a dump file (mode = all)
883
+     *  Used for debugging.
884
+     *  Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
885
+     *
886
+     *  @return	void
887
+     */
888
+    function dump_mail()
889
+    {
890 890
         // phpcs:enable
891
-		global $conf,$dolibarr_main_data_root;
892
-
893
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894
-		{
895
-			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
-			$fp = fopen($outputfile,"w");
897
-
898
-			if ($this->sendmode == 'mail')
899
-			{
900
-				fputs($fp, $this->headers);
901
-				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902
-				fputs($fp, $this->message);
903
-			}
904
-			elseif ($this->sendmode == 'smtps')
905
-			{
906
-				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
-			}
908
-			elseif ($this->sendmode == 'swiftmailer')
909
-			{
910
-				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911
-			}
912
-
913
-			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
915
-				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916
-		}
917
-	}
918
-
919
-
920
-	/**
921
-	 * Correct an uncomplete html string
922
-	 *
923
-	 * @param	string	$msg	String
924
-	 * @return	string			Completed string
925
-	 */
926
-	function checkIfHTML($msg)
927
-	{
928
-		if (!preg_match('/^[\s\t]*<html/i',$msg))
929
-		{
930
-			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
-			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
-			$out.= ">";
935
-			$out.= $msg;
936
-			$out.= "</body></html>";
937
-		}
938
-		else
939
-		{
940
-			$out = $msg;
941
-		}
942
-
943
-		return $out;
944
-	}
945
-
946
-	/**
947
-	 * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
948
-	 *
949
-	 * @return string
950
-	 */
951
-	function buildCSS()
952
-	{
953
-		if (! empty($this->css))
954
-		{
955
-			// Style CSS
956
-			$this->styleCSS = '<style type="text/css">';
957
-			$this->styleCSS.= 'body {';
958
-
959
-			if ($this->css['bgcolor'])
960
-			{
961
-				$this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
-				$this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
963
-			}
964
-			if ($this->css['bgimage'])
965
-			{
966
-				// TODO recuperer cid
967
-				$this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968
-			}
969
-			$this->styleCSS.= '}';
970
-			$this->styleCSS.= '</style>';
971
-		}
972
-	}
891
+        global $conf,$dolibarr_main_data_root;
892
+
893
+        if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894
+        {
895
+            $outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
+            $fp = fopen($outputfile,"w");
897
+
898
+            if ($this->sendmode == 'mail')
899
+            {
900
+                fputs($fp, $this->headers);
901
+                fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902
+                fputs($fp, $this->message);
903
+            }
904
+            elseif ($this->sendmode == 'smtps')
905
+            {
906
+                fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
+            }
908
+            elseif ($this->sendmode == 'swiftmailer')
909
+            {
910
+                fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911
+            }
912
+
913
+            fclose($fp);
914
+            if (! empty($conf->global->MAIN_UMASK))
915
+                @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916
+        }
917
+    }
918
+
919
+
920
+    /**
921
+     * Correct an uncomplete html string
922
+     *
923
+     * @param	string	$msg	String
924
+     * @return	string			Completed string
925
+     */
926
+    function checkIfHTML($msg)
927
+    {
928
+        if (!preg_match('/^[\s\t]*<html/i',$msg))
929
+        {
930
+            $out = "<html><head><title></title>";
931
+            if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
+            $out.= "</head><body";
933
+            if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
+            $out.= ">";
935
+            $out.= $msg;
936
+            $out.= "</body></html>";
937
+        }
938
+        else
939
+        {
940
+            $out = $msg;
941
+        }
942
+
943
+        return $out;
944
+    }
945
+
946
+    /**
947
+     * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
948
+     *
949
+     * @return string
950
+     */
951
+    function buildCSS()
952
+    {
953
+        if (! empty($this->css))
954
+        {
955
+            // Style CSS
956
+            $this->styleCSS = '<style type="text/css">';
957
+            $this->styleCSS.= 'body {';
958
+
959
+            if ($this->css['bgcolor'])
960
+            {
961
+                $this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
+                $this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
963
+            }
964
+            if ($this->css['bgimage'])
965
+            {
966
+                // TODO recuperer cid
967
+                $this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968
+            }
969
+            $this->styleCSS.= '}';
970
+            $this->styleCSS.= '</style>';
971
+        }
972
+    }
973 973
 
974 974
 
975 975
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
976
-	/**
977
-	 * Create SMTP headers (mode = 'mail')
978
-	 *
979
-	 * @return	string headers
980
-	 */
981
-	function write_smtpheaders()
982
-	{
976
+    /**
977
+     * Create SMTP headers (mode = 'mail')
978
+     *
979
+     * @return	string headers
980
+     */
981
+    function write_smtpheaders()
982
+    {
983 983
         // phpcs:enable
984
-		global $conf;
985
-		$out = "";
984
+        global $conf;
985
+        $out = "";
986 986
 
987
-		$host = dol_getprefix('email');
987
+        $host = dol_getprefix('email');
988 988
 
989
-		// Sender
990
-		//$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
-		$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
-		if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993
-		{
994
-			$out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
995
-		}
996
-		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
-		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
989
+        // Sender
990
+        //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
+        $out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
+        if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993
+        {
994
+            $out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
995
+        }
996
+        // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
+        $out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
+        if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
+        if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1000 1000
 
1001
-		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1001
+        // Receiver
1002
+        if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
+        if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1004
 
1005
-		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1005
+        // Delivery receipt
1006
+        if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1007 1007
 
1008
-		//$out.= "X-Priority: 3".$this->eol2;
1008
+        //$out.= "X-Priority: 3".$this->eol2;
1009 1009
 
1010
-		$out.= 'Date: ' . date("r") . $this->eol2;
1010
+        $out.= 'Date: ' . date("r") . $this->eol2;
1011 1011
 
1012
-		$trackid = $this->trackid;
1013
-		if ($trackid)
1014
-		{
1015
-			// References is kept in response and Message-ID is returned into In-Reply-To:
1016
-			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
-			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
-			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
-		}
1020
-		else
1021
-		{
1022
-			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023
-		}
1012
+        $trackid = $this->trackid;
1013
+        if ($trackid)
1014
+        {
1015
+            // References is kept in response and Message-ID is returned into In-Reply-To:
1016
+            $out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
+            $out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
+            $out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
+        }
1020
+        else
1021
+        {
1022
+            $out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023
+        }
1024 1024
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
-		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
-		$out.= "Mime-Version: 1.0".$this->eol2;
1025
+        if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
+        $out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
+        $out.= "Mime-Version: 1.0".$this->eol2;
1028 1028
 
1029
-		//$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1029
+        //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1030 1030
 
1031
-		$out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
-		$out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1031
+        $out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
+        $out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1033 1033
 
1034
-		dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035
-		return $out;
1036
-	}
1034
+        dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035
+        return $out;
1036
+    }
1037 1037
 
1038 1038
 
1039 1039
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1040
-	/**
1041
-	 * Create header MIME (mode = 'mail')
1042
-	 *
1043
-	 * @param	array	$filename_list			Array of filenames
1044
-	 * @param 	array	$mimefilename_list		Array of mime types
1045
-	 * @return	string							mime headers
1046
-	 */
1047
-	function write_mimeheaders($filename_list, $mimefilename_list)
1048
-	{
1040
+    /**
1041
+     * Create header MIME (mode = 'mail')
1042
+     *
1043
+     * @param	array	$filename_list			Array of filenames
1044
+     * @param 	array	$mimefilename_list		Array of mime types
1045
+     * @return	string							mime headers
1046
+     */
1047
+    function write_mimeheaders($filename_list, $mimefilename_list)
1048
+    {
1049 1049
         // phpcs:enable
1050
-		$mimedone=0;
1051
-		$out = "";
1052
-
1053
-		if (is_array($filename_list))
1054
-		{
1055
-			$filename_list_size=count($filename_list);
1056
-			for($i=0;$i < $filename_list_size;$i++)
1057
-			{
1058
-				if ($filename_list[$i])
1059
-				{
1060
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
-					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062
-				}
1063
-			}
1064
-		}
1065
-
1066
-		dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1067
-		return $out;
1068
-	}
1050
+        $mimedone=0;
1051
+        $out = "";
1052
+
1053
+        if (is_array($filename_list))
1054
+        {
1055
+            $filename_list_size=count($filename_list);
1056
+            for($i=0;$i < $filename_list_size;$i++)
1057
+            {
1058
+                if ($filename_list[$i])
1059
+                {
1060
+                    if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
+                    $out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062
+                }
1063
+            }
1064
+        }
1069 1065
 
1070
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1071
-	/**
1072
-	 * Return email content (mode = 'mail')
1073
-	 *
1074
-	 * @param	string		$msgtext		Message string
1075
-	 * @return	string						String content
1076
-	 */
1077
-	function write_body($msgtext)
1078
-	{
1079
-        // phpcs:enable
1080
-		global $conf;
1081
-
1082
-		$out='';
1083
-
1084
-		$out.= "--" . $this->mixed_boundary . $this->eol;
1085
-
1086
-		if ($this->atleastoneimage)
1087
-		{
1088
-			$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
-			$out.= $this->eol;
1090
-			$out.= "--" . $this->alternative_boundary . $this->eol;
1091
-		}
1092
-
1093
-		// Make RFC821 Compliant, replace bare linefeeds
1094
-		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096
-		{
1097
-			$strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1098
-		}
1099
-
1100
-		$strContentAltText = '';
1101
-		if ($this->msgishtml)
1102
-		{
1103
-			// Similar code to forge a text from html is also in CMailFile.class.php
1104
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1105
-			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
-			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1107
-
1108
-			// Check if html header already in message, if not complete the message
1109
-			$strContent = $this->checkIfHTML($strContent);
1110
-		}
1111
-
1112
-		// Make RFC2045 Compliant, split lines
1113
-		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114
-		// TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
-		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1116
-
1117
-		if ($this->msgishtml)
1118
-		{
1119
-			if ($this->atleastoneimage)
1120
-			{
1121
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122
-				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
-				$out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1125
-				$out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
-				$out.= $this->eol;
1127
-				$out.= "--" . $this->related_boundary . $this->eol;
1128
-			}
1129
-
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131
-			{
1132
-				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
-				$out.= $this->eol;
1134
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1135
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136
-				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
-				$out.= $this->eol.$strContentAltText.$this->eol;
1138
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1139
-			}
1140
-
1141
-			$out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142
-			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
-			$out.= $this->eol.$strContent.$this->eol;
1144
-
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146
-			{
1147
-				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148
-			}
1149
-		}
1150
-		else
1151
-		{
1152
-			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153
-			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
-			$out.= $this->eol.$strContent.$this->eol;
1155
-		}
1156
-
1157
-		$out.= $this->eol;
1158
-
1159
-		// Encode images
1160
-		if ($this->atleastoneimage)
1161
-		{
1162
-			$out .= $this->write_images($this->images_encoded);
1163
-			// always end related and end alternative after inline images
1164
-			$out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
-			$out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1166
-			$out .= $this->eol;
1167
-		}
1168
-
1169
-		return $out;
1170
-	}
1066
+        dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1067
+        return $out;
1068
+    }
1171 1069
 
1172 1070
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1173
-	/**
1174
-	 * Attach file to email (mode = 'mail')
1175
-	 *
1176
-	 * @param	array	$filename_list		Tableau
1177
-	 * @param	array	$mimetype_list		Tableau
1178
-	 * @param 	array	$mimefilename_list	Tableau
1179
-	 * @return	string						Chaine fichiers encodes
1180
-	 */
1181
-	function write_files($filename_list,$mimetype_list,$mimefilename_list)
1182
-	{
1071
+    /**
1072
+     * Return email content (mode = 'mail')
1073
+     *
1074
+     * @param	string		$msgtext		Message string
1075
+     * @return	string						String content
1076
+     */
1077
+    function write_body($msgtext)
1078
+    {
1183 1079
         // phpcs:enable
1184
-		$out = '';
1185
-
1186
-		$filename_list_size=count($filename_list);
1187
-		for($i=0;$i < $filename_list_size;$i++)
1188
-		{
1189
-			if ($filename_list[$i])
1190
-			{
1191
-				dol_syslog("CMailFile::write_files: i=$i");
1192
-				$encoded = $this->_encode_file($filename_list[$i]);
1193
-				if ($encoded >= 0)
1194
-				{
1195
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
-					if (! $mimetype_list[$i]) {
1197
-						$mimetype_list[$i] = "application/octet-stream";
1198
-					}
1199
-
1200
-					$out.= "--" . $this->mixed_boundary . $this->eol;
1201
-					$out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
-					$out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
-					$out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
-					$out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
-					$out.= $this->eol;
1206
-					$out.= $encoded;
1207
-					$out.= $this->eol;
1208
-					//$out.= $this->eol;
1209
-				}
1210
-				else
1211
-				{
1212
-					return $encoded;
1213
-				}
1214
-			}
1215
-		}
1216
-
1217
-		return $out;
1218
-	}
1080
+        global $conf;
1081
+
1082
+        $out='';
1083
+
1084
+        $out.= "--" . $this->mixed_boundary . $this->eol;
1085
+
1086
+        if ($this->atleastoneimage)
1087
+        {
1088
+            $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
+            $out.= $this->eol;
1090
+            $out.= "--" . $this->alternative_boundary . $this->eol;
1091
+        }
1092
+
1093
+        // Make RFC821 Compliant, replace bare linefeeds
1094
+        $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
+        if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096
+        {
1097
+            $strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1098
+        }
1099
+
1100
+        $strContentAltText = '';
1101
+        if ($this->msgishtml)
1102
+        {
1103
+            // Similar code to forge a text from html is also in CMailFile.class.php
1104
+            $strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1105
+            $strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
+            $strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1107
+
1108
+            // Check if html header already in message, if not complete the message
1109
+            $strContent = $this->checkIfHTML($strContent);
1110
+        }
1111
+
1112
+        // Make RFC2045 Compliant, split lines
1113
+        //$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114
+        // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
+        $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1116
+
1117
+        if ($this->msgishtml)
1118
+        {
1119
+            if ($this->atleastoneimage)
1120
+            {
1121
+                $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122
+                //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
+                $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1125
+                $out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
+                $out.= $this->eol;
1127
+                $out.= "--" . $this->related_boundary . $this->eol;
1128
+            }
1129
+
1130
+            if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131
+            {
1132
+                $out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
+                $out.= $this->eol;
1134
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1135
+                $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136
+                //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
+                $out.= $this->eol.$strContentAltText.$this->eol;
1138
+                $out.= "--" . $this->alternative_boundary . $this->eol;
1139
+            }
1140
+
1141
+            $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142
+            //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
+            $out.= $this->eol.$strContent.$this->eol;
1219 1144
 
1145
+            if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146
+            {
1147
+                $out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148
+            }
1149
+        }
1150
+        else
1151
+        {
1152
+            $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153
+            //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
+            $out.= $this->eol.$strContent.$this->eol;
1155
+        }
1156
+
1157
+        $out.= $this->eol;
1158
+
1159
+        // Encode images
1160
+        if ($this->atleastoneimage)
1161
+        {
1162
+            $out .= $this->write_images($this->images_encoded);
1163
+            // always end related and end alternative after inline images
1164
+            $out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
+            $out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1166
+            $out .= $this->eol;
1167
+        }
1168
+
1169
+        return $out;
1170
+    }
1220 1171
 
1221 1172
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1222
-	/**
1223
-	 * Attach an image to email (mode = 'mail')
1224
-	 *
1225
-	 * @param	array	$images_list	Array of array image
1226
-	 * @return	string					Chaine images encodees
1227
-	 */
1228
-	function write_images($images_list)
1229
-	{
1173
+    /**
1174
+     * Attach file to email (mode = 'mail')
1175
+     *
1176
+     * @param	array	$filename_list		Tableau
1177
+     * @param	array	$mimetype_list		Tableau
1178
+     * @param 	array	$mimefilename_list	Tableau
1179
+     * @return	string						Chaine fichiers encodes
1180
+     */
1181
+    function write_files($filename_list,$mimetype_list,$mimefilename_list)
1182
+    {
1230 1183
         // phpcs:enable
1231
-		$out = '';
1184
+        $out = '';
1185
+
1186
+        $filename_list_size=count($filename_list);
1187
+        for($i=0;$i < $filename_list_size;$i++)
1188
+        {
1189
+            if ($filename_list[$i])
1190
+            {
1191
+                dol_syslog("CMailFile::write_files: i=$i");
1192
+                $encoded = $this->_encode_file($filename_list[$i]);
1193
+                if ($encoded >= 0)
1194
+                {
1195
+                    if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
+                    if (! $mimetype_list[$i]) {
1197
+                        $mimetype_list[$i] = "application/octet-stream";
1198
+                    }
1199
+
1200
+                    $out.= "--" . $this->mixed_boundary . $this->eol;
1201
+                    $out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
+                    $out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
+                    $out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
+                    $out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
+                    $out.= $this->eol;
1206
+                    $out.= $encoded;
1207
+                    $out.= $this->eol;
1208
+                    //$out.= $this->eol;
1209
+                }
1210
+                else
1211
+                {
1212
+                    return $encoded;
1213
+                }
1214
+            }
1215
+        }
1232 1216
 
1233
-		if (is_array($images_list))
1234
-		{
1235
-			foreach ($images_list as $img)
1236
-			{
1237
-				dol_syslog("CMailFile::write_images: ".$img["name"]);
1217
+        return $out;
1218
+    }
1238 1219
 
1239
-				$out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
-				$out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
-				$out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
-				$out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
-				$out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
-				$out.= $this->eol;
1245
-				$out.= $img["image_encoded"];
1246
-				$out.= $this->eol;
1247
-			}
1248
-		}
1249 1220
 
1250
-		return $out;
1251
-	}
1221
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1222
+    /**
1223
+     * Attach an image to email (mode = 'mail')
1224
+     *
1225
+     * @param	array	$images_list	Array of array image
1226
+     * @return	string					Chaine images encodees
1227
+     */
1228
+    function write_images($images_list)
1229
+    {
1230
+        // phpcs:enable
1231
+        $out = '';
1232
+
1233
+        if (is_array($images_list))
1234
+        {
1235
+            foreach ($images_list as $img)
1236
+            {
1237
+                dol_syslog("CMailFile::write_images: ".$img["name"]);
1238
+
1239
+                $out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
+                $out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
+                $out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
+                $out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
+                $out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
+                $out.= $this->eol;
1245
+                $out.= $img["image_encoded"];
1246
+                $out.= $this->eol;
1247
+            }
1248
+        }
1249
+
1250
+        return $out;
1251
+    }
1252 1252
 
1253 1253
 
1254 1254
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1255
-	/**
1256
-	 * Try to create a socket connection
1257
-	 *
1258
-	 * @param 	string		$host		Add ssl:// for SSL/TLS.
1259
-	 * @param 	int			$port		Example: 25, 465
1260
-	 * @return	int						Socket id if ok, 0 if KO
1261
-	 */
1262
-	function check_server_port($host,$port)
1263
-	{
1255
+    /**
1256
+     * Try to create a socket connection
1257
+     *
1258
+     * @param 	string		$host		Add ssl:// for SSL/TLS.
1259
+     * @param 	int			$port		Example: 25, 465
1260
+     * @return	int						Socket id if ok, 0 if KO
1261
+     */
1262
+    function check_server_port($host,$port)
1263
+    {
1264 1264
         // phpcs:enable
1265
-		global $conf;
1266
-
1267
-		$_retVal=0;
1268
-		$timeout=5;	// Timeout in seconds
1269
-
1270
-		if (function_exists('fsockopen'))
1271
-		{
1272
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1278
-			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279
-			{
1280
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286
-			}
1287
-
1288
-			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1290
-			// tls smtp start with no encryption
1291
-			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292
-
1293
-			dol_syslog("Try socket connection to host=".$host." port=".$port);
1294
-			//See if we can connect to the SMTP server
1295
-			if ($socket = @fsockopen(
1296
-					$host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
-					$port,       // which Port number to use
1298
-					$errno,      // actual system level error
1299
-					$errstr,     // and any text that goes with the error
1300
-					$timeout
1301
-			))  // timeout for reading/writing data over the socket
1302
-			{
1303
-				// Windows still does not have support for this timeout function
1304
-				if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1305
-
1306
-				dol_syslog("Now we wait for answer 220");
1307
-
1308
-				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
-			}
1311
-			else
1312
-			{
1313
-				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314
-			}
1315
-		}
1316
-		return $_retVal;
1317
-	}
1265
+        global $conf;
1266
+
1267
+        $_retVal=0;
1268
+        $timeout=5;	// Timeout in seconds
1269
+
1270
+        if (function_exists('fsockopen'))
1271
+        {
1272
+            $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
+            $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
+            $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
+            $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
+            $keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
+            $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1278
+            if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279
+            {
1280
+                $keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
+                $keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
+                $keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
+                $keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
+                $keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
+                $keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286
+            }
1287
+
1288
+            // If we use SSL/TLS
1289
+            if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1290
+            // tls smtp start with no encryption
1291
+            //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292
+
1293
+            dol_syslog("Try socket connection to host=".$host." port=".$port);
1294
+            //See if we can connect to the SMTP server
1295
+            if ($socket = @fsockopen(
1296
+                    $host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
+                    $port,       // which Port number to use
1298
+                    $errno,      // actual system level error
1299
+                    $errstr,     // and any text that goes with the error
1300
+                    $timeout
1301
+            ))  // timeout for reading/writing data over the socket
1302
+            {
1303
+                // Windows still does not have support for this timeout function
1304
+                if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1305
+
1306
+                dol_syslog("Now we wait for answer 220");
1307
+
1308
+                // Check response from Server
1309
+                if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
+            }
1311
+            else
1312
+            {
1313
+                $this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314
+            }
1315
+        }
1316
+        return $_retVal;
1317
+    }
1318 1318
 
1319 1319
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1320
-	/**
1321
-	 * This function has been modified as provided by SirSir to allow multiline responses when
1322
-	 * using SMTP Extensions.
1323
-	 *
1324
-	 * @param	Socket	$socket			Socket
1325
-	 * @param   string	$response		Response string
1326
-	 * @return  boolean					true if success
1327
-	 */
1328
-	function server_parse($socket, $response)
1329
-	{
1320
+    /**
1321
+     * This function has been modified as provided by SirSir to allow multiline responses when
1322
+     * using SMTP Extensions.
1323
+     *
1324
+     * @param	Socket	$socket			Socket
1325
+     * @param   string	$response		Response string
1326
+     * @return  boolean					true if success
1327
+     */
1328
+    function server_parse($socket, $response)
1329
+    {
1330 1330
         // phpcs:enable
1331
-		$_retVal = true;	// Indicates if Object was created or not
1332
-		$server_response = '';
1333
-
1334
-		while (substr($server_response,3,1) != ' ')
1335
-		{
1336
-			if (! ($server_response = fgets($socket, 256)) )
1337
-			{
1338
-				$this->error="Couldn't get mail server response codes";
1339
-				return false;
1340
-			}
1341
-		}
1342
-
1343
-		if( !( substr($server_response, 0, 3) == $response ) )
1344
-		{
1345
-			$this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1346
-			$_retVal = false;
1347
-		}
1348
-
1349
-		return $_retVal;
1350
-	}
1351
-
1352
-	/**
1353
-	 * Seearch images into html message and init array this->images_encoded if found
1354
-	 *
1355
-	 * @param	string	$images_dir		Location of physical images files
1356
-	 * @return	int 		        	>0 if OK, <0 if KO
1357
-	 */
1358
-	function findHtmlImages($images_dir)
1359
-	{
1360
-		// Build the list of image extensions
1361
-		$extensions = array_keys($this->image_types);
1362
-
1363
-		$matches = array();
1364
-		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1365
-
1366
-		if (! empty($matches))
1367
-		{
1368
-			$i=0;
1369
-			foreach ($matches[1] as $full)
1370
-			{
1371
-
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1373
-				{
1374
-					$img = $regs[1];
1375
-
1376
-					if (file_exists($images_dir.'/'.$img))
1377
-					{
1378
-						// Image path in src
1379
-						$src = preg_quote($full,'/');
1380
-
1381
-						// Image full path
1382
-						$this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
1383
-
1384
-						// Image name
1385
-						$this->html_images[$i]["name"] = $img;
1386
-
1387
-						// Content type
1388
-						if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389
-						{
1390
-							$ext=strtolower($reg[1]);
1391
-							$this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392
-						}
1393
-
1394
-						// cid
1395
-						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1396
-						$this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397
-					}
1398
-					$i++;
1399
-				}
1400
-			}
1401
-
1402
-			if (!empty($this->html_images))
1403
-			{
1404
-				$inline = array();
1405
-
1406
-				$i=0;
1407
-
1408
-				foreach ($this->html_images as $img)
1409
-				{
1410
-					$fullpath = $images_dir.'/'.$img["name"];
1411
-
1412
-					// If duplicate images are embedded, they may show up as attachments, so remove them.
1413
-					if (!in_array($fullpath,$inline))
1414
-					{
1415
-						// Read image file
1416
-						if ($image = file_get_contents($fullpath))
1417
-						{
1418
-							// On garde que le nom de l'image
1419
-							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1420
-							$imgName = $regs[1];
1421
-
1422
-							$this->images_encoded[$i]['name'] = $imgName;
1423
-							$this->images_encoded[$i]['fullpath'] = $fullpath;
1424
-							$this->images_encoded[$i]['content_type'] = $img["content_type"];
1425
-							$this->images_encoded[$i]['cid'] = $img["cid"];
1426
-							// Encodage de l'image
1427
-							$this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1428
-							$inline[] = $fullpath;
1429
-						}
1430
-					}
1431
-					$i++;
1432
-				}
1433
-			}
1434
-			else
1435
-			{
1436
-				return -1;
1437
-			}
1438
-
1439
-			return 1;
1440
-		}
1441
-		else
1442
-		{
1443
-			return 0;
1444
-		}
1445
-	}
1446
-
1447
-	/**
1448
-	 * Return a formatted address string for SMTP protocol
1449
-	 *
1450
-	 * @param	string		$address		     Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1451
-	 * @param	int			$format			     0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between "
1452
-	 * @param	int			$encode			     0=No encode name, 1=Encode name to RFC2822
1453
-	 * @param   int         $maxnumberofemail    0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
1454
-	 * @return	string						     If format 0: '<[email protected]>' or 'John Doe <[email protected]>' or '=?UTF-8?B?Sm9obiBEb2U=?= <[email protected]>'
1455
-	 * 										     If format 1: '<[email protected]>'
1456
-	 *										     If format 2: '[email protected]'
1457
-	 *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458
-	 *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459
-	 */
1460
-	static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1461
-	{
1462
-		global $conf;
1463
-
1464
-		$ret='';
1465
-
1466
-		$arrayaddress=explode(',',$address);
1467
-
1468
-		// Boucle sur chaque composant de l'adresse
1469
-		$i=0;
1470
-		foreach($arrayaddress as $val)
1471
-		{
1472
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1473
-			{
1474
-				$name  = trim($regs[1]);
1475
-				$email = trim($regs[2]);
1476
-			}
1477
-			else
1478
-			{
1479
-				$name  = '';
1480
-				$email = trim($val);
1481
-			}
1482
-
1483
-			if ($email)
1484
-			{
1485
-				$i++;
1486
-
1487
-				$newemail='';
1488
-				if ($format == 4)
1489
-				{
1490
-					$newemail = $name?$name:$email;
1491
-				}
1492
-				if ($format == 2)
1493
-				{
1494
-					$newemail=$email;
1495
-				}
1496
-				if ($format == 1 || $format == 3)
1497
-				{
1498
-					$newemail='<'.$email.'>';
1499
-				}
1500
-				if ($format == 0 || $format == 3)
1501
-				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1505
-				}
1506
-
1507
-				$ret=($ret ? $ret.',' : '').$newemail;
1508
-
1509
-				// Stop if we have too much records
1510
-				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511
-				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1513
-					break;
1514
-				}
1515
-			}
1516
-		}
1517
-
1518
-		return $ret;
1519
-	}
1520
-
1521
-	/**
1522
-	 * Return a formatted array of address string for SMTP protocol
1523
-	 *
1524
-	 * @param   string      $address        Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1525
-	 * @return  array                       array of email => name
1526
-	 */
1527
-	function getArrayAddress($address)
1528
-	{
1529
-		global $conf;
1530
-
1531
-		$ret=array();
1532
-
1533
-		$arrayaddress=explode(',',$address);
1534
-
1535
-		// Boucle sur chaque composant de l'adresse
1536
-		foreach($arrayaddress as $val)
1537
-		{
1538
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1539
-			{
1540
-				$name  = trim($regs[1]);
1541
-				$email = trim($regs[2]);
1542
-			}
1543
-			else
1544
-			{
1545
-				$name  = null;
1546
-				$email = trim($val);
1547
-			}
1548
-
1549
-			$ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1550
-		}
1551
-
1552
-		return $ret;
1553
-	}
1331
+        $_retVal = true;	// Indicates if Object was created or not
1332
+        $server_response = '';
1333
+
1334
+        while (substr($server_response,3,1) != ' ')
1335
+        {
1336
+            if (! ($server_response = fgets($socket, 256)) )
1337
+            {
1338
+                $this->error="Couldn't get mail server response codes";
1339
+                return false;
1340
+            }
1341
+        }
1342
+
1343
+        if( !( substr($server_response, 0, 3) == $response ) )
1344
+        {
1345
+            $this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1346
+            $_retVal = false;
1347
+        }
1348
+
1349
+        return $_retVal;
1350
+    }
1351
+
1352
+    /**
1353
+     * Seearch images into html message and init array this->images_encoded if found
1354
+     *
1355
+     * @param	string	$images_dir		Location of physical images files
1356
+     * @return	int 		        	>0 if OK, <0 if KO
1357
+     */
1358
+    function findHtmlImages($images_dir)
1359
+    {
1360
+        // Build the list of image extensions
1361
+        $extensions = array_keys($this->image_types);
1362
+
1363
+        $matches = array();
1364
+        preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1365
+
1366
+        if (! empty($matches))
1367
+        {
1368
+            $i=0;
1369
+            foreach ($matches[1] as $full)
1370
+            {
1371
+
1372
+                if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1373
+                {
1374
+                    $img = $regs[1];
1375
+
1376
+                    if (file_exists($images_dir.'/'.$img))
1377
+                    {
1378
+                        // Image path in src
1379
+                        $src = preg_quote($full,'/');
1380
+
1381
+                        // Image full path
1382
+                        $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
1383
+
1384
+                        // Image name
1385
+                        $this->html_images[$i]["name"] = $img;
1386
+
1387
+                        // Content type
1388
+                        if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389
+                        {
1390
+                            $ext=strtolower($reg[1]);
1391
+                            $this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392
+                        }
1393
+
1394
+                        // cid
1395
+                        $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1396
+                        $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397
+                    }
1398
+                    $i++;
1399
+                }
1400
+            }
1401
+
1402
+            if (!empty($this->html_images))
1403
+            {
1404
+                $inline = array();
1405
+
1406
+                $i=0;
1407
+
1408
+                foreach ($this->html_images as $img)
1409
+                {
1410
+                    $fullpath = $images_dir.'/'.$img["name"];
1411
+
1412
+                    // If duplicate images are embedded, they may show up as attachments, so remove them.
1413
+                    if (!in_array($fullpath,$inline))
1414
+                    {
1415
+                        // Read image file
1416
+                        if ($image = file_get_contents($fullpath))
1417
+                        {
1418
+                            // On garde que le nom de l'image
1419
+                            preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1420
+                            $imgName = $regs[1];
1421
+
1422
+                            $this->images_encoded[$i]['name'] = $imgName;
1423
+                            $this->images_encoded[$i]['fullpath'] = $fullpath;
1424
+                            $this->images_encoded[$i]['content_type'] = $img["content_type"];
1425
+                            $this->images_encoded[$i]['cid'] = $img["cid"];
1426
+                            // Encodage de l'image
1427
+                            $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1428
+                            $inline[] = $fullpath;
1429
+                        }
1430
+                    }
1431
+                    $i++;
1432
+                }
1433
+            }
1434
+            else
1435
+            {
1436
+                return -1;
1437
+            }
1438
+
1439
+            return 1;
1440
+        }
1441
+        else
1442
+        {
1443
+            return 0;
1444
+        }
1445
+    }
1446
+
1447
+    /**
1448
+     * Return a formatted address string for SMTP protocol
1449
+     *
1450
+     * @param	string		$address		     Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1451
+     * @param	int			$format			     0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between "
1452
+     * @param	int			$encode			     0=No encode name, 1=Encode name to RFC2822
1453
+     * @param   int         $maxnumberofemail    0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
1454
+     * @return	string						     If format 0: '<[email protected]>' or 'John Doe <[email protected]>' or '=?UTF-8?B?Sm9obiBEb2U=?= <[email protected]>'
1455
+     * 										     If format 1: '<[email protected]>'
1456
+     *										     If format 2: '[email protected]'
1457
+     *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458
+     *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459
+     */
1460
+    static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1461
+    {
1462
+        global $conf;
1463
+
1464
+        $ret='';
1465
+
1466
+        $arrayaddress=explode(',',$address);
1467
+
1468
+        // Boucle sur chaque composant de l'adresse
1469
+        $i=0;
1470
+        foreach($arrayaddress as $val)
1471
+        {
1472
+            if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1473
+            {
1474
+                $name  = trim($regs[1]);
1475
+                $email = trim($regs[2]);
1476
+            }
1477
+            else
1478
+            {
1479
+                $name  = '';
1480
+                $email = trim($val);
1481
+            }
1482
+
1483
+            if ($email)
1484
+            {
1485
+                $i++;
1486
+
1487
+                $newemail='';
1488
+                if ($format == 4)
1489
+                {
1490
+                    $newemail = $name?$name:$email;
1491
+                }
1492
+                if ($format == 2)
1493
+                {
1494
+                    $newemail=$email;
1495
+                }
1496
+                if ($format == 1 || $format == 3)
1497
+                {
1498
+                    $newemail='<'.$email.'>';
1499
+                }
1500
+                if ($format == 0 || $format == 3)
1501
+                {
1502
+                    if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
+                    elseif (! $name) $newemail='<'.$email.'>';
1504
+                    else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1505
+                }
1506
+
1507
+                $ret=($ret ? $ret.',' : '').$newemail;
1508
+
1509
+                // Stop if we have too much records
1510
+                if ($maxnumberofemail && $i >= $maxnumberofemail)
1511
+                {
1512
+                    if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1513
+                    break;
1514
+                }
1515
+            }
1516
+        }
1517
+
1518
+        return $ret;
1519
+    }
1520
+
1521
+    /**
1522
+     * Return a formatted array of address string for SMTP protocol
1523
+     *
1524
+     * @param   string      $address        Example: 'John Doe <[email protected]>, Alan Smith <[email protected]>' or '[email protected], [email protected]'
1525
+     * @return  array                       array of email => name
1526
+     */
1527
+    function getArrayAddress($address)
1528
+    {
1529
+        global $conf;
1530
+
1531
+        $ret=array();
1532
+
1533
+        $arrayaddress=explode(',',$address);
1534
+
1535
+        // Boucle sur chaque composant de l'adresse
1536
+        foreach($arrayaddress as $val)
1537
+        {
1538
+            if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1539
+            {
1540
+                $name  = trim($regs[1]);
1541
+                $email = trim($regs[2]);
1542
+            }
1543
+            else
1544
+            {
1545
+                $name  = null;
1546
+                $email = trim($val);
1547
+            }
1548
+
1549
+            $ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1550
+        }
1551
+
1552
+        return $ret;
1553
+    }
1554 1554
 }
Please login to merge, or discard this patch.
Spacing   +329 added lines, -329 removed lines patch added patch discarded remove patch
@@ -40,13 +40,13 @@  discard block
 block discarded – undo
40 40
 	public $sendmode;
41 41
 	public $sendsetup;
42 42
 
43
-	var $subject;      	// Topic:       Subject of email
44
-	var $addr_from;    	// From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
43
+	var $subject; // Topic:       Subject of email
44
+	var $addr_from; // From:		Label and EMail of sender (must include '<>'). For example '<[email protected]>' or 'John Doe <[email protected]>' or '<[email protected]>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
45 45
 	// Sender:      Who send the email ("Sender" has sent emails on behalf of "From").
46 46
 	//              Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
47 47
 	// Return-Path: Email where to send bounds.
48
-	var $reply_to;		// Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
-	var $errors_to;		// Errors-To:	Email where to send errors.
48
+	var $reply_to; // Reply-To:	Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
49
+	var $errors_to; // Errors-To:	Email where to send errors.
50 50
 	var $addr_to;
51 51
 	var $addr_cc;
52 52
 	var $addr_bcc;
@@ -63,10 +63,10 @@  discard block
 block discarded – undo
63 63
 	/**
64 64
 	 * @var string Error code (or message)
65 65
 	 */
66
-	public $error='';
66
+	public $error = '';
67 67
 
68
-	var $smtps;			// Contains SMTPs object (if this method is used)
69
-	var $phpmailer;		// Contains PHPMailer object (if this method is used)
68
+	var $smtps; // Contains SMTPs object (if this method is used)
69
+	var $phpmailer; // Contains PHPMailer object (if this method is used)
70 70
 
71 71
 	/**
72 72
 	 * @var string CSS
@@ -83,9 +83,9 @@  discard block
 block discarded – undo
83 83
 	// Image
84 84
 	var $html;
85 85
 	var $image_boundary;
86
-	var $atleastoneimage=0;    // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
-	var $html_images=array();
88
-	var $images_encoded=array();
86
+	var $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
87
+	var $html_images = array();
88
+	var $images_encoded = array();
89 89
 	var $image_types = array(
90 90
         'gif'  => 'image/gif',
91 91
 		'jpg'  => 'image/jpeg',
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
 	 *  @param  string  $sendcontext      	 'standard', 'emailing', ... (used to define with sending mode and parameters to use)
120 120
 	 *  @param	string	$replyto			 Reply-to email (will be set to same value than From by default if not provided)
121 121
 	 */
122
-	function __construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='')
122
+	function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = 0, $errors_to = '', $css = '', $trackid = '', $moreinheader = '', $sendcontext = 'standard', $replyto = '')
123 123
 	{
124 124
 		global $conf, $dolibarr_main_data_root;
125 125
 
126 126
 		$this->sendcontext = $sendcontext;
127 127
 
128
-		if (empty($replyto)) $replyto=$from;
128
+		if (empty($replyto)) $replyto = $from;
129 129
 
130 130
 		// Define this->sendmode
131 131
 		$this->sendmode = '';
@@ -133,28 +133,28 @@  discard block
 block discarded – undo
133 133
 		{
134 134
 			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135 135
 		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
136
+		if (empty($this->sendmode)) $this->sendmode = $conf->global->MAIN_MAIL_SENDMODE;
137
+		if (empty($this->sendmode)) $this->sendmode = 'mail';
138 138
 
139 139
 		// We define end of line (RFC 821).
140
-		$this->eol="\r\n";
140
+		$this->eol = "\r\n";
141 141
 		// We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
142
-		$this->eol2="\r\n";
143
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
142
+		$this->eol2 = "\r\n";
143
+		if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
144 144
 		{
145
-			$this->eol="\n";
146
-			$this->eol2="\n";
147
-			$moreinheader = str_replace("\r\n","\n",$moreinheader);
145
+			$this->eol = "\n";
146
+			$this->eol2 = "\n";
147
+			$moreinheader = str_replace("\r\n", "\n", $moreinheader);
148 148
 		}
149 149
 
150 150
 		// On defini mixed_boundary
151
-		$this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
151
+		$this->mixed_boundary = "multipart_x.".time().".x_boundary";
152 152
 
153 153
 		// On defini related_boundary
154
-		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3);	// Force md5 hash (does not contains special chars)
154
+		$this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars)
155 155
 
156 156
 		// On defini alternative_boundary
157
-		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3);	// Force md5 hash (does not contains special chars)
157
+		$this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars)
158 158
 
159 159
 		dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
160 160
 		dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
 		if (empty($subject))
163 163
 		{
164 164
 			dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
165
-			$this->error='ErrorSubjectIsRequired';
165
+			$this->error = 'ErrorSubjectIsRequired';
166 166
 			return;
167 167
 		}
168 168
 		if (empty($msg))
169 169
 		{
170 170
 		    dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
171
-		    $msg='.';     // Avoid empty message (with empty message conten show a multipart structure)
171
+		    $msg = '.'; // Avoid empty message (with empty message conten show a multipart structure)
172 172
 		}
173 173
 
174 174
 		// Detect if message is HTML (use fast method)
@@ -185,21 +185,21 @@  discard block
 block discarded – undo
185 185
 		global $dolibarr_main_url_root;
186 186
 
187 187
 		// Define $urlwithroot
188
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
189
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
188
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
189
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
190 190
 		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
191 191
 
192 192
 		// Replace relative /viewimage to absolute path
193
-		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
193
+		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194 194
 
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
195
+		if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml = 1; // To force to send everything with content type html.
196 196
 
197 197
 		// Detect images
198 198
 		if ($this->msgishtml)
199 199
 		{
200 200
 			$this->html = $msg;
201 201
 
202
-			if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
202
+			if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
203 203
 			{
204 204
 				$findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
205 205
 			}
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 				{
212 212
 					if ($this->html_images[$i])
213 213
 					{
214
-						$this->atleastoneimage=1;
214
+						$this->atleastoneimage = 1;
215 215
 						dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
216 216
 					}
217 217
 				}
@@ -225,14 +225,14 @@  discard block
 block discarded – undo
225 225
 			{
226 226
 				if ($filename_list[$i])
227 227
 				{
228
-					$this->atleastonefile=1;
228
+					$this->atleastonefile = 1;
229 229
 					dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
230 230
 				}
231 231
 			}
232 232
 		}
233 233
 
234 234
 		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
235
+		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc .= ($addr_bcc ? ', ' : '').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
236 236
 
237 237
 		// Action according to choosed sending method
238 238
 		if ($this->sendmode == 'mail')
@@ -257,17 +257,17 @@  discard block
 block discarded – undo
257 257
 			$this->trackid = $trackid;
258 258
 
259 259
 			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
260
+			if (!empty($moreinheader)) $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n
261 261
 
262 262
 			// Define mime_headers
263 263
 			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
264 264
 
265
-			if (! empty($this->html))
265
+			if (!empty($this->html))
266 266
 			{
267 267
 				if (!empty($css))
268 268
 				{
269 269
 					$this->css = $css;
270
-					$this->buildCSS();    // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
270
+					$this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
271 271
 				}
272 272
 
273 273
 				$msg = $this->html;
@@ -279,20 +279,20 @@  discard block
 block discarded – undo
279 279
 			// Add attachments to text_encoded
280 280
 			if ($this->atleastonefile)
281 281
 			{
282
-				$files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
282
+				$files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list);
283 283
 			}
284 284
 
285 285
 			// We now define $this->headers and $this->message
286
-			$this->headers = $smtp_headers . $mime_headers;
286
+			$this->headers = $smtp_headers.$mime_headers;
287 287
 			// On nettoie le header pour qu'il ne se termine pas par un retour chariot.
288 288
 			// Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
289 289
 			// comme des injections mail par les serveurs de messagerie.
290
-			$this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
290
+			$this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers);
291 291
 
292 292
 			//$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
293 293
 			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294
-			$this->message.= $text_body . $files_encoded;
295
-			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
294
+			$this->message .= $text_body.$files_encoded;
295
+			$this->message .= "--".$this->mixed_boundary."--".$this->eol;
296 296
 		}
297 297
 		else if ($this->sendmode == 'smtps')
298 298
 		{
@@ -304,14 +304,14 @@  discard block
 block discarded – undo
304 304
 			$smtps->setCharSet($conf->file->character_set_client);
305 305
 
306 306
 			$smtps->setSubject($this->encodetorfc2822($subject));
307
-			$smtps->setTO($this->getValidAddress($to,0,1));
308
-			$smtps->setFrom($this->getValidAddress($from,0,1));
307
+			$smtps->setTO($this->getValidAddress($to, 0, 1));
308
+			$smtps->setFrom($this->getValidAddress($from, 0, 1));
309 309
 			$smtps->setTrackId($trackid);
310
-			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
310
+			$smtps->setReplyTo($this->getValidAddress($replyto, 0, 1));
311 311
 
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
312
+			if (!empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
313 313
 
314
-			if (! empty($this->html))
314
+			if (!empty($this->html))
315 315
 			{
316 316
 				if (!empty($css))
317 317
 				{
@@ -322,14 +322,14 @@  discard block
 block discarded – undo
322 322
 				$msg = $this->checkIfHTML($msg);
323 323
 			}
324 324
 
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
325
+			if ($this->msgishtml) $smtps->setBodyContent($msg, 'html');
326
+			else $smtps->setBodyContent($msg, 'plain');
327 327
 
328 328
 			if ($this->atleastoneimage)
329 329
 			{
330 330
 				foreach ($this->images_encoded as $img)
331 331
 				{
332
-					$smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
332
+					$smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']);
333 333
 				}
334 334
 			}
335 335
 
@@ -337,8 +337,8 @@  discard block
 block discarded – undo
337 337
 			{
338 338
 				foreach ($filename_list as $i => $val)
339 339
 				{
340
-					$content=file_get_contents($filename_list[$i]);
341
-					$smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
340
+					$content = file_get_contents($filename_list[$i]);
341
+					$smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i]);
342 342
 				}
343 343
 			}
344 344
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
 			$smtps->setErrorsTo($errors_to);
348 348
 			$smtps->setDeliveryReceipt($deliveryreceipt);
349 349
 
350
-			$this->smtps=$smtps;
350
+			$this->smtps = $smtps;
351 351
 		}
352 352
 		else if ($this->sendmode == 'swiftmailer')
353 353
 		{
@@ -383,8 +383,8 @@  discard block
 block discarded – undo
383 383
             //$this->message = new Swift_SignedMessage();
384 384
             // Adding a trackid header to a message
385 385
 			$headers = $this->message->getHeaders();
386
-			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid . '@' . $host);
387
-			$headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
386
+			$headers->addTextHeader('X-Dolibarr-TRACKID', $trackid.'@'.$host);
387
+			$headerID = time().'.swiftmailer-dolibarr-'.$trackid.'@'.$host;
388 388
 			$msgid = $headers->get('Message-ID');
389 389
 			$msgid->setId($headerID);
390 390
 			$headers->addIdHeader('References', $headerID);
@@ -394,12 +394,12 @@  discard block
 block discarded – undo
394 394
 			try {
395 395
 				$result = $this->message->setSubject($subject);
396 396
 			} catch (Exception $e) {
397
-				$this->errors[] =  $e->getMessage();
397
+				$this->errors[] = $e->getMessage();
398 398
 			}
399 399
 
400 400
 			// Set the From address with an associative array
401 401
 			//$this->message->setFrom(array('[email protected]' => 'John Doe'));
402
-			if (! empty($from)) {
402
+			if (!empty($from)) {
403 403
                 try {
404 404
                 	$result = $this->message->setFrom($this->getArrayAddress($from));
405 405
                 } catch (Exception $e) {
@@ -408,7 +408,7 @@  discard block
 block discarded – undo
408 408
             }
409 409
 
410 410
 			// Set the To addresses with an associative array
411
-			if (! empty($to)) {
411
+			if (!empty($to)) {
412 412
                 try {
413 413
                 	$result = $this->message->setTo($this->getArrayAddress($to));
414 414
                 } catch (Exception $e) {
@@ -416,7 +416,7 @@  discard block
 block discarded – undo
416 416
                 }
417 417
             }
418 418
 
419
-			if (! empty($replyto)) {
419
+			if (!empty($replyto)) {
420 420
                 try {
421 421
                 	$result = $this->message->SetReplyTo($this->getArrayAddress($replyto));
422 422
                 } catch (Exception $e) {
@@ -427,10 +427,10 @@  discard block
 block discarded – undo
427 427
 			try {
428 428
 				$result = $this->message->setCharSet($conf->file->character_set_client);
429 429
 			} catch (Exception $e) {
430
-				$this->errors[] =  $e->getMessage();
430
+				$this->errors[] = $e->getMessage();
431 431
 			}
432 432
 
433
-			if (! empty($this->html))
433
+			if (!empty($this->html))
434 434
 			{
435 435
 				if (!empty($css))
436 436
 				{
@@ -455,11 +455,11 @@  discard block
 block discarded – undo
455 455
 			}
456 456
 
457 457
 			if ($this->msgishtml) {
458
-				$this->message->setBody($msg,'text/html');
458
+				$this->message->setBody($msg, 'text/html');
459 459
 				// And optionally an alternative body
460 460
 				$this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
461 461
 			} else {
462
-				$this->message->setBody($msg,'text/plain');
462
+				$this->message->setBody($msg, 'text/plain');
463 463
 				// And optionally an alternative body
464 464
 				$this->message->addPart($msg, 'text/html');
465 465
 			}
@@ -469,13 +469,13 @@  discard block
 block discarded – undo
469 469
 				foreach ($filename_list as $i => $val)
470 470
 				{
471 471
 					//$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
472
-					$attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
472
+					$attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
473 473
 					$this->message->attach($attachment);
474 474
 				}
475 475
 			}
476 476
 
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
477
+			if (!empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
+			if (!empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
479 479
 			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480 480
 			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481 481
 		}
@@ -495,25 +495,25 @@  discard block
 block discarded – undo
495 495
 	 */
496 496
 	function sendfile()
497 497
 	{
498
-		global $conf,$db,$langs;
498
+		global $conf, $db, $langs;
499 499
 
500
-		$errorlevel=error_reporting();
500
+		$errorlevel = error_reporting();
501 501
 		//error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
502 502
 
503
-		$res=false;
503
+		$res = false;
504 504
 
505 505
 		if (empty($conf->global->MAIN_DISABLE_ALL_MAILS) || !empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
506 506
 		{
507
-			require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
507
+			require_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
508 508
 			$hookmanager = new HookManager($db);
509 509
 			$hookmanager->initHooks(array('mail'));
510 510
 
511
-			$parameters=array(); $action='';
511
+			$parameters = array(); $action = '';
512 512
 			$reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
513 513
 			if ($reshook < 0)
514 514
 			{
515
-				$this->error = "Error in hook maildao sendMail " . $reshook;
516
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
515
+				$this->error = "Error in hook maildao sendMail ".$reshook;
516
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
517 517
 
518 518
 				return $reshook;
519 519
 			}
@@ -523,52 +523,52 @@  discard block
 block discarded – undo
523 523
 			}
524 524
 
525 525
 			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
526
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
527 527
 			$tmparray1 = explode(',', $this->addr_to);
528 528
 			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529 529
 			{
530 530
 				$this->error = 'Too much recipients in to:';
531
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
531
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
532 532
 				return false;
533 533
 			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
534
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
535 535
 			$tmparray2 = explode(',', $this->addr_cc);
536 536
 			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537 537
 			{
538 538
 				$this->error = 'Too much recipients in cc:';
539
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
539
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
540 540
 				return false;
541 541
 			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
542
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
543 543
 			$tmparray3 = explode(',', $this->addr_bcc);
544 544
 			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545 545
 			{
546 546
 				$this->error = 'Too much recipients in bcc:';
547
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
547
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
548 548
 				return false;
549 549
 			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
551
-			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
550
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
551
+			if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552 552
 			{
553 553
 				$this->error = 'Too much recipients in to:, cc:, bcc:';
554
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
554
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
555 555
 				return false;
556 556
 			}
557 557
 
558
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
559
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
560
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
561
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
562
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
563
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
558
+			$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
559
+			$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT';
560
+			$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID';
561
+			$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW';
562
+			$keyfortls       = 'MAIN_MAIL_EMAIL_TLS';
563
+			$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS';
564 564
 			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
565 565
 			{
566
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
567
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
568
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
569
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
570
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
571
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
566
+				$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING';
567
+				$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT_EMAILING';
568
+				$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID_EMAILING';
569
+				$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW_EMAILING';
570
+				$keyfortls       = 'MAIN_MAIL_EMAIL_TLS_EMAILING';
571
+				$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
572 572
 			}
573 573
 
574 574
 			if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO))
@@ -591,68 +591,68 @@  discard block
 block discarded – undo
591 591
 				if (isset($_SERVER["WINDIR"]))
592 592
 				{
593 593
 					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
594
-					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
594
+					@ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
595 595
 				}
596 596
 
597 597
 				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
598
+				if (!empty($conf->global->$keyforsmtpserver)) ini_set('SMTP', $conf->global->$keyforsmtpserver);
599
+				if (!empty($conf->global->$keyforsmtpport))   ini_set('smtp_port', $conf->global->$keyforsmtpport);
600 600
 
601
-				$res=true;
602
-				if ($res && ! $this->subject)
601
+				$res = true;
602
+				if ($res && !$this->subject)
603 603
 				{
604
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
604
+					$this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
605 605
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
606
-					$res=false;
606
+					$res = false;
607 607
 				}
608
-				$dest=$this->getValidAddress($this->addr_to,2);
609
-				if ($res && ! $dest)
608
+				$dest = $this->getValidAddress($this->addr_to, 2);
609
+				if ($res && !$dest)
610 610
 				{
611
-					$this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
611
+					$this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
612 612
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
613
-					$res=false;
613
+					$res = false;
614 614
 				}
615 615
 
616 616
 				if ($res)
617 617
 				{
618
-					$additionnalparam = '';	// By default
619
-					if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
618
+					$additionnalparam = ''; // By default
619
+					if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
620 620
 					{
621 621
 						// le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
622 622
 						// Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
623 623
 						// Having this variable defined may create problems with some sendmail (option -f refused)
624 624
 						// Having this variable not defined may create problems with some other sendmail (option -f required)
625
-						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
625
+						$additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : ''));
626 626
 					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
627
+					if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628 628
 					{
629
-						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
629
+						$additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
630 630
 					}
631 631
 
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
632
+					if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params
633 633
 
634 634
 					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635 635
 
636
-					$this->message=stripslashes($this->message);
636
+					$this->message = stripslashes($this->message);
637 637
 
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
638
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
639 639
 
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
640
+					if (!empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641 641
 					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
642 642
 
643
-					if (! $res)
643
+					if (!$res)
644 644
 					{
645 645
 						$langs->load("errors");
646
-						$this->error="Failed to send mail with php mail";
647
-						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
650
-						if (! $linuxlike)
646
+						$this->error = "Failed to send mail with php mail";
647
+						$linuxlike = 1;
648
+						if (preg_match('/^win/i', PHP_OS)) $linuxlike = 0;
649
+						if (preg_match('/^mac/i', PHP_OS)) $linuxlike = 0;
650
+						if (!$linuxlike)
651 651
 						{
652
-							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
652
+							$this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
653 653
 						}
654
-						$this->error.=".<br>";
655
-						$this->error.=$langs->trans("ErrorPhpMailDelivery");
654
+						$this->error .= ".<br>";
655
+						$this->error .= $langs->trans("ErrorPhpMailDelivery");
656 656
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657 657
 					}
658 658
 					else
@@ -667,86 +667,86 @@  discard block
 block discarded – undo
667 667
 				}
668 668
 
669 669
 				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
670
+				if (!empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
+				if (!empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672 672
 			}
673 673
 			else if ($this->sendmode == 'smtps')
674 674
 			{
675
-				if (! is_object($this->smtps))
675
+				if (!is_object($this->smtps))
676 676
 				{
677
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
677
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
678 678
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
679 679
 					return false;
680 680
 				}
681 681
 
682 682
 				// Use SMTPS library
683 683
 				// ------------------------------------------
684
-				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
684
+				$this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
685 685
 
686 686
 				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
687
+				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP');
688
+				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport = ini_get('smtp_port');
689 689
 
690 690
 				// If we use SSL/TLS
691
-				$server=$conf->global->$keyforsmtpserver;
692
-				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
695
-				$server=($secure?$secure.'://':'').$server;
691
+				$server = $conf->global->$keyforsmtpserver;
692
+				$secure = '';
693
+				if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl';
694
+				if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls';
695
+				$server = ($secure ? $secure.'://' : '').$server;
696 696
 
697
-				$port=$conf->global->$keyforsmtpport;
697
+				$port = $conf->global->$keyforsmtpport;
698 698
 
699 699
 				$this->smtps->setHost($server);
700 700
 				$this->smtps->setPort($port); // 25, 465...;
701 701
 
702
-				$loginid=''; $loginpass='';
703
-				if (! empty($conf->global->$keyforsmtpid))
702
+				$loginid = ''; $loginpass = '';
703
+				if (!empty($conf->global->$keyforsmtpid))
704 704
 				{
705 705
 					$loginid = $conf->global->$keyforsmtpid;
706 706
 					$this->smtps->setID($loginid);
707 707
 				}
708
-				if (! empty($conf->global->$keyforsmtppw))
708
+				if (!empty($conf->global->$keyforsmtppw))
709 709
 				{
710 710
 					$loginpass = $conf->global->$keyforsmtppw;
711 711
 					$this->smtps->setPW($loginpass);
712 712
 				}
713 713
 
714
-				$res=true;
715
-				$from=$this->smtps->getFrom('org');
716
-				if ($res && ! $from)
714
+				$res = true;
715
+				$from = $this->smtps->getFrom('org');
716
+				if ($res && !$from)
717 717
 				{
718
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
718
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Sender address '$from' invalid";
719 719
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
720
-					$res=false;
720
+					$res = false;
721 721
 				}
722
-				$dest=$this->smtps->getTo();
723
-				if ($res && ! $dest)
722
+				$dest = $this->smtps->getTo();
723
+				if ($res && !$dest)
724 724
 				{
725
-					$this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
725
+					$this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Recipient address '$dest' invalid";
726 726
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
727
-					$res=false;
727
+					$res = false;
728 728
 				}
729 729
 
730 730
 				if ($res)
731 731
 				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
732
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
733 733
 
734
-					$result=$this->smtps->sendMsg();
734
+					$result = $this->smtps->sendMsg();
735 735
 					//print $result;
736 736
 
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
737
+					if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
738 738
 
739
-					$result=$this->smtps->getErrors();
739
+					$result = $this->smtps->getErrors();
740 740
 					if (empty($this->error) && empty($result))
741 741
 					{
742 742
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743
-						$res=true;
743
+						$res = true;
744 744
 					}
745 745
 					else
746 746
 					{
747
-						if (empty($this->error)) $this->error=$result;
747
+						if (empty($this->error)) $this->error = $result;
748 748
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749
-						$res=false;
749
+						$res = false;
750 750
 					}
751 751
 				}
752 752
 			}
@@ -757,19 +757,19 @@  discard block
 block discarded – undo
757 757
 				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758 758
 
759 759
 				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
760
+				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver = ini_get('SMTP');
761
+				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport = ini_get('smtp_port');
762 762
 
763 763
 				// If we use SSL/TLS
764 764
 				$server = $conf->global->$keyforsmtpserver;
765 765
 				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
766
+				if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure = 'ssl';
767
+				if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure = 'tls';
768 768
 
769 769
 				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770 770
 
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
771
+				if (!empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
+				if (!empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
773 773
 				//$smtps->_msgReplyTo  = '[email protected]';
774 774
 
775 775
 				// Create the Mailer using your created Transport
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
                     $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
785 785
                 }
786 786
 
787
-                if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
787
+                if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
788 788
 					// To use the ArrayLogger
789 789
 					$this->logger = new Swift_Plugins_Loggers_ArrayLogger();
790 790
 					// Or to use the Echo Logger
@@ -795,14 +795,14 @@  discard block
 block discarded – undo
795 795
 				try {
796 796
 					$result = $this->mailer->send($this->message);
797 797
 				} catch (Exception $e) {
798
-					$this->error =  $e->getMessage();
798
+					$this->error = $e->getMessage();
799 799
 				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
800
+				if (!empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
801 801
 
802 802
 				$res = true;
803
-				if (! empty($this->error) || ! $result) {
803
+				if (!empty($this->error) || !$result) {
804 804
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805
-					$res=false;
805
+					$res = false;
806 806
 				}
807 807
 				else
808 808
 				{
@@ -817,23 +817,23 @@  discard block
 block discarded – undo
817 817
 				return 'Bad value for sendmode';
818 818
 			}
819 819
 
820
-			$parameters=array(); $action='';
820
+			$parameters = array(); $action = '';
821 821
 			$reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
822 822
 			if ($reshook < 0)
823 823
 			{
824
-				$this->error = "Error in hook maildao sendMailAfter " . $reshook;
825
-				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
824
+				$this->error = "Error in hook maildao sendMailAfter ".$reshook;
825
+				dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
826 826
 
827 827
 				return $reshook;
828 828
 			}
829 829
 		}
830 830
 		else
831 831
 		{
832
-			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
832
+			$this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833 833
 			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
834 834
 		}
835 835
 
836
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
836
+		error_reporting($errorlevel); // Reactive niveau erreur origine
837 837
 
838 838
 		return $res;
839 839
 	}
@@ -860,17 +860,17 @@  discard block
 block discarded – undo
860 860
 	function _encode_file($sourcefile)
861 861
 	{
862 862
         // phpcs:enable
863
-		$newsourcefile=dol_osencode($sourcefile);
863
+		$newsourcefile = dol_osencode($sourcefile);
864 864
 
865 865
 		if (is_readable($newsourcefile))
866 866
 		{
867
-			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868
-			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
867
+			$contents = file_get_contents($newsourcefile); // Need PHP 4.3
868
+			$encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
869 869
 			return $encoded;
870 870
 		}
871 871
 		else
872 872
 		{
873
-			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
873
+			$this->error = "Error: Can't read file '".$sourcefile."' into _encode_file";
874 874
 			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
875 875
 			return -1;
876 876
 		}
@@ -888,30 +888,30 @@  discard block
 block discarded – undo
888 888
 	function dump_mail()
889 889
 	{
890 890
         // phpcs:enable
891
-		global $conf,$dolibarr_main_data_root;
891
+		global $conf, $dolibarr_main_data_root;
892 892
 
893 893
 		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
894 894
 		{
895
-			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
896
-			$fp = fopen($outputfile,"w");
895
+			$outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
896
+			$fp = fopen($outputfile, "w");
897 897
 
898 898
 			if ($this->sendmode == 'mail')
899 899
 			{
900 900
 				fputs($fp, $this->headers);
901
-				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
901
+				fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log
902 902
 				fputs($fp, $this->message);
903 903
 			}
904 904
 			elseif ($this->sendmode == 'smtps')
905 905
 			{
906
-				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
906
+				fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907 907
 			}
908 908
 			elseif ($this->sendmode == 'swiftmailer')
909 909
 			{
910
-				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
910
+				fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911 911
 			}
912 912
 
913 913
 			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
914
+			if (!empty($conf->global->MAIN_UMASK))
915 915
 				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
916 916
 		}
917 917
 	}
@@ -925,15 +925,15 @@  discard block
 block discarded – undo
925 925
 	 */
926 926
 	function checkIfHTML($msg)
927 927
 	{
928
-		if (!preg_match('/^[\s\t]*<html/i',$msg))
928
+		if (!preg_match('/^[\s\t]*<html/i', $msg))
929 929
 		{
930 930
 			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
932
-			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
934
-			$out.= ">";
935
-			$out.= $msg;
936
-			$out.= "</body></html>";
931
+			if (!empty($this->styleCSS)) $out .= $this->styleCSS;
932
+			$out .= "</head><body";
933
+			if (!empty($this->bodyCSS)) $out .= $this->bodyCSS;
934
+			$out .= ">";
935
+			$out .= $msg;
936
+			$out .= "</body></html>";
937 937
 		}
938 938
 		else
939 939
 		{
@@ -950,24 +950,24 @@  discard block
 block discarded – undo
950 950
 	 */
951 951
 	function buildCSS()
952 952
 	{
953
-		if (! empty($this->css))
953
+		if (!empty($this->css))
954 954
 		{
955 955
 			// Style CSS
956 956
 			$this->styleCSS = '<style type="text/css">';
957
-			$this->styleCSS.= 'body {';
957
+			$this->styleCSS .= 'body {';
958 958
 
959 959
 			if ($this->css['bgcolor'])
960 960
 			{
961
-				$this->styleCSS.= '  background-color: '.$this->css['bgcolor'].';';
962
-				$this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
961
+				$this->styleCSS .= '  background-color: '.$this->css['bgcolor'].';';
962
+				$this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
963 963
 			}
964 964
 			if ($this->css['bgimage'])
965 965
 			{
966 966
 				// TODO recuperer cid
967
-				$this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
967
+				$this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
968 968
 			}
969
-			$this->styleCSS.= '}';
970
-			$this->styleCSS.= '</style>';
969
+			$this->styleCSS .= '}';
970
+			$this->styleCSS .= '</style>';
971 971
 		}
972 972
 	}
973 973
 
@@ -988,48 +988,48 @@  discard block
 block discarded – undo
988 988
 
989 989
 		// Sender
990 990
 		//$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
991
-		$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
992
-		if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
991
+		$out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
992
+		if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
993 993
 		{
994
-			$out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
994
+			$out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
995 995
 		}
996 996
 		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997
-		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
997
+		$out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
998
+		if (isset($this->reply_to) && $this->reply_to)  $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
999
+		if (isset($this->errors_to) && $this->errors_to) $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1000 1000
 
1001 1001
 		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1002
+		if (isset($this->addr_cc) && $this->addr_cc)   $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1003
+		if (isset($this->addr_bcc) && $this->addr_bcc)  $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1004
 
1005 1005
 		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1006
+		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1007 1007
 
1008 1008
 		//$out.= "X-Priority: 3".$this->eol2;
1009 1009
 
1010
-		$out.= 'Date: ' . date("r") . $this->eol2;
1010
+		$out .= 'Date: '.date("r").$this->eol2;
1011 1011
 
1012 1012
 		$trackid = $this->trackid;
1013 1013
 		if ($trackid)
1014 1014
 		{
1015 1015
 			// References is kept in response and Message-ID is returned into In-Reply-To:
1016
-			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017
-			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018
-			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1016
+			$out .= 'Message-ID: <'.time().'.phpmail-dolibarr-'.$trackid.'@'.$host.">".$this->eol2; // Uppercase seems replaced by phpmail
1017
+			$out .= 'References: <'.time().'.phpmail-dolibarr-'.$trackid.'@'.$host.">".$this->eol2;
1018
+			$out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
1019 1019
 		}
1020 1020
 		else
1021 1021
 		{
1022
-			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1022
+			$out .= 'Message-ID: <'.time().'.phpmail@'.$host.">".$this->eol2;
1023 1023
 		}
1024 1024
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1026
-		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027
-		$out.= "Mime-Version: 1.0".$this->eol2;
1025
+		if (!empty($_SERVER['REMOTE_ADDR'])) $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
1026
+		$out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
1027
+		$out .= "Mime-Version: 1.0".$this->eol2;
1028 1028
 
1029 1029
 		//$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1030 1030
 
1031
-		$out.= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
-		$out.= "Content-Transfer-Encoding: 8bit".$this->eol2;		// TODO Seems to be ignored. Header is 7bit once received.
1031
+		$out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1032
+		$out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
1033 1033
 
1034 1034
 		dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1035 1035
 		return $out;
@@ -1047,18 +1047,18 @@  discard block
 block discarded – undo
1047 1047
 	function write_mimeheaders($filename_list, $mimefilename_list)
1048 1048
 	{
1049 1049
         // phpcs:enable
1050
-		$mimedone=0;
1050
+		$mimedone = 0;
1051 1051
 		$out = "";
1052 1052
 
1053 1053
 		if (is_array($filename_list))
1054 1054
 		{
1055
-			$filename_list_size=count($filename_list);
1056
-			for($i=0;$i < $filename_list_size;$i++)
1055
+			$filename_list_size = count($filename_list);
1056
+			for ($i = 0; $i < $filename_list_size; $i++)
1057 1057
 			{
1058 1058
 				if ($filename_list[$i])
1059 1059
 				{
1060 1060
 					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1061
-					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1061
+					$out .= "X-attachments: $filename_list[$i]".$this->eol2;
1062 1062
 				}
1063 1063
 			}
1064 1064
 		}
@@ -1079,31 +1079,31 @@  discard block
 block discarded – undo
1079 1079
         // phpcs:enable
1080 1080
 		global $conf;
1081 1081
 
1082
-		$out='';
1082
+		$out = '';
1083 1083
 
1084
-		$out.= "--" . $this->mixed_boundary . $this->eol;
1084
+		$out .= "--".$this->mixed_boundary.$this->eol;
1085 1085
 
1086 1086
 		if ($this->atleastoneimage)
1087 1087
 		{
1088
-			$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
-			$out.= $this->eol;
1090
-			$out.= "--" . $this->alternative_boundary . $this->eol;
1088
+			$out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1089
+			$out .= $this->eol;
1090
+			$out .= "--".$this->alternative_boundary.$this->eol;
1091 1091
 		}
1092 1092
 
1093 1093
 		// Make RFC821 Compliant, replace bare linefeeds
1094
-		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);	// PCRE modifier /s means new lines are common chars
1095
-		if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1094
+		$strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
1095
+		if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
1096 1096
 		{
1097
-			$strContent = preg_replace("/\r\n/si", "\n", $strContent);	// PCRE modifier /s means new lines are common chars
1097
+			$strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
1098 1098
 		}
1099 1099
 
1100 1100
 		$strContentAltText = '';
1101 1101
 		if ($this->msgishtml)
1102 1102
 		{
1103 1103
 			// Similar code to forge a text from html is also in CMailFile.class.php
1104
-			$strContentAltText = preg_replace("/<br\s*[^>]*>/"," ", $strContent);
1104
+			$strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1105 1105
 			$strContentAltText = html_entity_decode(strip_tags($strContentAltText));
1106
-			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));
1106
+			$strContentAltText = rtrim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n"));
1107 1107
 
1108 1108
 			// Check if html header already in message, if not complete the message
1109 1109
 			$strContent = $this->checkIfHTML($strContent);
@@ -1112,57 +1112,57 @@  discard block
 block discarded – undo
1112 1112
 		// Make RFC2045 Compliant, split lines
1113 1113
 		//$strContent = rtrim(chunk_split($strContent));    // Function chunck_split seems ko if not used on a base64 content
1114 1114
 		// TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1115
-		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)?"\r\n":"\n"));   // TODO Using this method creates unexpected line break on text/plain content.
1115
+		$strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content.
1116 1116
 
1117 1117
 		if ($this->msgishtml)
1118 1118
 		{
1119 1119
 			if ($this->atleastoneimage)
1120 1120
 			{
1121
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1121
+				$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1122 1122
 				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1123
-				$out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
1124
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1125
-				$out.= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
-				$out.= $this->eol;
1127
-				$out.= "--" . $this->related_boundary . $this->eol;
1123
+				$out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
1124
+				$out .= "--".$this->alternative_boundary.$this->eol;
1125
+				$out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1126
+				$out .= $this->eol;
1127
+				$out .= "--".$this->related_boundary.$this->eol;
1128 1128
 			}
1129 1129
 
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1130
+			if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1131 1131
 			{
1132
-				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
-				$out.= $this->eol;
1134
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1135
-				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1132
+				$out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1133
+				$out .= $this->eol;
1134
+				$out .= "--".$this->alternative_boundary.$this->eol;
1135
+				$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1136 1136
 				//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1137
-				$out.= $this->eol.$strContentAltText.$this->eol;
1138
-				$out.= "--" . $this->alternative_boundary . $this->eol;
1137
+				$out .= $this->eol.$strContentAltText.$this->eol;
1138
+				$out .= "--".$this->alternative_boundary.$this->eol;
1139 1139
 			}
1140 1140
 
1141
-			$out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1141
+			$out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1142 1142
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143
-			$out.= $this->eol.$strContent.$this->eol;
1143
+			$out .= $this->eol.$strContent.$this->eol;
1144 1144
 
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1145
+			if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1146 1146
 			{
1147
-				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1147
+				$out .= "--".$this->alternative_boundary."--".$this->eol;
1148 1148
 			}
1149 1149
 		}
1150 1150
 		else
1151 1151
 		{
1152
-			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1152
+			$out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153 1153
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1154
-			$out.= $this->eol.$strContent.$this->eol;
1154
+			$out .= $this->eol.$strContent.$this->eol;
1155 1155
 		}
1156 1156
 
1157
-		$out.= $this->eol;
1157
+		$out .= $this->eol;
1158 1158
 
1159 1159
 		// Encode images
1160 1160
 		if ($this->atleastoneimage)
1161 1161
 		{
1162 1162
 			$out .= $this->write_images($this->images_encoded);
1163 1163
 			// always end related and end alternative after inline images
1164
-			$out .= "--" . $this->related_boundary . "--" . $this->eol;
1165
-			$out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
1164
+			$out .= "--".$this->related_boundary."--".$this->eol;
1165
+			$out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
1166 1166
 			$out .= $this->eol;
1167 1167
 		}
1168 1168
 
@@ -1178,13 +1178,13 @@  discard block
 block discarded – undo
1178 1178
 	 * @param 	array	$mimefilename_list	Tableau
1179 1179
 	 * @return	string						Chaine fichiers encodes
1180 1180
 	 */
1181
-	function write_files($filename_list,$mimetype_list,$mimefilename_list)
1181
+	function write_files($filename_list, $mimetype_list, $mimefilename_list)
1182 1182
 	{
1183 1183
         // phpcs:enable
1184 1184
 		$out = '';
1185 1185
 
1186
-		$filename_list_size=count($filename_list);
1187
-		for($i=0;$i < $filename_list_size;$i++)
1186
+		$filename_list_size = count($filename_list);
1187
+		for ($i = 0; $i < $filename_list_size; $i++)
1188 1188
 		{
1189 1189
 			if ($filename_list[$i])
1190 1190
 			{
@@ -1193,18 +1193,18 @@  discard block
 block discarded – undo
1193 1193
 				if ($encoded >= 0)
1194 1194
 				{
1195 1195
 					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1196
-					if (! $mimetype_list[$i]) {
1196
+					if (!$mimetype_list[$i]) {
1197 1197
 						$mimetype_list[$i] = "application/octet-stream";
1198 1198
 					}
1199 1199
 
1200
-					$out.= "--" . $this->mixed_boundary . $this->eol;
1201
-					$out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
-					$out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
1203
-					$out.= "Content-Transfer-Encoding: base64".$this->eol;
1204
-					$out.= "Content-Description: ".$filename_list[$i].$this->eol;
1205
-					$out.= $this->eol;
1206
-					$out.= $encoded;
1207
-					$out.= $this->eol;
1200
+					$out .= "--".$this->mixed_boundary.$this->eol;
1201
+					$out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1202
+					$out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
1203
+					$out .= "Content-Transfer-Encoding: base64".$this->eol;
1204
+					$out .= "Content-Description: ".$filename_list[$i].$this->eol;
1205
+					$out .= $this->eol;
1206
+					$out .= $encoded;
1207
+					$out .= $this->eol;
1208 1208
 					//$out.= $this->eol;
1209 1209
 				}
1210 1210
 				else
@@ -1236,14 +1236,14 @@  discard block
 block discarded – undo
1236 1236
 			{
1237 1237
 				dol_syslog("CMailFile::write_images: ".$img["name"]);
1238 1238
 
1239
-				$out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
1240
-				$out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
1241
-				$out.= "Content-Transfer-Encoding: base64".$this->eol;
1242
-				$out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
-				$out.= "Content-ID: <".$img["cid"].">".$this->eol;
1244
-				$out.= $this->eol;
1245
-				$out.= $img["image_encoded"];
1246
-				$out.= $this->eol;
1239
+				$out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
1240
+				$out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
1241
+				$out .= "Content-Transfer-Encoding: base64".$this->eol;
1242
+				$out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1243
+				$out .= "Content-ID: <".$img["cid"].">".$this->eol;
1244
+				$out .= $this->eol;
1245
+				$out .= $img["image_encoded"];
1246
+				$out .= $this->eol;
1247 1247
 			}
1248 1248
 		}
1249 1249
 
@@ -1259,44 +1259,44 @@  discard block
 block discarded – undo
1259 1259
 	 * @param 	int			$port		Example: 25, 465
1260 1260
 	 * @return	int						Socket id if ok, 0 if KO
1261 1261
 	 */
1262
-	function check_server_port($host,$port)
1262
+	function check_server_port($host, $port)
1263 1263
 	{
1264 1264
         // phpcs:enable
1265 1265
 		global $conf;
1266 1266
 
1267
-		$_retVal=0;
1268
-		$timeout=5;	// Timeout in seconds
1267
+		$_retVal = 0;
1268
+		$timeout = 5; // Timeout in seconds
1269 1269
 
1270 1270
 		if (function_exists('fsockopen'))
1271 1271
 		{
1272
-			$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER';
1273
-			$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT';
1274
-			$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID';
1275
-			$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW';
1276
-			$keyfortls       ='MAIN_MAIL_EMAIL_TLS';
1277
-			$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS';
1272
+			$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
1273
+			$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT';
1274
+			$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID';
1275
+			$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW';
1276
+			$keyfortls       = 'MAIN_MAIL_EMAIL_TLS';
1277
+			$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS';
1278 1278
 			if ($this->sendcontext == 'emailing' && !empty($conf->global->MAIN_MAIL_SENDMODE_EMAILING) && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default')
1279 1279
 			{
1280
-				$keyforsmtpserver='MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
-				$keyforsmtpport  ='MAIN_MAIL_SMTP_PORT_EMAILING';
1282
-				$keyforsmtpid    ='MAIN_MAIL_SMTPS_ID_EMAILING';
1283
-				$keyforsmtppw    ='MAIN_MAIL_SMTPS_PW_EMAILING';
1284
-				$keyfortls       ='MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
-				$keyforstarttls  ='MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1280
+				$keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_EMAILING';
1281
+				$keyforsmtpport  = 'MAIN_MAIL_SMTP_PORT_EMAILING';
1282
+				$keyforsmtpid    = 'MAIN_MAIL_SMTPS_ID_EMAILING';
1283
+				$keyforsmtppw    = 'MAIN_MAIL_SMTPS_PW_EMAILING';
1284
+				$keyfortls       = 'MAIN_MAIL_EMAIL_TLS_EMAILING';
1285
+				$keyforstarttls  = 'MAIN_MAIL_EMAIL_STARTTLS_EMAILING';
1286 1286
 			}
1287 1287
 
1288 1288
 			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1289
+			if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host = 'ssl://'.$host;
1290 1290
 			// tls smtp start with no encryption
1291 1291
 			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292 1292
 
1293 1293
 			dol_syslog("Try socket connection to host=".$host." port=".$port);
1294 1294
 			//See if we can connect to the SMTP server
1295 1295
 			if ($socket = @fsockopen(
1296
-					$host,       // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
-					$port,       // which Port number to use
1298
-					$errno,      // actual system level error
1299
-					$errstr,     // and any text that goes with the error
1296
+					$host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1297
+					$port, // which Port number to use
1298
+					$errno, // actual system level error
1299
+					$errstr, // and any text that goes with the error
1300 1300
 					$timeout
1301 1301
 			))  // timeout for reading/writing data over the socket
1302 1302
 			{
@@ -1306,11 +1306,11 @@  discard block
 block discarded – undo
1306 1306
 				dol_syslog("Now we wait for answer 220");
1307 1307
 
1308 1308
 				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1309
+				if ($_retVal = $this->server_parse($socket, "220")) $_retVal = $socket;
1310 1310
 			}
1311 1311
 			else
1312 1312
 			{
1313
-				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1313
+				$this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr);
1314 1314
 			}
1315 1315
 		}
1316 1316
 		return $_retVal;
@@ -1328,21 +1328,21 @@  discard block
 block discarded – undo
1328 1328
 	function server_parse($socket, $response)
1329 1329
 	{
1330 1330
         // phpcs:enable
1331
-		$_retVal = true;	// Indicates if Object was created or not
1331
+		$_retVal = true; // Indicates if Object was created or not
1332 1332
 		$server_response = '';
1333 1333
 
1334
-		while (substr($server_response,3,1) != ' ')
1334
+		while (substr($server_response, 3, 1) != ' ')
1335 1335
 		{
1336
-			if (! ($server_response = fgets($socket, 256)) )
1336
+			if (!($server_response = fgets($socket, 256)))
1337 1337
 			{
1338
-				$this->error="Couldn't get mail server response codes";
1338
+				$this->error = "Couldn't get mail server response codes";
1339 1339
 				return false;
1340 1340
 			}
1341 1341
 		}
1342 1342
 
1343
-		if( !( substr($server_response, 0, 3) == $response ) )
1343
+		if (!(substr($server_response, 0, 3) == $response))
1344 1344
 		{
1345
-			$this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
1345
+			$this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
1346 1346
 			$_retVal = false;
1347 1347
 		}
1348 1348
 
@@ -1361,22 +1361,22 @@  discard block
 block discarded – undo
1361 1361
 		$extensions = array_keys($this->image_types);
1362 1362
 
1363 1363
 		$matches = array();
1364
-		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches);  // If "xxx.ext" or 'xxx.ext' found
1364
+		preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
1365 1365
 
1366
-		if (! empty($matches))
1366
+		if (!empty($matches))
1367 1367
 		{
1368
-			$i=0;
1368
+			$i = 0;
1369 1369
 			foreach ($matches[1] as $full)
1370 1370
 			{
1371 1371
 
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1372
+				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs))   // If xxx is 'file=aaa'
1373 1373
 				{
1374 1374
 					$img = $regs[1];
1375 1375
 
1376 1376
 					if (file_exists($images_dir.'/'.$img))
1377 1377
 					{
1378 1378
 						// Image path in src
1379
-						$src = preg_quote($full,'/');
1379
+						$src = preg_quote($full, '/');
1380 1380
 
1381 1381
 						// Image full path
1382 1382
 						$this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
@@ -1387,12 +1387,12 @@  discard block
 block discarded – undo
1387 1387
 						// Content type
1388 1388
 						if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
1389 1389
 						{
1390
-							$ext=strtolower($reg[1]);
1390
+							$ext = strtolower($reg[1]);
1391 1391
 							$this->html_images[$i]["content_type"] = $this->image_types[$ext];
1392 1392
 						}
1393 1393
 
1394 1394
 						// cid
1395
-						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3);	// Force md5 hash (does not contains special chars)
1395
+						$this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars)
1396 1396
 						$this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1397 1397
 					}
1398 1398
 					$i++;
@@ -1403,20 +1403,20 @@  discard block
 block discarded – undo
1403 1403
 			{
1404 1404
 				$inline = array();
1405 1405
 
1406
-				$i=0;
1406
+				$i = 0;
1407 1407
 
1408 1408
 				foreach ($this->html_images as $img)
1409 1409
 				{
1410 1410
 					$fullpath = $images_dir.'/'.$img["name"];
1411 1411
 
1412 1412
 					// If duplicate images are embedded, they may show up as attachments, so remove them.
1413
-					if (!in_array($fullpath,$inline))
1413
+					if (!in_array($fullpath, $inline))
1414 1414
 					{
1415 1415
 						// Read image file
1416 1416
 						if ($image = file_get_contents($fullpath))
1417 1417
 						{
1418 1418
 							// On garde que le nom de l'image
1419
-							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
1419
+							preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
1420 1420
 							$imgName = $regs[1];
1421 1421
 
1422 1422
 							$this->images_encoded[$i]['name'] = $imgName;
@@ -1457,19 +1457,19 @@  discard block
 block discarded – undo
1457 1457
 	 *										     If format 3: '<[email protected]>' or '"John Doe" <[email protected]>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <[email protected]>'
1458 1458
 	 *                                           If format 4: 'John Doe' or '[email protected]' if no label exists
1459 1459
 	 */
1460
-	static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
1460
+	static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
1461 1461
 	{
1462 1462
 		global $conf;
1463 1463
 
1464
-		$ret='';
1464
+		$ret = '';
1465 1465
 
1466
-		$arrayaddress=explode(',',$address);
1466
+		$arrayaddress = explode(',', $address);
1467 1467
 
1468 1468
 		// Boucle sur chaque composant de l'adresse
1469
-		$i=0;
1470
-		foreach($arrayaddress as $val)
1469
+		$i = 0;
1470
+		foreach ($arrayaddress as $val)
1471 1471
 		{
1472
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1472
+			if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs))
1473 1473
 			{
1474 1474
 				$name  = trim($regs[1]);
1475 1475
 				$email = trim($regs[2]);
@@ -1484,32 +1484,32 @@  discard block
 block discarded – undo
1484 1484
 			{
1485 1485
 				$i++;
1486 1486
 
1487
-				$newemail='';
1487
+				$newemail = '';
1488 1488
 				if ($format == 4)
1489 1489
 				{
1490
-					$newemail = $name?$name:$email;
1490
+					$newemail = $name ? $name : $email;
1491 1491
 				}
1492 1492
 				if ($format == 2)
1493 1493
 				{
1494
-					$newemail=$email;
1494
+					$newemail = $email;
1495 1495
 				}
1496 1496
 				if ($format == 1 || $format == 3)
1497 1497
 				{
1498
-					$newemail='<'.$email.'>';
1498
+					$newemail = '<'.$email.'>';
1499 1499
 				}
1500 1500
 				if ($format == 0 || $format == 3)
1501 1501
 				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1502
+					if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail = '<'.$email.'>';
1503
+					elseif (!$name) $newemail = '<'.$email.'>';
1504
+					else $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>';
1505 1505
 				}
1506 1506
 
1507
-				$ret=($ret ? $ret.',' : '').$newemail;
1507
+				$ret = ($ret ? $ret.',' : '').$newemail;
1508 1508
 
1509 1509
 				// Stop if we have too much records
1510 1510
 				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511 1511
 				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1512
+					if (count($arrayaddress) > $maxnumberofemail) $ret .= '...';
1513 1513
 					break;
1514 1514
 				}
1515 1515
 			}
@@ -1528,14 +1528,14 @@  discard block
 block discarded – undo
1528 1528
 	{
1529 1529
 		global $conf;
1530 1530
 
1531
-		$ret=array();
1531
+		$ret = array();
1532 1532
 
1533
-		$arrayaddress=explode(',',$address);
1533
+		$arrayaddress = explode(',', $address);
1534 1534
 
1535 1535
 		// Boucle sur chaque composant de l'adresse
1536
-		foreach($arrayaddress as $val)
1536
+		foreach ($arrayaddress as $val)
1537 1537
 		{
1538
-			if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
1538
+			if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs))
1539 1539
 			{
1540 1540
 				$name  = trim($regs[1]);
1541 1541
 				$email = trim($regs[2]);
@@ -1546,7 +1546,7 @@  discard block
 block discarded – undo
1546 1546
 				$email = trim($val);
1547 1547
 			}
1548 1548
 
1549
-			$ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
1549
+			$ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name : null;
1550 1550
 		}
1551 1551
 
1552 1552
 		return $ret;
Please login to merge, or discard this patch.
Braces   +221 added lines, -113 removed lines patch added patch discarded remove patch
@@ -125,7 +125,9 @@  discard block
 block discarded – undo
125 125
 
126 126
 		$this->sendcontext = $sendcontext;
127 127
 
128
-		if (empty($replyto)) $replyto=$from;
128
+		if (empty($replyto)) {
129
+		    $replyto=$from;
130
+		}
129 131
 
130 132
 		// Define this->sendmode
131 133
 		$this->sendmode = '';
@@ -133,8 +135,12 @@  discard block
 block discarded – undo
133 135
 		{
134 136
 			$this->sendmode = $conf->global->MAIN_MAIL_SENDMODE_EMAILING;
135 137
 		}
136
-		if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
137
-		if (empty($this->sendmode)) $this->sendmode='mail';
138
+		if (empty($this->sendmode)) {
139
+		    $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
140
+		}
141
+		if (empty($this->sendmode)) {
142
+		    $this->sendmode='mail';
143
+		}
138 144
 
139 145
 		// We define end of line (RFC 821).
140 146
 		$this->eol="\r\n";
@@ -175,9 +181,10 @@  discard block
 block discarded – undo
175 181
 		if ($msgishtml == -1)
176 182
 		{
177 183
 			$this->msgishtml = 0;
178
-			if (dol_textishtml($msg)) $this->msgishtml = 1;
179
-		}
180
-		else
184
+			if (dol_textishtml($msg)) {
185
+			    $this->msgishtml = 1;
186
+			}
187
+		} else
181 188
 		{
182 189
 			$this->msgishtml = $msgishtml;
183 190
 		}
@@ -192,7 +199,10 @@  discard block
 block discarded – undo
192 199
 		// Replace relative /viewimage to absolute path
193 200
 		$msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT,'/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1, $nbrep);
194 201
 
195
-		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
202
+		if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
203
+		    $this->msgishtml=1;
204
+		}
205
+		// To force to send everything with content type html.
196 206
 
197 207
 		// Detect images
198 208
 		if ($this->msgishtml)
@@ -232,7 +242,9 @@  discard block
 block discarded – undo
232 242
 		}
233 243
 
234 244
 		// Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
235
-		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
245
+		if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
246
+		    $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
247
+		}
236 248
 
237 249
 		// Action according to choosed sending method
238 250
 		if ($this->sendmode == 'mail')
@@ -257,7 +269,10 @@  discard block
 block discarded – undo
257 269
 			$this->trackid = $trackid;
258 270
 
259 271
 			$smtp_headers = $this->write_smtpheaders();
260
-			if (! empty($moreinheader)) $smtp_headers.=$moreinheader;   // $moreinheader contains the \r\n
272
+			if (! empty($moreinheader)) {
273
+			    $smtp_headers.=$moreinheader;
274
+			}
275
+			// $moreinheader contains the \r\n
261 276
 
262 277
 			// Define mime_headers
263 278
 			$mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
@@ -293,8 +308,7 @@  discard block
 block discarded – undo
293 308
 			$this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
294 309
 			$this->message.= $text_body . $files_encoded;
295 310
 			$this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
296
-		}
297
-		else if ($this->sendmode == 'smtps')
311
+		} else if ($this->sendmode == 'smtps')
298 312
 		{
299 313
 			// Use SMTPS library
300 314
 			// ------------------------------------------
@@ -309,7 +323,9 @@  discard block
 block discarded – undo
309 323
 			$smtps->setTrackId($trackid);
310 324
 			$smtps->setReplyTo($this->getValidAddress($replyto,0,1));
311 325
 
312
-			if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
326
+			if (! empty($moreinheader)) {
327
+			    $smtps->setMoreInHeader($moreinheader);
328
+			}
313 329
 
314 330
 			if (! empty($this->html))
315 331
 			{
@@ -322,8 +338,11 @@  discard block
 block discarded – undo
322 338
 				$msg = $this->checkIfHTML($msg);
323 339
 			}
324 340
 
325
-			if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
326
-			else $smtps->setBodyContent($msg,'plain');
341
+			if ($this->msgishtml) {
342
+			    $smtps->setBodyContent($msg,'html');
343
+			} else {
344
+			    $smtps->setBodyContent($msg,'plain');
345
+			}
327 346
 
328 347
 			if ($this->atleastoneimage)
329 348
 			{
@@ -348,8 +367,7 @@  discard block
 block discarded – undo
348 367
 			$smtps->setDeliveryReceipt($deliveryreceipt);
349 368
 
350 369
 			$this->smtps=$smtps;
351
-		}
352
-		else if ($this->sendmode == 'swiftmailer')
370
+		} else if ($this->sendmode == 'swiftmailer')
353 371
 		{
354 372
 			// Use Swift Mailer library
355 373
 			// ------------------------------------------
@@ -474,12 +492,17 @@  discard block
 block discarded – undo
474 492
 				}
475 493
 			}
476 494
 
477
-			if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
478
-			if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
495
+			if (! empty($addr_cc)) {
496
+			    $this->message->setCc($this->getArrayAddress($addr_cc));
497
+			}
498
+			if (! empty($addr_bcc)) {
499
+			    $this->message->setBcc($this->getArrayAddress($addr_bcc));
500
+			}
479 501
 			//if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
480
-			if (isset($deliveryreceipt) && $deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
481
-		}
482
-		else
502
+			if (isset($deliveryreceipt) && $deliveryreceipt == 1) {
503
+			    $this->message->setReadReceiptTo($this->getArrayAddress($from));
504
+			}
505
+		} else
483 506
 		{
484 507
 			// Send mail method not correctly defined
485 508
 			// --------------------------------------
@@ -517,13 +540,17 @@  discard block
 block discarded – undo
517 540
 
518 541
 				return $reshook;
519 542
 			}
520
-			if ($reshook == 1)	// Hook replace standard code
543
+			if ($reshook == 1) {
544
+			    // Hook replace standard code
521 545
 			{
522 546
 				return true;
523 547
 			}
548
+			}
524 549
 
525 550
 			// Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
526
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
551
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
552
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
553
+			}
527 554
 			$tmparray1 = explode(',', $this->addr_to);
528 555
 			if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
529 556
 			{
@@ -531,7 +558,9 @@  discard block
 block discarded – undo
531 558
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
532 559
 				return false;
533 560
 			}
534
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
561
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
562
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
563
+			}
535 564
 			$tmparray2 = explode(',', $this->addr_cc);
536 565
 			if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
537 566
 			{
@@ -539,7 +568,9 @@  discard block
 block discarded – undo
539 568
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
540 569
 				return false;
541 570
 			}
542
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
571
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
572
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
573
+			}
543 574
 			$tmparray3 = explode(',', $this->addr_bcc);
544 575
 			if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
545 576
 			{
@@ -547,7 +578,9 @@  discard block
 block discarded – undo
547 578
 				dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
548 579
 				return false;
549 580
 			}
550
-			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
581
+			if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
582
+			    $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
583
+			}
551 584
 			if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
552 585
 			{
553 586
 				$this->error = 'Too much recipients in to:, cc:, bcc:';
@@ -590,13 +623,19 @@  discard block
 block discarded – undo
590 623
 				// If Windows, sendmail_from must be defined
591 624
 				if (isset($_SERVER["WINDIR"]))
592 625
 				{
593
-					if (empty($this->addr_from)) $this->addr_from = '[email protected]';
626
+					if (empty($this->addr_from)) {
627
+					    $this->addr_from = '[email protected]';
628
+					}
594 629
 					@ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
595 630
 				}
596 631
 
597 632
 				// Force parameters
598
-				if (! empty($conf->global->$keyforsmtpserver)) ini_set('SMTP',$conf->global->$keyforsmtpserver);
599
-				if (! empty($conf->global->$keyforsmtpport))   ini_set('smtp_port',$conf->global->$keyforsmtpport);
633
+				if (! empty($conf->global->$keyforsmtpserver)) {
634
+				    ini_set('SMTP',$conf->global->$keyforsmtpserver);
635
+				}
636
+				if (! empty($conf->global->$keyforsmtpport)) {
637
+				    ini_set('smtp_port',$conf->global->$keyforsmtpport);
638
+				}
600 639
 
601 640
 				$res=true;
602 641
 				if ($res && ! $this->subject)
@@ -624,29 +663,43 @@  discard block
 block discarded – undo
624 663
 						// Having this variable not defined may create problems with some other sendmail (option -f required)
625 664
 						$additionnalparam .= ($additionnalparam?' ':'').(! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f' . $this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO,2) : ($this->addr_from != '' ? '-f' . $this->getValidAddress($this->addr_from,2) : '') );
626 665
 					}
627
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
666
+					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
667
+					    // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
628 668
 					{
629 669
 						$additionnalparam .= ($additionnalparam?' ':'').'-ba';
630 670
 					}
671
+					}
631 672
 
632
-					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
673
+					if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
674
+					    $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam;
675
+					}
676
+					// Use -U to add additionnal params
633 677
 
634 678
 					dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
635 679
 
636 680
 					$this->message=stripslashes($this->message);
637 681
 
638
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
682
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
683
+					    $this->dump_mail();
684
+					}
639 685
 
640
-					if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
641
-					else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
686
+					if (! empty($additionnalparam)) {
687
+					    $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
688
+					} else {
689
+					    $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
690
+					}
642 691
 
643 692
 					if (! $res)
644 693
 					{
645 694
 						$langs->load("errors");
646 695
 						$this->error="Failed to send mail with php mail";
647 696
 						$linuxlike=1;
648
-						if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
649
-						if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
697
+						if (preg_match('/^win/i',PHP_OS)) {
698
+						    $linuxlike=0;
699
+						}
700
+						if (preg_match('/^mac/i',PHP_OS)) {
701
+						    $linuxlike=0;
702
+						}
650 703
 						if (! $linuxlike)
651 704
 						{
652 705
 							$this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port');	// This values are value used only for non linuxlike systems
@@ -654,8 +707,7 @@  discard block
 block discarded – undo
654 707
 						$this->error.=".<br>";
655 708
 						$this->error.=$langs->trans("ErrorPhpMailDelivery");
656 709
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
657
-					}
658
-					else
710
+					} else
659 711
 					{
660 712
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
661 713
 					}
@@ -667,10 +719,13 @@  discard block
 block discarded – undo
667 719
 				}
668 720
 
669 721
 				// Restore parameters
670
-				if (! empty($conf->global->$keyforsmtpserver))	ini_restore('SMTP');
671
-				if (! empty($conf->global->$keyforsmtpport)) 	ini_restore('smtp_port');
672
-			}
673
-			else if ($this->sendmode == 'smtps')
722
+				if (! empty($conf->global->$keyforsmtpserver)) {
723
+				    ini_restore('SMTP');
724
+				}
725
+				if (! empty($conf->global->$keyforsmtpport)) {
726
+				    ini_restore('smtp_port');
727
+				}
728
+			} else if ($this->sendmode == 'smtps')
674 729
 			{
675 730
 				if (! is_object($this->smtps))
676 731
 				{
@@ -684,14 +739,22 @@  discard block
 block discarded – undo
684 739
 				$this->smtps->setTransportType(0);	// Only this method is coded in SMTPs library
685 740
 
686 741
 				// Clean parameters
687
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
688
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
742
+				if (empty($conf->global->$keyforsmtpserver)) {
743
+				    $conf->global->$keyforsmtpserver=ini_get('SMTP');
744
+				}
745
+				if (empty($conf->global->$keyforsmtpport)) {
746
+				    $conf->global->$keyforsmtpport=ini_get('smtp_port');
747
+				}
689 748
 
690 749
 				// If we use SSL/TLS
691 750
 				$server=$conf->global->$keyforsmtpserver;
692 751
 				$secure='';
693
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
694
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
752
+				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
753
+				    $secure='ssl';
754
+				}
755
+				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
756
+				    $secure='tls';
757
+				}
695 758
 				$server=($secure?$secure.'://':'').$server;
696 759
 
697 760
 				$port=$conf->global->$keyforsmtpport;
@@ -729,47 +792,63 @@  discard block
 block discarded – undo
729 792
 
730 793
 				if ($res)
731 794
 				{
732
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
795
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
796
+					    $this->smtps->setDebug(true);
797
+					}
733 798
 
734 799
 					$result=$this->smtps->sendMsg();
735 800
 					//print $result;
736 801
 
737
-					if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
802
+					if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
803
+					    $this->dump_mail();
804
+					}
738 805
 
739 806
 					$result=$this->smtps->getErrors();
740 807
 					if (empty($this->error) && empty($result))
741 808
 					{
742 809
 						dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
743 810
 						$res=true;
744
-					}
745
-					else
811
+					} else
746 812
 					{
747
-						if (empty($this->error)) $this->error=$result;
813
+						if (empty($this->error)) {
814
+						    $this->error=$result;
815
+						}
748 816
 						dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
749 817
 						$res=false;
750 818
 					}
751 819
 				}
752
-			}
753
-			else if ($this->sendmode == 'swiftmailer')
820
+			} else if ($this->sendmode == 'swiftmailer')
754 821
 			{
755 822
 				// Use Swift Mailer library
756 823
 				// ------------------------------------------
757 824
 				require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
758 825
 
759 826
 				// Clean parameters
760
-				if (empty($conf->global->$keyforsmtpserver)) $conf->global->$keyforsmtpserver=ini_get('SMTP');
761
-				if (empty($conf->global->$keyforsmtpport))   $conf->global->$keyforsmtpport=ini_get('smtp_port');
827
+				if (empty($conf->global->$keyforsmtpserver)) {
828
+				    $conf->global->$keyforsmtpserver=ini_get('SMTP');
829
+				}
830
+				if (empty($conf->global->$keyforsmtpport)) {
831
+				    $conf->global->$keyforsmtpport=ini_get('smtp_port');
832
+				}
762 833
 
763 834
 				// If we use SSL/TLS
764 835
 				$server = $conf->global->$keyforsmtpserver;
765 836
 				$secure = '';
766
-				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $secure='ssl';
767
-				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) $secure='tls';
837
+				if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
838
+				    $secure='ssl';
839
+				}
840
+				if (! empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
841
+				    $secure='tls';
842
+				}
768 843
 
769 844
 				$this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
770 845
 
771
-				if (! empty($conf->global->$keyforsmtpid)) $this->transport->setUsername($conf->global->$keyforsmtpid);
772
-				if (! empty($conf->global->$keyforsmtppw)) $this->transport->setPassword($conf->global->$keyforsmtppw);
846
+				if (! empty($conf->global->$keyforsmtpid)) {
847
+				    $this->transport->setUsername($conf->global->$keyforsmtpid);
848
+				}
849
+				if (! empty($conf->global->$keyforsmtppw)) {
850
+				    $this->transport->setPassword($conf->global->$keyforsmtppw);
851
+				}
773 852
 				//$smtps->_msgReplyTo  = '[email protected]';
774 853
 
775 854
 				// Create the Mailer using your created Transport
@@ -797,19 +876,19 @@  discard block
 block discarded – undo
797 876
 				} catch (Exception $e) {
798 877
 					$this->error =  $e->getMessage();
799 878
 				}
800
-				if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
879
+				if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
880
+				    $this->dump_mail();
881
+				}
801 882
 
802 883
 				$res = true;
803 884
 				if (! empty($this->error) || ! $result) {
804 885
 					dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
805 886
 					$res=false;
806
-				}
807
-				else
887
+				} else
808 888
 				{
809 889
 					dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
810 890
 				}
811
-			}
812
-			else
891
+			} else
813 892
 			{
814 893
 				// Send mail method not correctly defined
815 894
 				// --------------------------------------
@@ -826,8 +905,7 @@  discard block
 block discarded – undo
826 905
 
827 906
 				return $reshook;
828 907
 			}
829
-		}
830
-		else
908
+		} else
831 909
 		{
832 910
 			$this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
833 911
 			dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
@@ -867,8 +945,7 @@  discard block
 block discarded – undo
867 945
 			$contents = file_get_contents($newsourcefile);	// Need PHP 4.3
868 946
 			$encoded = chunk_split(base64_encode($contents), 76, $this->eol);    // 76 max is defined into http://tools.ietf.org/html/rfc2047
869 947
 			return $encoded;
870
-		}
871
-		else
948
+		} else
872 949
 		{
873 950
 			$this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
874 951
 			dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
@@ -890,9 +967,11 @@  discard block
 block discarded – undo
890 967
         // phpcs:enable
891 968
 		global $conf,$dolibarr_main_data_root;
892 969
 
893
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
970
+		if (@is_writeable($dolibarr_main_data_root)) {
971
+		    // Avoid fatal error on fopen with open_basedir
894 972
 		{
895 973
 			$outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
974
+		}
896 975
 			$fp = fopen($outputfile,"w");
897 976
 
898 977
 			if ($this->sendmode == 'mail')
@@ -900,19 +979,18 @@  discard block
 block discarded – undo
900 979
 				fputs($fp, $this->headers);
901 980
 				fputs($fp, $this->eol);			// This eol is added by the mail function, so we add it in log
902 981
 				fputs($fp, $this->message);
903
-			}
904
-			elseif ($this->sendmode == 'smtps')
982
+			} elseif ($this->sendmode == 'smtps')
905 983
 			{
906 984
 				fputs($fp, $this->smtps->log);	// this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
907
-			}
908
-			elseif ($this->sendmode == 'swiftmailer')
985
+			} elseif ($this->sendmode == 'swiftmailer')
909 986
 			{
910 987
 				fputs($fp, $this->logger->dump());	// this->logger is filled only if MAIN_MAIL_DEBUG was set to on
911 988
 			}
912 989
 
913 990
 			fclose($fp);
914
-			if (! empty($conf->global->MAIN_UMASK))
915
-				@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
991
+			if (! empty($conf->global->MAIN_UMASK)) {
992
+							@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
993
+			}
916 994
 		}
917 995
 	}
918 996
 
@@ -928,14 +1006,17 @@  discard block
 block discarded – undo
928 1006
 		if (!preg_match('/^[\s\t]*<html/i',$msg))
929 1007
 		{
930 1008
 			$out = "<html><head><title></title>";
931
-			if (!empty($this->styleCSS)) $out.= $this->styleCSS;
1009
+			if (!empty($this->styleCSS)) {
1010
+			    $out.= $this->styleCSS;
1011
+			}
932 1012
 			$out.= "</head><body";
933
-			if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
1013
+			if (!empty($this->bodyCSS)) {
1014
+			    $out.= $this->bodyCSS;
1015
+			}
934 1016
 			$out.= ">";
935 1017
 			$out.= $msg;
936 1018
 			$out.= "</body></html>";
937
-		}
938
-		else
1019
+		} else
939 1020
 		{
940 1021
 			$out = $msg;
941 1022
 		}
@@ -995,15 +1076,26 @@  discard block
 block discarded – undo
995 1076
 		}
996 1077
 		// Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
997 1078
 		$out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
998
-		if (isset($this->reply_to)  && $this->reply_to)  $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
999
-		if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1079
+		if (isset($this->reply_to)  && $this->reply_to) {
1080
+		    $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
1081
+		}
1082
+		if (isset($this->errors_to) && $this->errors_to) {
1083
+		    $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
1084
+		}
1000 1085
 
1001 1086
 		// Receiver
1002
-		if (isset($this->addr_cc)   && $this->addr_cc)   $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1003
-		if (isset($this->addr_bcc)  && $this->addr_bcc)  $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;    // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1087
+		if (isset($this->addr_cc)   && $this->addr_cc) {
1088
+		    $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
1089
+		}
1090
+		if (isset($this->addr_bcc)  && $this->addr_bcc) {
1091
+		    $out.= "Bcc: ".$this->getValidAddress($this->addr_bcc,2).$this->eol2;
1092
+		}
1093
+		// TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1004 1094
 
1005 1095
 		// Delivery receipt
1006
-		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1096
+		if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1097
+		    $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
1098
+		}
1007 1099
 
1008 1100
 		//$out.= "X-Priority: 3".$this->eol2;
1009 1101
 
@@ -1016,13 +1108,14 @@  discard block
 block discarded – undo
1016 1108
 			$out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;	// Uppercase seems replaced by phpmail
1017 1109
 			$out.= 'References: <' . time() . '.phpmail-dolibarr-'. $trackid . '@' . $host . ">" . $this->eol2;
1018 1110
 			$out.= 'X-Dolibarr-TRACKID: ' . $trackid . '@' . $host. $this->eol2;
1019
-		}
1020
-		else
1111
+		} else
1021 1112
 		{
1022 1113
 			$out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
1023 1114
 		}
1024 1115
 
1025
-		if (! empty($_SERVER['REMOTE_ADDR'])) $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1116
+		if (! empty($_SERVER['REMOTE_ADDR'])) {
1117
+		    $out.= "X-RemoteAddr: " . $_SERVER['REMOTE_ADDR']. $this->eol2;
1118
+		}
1026 1119
 		$out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
1027 1120
 		$out.= "Mime-Version: 1.0".$this->eol2;
1028 1121
 
@@ -1057,7 +1150,9 @@  discard block
 block discarded – undo
1057 1150
 			{
1058 1151
 				if ($filename_list[$i])
1059 1152
 				{
1060
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1153
+					if ($mimefilename_list[$i]) {
1154
+					    $filename_list[$i] = $mimefilename_list[$i];
1155
+					}
1061 1156
 					$out.= "X-attachments: $filename_list[$i]".$this->eol2;
1062 1157
 				}
1063 1158
 			}
@@ -1127,9 +1222,11 @@  discard block
 block discarded – undo
1127 1222
 				$out.= "--" . $this->related_boundary . $this->eol;
1128 1223
 			}
1129 1224
 
1130
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part before html part
1225
+			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1226
+			    // Add plain text message part before html part
1131 1227
 			{
1132 1228
 				$out.= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1229
+			}
1133 1230
 				$out.= $this->eol;
1134 1231
 				$out.= "--" . $this->alternative_boundary . $this->eol;
1135 1232
 				$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
@@ -1142,12 +1239,13 @@  discard block
 block discarded – undo
1142 1239
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;	// TODO Use base64
1143 1240
 			$out.= $this->eol.$strContent.$this->eol;
1144 1241
 
1145
-			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART))    // Add plain text message part after html part
1242
+			if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) {
1243
+			    // Add plain text message part after html part
1146 1244
 			{
1147 1245
 				$out.= "--" . $this->alternative_boundary . "--". $this->eol;
1148 1246
 			}
1149
-		}
1150
-		else
1247
+			}
1248
+		} else
1151 1249
 		{
1152 1250
 			$out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1153 1251
 			//$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
@@ -1192,7 +1290,9 @@  discard block
 block discarded – undo
1192 1290
 				$encoded = $this->_encode_file($filename_list[$i]);
1193 1291
 				if ($encoded >= 0)
1194 1292
 				{
1195
-					if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
1293
+					if ($mimefilename_list[$i]) {
1294
+					    $filename_list[$i] = $mimefilename_list[$i];
1295
+					}
1196 1296
 					if (! $mimetype_list[$i]) {
1197 1297
 						$mimetype_list[$i] = "application/octet-stream";
1198 1298
 					}
@@ -1206,8 +1306,7 @@  discard block
 block discarded – undo
1206 1306
 					$out.= $encoded;
1207 1307
 					$out.= $this->eol;
1208 1308
 					//$out.= $this->eol;
1209
-				}
1210
-				else
1309
+				} else
1211 1310
 				{
1212 1311
 					return $encoded;
1213 1312
 				}
@@ -1286,7 +1385,9 @@  discard block
 block discarded – undo
1286 1385
 			}
1287 1386
 
1288 1387
 			// If we use SSL/TLS
1289
-			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) $host='ssl://'.$host;
1388
+			if (! empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
1389
+			    $host='ssl://'.$host;
1390
+			}
1290 1391
 			// tls smtp start with no encryption
1291 1392
 			//if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1292 1393
 
@@ -1298,17 +1399,20 @@  discard block
 block discarded – undo
1298 1399
 					$errno,      // actual system level error
1299 1400
 					$errstr,     // and any text that goes with the error
1300 1401
 					$timeout
1301
-			))  // timeout for reading/writing data over the socket
1402
+			)) {
1403
+			    // timeout for reading/writing data over the socket
1302 1404
 			{
1303 1405
 				// Windows still does not have support for this timeout function
1304 1406
 				if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
1407
+			}
1305 1408
 
1306 1409
 				dol_syslog("Now we wait for answer 220");
1307 1410
 
1308 1411
 				// Check response from Server
1309
-				if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
1310
-			}
1311
-			else
1412
+				if ( $_retVal = $this->server_parse($socket, "220") ) {
1413
+				    $_retVal = $socket;
1414
+				}
1415
+			} else
1312 1416
 			{
1313 1417
 				$this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
1314 1418
 			}
@@ -1369,9 +1473,11 @@  discard block
 block discarded – undo
1369 1473
 			foreach ($matches[1] as $full)
1370 1474
 			{
1371 1475
 
1372
-				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs))   // If xxx is 'file=aaa'
1476
+				if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs)) {
1477
+				    // If xxx is 'file=aaa'
1373 1478
 				{
1374 1479
 					$img = $regs[1];
1480
+				}
1375 1481
 
1376 1482
 					if (file_exists($images_dir.'/'.$img))
1377 1483
 					{
@@ -1430,15 +1536,13 @@  discard block
 block discarded – undo
1430 1536
 					}
1431 1537
 					$i++;
1432 1538
 				}
1433
-			}
1434
-			else
1539
+			} else
1435 1540
 			{
1436 1541
 				return -1;
1437 1542
 			}
1438 1543
 
1439 1544
 			return 1;
1440
-		}
1441
-		else
1545
+		} else
1442 1546
 		{
1443 1547
 			return 0;
1444 1548
 		}
@@ -1473,8 +1577,7 @@  discard block
 block discarded – undo
1473 1577
 			{
1474 1578
 				$name  = trim($regs[1]);
1475 1579
 				$email = trim($regs[2]);
1476
-			}
1477
-			else
1580
+			} else
1478 1581
 			{
1479 1582
 				$name  = '';
1480 1583
 				$email = trim($val);
@@ -1499,9 +1602,13 @@  discard block
 block discarded – undo
1499 1602
 				}
1500 1603
 				if ($format == 0 || $format == 3)
1501 1604
 				{
1502
-					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
1503
-					elseif (! $name) $newemail='<'.$email.'>';
1504
-					else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1605
+					if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
1606
+					    $newemail='<'.$email.'>';
1607
+					} elseif (! $name) {
1608
+					    $newemail='<'.$email.'>';
1609
+					} else {
1610
+					    $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
1611
+					}
1505 1612
 				}
1506 1613
 
1507 1614
 				$ret=($ret ? $ret.',' : '').$newemail;
@@ -1509,7 +1616,9 @@  discard block
 block discarded – undo
1509 1616
 				// Stop if we have too much records
1510 1617
 				if ($maxnumberofemail && $i >= $maxnumberofemail)
1511 1618
 				{
1512
-					if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
1619
+					if (count($arrayaddress) > $maxnumberofemail) {
1620
+					    $ret.='...';
1621
+					}
1513 1622
 					break;
1514 1623
 				}
1515 1624
 			}
@@ -1539,8 +1648,7 @@  discard block
 block discarded – undo
1539 1648
 			{
1540 1649
 				$name  = trim($regs[1]);
1541 1650
 				$email = trim($regs[2]);
1542
-			}
1543
-			else
1651
+			} else
1544 1652
 			{
1545 1653
 				$name  = null;
1546 1654
 				$email = trim($val);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formbarcode.class.php 2 patches
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     /**
38 38
      * @var string Error code (or message)
39 39
      */
40
-    public $error='';
40
+    public $error = '';
41 41
 
42 42
 
43 43
     /**
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
      *  @param  int		$idForm			Id du formulaire
61 61
      * 	@return	string					HTML select string
62 62
      */
63
-    function setBarcodeEncoder($selected,$barcodelist,$code_id,$idForm='formbarcode')
63
+    function setBarcodeEncoder($selected, $barcodelist, $code_id, $idForm = 'formbarcode')
64 64
     {
65 65
         global $conf, $langs;
66 66
 
@@ -81,8 +81,8 @@  discard block
 block discarded – undo
81 81
         }
82 82
 
83 83
         // We check if barcode is already selected by default
84
-        if (((! empty($conf->product->enabled) || ! empty($conf->service->enabled)) && $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE == $code_id) ||
85
-        (! empty($conf->societe->enabled) && $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY == $code_id))
84
+        if (((!empty($conf->product->enabled) || !empty($conf->service->enabled)) && $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE == $code_id) ||
85
+        (!empty($conf->societe->enabled) && $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY == $code_id))
86 86
         {
87 87
             $disable = 'disabled';
88 88
         }
@@ -90,24 +90,24 @@  discard block
 block discarded – undo
90 90
         if (!empty($conf->use_javascript_ajax))
91 91
         {
92 92
             $select_encoder = '<form action="'.DOL_URL_ROOT.'/admin/barcode.php" method="POST" id="form'.$idForm.'">';
93
-            $select_encoder.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
94
-            $select_encoder.= '<input type="hidden" name="action" value="update">';
95
-            $select_encoder.= '<input type="hidden" name="code_id" value="'.$code_id.'">';
93
+            $select_encoder .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
94
+            $select_encoder .= '<input type="hidden" name="action" value="update">';
95
+            $select_encoder .= '<input type="hidden" name="code_id" value="'.$code_id.'">';
96 96
         }
97 97
         
98
-        $selectname=(!empty($conf->use_javascript_ajax)?'coder':'coder'.$code_id);
99
-        $select_encoder.= '<select id="select'.$idForm.'" class="flat" name="'.$selectname.'">';
100
-        $select_encoder.= '<option value="0"'.($selected==0?' selected':'').' '.$disable.'>'.$langs->trans('Disable').'</option>';
101
-        $select_encoder.= '<option value="-1" disabled>--------------------</option>';
102
-        foreach($barcodelist as $key => $value)
98
+        $selectname = (!empty($conf->use_javascript_ajax) ? 'coder' : 'coder'.$code_id);
99
+        $select_encoder .= '<select id="select'.$idForm.'" class="flat" name="'.$selectname.'">';
100
+        $select_encoder .= '<option value="0"'.($selected == 0 ? ' selected' : '').' '.$disable.'>'.$langs->trans('Disable').'</option>';
101
+        $select_encoder .= '<option value="-1" disabled>--------------------</option>';
102
+        foreach ($barcodelist as $key => $value)
103 103
         {
104
-            $select_encoder.= '<option value="'.$key.'"'.($selected==$key?' selected':'').'>'.$value.'</option>';
104
+            $select_encoder .= '<option value="'.$key.'"'.($selected == $key ? ' selected' : '').'>'.$value.'</option>';
105 105
         }
106
-        $select_encoder.= '</select>';
106
+        $select_encoder .= '</select>';
107 107
         
108 108
         if (!empty($conf->use_javascript_ajax))
109 109
         {
110
-            $select_encoder.= '</form>';
110
+            $select_encoder .= '</form>';
111 111
         }
112 112
 
113 113
         return $select_encoder;
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
      *  @return void
124 124
      *  @deprecated
125 125
      */
126
-    function select_barcode_type($selected='', $htmlname='barcodetype_id', $useempty=0)
126
+    function select_barcode_type($selected = '', $htmlname = 'barcodetype_id', $useempty = 0)
127 127
     {
128 128
         // phpcs:enable
129 129
         print $this->selectBarcodeType($selected, $htmlname, $useempty);
@@ -137,17 +137,17 @@  discard block
 block discarded – undo
137 137
      *  @param  int     $useempty          Display empty value in select
138 138
      *  @return string
139 139
      */
140
-    function selectBarcodeType($selected='', $htmlname='barcodetype_id', $useempty=0)
140
+    function selectBarcodeType($selected = '', $htmlname = 'barcodetype_id', $useempty = 0)
141 141
     {
142 142
         global $langs, $conf;
143 143
 
144 144
         $out = '';
145 145
 
146 146
         $sql = "SELECT rowid, code, libelle";
147
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
148
-        $sql.= " WHERE coder <> '0'";
149
-        $sql.= " AND entity = ".$conf->entity;
150
-        $sql.= " ORDER BY code";
147
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
148
+        $sql .= " WHERE coder <> '0'";
149
+        $sql .= " AND entity = ".$conf->entity;
150
+        $sql .= " ORDER BY code";
151 151
 
152 152
         $result = $this->db->query($sql);
153 153
         if ($result) {
@@ -155,20 +155,20 @@  discard block
 block discarded – undo
155 155
             $i = 0;
156 156
 
157 157
             if ($useempty && $num > 0) {
158
-                $out .= '<select class="flat minwidth75imp" name="' . $htmlname . '" id="select_' . $htmlname . '">';
158
+                $out .= '<select class="flat minwidth75imp" name="'.$htmlname.'" id="select_'.$htmlname.'">';
159 159
                 $out .= '<option value="0">&nbsp;</option>';
160 160
             } else {
161 161
                 $langs->load("errors");
162
-                $out .= '<select disabled class="flat minwidth75imp" name="' . $htmlname . '" id="select_' . $htmlname . '">';
163
-                $out .= '<option value="0" selected>' . $langs->trans('ErrorNoActivatedBarcode') . '</option>';
162
+                $out .= '<select disabled class="flat minwidth75imp" name="'.$htmlname.'" id="select_'.$htmlname.'">';
163
+                $out .= '<option value="0" selected>'.$langs->trans('ErrorNoActivatedBarcode').'</option>';
164 164
             }
165 165
 
166 166
             while ($i < $num) {
167 167
                 $obj = $this->db->fetch_object($result);
168 168
                 if ($selected == $obj->rowid) {
169
-                    $out .= '<option value="' . $obj->rowid . '" selected>';
169
+                    $out .= '<option value="'.$obj->rowid.'" selected>';
170 170
                 } else {
171
-                    $out .= '<option value="' . $obj->rowid . '">';
171
+                    $out .= '<option value="'.$obj->rowid.'">';
172 172
                 }
173 173
                 $out .= $obj->libelle;
174 174
                 $out .= '</option>';
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
      *  @return	void
194 194
      *  @deprecated
195 195
      */
196
-    function form_barcode_type($page, $selected='', $htmlname='barcodetype_id')
196
+    function form_barcode_type($page, $selected = '', $htmlname = 'barcodetype_id')
197 197
     {
198 198
         // phpcs:enable
199 199
         print $this->formBarcodeType($page, $selected, $htmlname);
@@ -207,19 +207,19 @@  discard block
 block discarded – undo
207 207
      *  @param  string      $htmlname       Nom du formulaire select
208 208
      *  @return string
209 209
      */
210
-    function formBarcodeType($page, $selected='', $htmlname='barcodetype_id')
210
+    function formBarcodeType($page, $selected = '', $htmlname = 'barcodetype_id')
211 211
     {
212 212
         global $langs, $conf;
213 213
         $out = '';
214 214
         if ($htmlname != "none") {
215
-            $out .= '<form method="post" action="' . $page . '">';
216
-            $out .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
215
+            $out .= '<form method="post" action="'.$page.'">';
216
+            $out .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
217 217
             $out .= '<input type="hidden" name="action" value="set'.$htmlname.'">';
218 218
             $out .= '<table class="nobordernopadding" cellpadding="0" cellspacing="0">';
219 219
             $out .= '<tr><td>';
220 220
             $out .= $this->selectBarcodeType($selected, $htmlname, 1);
221 221
             $out .= '</td>';
222
-            $out .= '<td align="left"><input type="submit" class="button" value="' . $langs->trans("Modify") . '">';
222
+            $out .= '<td align="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'">';
223 223
             $out .= '</td></tr></table></form>';
224 224
         }
225 225
         return $out;
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -176,8 +176,7 @@
 block discarded – undo
176 176
             }
177 177
             $out .= "</select>";
178 178
             $out .= ajax_combobox("select_".$htmlname);
179
-        }
180
-        else {
179
+        } else {
181 180
             dol_print_error($this->db);
182 181
         }
183 182
         return $out;
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/CSMSFile.class.php 3 patches
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -35,73 +35,73 @@  discard block
 block discarded – undo
35 35
 class CSMSFile
36 36
 {
37 37
     /**
38
-	 * @var string Error code (or message)
39
-	 */
40
-	public $error='';
41
-
42
-	public $addr_from;
43
-	public $addr_to;
44
-	public $deferred;
45
-	public $priority;
46
-	public $class;
47
-	public $message;
48
-	public $nostop;
49
-
50
-
51
-	/**
52
-	 *	CSMSFile
53
-	 *
54
-	 *	@param	string	$to                 Recipients SMS
55
-	 *	@param 	string	$from               Sender SMS
56
-	 *	@param 	string	$msg                Message
57
-	 *	@param 	int		$deliveryreceipt	Not used
58
-	 *	@param 	int		$deferred			Deferred or not
59
-	 *	@param 	int		$priority			Priority
60
-	 *	@param 	int		$class				Class
61
-	 */
62
-	function __construct($to,$from,$msg,$deliveryreceipt=0,$deferred=0,$priority=3,$class=1)
63
-	{
64
-		global $conf;
65
-
66
-		// On definit fin de ligne
67
-		$this->eol="\n";
68
-		if (preg_match('/^win/i',PHP_OS)) $this->eol="\r\n";
69
-		if (preg_match('/^mac/i',PHP_OS)) $this->eol="\r";
70
-
71
-		// If ending method not defined
72
-		if (empty($conf->global->MAIN_SMS_SENDMODE))
73
-		{
74
-		    $this->error='No SMS Engine defined';
75
-		    return -1;
76
-		}
77
-
78
-		dol_syslog("CSMSFile::CSMSFile: MAIN_SMS_SENDMODE=".$conf->global->MAIN_SMS_SENDMODE." charset=".$conf->file->character_set_client." from=".$from.", to=".$to.", msg length=".count($msg), LOG_DEBUG);
79
-		dol_syslog("CSMSFile::CSMSFile: deferred=".$deferred." priority=".$priority." class=".$class, LOG_DEBUG);
80
-
81
-		// Action according to choosed sending method
82
-	    $this->addr_from=$from;
83
-	    $this->addr_to=$to;
38
+     * @var string Error code (or message)
39
+     */
40
+    public $error='';
41
+
42
+    public $addr_from;
43
+    public $addr_to;
44
+    public $deferred;
45
+    public $priority;
46
+    public $class;
47
+    public $message;
48
+    public $nostop;
49
+
50
+
51
+    /**
52
+     *	CSMSFile
53
+     *
54
+     *	@param	string	$to                 Recipients SMS
55
+     *	@param 	string	$from               Sender SMS
56
+     *	@param 	string	$msg                Message
57
+     *	@param 	int		$deliveryreceipt	Not used
58
+     *	@param 	int		$deferred			Deferred or not
59
+     *	@param 	int		$priority			Priority
60
+     *	@param 	int		$class				Class
61
+     */
62
+    function __construct($to,$from,$msg,$deliveryreceipt=0,$deferred=0,$priority=3,$class=1)
63
+    {
64
+        global $conf;
65
+
66
+        // On definit fin de ligne
67
+        $this->eol="\n";
68
+        if (preg_match('/^win/i',PHP_OS)) $this->eol="\r\n";
69
+        if (preg_match('/^mac/i',PHP_OS)) $this->eol="\r";
70
+
71
+        // If ending method not defined
72
+        if (empty($conf->global->MAIN_SMS_SENDMODE))
73
+        {
74
+            $this->error='No SMS Engine defined';
75
+            return -1;
76
+        }
77
+
78
+        dol_syslog("CSMSFile::CSMSFile: MAIN_SMS_SENDMODE=".$conf->global->MAIN_SMS_SENDMODE." charset=".$conf->file->character_set_client." from=".$from.", to=".$to.", msg length=".count($msg), LOG_DEBUG);
79
+        dol_syslog("CSMSFile::CSMSFile: deferred=".$deferred." priority=".$priority." class=".$class, LOG_DEBUG);
80
+
81
+        // Action according to choosed sending method
82
+        $this->addr_from=$from;
83
+        $this->addr_to=$to;
84 84
         $this->deferred=$deferred;
85 85
         $this->priority=$priority;
86 86
         $this->class=$class;
87 87
         $this->message=$msg;
88 88
         $this->nostop=false;
89
-	}
89
+    }
90 90
 
91 91
 
92
-	/**
93
-	 * Send sms that was prepared by constructor
94
-	 *
95
-	 * @return    boolean     True if sms sent, false otherwise
96
-	 */
97
-	function sendfile()
98
-	{
99
-		global $conf;
92
+    /**
93
+     * Send sms that was prepared by constructor
94
+     *
95
+     * @return    boolean     True if sms sent, false otherwise
96
+     */
97
+    function sendfile()
98
+    {
99
+        global $conf;
100 100
 
101
-		$errorlevel=error_reporting();
102
-		error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
101
+        $errorlevel=error_reporting();
102
+        error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
103 103
 
104
-		$res=false;
104
+        $res=false;
105 105
 
106 106
         dol_syslog("CSMSFile::sendfile addr_to=".$this->addr_to, LOG_DEBUG);
107 107
         dol_syslog("CSMSFile::sendfile message=\n".$this->message);
@@ -110,121 +110,121 @@  discard block
 block discarded – undo
110 110
 
111 111
         if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms();
112 112
 
113
-		if (empty($conf->global->MAIN_DISABLE_ALL_SMS))
114
-		{
115
-
116
-		    // Action according to choosed sending method
117
-		    if ($conf->global->MAIN_SMS_SENDMODE == 'ovh')    // Backward compatibility    @deprecated
118
-			{
119
-				dol_include_once('/ovh/class/ovhsms.class.php');
120
-				$sms=new OvhSms($this->db);
121
-				$sms->expe=$this->addr_from;
122
-				$sms->dest=$this->addr_to;
123
-				$sms->message=$this->message;
124
-				$sms->deferred=$this->deferred;
125
-				$sms->priority=$this->priority;
113
+        if (empty($conf->global->MAIN_DISABLE_ALL_SMS))
114
+        {
115
+
116
+            // Action according to choosed sending method
117
+            if ($conf->global->MAIN_SMS_SENDMODE == 'ovh')    // Backward compatibility    @deprecated
118
+            {
119
+                dol_include_once('/ovh/class/ovhsms.class.php');
120
+                $sms=new OvhSms($this->db);
121
+                $sms->expe=$this->addr_from;
122
+                $sms->dest=$this->addr_to;
123
+                $sms->message=$this->message;
124
+                $sms->deferred=$this->deferred;
125
+                $sms->priority=$this->priority;
126 126
                 $sms->class=$this->class;
127 127
                 $sms->nostop=$this->nostop;
128 128
 
129 129
                 $res=$sms->SmsSend();
130
-				if ($res <= 0)
131
-				{
132
-					$this->error=$sms->error;
133
-					dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
134
-				}
135
-				else
136
-				{
137
-					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
138
-					//var_dump($res);        // 1973128
139
-					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
140
-				}
141
-			}
142
-		    else if (! empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
143
-		    {
144
-		        $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
145
-		        $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
146
-		        dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
147
-		        try
148
-		        {
149
-		            $classname=ucfirst($classfile);
150
-		            $sms = new $classname($this->db);
151
-		            $sms->expe=$this->addr_from;
152
-		            $sms->dest=$this->addr_to;
153
-		            $sms->deferred=$this->deferred;
154
-		            $sms->priority=$this->priority;
155
-		            $sms->class=$this->class;
156
-		            $sms->message=$this->message;
157
-		            $sms->nostop=$this->nostop;
130
+                if ($res <= 0)
131
+                {
132
+                    $this->error=$sms->error;
133
+                    dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
134
+                }
135
+                else
136
+                {
137
+                    dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
138
+                    //var_dump($res);        // 1973128
139
+                    if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
140
+                }
141
+            }
142
+            else if (! empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
143
+            {
144
+                $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
145
+                $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
146
+                dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
147
+                try
148
+                {
149
+                    $classname=ucfirst($classfile);
150
+                    $sms = new $classname($this->db);
151
+                    $sms->expe=$this->addr_from;
152
+                    $sms->dest=$this->addr_to;
153
+                    $sms->deferred=$this->deferred;
154
+                    $sms->priority=$this->priority;
155
+                    $sms->class=$this->class;
156
+                    $sms->message=$this->message;
157
+                    $sms->nostop=$this->nostop;
158 158
 
159 159
                     $res=$sms->SmsSend();
160 160
                     $this->error = $sms->error;
161 161
                     $this->errors = $sms->errors;
162
-    				if ($res <= 0)
163
-    				{
164
-    					dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
165
-    				}
166
-    				else
167
-    				{
168
-    					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
169
-    					//var_dump($res);        // 1973128
170
-    					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
171
-    				}
172
-		        }
173
-		        catch(Exception $e)
174
-		        {
175
-		            dol_print_error('','Error to get list of senders: '.$e->getMessage());
176
-		        }
177
-		    }
178
-			else
179
-			{
180
-				// Send sms method not correctly defined
181
-				// --------------------------------------
182
-
183
-				return 'Bad value for MAIN_SMS_SENDMODE constant';
184
-			}
185
-		}
186
-		else
187
-		{
188
-			$this->error='No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS';
189
-			dol_syslog("CSMSFile::sendfile: ".$this->error, LOG_WARNING);
190
-		}
191
-
192
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
193
-
194
-		return $res;
195
-	}
162
+                    if ($res <= 0)
163
+                    {
164
+                        dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
165
+                    }
166
+                    else
167
+                    {
168
+                        dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
169
+                        //var_dump($res);        // 1973128
170
+                        if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
171
+                    }
172
+                }
173
+                catch(Exception $e)
174
+                {
175
+                    dol_print_error('','Error to get list of senders: '.$e->getMessage());
176
+                }
177
+            }
178
+            else
179
+            {
180
+                // Send sms method not correctly defined
181
+                // --------------------------------------
182
+
183
+                return 'Bad value for MAIN_SMS_SENDMODE constant';
184
+            }
185
+        }
186
+        else
187
+        {
188
+            $this->error='No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS';
189
+            dol_syslog("CSMSFile::sendfile: ".$this->error, LOG_WARNING);
190
+        }
191
+
192
+        error_reporting($errorlevel);              // Reactive niveau erreur origine
193
+
194
+        return $res;
195
+    }
196 196
 
197 197
 
198 198
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
199
-	/**
200
-	 *  Write content of a SendSms request into a dump file (mode = all)
201
-	 *  Used for debugging.
202
-	 *
203
-	 *  @return	void
204
-	 */
205
-	function dump_sms()
206
-	{
199
+    /**
200
+     *  Write content of a SendSms request into a dump file (mode = all)
201
+     *  Used for debugging.
202
+     *
203
+     *  @return	void
204
+     */
205
+    function dump_sms()
206
+    {
207 207
         // phpcs:enable
208
-		global $conf,$dolibarr_main_data_root;
209
-
210
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
211
-		{
212
-			$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
213
-			$fp = fopen($outputfile,"w");
214
-
215
-			fputs($fp, "From: ".$this->addr_from."\n");
216
-			fputs($fp, "To: ".$this->addr_to."\n");
217
-			fputs($fp, "Priority: ".$this->priority."\n");
218
-			fputs($fp, "Class: ".$this->class."\n");
219
-			fputs($fp, "Deferred: ".$this->deferred."\n");
220
-			fputs($fp, "DisableStop: ".$this->nostop."\n");
221
-			fputs($fp, "Message:\n".$this->message);
222
-
223
-			fclose($fp);
224
-			if (! empty($conf->global->MAIN_UMASK))
225
-			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
226
-		}
227
-	}
208
+        global $conf,$dolibarr_main_data_root;
209
+
210
+        if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
211
+        {
212
+            $outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
213
+            $fp = fopen($outputfile,"w");
214
+
215
+            fputs($fp, "From: ".$this->addr_from."\n");
216
+            fputs($fp, "To: ".$this->addr_to."\n");
217
+            fputs($fp, "Priority: ".$this->priority."\n");
218
+            fputs($fp, "Class: ".$this->class."\n");
219
+            fputs($fp, "Deferred: ".$this->deferred."\n");
220
+            fputs($fp, "DisableStop: ".$this->nostop."\n");
221
+            fputs($fp, "Message:\n".$this->message);
222
+
223
+            fclose($fp);
224
+            if (! empty($conf->global->MAIN_UMASK))
225
+            @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
226
+        }
227
+    }
228 228
 
229 229
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
230 230
     /**
@@ -241,7 +241,7 @@  discard block
 block discarded – undo
241 241
 
242 242
         if (@is_writeable($dolibarr_main_data_root))    // Avoid fatal error on fopen with open_basedir
243 243
         {
244
-        	$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
244
+            $outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
245 245
             $fp = fopen($outputfile,"a+");
246 246
 
247 247
             fputs($fp, "\nResult id=".$result);
Please login to merge, or discard this patch.
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
     /**
38 38
 	 * @var string Error code (or message)
39 39
 	 */
40
-	public $error='';
40
+	public $error = '';
41 41
 
42 42
 	public $addr_from;
43 43
 	public $addr_to;
@@ -59,19 +59,19 @@  discard block
 block discarded – undo
59 59
 	 *	@param 	int		$priority			Priority
60 60
 	 *	@param 	int		$class				Class
61 61
 	 */
62
-	function __construct($to,$from,$msg,$deliveryreceipt=0,$deferred=0,$priority=3,$class=1)
62
+	function __construct($to, $from, $msg, $deliveryreceipt = 0, $deferred = 0, $priority = 3, $class = 1)
63 63
 	{
64 64
 		global $conf;
65 65
 
66 66
 		// On definit fin de ligne
67
-		$this->eol="\n";
68
-		if (preg_match('/^win/i',PHP_OS)) $this->eol="\r\n";
69
-		if (preg_match('/^mac/i',PHP_OS)) $this->eol="\r";
67
+		$this->eol = "\n";
68
+		if (preg_match('/^win/i', PHP_OS)) $this->eol = "\r\n";
69
+		if (preg_match('/^mac/i', PHP_OS)) $this->eol = "\r";
70 70
 
71 71
 		// If ending method not defined
72 72
 		if (empty($conf->global->MAIN_SMS_SENDMODE))
73 73
 		{
74
-		    $this->error='No SMS Engine defined';
74
+		    $this->error = 'No SMS Engine defined';
75 75
 		    return -1;
76 76
 		}
77 77
 
@@ -79,13 +79,13 @@  discard block
 block discarded – undo
79 79
 		dol_syslog("CSMSFile::CSMSFile: deferred=".$deferred." priority=".$priority." class=".$class, LOG_DEBUG);
80 80
 
81 81
 		// Action according to choosed sending method
82
-	    $this->addr_from=$from;
83
-	    $this->addr_to=$to;
84
-        $this->deferred=$deferred;
85
-        $this->priority=$priority;
86
-        $this->class=$class;
87
-        $this->message=$msg;
88
-        $this->nostop=false;
82
+	    $this->addr_from = $from;
83
+	    $this->addr_to = $to;
84
+        $this->deferred = $deferred;
85
+        $this->priority = $priority;
86
+        $this->class = $class;
87
+        $this->message = $msg;
88
+        $this->nostop = false;
89 89
 	}
90 90
 
91 91
 
@@ -98,17 +98,17 @@  discard block
 block discarded – undo
98 98
 	{
99 99
 		global $conf;
100 100
 
101
-		$errorlevel=error_reporting();
102
-		error_reporting($errorlevel ^ E_WARNING);   // Desactive warnings
101
+		$errorlevel = error_reporting();
102
+		error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
103 103
 
104
-		$res=false;
104
+		$res = false;
105 105
 
106 106
         dol_syslog("CSMSFile::sendfile addr_to=".$this->addr_to, LOG_DEBUG);
107 107
         dol_syslog("CSMSFile::sendfile message=\n".$this->message);
108 108
 
109
-        $this->message=stripslashes($this->message);
109
+        $this->message = stripslashes($this->message);
110 110
 
111
-        if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms();
111
+        if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms();
112 112
 
113 113
 		if (empty($conf->global->MAIN_DISABLE_ALL_SMS))
114 114
 		{
@@ -117,46 +117,46 @@  discard block
 block discarded – undo
117 117
 		    if ($conf->global->MAIN_SMS_SENDMODE == 'ovh')    // Backward compatibility    @deprecated
118 118
 			{
119 119
 				dol_include_once('/ovh/class/ovhsms.class.php');
120
-				$sms=new OvhSms($this->db);
121
-				$sms->expe=$this->addr_from;
122
-				$sms->dest=$this->addr_to;
123
-				$sms->message=$this->message;
124
-				$sms->deferred=$this->deferred;
125
-				$sms->priority=$this->priority;
126
-                $sms->class=$this->class;
127
-                $sms->nostop=$this->nostop;
128
-
129
-                $res=$sms->SmsSend();
120
+				$sms = new OvhSms($this->db);
121
+				$sms->expe = $this->addr_from;
122
+				$sms->dest = $this->addr_to;
123
+				$sms->message = $this->message;
124
+				$sms->deferred = $this->deferred;
125
+				$sms->priority = $this->priority;
126
+                $sms->class = $this->class;
127
+                $sms->nostop = $this->nostop;
128
+
129
+                $res = $sms->SmsSend();
130 130
 				if ($res <= 0)
131 131
 				{
132
-					$this->error=$sms->error;
132
+					$this->error = $sms->error;
133 133
 					dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
134 134
 				}
135 135
 				else
136 136
 				{
137 137
 					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
138 138
 					//var_dump($res);        // 1973128
139
-					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
139
+					if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
140 140
 				}
141 141
 			}
142
-		    else if (! empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
142
+		    else if (!empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
143 143
 		    {
144
-		        $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
145
-		        $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
144
+		        $tmp = explode('@', $conf->global->MAIN_SMS_SENDMODE);
145
+		        $classfile = $tmp[0]; $module = (empty($tmp[1]) ? $tmp[0] : $tmp[1]);
146 146
 		        dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
147 147
 		        try
148 148
 		        {
149
-		            $classname=ucfirst($classfile);
149
+		            $classname = ucfirst($classfile);
150 150
 		            $sms = new $classname($this->db);
151
-		            $sms->expe=$this->addr_from;
152
-		            $sms->dest=$this->addr_to;
153
-		            $sms->deferred=$this->deferred;
154
-		            $sms->priority=$this->priority;
155
-		            $sms->class=$this->class;
156
-		            $sms->message=$this->message;
157
-		            $sms->nostop=$this->nostop;
158
-
159
-                    $res=$sms->SmsSend();
151
+		            $sms->expe = $this->addr_from;
152
+		            $sms->dest = $this->addr_to;
153
+		            $sms->deferred = $this->deferred;
154
+		            $sms->priority = $this->priority;
155
+		            $sms->class = $this->class;
156
+		            $sms->message = $this->message;
157
+		            $sms->nostop = $this->nostop;
158
+
159
+                    $res = $sms->SmsSend();
160 160
                     $this->error = $sms->error;
161 161
                     $this->errors = $sms->errors;
162 162
     				if ($res <= 0)
@@ -167,12 +167,12 @@  discard block
 block discarded – undo
167 167
     				{
168 168
     					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
169 169
     					//var_dump($res);        // 1973128
170
-    					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
170
+    					if (!empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
171 171
     				}
172 172
 		        }
173
-		        catch(Exception $e)
173
+		        catch (Exception $e)
174 174
 		        {
175
-		            dol_print_error('','Error to get list of senders: '.$e->getMessage());
175
+		            dol_print_error('', 'Error to get list of senders: '.$e->getMessage());
176 176
 		        }
177 177
 		    }
178 178
 			else
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
 		}
186 186
 		else
187 187
 		{
188
-			$this->error='No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS';
188
+			$this->error = 'No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS';
189 189
 			dol_syslog("CSMSFile::sendfile: ".$this->error, LOG_WARNING);
190 190
 		}
191 191
 
192
-		error_reporting($errorlevel);              // Reactive niveau erreur origine
192
+		error_reporting($errorlevel); // Reactive niveau erreur origine
193 193
 
194 194
 		return $res;
195 195
 	}
@@ -205,12 +205,12 @@  discard block
 block discarded – undo
205 205
 	function dump_sms()
206 206
 	{
207 207
         // phpcs:enable
208
-		global $conf,$dolibarr_main_data_root;
208
+		global $conf, $dolibarr_main_data_root;
209 209
 
210 210
 		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
211 211
 		{
212
-			$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
213
-			$fp = fopen($outputfile,"w");
212
+			$outputfile = $dolibarr_main_data_root."/dolibarr_sms.log";
213
+			$fp = fopen($outputfile, "w");
214 214
 
215 215
 			fputs($fp, "From: ".$this->addr_from."\n");
216 216
 			fputs($fp, "To: ".$this->addr_to."\n");
@@ -221,7 +221,7 @@  discard block
 block discarded – undo
221 221
 			fputs($fp, "Message:\n".$this->message);
222 222
 
223 223
 			fclose($fp);
224
-			if (! empty($conf->global->MAIN_UMASK))
224
+			if (!empty($conf->global->MAIN_UMASK))
225 225
 			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
226 226
 		}
227 227
 	}
@@ -237,17 +237,17 @@  discard block
 block discarded – undo
237 237
     function dump_sms_result($result)
238 238
     {
239 239
         // phpcs:enable
240
-        global $conf,$dolibarr_main_data_root;
240
+        global $conf, $dolibarr_main_data_root;
241 241
 
242 242
         if (@is_writeable($dolibarr_main_data_root))    // Avoid fatal error on fopen with open_basedir
243 243
         {
244
-        	$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
245
-            $fp = fopen($outputfile,"a+");
244
+        	$outputfile = $dolibarr_main_data_root."/dolibarr_sms.log";
245
+            $fp = fopen($outputfile, "a+");
246 246
 
247 247
             fputs($fp, "\nResult id=".$result);
248 248
 
249 249
             fclose($fp);
250
-            if (! empty($conf->global->MAIN_UMASK))
250
+            if (!empty($conf->global->MAIN_UMASK))
251 251
             @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
252 252
         }
253 253
     }
Please login to merge, or discard this patch.
Braces   +38 added lines, -24 removed lines patch added patch discarded remove patch
@@ -65,8 +65,12 @@  discard block
 block discarded – undo
65 65
 
66 66
 		// On definit fin de ligne
67 67
 		$this->eol="\n";
68
-		if (preg_match('/^win/i',PHP_OS)) $this->eol="\r\n";
69
-		if (preg_match('/^mac/i',PHP_OS)) $this->eol="\r";
68
+		if (preg_match('/^win/i',PHP_OS)) {
69
+		    $this->eol="\r\n";
70
+		}
71
+		if (preg_match('/^mac/i',PHP_OS)) {
72
+		    $this->eol="\r";
73
+		}
70 74
 
71 75
 		// If ending method not defined
72 76
 		if (empty($conf->global->MAIN_SMS_SENDMODE))
@@ -108,15 +112,19 @@  discard block
 block discarded – undo
108 112
 
109 113
         $this->message=stripslashes($this->message);
110 114
 
111
-        if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms();
115
+        if (! empty($conf->global->MAIN_SMS_DEBUG)) {
116
+            $this->dump_sms();
117
+        }
112 118
 
113 119
 		if (empty($conf->global->MAIN_DISABLE_ALL_SMS))
114 120
 		{
115 121
 
116 122
 		    // Action according to choosed sending method
117
-		    if ($conf->global->MAIN_SMS_SENDMODE == 'ovh')    // Backward compatibility    @deprecated
123
+		    if ($conf->global->MAIN_SMS_SENDMODE == 'ovh') {
124
+		        // Backward compatibility    @deprecated
118 125
 			{
119 126
 				dol_include_once('/ovh/class/ovhsms.class.php');
127
+		    }
120 128
 				$sms=new OvhSms($this->db);
121 129
 				$sms->expe=$this->addr_from;
122 130
 				$sms->dest=$this->addr_to;
@@ -131,17 +139,19 @@  discard block
 block discarded – undo
131 139
 				{
132 140
 					$this->error=$sms->error;
133 141
 					dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
134
-				}
135
-				else
142
+				} else
136 143
 				{
137 144
 					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
138 145
 					//var_dump($res);        // 1973128
139
-					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
146
+					if (! empty($conf->global->MAIN_SMS_DEBUG)) {
147
+					    $this->dump_sms_result($res);
148
+					}
140 149
 				}
141
-			}
142
-		    else if (! empty($conf->global->MAIN_SMS_SENDMODE))    // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
150
+			} else if (! empty($conf->global->MAIN_SMS_SENDMODE)) {
151
+		        // $conf->global->MAIN_SMS_SENDMODE looks like a value 'class@module'
143 152
 		    {
144 153
 		        $tmp=explode('@',$conf->global->MAIN_SMS_SENDMODE);
154
+		    }
145 155
 		        $classfile=$tmp[0]; $module=(empty($tmp[1])?$tmp[0]:$tmp[1]);
146 156
 		        dol_include_once('/'.$module.'/class/'.$classfile.'.class.php');
147 157
 		        try
@@ -162,28 +172,26 @@  discard block
 block discarded – undo
162 172
     				if ($res <= 0)
163 173
     				{
164 174
     					dol_syslog("CSMSFile::sendfile: sms send error=".$this->error, LOG_ERR);
165
-    				}
166
-    				else
175
+    				} else
167 176
     				{
168 177
     					dol_syslog("CSMSFile::sendfile: sms send success with id=".$res, LOG_DEBUG);
169 178
     					//var_dump($res);        // 1973128
170
-    					if (! empty($conf->global->MAIN_SMS_DEBUG)) $this->dump_sms_result($res);
179
+    					if (! empty($conf->global->MAIN_SMS_DEBUG)) {
180
+    					    $this->dump_sms_result($res);
181
+    					}
171 182
     				}
172
-		        }
173
-		        catch(Exception $e)
183
+		        } catch(Exception $e)
174 184
 		        {
175 185
 		            dol_print_error('','Error to get list of senders: '.$e->getMessage());
176 186
 		        }
177
-		    }
178
-			else
187
+		    } else
179 188
 			{
180 189
 				// Send sms method not correctly defined
181 190
 				// --------------------------------------
182 191
 
183 192
 				return 'Bad value for MAIN_SMS_SENDMODE constant';
184 193
 			}
185
-		}
186
-		else
194
+		} else
187 195
 		{
188 196
 			$this->error='No sms sent. Feature is disabled by option MAIN_DISABLE_ALL_SMS';
189 197
 			dol_syslog("CSMSFile::sendfile: ".$this->error, LOG_WARNING);
@@ -207,9 +215,11 @@  discard block
 block discarded – undo
207 215
         // phpcs:enable
208 216
 		global $conf,$dolibarr_main_data_root;
209 217
 
210
-		if (@is_writeable($dolibarr_main_data_root))	// Avoid fatal error on fopen with open_basedir
218
+		if (@is_writeable($dolibarr_main_data_root)) {
219
+		    // Avoid fatal error on fopen with open_basedir
211 220
 		{
212 221
 			$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
222
+		}
213 223
 			$fp = fopen($outputfile,"w");
214 224
 
215 225
 			fputs($fp, "From: ".$this->addr_from."\n");
@@ -221,8 +231,9 @@  discard block
 block discarded – undo
221 231
 			fputs($fp, "Message:\n".$this->message);
222 232
 
223 233
 			fclose($fp);
224
-			if (! empty($conf->global->MAIN_UMASK))
225
-			@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
234
+			if (! empty($conf->global->MAIN_UMASK)) {
235
+						@chmod($outputfile, octdec($conf->global->MAIN_UMASK));
236
+			}
226 237
 		}
227 238
 	}
228 239
 
@@ -239,16 +250,19 @@  discard block
 block discarded – undo
239 250
         // phpcs:enable
240 251
         global $conf,$dolibarr_main_data_root;
241 252
 
242
-        if (@is_writeable($dolibarr_main_data_root))    // Avoid fatal error on fopen with open_basedir
253
+        if (@is_writeable($dolibarr_main_data_root)) {
254
+            // Avoid fatal error on fopen with open_basedir
243 255
         {
244 256
         	$outputfile=$dolibarr_main_data_root."/dolibarr_sms.log";
257
+        }
245 258
             $fp = fopen($outputfile,"a+");
246 259
 
247 260
             fputs($fp, "\nResult id=".$result);
248 261
 
249 262
             fclose($fp);
250
-            if (! empty($conf->global->MAIN_UMASK))
251
-            @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
263
+            if (! empty($conf->global->MAIN_UMASK)) {
264
+                        @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
265
+            }
252 266
         }
253 267
     }
254 268
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/fileupload.class.php 3 patches
Indentation   +516 added lines, -516 removed lines patch added patch discarded remove patch
@@ -30,143 +30,143 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class FileUpload
32 32
 {
33
-	protected $options;
34
-	protected $fk_element;
35
-	protected $element;
36
-
37
-	/**
38
-	 * Constructor
39
-	 *
40
-	 * @param array		$options		Options array
41
-	 * @param int		$fk_element		fk_element
42
-	 * @param string	$element		element
43
-	 */
44
-	function __construct($options=null,$fk_element=null,$element=null)
45
-	{
46
-		global $db, $conf;
47
-		global $object;
48
-
49
-		$this->fk_element=$fk_element;
50
-		$this->element=$element;
51
-
52
-		$pathname=$filename=$element;
53
-		if (preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
54
-		{
55
-			$pathname = $regs[1];
56
-			$filename = $regs[2];
57
-		}
58
-
59
-		$parentForeignKey = '';
60
-
61
-		// For compatibility
62
-		if ($element == 'propal') {
63
-			$pathname = 'comm/propal';
64
-			$dir_output=$conf->$element->dir_output;
65
-		}
66
-		elseif ($element == 'facture') {
67
-			$pathname = 'compta/facture';
68
-			$dir_output=$conf->$element->dir_output;
69
-		}
70
-		elseif ($element == 'project') {
71
-			$element = $pathname = 'projet';
72
-			$dir_output=$conf->$element->dir_output;
73
-		}
74
-		elseif ($element == 'project_task') {
75
-			$pathname = 'projet'; $filename='task';
76
-			$dir_output=$conf->projet->dir_output;
77
-			$parentForeignKey = 'fk_project';
78
-			$parentClass = 'Project';
79
-			$parentElement = 'projet';
80
-			$parentObject = 'project';
81
-		}
82
-		elseif ($element == 'fichinter') {
83
-			$element='ficheinter';
84
-			$dir_output=$conf->$element->dir_output;
85
-		}
86
-		elseif ($element == 'order_supplier') {
87
-			$pathname = 'fourn'; $filename='fournisseur.commande';
88
-			$dir_output=$conf->fournisseur->commande->dir_output;
89
-		}
90
-		elseif ($element == 'invoice_supplier') {
91
-			$pathname = 'fourn'; $filename='fournisseur.facture';
92
-			$dir_output=$conf->fournisseur->facture->dir_output;
93
-		}
94
-		elseif ($element == 'product') {
95
-			$dir_output = $conf->product->multidir_output[$conf->entity];
96
-		}
97
-		elseif ($element == 'productbatch') {
98
-			$dir_output = $conf->productbatch->multidir_output[$conf->entity];
99
-		}
100
-		elseif ($element == 'action') {
101
-			$pathname = 'comm/action'; $filename='actioncomm';
102
-			$dir_output=$conf->agenda->dir_output;
103
-		}
104
-		elseif ($element == 'chargesociales') {
105
-			$pathname = 'compta/sociales'; $filename='chargesociales';
106
-			$dir_output=$conf->tax->dir_output;
107
-		} else {
108
-			$dir_output=$conf->$element->dir_output;
109
-		}
110
-
111
-		dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
112
-
113
-		$classname = ucfirst($filename);
114
-
115
-		if ($element == 'order_supplier') {
116
-			$classname = 'CommandeFournisseur';
117
-		} elseif ($element == 'invoice_supplier') {
118
-			$classname = 'FactureFournisseur';
119
-		}
120
-
121
-		$object = new $classname($db);
122
-
123
-		$object->fetch($fk_element);
124
-		if (!empty($parentForeignKey)) {
125
-			dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
126
-			$parent = new $parentClass($db);
127
-			$parent->fetch($object->$parentForeignKey);
128
-			if (!empty($parent->socid)) {
129
-				$parent->fetch_thirdparty();
130
-			}
131
-			$object->$parentObject = clone $parent;
132
-		} else {
133
-			$object->fetch_thirdparty();
134
-		}
135
-
136
-		$object_ref = dol_sanitizeFileName($object->ref);
137
-		if ($element == 'invoice_supplier') {
138
-			$object_ref = get_exdir($object->id,2,0,0,$object,'invoice_supplier') . $object_ref;
139
-		} else if ($element == 'project_task') {
140
-			$object_ref = $object->project->ref . '/' . $object_ref;
141
-		}
142
-
143
-		$this->options = array(
144
-				'script_url' => $_SERVER['PHP_SELF'],
145
-				'upload_dir' => $dir_output . '/' . $object_ref . '/',
146
-				'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
147
-				'param_name' => 'files',
148
-				// Set the following option to 'POST', if your server does not support
149
-				// DELETE requests. This is a parameter sent to the client:
150
-				'delete_type' => 'DELETE',
151
-				// The php.ini settings upload_max_filesize and post_max_size
152
-				// take precedence over the following max_file_size setting:
153
-				'max_file_size' => null,
154
-				'min_file_size' => 1,
155
-				'accept_file_types' => '/.+$/i',
156
-				// The maximum number of files for the upload directory:
157
-				'max_number_of_files' => null,
158
-				// Image resolution restrictions:
159
-				'max_width' => null,
160
-				'max_height' => null,
161
-				'min_width' => 1,
162
-				'min_height' => 1,
163
-				// Set the following option to false to enable resumable uploads:
164
-				'discard_aborted_uploads' => true,
165
-				'image_versions' => array(
166
-						// Uncomment the following version to restrict the size of
167
-						// uploaded images. You can also add additional versions with
168
-						// their own upload directories:
169
-						/*
33
+    protected $options;
34
+    protected $fk_element;
35
+    protected $element;
36
+
37
+    /**
38
+     * Constructor
39
+     *
40
+     * @param array		$options		Options array
41
+     * @param int		$fk_element		fk_element
42
+     * @param string	$element		element
43
+     */
44
+    function __construct($options=null,$fk_element=null,$element=null)
45
+    {
46
+        global $db, $conf;
47
+        global $object;
48
+
49
+        $this->fk_element=$fk_element;
50
+        $this->element=$element;
51
+
52
+        $pathname=$filename=$element;
53
+        if (preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
54
+        {
55
+            $pathname = $regs[1];
56
+            $filename = $regs[2];
57
+        }
58
+
59
+        $parentForeignKey = '';
60
+
61
+        // For compatibility
62
+        if ($element == 'propal') {
63
+            $pathname = 'comm/propal';
64
+            $dir_output=$conf->$element->dir_output;
65
+        }
66
+        elseif ($element == 'facture') {
67
+            $pathname = 'compta/facture';
68
+            $dir_output=$conf->$element->dir_output;
69
+        }
70
+        elseif ($element == 'project') {
71
+            $element = $pathname = 'projet';
72
+            $dir_output=$conf->$element->dir_output;
73
+        }
74
+        elseif ($element == 'project_task') {
75
+            $pathname = 'projet'; $filename='task';
76
+            $dir_output=$conf->projet->dir_output;
77
+            $parentForeignKey = 'fk_project';
78
+            $parentClass = 'Project';
79
+            $parentElement = 'projet';
80
+            $parentObject = 'project';
81
+        }
82
+        elseif ($element == 'fichinter') {
83
+            $element='ficheinter';
84
+            $dir_output=$conf->$element->dir_output;
85
+        }
86
+        elseif ($element == 'order_supplier') {
87
+            $pathname = 'fourn'; $filename='fournisseur.commande';
88
+            $dir_output=$conf->fournisseur->commande->dir_output;
89
+        }
90
+        elseif ($element == 'invoice_supplier') {
91
+            $pathname = 'fourn'; $filename='fournisseur.facture';
92
+            $dir_output=$conf->fournisseur->facture->dir_output;
93
+        }
94
+        elseif ($element == 'product') {
95
+            $dir_output = $conf->product->multidir_output[$conf->entity];
96
+        }
97
+        elseif ($element == 'productbatch') {
98
+            $dir_output = $conf->productbatch->multidir_output[$conf->entity];
99
+        }
100
+        elseif ($element == 'action') {
101
+            $pathname = 'comm/action'; $filename='actioncomm';
102
+            $dir_output=$conf->agenda->dir_output;
103
+        }
104
+        elseif ($element == 'chargesociales') {
105
+            $pathname = 'compta/sociales'; $filename='chargesociales';
106
+            $dir_output=$conf->tax->dir_output;
107
+        } else {
108
+            $dir_output=$conf->$element->dir_output;
109
+        }
110
+
111
+        dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
112
+
113
+        $classname = ucfirst($filename);
114
+
115
+        if ($element == 'order_supplier') {
116
+            $classname = 'CommandeFournisseur';
117
+        } elseif ($element == 'invoice_supplier') {
118
+            $classname = 'FactureFournisseur';
119
+        }
120
+
121
+        $object = new $classname($db);
122
+
123
+        $object->fetch($fk_element);
124
+        if (!empty($parentForeignKey)) {
125
+            dol_include_once('/'.$parentElement.'/class/'.$parentObject.'.class.php');
126
+            $parent = new $parentClass($db);
127
+            $parent->fetch($object->$parentForeignKey);
128
+            if (!empty($parent->socid)) {
129
+                $parent->fetch_thirdparty();
130
+            }
131
+            $object->$parentObject = clone $parent;
132
+        } else {
133
+            $object->fetch_thirdparty();
134
+        }
135
+
136
+        $object_ref = dol_sanitizeFileName($object->ref);
137
+        if ($element == 'invoice_supplier') {
138
+            $object_ref = get_exdir($object->id,2,0,0,$object,'invoice_supplier') . $object_ref;
139
+        } else if ($element == 'project_task') {
140
+            $object_ref = $object->project->ref . '/' . $object_ref;
141
+        }
142
+
143
+        $this->options = array(
144
+                'script_url' => $_SERVER['PHP_SELF'],
145
+                'upload_dir' => $dir_output . '/' . $object_ref . '/',
146
+                'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
147
+                'param_name' => 'files',
148
+                // Set the following option to 'POST', if your server does not support
149
+                // DELETE requests. This is a parameter sent to the client:
150
+                'delete_type' => 'DELETE',
151
+                // The php.ini settings upload_max_filesize and post_max_size
152
+                // take precedence over the following max_file_size setting:
153
+                'max_file_size' => null,
154
+                'min_file_size' => 1,
155
+                'accept_file_types' => '/.+$/i',
156
+                // The maximum number of files for the upload directory:
157
+                'max_number_of_files' => null,
158
+                // Image resolution restrictions:
159
+                'max_width' => null,
160
+                'max_height' => null,
161
+                'min_width' => 1,
162
+                'min_height' => 1,
163
+                // Set the following option to false to enable resumable uploads:
164
+                'discard_aborted_uploads' => true,
165
+                'image_versions' => array(
166
+                        // Uncomment the following version to restrict the size of
167
+                        // uploaded images. You can also add additional versions with
168
+                        // their own upload directories:
169
+                        /*
170 170
 		'large' => array(
171 171
 				'upload_dir' => dirname($_SERVER['SCRIPT_FILENAME']).'/files/',
172 172
 				'upload_url' => $this->getFullUrl().'/files/',
@@ -175,338 +175,338 @@  discard block
 block discarded – undo
175 175
 				'jpeg_quality' => 95
176 176
 		),
177 177
 		*/
178
-						'thumbnail' => array(
179
-								'upload_dir' => $dir_output . '/' . $object_ref . '/thumbs/',
180
-								'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
181
-								'max_width' => 80,
182
-								'max_height' => 80
183
-						)
184
-				)
185
-		);
186
-		if ($options) {
187
-			$this->options = array_replace_recursive($this->options, $options);
188
-		}
189
-	}
190
-
191
-	/**
192
-	 *	Return full URL
193
-	 *
194
-	 *	@return	string			URL
195
-	 */
196
-	protected function getFullUrl()
197
-	{
198
-		$https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
199
-		return
200
-		($https ? 'https://' : 'http://').
201
-		(!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
202
-		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
203
-				($https && $_SERVER['SERVER_PORT'] === 443 ||
204
-						$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
205
-						substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
206
-	}
207
-
208
-	/**
209
-	 * Set delete url
210
-	 *
211
-	 * @param 	string	$file		Filename
212
-	 * @return	void
213
-	 */
214
-	protected function setFileDeleteUrl($file)
215
-	{
216
-		$file->delete_url = $this->options['script_url']
217
-		.'?file='.rawurlencode($file->name).'&fk_element='.$this->fk_element.'&element='.$this->element;
218
-		$file->delete_type = $this->options['delete_type'];
219
-		if ($file->delete_type !== 'DELETE') {
220
-			$file->delete_url .= '&_method=DELETE';
221
-		}
222
-	}
223
-
224
-	/**
225
-	 * getFileObject
226
-	 *
227
-	 * @param	string		$file_name		Filename
228
-	 * @return 	stdClass|null
229
-	 */
230
-	protected function getFileObject($file_name)
231
-	{
232
-		$file_path = $this->options['upload_dir'].$file_name;
233
-		if (is_file($file_path) && $file_name[0] !== '.')
234
-		{
235
-			$file = new stdClass();
236
-			$file->name = $file_name;
237
-			$file->mime = dol_mimetype($file_name,'',2);
238
-			$file->size = filesize($file_path);
239
-			$file->url = $this->options['upload_url'].rawurlencode($file->name);
240
-			foreach($this->options['image_versions'] as $version => $options) {
241
-				if (is_file($options['upload_dir'].$file_name)) {
242
-					$tmp=explode('.',$file->name);
243
-					$file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
244
-				}
245
-			}
246
-			$this->setFileDeleteUrl($file);
247
-			return $file;
248
-		}
249
-		return null;
250
-	}
251
-
252
-	/**
253
-	 * getFileObjects
254
-	 *
255
-	 * @return	void
256
-	 */
257
-	protected function getFileObjects()
258
-	{
259
-		return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
260
-	}
261
-
262
-	/**
263
-	 *  Create thumbs of a file uploaded. Only the "mini" thumb is generated.
264
-	 *
265
-	 *  @param	string	$file_name		Filename
266
-	 *  @param	string	$options 		is array('max_width', 'max_height')
267
-	 *  @return	boolean
268
-	 */
269
-	protected function createScaledImage($file_name, $options)
270
-	{
271
-		global $maxwidthmini, $maxheightmini;
272
-
273
-		$file_path = $this->options['upload_dir'].$file_name;
274
-		$new_file_path = $options['upload_dir'].$file_name;
275
-
276
-		if (dol_mkdir($options['upload_dir']) >= 0)
277
-		{
278
-			list($img_width, $img_height) = @getimagesize($file_path);
279
-			if (!$img_width || !$img_height) {
280
-				return false;
281
-			}
282
-
283
-			$res=vignette($file_path,$maxwidthmini,$maxheightmini,'_mini');  // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
284
-
285
-			if (preg_match('/error/i',$res)) return false;
286
-			return true;
287
-		}
288
-		else
289
-		{
290
-			return false;
291
-		}
292
-	}
293
-
294
-	/**
295
-	 * Enter description here ...
296
-	 *
297
-	 * @param 	string	$uploaded_file		Uploade file
298
-	 * @param 	string	$file				File
299
-	 * @param 	string	$error				Error
300
-	 * @param	string	$index				Index
301
-	 * @return  boolean                     True if OK, False if KO
302
-	 */
303
-	protected function validate($uploaded_file, $file, $error, $index)
304
-	{
305
-		if ($error) {
306
-			$file->error = $error;
307
-			return false;
308
-		}
309
-		if (!$file->name) {
310
-			$file->error = 'missingFileName';
311
-			return false;
312
-		}
313
-		if (!preg_match($this->options['accept_file_types'], $file->name)) {
314
-			$file->error = 'acceptFileTypes';
315
-			return false;
316
-		}
317
-		if ($uploaded_file && is_uploaded_file($uploaded_file)) {
318
-			$file_size = filesize($uploaded_file);
319
-		} else {
320
-			$file_size = $_SERVER['CONTENT_LENGTH'];
321
-		}
322
-		if ($this->options['max_file_size'] && (
323
-				$file_size > $this->options['max_file_size'] ||
324
-				$file->size > $this->options['max_file_size'])
325
-		) {
326
-			$file->error = 'maxFileSize';
327
-			return false;
328
-		}
329
-		if ($this->options['min_file_size'] &&
330
-				$file_size < $this->options['min_file_size']) {
331
-			$file->error = 'minFileSize';
332
-			return false;
333
-		}
334
-		if (is_numeric($this->options['max_number_of_files']) && (
335
-				count($this->getFileObjects()) >= $this->options['max_number_of_files'])
336
-		) {
337
-			$file->error = 'maxNumberOfFiles';
338
-			return false;
339
-		}
340
-		list($img_width, $img_height) = @getimagesize($uploaded_file);
341
-		if (is_numeric($img_width)) {
342
-			if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
343
-					$this->options['max_height'] && $img_height > $this->options['max_height']) {
344
-				$file->error = 'maxResolution';
345
-				return false;
346
-			}
347
-			if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
348
-					$this->options['min_height'] && $img_height < $this->options['min_height']) {
349
-				$file->error = 'minResolution';
350
-				return false;
351
-			}
352
-		}
353
-		return true;
354
-	}
355
-
356
-	/**
357
-	 * Enter description here ...
358
-	 *
359
-	 * @param 	int		$matches		???
360
-	 * @return	string					???
361
-	 */
362
-	protected function upcountNameCallback($matches)
363
-	{
364
-		$index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
365
-		$ext = isset($matches[2]) ? $matches[2] : '';
366
-		return ' ('.$index.')'.$ext;
367
-	}
368
-
369
-	/**
370
-	 * Enter description here ...
371
-	 *
372
-	 * @param 	string		$name		???
373
-	 * @return	string					???
374
-	 */
375
-	protected function upcountName($name)
376
-	{
377
-		return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
378
-	}
379
-
380
-	/**
381
-	 * trimFileName
382
-	 *
383
-	 * @param 	string $name		Filename
384
-	 * @param 	string $type		???
385
-	 * @param 	string $index		???
386
-	 * @return	string
387
-	 */
388
-	protected function trimFileName($name, $type, $index)
389
-	{
390
-		// Remove path information and dots around the filename, to prevent uploading
391
-		// into different directories or replacing hidden system files.
392
-		// Also remove control characters and spaces (\x00..\x20) around the filename:
393
-		$file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
394
-		// Add missing file extension for known image types:
395
-		if (strpos($file_name, '.') === false &&
396
-				preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
397
-			$file_name .= '.'.$matches[1];
398
-		}
399
-		if ($this->options['discard_aborted_uploads'])
400
-		{
401
-			while(is_file($this->options['upload_dir'].$file_name))
402
-			{
403
-				$file_name = $this->upcountName($file_name);
404
-			}
405
-		}
406
-		return $file_name;
407
-	}
408
-
409
-	/**
410
-	 * handleFileUpload
411
-	 *
412
-	 * @param 	string		$uploaded_file		Uploade file
413
-	 * @param 	string		$name				Name
414
-	 * @param 	int			$size				Size
415
-	 * @param 	string		$type				Type
416
-	 * @param 	string		$error				Error
417
-	 * @param	string		$index				Index
418
-	 * @return stdClass
419
-	 */
420
-	protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
421
-	{
422
-		$file = new stdClass();
423
-		$file->name = $this->trimFileName($name, $type, $index);
424
-		$file->mime = dol_mimetype($file->name,'',2);
425
-		$file->size = intval($size);
426
-		$file->type = $type;
427
-		if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0)
428
-		{
429
-			$file_path = $this->options['upload_dir'].$file->name;
430
-			$append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
431
-			clearstatcache();
432
-			if ($uploaded_file && is_uploaded_file($uploaded_file)) {
433
-				// multipart/formdata uploads (POST method uploads)
434
-				if ($append_file)
435
-				{
436
-					file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
437
-				} else {
438
-					dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
439
-				}
440
-			}
441
-			else
442
-			{
443
-				// Non-multipart uploads (PUT method support)
444
-				file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
445
-			}
446
-			$file_size = filesize($file_path);
447
-			if ($file_size === $file->size)
448
-			{
449
-				$file->url = $this->options['upload_url'].rawurlencode($file->name);
450
-				foreach($this->options['image_versions'] as $version => $options)
451
-				{
452
-					if ($this->createScaledImage($file->name, $options))
453
-					{
454
-						$tmp=explode('.',$file->name);
455
-						$file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
456
-					}
457
-				}
458
-			}
459
-			else if ($this->options['discard_aborted_uploads'])
460
-			{
461
-				unlink($file_path);
462
-				$file->error = 'abort';
463
-			}
464
-			$file->size = $file_size;
465
-			$this->setFileDeleteUrl($file);
466
-		}
467
-		return $file;
468
-	}
469
-
470
-	/**
471
-	 * Output data
472
-	 *
473
-	 * @return	void
474
-	 */
475
-	public function get()
476
-	{
477
-		$file_name = isset($_REQUEST['file']) ?
478
-		basename(stripslashes($_REQUEST['file'])) : null;
479
-		if ($file_name)
480
-		{
481
-			$info = $this->getFileObject($file_name);
482
-		}
483
-		else
484
-		{
485
-			$info = $this->getFileObjects();
486
-		}
487
-		header('Content-type: application/json');
488
-		echo json_encode($info);
489
-	}
490
-
491
-	/**
492
-	 * Output data
493
-	 *
494
-	 * @return	void
495
-	 */
496
-	public function post()
497
-	{
498
-		if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE')
499
-		{
500
-			return $this->delete();
501
-		}
502
-		$upload = isset($_FILES[$this->options['param_name']]) ?
503
-		$_FILES[$this->options['param_name']] : null;
504
-		$info = array();
505
-		if ($upload && is_array($upload['tmp_name']))
506
-		{
507
-			// param_name is an array identifier like "files[]",
508
-			// $_FILES is a multi-dimensional array:
509
-			foreach ($upload['tmp_name'] as $index => $value) {
178
+                        'thumbnail' => array(
179
+                                'upload_dir' => $dir_output . '/' . $object_ref . '/thumbs/',
180
+                                'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
181
+                                'max_width' => 80,
182
+                                'max_height' => 80
183
+                        )
184
+                )
185
+        );
186
+        if ($options) {
187
+            $this->options = array_replace_recursive($this->options, $options);
188
+        }
189
+    }
190
+
191
+    /**
192
+     *	Return full URL
193
+     *
194
+     *	@return	string			URL
195
+     */
196
+    protected function getFullUrl()
197
+    {
198
+        $https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
199
+        return
200
+        ($https ? 'https://' : 'http://').
201
+        (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
202
+        (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
203
+                ($https && $_SERVER['SERVER_PORT'] === 443 ||
204
+                        $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
205
+                        substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
206
+    }
207
+
208
+    /**
209
+     * Set delete url
210
+     *
211
+     * @param 	string	$file		Filename
212
+     * @return	void
213
+     */
214
+    protected function setFileDeleteUrl($file)
215
+    {
216
+        $file->delete_url = $this->options['script_url']
217
+        .'?file='.rawurlencode($file->name).'&fk_element='.$this->fk_element.'&element='.$this->element;
218
+        $file->delete_type = $this->options['delete_type'];
219
+        if ($file->delete_type !== 'DELETE') {
220
+            $file->delete_url .= '&_method=DELETE';
221
+        }
222
+    }
223
+
224
+    /**
225
+     * getFileObject
226
+     *
227
+     * @param	string		$file_name		Filename
228
+     * @return 	stdClass|null
229
+     */
230
+    protected function getFileObject($file_name)
231
+    {
232
+        $file_path = $this->options['upload_dir'].$file_name;
233
+        if (is_file($file_path) && $file_name[0] !== '.')
234
+        {
235
+            $file = new stdClass();
236
+            $file->name = $file_name;
237
+            $file->mime = dol_mimetype($file_name,'',2);
238
+            $file->size = filesize($file_path);
239
+            $file->url = $this->options['upload_url'].rawurlencode($file->name);
240
+            foreach($this->options['image_versions'] as $version => $options) {
241
+                if (is_file($options['upload_dir'].$file_name)) {
242
+                    $tmp=explode('.',$file->name);
243
+                    $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
244
+                }
245
+            }
246
+            $this->setFileDeleteUrl($file);
247
+            return $file;
248
+        }
249
+        return null;
250
+    }
251
+
252
+    /**
253
+     * getFileObjects
254
+     *
255
+     * @return	void
256
+     */
257
+    protected function getFileObjects()
258
+    {
259
+        return array_values(array_filter(array_map(array($this, 'getFileObject'), scandir($this->options['upload_dir']))));
260
+    }
261
+
262
+    /**
263
+     *  Create thumbs of a file uploaded. Only the "mini" thumb is generated.
264
+     *
265
+     *  @param	string	$file_name		Filename
266
+     *  @param	string	$options 		is array('max_width', 'max_height')
267
+     *  @return	boolean
268
+     */
269
+    protected function createScaledImage($file_name, $options)
270
+    {
271
+        global $maxwidthmini, $maxheightmini;
272
+
273
+        $file_path = $this->options['upload_dir'].$file_name;
274
+        $new_file_path = $options['upload_dir'].$file_name;
275
+
276
+        if (dol_mkdir($options['upload_dir']) >= 0)
277
+        {
278
+            list($img_width, $img_height) = @getimagesize($file_path);
279
+            if (!$img_width || !$img_height) {
280
+                return false;
281
+            }
282
+
283
+            $res=vignette($file_path,$maxwidthmini,$maxheightmini,'_mini');  // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
284
+
285
+            if (preg_match('/error/i',$res)) return false;
286
+            return true;
287
+        }
288
+        else
289
+        {
290
+            return false;
291
+        }
292
+    }
293
+
294
+    /**
295
+     * Enter description here ...
296
+     *
297
+     * @param 	string	$uploaded_file		Uploade file
298
+     * @param 	string	$file				File
299
+     * @param 	string	$error				Error
300
+     * @param	string	$index				Index
301
+     * @return  boolean                     True if OK, False if KO
302
+     */
303
+    protected function validate($uploaded_file, $file, $error, $index)
304
+    {
305
+        if ($error) {
306
+            $file->error = $error;
307
+            return false;
308
+        }
309
+        if (!$file->name) {
310
+            $file->error = 'missingFileName';
311
+            return false;
312
+        }
313
+        if (!preg_match($this->options['accept_file_types'], $file->name)) {
314
+            $file->error = 'acceptFileTypes';
315
+            return false;
316
+        }
317
+        if ($uploaded_file && is_uploaded_file($uploaded_file)) {
318
+            $file_size = filesize($uploaded_file);
319
+        } else {
320
+            $file_size = $_SERVER['CONTENT_LENGTH'];
321
+        }
322
+        if ($this->options['max_file_size'] && (
323
+                $file_size > $this->options['max_file_size'] ||
324
+                $file->size > $this->options['max_file_size'])
325
+        ) {
326
+            $file->error = 'maxFileSize';
327
+            return false;
328
+        }
329
+        if ($this->options['min_file_size'] &&
330
+                $file_size < $this->options['min_file_size']) {
331
+            $file->error = 'minFileSize';
332
+            return false;
333
+        }
334
+        if (is_numeric($this->options['max_number_of_files']) && (
335
+                count($this->getFileObjects()) >= $this->options['max_number_of_files'])
336
+        ) {
337
+            $file->error = 'maxNumberOfFiles';
338
+            return false;
339
+        }
340
+        list($img_width, $img_height) = @getimagesize($uploaded_file);
341
+        if (is_numeric($img_width)) {
342
+            if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
343
+                    $this->options['max_height'] && $img_height > $this->options['max_height']) {
344
+                $file->error = 'maxResolution';
345
+                return false;
346
+            }
347
+            if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
348
+                    $this->options['min_height'] && $img_height < $this->options['min_height']) {
349
+                $file->error = 'minResolution';
350
+                return false;
351
+            }
352
+        }
353
+        return true;
354
+    }
355
+
356
+    /**
357
+     * Enter description here ...
358
+     *
359
+     * @param 	int		$matches		???
360
+     * @return	string					???
361
+     */
362
+    protected function upcountNameCallback($matches)
363
+    {
364
+        $index = isset($matches[1]) ? intval($matches[1]) + 1 : 1;
365
+        $ext = isset($matches[2]) ? $matches[2] : '';
366
+        return ' ('.$index.')'.$ext;
367
+    }
368
+
369
+    /**
370
+     * Enter description here ...
371
+     *
372
+     * @param 	string		$name		???
373
+     * @return	string					???
374
+     */
375
+    protected function upcountName($name)
376
+    {
377
+        return preg_replace_callback('/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/', array($this, 'upcountNameCallback'), $name, 1);
378
+    }
379
+
380
+    /**
381
+     * trimFileName
382
+     *
383
+     * @param 	string $name		Filename
384
+     * @param 	string $type		???
385
+     * @param 	string $index		???
386
+     * @return	string
387
+     */
388
+    protected function trimFileName($name, $type, $index)
389
+    {
390
+        // Remove path information and dots around the filename, to prevent uploading
391
+        // into different directories or replacing hidden system files.
392
+        // Also remove control characters and spaces (\x00..\x20) around the filename:
393
+        $file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
394
+        // Add missing file extension for known image types:
395
+        if (strpos($file_name, '.') === false &&
396
+                preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
397
+            $file_name .= '.'.$matches[1];
398
+        }
399
+        if ($this->options['discard_aborted_uploads'])
400
+        {
401
+            while(is_file($this->options['upload_dir'].$file_name))
402
+            {
403
+                $file_name = $this->upcountName($file_name);
404
+            }
405
+        }
406
+        return $file_name;
407
+    }
408
+
409
+    /**
410
+     * handleFileUpload
411
+     *
412
+     * @param 	string		$uploaded_file		Uploade file
413
+     * @param 	string		$name				Name
414
+     * @param 	int			$size				Size
415
+     * @param 	string		$type				Type
416
+     * @param 	string		$error				Error
417
+     * @param	string		$index				Index
418
+     * @return stdClass
419
+     */
420
+    protected function handleFileUpload($uploaded_file, $name, $size, $type, $error, $index)
421
+    {
422
+        $file = new stdClass();
423
+        $file->name = $this->trimFileName($name, $type, $index);
424
+        $file->mime = dol_mimetype($file->name,'',2);
425
+        $file->size = intval($size);
426
+        $file->type = $type;
427
+        if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0)
428
+        {
429
+            $file_path = $this->options['upload_dir'].$file->name;
430
+            $append_file = !$this->options['discard_aborted_uploads'] && is_file($file_path) && $file->size > filesize($file_path);
431
+            clearstatcache();
432
+            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
433
+                // multipart/formdata uploads (POST method uploads)
434
+                if ($append_file)
435
+                {
436
+                    file_put_contents($file_path, fopen($uploaded_file, 'r'), FILE_APPEND);
437
+                } else {
438
+                    dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
439
+                }
440
+            }
441
+            else
442
+            {
443
+                // Non-multipart uploads (PUT method support)
444
+                file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
445
+            }
446
+            $file_size = filesize($file_path);
447
+            if ($file_size === $file->size)
448
+            {
449
+                $file->url = $this->options['upload_url'].rawurlencode($file->name);
450
+                foreach($this->options['image_versions'] as $version => $options)
451
+                {
452
+                    if ($this->createScaledImage($file->name, $options))
453
+                    {
454
+                        $tmp=explode('.',$file->name);
455
+                        $file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
456
+                    }
457
+                }
458
+            }
459
+            else if ($this->options['discard_aborted_uploads'])
460
+            {
461
+                unlink($file_path);
462
+                $file->error = 'abort';
463
+            }
464
+            $file->size = $file_size;
465
+            $this->setFileDeleteUrl($file);
466
+        }
467
+        return $file;
468
+    }
469
+
470
+    /**
471
+     * Output data
472
+     *
473
+     * @return	void
474
+     */
475
+    public function get()
476
+    {
477
+        $file_name = isset($_REQUEST['file']) ?
478
+        basename(stripslashes($_REQUEST['file'])) : null;
479
+        if ($file_name)
480
+        {
481
+            $info = $this->getFileObject($file_name);
482
+        }
483
+        else
484
+        {
485
+            $info = $this->getFileObjects();
486
+        }
487
+        header('Content-type: application/json');
488
+        echo json_encode($info);
489
+    }
490
+
491
+    /**
492
+     * Output data
493
+     *
494
+     * @return	void
495
+     */
496
+    public function post()
497
+    {
498
+        if (isset($_REQUEST['_method']) && $_REQUEST['_method'] === 'DELETE')
499
+        {
500
+            return $this->delete();
501
+        }
502
+        $upload = isset($_FILES[$this->options['param_name']]) ?
503
+        $_FILES[$this->options['param_name']] : null;
504
+        $info = array();
505
+        if ($upload && is_array($upload['tmp_name']))
506
+        {
507
+            // param_name is an array identifier like "files[]",
508
+            // $_FILES is a multi-dimensional array:
509
+            foreach ($upload['tmp_name'] as $index => $value) {
510 510
                 $info[] = $this->handleFileUpload(
511 511
                     $upload['tmp_name'][$index],
512 512
                     isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index],
@@ -515,10 +515,10 @@  discard block
 block discarded – undo
515 515
                     $upload['error'][$index],
516 516
                     $index
517 517
                 );
518
-			}
519
-		} elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
520
-			// param_name is a single object identifier like "file",
521
-			// $_FILES is a one-dimensional array:
518
+            }
519
+        } elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
520
+            // param_name is a single object identifier like "file",
521
+            // $_FILES is a one-dimensional array:
522 522
             $info[] = $this->handleFileUpload(
523 523
                 isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
524 524
                 isset($_SERVER['HTTP_X_FILE_NAME']) ? $_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ? $upload['name'] : null),
@@ -527,47 +527,47 @@  discard block
 block discarded – undo
527 527
                 isset($upload['error']) ? $upload['error'] : null,
528 528
                 0
529 529
             );
530
-		}
531
-		header('Vary: Accept');
532
-		$json = json_encode($info);
533
-		$redirect = isset($_REQUEST['redirect']) ?
534
-		stripslashes($_REQUEST['redirect']) : null;
535
-		if ($redirect) {
536
-			header('Location: '.sprintf($redirect, rawurlencode($json)));
537
-			return;
538
-		}
539
-		if (isset($_SERVER['HTTP_ACCEPT']) &&
540
-				(strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
541
-			header('Content-type: application/json');
542
-		} else {
543
-			header('Content-type: text/plain');
544
-		}
545
-		echo $json;
546
-	}
547
-
548
-	/**
549
-	 * Delete uploaded file
550
-	 *
551
-	 * @return	void
552
-	 */
553
-	public function delete()
554
-	{
555
-		$file_name = isset($_REQUEST['file']) ?
556
-		basename(stripslashes($_REQUEST['file'])) : null;
557
-		$file_path = $this->options['upload_dir'].$file_name;
558
-		$success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
559
-		if ($success)
560
-		{
561
-			foreach($this->options['image_versions'] as $version => $options)
562
-			{
563
-				$file = $options['upload_dir'].$file_name;
564
-				if (is_file($file))
565
-				{
566
-					unlink($file);
567
-				}
568
-			}
569
-		}
570
-		header('Content-type: application/json');
571
-		echo json_encode($success);
572
-	}
530
+        }
531
+        header('Vary: Accept');
532
+        $json = json_encode($info);
533
+        $redirect = isset($_REQUEST['redirect']) ?
534
+        stripslashes($_REQUEST['redirect']) : null;
535
+        if ($redirect) {
536
+            header('Location: '.sprintf($redirect, rawurlencode($json)));
537
+            return;
538
+        }
539
+        if (isset($_SERVER['HTTP_ACCEPT']) &&
540
+                (strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
541
+            header('Content-type: application/json');
542
+        } else {
543
+            header('Content-type: text/plain');
544
+        }
545
+        echo $json;
546
+    }
547
+
548
+    /**
549
+     * Delete uploaded file
550
+     *
551
+     * @return	void
552
+     */
553
+    public function delete()
554
+    {
555
+        $file_name = isset($_REQUEST['file']) ?
556
+        basename(stripslashes($_REQUEST['file'])) : null;
557
+        $file_path = $this->options['upload_dir'].$file_name;
558
+        $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
559
+        if ($success)
560
+        {
561
+            foreach($this->options['image_versions'] as $version => $options)
562
+            {
563
+                $file = $options['upload_dir'].$file_name;
564
+                if (is_file($file))
565
+                {
566
+                    unlink($file);
567
+                }
568
+            }
569
+        }
570
+        header('Content-type: application/json');
571
+        echo json_encode($success);
572
+    }
573 573
 }
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -41,16 +41,16 @@  discard block
 block discarded – undo
41 41
 	 * @param int		$fk_element		fk_element
42 42
 	 * @param string	$element		element
43 43
 	 */
44
-	function __construct($options=null,$fk_element=null,$element=null)
44
+	function __construct($options = null, $fk_element = null, $element = null)
45 45
 	{
46 46
 		global $db, $conf;
47 47
 		global $object;
48 48
 
49
-		$this->fk_element=$fk_element;
50
-		$this->element=$element;
49
+		$this->fk_element = $fk_element;
50
+		$this->element = $element;
51 51
 
52
-		$pathname=$filename=$element;
53
-		if (preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
52
+		$pathname = $filename = $element;
53
+		if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs))
54 54
 		{
55 55
 			$pathname = $regs[1];
56 56
 			$filename = $regs[2];
@@ -61,35 +61,35 @@  discard block
 block discarded – undo
61 61
 		// For compatibility
62 62
 		if ($element == 'propal') {
63 63
 			$pathname = 'comm/propal';
64
-			$dir_output=$conf->$element->dir_output;
64
+			$dir_output = $conf->$element->dir_output;
65 65
 		}
66 66
 		elseif ($element == 'facture') {
67 67
 			$pathname = 'compta/facture';
68
-			$dir_output=$conf->$element->dir_output;
68
+			$dir_output = $conf->$element->dir_output;
69 69
 		}
70 70
 		elseif ($element == 'project') {
71 71
 			$element = $pathname = 'projet';
72
-			$dir_output=$conf->$element->dir_output;
72
+			$dir_output = $conf->$element->dir_output;
73 73
 		}
74 74
 		elseif ($element == 'project_task') {
75
-			$pathname = 'projet'; $filename='task';
76
-			$dir_output=$conf->projet->dir_output;
75
+			$pathname = 'projet'; $filename = 'task';
76
+			$dir_output = $conf->projet->dir_output;
77 77
 			$parentForeignKey = 'fk_project';
78 78
 			$parentClass = 'Project';
79 79
 			$parentElement = 'projet';
80 80
 			$parentObject = 'project';
81 81
 		}
82 82
 		elseif ($element == 'fichinter') {
83
-			$element='ficheinter';
84
-			$dir_output=$conf->$element->dir_output;
83
+			$element = 'ficheinter';
84
+			$dir_output = $conf->$element->dir_output;
85 85
 		}
86 86
 		elseif ($element == 'order_supplier') {
87
-			$pathname = 'fourn'; $filename='fournisseur.commande';
88
-			$dir_output=$conf->fournisseur->commande->dir_output;
87
+			$pathname = 'fourn'; $filename = 'fournisseur.commande';
88
+			$dir_output = $conf->fournisseur->commande->dir_output;
89 89
 		}
90 90
 		elseif ($element == 'invoice_supplier') {
91
-			$pathname = 'fourn'; $filename='fournisseur.facture';
92
-			$dir_output=$conf->fournisseur->facture->dir_output;
91
+			$pathname = 'fourn'; $filename = 'fournisseur.facture';
92
+			$dir_output = $conf->fournisseur->facture->dir_output;
93 93
 		}
94 94
 		elseif ($element == 'product') {
95 95
 			$dir_output = $conf->product->multidir_output[$conf->entity];
@@ -98,14 +98,14 @@  discard block
 block discarded – undo
98 98
 			$dir_output = $conf->productbatch->multidir_output[$conf->entity];
99 99
 		}
100 100
 		elseif ($element == 'action') {
101
-			$pathname = 'comm/action'; $filename='actioncomm';
102
-			$dir_output=$conf->agenda->dir_output;
101
+			$pathname = 'comm/action'; $filename = 'actioncomm';
102
+			$dir_output = $conf->agenda->dir_output;
103 103
 		}
104 104
 		elseif ($element == 'chargesociales') {
105
-			$pathname = 'compta/sociales'; $filename='chargesociales';
106
-			$dir_output=$conf->tax->dir_output;
105
+			$pathname = 'compta/sociales'; $filename = 'chargesociales';
106
+			$dir_output = $conf->tax->dir_output;
107 107
 		} else {
108
-			$dir_output=$conf->$element->dir_output;
108
+			$dir_output = $conf->$element->dir_output;
109 109
 		}
110 110
 
111 111
 		dol_include_once('/'.$pathname.'/class/'.$filename.'.class.php');
@@ -135,14 +135,14 @@  discard block
 block discarded – undo
135 135
 
136 136
 		$object_ref = dol_sanitizeFileName($object->ref);
137 137
 		if ($element == 'invoice_supplier') {
138
-			$object_ref = get_exdir($object->id,2,0,0,$object,'invoice_supplier') . $object_ref;
138
+			$object_ref = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object_ref;
139 139
 		} else if ($element == 'project_task') {
140
-			$object_ref = $object->project->ref . '/' . $object_ref;
140
+			$object_ref = $object->project->ref.'/'.$object_ref;
141 141
 		}
142 142
 
143 143
 		$this->options = array(
144 144
 				'script_url' => $_SERVER['PHP_SELF'],
145
-				'upload_dir' => $dir_output . '/' . $object_ref . '/',
145
+				'upload_dir' => $dir_output.'/'.$object_ref.'/',
146 146
 				'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/',
147 147
 				'param_name' => 'files',
148 148
 				// Set the following option to 'POST', if your server does not support
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
 		),
177 177
 		*/
178 178
 						'thumbnail' => array(
179
-								'upload_dir' => $dir_output . '/' . $object_ref . '/thumbs/',
179
+								'upload_dir' => $dir_output.'/'.$object_ref.'/thumbs/',
180 180
 								'upload_url' => DOL_URL_ROOT.'/document.php?modulepart='.$element.'&attachment=1&file=/'.$object_ref.'/thumbs/',
181 181
 								'max_width' => 80,
182 182
 								'max_height' => 80
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 		(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
203 203
 				($https && $_SERVER['SERVER_PORT'] === 443 ||
204 204
 						$_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
205
-						substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
205
+						substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
206 206
 	}
207 207
 
208 208
 	/**
@@ -234,12 +234,12 @@  discard block
 block discarded – undo
234 234
 		{
235 235
 			$file = new stdClass();
236 236
 			$file->name = $file_name;
237
-			$file->mime = dol_mimetype($file_name,'',2);
237
+			$file->mime = dol_mimetype($file_name, '', 2);
238 238
 			$file->size = filesize($file_path);
239 239
 			$file->url = $this->options['upload_url'].rawurlencode($file->name);
240
-			foreach($this->options['image_versions'] as $version => $options) {
240
+			foreach ($this->options['image_versions'] as $version => $options) {
241 241
 				if (is_file($options['upload_dir'].$file_name)) {
242
-					$tmp=explode('.',$file->name);
242
+					$tmp = explode('.', $file->name);
243 243
 					$file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
244 244
 				}
245 245
 			}
@@ -280,9 +280,9 @@  discard block
 block discarded – undo
280 280
 				return false;
281 281
 			}
282 282
 
283
-			$res=vignette($file_path,$maxwidthmini,$maxheightmini,'_mini');  // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
283
+			$res = vignette($file_path, $maxwidthmini, $maxheightmini, '_mini'); // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
284 284
 
285
-			if (preg_match('/error/i',$res)) return false;
285
+			if (preg_match('/error/i', $res)) return false;
286 286
 			return true;
287 287
 		}
288 288
 		else
@@ -398,7 +398,7 @@  discard block
 block discarded – undo
398 398
 		}
399 399
 		if ($this->options['discard_aborted_uploads'])
400 400
 		{
401
-			while(is_file($this->options['upload_dir'].$file_name))
401
+			while (is_file($this->options['upload_dir'].$file_name))
402 402
 			{
403 403
 				$file_name = $this->upcountName($file_name);
404 404
 			}
@@ -421,7 +421,7 @@  discard block
 block discarded – undo
421 421
 	{
422 422
 		$file = new stdClass();
423 423
 		$file->name = $this->trimFileName($name, $type, $index);
424
-		$file->mime = dol_mimetype($file->name,'',2);
424
+		$file->mime = dol_mimetype($file->name, '', 2);
425 425
 		$file->size = intval($size);
426 426
 		$file->type = $type;
427 427
 		if ($this->validate($uploaded_file, $file, $error, $index) && dol_mkdir($this->options['upload_dir']) >= 0)
@@ -447,11 +447,11 @@  discard block
 block discarded – undo
447 447
 			if ($file_size === $file->size)
448 448
 			{
449 449
 				$file->url = $this->options['upload_url'].rawurlencode($file->name);
450
-				foreach($this->options['image_versions'] as $version => $options)
450
+				foreach ($this->options['image_versions'] as $version => $options)
451 451
 				{
452 452
 					if ($this->createScaledImage($file->name, $options))
453 453
 					{
454
-						$tmp=explode('.',$file->name);
454
+						$tmp = explode('.', $file->name);
455 455
 						$file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
456 456
 					}
457 457
 				}
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 		$success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
559 559
 		if ($success)
560 560
 		{
561
-			foreach($this->options['image_versions'] as $version => $options)
561
+			foreach ($this->options['image_versions'] as $version => $options)
562 562
 			{
563 563
 				$file = $options['upload_dir'].$file_name;
564 564
 				if (is_file($file))
Please login to merge, or discard this patch.
Braces   +17 added lines, -29 removed lines patch added patch discarded remove patch
@@ -62,46 +62,36 @@  discard block
 block discarded – undo
62 62
 		if ($element == 'propal') {
63 63
 			$pathname = 'comm/propal';
64 64
 			$dir_output=$conf->$element->dir_output;
65
-		}
66
-		elseif ($element == 'facture') {
65
+		} elseif ($element == 'facture') {
67 66
 			$pathname = 'compta/facture';
68 67
 			$dir_output=$conf->$element->dir_output;
69
-		}
70
-		elseif ($element == 'project') {
68
+		} elseif ($element == 'project') {
71 69
 			$element = $pathname = 'projet';
72 70
 			$dir_output=$conf->$element->dir_output;
73
-		}
74
-		elseif ($element == 'project_task') {
71
+		} elseif ($element == 'project_task') {
75 72
 			$pathname = 'projet'; $filename='task';
76 73
 			$dir_output=$conf->projet->dir_output;
77 74
 			$parentForeignKey = 'fk_project';
78 75
 			$parentClass = 'Project';
79 76
 			$parentElement = 'projet';
80 77
 			$parentObject = 'project';
81
-		}
82
-		elseif ($element == 'fichinter') {
78
+		} elseif ($element == 'fichinter') {
83 79
 			$element='ficheinter';
84 80
 			$dir_output=$conf->$element->dir_output;
85
-		}
86
-		elseif ($element == 'order_supplier') {
81
+		} elseif ($element == 'order_supplier') {
87 82
 			$pathname = 'fourn'; $filename='fournisseur.commande';
88 83
 			$dir_output=$conf->fournisseur->commande->dir_output;
89
-		}
90
-		elseif ($element == 'invoice_supplier') {
84
+		} elseif ($element == 'invoice_supplier') {
91 85
 			$pathname = 'fourn'; $filename='fournisseur.facture';
92 86
 			$dir_output=$conf->fournisseur->facture->dir_output;
93
-		}
94
-		elseif ($element == 'product') {
87
+		} elseif ($element == 'product') {
95 88
 			$dir_output = $conf->product->multidir_output[$conf->entity];
96
-		}
97
-		elseif ($element == 'productbatch') {
89
+		} elseif ($element == 'productbatch') {
98 90
 			$dir_output = $conf->productbatch->multidir_output[$conf->entity];
99
-		}
100
-		elseif ($element == 'action') {
91
+		} elseif ($element == 'action') {
101 92
 			$pathname = 'comm/action'; $filename='actioncomm';
102 93
 			$dir_output=$conf->agenda->dir_output;
103
-		}
104
-		elseif ($element == 'chargesociales') {
94
+		} elseif ($element == 'chargesociales') {
105 95
 			$pathname = 'compta/sociales'; $filename='chargesociales';
106 96
 			$dir_output=$conf->tax->dir_output;
107 97
 		} else {
@@ -282,10 +272,11 @@  discard block
 block discarded – undo
282 272
 
283 273
 			$res=vignette($file_path,$maxwidthmini,$maxheightmini,'_mini');  // We don't use ->addThumbs here because there is no object and we don't need all thumbs, only the "mini".
284 274
 
285
-			if (preg_match('/error/i',$res)) return false;
275
+			if (preg_match('/error/i',$res)) {
276
+			    return false;
277
+			}
286 278
 			return true;
287
-		}
288
-		else
279
+		} else
289 280
 		{
290 281
 			return false;
291 282
 		}
@@ -437,8 +428,7 @@  discard block
 block discarded – undo
437 428
 				} else {
438 429
 					dol_move_uploaded_file($uploaded_file, $file_path, 1, 0, 0, 0, 'userfile');
439 430
 				}
440
-			}
441
-			else
431
+			} else
442 432
 			{
443 433
 				// Non-multipart uploads (PUT method support)
444 434
 				file_put_contents($file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0);
@@ -455,8 +445,7 @@  discard block
 block discarded – undo
455 445
 						$file->{$version.'_url'} = $options['upload_url'].rawurlencode($tmp[0].'_mini.'.$tmp[1]);
456 446
 					}
457 447
 				}
458
-			}
459
-			else if ($this->options['discard_aborted_uploads'])
448
+			} else if ($this->options['discard_aborted_uploads'])
460 449
 			{
461 450
 				unlink($file_path);
462 451
 				$file->error = 'abort';
@@ -479,8 +468,7 @@  discard block
 block discarded – undo
479 468
 		if ($file_name)
480 469
 		{
481 470
 			$info = $this->getFileObject($file_name);
482
-		}
483
-		else
471
+		} else
484 472
 		{
485 473
 			$info = $this->getFileObjects();
486 474
 		}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/commonorder.class.php 2 patches
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -37,112 +37,112 @@
 block discarded – undo
37 37
  */
38 38
 abstract class CommonOrderLine extends CommonObjectLine
39 39
 {
40
-	/**
41
-	 * Product ref
42
-	 * @var string
43
-	 * @deprecated Use product_ref
44
-	 * @see product_ref
45
-	 */
46
-	public $ref;
47
-
48
-	/**
49
-	 * Product ref
50
-	 * @var string
51
-	 */
52
-	public $product_ref;
53
-
54
-	/**
55
-	 * Product label
56
-	 * @var string
57
-	 * @deprecated Use product_label
58
-	 * @see product_label
59
-	 */
60
-	public $libelle;
61
-
62
-	/**
63
-	 * Product label
64
-	 * @var string
65
-	 */
66
-	public $product_label;
67
-
68
-	/**
69
-	 * Product description
70
-	 * @var string
71
-	 */
72
-	public $product_desc;
73
-
74
-	/**
75
-	 * Quantity
76
-	 * @var float
77
-	 */
78
-	public $qty;
79
-
80
-	/**
81
-	 * Unit price
82
-	 * @deprecated
83
-	 * @see subprice
84
-	 */
85
-	var $price;
86
-
87
-	/**
88
-	 * Unit price before taxes
89
-	 * @var float
90
-	 */
91
-	public $subprice;
92
-
93
-	/**
94
-	 * Type of the product. 0 for product 1 for service
95
-	 * @var int
96
-	 */
97
-	public $product_type = 0;
98
-
99
-	/**
100
-	 * Description of the line
101
-	 * @var string
102
-	 */
103
-	public $desc;
104
-
105
-	/**
106
-	 * Id of corresponding product
107
-	 * @var int
108
-	 */
109
-	public $fk_product;
110
-
111
-	/**
112
-	 * Percent line discount
113
-	 * @var float
114
-	 */
115
-	public $remise_percent;
116
-
117
-	/**
118
-	 * VAT %
119
-	 * @var float
120
-	 */
121
-	public $tva_tx;
122
-
123
-	/**
124
-	 * Local tax 1 %
125
-	 * @var float
126
-	 */
127
-	public $localtax1_tx;
128
-
129
-	/**
130
-	 * Local tax 2 %
131
-	 * @var float
132
-	 */
133
-	public $localtax2_tx;
134
-
135
-	public $localtax1_type;
136
-	public $localtax2_type;
137
-
138
-	/**
139
-	 * Liste d'options cumulables:
140
-	 * Bit 0:	0 si TVA normal - 1 si TVA NPR
141
-	 * Bit 1:	0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
142
-	 * @var int
143
-	 */
144
-	public $info_bits = 0;
145
-
146
-	public $special_code = 0;
40
+    /**
41
+     * Product ref
42
+     * @var string
43
+     * @deprecated Use product_ref
44
+     * @see product_ref
45
+     */
46
+    public $ref;
47
+
48
+    /**
49
+     * Product ref
50
+     * @var string
51
+     */
52
+    public $product_ref;
53
+
54
+    /**
55
+     * Product label
56
+     * @var string
57
+     * @deprecated Use product_label
58
+     * @see product_label
59
+     */
60
+    public $libelle;
61
+
62
+    /**
63
+     * Product label
64
+     * @var string
65
+     */
66
+    public $product_label;
67
+
68
+    /**
69
+     * Product description
70
+     * @var string
71
+     */
72
+    public $product_desc;
73
+
74
+    /**
75
+     * Quantity
76
+     * @var float
77
+     */
78
+    public $qty;
79
+
80
+    /**
81
+     * Unit price
82
+     * @deprecated
83
+     * @see subprice
84
+     */
85
+    var $price;
86
+
87
+    /**
88
+     * Unit price before taxes
89
+     * @var float
90
+     */
91
+    public $subprice;
92
+
93
+    /**
94
+     * Type of the product. 0 for product 1 for service
95
+     * @var int
96
+     */
97
+    public $product_type = 0;
98
+
99
+    /**
100
+     * Description of the line
101
+     * @var string
102
+     */
103
+    public $desc;
104
+
105
+    /**
106
+     * Id of corresponding product
107
+     * @var int
108
+     */
109
+    public $fk_product;
110
+
111
+    /**
112
+     * Percent line discount
113
+     * @var float
114
+     */
115
+    public $remise_percent;
116
+
117
+    /**
118
+     * VAT %
119
+     * @var float
120
+     */
121
+    public $tva_tx;
122
+
123
+    /**
124
+     * Local tax 1 %
125
+     * @var float
126
+     */
127
+    public $localtax1_tx;
128
+
129
+    /**
130
+     * Local tax 2 %
131
+     * @var float
132
+     */
133
+    public $localtax2_tx;
134
+
135
+    public $localtax1_type;
136
+    public $localtax2_type;
137
+
138
+    /**
139
+     * Liste d'options cumulables:
140
+     * Bit 0:	0 si TVA normal - 1 si TVA NPR
141
+     * Bit 1:	0 si ligne normal - 1 si bit discount (link to line into llx_remise_except)
142
+     * @var int
143
+     */
144
+    public $info_bits = 0;
145
+
146
+    public $special_code = 0;
147 147
 }
148 148
 
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -21,8 +21,8 @@
 block discarded – undo
21 21
  *       \brief      File of the superclass of orders classes (customer and supplier)
22 22
  */
23 23
 
24
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
25
-require_once DOL_DOCUMENT_ROOT .'/core/class/commonobjectline.class.php';
24
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
25
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
26 26
 
27 27
 /**
28 28
  *      Superclass for orders classes
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formprojet.class.php 3 patches
Indentation   +616 added lines, -616 removed lines patch added patch discarded remove patch
@@ -29,660 +29,660 @@
 block discarded – undo
29 29
  */
30 30
 class FormProjets
31 31
 {
32
-	/**
32
+    /**
33 33
      * @var DoliDB Database handler.
34 34
      */
35 35
     public $db;
36 36
 
37
-	/**
38
-	 * @var string Error code (or message)
39
-	 */
40
-	public $error='';
37
+    /**
38
+     * @var string Error code (or message)
39
+     */
40
+    public $error='';
41 41
 
42 42
 
43
-	/**
44
-	 *	Constructor
45
-	 *
46
-	 *  @param		DoliDB		$db      Database handler
47
-	 */
48
-	function __construct($db)
49
-	{
50
-		$this->db = $db;
51
-	}
43
+    /**
44
+     *	Constructor
45
+     *
46
+     *  @param		DoliDB		$db      Database handler
47
+     */
48
+    function __construct($db)
49
+    {
50
+        $this->db = $db;
51
+    }
52 52
 
53 53
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
54
-	/**
55
-	 *	Output a combo list with projects qualified for a third party / user
56
-	 *
57
-	 *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
58
-	 *	@param  string	$selected   	Id project preselected ('' or id of project)
59
-	 *	@param  string	$htmlname   	Name of HTML field
60
-	 *	@param	int		$maxlength		Maximum length of label
61
-	 *	@param	int		$option_only	Return only html options lines without the select tag
62
-	 *	@param	int		$show_empty		Add an empty line
63
-	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
64
-	 *  @param	int		$forcefocus		Force focus on field (works with javascript only)
65
-	 *  @param	int		$disabled		Disabled
66
-	 *  @param  int     $mode           0 for HTML mode and 1 for JSON mode
67
-	 *  @param  string  $filterkey      Key to filter
68
-	 *  @param  int     $nooutput       No print output. Return it only.
69
-	 *  @param  int     $forceaddid     Force to add project id in list, event if not qualified
70
-	 *  @param  string  $morecss        More css
71
-	 *	@param  int     $htmlid         Html id to use instead of htmlname
72
-	 *	@return string           		Return html content
73
-	 */
74
-	function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '', $nooutput=0, $forceaddid=0, $morecss='', $htmlid='')
75
-	{
54
+    /**
55
+     *	Output a combo list with projects qualified for a third party / user
56
+     *
57
+     *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
58
+     *	@param  string	$selected   	Id project preselected ('' or id of project)
59
+     *	@param  string	$htmlname   	Name of HTML field
60
+     *	@param	int		$maxlength		Maximum length of label
61
+     *	@param	int		$option_only	Return only html options lines without the select tag
62
+     *	@param	int		$show_empty		Add an empty line
63
+     *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
64
+     *  @param	int		$forcefocus		Force focus on field (works with javascript only)
65
+     *  @param	int		$disabled		Disabled
66
+     *  @param  int     $mode           0 for HTML mode and 1 for JSON mode
67
+     *  @param  string  $filterkey      Key to filter
68
+     *  @param  int     $nooutput       No print output. Return it only.
69
+     *  @param  int     $forceaddid     Force to add project id in list, event if not qualified
70
+     *  @param  string  $morecss        More css
71
+     *	@param  int     $htmlid         Html id to use instead of htmlname
72
+     *	@return string           		Return html content
73
+     */
74
+    function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '', $nooutput=0, $forceaddid=0, $morecss='', $htmlid='')
75
+    {
76 76
         // phpcs:enable
77
-		global $langs,$conf,$form;
78
-
79
-		$out='';
80
-
81
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
82
-		{
83
-			$placeholder='';
84
-
85
-			if ($selected && empty($selected_input_value))
86
-			{
87
-				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
88
-				$project = new Project($this->db);
89
-				$project->fetch($selected);
90
-				$selected_input_value=$project->ref;
91
-			}
92
-			$urloption='socid='.$socid.'&htmlname='.$htmlname.'&discardclosed='.$discard_closed;
93
-			$out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
77
+        global $langs,$conf,$form;
78
+
79
+        $out='';
80
+
81
+        if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
82
+        {
83
+            $placeholder='';
84
+
85
+            if ($selected && empty($selected_input_value))
86
+            {
87
+                require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
88
+                $project = new Project($this->db);
89
+                $project->fetch($selected);
90
+                $selected_input_value=$project->ref;
91
+            }
92
+            $urloption='socid='.$socid.'&htmlname='.$htmlname.'&discardclosed='.$discard_closed;
93
+            $out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
94 94
 //				'update' => array(
95 95
 //					'projectid' => 'id'
96 96
 //				)
97
-			));
98
-
99
-			$out.='<input type="text" class="minwidth200'.($morecss?' '.$morecss:'').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
100
-		}
101
-		else
102
-		{
103
-			$out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
104
-		}
105
-		if ($discard_closed)
106
-		{
107
-			if (class_exists('Form'))
108
-			{
109
-				if (empty($form)) $form=new Form($this->db);
110
-				$out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
111
-			}
112
-		}
113
-
114
-		if (empty($nooutput))
115
-		{
116
-		    print $out;
117
-		    return '';
118
-		}
119
-		else return $out;
120
-	}
97
+            ));
98
+
99
+            $out.='<input type="text" class="minwidth200'.($morecss?' '.$morecss:'').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
100
+        }
101
+        else
102
+        {
103
+            $out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
104
+        }
105
+        if ($discard_closed)
106
+        {
107
+            if (class_exists('Form'))
108
+            {
109
+                if (empty($form)) $form=new Form($this->db);
110
+                $out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
111
+            }
112
+        }
113
+
114
+        if (empty($nooutput))
115
+        {
116
+            print $out;
117
+            return '';
118
+        }
119
+        else return $out;
120
+    }
121 121
 
122 122
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
123
-	/**
124
-	 * Returns an array with projects qualified for a third party
125
-	 *
126
-	 * @param  int     $socid      	       Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
127
-	 * @param  int     $selected   	       Id project preselected
128
-	 * @param  string  $htmlname   	       Nom de la zone html
129
-	 * @param  int     $maxlength          Maximum length of label
130
-	 * @param  int     $option_only	       Return only html options lines without the select tag
131
-	 * @param  int     $show_empty		   Add an empty line
132
-	 * @param  int     $discard_closed     Discard closed projects (0=Keep,1=hide completely,2=Disable)
123
+    /**
124
+     * Returns an array with projects qualified for a third party
125
+     *
126
+     * @param  int     $socid      	       Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
127
+     * @param  int     $selected   	       Id project preselected
128
+     * @param  string  $htmlname   	       Nom de la zone html
129
+     * @param  int     $maxlength          Maximum length of label
130
+     * @param  int     $option_only	       Return only html options lines without the select tag
131
+     * @param  int     $show_empty		   Add an empty line
132
+     * @param  int     $discard_closed     Discard closed projects (0=Keep,1=hide completely,2=Disable)
133 133
      * @param  int     $forcefocus		   Force focus on field (works with javascript only)
134 134
      * @param  int     $disabled           Disabled
135
-	 * @param  int     $mode               0 for HTML mode and 1 for array return (to be used by json_encode for example)
136
-	 * @param  string  $filterkey          Key to filter
137
-	 * @param  int     $nooutput           No print output. Return it only.
138
-	 * @param  int     $forceaddid         Force to add project id in list, event if not qualified
139
-	 * @param  int     $htmlid             Html id to use instead of htmlname
140
-	 * @param  string  $morecss            More CSS
141
-	 * @return int         			       Nb of project if OK, <0 if KO
142
-	 */
143
-	function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '', $nooutput=0, $forceaddid=0, $htmlid='', $morecss='maxwidth500')
144
-	{
135
+     * @param  int     $mode               0 for HTML mode and 1 for array return (to be used by json_encode for example)
136
+     * @param  string  $filterkey          Key to filter
137
+     * @param  int     $nooutput           No print output. Return it only.
138
+     * @param  int     $forceaddid         Force to add project id in list, event if not qualified
139
+     * @param  int     $htmlid             Html id to use instead of htmlname
140
+     * @param  string  $morecss            More CSS
141
+     * @return int         			       Nb of project if OK, <0 if KO
142
+     */
143
+    function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '', $nooutput=0, $forceaddid=0, $htmlid='', $morecss='maxwidth500')
144
+    {
145 145
         // phpcs:enable
146
-		global $user,$conf,$langs;
147
-
148
-		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
149
-
150
-		if (empty($htmlid)) $htmlid = $htmlname;
151
-
152
-		$out='';
153
-		$outarray=array();
154
-
155
-		$hideunselectables = false;
156
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
157
-
158
-		$projectsListId = false;
159
-		if (empty($user->rights->projet->all->lire))
160
-		{
161
-			$projectstatic=new Project($this->db);
162
-			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
163
-		}
164
-
165
-		// Search all projects
166
-		$sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name, s.name_alias';
167
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p LEFT JOIN '.MAIN_DB_PREFIX .'societe as s ON s.rowid = p.fk_soc';
168
-		$sql.= " WHERE p.entity IN (".getEntity('project').")";
169
-		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
170
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
171
-		if ($socid > 0)
172
-		{
173
-		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
174
-		    else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')    // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
175
-		    {
176
-		        $sql.= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
177
-		    }
178
-		}
179
-		if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
180
-		$sql.= " ORDER BY p.ref ASC";
181
-
182
-		$resql=$this->db->query($sql);
183
-		if ($resql)
184
-		{
185
-			// Use select2 selector
186
-			if (! empty($conf->use_javascript_ajax))
187
-			{
188
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
189
-	           	$comboenhancement = ajax_combobox($htmlid, array(), 0, $forcefocus);
190
-            	$out.=$comboenhancement;
191
-            	$morecss.=' minwidth100';
192
-			}
193
-
194
-			if (empty($option_only)) {
195
-				$out.= '<select class="flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlid.'" name="'.$htmlname.'">';
196
-			}
197
-			if (!empty($show_empty)) {
198
-				$out.= '<option value="0">&nbsp;</option>';
199
-			}
200
-			$num = $this->db->num_rows($resql);
201
-			$i = 0;
202
-			if ($num)
203
-			{
204
-				while ($i < $num)
205
-				{
206
-					$obj = $this->db->fetch_object($resql);
207
-					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
208
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
209
-					{
210
-						// Do nothing
211
-					}
212
-					else
213
-					{
214
-						if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected
215
-						{
216
-							$i++;
217
-							continue;
218
-						}
219
-
220
-						$labeltoshow=dol_trunc($obj->ref,18);
221
-						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
222
-						//else $labeltoshow.=' ('.$langs->trans("Private").')';
223
-						$labeltoshow.=', '.dol_trunc($obj->title, $maxlength);
224
-						if ($obj->name)
225
-						{
226
-						    $labeltoshow.=' - '.$obj->name;
227
-						    if ($obj->name_alias) $labeltoshow.=' ('.$obj->name_alias.')';
228
-						}
229
-
230
-						$disabled=0;
231
-						if ($obj->fk_statut == 0)
232
-						{
233
-							$disabled=1;
234
-							$labeltoshow.=' - '.$langs->trans("Draft");
235
-						}
236
-						else if ($obj->fk_statut == 2)
237
-						{
238
-							if ($discard_closed == 2) $disabled=1;
239
-							$labeltoshow.=' - '.$langs->trans("Closed");
240
-						}
241
-						else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
242
-						{
243
-							$disabled=1;
244
-							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
245
-						}
246
-
247
-						if (!empty($selected) && $selected == $obj->rowid)
248
-						{
249
-							$out.= '<option value="'.$obj->rowid.'" selected';
250
-							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
251
-							$out.= '>'.$labeltoshow.'</option>';
252
-						}
253
-						else
254
-						{
255
-							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
256
-							{
257
-								$resultat='';
258
-							}
259
-							else
260
-							{
261
-								$resultat='<option value="'.$obj->rowid.'"';
262
-								if ($disabled) $resultat.=' disabled';
263
-								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
264
-								//else $labeltoshow.=' ('.$langs->trans("Private").')';
265
-								$resultat.='>';
266
-								$resultat.=$labeltoshow;
267
-								$resultat.='</option>';
268
-							}
269
-							$out.= $resultat;
270
-
271
-							$outarray[] = array(
272
-								'key' => (int) $obj->rowid,
273
-								'value' => $obj->ref,
274
-								'ref' => $obj->ref,
275
-								'label' => $labeltoshow,
276
-								'disabled' => (bool) $disabled
277
-							);
278
-						}
279
-					}
280
-					$i++;
281
-				}
282
-			}
283
-
284
-			$this->db->free($resql);
285
-
286
-			if (!$mode) {
287
-				if (empty($option_only)) $out.= '</select>';
288
-				if (empty($nooutput))
289
-				{
290
-				    print $out;
291
-				    return '';
292
-				}
293
-				else return $out;
294
-			} else {
295
-				return $outarray;
296
-			}
297
-		}
298
-		else
299
-		{
300
-			dol_print_error($this->db);
301
-			return -1;
302
-		}
303
-	}
304
-
305
-	/**
306
-	 *	Output a combo list with tasks qualified for a third party
307
-	 *
308
-	 *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
309
-	 *	@param  int		$selected   	Id task preselected
310
-	 *	@param  string	$htmlname   	Name of HTML select
311
-	 *	@param	int		$maxlength		Maximum length of label
312
-	 *	@param	int		$option_only	Return only html options lines without the select tag
313
-	 *	@param	string	$show_empty		Add an empty line ('1' or string to show for empty line)
314
-	 *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
146
+        global $user,$conf,$langs;
147
+
148
+        require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
149
+
150
+        if (empty($htmlid)) $htmlid = $htmlname;
151
+
152
+        $out='';
153
+        $outarray=array();
154
+
155
+        $hideunselectables = false;
156
+        if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
157
+
158
+        $projectsListId = false;
159
+        if (empty($user->rights->projet->all->lire))
160
+        {
161
+            $projectstatic=new Project($this->db);
162
+            $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
163
+        }
164
+
165
+        // Search all projects
166
+        $sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name, s.name_alias';
167
+        $sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p LEFT JOIN '.MAIN_DB_PREFIX .'societe as s ON s.rowid = p.fk_soc';
168
+        $sql.= " WHERE p.entity IN (".getEntity('project').")";
169
+        if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
170
+        if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
171
+        if ($socid > 0)
172
+        {
173
+            if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
174
+            else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')    // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
175
+            {
176
+                $sql.= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
177
+            }
178
+        }
179
+        if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
180
+        $sql.= " ORDER BY p.ref ASC";
181
+
182
+        $resql=$this->db->query($sql);
183
+        if ($resql)
184
+        {
185
+            // Use select2 selector
186
+            if (! empty($conf->use_javascript_ajax))
187
+            {
188
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
189
+                    $comboenhancement = ajax_combobox($htmlid, array(), 0, $forcefocus);
190
+                $out.=$comboenhancement;
191
+                $morecss.=' minwidth100';
192
+            }
193
+
194
+            if (empty($option_only)) {
195
+                $out.= '<select class="flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlid.'" name="'.$htmlname.'">';
196
+            }
197
+            if (!empty($show_empty)) {
198
+                $out.= '<option value="0">&nbsp;</option>';
199
+            }
200
+            $num = $this->db->num_rows($resql);
201
+            $i = 0;
202
+            if ($num)
203
+            {
204
+                while ($i < $num)
205
+                {
206
+                    $obj = $this->db->fetch_object($resql);
207
+                    // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
208
+                    if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
209
+                    {
210
+                        // Do nothing
211
+                    }
212
+                    else
213
+                    {
214
+                        if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected
215
+                        {
216
+                            $i++;
217
+                            continue;
218
+                        }
219
+
220
+                        $labeltoshow=dol_trunc($obj->ref,18);
221
+                        //if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
222
+                        //else $labeltoshow.=' ('.$langs->trans("Private").')';
223
+                        $labeltoshow.=', '.dol_trunc($obj->title, $maxlength);
224
+                        if ($obj->name)
225
+                        {
226
+                            $labeltoshow.=' - '.$obj->name;
227
+                            if ($obj->name_alias) $labeltoshow.=' ('.$obj->name_alias.')';
228
+                        }
229
+
230
+                        $disabled=0;
231
+                        if ($obj->fk_statut == 0)
232
+                        {
233
+                            $disabled=1;
234
+                            $labeltoshow.=' - '.$langs->trans("Draft");
235
+                        }
236
+                        else if ($obj->fk_statut == 2)
237
+                        {
238
+                            if ($discard_closed == 2) $disabled=1;
239
+                            $labeltoshow.=' - '.$langs->trans("Closed");
240
+                        }
241
+                        else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
242
+                        {
243
+                            $disabled=1;
244
+                            $labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
245
+                        }
246
+
247
+                        if (!empty($selected) && $selected == $obj->rowid)
248
+                        {
249
+                            $out.= '<option value="'.$obj->rowid.'" selected';
250
+                            //if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
251
+                            $out.= '>'.$labeltoshow.'</option>';
252
+                        }
253
+                        else
254
+                        {
255
+                            if ($hideunselectables && $disabled && ($selected != $obj->rowid))
256
+                            {
257
+                                $resultat='';
258
+                            }
259
+                            else
260
+                            {
261
+                                $resultat='<option value="'.$obj->rowid.'"';
262
+                                if ($disabled) $resultat.=' disabled';
263
+                                //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
264
+                                //else $labeltoshow.=' ('.$langs->trans("Private").')';
265
+                                $resultat.='>';
266
+                                $resultat.=$labeltoshow;
267
+                                $resultat.='</option>';
268
+                            }
269
+                            $out.= $resultat;
270
+
271
+                            $outarray[] = array(
272
+                                'key' => (int) $obj->rowid,
273
+                                'value' => $obj->ref,
274
+                                'ref' => $obj->ref,
275
+                                'label' => $labeltoshow,
276
+                                'disabled' => (bool) $disabled
277
+                            );
278
+                        }
279
+                    }
280
+                    $i++;
281
+                }
282
+            }
283
+
284
+            $this->db->free($resql);
285
+
286
+            if (!$mode) {
287
+                if (empty($option_only)) $out.= '</select>';
288
+                if (empty($nooutput))
289
+                {
290
+                    print $out;
291
+                    return '';
292
+                }
293
+                else return $out;
294
+            } else {
295
+                return $outarray;
296
+            }
297
+        }
298
+        else
299
+        {
300
+            dol_print_error($this->db);
301
+            return -1;
302
+        }
303
+    }
304
+
305
+    /**
306
+     *	Output a combo list with tasks qualified for a third party
307
+     *
308
+     *	@param	int		$socid      	Id third party (-1=all, 0=only projects not linked to a third party, id=projects not linked or linked to third party id)
309
+     *	@param  int		$selected   	Id task preselected
310
+     *	@param  string	$htmlname   	Name of HTML select
311
+     *	@param	int		$maxlength		Maximum length of label
312
+     *	@param	int		$option_only	Return only html options lines without the select tag
313
+     *	@param	string	$show_empty		Add an empty line ('1' or string to show for empty line)
314
+     *  @param	int		$discard_closed Discard closed projects (0=Keep,1=hide completely,2=Disable)
315 315
      *  @param	int		$forcefocus		Force focus on field (works with javascript only)
316 316
      *  @param	int		$disabled		Disabled
317
-	 *  @param	string	$morecss        More css added to the select component
318
-	 *  @param	string	$projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
319
-	 *  @param	string	$showproject	'all' = Show project info, ''=Hide project info
320
-	 *  @param	User	$usertofilter	User object to use for filtering
321
-	 *	@return int         			Nbr of project if OK, <0 if KO
322
-	 */
323
-	function selectTasks($socid=-1, $selected='', $htmlname='taskid', $maxlength=24, $option_only=0, $show_empty='1', $discard_closed=0, $forcefocus=0, $disabled=0, $morecss='maxwidth500', $projectsListId='', $showproject='all', $usertofilter=null)
324
-	{
325
-		global $user,$conf,$langs;
326
-
327
-		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
328
-
329
-		if (is_null($usertofilter))
330
-		{
331
-			$usertofilter = $user;
332
-		}
333
-
334
-		$out='';
335
-
336
-		$hideunselectables = false;
337
-		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
338
-
339
-		if (empty($projectsListId))
340
-		{
341
-			if (empty($usertofilter->rights->projet->all->lire))
342
-			{
343
-				$projectstatic=new Project($this->db);
344
-				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter,0,1);
345
-			}
346
-		}
347
-
348
-		// Search all projects
349
-		$sql = 'SELECT t.rowid, t.ref as tref, t.label as tlabel, p.rowid as pid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public,';
350
-		$sql.= ' s.nom as name';
351
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
352
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
353
-		$sql.= ' '.MAIN_DB_PREFIX.'projet_task as t';
354
-		$sql.= " WHERE p.entity IN (".getEntity('project').")";
355
-		$sql.= " AND t.fk_projet = p.rowid";
356
-		if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
357
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
358
-		if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
359
-		$sql.= " ORDER BY p.ref, t.ref ASC";
360
-
361
-		$resql=$this->db->query($sql);
362
-		if ($resql)
363
-		{
364
-			// Use select2 selector
365
-			if (! empty($conf->use_javascript_ajax))
366
-			{
367
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
368
-	           	$comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
369
-            	$out.=$comboenhancement;
370
-            	$morecss='minwidth200 maxwidth500';
371
-			}
372
-
373
-			if (empty($option_only)) {
374
-				$out.= '<select class="valignmiddle flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'">';
375
-			}
376
-			if (! empty($show_empty)) {
377
-				$out.= '<option value="0" class="optiongrey">';
378
-				if (! is_numeric($show_empty)) $out.=$show_empty;
379
-				else $out.='&nbsp;';
380
-				$out.= '</option>';
381
-			}
382
-			$num = $this->db->num_rows($resql);
383
-			$i = 0;
384
-			if ($num)
385
-			{
386
-				while ($i < $num)
387
-				{
388
-					$obj = $this->db->fetch_object($resql);
389
-					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
390
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
391
-					{
392
-						// Do nothing
393
-					}
394
-					else
395
-					{
396
-						if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
397
-						{
398
-							$i++;
399
-							continue;
400
-						}
401
-
402
-						$labeltoshow = '';
403
-
404
-						if ($showproject == 'all')
405
-						{
406
-							$labeltoshow.=dol_trunc($obj->ref,18);     // Project ref
407
-							//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
408
-							//else $labeltoshow.=' ('.$langs->trans("Private").')';
409
-							$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
410
-
411
-							if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
412
-
413
-							$disabled=0;
414
-							if ($obj->fk_statut == Project::STATUS_DRAFT)
415
-							{
416
-								$disabled=1;
417
-								$labeltoshow.=' - '.$langs->trans("Draft");
418
-							}
419
-							else if ($obj->fk_statut == Project::STATUS_CLOSED)
420
-							{
421
-								if ($discard_closed == 2) $disabled=1;
422
-								$labeltoshow.=' - '.$langs->trans("Closed");
423
-							}
424
-							else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
425
-							{
426
-								$disabled=1;
427
-								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
428
-							}
429
-							$labeltoshow.=' - ';
430
-						}
431
-
432
-						// Label for task
433
-						$labeltoshow.=$obj->tref.' '.dol_trunc($obj->tlabel,$maxlength);
434
-
435
-						if (!empty($selected) && $selected == $obj->rowid)
436
-						{
437
-							$out.= '<option value="'.$obj->rowid.'" selected';
438
-							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
439
-							$out.= '>'.$labeltoshow.'</option>';
440
-						}
441
-						else
442
-						{
443
-							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
444
-							{
445
-								$resultat='';
446
-							}
447
-							else
448
-							{
449
-								$resultat='<option value="'.$obj->rowid.'"';
450
-								if ($disabled) $resultat.=' disabled';
451
-								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
452
-								//else $labeltoshow.=' ('.$langs->trans("Private").')';
453
-								$resultat.='>';
454
-								$resultat.=$labeltoshow;
455
-								$resultat.='</option>';
456
-							}
457
-							$out.= $resultat;
458
-						}
459
-					}
460
-					$i++;
461
-				}
462
-			}
463
-			if (empty($option_only)) {
464
-				$out.= '</select>';
465
-			}
466
-
467
-			print $out;
468
-
469
-			$this->db->free($resql);
470
-			return $num;
471
-		}
472
-		else
473
-		{
474
-			dol_print_error($this->db);
475
-			return -1;
476
-		}
477
-	}
317
+     *  @param	string	$morecss        More css added to the select component
318
+     *  @param	string	$projectsListId ''=Automatic filter on project allowed. List of id=Filter on project ids.
319
+     *  @param	string	$showproject	'all' = Show project info, ''=Hide project info
320
+     *  @param	User	$usertofilter	User object to use for filtering
321
+     *	@return int         			Nbr of project if OK, <0 if KO
322
+     */
323
+    function selectTasks($socid=-1, $selected='', $htmlname='taskid', $maxlength=24, $option_only=0, $show_empty='1', $discard_closed=0, $forcefocus=0, $disabled=0, $morecss='maxwidth500', $projectsListId='', $showproject='all', $usertofilter=null)
324
+    {
325
+        global $user,$conf,$langs;
326
+
327
+        require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
328
+
329
+        if (is_null($usertofilter))
330
+        {
331
+            $usertofilter = $user;
332
+        }
333
+
334
+        $out='';
335
+
336
+        $hideunselectables = false;
337
+        if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
338
+
339
+        if (empty($projectsListId))
340
+        {
341
+            if (empty($usertofilter->rights->projet->all->lire))
342
+            {
343
+                $projectstatic=new Project($this->db);
344
+                $projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter,0,1);
345
+            }
346
+        }
347
+
348
+        // Search all projects
349
+        $sql = 'SELECT t.rowid, t.ref as tref, t.label as tlabel, p.rowid as pid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public,';
350
+        $sql.= ' s.nom as name';
351
+        $sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
352
+        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
353
+        $sql.= ' '.MAIN_DB_PREFIX.'projet_task as t';
354
+        $sql.= " WHERE p.entity IN (".getEntity('project').")";
355
+        $sql.= " AND t.fk_projet = p.rowid";
356
+        if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
357
+        if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
358
+        if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
359
+        $sql.= " ORDER BY p.ref, t.ref ASC";
360
+
361
+        $resql=$this->db->query($sql);
362
+        if ($resql)
363
+        {
364
+            // Use select2 selector
365
+            if (! empty($conf->use_javascript_ajax))
366
+            {
367
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
368
+                    $comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
369
+                $out.=$comboenhancement;
370
+                $morecss='minwidth200 maxwidth500';
371
+            }
372
+
373
+            if (empty($option_only)) {
374
+                $out.= '<select class="valignmiddle flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'">';
375
+            }
376
+            if (! empty($show_empty)) {
377
+                $out.= '<option value="0" class="optiongrey">';
378
+                if (! is_numeric($show_empty)) $out.=$show_empty;
379
+                else $out.='&nbsp;';
380
+                $out.= '</option>';
381
+            }
382
+            $num = $this->db->num_rows($resql);
383
+            $i = 0;
384
+            if ($num)
385
+            {
386
+                while ($i < $num)
387
+                {
388
+                    $obj = $this->db->fetch_object($resql);
389
+                    // If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
390
+                    if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
391
+                    {
392
+                        // Do nothing
393
+                    }
394
+                    else
395
+                    {
396
+                        if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
397
+                        {
398
+                            $i++;
399
+                            continue;
400
+                        }
401
+
402
+                        $labeltoshow = '';
403
+
404
+                        if ($showproject == 'all')
405
+                        {
406
+                            $labeltoshow.=dol_trunc($obj->ref,18);     // Project ref
407
+                            //if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
408
+                            //else $labeltoshow.=' ('.$langs->trans("Private").')';
409
+                            $labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
410
+
411
+                            if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
412
+
413
+                            $disabled=0;
414
+                            if ($obj->fk_statut == Project::STATUS_DRAFT)
415
+                            {
416
+                                $disabled=1;
417
+                                $labeltoshow.=' - '.$langs->trans("Draft");
418
+                            }
419
+                            else if ($obj->fk_statut == Project::STATUS_CLOSED)
420
+                            {
421
+                                if ($discard_closed == 2) $disabled=1;
422
+                                $labeltoshow.=' - '.$langs->trans("Closed");
423
+                            }
424
+                            else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
425
+                            {
426
+                                $disabled=1;
427
+                                $labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
428
+                            }
429
+                            $labeltoshow.=' - ';
430
+                        }
431
+
432
+                        // Label for task
433
+                        $labeltoshow.=$obj->tref.' '.dol_trunc($obj->tlabel,$maxlength);
434
+
435
+                        if (!empty($selected) && $selected == $obj->rowid)
436
+                        {
437
+                            $out.= '<option value="'.$obj->rowid.'" selected';
438
+                            //if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
439
+                            $out.= '>'.$labeltoshow.'</option>';
440
+                        }
441
+                        else
442
+                        {
443
+                            if ($hideunselectables && $disabled && ($selected != $obj->rowid))
444
+                            {
445
+                                $resultat='';
446
+                            }
447
+                            else
448
+                            {
449
+                                $resultat='<option value="'.$obj->rowid.'"';
450
+                                if ($disabled) $resultat.=' disabled';
451
+                                //if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
452
+                                //else $labeltoshow.=' ('.$langs->trans("Private").')';
453
+                                $resultat.='>';
454
+                                $resultat.=$labeltoshow;
455
+                                $resultat.='</option>';
456
+                            }
457
+                            $out.= $resultat;
458
+                        }
459
+                    }
460
+                    $i++;
461
+                }
462
+            }
463
+            if (empty($option_only)) {
464
+                $out.= '</select>';
465
+            }
466
+
467
+            print $out;
468
+
469
+            $this->db->free($resql);
470
+            return $num;
471
+        }
472
+        else
473
+        {
474
+            dol_print_error($this->db);
475
+            return -1;
476
+        }
477
+    }
478 478
 
479 479
 
480 480
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
481
-	/**
482
-	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
483
-	 *
484
-	 *    @param	string		$table_element		Table of the element to update
485
-	 *    @param	string		$socid				If of thirdparty to use as filter or 'id1,id2,...'
486
-	 *    @param	string		$morecss			More CSS
487
-	 *    @param    int         $limitonstatus      Add filters to limit length of list to opened status (for example to avoid ERR_RESPONSE_HEADERS_TOO_BIG on project/element.php page). TODO To implement
488
-	 *    @param	string		$projectkey			Equivalent key  to fk_projet for actual table_element
489
-	 *    @return	int|string						The HTML select list of element or '' if nothing or -1 if KO
490
-	 */
491
-	function select_element($table_element, $socid=0, $morecss='', $limitonstatus=-2,$projectkey="fk_projet")
492
-	{
481
+    /**
482
+     *    Build a HTML select list of element of same thirdparty to suggest to link them to project
483
+     *
484
+     *    @param	string		$table_element		Table of the element to update
485
+     *    @param	string		$socid				If of thirdparty to use as filter or 'id1,id2,...'
486
+     *    @param	string		$morecss			More CSS
487
+     *    @param    int         $limitonstatus      Add filters to limit length of list to opened status (for example to avoid ERR_RESPONSE_HEADERS_TOO_BIG on project/element.php page). TODO To implement
488
+     *    @param	string		$projectkey			Equivalent key  to fk_projet for actual table_element
489
+     *    @return	int|string						The HTML select list of element or '' if nothing or -1 if KO
490
+     */
491
+    function select_element($table_element, $socid=0, $morecss='', $limitonstatus=-2,$projectkey="fk_projet")
492
+    {
493 493
         // phpcs:enable
494
-		global $conf, $langs;
495
-
496
-		if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
497
-
498
-		$linkedtothirdparty=false;
499
-		if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','payment_salary','payment_various','chargesociales'))) $linkedtothirdparty=true;
500
-
501
-		$sqlfilter='';
502
-
503
-		//print $table_element;
504
-		switch ($table_element)
505
-		{
506
-			case "loan":
507
-				$sql = "SELECT t.rowid, t.label as ref";
508
-				break;
509
-			case "facture":
510
-				$sql = "SELECT t.rowid, t.ref as ref";
511
-				break;
512
-			case "facture_fourn":
513
-				$sql = "SELECT t.rowid, t.ref, t.ref_supplier";
514
-				break;
515
-			case "commande_fourn":
516
-			case "commande_fournisseur":
517
-			    $sql = "SELECT t.rowid, t.ref, t.ref_supplier";
518
-				break;
519
-			case "facture_rec":
520
-				$sql = "SELECT t.rowid, t.titre as ref";
521
-				break;
522
-			case "actioncomm":
523
-				$sql = "SELECT t.id as rowid, t.label as ref";
524
-				$projectkey="fk_project";
525
-				break;
526
-			case "expensereport":
527
-				return '';
528
-			case "expensereport_det":
529
-				/*$sql = "SELECT rowid, '' as ref";	// table is llx_expensereport_det
494
+        global $conf, $langs;
495
+
496
+        if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
497
+
498
+        $linkedtothirdparty=false;
499
+        if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','payment_salary','payment_various','chargesociales'))) $linkedtothirdparty=true;
500
+
501
+        $sqlfilter='';
502
+
503
+        //print $table_element;
504
+        switch ($table_element)
505
+        {
506
+            case "loan":
507
+                $sql = "SELECT t.rowid, t.label as ref";
508
+                break;
509
+            case "facture":
510
+                $sql = "SELECT t.rowid, t.ref as ref";
511
+                break;
512
+            case "facture_fourn":
513
+                $sql = "SELECT t.rowid, t.ref, t.ref_supplier";
514
+                break;
515
+            case "commande_fourn":
516
+            case "commande_fournisseur":
517
+                $sql = "SELECT t.rowid, t.ref, t.ref_supplier";
518
+                break;
519
+            case "facture_rec":
520
+                $sql = "SELECT t.rowid, t.titre as ref";
521
+                break;
522
+            case "actioncomm":
523
+                $sql = "SELECT t.id as rowid, t.label as ref";
524
+                $projectkey="fk_project";
525
+                break;
526
+            case "expensereport":
527
+                return '';
528
+            case "expensereport_det":
529
+                /*$sql = "SELECT rowid, '' as ref";	// table is llx_expensereport_det
530 530
 				$projectkey="fk_projet";
531 531
 				break;*/
532
-				return '';
533
-			case "commande":
534
-		    case "contrat":
535
-			case "fichinter":
536
-			    $sql = "SELECT t.rowid, t.ref";
537
-			    break;
538
-			case 'stock_mouvement':
539
-				$sql = 'SELECT t.rowid, t.label as ref';
540
-				$projectkey='fk_origin';
541
-				break;
542
-			case "payment_salary":
543
-				$sql = "SELECT t.rowid, t.num_payment as ref";	// TODO In a future fill and use real ref field
544
-				break;
545
-			case "payment_various":
546
-				$sql = "SELECT t.rowid, t.num_payment as ref";
547
-				break;
548
-			case "chargesociales":
549
-			default:
550
-				$sql = "SELECT t.rowid, t.ref";
551
-				break;
552
-		}
553
-		if ($linkedtothirdparty) $sql.=", s.nom as name";
554
-		$sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
555
-		if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
556
-		$sql.= " WHERE ".$projectkey." is null";
557
-		if (! empty($socid) && $linkedtothirdparty)
558
-		{
559
-		    if (is_numeric($socid)) $sql.= " AND t.fk_soc=".$socid;
560
-		    else $sql.= " AND t.fk_soc IN (".$socid.")";
561
-		}
562
-		if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) $sql.= ' AND t.entity IN ('.getEntity('project').')';
563
-		if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
564
-		if ($sqlfilter) $sql.= " AND ".$sqlfilter;
565
-		$sql.= " ORDER BY ref DESC";
566
-
567
-		dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
568
-		$resql=$this->db->query($sql);
569
-		if ($resql)
570
-		{
571
-			$num = $this->db->num_rows($resql);
572
-			$i = 0;
573
-			if ($num > 0)
574
-			{
575
-				$sellist = '<select class="flat elementselect css'.$table_element.($morecss?' '.$morecss:'').'" name="elementselect">';
576
-				$sellist .='<option value="-1"></option>';
577
-				while ($i < $num)
578
-				{
579
-					$obj = $this->db->fetch_object($resql);
580
-					$ref=$obj->ref?$obj->ref:$obj->rowid;
581
-					if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
582
-					if (! empty($obj->name)) $ref.=' - '.$obj->name;
583
-					$sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
584
-					$i++;
585
-				}
586
-				$sellist .='</select>';
587
-			}
588
-			/*else
532
+                return '';
533
+            case "commande":
534
+            case "contrat":
535
+            case "fichinter":
536
+                $sql = "SELECT t.rowid, t.ref";
537
+                break;
538
+            case 'stock_mouvement':
539
+                $sql = 'SELECT t.rowid, t.label as ref';
540
+                $projectkey='fk_origin';
541
+                break;
542
+            case "payment_salary":
543
+                $sql = "SELECT t.rowid, t.num_payment as ref";	// TODO In a future fill and use real ref field
544
+                break;
545
+            case "payment_various":
546
+                $sql = "SELECT t.rowid, t.num_payment as ref";
547
+                break;
548
+            case "chargesociales":
549
+            default:
550
+                $sql = "SELECT t.rowid, t.ref";
551
+                break;
552
+        }
553
+        if ($linkedtothirdparty) $sql.=", s.nom as name";
554
+        $sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
555
+        if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
556
+        $sql.= " WHERE ".$projectkey." is null";
557
+        if (! empty($socid) && $linkedtothirdparty)
558
+        {
559
+            if (is_numeric($socid)) $sql.= " AND t.fk_soc=".$socid;
560
+            else $sql.= " AND t.fk_soc IN (".$socid.")";
561
+        }
562
+        if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) $sql.= ' AND t.entity IN ('.getEntity('project').')';
563
+        if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
564
+        if ($sqlfilter) $sql.= " AND ".$sqlfilter;
565
+        $sql.= " ORDER BY ref DESC";
566
+
567
+        dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
568
+        $resql=$this->db->query($sql);
569
+        if ($resql)
570
+        {
571
+            $num = $this->db->num_rows($resql);
572
+            $i = 0;
573
+            if ($num > 0)
574
+            {
575
+                $sellist = '<select class="flat elementselect css'.$table_element.($morecss?' '.$morecss:'').'" name="elementselect">';
576
+                $sellist .='<option value="-1"></option>';
577
+                while ($i < $num)
578
+                {
579
+                    $obj = $this->db->fetch_object($resql);
580
+                    $ref=$obj->ref?$obj->ref:$obj->rowid;
581
+                    if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
582
+                    if (! empty($obj->name)) $ref.=' - '.$obj->name;
583
+                    $sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
584
+                    $i++;
585
+                }
586
+                $sellist .='</select>';
587
+            }
588
+            /*else
589 589
 			{
590 590
 				$sellist = '<select class="flat" name="elementselect">';
591 591
 				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
592 592
 				$sellist.= '</select>';
593 593
 			}*/
594
-			$this->db->free($resql);
595
-
596
-			return $sellist;
597
-		}
598
-		else
599
-		{
600
-			dol_print_error($this->db);
601
-			$this->error=$this->db->lasterror();
602
-			$this->errors[]=$this->db->lasterror();
603
-			dol_syslog(get_class($this) . "::select_element " . $this->error, LOG_ERR);
604
-			return -1;
605
-		}
606
-	}
607
-
608
-
609
-	/**
610
-	 *    Build a HTML select list of element of same thirdparty to suggest to link them to project
611
-	 *
612
-	 *    @param   string      $htmlname           HTML name
613
-	 *    @param   string      $preselected        Preselected (int or 'all' or 'none')
614
-	 *    @param   int         $showempty          Add an empty line
615
-	 *    @param   int         $useshortlabel      Use short label
616
-	 *    @param   int         $showallnone        Add choice "All" and "None"
617
-	 *    @param   int         $showpercent        Show default probability for status
618
-	 *    @param   string      $morecss            Add more css
619
-	 *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
620
-	 */
621
-	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0, $morecss='')
622
-	{
623
-		global $conf, $langs;
624
-
625
-		$sql = "SELECT rowid, code, label, percent";
626
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
627
-		$sql.= " WHERE active = 1";
628
-		$sql.= " ORDER BY position";
629
-
630
-		$resql=$this->db->query($sql);
631
-		if ($resql)
632
-		{
633
-			$num = $this->db->num_rows($resql);
634
-			$i = 0;
635
-			if ($num > 0)
636
-			{
637
-				$sellist = '<select class="flat oppstatus'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
638
-				if ($showempty) {
594
+            $this->db->free($resql);
595
+
596
+            return $sellist;
597
+        }
598
+        else
599
+        {
600
+            dol_print_error($this->db);
601
+            $this->error=$this->db->lasterror();
602
+            $this->errors[]=$this->db->lasterror();
603
+            dol_syslog(get_class($this) . "::select_element " . $this->error, LOG_ERR);
604
+            return -1;
605
+        }
606
+    }
607
+
608
+
609
+    /**
610
+     *    Build a HTML select list of element of same thirdparty to suggest to link them to project
611
+     *
612
+     *    @param   string      $htmlname           HTML name
613
+     *    @param   string      $preselected        Preselected (int or 'all' or 'none')
614
+     *    @param   int         $showempty          Add an empty line
615
+     *    @param   int         $useshortlabel      Use short label
616
+     *    @param   int         $showallnone        Add choice "All" and "None"
617
+     *    @param   int         $showpercent        Show default probability for status
618
+     *    @param   string      $morecss            Add more css
619
+     *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
620
+     */
621
+    function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0, $morecss='')
622
+    {
623
+        global $conf, $langs;
624
+
625
+        $sql = "SELECT rowid, code, label, percent";
626
+        $sql.= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
627
+        $sql.= " WHERE active = 1";
628
+        $sql.= " ORDER BY position";
629
+
630
+        $resql=$this->db->query($sql);
631
+        if ($resql)
632
+        {
633
+            $num = $this->db->num_rows($resql);
634
+            $i = 0;
635
+            if ($num > 0)
636
+            {
637
+                $sellist = '<select class="flat oppstatus'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
638
+                if ($showempty) {
639 639
                     // Without &nbsp, strange move of screen when switching value
640 640
                     $sellist.= '<option value="-1">&nbsp;</option>';
641 641
                 }
642
-				if ($showallnone) {
642
+                if ($showallnone) {
643 643
                     $sellist.= '<option value="all"'.($preselected == 'all'?' selected="selected"':'').'>-- '.$langs->trans("OnlyOpportunitiesShort").' --</option>';
644
-				    $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>-- '.$langs->trans("OpenedOpportunitiesShort").' --</option>';
645
-				    $sellist.= '<option value="notopenedopp"'.($preselected == 'notopenedopp'?' selected="selected"':'').'>-- '.$langs->trans("NotOpenedOpportunitiesShort").' --</option>';
646
-				    $sellist.= '<option value="none"'.($preselected == 'none'?' selected="selected"':'').'>-- '.$langs->trans("NotAnOpportunityShort").' --</option>';
644
+                    $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>-- '.$langs->trans("OpenedOpportunitiesShort").' --</option>';
645
+                    $sellist.= '<option value="notopenedopp"'.($preselected == 'notopenedopp'?' selected="selected"':'').'>-- '.$langs->trans("NotOpenedOpportunitiesShort").' --</option>';
646
+                    $sellist.= '<option value="none"'.($preselected == 'none'?' selected="selected"':'').'>-- '.$langs->trans("NotAnOpportunityShort").' --</option>';
647
+                }
648
+                while ($i < $num)
649
+                {
650
+                    $obj = $this->db->fetch_object($resql);
651
+
652
+                    $sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
653
+                    if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
654
+                    $sellist .= '>';
655
+                    if ($useshortlabel)
656
+                    {
657
+                        $finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
658
+                    }
659
+                    else
660
+                    {
661
+                        $finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
662
+                        if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
663
+                    }
664
+                    $sellist .= $finallabel;
665
+                    $sellist .='</option>';
666
+                    $i++;
647 667
                 }
648
-				while ($i < $num)
649
-				{
650
-					$obj = $this->db->fetch_object($resql);
651
-
652
-					$sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
653
-					if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
654
-					$sellist .= '>';
655
-					if ($useshortlabel)
656
-					{
657
-						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
658
-					}
659
-					else
660
-					{
661
-						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
662
-						if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
663
-					}
664
-					$sellist .= $finallabel;
665
-					$sellist .='</option>';
666
-					$i++;
667
-				}
668
-				$sellist .='</select>';
669
-			}
670
-			/*else
668
+                $sellist .='</select>';
669
+            }
670
+            /*else
671 671
 			{
672 672
 				$sellist = '<select class="flat" name="elementselect">';
673 673
 				$sellist.= '<option value="0" disabled>'.$langs->trans("None").'</option>';
674 674
 				$sellist.= '</select>';
675 675
 			}*/
676
-			$this->db->free($resql);
677
-
678
-			return $sellist;
679
-		}
680
-		else
681
-		{
682
-			$this->error=$this->db->lasterror();
683
-			$this->errors[]=$this->db->lasterror();
684
-			dol_syslog(get_class($this) . "::selectOpportunityStatus " . $this->error, LOG_ERR);
685
-			return -1;
686
-		}
687
-	}
676
+            $this->db->free($resql);
677
+
678
+            return $sellist;
679
+        }
680
+        else
681
+        {
682
+            $this->error=$this->db->lasterror();
683
+            $this->errors[]=$this->db->lasterror();
684
+            dol_syslog(get_class($this) . "::selectOpportunityStatus " . $this->error, LOG_ERR);
685
+            return -1;
686
+        }
687
+    }
688 688
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -37,7 +37,7 @@  discard block
 block discarded – undo
37 37
 	/**
38 38
 	 * @var string Error code (or message)
39 39
 	 */
40
-	public $error='';
40
+	public $error = '';
41 41
 
42 42
 
43 43
 	/**
@@ -71,43 +71,43 @@  discard block
 block discarded – undo
71 71
 	 *	@param  int     $htmlid         Html id to use instead of htmlname
72 72
 	 *	@return string           		Return html content
73 73
 	 */
74
-	function select_projects($socid=-1, $selected='', $htmlname='projectid', $maxlength=16, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode = 0, $filterkey = '', $nooutput=0, $forceaddid=0, $morecss='', $htmlid='')
74
+	function select_projects($socid = -1, $selected = '', $htmlname = 'projectid', $maxlength = 16, $option_only = 0, $show_empty = 1, $discard_closed = 0, $forcefocus = 0, $disabled = 0, $mode = 0, $filterkey = '', $nooutput = 0, $forceaddid = 0, $morecss = '', $htmlid = '')
75 75
 	{
76 76
         // phpcs:enable
77
-		global $langs,$conf,$form;
77
+		global $langs, $conf, $form;
78 78
 
79
-		$out='';
79
+		$out = '';
80 80
 
81
-		if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
81
+		if (!empty($conf->use_javascript_ajax) && !empty($conf->global->PROJECT_USE_SEARCH_TO_SELECT))
82 82
 		{
83
-			$placeholder='';
83
+			$placeholder = '';
84 84
 
85 85
 			if ($selected && empty($selected_input_value))
86 86
 			{
87 87
 				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
88 88
 				$project = new Project($this->db);
89 89
 				$project->fetch($selected);
90
-				$selected_input_value=$project->ref;
90
+				$selected_input_value = $project->ref;
91 91
 			}
92
-			$urloption='socid='.$socid.'&htmlname='.$htmlname.'&discardclosed='.$discard_closed;
93
-			$out.=ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
92
+			$urloption = 'socid='.$socid.'&htmlname='.$htmlname.'&discardclosed='.$discard_closed;
93
+			$out .= ajax_autocompleter($selected, $htmlname, DOL_URL_ROOT.'/projet/ajax/projects.php', $urloption, $conf->global->PROJECT_USE_SEARCH_TO_SELECT, 0, array(
94 94
 //				'update' => array(
95 95
 //					'projectid' => 'id'
96 96
 //				)
97 97
 			));
98 98
 
99
-			$out.='<input type="text" class="minwidth200'.($morecss?' '.$morecss:'').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
99
+			$out .= '<input type="text" class="minwidth200'.($morecss ? ' '.$morecss : '').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
100 100
 		}
101 101
 		else
102 102
 		{
103
-			$out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
103
+			$out .= $this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
104 104
 		}
105 105
 		if ($discard_closed)
106 106
 		{
107 107
 			if (class_exists('Form'))
108 108
 			{
109
-				if (empty($form)) $form=new Form($this->db);
110
-				$out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
109
+				if (empty($form)) $form = new Form($this->db);
110
+				$out .= $form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
111 111
 			}
112 112
 		}
113 113
 
@@ -140,62 +140,62 @@  discard block
 block discarded – undo
140 140
 	 * @param  string  $morecss            More CSS
141 141
 	 * @return int         			       Nb of project if OK, <0 if KO
142 142
 	 */
143
-	function select_projects_list($socid=-1, $selected='', $htmlname='projectid', $maxlength=24, $option_only=0, $show_empty=1, $discard_closed=0, $forcefocus=0, $disabled=0, $mode=0, $filterkey = '', $nooutput=0, $forceaddid=0, $htmlid='', $morecss='maxwidth500')
143
+	function select_projects_list($socid = -1, $selected = '', $htmlname = 'projectid', $maxlength = 24, $option_only = 0, $show_empty = 1, $discard_closed = 0, $forcefocus = 0, $disabled = 0, $mode = 0, $filterkey = '', $nooutput = 0, $forceaddid = 0, $htmlid = '', $morecss = 'maxwidth500')
144 144
 	{
145 145
         // phpcs:enable
146
-		global $user,$conf,$langs;
146
+		global $user, $conf, $langs;
147 147
 
148 148
 		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
149 149
 
150 150
 		if (empty($htmlid)) $htmlid = $htmlname;
151 151
 
152
-		$out='';
153
-		$outarray=array();
152
+		$out = '';
153
+		$outarray = array();
154 154
 
155 155
 		$hideunselectables = false;
156
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
156
+		if (!empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
157 157
 
158 158
 		$projectsListId = false;
159 159
 		if (empty($user->rights->projet->all->lire))
160 160
 		{
161
-			$projectstatic=new Project($this->db);
162
-			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user,0,1);
161
+			$projectstatic = new Project($this->db);
162
+			$projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1);
163 163
 		}
164 164
 
165 165
 		// Search all projects
166 166
 		$sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name, s.name_alias';
167
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p LEFT JOIN '.MAIN_DB_PREFIX .'societe as s ON s.rowid = p.fk_soc';
168
-		$sql.= " WHERE p.entity IN (".getEntity('project').")";
169
-		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
170
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
167
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc';
168
+		$sql .= " WHERE p.entity IN (".getEntity('project').")";
169
+		if ($projectsListId !== false) $sql .= " AND p.rowid IN (".$projectsListId.")";
170
+		if ($socid == 0) $sql .= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
171 171
 		if ($socid > 0)
172 172
 		{
173
-		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
173
+		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql .= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
174 174
 		    else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')    // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
175 175
 		    {
176
-		        $sql.= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
176
+		        $sql .= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
177 177
 		    }
178 178
 		}
179 179
 		if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
180
-		$sql.= " ORDER BY p.ref ASC";
180
+		$sql .= " ORDER BY p.ref ASC";
181 181
 
182
-		$resql=$this->db->query($sql);
182
+		$resql = $this->db->query($sql);
183 183
 		if ($resql)
184 184
 		{
185 185
 			// Use select2 selector
186
-			if (! empty($conf->use_javascript_ajax))
186
+			if (!empty($conf->use_javascript_ajax))
187 187
 			{
188
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
188
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
189 189
 	           	$comboenhancement = ajax_combobox($htmlid, array(), 0, $forcefocus);
190
-            	$out.=$comboenhancement;
191
-            	$morecss.=' minwidth100';
190
+            	$out .= $comboenhancement;
191
+            	$morecss .= ' minwidth100';
192 192
 			}
193 193
 
194 194
 			if (empty($option_only)) {
195
-				$out.= '<select class="flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlid.'" name="'.$htmlname.'">';
195
+				$out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlid.'" name="'.$htmlname.'">';
196 196
 			}
197 197
 			if (!empty($show_empty)) {
198
-				$out.= '<option value="0">&nbsp;</option>';
198
+				$out .= '<option value="0">&nbsp;</option>';
199 199
 			}
200 200
 			$num = $this->db->num_rows($resql);
201 201
 			$i = 0;
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 				{
206 206
 					$obj = $this->db->fetch_object($resql);
207 207
 					// If we ask to filter on a company and user has no permission to see all companies and project is linked to another company, we hide project.
208
-					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
208
+					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && !$user->rights->societe->lire)
209 209
 					{
210 210
 						// Do nothing
211 211
 					}
@@ -217,56 +217,56 @@  discard block
 block discarded – undo
217 217
 							continue;
218 218
 						}
219 219
 
220
-						$labeltoshow=dol_trunc($obj->ref,18);
220
+						$labeltoshow = dol_trunc($obj->ref, 18);
221 221
 						//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
222 222
 						//else $labeltoshow.=' ('.$langs->trans("Private").')';
223
-						$labeltoshow.=', '.dol_trunc($obj->title, $maxlength);
223
+						$labeltoshow .= ', '.dol_trunc($obj->title, $maxlength);
224 224
 						if ($obj->name)
225 225
 						{
226
-						    $labeltoshow.=' - '.$obj->name;
227
-						    if ($obj->name_alias) $labeltoshow.=' ('.$obj->name_alias.')';
226
+						    $labeltoshow .= ' - '.$obj->name;
227
+						    if ($obj->name_alias) $labeltoshow .= ' ('.$obj->name_alias.')';
228 228
 						}
229 229
 
230
-						$disabled=0;
230
+						$disabled = 0;
231 231
 						if ($obj->fk_statut == 0)
232 232
 						{
233
-							$disabled=1;
234
-							$labeltoshow.=' - '.$langs->trans("Draft");
233
+							$disabled = 1;
234
+							$labeltoshow .= ' - '.$langs->trans("Draft");
235 235
 						}
236 236
 						else if ($obj->fk_statut == 2)
237 237
 						{
238
-							if ($discard_closed == 2) $disabled=1;
239
-							$labeltoshow.=' - '.$langs->trans("Closed");
238
+							if ($discard_closed == 2) $disabled = 1;
239
+							$labeltoshow .= ' - '.$langs->trans("Closed");
240 240
 						}
241
-						else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
241
+						else if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) && $socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
242 242
 						{
243
-							$disabled=1;
244
-							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
243
+							$disabled = 1;
244
+							$labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
245 245
 						}
246 246
 
247 247
 						if (!empty($selected) && $selected == $obj->rowid)
248 248
 						{
249
-							$out.= '<option value="'.$obj->rowid.'" selected';
249
+							$out .= '<option value="'.$obj->rowid.'" selected';
250 250
 							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
251
-							$out.= '>'.$labeltoshow.'</option>';
251
+							$out .= '>'.$labeltoshow.'</option>';
252 252
 						}
253 253
 						else
254 254
 						{
255 255
 							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
256 256
 							{
257
-								$resultat='';
257
+								$resultat = '';
258 258
 							}
259 259
 							else
260 260
 							{
261
-								$resultat='<option value="'.$obj->rowid.'"';
262
-								if ($disabled) $resultat.=' disabled';
261
+								$resultat = '<option value="'.$obj->rowid.'"';
262
+								if ($disabled) $resultat .= ' disabled';
263 263
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
264 264
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
265
-								$resultat.='>';
266
-								$resultat.=$labeltoshow;
267
-								$resultat.='</option>';
265
+								$resultat .= '>';
266
+								$resultat .= $labeltoshow;
267
+								$resultat .= '</option>';
268 268
 							}
269
-							$out.= $resultat;
269
+							$out .= $resultat;
270 270
 
271 271
 							$outarray[] = array(
272 272
 								'key' => (int) $obj->rowid,
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 			$this->db->free($resql);
285 285
 
286 286
 			if (!$mode) {
287
-				if (empty($option_only)) $out.= '</select>';
287
+				if (empty($option_only)) $out .= '</select>';
288 288
 				if (empty($nooutput))
289 289
 				{
290 290
 				    print $out;
@@ -320,9 +320,9 @@  discard block
 block discarded – undo
320 320
 	 *  @param	User	$usertofilter	User object to use for filtering
321 321
 	 *	@return int         			Nbr of project if OK, <0 if KO
322 322
 	 */
323
-	function selectTasks($socid=-1, $selected='', $htmlname='taskid', $maxlength=24, $option_only=0, $show_empty='1', $discard_closed=0, $forcefocus=0, $disabled=0, $morecss='maxwidth500', $projectsListId='', $showproject='all', $usertofilter=null)
323
+	function selectTasks($socid = -1, $selected = '', $htmlname = 'taskid', $maxlength = 24, $option_only = 0, $show_empty = '1', $discard_closed = 0, $forcefocus = 0, $disabled = 0, $morecss = 'maxwidth500', $projectsListId = '', $showproject = 'all', $usertofilter = null)
324 324
 	{
325
-		global $user,$conf,$langs;
325
+		global $user, $conf, $langs;
326 326
 
327 327
 		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
328 328
 
@@ -331,53 +331,53 @@  discard block
 block discarded – undo
331 331
 			$usertofilter = $user;
332 332
 		}
333 333
 
334
-		$out='';
334
+		$out = '';
335 335
 
336 336
 		$hideunselectables = false;
337
-		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
337
+		if (!empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
338 338
 
339 339
 		if (empty($projectsListId))
340 340
 		{
341 341
 			if (empty($usertofilter->rights->projet->all->lire))
342 342
 			{
343
-				$projectstatic=new Project($this->db);
344
-				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter,0,1);
343
+				$projectstatic = new Project($this->db);
344
+				$projectsListId = $projectstatic->getProjectsAuthorizedForUser($usertofilter, 0, 1);
345 345
 			}
346 346
 		}
347 347
 
348 348
 		// Search all projects
349 349
 		$sql = 'SELECT t.rowid, t.ref as tref, t.label as tlabel, p.rowid as pid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public,';
350
-		$sql.= ' s.nom as name';
351
-		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p';
352
-		$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
353
-		$sql.= ' '.MAIN_DB_PREFIX.'projet_task as t';
354
-		$sql.= " WHERE p.entity IN (".getEntity('project').")";
355
-		$sql.= " AND t.fk_projet = p.rowid";
356
-		if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
357
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
358
-		if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
359
-		$sql.= " ORDER BY p.ref, t.ref ASC";
360
-
361
-		$resql=$this->db->query($sql);
350
+		$sql .= ' s.nom as name';
351
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'projet as p';
352
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = p.fk_soc,';
353
+		$sql .= ' '.MAIN_DB_PREFIX.'projet_task as t';
354
+		$sql .= " WHERE p.entity IN (".getEntity('project').")";
355
+		$sql .= " AND t.fk_projet = p.rowid";
356
+		if ($projectsListId) $sql .= " AND p.rowid IN (".$projectsListId.")";
357
+		if ($socid == 0) $sql .= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
358
+		if ($socid > 0)  $sql .= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
359
+		$sql .= " ORDER BY p.ref, t.ref ASC";
360
+
361
+		$resql = $this->db->query($sql);
362 362
 		if ($resql)
363 363
 		{
364 364
 			// Use select2 selector
365
-			if (! empty($conf->use_javascript_ajax))
365
+			if (!empty($conf->use_javascript_ajax))
366 366
 			{
367
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
367
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
368 368
 	           	$comboenhancement = ajax_combobox($htmlname, '', 0, $forcefocus);
369
-            	$out.=$comboenhancement;
370
-            	$morecss='minwidth200 maxwidth500';
369
+            	$out .= $comboenhancement;
370
+            	$morecss = 'minwidth200 maxwidth500';
371 371
 			}
372 372
 
373 373
 			if (empty($option_only)) {
374
-				$out.= '<select class="valignmiddle flat'.($morecss?' '.$morecss:'').'"'.($disabled?' disabled="disabled"':'').' id="'.$htmlname.'" name="'.$htmlname.'">';
374
+				$out .= '<select class="valignmiddle flat'.($morecss ? ' '.$morecss : '').'"'.($disabled ? ' disabled="disabled"' : '').' id="'.$htmlname.'" name="'.$htmlname.'">';
375 375
 			}
376
-			if (! empty($show_empty)) {
377
-				$out.= '<option value="0" class="optiongrey">';
378
-				if (! is_numeric($show_empty)) $out.=$show_empty;
379
-				else $out.='&nbsp;';
380
-				$out.= '</option>';
376
+			if (!empty($show_empty)) {
377
+				$out .= '<option value="0" class="optiongrey">';
378
+				if (!is_numeric($show_empty)) $out .= $show_empty;
379
+				else $out .= '&nbsp;';
380
+				$out .= '</option>';
381 381
 			}
382 382
 			$num = $this->db->num_rows($resql);
383 383
 			$i = 0;
@@ -403,65 +403,65 @@  discard block
 block discarded – undo
403 403
 
404 404
 						if ($showproject == 'all')
405 405
 						{
406
-							$labeltoshow.=dol_trunc($obj->ref,18);     // Project ref
406
+							$labeltoshow .= dol_trunc($obj->ref, 18); // Project ref
407 407
 							//if ($obj->public) $labeltoshow.=' ('.$langs->trans("SharedProject").')';
408 408
 							//else $labeltoshow.=' ('.$langs->trans("Private").')';
409
-							$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
409
+							$labeltoshow .= ' '.dol_trunc($obj->title, $maxlength);
410 410
 
411
-							if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
411
+							if ($obj->name) $labeltoshow .= ' ('.$obj->name.')';
412 412
 
413
-							$disabled=0;
413
+							$disabled = 0;
414 414
 							if ($obj->fk_statut == Project::STATUS_DRAFT)
415 415
 							{
416
-								$disabled=1;
417
-								$labeltoshow.=' - '.$langs->trans("Draft");
416
+								$disabled = 1;
417
+								$labeltoshow .= ' - '.$langs->trans("Draft");
418 418
 							}
419 419
 							else if ($obj->fk_statut == Project::STATUS_CLOSED)
420 420
 							{
421
-								if ($discard_closed == 2) $disabled=1;
422
-								$labeltoshow.=' - '.$langs->trans("Closed");
421
+								if ($discard_closed == 2) $disabled = 1;
422
+								$labeltoshow .= ' - '.$langs->trans("Closed");
423 423
 							}
424
-							else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
424
+							else if ($socid > 0 && (!empty($obj->fk_soc) && $obj->fk_soc != $socid))
425 425
 							{
426
-								$disabled=1;
427
-								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
426
+								$disabled = 1;
427
+								$labeltoshow .= ' - '.$langs->trans("LinkedToAnotherCompany");
428 428
 							}
429
-							$labeltoshow.=' - ';
429
+							$labeltoshow .= ' - ';
430 430
 						}
431 431
 
432 432
 						// Label for task
433
-						$labeltoshow.=$obj->tref.' '.dol_trunc($obj->tlabel,$maxlength);
433
+						$labeltoshow .= $obj->tref.' '.dol_trunc($obj->tlabel, $maxlength);
434 434
 
435 435
 						if (!empty($selected) && $selected == $obj->rowid)
436 436
 						{
437
-							$out.= '<option value="'.$obj->rowid.'" selected';
437
+							$out .= '<option value="'.$obj->rowid.'" selected';
438 438
 							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
439
-							$out.= '>'.$labeltoshow.'</option>';
439
+							$out .= '>'.$labeltoshow.'</option>';
440 440
 						}
441 441
 						else
442 442
 						{
443 443
 							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
444 444
 							{
445
-								$resultat='';
445
+								$resultat = '';
446 446
 							}
447 447
 							else
448 448
 							{
449
-								$resultat='<option value="'.$obj->rowid.'"';
450
-								if ($disabled) $resultat.=' disabled';
449
+								$resultat = '<option value="'.$obj->rowid.'"';
450
+								if ($disabled) $resultat .= ' disabled';
451 451
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
452 452
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
453
-								$resultat.='>';
454
-								$resultat.=$labeltoshow;
455
-								$resultat.='</option>';
453
+								$resultat .= '>';
454
+								$resultat .= $labeltoshow;
455
+								$resultat .= '</option>';
456 456
 							}
457
-							$out.= $resultat;
457
+							$out .= $resultat;
458 458
 						}
459 459
 					}
460 460
 					$i++;
461 461
 				}
462 462
 			}
463 463
 			if (empty($option_only)) {
464
-				$out.= '</select>';
464
+				$out .= '</select>';
465 465
 			}
466 466
 
467 467
 			print $out;
@@ -488,17 +488,17 @@  discard block
 block discarded – undo
488 488
 	 *    @param	string		$projectkey			Equivalent key  to fk_projet for actual table_element
489 489
 	 *    @return	int|string						The HTML select list of element or '' if nothing or -1 if KO
490 490
 	 */
491
-	function select_element($table_element, $socid=0, $morecss='', $limitonstatus=-2,$projectkey="fk_projet")
491
+	function select_element($table_element, $socid = 0, $morecss = '', $limitonstatus = -2, $projectkey = "fk_projet")
492 492
 	{
493 493
         // phpcs:enable
494 494
 		global $conf, $langs;
495 495
 
496
-		if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
496
+		if ($table_element == 'projet_task') return ''; // Special cas of element we never link to a project (already always done)
497 497
 
498
-		$linkedtothirdparty=false;
499
-		if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','payment_salary','payment_various','chargesociales'))) $linkedtothirdparty=true;
498
+		$linkedtothirdparty = false;
499
+		if (!in_array($table_element, array('don', 'expensereport_det', 'expensereport', 'loan', 'stock_mouvement', 'payment_salary', 'payment_various', 'chargesociales'))) $linkedtothirdparty = true;
500 500
 
501
-		$sqlfilter='';
501
+		$sqlfilter = '';
502 502
 
503 503
 		//print $table_element;
504 504
 		switch ($table_element)
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 				break;
522 522
 			case "actioncomm":
523 523
 				$sql = "SELECT t.id as rowid, t.label as ref";
524
-				$projectkey="fk_project";
524
+				$projectkey = "fk_project";
525 525
 				break;
526 526
 			case "expensereport":
527 527
 				return '';
@@ -537,10 +537,10 @@  discard block
 block discarded – undo
537 537
 			    break;
538 538
 			case 'stock_mouvement':
539 539
 				$sql = 'SELECT t.rowid, t.label as ref';
540
-				$projectkey='fk_origin';
540
+				$projectkey = 'fk_origin';
541 541
 				break;
542 542
 			case "payment_salary":
543
-				$sql = "SELECT t.rowid, t.num_payment as ref";	// TODO In a future fill and use real ref field
543
+				$sql = "SELECT t.rowid, t.num_payment as ref"; // TODO In a future fill and use real ref field
544 544
 				break;
545 545
 			case "payment_various":
546 546
 				$sql = "SELECT t.rowid, t.num_payment as ref";
@@ -550,40 +550,40 @@  discard block
 block discarded – undo
550 550
 				$sql = "SELECT t.rowid, t.ref";
551 551
 				break;
552 552
 		}
553
-		if ($linkedtothirdparty) $sql.=", s.nom as name";
554
-		$sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
555
-		if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
556
-		$sql.= " WHERE ".$projectkey." is null";
557
-		if (! empty($socid) && $linkedtothirdparty)
553
+		if ($linkedtothirdparty) $sql .= ", s.nom as name";
554
+		$sql .= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
555
+		if ($linkedtothirdparty) $sql .= ", ".MAIN_DB_PREFIX."societe as s";
556
+		$sql .= " WHERE ".$projectkey." is null";
557
+		if (!empty($socid) && $linkedtothirdparty)
558 558
 		{
559
-		    if (is_numeric($socid)) $sql.= " AND t.fk_soc=".$socid;
560
-		    else $sql.= " AND t.fk_soc IN (".$socid.")";
559
+		    if (is_numeric($socid)) $sql .= " AND t.fk_soc=".$socid;
560
+		    else $sql .= " AND t.fk_soc IN (".$socid.")";
561 561
 		}
562
-		if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) $sql.= ' AND t.entity IN ('.getEntity('project').')';
563
-		if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
564
-		if ($sqlfilter) $sql.= " AND ".$sqlfilter;
565
-		$sql.= " ORDER BY ref DESC";
562
+		if (!in_array($table_element, array('expensereport_det', 'stock_mouvement'))) $sql .= ' AND t.entity IN ('.getEntity('project').')';
563
+		if ($linkedtothirdparty) $sql .= " AND s.rowid = t.fk_soc";
564
+		if ($sqlfilter) $sql .= " AND ".$sqlfilter;
565
+		$sql .= " ORDER BY ref DESC";
566 566
 
567 567
 		dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
568
-		$resql=$this->db->query($sql);
568
+		$resql = $this->db->query($sql);
569 569
 		if ($resql)
570 570
 		{
571 571
 			$num = $this->db->num_rows($resql);
572 572
 			$i = 0;
573 573
 			if ($num > 0)
574 574
 			{
575
-				$sellist = '<select class="flat elementselect css'.$table_element.($morecss?' '.$morecss:'').'" name="elementselect">';
576
-				$sellist .='<option value="-1"></option>';
575
+				$sellist = '<select class="flat elementselect css'.$table_element.($morecss ? ' '.$morecss : '').'" name="elementselect">';
576
+				$sellist .= '<option value="-1"></option>';
577 577
 				while ($i < $num)
578 578
 				{
579 579
 					$obj = $this->db->fetch_object($resql);
580
-					$ref=$obj->ref?$obj->ref:$obj->rowid;
581
-					if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
582
-					if (! empty($obj->name)) $ref.=' - '.$obj->name;
583
-					$sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
580
+					$ref = $obj->ref ? $obj->ref : $obj->rowid;
581
+					if (!empty($obj->ref_supplier)) $ref .= ' ('.$obj->ref_supplier.')';
582
+					if (!empty($obj->name)) $ref .= ' - '.$obj->name;
583
+					$sellist .= '<option value="'.$obj->rowid.'">'.$ref.'</option>';
584 584
 					$i++;
585 585
 				}
586
-				$sellist .='</select>';
586
+				$sellist .= '</select>';
587 587
 			}
588 588
 			/*else
589 589
 			{
@@ -598,9 +598,9 @@  discard block
 block discarded – undo
598 598
 		else
599 599
 		{
600 600
 			dol_print_error($this->db);
601
-			$this->error=$this->db->lasterror();
602
-			$this->errors[]=$this->db->lasterror();
603
-			dol_syslog(get_class($this) . "::select_element " . $this->error, LOG_ERR);
601
+			$this->error = $this->db->lasterror();
602
+			$this->errors[] = $this->db->lasterror();
603
+			dol_syslog(get_class($this)."::select_element ".$this->error, LOG_ERR);
604 604
 			return -1;
605 605
 		}
606 606
 	}
@@ -618,38 +618,38 @@  discard block
 block discarded – undo
618 618
 	 *    @param   string      $morecss            Add more css
619 619
 	 *    @return  int|string                      The HTML select list of element or '' if nothing or -1 if KO
620 620
 	 */
621
-	function selectOpportunityStatus($htmlname, $preselected='-1', $showempty=1, $useshortlabel=0, $showallnone=0, $showpercent=0, $morecss='')
621
+	function selectOpportunityStatus($htmlname, $preselected = '-1', $showempty = 1, $useshortlabel = 0, $showallnone = 0, $showpercent = 0, $morecss = '')
622 622
 	{
623 623
 		global $conf, $langs;
624 624
 
625 625
 		$sql = "SELECT rowid, code, label, percent";
626
-		$sql.= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
627
-		$sql.= " WHERE active = 1";
628
-		$sql.= " ORDER BY position";
626
+		$sql .= " FROM ".MAIN_DB_PREFIX.'c_lead_status';
627
+		$sql .= " WHERE active = 1";
628
+		$sql .= " ORDER BY position";
629 629
 
630
-		$resql=$this->db->query($sql);
630
+		$resql = $this->db->query($sql);
631 631
 		if ($resql)
632 632
 		{
633 633
 			$num = $this->db->num_rows($resql);
634 634
 			$i = 0;
635 635
 			if ($num > 0)
636 636
 			{
637
-				$sellist = '<select class="flat oppstatus'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
637
+				$sellist = '<select class="flat oppstatus'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
638 638
 				if ($showempty) {
639 639
                     // Without &nbsp, strange move of screen when switching value
640
-                    $sellist.= '<option value="-1">&nbsp;</option>';
640
+                    $sellist .= '<option value="-1">&nbsp;</option>';
641 641
                 }
642 642
 				if ($showallnone) {
643
-                    $sellist.= '<option value="all"'.($preselected == 'all'?' selected="selected"':'').'>-- '.$langs->trans("OnlyOpportunitiesShort").' --</option>';
644
-				    $sellist.= '<option value="openedopp"'.($preselected == 'openedopp'?' selected="selected"':'').'>-- '.$langs->trans("OpenedOpportunitiesShort").' --</option>';
645
-				    $sellist.= '<option value="notopenedopp"'.($preselected == 'notopenedopp'?' selected="selected"':'').'>-- '.$langs->trans("NotOpenedOpportunitiesShort").' --</option>';
646
-				    $sellist.= '<option value="none"'.($preselected == 'none'?' selected="selected"':'').'>-- '.$langs->trans("NotAnOpportunityShort").' --</option>';
643
+                    $sellist .= '<option value="all"'.($preselected == 'all' ? ' selected="selected"' : '').'>-- '.$langs->trans("OnlyOpportunitiesShort").' --</option>';
644
+				    $sellist .= '<option value="openedopp"'.($preselected == 'openedopp' ? ' selected="selected"' : '').'>-- '.$langs->trans("OpenedOpportunitiesShort").' --</option>';
645
+				    $sellist .= '<option value="notopenedopp"'.($preselected == 'notopenedopp' ? ' selected="selected"' : '').'>-- '.$langs->trans("NotOpenedOpportunitiesShort").' --</option>';
646
+				    $sellist .= '<option value="none"'.($preselected == 'none' ? ' selected="selected"' : '').'>-- '.$langs->trans("NotAnOpportunityShort").' --</option>';
647 647
                 }
648 648
 				while ($i < $num)
649 649
 				{
650 650
 					$obj = $this->db->fetch_object($resql);
651 651
 
652
-					$sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
652
+					$sellist .= '<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
653 653
 					if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
654 654
 					$sellist .= '>';
655 655
 					if ($useshortlabel)
@@ -659,13 +659,13 @@  discard block
 block discarded – undo
659 659
 					else
660 660
 					{
661 661
 						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
662
-						if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
662
+						if ($showpercent) $finallabel .= ' ('.$obj->percent.'%)';
663 663
 					}
664 664
 					$sellist .= $finallabel;
665
-					$sellist .='</option>';
665
+					$sellist .= '</option>';
666 666
 					$i++;
667 667
 				}
668
-				$sellist .='</select>';
668
+				$sellist .= '</select>';
669 669
 			}
670 670
 			/*else
671 671
 			{
@@ -679,9 +679,9 @@  discard block
 block discarded – undo
679 679
 		}
680 680
 		else
681 681
 		{
682
-			$this->error=$this->db->lasterror();
683
-			$this->errors[]=$this->db->lasterror();
684
-			dol_syslog(get_class($this) . "::selectOpportunityStatus " . $this->error, LOG_ERR);
682
+			$this->error = $this->db->lasterror();
683
+			$this->errors[] = $this->db->lasterror();
684
+			dol_syslog(get_class($this)."::selectOpportunityStatus ".$this->error, LOG_ERR);
685 685
 			return -1;
686 686
 		}
687 687
 	}
Please login to merge, or discard this patch.
Braces   +123 added lines, -69 removed lines patch added patch discarded remove patch
@@ -97,8 +97,7 @@  discard block
 block discarded – undo
97 97
 			));
98 98
 
99 99
 			$out.='<input type="text" class="minwidth200'.($morecss?' '.$morecss:'').'" name="search_'.$htmlname.'" id="search_'.$htmlname.'" value="'.$selected_input_value.'"'.$placeholder.' />';
100
-		}
101
-		else
100
+		} else
102 101
 		{
103 102
 			$out.=$this->select_projects_list($socid, $selected, $htmlname, $maxlength, $option_only, $show_empty, $discard_closed, $forcefocus, $disabled, 0, $filterkey, 1, $forceaddid, $htmlid, $morecss);
104 103
 		}
@@ -106,7 +105,9 @@  discard block
 block discarded – undo
106 105
 		{
107 106
 			if (class_exists('Form'))
108 107
 			{
109
-				if (empty($form)) $form=new Form($this->db);
108
+				if (empty($form)) {
109
+				    $form=new Form($this->db);
110
+				}
110 111
 				$out.=$form->textwithpicto('', $langs->trans("ClosedProjectsAreHidden"));
111 112
 			}
112 113
 		}
@@ -115,8 +116,9 @@  discard block
 block discarded – undo
115 116
 		{
116 117
 		    print $out;
117 118
 		    return '';
119
+		} else {
120
+		    return $out;
118 121
 		}
119
-		else return $out;
120 122
 	}
121 123
 
122 124
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -147,13 +149,17 @@  discard block
 block discarded – undo
147 149
 
148 150
 		require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
149 151
 
150
-		if (empty($htmlid)) $htmlid = $htmlname;
152
+		if (empty($htmlid)) {
153
+		    $htmlid = $htmlname;
154
+		}
151 155
 
152 156
 		$out='';
153 157
 		$outarray=array();
154 158
 
155 159
 		$hideunselectables = false;
156
-		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) $hideunselectables = true;
160
+		if (! empty($conf->global->CONTRACT_HIDE_UNSELECTABLES)) {
161
+		    $hideunselectables = true;
162
+		}
157 163
 
158 164
 		$projectsListId = false;
159 165
 		if (empty($user->rights->projet->all->lire))
@@ -166,17 +172,26 @@  discard block
 block discarded – undo
166 172
 		$sql = 'SELECT p.rowid, p.ref, p.title, p.fk_soc, p.fk_statut, p.public, s.nom as name, s.name_alias';
167 173
 		$sql.= ' FROM '.MAIN_DB_PREFIX .'projet as p LEFT JOIN '.MAIN_DB_PREFIX .'societe as s ON s.rowid = p.fk_soc';
168 174
 		$sql.= " WHERE p.entity IN (".getEntity('project').")";
169
-		if ($projectsListId !== false) $sql.= " AND p.rowid IN (".$projectsListId.")";
170
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
175
+		if ($projectsListId !== false) {
176
+		    $sql.= " AND p.rowid IN (".$projectsListId.")";
177
+		}
178
+		if ($socid == 0) {
179
+		    $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
180
+		}
171 181
 		if ($socid > 0)
172 182
 		{
173
-		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY))  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
174
-		    else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all')    // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
183
+		    if (empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY)) {
184
+		        $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
185
+		    } else if ($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY != 'all') {
186
+		        // PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY is 'all' or a list of ids separated by coma.
175 187
 		    {
176 188
 		        $sql.= " AND (p.fk_soc IN (".$socid.", ".$conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY.") OR p.fk_soc IS NULL)";
177 189
 		    }
190
+		    }
191
+		}
192
+		if (!empty($filterkey)) {
193
+		    $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
178 194
 		}
179
-		if (!empty($filterkey)) $sql .= natural_search(array('p.title', 'p.ref'), $filterkey);
180 195
 		$sql.= " ORDER BY p.ref ASC";
181 196
 
182 197
 		$resql=$this->db->query($sql);
@@ -208,12 +223,13 @@  discard block
 block discarded – undo
208 223
 					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && ! $user->rights->societe->lire)
209 224
 					{
210 225
 						// Do nothing
211
-					}
212
-					else
226
+					} else
213 227
 					{
214
-						if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) // We discard closed except if selected
228
+						if ($discard_closed == 1 && $obj->fk_statut == 2 && $obj->rowid != $selected) {
229
+						    // We discard closed except if selected
215 230
 						{
216 231
 							$i++;
232
+						}
217 233
 							continue;
218 234
 						}
219 235
 
@@ -224,7 +240,9 @@  discard block
 block discarded – undo
224 240
 						if ($obj->name)
225 241
 						{
226 242
 						    $labeltoshow.=' - '.$obj->name;
227
-						    if ($obj->name_alias) $labeltoshow.=' ('.$obj->name_alias.')';
243
+						    if ($obj->name_alias) {
244
+						        $labeltoshow.=' ('.$obj->name_alias.')';
245
+						    }
228 246
 						}
229 247
 
230 248
 						$disabled=0;
@@ -232,13 +250,13 @@  discard block
 block discarded – undo
232 250
 						{
233 251
 							$disabled=1;
234 252
 							$labeltoshow.=' - '.$langs->trans("Draft");
235
-						}
236
-						else if ($obj->fk_statut == 2)
253
+						} else if ($obj->fk_statut == 2)
237 254
 						{
238
-							if ($discard_closed == 2) $disabled=1;
255
+							if ($discard_closed == 2) {
256
+							    $disabled=1;
257
+							}
239 258
 							$labeltoshow.=' - '.$langs->trans("Closed");
240
-						}
241
-						else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
259
+						} else if ( empty($conf->global->PROJECT_ALLOW_TO_LINK_FROM_OTHER_COMPANY) &&  $socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
242 260
 						{
243 261
 							$disabled=1;
244 262
 							$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
@@ -249,17 +267,17 @@  discard block
 block discarded – undo
249 267
 							$out.= '<option value="'.$obj->rowid.'" selected';
250 268
 							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
251 269
 							$out.= '>'.$labeltoshow.'</option>';
252
-						}
253
-						else
270
+						} else
254 271
 						{
255 272
 							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
256 273
 							{
257 274
 								$resultat='';
258
-							}
259
-							else
275
+							} else
260 276
 							{
261 277
 								$resultat='<option value="'.$obj->rowid.'"';
262
-								if ($disabled) $resultat.=' disabled';
278
+								if ($disabled) {
279
+								    $resultat.=' disabled';
280
+								}
263 281
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
264 282
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
265 283
 								$resultat.='>';
@@ -284,18 +302,20 @@  discard block
 block discarded – undo
284 302
 			$this->db->free($resql);
285 303
 
286 304
 			if (!$mode) {
287
-				if (empty($option_only)) $out.= '</select>';
305
+				if (empty($option_only)) {
306
+				    $out.= '</select>';
307
+				}
288 308
 				if (empty($nooutput))
289 309
 				{
290 310
 				    print $out;
291 311
 				    return '';
312
+				} else {
313
+				    return $out;
292 314
 				}
293
-				else return $out;
294 315
 			} else {
295 316
 				return $outarray;
296 317
 			}
297
-		}
298
-		else
318
+		} else
299 319
 		{
300 320
 			dol_print_error($this->db);
301 321
 			return -1;
@@ -334,7 +354,9 @@  discard block
 block discarded – undo
334 354
 		$out='';
335 355
 
336 356
 		$hideunselectables = false;
337
-		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) $hideunselectables = true;
357
+		if (! empty($conf->global->PROJECT_HIDE_UNSELECTABLES)) {
358
+		    $hideunselectables = true;
359
+		}
338 360
 
339 361
 		if (empty($projectsListId))
340 362
 		{
@@ -353,9 +375,15 @@  discard block
 block discarded – undo
353 375
 		$sql.= ' '.MAIN_DB_PREFIX.'projet_task as t';
354 376
 		$sql.= " WHERE p.entity IN (".getEntity('project').")";
355 377
 		$sql.= " AND t.fk_projet = p.rowid";
356
-		if ($projectsListId) $sql.= " AND p.rowid IN (".$projectsListId.")";
357
-		if ($socid == 0) $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
358
-		if ($socid > 0)  $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
378
+		if ($projectsListId) {
379
+		    $sql.= " AND p.rowid IN (".$projectsListId.")";
380
+		}
381
+		if ($socid == 0) {
382
+		    $sql.= " AND (p.fk_soc=0 OR p.fk_soc IS NULL)";
383
+		}
384
+		if ($socid > 0) {
385
+		    $sql.= " AND (p.fk_soc=".$socid." OR p.fk_soc IS NULL)";
386
+		}
359 387
 		$sql.= " ORDER BY p.ref, t.ref ASC";
360 388
 
361 389
 		$resql=$this->db->query($sql);
@@ -375,8 +403,11 @@  discard block
 block discarded – undo
375 403
 			}
376 404
 			if (! empty($show_empty)) {
377 405
 				$out.= '<option value="0" class="optiongrey">';
378
-				if (! is_numeric($show_empty)) $out.=$show_empty;
379
-				else $out.='&nbsp;';
406
+				if (! is_numeric($show_empty)) {
407
+				    $out.=$show_empty;
408
+				} else {
409
+				    $out.='&nbsp;';
410
+				}
380 411
 				$out.= '</option>';
381 412
 			}
382 413
 			$num = $this->db->num_rows($resql);
@@ -390,8 +421,7 @@  discard block
 block discarded – undo
390 421
 					if ($socid > 0 && (empty($obj->fk_soc) || $obj->fk_soc == $socid) && empty($usertofilter->rights->societe->lire))
391 422
 					{
392 423
 						// Do nothing
393
-					}
394
-					else
424
+					} else
395 425
 					{
396 426
 						if ($discard_closed == 1 && $obj->fk_statut == Project::STATUS_CLOSED)
397 427
 						{
@@ -408,20 +438,22 @@  discard block
 block discarded – undo
408 438
 							//else $labeltoshow.=' ('.$langs->trans("Private").')';
409 439
 							$labeltoshow.=' '.dol_trunc($obj->title,$maxlength);
410 440
 
411
-							if ($obj->name) $labeltoshow.=' ('.$obj->name.')';
441
+							if ($obj->name) {
442
+							    $labeltoshow.=' ('.$obj->name.')';
443
+							}
412 444
 
413 445
 							$disabled=0;
414 446
 							if ($obj->fk_statut == Project::STATUS_DRAFT)
415 447
 							{
416 448
 								$disabled=1;
417 449
 								$labeltoshow.=' - '.$langs->trans("Draft");
418
-							}
419
-							else if ($obj->fk_statut == Project::STATUS_CLOSED)
450
+							} else if ($obj->fk_statut == Project::STATUS_CLOSED)
420 451
 							{
421
-								if ($discard_closed == 2) $disabled=1;
452
+								if ($discard_closed == 2) {
453
+								    $disabled=1;
454
+								}
422 455
 								$labeltoshow.=' - '.$langs->trans("Closed");
423
-							}
424
-							else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
456
+							} else if ($socid > 0 && (! empty($obj->fk_soc) && $obj->fk_soc != $socid))
425 457
 							{
426 458
 								$disabled=1;
427 459
 								$labeltoshow.=' - '.$langs->trans("LinkedToAnotherCompany");
@@ -437,17 +469,17 @@  discard block
 block discarded – undo
437 469
 							$out.= '<option value="'.$obj->rowid.'" selected';
438 470
 							//if ($disabled) $out.=' disabled';						// with select2, field can't be preselected if disabled
439 471
 							$out.= '>'.$labeltoshow.'</option>';
440
-						}
441
-						else
472
+						} else
442 473
 						{
443 474
 							if ($hideunselectables && $disabled && ($selected != $obj->rowid))
444 475
 							{
445 476
 								$resultat='';
446
-							}
447
-							else
477
+							} else
448 478
 							{
449 479
 								$resultat='<option value="'.$obj->rowid.'"';
450
-								if ($disabled) $resultat.=' disabled';
480
+								if ($disabled) {
481
+								    $resultat.=' disabled';
482
+								}
451 483
 								//if ($obj->public) $labeltoshow.=' ('.$langs->trans("Public").')';
452 484
 								//else $labeltoshow.=' ('.$langs->trans("Private").')';
453 485
 								$resultat.='>';
@@ -468,8 +500,7 @@  discard block
 block discarded – undo
468 500
 
469 501
 			$this->db->free($resql);
470 502
 			return $num;
471
-		}
472
-		else
503
+		} else
473 504
 		{
474 505
 			dol_print_error($this->db);
475 506
 			return -1;
@@ -493,10 +524,15 @@  discard block
 block discarded – undo
493 524
         // phpcs:enable
494 525
 		global $conf, $langs;
495 526
 
496
-		if ($table_element == 'projet_task') return '';		// Special cas of element we never link to a project (already always done)
527
+		if ($table_element == 'projet_task') {
528
+		    return '';
529
+		}
530
+		// Special cas of element we never link to a project (already always done)
497 531
 
498 532
 		$linkedtothirdparty=false;
499
-		if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','payment_salary','payment_various','chargesociales'))) $linkedtothirdparty=true;
533
+		if (! in_array($table_element, array('don','expensereport_det','expensereport','loan','stock_mouvement','payment_salary','payment_various','chargesociales'))) {
534
+		    $linkedtothirdparty=true;
535
+		}
500 536
 
501 537
 		$sqlfilter='';
502 538
 
@@ -550,18 +586,31 @@  discard block
 block discarded – undo
550 586
 				$sql = "SELECT t.rowid, t.ref";
551 587
 				break;
552 588
 		}
553
-		if ($linkedtothirdparty) $sql.=", s.nom as name";
589
+		if ($linkedtothirdparty) {
590
+		    $sql.=", s.nom as name";
591
+		}
554 592
 		$sql.= " FROM ".MAIN_DB_PREFIX.$table_element." as t";
555
-		if ($linkedtothirdparty) $sql.=", ".MAIN_DB_PREFIX."societe as s";
593
+		if ($linkedtothirdparty) {
594
+		    $sql.=", ".MAIN_DB_PREFIX."societe as s";
595
+		}
556 596
 		$sql.= " WHERE ".$projectkey." is null";
557 597
 		if (! empty($socid) && $linkedtothirdparty)
558 598
 		{
559
-		    if (is_numeric($socid)) $sql.= " AND t.fk_soc=".$socid;
560
-		    else $sql.= " AND t.fk_soc IN (".$socid.")";
599
+		    if (is_numeric($socid)) {
600
+		        $sql.= " AND t.fk_soc=".$socid;
601
+		    } else {
602
+		        $sql.= " AND t.fk_soc IN (".$socid.")";
603
+		    }
604
+		}
605
+		if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) {
606
+		    $sql.= ' AND t.entity IN ('.getEntity('project').')';
607
+		}
608
+		if ($linkedtothirdparty) {
609
+		    $sql.=" AND s.rowid = t.fk_soc";
610
+		}
611
+		if ($sqlfilter) {
612
+		    $sql.= " AND ".$sqlfilter;
561 613
 		}
562
-		if (! in_array($table_element, array('expensereport_det','stock_mouvement'))) $sql.= ' AND t.entity IN ('.getEntity('project').')';
563
-		if ($linkedtothirdparty) $sql.=" AND s.rowid = t.fk_soc";
564
-		if ($sqlfilter) $sql.= " AND ".$sqlfilter;
565 614
 		$sql.= " ORDER BY ref DESC";
566 615
 
567 616
 		dol_syslog(get_class($this).'::select_element', LOG_DEBUG);
@@ -578,8 +627,12 @@  discard block
 block discarded – undo
578 627
 				{
579 628
 					$obj = $this->db->fetch_object($resql);
580 629
 					$ref=$obj->ref?$obj->ref:$obj->rowid;
581
-					if (! empty($obj->ref_supplier)) $ref.=' ('.$obj->ref_supplier.')';
582
-					if (! empty($obj->name)) $ref.=' - '.$obj->name;
630
+					if (! empty($obj->ref_supplier)) {
631
+					    $ref.=' ('.$obj->ref_supplier.')';
632
+					}
633
+					if (! empty($obj->name)) {
634
+					    $ref.=' - '.$obj->name;
635
+					}
583 636
 					$sellist .='<option value="'.$obj->rowid.'">'.$ref.'</option>';
584 637
 					$i++;
585 638
 				}
@@ -594,8 +647,7 @@  discard block
 block discarded – undo
594 647
 			$this->db->free($resql);
595 648
 
596 649
 			return $sellist;
597
-		}
598
-		else
650
+		} else
599 651
 		{
600 652
 			dol_print_error($this->db);
601 653
 			$this->error=$this->db->lasterror();
@@ -650,16 +702,19 @@  discard block
 block discarded – undo
650 702
 					$obj = $this->db->fetch_object($resql);
651 703
 
652 704
 					$sellist .='<option value="'.$obj->rowid.'" defaultpercent="'.$obj->percent.'" elemcode="'.$obj->code.'"';
653
-					if ($obj->rowid == $preselected) $sellist .= ' selected="selected"';
705
+					if ($obj->rowid == $preselected) {
706
+					    $sellist .= ' selected="selected"';
707
+					}
654 708
 					$sellist .= '>';
655 709
 					if ($useshortlabel)
656 710
 					{
657 711
 						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
658
-					}
659
-					else
712
+					} else
660 713
 					{
661 714
 						$finallabel = ($langs->transnoentitiesnoconv("OppStatus".$obj->code) != "OppStatus".$obj->code ? $langs->transnoentitiesnoconv("OppStatus".$obj->code) : $obj->label);
662
-						if ($showpercent) $finallabel.= ' ('.$obj->percent.'%)';
715
+						if ($showpercent) {
716
+						    $finallabel.= ' ('.$obj->percent.'%)';
717
+						}
663 718
 					}
664 719
 					$sellist .= $finallabel;
665 720
 					$sellist .='</option>';
@@ -676,8 +731,7 @@  discard block
 block discarded – undo
676 731
 			$this->db->free($resql);
677 732
 
678 733
 			return $sellist;
679
-		}
680
-		else
734
+		} else
681 735
 		{
682 736
 			$this->error=$this->db->lasterror();
683 737
 			$this->errors[]=$this->db->lasterror();
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formorder.class.php 2 patches
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -31,7 +31,7 @@  discard block
 block discarded – undo
31 31
 class FormOrder extends Form
32 32
 {
33 33
 
34
-	/**
34
+    /**
35 35
      *    Return combo list of differents status of a orders
36 36
      *
37 37
      *    @param	string	$selected   Preselected value
@@ -41,64 +41,64 @@  discard block
 block discarded – undo
41 41
      */
42 42
     public function selectSupplierOrderStatus($selected='', $short=0, $hmlname='order_status')
43 43
     {
44
-	    $options = array();
45
-
46
-	    // 7 is same label than 6. 8 does not exists (billed is another field)
47
-	    $statustohow = array(
48
-		    '0' => '0',
49
-		    '1' => '1',
50
-		    '2' => '2',
51
-		    '3' => '3',
52
-		    '4' => '4',
53
-		    '5' => '5',
54
-		    '6' => '6,7',
55
-		    '9' => '9'
56
-	    );
57
-
58
-	    $tmpsupplierorder = new CommandeFournisseur($this->db);
59
-
60
-	    foreach ($statustohow as $key => $value) {
61
-		    $tmpsupplierorder->statut = $key;
62
-		    $options[$value] = $tmpsupplierorder->getLibStatut($short);
63
-	    }
64
-
65
-	    print Form::selectarray($hmlname, $options, $selected, 1);
44
+        $options = array();
45
+
46
+        // 7 is same label than 6. 8 does not exists (billed is another field)
47
+        $statustohow = array(
48
+            '0' => '0',
49
+            '1' => '1',
50
+            '2' => '2',
51
+            '3' => '3',
52
+            '4' => '4',
53
+            '5' => '5',
54
+            '6' => '6,7',
55
+            '9' => '9'
56
+        );
57
+
58
+        $tmpsupplierorder = new CommandeFournisseur($this->db);
59
+
60
+        foreach ($statustohow as $key => $value) {
61
+            $tmpsupplierorder->statut = $key;
62
+            $options[$value] = $tmpsupplierorder->getLibStatut($short);
63
+        }
64
+
65
+        print Form::selectarray($hmlname, $options, $selected, 1);
66 66
     }
67 67
 
68
-	/**
69
-	 *	Return list of input method (mode used to receive order, like order received by email, fax, online)
70
-	 *  List found into table c_input_method.
71
-	 *
72
-	 *	@param	string	$selected		Id of preselected input method
73
-	 *  @param  string	$htmlname 		Name of HTML select list
74
-	 *  @param  int		$addempty		0=list with no empty value, 1=list with empty value
75
-	 *  @return	array					Tableau des sources de commandes
76
-	 */
77
-	public function selectInputMethod($selected='',$htmlname='source_id',$addempty=0)
78
-	{
79
-		global $langs;
68
+    /**
69
+     *	Return list of input method (mode used to receive order, like order received by email, fax, online)
70
+     *  List found into table c_input_method.
71
+     *
72
+     *	@param	string	$selected		Id of preselected input method
73
+     *  @param  string	$htmlname 		Name of HTML select list
74
+     *  @param  int		$addempty		0=list with no empty value, 1=list with empty value
75
+     *  @return	array					Tableau des sources de commandes
76
+     */
77
+    public function selectInputMethod($selected='',$htmlname='source_id',$addempty=0)
78
+    {
79
+        global $langs;
80 80
 
81 81
         $listofmethods=array();
82 82
 
83
-		$sql = "SELECT rowid, code, libelle as label";
84
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
85
-		$sql.= " WHERE active = 1";
83
+        $sql = "SELECT rowid, code, libelle as label";
84
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
85
+        $sql.= " WHERE active = 1";
86 86
 
87
-		dol_syslog(get_class($this)."::selectInputMethod", LOG_DEBUG);
88
-		$resql=$this->db->query($sql);
87
+        dol_syslog(get_class($this)."::selectInputMethod", LOG_DEBUG);
88
+        $resql=$this->db->query($sql);
89 89
 
90
-		if (!$resql) {
91
-			dol_print_error($this->db);
92
-			return -1;
93
-		}
90
+        if (!$resql) {
91
+            dol_print_error($this->db);
92
+            return -1;
93
+        }
94 94
 
95
-		while ($obj = $this->db->fetch_object($resql)) {
96
-			$listofmethods[$obj->rowid] = $langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : $obj->label;
97
-		}
95
+        while ($obj = $this->db->fetch_object($resql)) {
96
+            $listofmethods[$obj->rowid] = $langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : $obj->label;
97
+        }
98 98
 
99
-		print Form::selectarray($htmlname,$listofmethods,$selected,$addempty);
99
+        print Form::selectarray($htmlname,$listofmethods,$selected,$addempty);
100 100
 
101
-		return 1;
102
-	}
101
+        return 1;
102
+    }
103 103
 }
104 104
 
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -22,7 +22,7 @@  discard block
 block discarded – undo
22 22
  *	\brief      File of predefined functions for HTML forms for order module
23 23
  */
24 24
 
25
-require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
25
+require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
26 26
 
27 27
 /**
28 28
  *	Class to manage HTML output components for orders
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      *    @param	string	$hmlname	Name of HTML select element
40 40
      *    @return	void
41 41
      */
42
-    public function selectSupplierOrderStatus($selected='', $short=0, $hmlname='order_status')
42
+    public function selectSupplierOrderStatus($selected = '', $short = 0, $hmlname = 'order_status')
43 43
     {
44 44
 	    $options = array();
45 45
 
@@ -74,18 +74,18 @@  discard block
 block discarded – undo
74 74
 	 *  @param  int		$addempty		0=list with no empty value, 1=list with empty value
75 75
 	 *  @return	array					Tableau des sources de commandes
76 76
 	 */
77
-	public function selectInputMethod($selected='',$htmlname='source_id',$addempty=0)
77
+	public function selectInputMethod($selected = '', $htmlname = 'source_id', $addempty = 0)
78 78
 	{
79 79
 		global $langs;
80 80
 
81
-        $listofmethods=array();
81
+        $listofmethods = array();
82 82
 
83 83
 		$sql = "SELECT rowid, code, libelle as label";
84
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_input_method";
85
-		$sql.= " WHERE active = 1";
84
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_input_method";
85
+		$sql .= " WHERE active = 1";
86 86
 
87 87
 		dol_syslog(get_class($this)."::selectInputMethod", LOG_DEBUG);
88
-		$resql=$this->db->query($sql);
88
+		$resql = $this->db->query($sql);
89 89
 
90 90
 		if (!$resql) {
91 91
 			dol_print_error($this->db);
@@ -96,7 +96,7 @@  discard block
 block discarded – undo
96 96
 			$listofmethods[$obj->rowid] = $langs->trans($obj->code) != $obj->code ? $langs->trans($obj->code) : $obj->label;
97 97
 		}
98 98
 
99
-		print Form::selectarray($htmlname,$listofmethods,$selected,$addempty);
99
+		print Form::selectarray($htmlname, $listofmethods, $selected, $addempty);
100 100
 
101 101
 		return 1;
102 102
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/class/html.formother.class.php 3 patches
Indentation   +146 added lines, -146 removed lines patch added patch discarded remove patch
@@ -40,9 +40,9 @@  discard block
 block discarded – undo
40 40
     private $db;
41 41
 
42 42
     /**
43
-	 * @var string Error code (or message)
44
-	 */
45
-	public $error;
43
+     * @var string Error code (or message)
44
+     */
45
+    public $error;
46 46
 
47 47
 
48 48
     /**
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
         $sql = "SELECT rowid, label";
74 74
         $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
75 75
         $sql.= " WHERE type = '".$type."'";
76
-		if (!empty($fk_user)) $sql.=" AND fk_user=".$fk_user;
76
+        if (!empty($fk_user)) $sql.=" AND fk_user=".$fk_user;
77 77
         $sql.= " ORDER BY rowid";
78 78
         $result = $this->db->query($sql);
79 79
         if ($result)
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
         $sql.= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
180 180
         $sql.= " ORDER BY country, e.organization ASC, e.code ASC";
181 181
 
182
-    	dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG);
182
+        dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG);
183 183
         $resql=$this->db->query($sql);
184 184
         if ($resql)
185 185
         {
@@ -230,50 +230,50 @@  discard block
 block discarded – undo
230 230
     function select_revenue_stamp($selected='', $htmlname='revenuestamp', $country_code='')
231 231
     {
232 232
         // phpcs:enable
233
-    	global $langs;
234
-
235
-    	$out='';
236
-
237
-    	$sql = "SELECT r.taux, r.revenuestamp_type";
238
-    	$sql.= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
239
-    	$sql.= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
240
-    	$sql.= " AND c.code = '".$country_code."'";
241
-
242
-    	dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG);
243
-    	$resql=$this->db->query($sql);
244
-    	if ($resql)
245
-    	{
246
-    		$out.='<select class="flat" name="'.$htmlname.'">';
247
-    		$num = $this->db->num_rows($resql);
248
-    		$i = 0;
249
-    		$out.='<option value="0">&nbsp;</option>'."\n";
250
-    		if ($num)
251
-    		{
252
-    			while ($i < $num)
253
-    			{
254
-    				$obj = $this->db->fetch_object($resql);
255
-    				if (($selected && $selected == $obj->taux) || $num == 1)
256
-    				{
257
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
258
-    				}
259
-    				else
260
-    				{
261
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
262
-    					//print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
263
-    				}
264
-    				$out.=$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
265
-    				$out.='</option>';
266
-    				$i++;
267
-    			}
268
-    		}
269
-    		$out.='</select>';
270
-    		return $out;
271
-    	}
272
-    	else
273
-    	{
274
-    		dol_print_error($this->db);
275
-    		return '';
276
-    	}
233
+        global $langs;
234
+
235
+        $out='';
236
+
237
+        $sql = "SELECT r.taux, r.revenuestamp_type";
238
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
239
+        $sql.= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
240
+        $sql.= " AND c.code = '".$country_code."'";
241
+
242
+        dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG);
243
+        $resql=$this->db->query($sql);
244
+        if ($resql)
245
+        {
246
+            $out.='<select class="flat" name="'.$htmlname.'">';
247
+            $num = $this->db->num_rows($resql);
248
+            $i = 0;
249
+            $out.='<option value="0">&nbsp;</option>'."\n";
250
+            if ($num)
251
+            {
252
+                while ($i < $num)
253
+                {
254
+                    $obj = $this->db->fetch_object($resql);
255
+                    if (($selected && $selected == $obj->taux) || $num == 1)
256
+                    {
257
+                        $out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
258
+                    }
259
+                    else
260
+                    {
261
+                        $out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
262
+                        //print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
263
+                    }
264
+                    $out.=$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
265
+                    $out.='</option>';
266
+                    $i++;
267
+                }
268
+            }
269
+            $out.='</select>';
270
+            return $out;
271
+        }
272
+        else
273
+        {
274
+            dol_print_error($this->db);
275
+            return '';
276
+        }
277 277
     }
278 278
 
279 279
 
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
         }
369 369
         if ($nocateg)
370 370
         {
371
-        	$langs->load("categories");
372
-        	$moreforfilter.='<option value="-2"'.($selected == -2 ? ' selected':'').'>- '.$langs->trans("NotCategorized").' -</option>';
371
+            $langs->load("categories");
372
+            $moreforfilter.='<option value="-2"'.($selected == -2 ? ' selected':'').'>- '.$langs->trans("NotCategorized").' -</option>';
373 373
         }
374 374
         $moreforfilter.='</select>';
375 375
 
@@ -404,7 +404,7 @@  discard block
 block discarded – undo
404 404
             $comboenhancement = ajax_combobox($htmlname);
405 405
             if ($comboenhancement)
406 406
             {
407
-            	$out.=$comboenhancement;
407
+                $out.=$comboenhancement;
408 408
             }
409 409
         }
410 410
         // Select each sales and print them in a select input
@@ -426,7 +426,7 @@  discard block
 block discarded – undo
426 426
             $sql_usr.= " WHERE u2.entity IN (0,".$conf->entity.")";
427 427
             $sql_usr.= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id;
428 428
         }
429
-	    $sql_usr.= " ORDER BY statut DESC, lastname ASC";  // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
429
+        $sql_usr.= " ORDER BY statut DESC, lastname ASC";  // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
430 430
         //print $sql_usr;exit;
431 431
 
432 432
         $resql_usr = $this->db->query($sql_usr);
@@ -450,18 +450,18 @@  discard block
 block discarded – undo
450 450
                 }
451 451
                 if ($showstatus >= 0)
452 452
                 {
453
-					if ($obj_usr->statut == 1 && $showstatus == 1)
454
-					{
455
-						$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
456
-	                	$moreinfo++;
457
-					}
458
-					if ($obj_usr->statut == 0)
459
-					{
460
-						$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
461
-                		$moreinfo++;
462
-					}
463
-				}
464
-				$out.=($moreinfo?')':'');
453
+                    if ($obj_usr->statut == 1 && $showstatus == 1)
454
+                    {
455
+                        $out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
456
+                        $moreinfo++;
457
+                    }
458
+                    if ($obj_usr->statut == 0)
459
+                    {
460
+                        $out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
461
+                        $moreinfo++;
462
+                    }
463
+                }
464
+                $out.=($moreinfo?')':'');
465 465
                 $out.='</option>';
466 466
             }
467 467
             $this->db->free($resql_usr);
@@ -486,7 +486,7 @@  discard block
 block discarded – undo
486 486
      * 	@param	int		$mode					0=Return list of tasks and their projects, 1=Return projects and tasks if exists
487 487
      *  @param  int		$useempty       		0=Allow empty values
488 488
      *  @param	int		$disablechildoftaskid	1=Disable task that are child of the provided task id
489
-	 *  @param	string	$filteronprojstatus		Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status)
489
+     *  @param	string	$filteronprojstatus		Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status)
490 490
      *  @param	string	$morecss				More css
491 491
      *  @return	void
492 492
      */
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
         $tasksarray=$task->getTasksArray($modetask?$user:0, $modeproject?$user:0, $projectid, 0, $mode, '', $filteronprojstatus);
502 502
         if ($tasksarray)
503 503
         {
504
-        	print '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
504
+            print '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
505 505
             if ($useempty) print '<option value="0">&nbsp;</option>';
506 506
             $j=0;
507 507
             $level=0;
@@ -537,11 +537,11 @@  discard block
 block discarded – undo
537 537
         $numlines=count($lines);
538 538
         for ($i = 0 ; $i < $numlines ; $i++)
539 539
         {
540
-        	if ($lines[$i]->fk_parent == $parent)
540
+            if ($lines[$i]->fk_parent == $parent)
541 541
             {
542 542
                 $var = !$var;
543 543
 
544
-				//var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id);		// $lines[$i]->id may be empty if project has no lines
544
+                //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id);		// $lines[$i]->id may be empty if project has no lines
545 545
 
546 546
                 // Break on a new project
547 547
                 if ($parent == 0)	// We are on a task at first level
@@ -574,13 +574,13 @@  discard block
 block discarded – undo
574 574
                 // Print task
575 575
                 if (isset($lines[$i]->id))		// We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
576 576
                 {
577
-                	// Check if we must disable entry
578
-                	$disabled=0;
579
-                	if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
580
-                	{
581
-               			$disabled++;
582
-               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id;	// If task is child of a disabled parent, we will propagate id to disable next child too
583
-                	}
577
+                    // Check if we must disable entry
578
+                    $disabled=0;
579
+                    if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
580
+                    {
581
+                            $disabled++;
582
+                            if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id;	// If task is child of a disabled parent, we will propagate id to disable next child too
583
+                    }
584 584
 
585 585
                     print '<option value="'.$lines[$i]->fk_project.'_'.$lines[$i]->id.'"';
586 586
                     if (($lines[$i]->id == $selectedtask) || ($lines[$i]->fk_project.'_'.$lines[$i]->id == $selectedtask)) print ' selected';
@@ -623,14 +623,14 @@  discard block
 block discarded – undo
623 623
      */
624 624
     static function showColor($color, $textifnotdefined='')
625 625
     {
626
-    	$textcolor='FFF';
627
-    	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
628
-    	if(colorIsLight($color)) $textcolor='000';
626
+        $textcolor='FFF';
627
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
628
+        if(colorIsLight($color)) $textcolor='000';
629 629
 
630
-    	$color = colorArrayToHex(colorStringToArray($color,array()),'');
630
+        $color = colorArrayToHex(colorStringToArray($color,array()),'');
631 631
 
632
-		if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
633
-		else print $textifnotdefined;
632
+        if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
633
+        else print $textifnotdefined;
634 634
     }
635 635
 
636 636
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
     function select_color($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='')
650 650
     {
651 651
         // phpcs:enable
652
-    	print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors);
652
+        print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors);
653 653
     }
654 654
 
655 655
     /**
@@ -666,10 +666,10 @@  discard block
 block discarded – undo
666 666
      */
667 667
     static function selectColor($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='', $morecss='')
668 668
     {
669
-	    // Deprecation warning
670
-	    if ($form_name) {
671
-		    dol_syslog(__METHOD__ . ": form_name parameter is deprecated", LOG_WARNING);
672
-	    }
669
+        // Deprecation warning
670
+        if ($form_name) {
671
+            dol_syslog(__METHOD__ . ": form_name parameter is deprecated", LOG_WARNING);
672
+        }
673 673
 
674 674
         global $langs,$conf;
675 675
 
@@ -680,9 +680,9 @@  discard block
 block discarded – undo
680 680
             $langs->load("other");
681 681
             if (empty($conf->dol_use_jmobile))
682 682
             {
683
-	            $out.= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
684
-	            $out.= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
685
-	            $out.= '<script type="text/javascript">
683
+                $out.= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
684
+                $out.= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
685
+                $out.= '<script type="text/javascript">
686 686
 	             jQuery(document).ready(function(){
687 687
 	                $(\'#colorpicker'.$prefix.'\').jPicker( {
688 688
 	                window: {
@@ -726,9 +726,9 @@  discard block
 block discarded – undo
726 726
         {
727 727
             if (empty($conf->dol_use_jmobile))
728 728
             {
729
-	        	$out.= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
730
-	            $out.= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
731
-	            $out.= '<script type="text/javascript">
729
+                $out.= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
730
+                $out.= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
731
+                $out.= '<script type="text/javascript">
732 732
 	             jQuery(document).ready(function(){
733 733
 	                 jQuery(\'#colorpicker'.$prefix.'\').colorpicker({
734 734
 	                     size: 14,
@@ -929,7 +929,7 @@  discard block
 block discarded – undo
929 929
         $out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="' . $htmlname . '" name="' . $htmlname . '"'.$option.' >';
930 930
         if($useempty)
931 931
         {
932
-        	$selected_html='';
932
+            $selected_html='';
933 933
             if ($selected == '') $selected_html = ' selected';
934 934
             $out.= '<option value=""' . $selected_html . '>&nbsp;</option>';
935 935
         }
@@ -1028,55 +1028,55 @@  discard block
 block discarded – undo
1028 1028
         $boxidactivatedforuser=array();
1029 1029
         foreach($boxactivated as $box)
1030 1030
         {
1031
-        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id;	// We keep only boxes to show for user
1031
+            if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id;	// We keep only boxes to show for user
1032 1032
         }
1033 1033
 
1034 1034
         // Define selectboxlist
1035 1035
         $arrayboxtoactivatelabel=array();
1036 1036
         if (! empty($user->conf->$confuserzone))
1037 1037
         {
1038
-        	$boxorder='';
1039
-        	$langs->load("boxes");	// Load label of boxes
1040
-        	foreach($boxactivated as $box)
1041
-        	{
1042
-        		if (! empty($boxidactivatedforuser[$box->id])) continue;	// Already visible for user
1043
-        		$label=$langs->transnoentitiesnoconv($box->boxlabel);
1044
-        		//if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1045
-        		if (preg_match('/graph/',$box->class) && $conf->browser->layout != 'phone')
1046
-        		{
1047
-        			$label=$label.' <span class="fa fa-bar-chart"></span>';
1048
-        		}
1049
-        		$arrayboxtoactivatelabel[$box->id]=$label;			// We keep only boxes not shown for user, to show into combo list
1050
-        	}
1038
+            $boxorder='';
1039
+            $langs->load("boxes");	// Load label of boxes
1040
+            foreach($boxactivated as $box)
1041
+            {
1042
+                if (! empty($boxidactivatedforuser[$box->id])) continue;	// Already visible for user
1043
+                $label=$langs->transnoentitiesnoconv($box->boxlabel);
1044
+                //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1045
+                if (preg_match('/graph/',$box->class) && $conf->browser->layout != 'phone')
1046
+                {
1047
+                    $label=$label.' <span class="fa fa-bar-chart"></span>';
1048
+                }
1049
+                $arrayboxtoactivatelabel[$box->id]=$label;			// We keep only boxes not shown for user, to show into combo list
1050
+            }
1051 1051
             foreach($boxidactivatedforuser as $boxid)
1052
-        	{
1053
-       			if (empty($boxorder)) $boxorder.='A:';
1054
-  				$boxorder.=$boxid.',';
1055
-        	}
1056
-
1057
-        	//var_dump($boxidactivatedforuser);
1058
-
1059
-        	// Class Form must have been already loaded
1060
-        	$selectboxlist.='<!-- Form with select box list -->'."\n";
1061
-			$selectboxlist.='<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1062
-			$selectboxlist.='<input type="hidden" name="addbox" value="addbox">';
1063
-			$selectboxlist.='<input type="hidden" name="userid" value="'.$user->id.'">';
1064
-			$selectboxlist.='<input type="hidden" name="areacode" value="'.$areacode.'">';
1065
-			$selectboxlist.='<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1066
-			$selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1052
+            {
1053
+                    if (empty($boxorder)) $boxorder.='A:';
1054
+                    $boxorder.=$boxid.',';
1055
+            }
1056
+
1057
+            //var_dump($boxidactivatedforuser);
1058
+
1059
+            // Class Form must have been already loaded
1060
+            $selectboxlist.='<!-- Form with select box list -->'."\n";
1061
+            $selectboxlist.='<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1062
+            $selectboxlist.='<input type="hidden" name="addbox" value="addbox">';
1063
+            $selectboxlist.='<input type="hidden" name="userid" value="'.$user->id.'">';
1064
+            $selectboxlist.='<input type="hidden" name="areacode" value="'.$areacode.'">';
1065
+            $selectboxlist.='<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1066
+            $selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1067 1067
             if (empty($conf->use_javascript_ajax)) $selectboxlist.=' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1068 1068
             $selectboxlist.='</form>';
1069 1069
             if (! empty($conf->use_javascript_ajax))
1070 1070
             {
1071
-            	include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1072
-            	$selectboxlist.=ajax_combobox("boxcombo");
1071
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1072
+                $selectboxlist.=ajax_combobox("boxcombo");
1073 1073
             }
1074 1074
         }
1075 1075
 
1076 1076
         // Javascript code for dynamic actions
1077 1077
         if (! empty($conf->use_javascript_ajax))
1078 1078
         {
1079
-	        $selectboxlist.='<script type="text/javascript" language="javascript">
1079
+            $selectboxlist.='<script type="text/javascript" language="javascript">
1080 1080
 
1081 1081
 	        // To update list of activated boxes
1082 1082
 	        function updateBoxOrder(closing) {
@@ -1115,8 +1115,8 @@  discard block
 block discarded – undo
1115 1115
 	        			window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=addbox&boxid=\'+boxid;
1116 1116
 	                }
1117 1117
 	        	});';
1118
-	        	if (! count($arrayboxtoactivatelabel)) $selectboxlist.='jQuery("#boxcombo").hide();';
1119
-	        	$selectboxlist.='
1118
+                if (! count($arrayboxtoactivatelabel)) $selectboxlist.='jQuery("#boxcombo").hide();';
1119
+                $selectboxlist.='
1120 1120
 
1121 1121
 	        	jQuery("#boxhalfleft, #boxhalfright").sortable({
1122 1122
 	    	    	handle: \'.boxhandle\',
@@ -1141,7 +1141,7 @@  discard block
 block discarded – undo
1141 1141
 
1142 1142
         	});'."\n";
1143 1143
 
1144
-	        $selectboxlist.='</script>'."\n";
1144
+            $selectboxlist.='</script>'."\n";
1145 1145
         }
1146 1146
 
1147 1147
         // Define boxlista and boxlistb
@@ -1149,10 +1149,10 @@  discard block
 block discarded – undo
1149 1149
 
1150 1150
         if ($nbboxactivated)
1151 1151
         {
1152
-        	// Load translation files required by the page
1152
+            // Load translation files required by the page
1153 1153
             $langs->loadLangs(array("boxes","projects"));
1154 1154
 
1155
-        	$emptybox=new ModeleBoxes($db);
1155
+            $emptybox=new ModeleBoxes($db);
1156 1156
 
1157 1157
             $boxlista.="\n<!-- Box left container -->\n";
1158 1158
 
@@ -1163,9 +1163,9 @@  discard block
 block discarded – undo
1163 1163
             $ii=0;
1164 1164
             foreach ($boxactivated as $key => $box)
1165 1165
             {
1166
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1167
-				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1168
-            	if (preg_match('/^A/i',$box->box_order)) // column A
1166
+                if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1167
+                if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1168
+                if (preg_match('/^A/i',$box->box_order)) // column A
1169 1169
                 {
1170 1170
                     $ii++;
1171 1171
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
@@ -1178,10 +1178,10 @@  discard block
 block discarded – undo
1178 1178
 
1179 1179
             if ($conf->browser->layout != 'phone')
1180 1180
             {
1181
-            	$emptybox->box_id='A';
1182
-            	$emptybox->info_box_head=array();
1183
-            	$emptybox->info_box_contents=array();
1184
-            	$boxlista.= $emptybox->outputBox(array(),array());
1181
+                $emptybox->box_id='A';
1182
+                $emptybox->info_box_head=array();
1183
+                $emptybox->info_box_contents=array();
1184
+                $boxlista.= $emptybox->outputBox(array(),array());
1185 1185
             }
1186 1186
             $boxlista.= "<!-- End box left container -->\n";
1187 1187
 
@@ -1190,9 +1190,9 @@  discard block
 block discarded – undo
1190 1190
             $ii=0;
1191 1191
             foreach ($boxactivated as $key => $box)
1192 1192
             {
1193
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1194
-            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1195
-            	if (preg_match('/^B/i',$box->box_order)) // colonne B
1193
+                if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1194
+                if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1195
+                if (preg_match('/^B/i',$box->box_order)) // colonne B
1196 1196
                 {
1197 1197
                     $ii++;
1198 1198
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
@@ -1205,10 +1205,10 @@  discard block
 block discarded – undo
1205 1205
 
1206 1206
             if ($conf->browser->layout != 'phone')
1207 1207
             {
1208
-            	$emptybox->box_id='B';
1209
-            	$emptybox->info_box_head=array();
1210
-            	$emptybox->info_box_contents=array();
1211
-            	$boxlistb.= $emptybox->outputBox(array(),array());
1208
+                $emptybox->box_id='B';
1209
+                $emptybox->info_box_head=array();
1210
+                $emptybox->info_box_contents=array();
1211
+                $boxlistb.= $emptybox->outputBox(array(),array());
1212 1212
             }
1213 1213
 
1214 1214
             $boxlistb.= "<!-- End box right container -->\n";
@@ -1274,7 +1274,7 @@  discard block
 block discarded – undo
1274 1274
                 print "</select>";
1275 1275
             }
1276 1276
             else
1277
-			{
1277
+            {
1278 1278
                 print $langs->trans("DictionaryEmpty");
1279 1279
             }
1280 1280
         }
Please login to merge, or discard this patch.
Spacing   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -67,14 +67,14 @@  discard block
 block discarded – undo
67 67
      *    @param    int		$fk_user          Utilisateur créant le modèle
68 68
      *    @return	void
69 69
      */
70
-    function select_export_model($selected='', $htmlname='exportmodelid', $type='', $useempty=0, $fk_user=null)
70
+    function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null)
71 71
     {
72 72
         // phpcs:enable
73 73
         $sql = "SELECT rowid, label";
74
-        $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
75
-        $sql.= " WHERE type = '".$type."'";
76
-		if (!empty($fk_user)) $sql.=" AND fk_user=".$fk_user;
77
-        $sql.= " ORDER BY rowid";
74
+        $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
75
+        $sql .= " WHERE type = '".$type."'";
76
+		if (!empty($fk_user)) $sql .= " AND fk_user=".$fk_user;
77
+        $sql .= " ORDER BY rowid";
78 78
         $result = $this->db->query($sql);
79 79
         if ($result)
80 80
         {
@@ -119,13 +119,13 @@  discard block
 block discarded – undo
119 119
      *    @param    int		$useempty          Affiche valeur vide dans liste
120 120
      *    @return	void
121 121
      */
122
-    function select_import_model($selected='', $htmlname='importmodelid', $type='', $useempty=0)
122
+    function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0)
123 123
     {
124 124
         // phpcs:enable
125 125
         $sql = "SELECT rowid, label";
126
-        $sql.= " FROM ".MAIN_DB_PREFIX."import_model";
127
-        $sql.= " WHERE type = '".$type."'";
128
-        $sql.= " ORDER BY rowid";
126
+        $sql .= " FROM ".MAIN_DB_PREFIX."import_model";
127
+        $sql .= " WHERE type = '".$type."'";
128
+        $sql .= " ORDER BY rowid";
129 129
         $result = $this->db->query($sql);
130 130
         if ($result)
131 131
         {
@@ -168,19 +168,19 @@  discard block
 block discarded – undo
168 168
      *    @param    string	$htmlname	Name of combo list
169 169
      *    @return	integer
170 170
      */
171
-    function select_ecotaxes($selected='', $htmlname='ecotaxe_id')
171
+    function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id')
172 172
     {
173 173
         // phpcs:enable
174 174
         global $langs;
175 175
 
176 176
         $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,";
177
-        $sql.= " c.label as country";
178
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c";
179
-        $sql.= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
180
-        $sql.= " ORDER BY country, e.organization ASC, e.code ASC";
177
+        $sql .= " c.label as country";
178
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c";
179
+        $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
180
+        $sql .= " ORDER BY country, e.organization ASC, e.code ASC";
181 181
 
182 182
     	dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG);
183
-        $resql=$this->db->query($sql);
183
+        $resql = $this->db->query($sql);
184 184
         if ($resql)
185 185
         {
186 186
             print '<select class="flat" name="'.$htmlname.'">';
@@ -227,26 +227,26 @@  discard block
 block discarded – undo
227 227
      *    @param    string	$country_code   Country Code
228 228
      *    @return	string					HTML select list
229 229
      */
230
-    function select_revenue_stamp($selected='', $htmlname='revenuestamp', $country_code='')
230
+    function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '')
231 231
     {
232 232
         // phpcs:enable
233 233
     	global $langs;
234 234
 
235
-    	$out='';
235
+    	$out = '';
236 236
 
237 237
     	$sql = "SELECT r.taux, r.revenuestamp_type";
238
-    	$sql.= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
239
-    	$sql.= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
240
-    	$sql.= " AND c.code = '".$country_code."'";
238
+    	$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
239
+    	$sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
240
+    	$sql .= " AND c.code = '".$country_code."'";
241 241
 
242 242
     	dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG);
243
-    	$resql=$this->db->query($sql);
243
+    	$resql = $this->db->query($sql);
244 244
     	if ($resql)
245 245
     	{
246
-    		$out.='<select class="flat" name="'.$htmlname.'">';
246
+    		$out .= '<select class="flat" name="'.$htmlname.'">';
247 247
     		$num = $this->db->num_rows($resql);
248 248
     		$i = 0;
249
-    		$out.='<option value="0">&nbsp;</option>'."\n";
249
+    		$out .= '<option value="0">&nbsp;</option>'."\n";
250 250
     		if ($num)
251 251
     		{
252 252
     			while ($i < $num)
@@ -254,19 +254,19 @@  discard block
 block discarded – undo
254 254
     				$obj = $this->db->fetch_object($resql);
255 255
     				if (($selected && $selected == $obj->taux) || $num == 1)
256 256
     				{
257
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
257
+    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
258 258
     				}
259 259
     				else
260 260
     				{
261
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
261
+    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
262 262
     					//print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
263 263
     				}
264
-    				$out.=$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
265
-    				$out.='</option>';
264
+    				$out .= $obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
265
+    				$out .= '</option>';
266 266
     				$i++;
267 267
     			}
268 268
     		}
269
-    		$out.='</select>';
269
+    		$out .= '</select>';
270 270
     		return $out;
271 271
     	}
272 272
     	else
@@ -290,27 +290,27 @@  discard block
 block discarded – undo
290 290
      *    @param    int     $showempty      Add also an empty line
291 291
      *    @return   string					HTML select string
292 292
      */
293
-    function select_percent($selected=0,$htmlname='percent',$disabled=0,$increment=5,$start=0,$end=100,$showempty=0)
293
+    function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0)
294 294
     {
295 295
         // phpcs:enable
296
-        $return = '<select class="flat" name="'.$htmlname.'" '.($disabled?'disabled':'').'>';
297
-        if ($showempty) $return.='<option value="-1"'.(($selected == -1 || $selected == '')?' selected':'').'>&nbsp;</option>';
296
+        $return = '<select class="flat" name="'.$htmlname.'" '.($disabled ? 'disabled' : '').'>';
297
+        if ($showempty) $return .= '<option value="-1"'.(($selected == -1 || $selected == '') ? ' selected' : '').'>&nbsp;</option>';
298 298
 
299
-        for ($i = $start ; $i <= $end ; $i += $increment)
299
+        for ($i = $start; $i <= $end; $i += $increment)
300 300
         {
301 301
             if ($selected != '' && (int) $selected == $i)
302 302
             {
303
-                $return.= '<option value="'.$i.'" selected>';
303
+                $return .= '<option value="'.$i.'" selected>';
304 304
             }
305 305
             else
306 306
             {
307
-                $return.= '<option value="'.$i.'">';
307
+                $return .= '<option value="'.$i.'">';
308 308
             }
309
-            $return.= $i.' % ';
310
-            $return.= '</option>';
309
+            $return .= $i.' % ';
310
+            $return .= '</option>';
311 311
         }
312 312
 
313
-        $return.= '</select>';
313
+        $return .= '</select>';
314 314
 
315 315
         return $return;
316 316
     }
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
      * @return  string		        	Html combo list code
329 329
      * @see	select_all_categories
330 330
      */
331
-    function select_categories($type, $selected=0, $htmlname='search_categ', $nocateg=0, $showempty=1, $morecss='')
331
+    function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '')
332 332
     {
333 333
         // phpcs:enable
334 334
         global $conf, $langs;
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
         // For backward compatibility
338 338
         if (is_numeric($type))
339 339
         {
340
-            dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
340
+            dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
341 341
         }
342 342
 
343 343
         // Load list of "categories"
@@ -348,30 +348,30 @@  discard block
 block discarded – undo
348 348
         // Enhance with select2
349 349
         if ($conf->use_javascript_ajax)
350 350
         {
351
-            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
351
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
352 352
             $comboenhancement = ajax_combobox('select_categ_'.$htmlname);
353
-            $moreforfilter.=$comboenhancement;
353
+            $moreforfilter .= $comboenhancement;
354 354
         }
355 355
 
356 356
         // Print a select with each of them
357
-        $moreforfilter.='<select class="flat minwidth100'.($morecss?' '.$morecss:'').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
358
-        if ($showempty) $moreforfilter.='<option value="0">&nbsp;</option>';	// Should use -1 to say nothing
357
+        $moreforfilter .= '<select class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
358
+        if ($showempty) $moreforfilter .= '<option value="0">&nbsp;</option>'; // Should use -1 to say nothing
359 359
 
360 360
         if (is_array($tab_categs))
361 361
         {
362 362
             foreach ($tab_categs as $categ)
363 363
             {
364
-                $moreforfilter.='<option value="'.$categ['id'].'"';
365
-                if ($categ['id'] == $selected) $moreforfilter.=' selected';
366
-                $moreforfilter.='>'.dol_trunc($categ['fulllabel'],50,'middle').'</option>';
364
+                $moreforfilter .= '<option value="'.$categ['id'].'"';
365
+                if ($categ['id'] == $selected) $moreforfilter .= ' selected';
366
+                $moreforfilter .= '>'.dol_trunc($categ['fulllabel'], 50, 'middle').'</option>';
367 367
             }
368 368
         }
369 369
         if ($nocateg)
370 370
         {
371 371
         	$langs->load("categories");
372
-        	$moreforfilter.='<option value="-2"'.($selected == -2 ? ' selected':'').'>- '.$langs->trans("NotCategorized").' -</option>';
372
+        	$moreforfilter .= '<option value="-2"'.($selected == -2 ? ' selected' : '').'>- '.$langs->trans("NotCategorized").' -</option>';
373 373
         }
374
-        $moreforfilter.='</select>';
374
+        $moreforfilter .= '</select>';
375 375
 
376 376
         return $moreforfilter;
377 377
     }
@@ -389,44 +389,44 @@  discard block
 block discarded – undo
389 389
      *  @param	string	$morecss		More CSS
390 390
      *  @return string					Html combo list code
391 391
      */
392
-    function select_salesrepresentatives($selected,$htmlname,$user,$showstatus=0,$showempty=1,$morecss='')
392
+    function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '')
393 393
     {
394 394
         // phpcs:enable
395
-        global $conf,$langs;
395
+        global $conf, $langs;
396 396
         $langs->load('users');
397 397
 
398 398
         $out = '';
399 399
         // Enhance with select2
400 400
         if ($conf->use_javascript_ajax)
401 401
         {
402
-            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
402
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
403 403
 
404 404
             $comboenhancement = ajax_combobox($htmlname);
405 405
             if ($comboenhancement)
406 406
             {
407
-            	$out.=$comboenhancement;
407
+            	$out .= $comboenhancement;
408 408
             }
409 409
         }
410 410
         // Select each sales and print them in a select input
411
-        $out.='<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
412
-        if ($showempty) $out.='<option value="0">&nbsp;</option>';
411
+        $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
412
+        if ($showempty) $out .= '<option value="0">&nbsp;</option>';
413 413
 
414 414
         // Get list of users allowed to be viewed
415 415
         $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login";
416
-        $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u";
417
-        $sql_usr.= " WHERE u.entity IN (0,".$conf->entity.")";
418
-        if (empty($user->rights->user->user->lire)) $sql_usr.=" AND u.rowid = ".$user->id;
419
-        if (! empty($user->societe_id)) $sql_usr.=" AND u.fk_soc = ".$user->societe_id;
416
+        $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u";
417
+        $sql_usr .= " WHERE u.entity IN (0,".$conf->entity.")";
418
+        if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id;
419
+        if (!empty($user->societe_id)) $sql_usr .= " AND u.fk_soc = ".$user->societe_id;
420 420
         // Add existing sales representatives of thirdparty of external user
421 421
         if (empty($user->rights->user->user->lire) && $user->societe_id)
422 422
         {
423
-            $sql_usr.=" UNION ";
424
-            $sql_usr.= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login";
425
-            $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc";
426
-            $sql_usr.= " WHERE u2.entity IN (0,".$conf->entity.")";
427
-            $sql_usr.= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id;
423
+            $sql_usr .= " UNION ";
424
+            $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login";
425
+            $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc";
426
+            $sql_usr .= " WHERE u2.entity IN (0,".$conf->entity.")";
427
+            $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id;
428 428
         }
429
-	    $sql_usr.= " ORDER BY statut DESC, lastname ASC";  // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
429
+	    $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
430 430
         //print $sql_usr;exit;
431 431
 
432 432
         $resql_usr = $this->db->query($sql_usr);
@@ -435,34 +435,34 @@  discard block
 block discarded – undo
435 435
             while ($obj_usr = $this->db->fetch_object($resql_usr))
436 436
             {
437 437
 
438
-                $out.='<option value="'.$obj_usr->rowid.'"';
438
+                $out .= '<option value="'.$obj_usr->rowid.'"';
439 439
 
440
-                if ($obj_usr->rowid == $selected) $out.=' selected';
440
+                if ($obj_usr->rowid == $selected) $out .= ' selected';
441 441
 
442
-                $out.='>';
443
-                $out.=dolGetFirstLastname($obj_usr->firstname,$obj_usr->lastname);
442
+                $out .= '>';
443
+                $out .= dolGetFirstLastname($obj_usr->firstname, $obj_usr->lastname);
444 444
                 // Complete name with more info
445
-                $moreinfo=0;
446
-                if (! empty($conf->global->MAIN_SHOW_LOGIN))
445
+                $moreinfo = 0;
446
+                if (!empty($conf->global->MAIN_SHOW_LOGIN))
447 447
                 {
448
-                    $out.=($moreinfo?' - ':' (').$obj_usr->login;
448
+                    $out .= ($moreinfo ? ' - ' : ' (').$obj_usr->login;
449 449
                     $moreinfo++;
450 450
                 }
451 451
                 if ($showstatus >= 0)
452 452
                 {
453 453
 					if ($obj_usr->statut == 1 && $showstatus == 1)
454 454
 					{
455
-						$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
455
+						$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
456 456
 	                	$moreinfo++;
457 457
 					}
458 458
 					if ($obj_usr->statut == 0)
459 459
 					{
460
-						$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
460
+						$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
461 461
                 		$moreinfo++;
462 462
 					}
463 463
 				}
464
-				$out.=($moreinfo?')':'');
465
-                $out.='</option>';
464
+				$out .= ($moreinfo ? ')' : '');
465
+                $out .= '</option>';
466 466
             }
467 467
             $this->db->free($resql_usr);
468 468
         }
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
         {
471 471
             dol_print_error($this->db);
472 472
         }
473
-        $out.='</select>';
473
+        $out .= '</select>';
474 474
 
475 475
         return $out;
476 476
     }
@@ -490,21 +490,21 @@  discard block
 block discarded – undo
490 490
      *  @param	string	$morecss				More css
491 491
      *  @return	void
492 492
      */
493
-    function selectProjectTasks($selectedtask='', $projectid=0, $htmlname='task_parent', $modeproject=0, $modetask=0, $mode=0, $useempty=0, $disablechildoftaskid=0, $filteronprojstatus='', $morecss='')
493
+    function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '')
494 494
     {
495 495
         global $user, $langs;
496 496
 
497 497
         require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
498 498
 
499 499
         //print $modeproject.'-'.$modetask;
500
-        $task=new Task($this->db);
501
-        $tasksarray=$task->getTasksArray($modetask?$user:0, $modeproject?$user:0, $projectid, 0, $mode, '', $filteronprojstatus);
500
+        $task = new Task($this->db);
501
+        $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus);
502 502
         if ($tasksarray)
503 503
         {
504
-        	print '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
504
+        	print '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
505 505
             if ($useempty) print '<option value="0">&nbsp;</option>';
506
-            $j=0;
507
-            $level=0;
506
+            $j = 0;
507
+            $level = 0;
508 508
             $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid);
509 509
             print '</select>';
510 510
 
@@ -528,14 +528,14 @@  discard block
 block discarded – undo
528 528
      * @param	int		$disablechildoftaskid	1=Disable task that are child of the provided task id
529 529
      * @return	void
530 530
      */
531
-    private function _pLineSelect(&$inc, $parent, $lines, $level=0, $selectedtask=0, $selectedproject=0, $disablechildoftaskid=0)
531
+    private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0)
532 532
     {
533 533
         global $langs, $user, $conf;
534 534
 
535
-        $lastprojectid=0;
535
+        $lastprojectid = 0;
536 536
 
537
-        $numlines=count($lines);
538
-        for ($i = 0 ; $i < $numlines ; $i++)
537
+        $numlines = count($lines);
538
+        for ($i = 0; $i < $numlines; $i++)
539 539
         {
540 540
         	if ($lines[$i]->fk_parent == $parent)
541 541
             {
@@ -551,7 +551,7 @@  discard block
 block discarded – undo
551 551
                         if ($i > 0) print '<option value="0" disabled>----------</option>';
552 552
                         print '<option value="'.$lines[$i]->fk_project.'_0"';
553 553
                         if ($selectedproject == $lines[$i]->fk_project) print ' selected';
554
-                        print '>';	// Project -> Task
554
+                        print '>'; // Project -> Task
555 555
                         print $langs->trans("Project").' '.$lines[$i]->projectref;
556 556
                         if (empty($lines[$i]->public))
557 557
                         {
@@ -564,22 +564,22 @@  discard block
 block discarded – undo
564 564
                         //print '-'.$parent.'-'.$lines[$i]->fk_project.'-'.$lastprojectid;
565 565
                         print "</option>\n";
566 566
 
567
-                        $lastprojectid=$lines[$i]->fk_project;
567
+                        $lastprojectid = $lines[$i]->fk_project;
568 568
                         $inc++;
569 569
                     }
570 570
                 }
571 571
 
572
-                $newdisablechildoftaskid=$disablechildoftaskid;
572
+                $newdisablechildoftaskid = $disablechildoftaskid;
573 573
 
574 574
                 // Print task
575 575
                 if (isset($lines[$i]->id))		// We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
576 576
                 {
577 577
                 	// Check if we must disable entry
578
-                	$disabled=0;
578
+                	$disabled = 0;
579 579
                 	if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
580 580
                 	{
581 581
                			$disabled++;
582
-               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id;	// If task is child of a disabled parent, we will propagate id to disable next child too
582
+               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too
583 583
                 	}
584 584
 
585 585
                     print '<option value="'.$lines[$i]->fk_project.'_'.$lines[$i]->id.'"';
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
                         print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
598 598
                     }
599 599
                     if ($lines[$i]->id) print ' > ';
600
-                    for ($k = 0 ; $k < $level ; $k++)
600
+                    for ($k = 0; $k < $level; $k++)
601 601
                     {
602 602
                         print "&nbsp;&nbsp;&nbsp;";
603 603
                     }
@@ -621,13 +621,13 @@  discard block
 block discarded – undo
621 621
      * 		@return	string							HTML code for color thumb
622 622
      *		@see selectColor
623 623
      */
624
-    static function showColor($color, $textifnotdefined='')
624
+    static function showColor($color, $textifnotdefined = '')
625 625
     {
626
-    	$textcolor='FFF';
626
+    	$textcolor = 'FFF';
627 627
     	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
628
-    	if(colorIsLight($color)) $textcolor='000';
628
+    	if (colorIsLight($color)) $textcolor = '000';
629 629
 
630
-    	$color = colorArrayToHex(colorStringToArray($color,array()),'');
630
+    	$color = colorArrayToHex(colorStringToArray($color, array()), '');
631 631
 
632 632
 		if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
633 633
 		else print $textifnotdefined;
@@ -646,7 +646,7 @@  discard block
 block discarded – undo
646 646
      * 		@deprecated Use instead selectColor
647 647
      *      @see selectColor()
648 648
      */
649
-    function select_color($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='')
649
+    function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '')
650 650
     {
651 651
         // phpcs:enable
652 652
     	print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors);
@@ -664,25 +664,25 @@  discard block
 block discarded – undo
664 664
      * 		@return	string
665 665
      *		@see showColor
666 666
      */
667
-    static function selectColor($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='', $morecss='')
667
+    static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '')
668 668
     {
669 669
 	    // Deprecation warning
670 670
 	    if ($form_name) {
671
-		    dol_syslog(__METHOD__ . ": form_name parameter is deprecated", LOG_WARNING);
671
+		    dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING);
672 672
 	    }
673 673
 
674
-        global $langs,$conf;
674
+        global $langs, $conf;
675 675
 
676
-        $out='';
676
+        $out = '';
677 677
 
678
-        if (! is_array($arrayofcolors) || count($arrayofcolors) < 1)
678
+        if (!is_array($arrayofcolors) || count($arrayofcolors) < 1)
679 679
         {
680 680
             $langs->load("other");
681 681
             if (empty($conf->dol_use_jmobile))
682 682
             {
683
-	            $out.= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
684
-	            $out.= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
685
-	            $out.= '<script type="text/javascript">
683
+	            $out .= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
684
+	            $out .= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
685
+	            $out .= '<script type="text/javascript">
686 686
 	             jQuery(document).ready(function(){
687 687
 	                $(\'#colorpicker'.$prefix.'\').jPicker( {
688 688
 	                window: {
@@ -720,15 +720,15 @@  discard block
 block discarded – undo
720 720
 			        } ); });
721 721
 	             </script>';
722 722
             }
723
-            $out.= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss?' '.$morecss:'').'" type="text" value="'.$set_color.'" />';
723
+            $out .= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss ? ' '.$morecss : '').'" type="text" value="'.$set_color.'" />';
724 724
         }
725 725
         else  // In most cases, this is not used. We used instead function with no specific list of colors
726 726
         {
727 727
             if (empty($conf->dol_use_jmobile))
728 728
             {
729
-	        	$out.= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
730
-	            $out.= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
731
-	            $out.= '<script type="text/javascript">
729
+	        	$out .= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
730
+	            $out .= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
731
+	            $out .= '<script type="text/javascript">
732 732
 	             jQuery(document).ready(function(){
733 733
 	                 jQuery(\'#colorpicker'.$prefix.'\').colorpicker({
734 734
 	                     size: 14,
@@ -738,15 +738,15 @@  discard block
 block discarded – undo
738 738
 	             });
739 739
 	             </script>';
740 740
             }
741
-            $out.= '<select id="colorpicker'.$prefix.'" class="flat'.($morecss?' '.$morecss:'').'" name="'.$prefix.'">';
741
+            $out .= '<select id="colorpicker'.$prefix.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$prefix.'">';
742 742
             //print '<option value="-1">&nbsp;</option>';
743 743
             foreach ($arrayofcolors as $val)
744 744
             {
745
-                $out.= '<option value="'.$val.'"';
746
-                if ($set_color == $val) $out.= ' selected';
747
-                $out.= '>'.$val.'</option>';
745
+                $out .= '<option value="'.$val.'"';
746
+                if ($set_color == $val) $out .= ' selected';
747
+                $out .= '>'.$val.'</option>';
748 748
             }
749
-            $out.= '</select>';
749
+            $out .= '</select>';
750 750
         }
751 751
 
752 752
         return $out;
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
      *	@param	int		$y      	Hauteur de l'image en pixels
764 764
      *	@return	void
765 765
      */
766
-    function CreateColorIcon($color,$module,$name,$x='12',$y='12')
766
+    function CreateColorIcon($color, $module, $name, $x = '12', $y = '12')
767 767
     {
768 768
         // phpcs:enable
769 769
         global $conf;
@@ -771,25 +771,25 @@  discard block
 block discarded – undo
771 771
         $file = $conf->$module->dir_temp.'/'.$name.'.png';
772 772
 
773 773
         // On cree le repertoire contenant les icones
774
-        if (! file_exists($conf->$module->dir_temp))
774
+        if (!file_exists($conf->$module->dir_temp))
775 775
         {
776 776
             dol_mkdir($conf->$module->dir_temp);
777 777
         }
778 778
 
779 779
         // On cree l'image en vraies couleurs
780
-        $image = imagecreatetruecolor($x,$y);
780
+        $image = imagecreatetruecolor($x, $y);
781 781
 
782
-        $color = substr($color,1,6);
782
+        $color = substr($color, 1, 6);
783 783
 
784
-        $rouge = hexdec(substr($color,0,2)); //conversion du canal rouge
785
-        $vert  = hexdec(substr($color,2,2)); //conversion du canal vert
786
-        $bleu  = hexdec(substr($color,4,2)); //conversion du canal bleu
784
+        $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge
785
+        $vert  = hexdec(substr($color, 2, 2)); //conversion du canal vert
786
+        $bleu  = hexdec(substr($color, 4, 2)); //conversion du canal bleu
787 787
 
788
-        $couleur = imagecolorallocate($image,$rouge,$vert,$bleu);
788
+        $couleur = imagecolorallocate($image, $rouge, $vert, $bleu);
789 789
         //print $rouge.$vert.$bleu;
790
-        imagefill($image,0,0,$couleur); //on remplit l'image
790
+        imagefill($image, 0, 0, $couleur); //on remplit l'image
791 791
         // On cree la couleur et on l'attribue a une variable pour ne pas la perdre
792
-        ImagePng($image,$file); //renvoie une image sous format png
792
+        ImagePng($image, $file); //renvoie une image sous format png
793 793
         ImageDestroy($image);
794 794
     }
795 795
 
@@ -802,7 +802,7 @@  discard block
 block discarded – undo
802 802
      *    	@param  int			$useempty          Affiche valeur vide dans liste
803 803
      *    	@return	string
804 804
      */
805
-    function select_dayofweek($selected='',$htmlname='weekid',$useempty=0)
805
+    function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0)
806 806
     {
807 807
         // phpcs:enable
808 808
         global $langs;
@@ -850,17 +850,17 @@  discard block
 block discarded – undo
850 850
      *      @param	string		$morecss			More Css
851 851
      *      @return string
852 852
      */
853
-    function select_month($selected='', $htmlname='monthid', $useempty=0, $longlabel=0, $morecss='')
853
+    function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = '')
854 854
     {
855 855
         // phpcs:enable
856 856
         global $langs;
857 857
 
858 858
         require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
859 859
 
860
-        if ($longlabel) $montharray = monthArray($langs, 0);	// Get array
860
+        if ($longlabel) $montharray = monthArray($langs, 0); // Get array
861 861
         else $montharray = monthArray($langs, 1);
862 862
 
863
-        $select_month = '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
863
+        $select_month = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
864 864
         if ($useempty)
865 865
         {
866 866
             $select_month .= '<option value="0">&nbsp;</option>';
@@ -897,10 +897,10 @@  discard block
 block discarded – undo
897 897
      *  @param	string		$morecss		More CSS
898 898
      *  @return	string
899 899
      */
900
-    function select_year($selected='',$htmlname='yearid',$useempty=0, $min_year=10, $max_year=5, $offset=0, $invert=0, $option='', $morecss='valignmiddle widthauto')
900
+    function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle widthauto')
901 901
     {
902 902
         // phpcs:enable
903
-        print $this->selectyear($selected,$htmlname,$useempty,$min_year,$max_year,$offset,$invert,$option,$morecss);
903
+        print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss);
904 904
     }
905 905
 
906 906
     /**
@@ -917,41 +917,41 @@  discard block
 block discarded – undo
917 917
      *  @param	string	$morecss		More css
918 918
      *  @return	string
919 919
      */
920
-    function selectyear($selected='',$htmlname='yearid',$useempty=0, $min_year=10, $max_year=5, $offset=0, $invert=0, $option='', $morecss='valignmiddle widthauto')
920
+    function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle widthauto')
921 921
     {
922
-        $out='';
922
+        $out = '';
923 923
 
924
-        $currentyear = date("Y")+$offset;
925
-        $max_year = $currentyear+$max_year;
926
-        $min_year = $currentyear-$min_year;
927
-        if(empty($selected) && empty($useempty)) $selected = $currentyear;
924
+        $currentyear = date("Y") + $offset;
925
+        $max_year = $currentyear + $max_year;
926
+        $min_year = $currentyear - $min_year;
927
+        if (empty($selected) && empty($useempty)) $selected = $currentyear;
928 928
 
929
-        $out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="' . $htmlname . '" name="' . $htmlname . '"'.$option.' >';
930
-        if($useempty)
929
+        $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$option.' >';
930
+        if ($useempty)
931 931
         {
932
-        	$selected_html='';
932
+        	$selected_html = '';
933 933
             if ($selected == '') $selected_html = ' selected';
934
-            $out.= '<option value=""' . $selected_html . '>&nbsp;</option>';
934
+            $out .= '<option value=""'.$selected_html.'>&nbsp;</option>';
935 935
         }
936
-        if (! $invert)
936
+        if (!$invert)
937 937
         {
938 938
             for ($y = $max_year; $y >= $min_year; $y--)
939 939
             {
940
-                $selected_html='';
940
+                $selected_html = '';
941 941
                 if ($selected > 0 && $y == $selected) $selected_html = ' selected';
942
-                $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
942
+                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
943 943
             }
944 944
         }
945 945
         else
946 946
         {
947 947
             for ($y = $min_year; $y <= $max_year; $y++)
948 948
             {
949
-                $selected_html='';
949
+                $selected_html = '';
950 950
                 if ($selected > 0 && $y == $selected) $selected_html = ' selected';
951
-                $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
951
+                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
952 952
             }
953 953
         }
954
-        $out.= "</select>\n";
954
+        $out .= "</select>\n";
955 955
 
956 956
         return $out;
957 957
     }
@@ -968,10 +968,10 @@  discard block
 block discarded – undo
968 968
      * @param  	int		$originid      	Id de l'origine
969 969
      * @return	void
970 970
      */
971
-    function form_address($page, $selected, $socid, $htmlname='address_id', $origin='', $originid='')
971
+    function form_address($page, $selected, $socid, $htmlname = 'address_id', $origin = '', $originid = '')
972 972
     {
973 973
         // phpcs:enable
974
-        global $langs,$conf;
974
+        global $langs, $conf;
975 975
         global $form;
976 976
 
977 977
         if ($htmlname != "none")
@@ -989,9 +989,9 @@  discard block
 block discarded – undo
989 989
         {
990 990
             if ($selected)
991 991
             {
992
-                require_once DOL_DOCUMENT_ROOT .'/societe/class/address.class.php';
993
-                $address=new Address($this->db);
994
-                $result=$address->fetch_address($selected);
992
+                require_once DOL_DOCUMENT_ROOT.'/societe/class/address.class.php';
993
+                $address = new Address($this->db);
994
+                $result = $address->fetch_address($selected);
995 995
                 print '<a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$address->socid.'&id='.$address->id.'&action=edit&origin='.$origin.'&originid='.$originid.'>'.$address->label.'</a>';
996 996
             }
997 997
             else
@@ -1011,72 +1011,72 @@  discard block
 block discarded – undo
1011 1011
      * 	@param	   String       $areacode    Code of area for pages ('0'=value for Home page)
1012 1012
      * 	@return    array                     array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>)
1013 1013
      */
1014
-    static function getBoxesArea($user,$areacode)
1014
+    static function getBoxesArea($user, $areacode)
1015 1015
     {
1016
-        global $conf,$langs,$db;
1016
+        global $conf, $langs, $db;
1017 1017
 
1018 1018
         include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1019 1019
 
1020
-        $confuserzone='MAIN_BOXES_'.$areacode;
1020
+        $confuserzone = 'MAIN_BOXES_'.$areacode;
1021 1021
 
1022 1022
         // $boxactivated will be array of boxes enabled into global setup
1023 1023
         // $boxidactivatedforuser will be array of boxes choosed by user
1024 1024
 
1025
-        $selectboxlist='';
1026
-        $boxactivated=InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone)?null:$user), array(), 0);	// Search boxes of common+user (or common only if user has no specific setup)
1025
+        $selectboxlist = '';
1026
+        $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup)
1027 1027
 
1028
-        $boxidactivatedforuser=array();
1029
-        foreach($boxactivated as $box)
1028
+        $boxidactivatedforuser = array();
1029
+        foreach ($boxactivated as $box)
1030 1030
         {
1031
-        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id;	// We keep only boxes to show for user
1031
+        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user
1032 1032
         }
1033 1033
 
1034 1034
         // Define selectboxlist
1035
-        $arrayboxtoactivatelabel=array();
1036
-        if (! empty($user->conf->$confuserzone))
1035
+        $arrayboxtoactivatelabel = array();
1036
+        if (!empty($user->conf->$confuserzone))
1037 1037
         {
1038
-        	$boxorder='';
1039
-        	$langs->load("boxes");	// Load label of boxes
1040
-        	foreach($boxactivated as $box)
1038
+        	$boxorder = '';
1039
+        	$langs->load("boxes"); // Load label of boxes
1040
+        	foreach ($boxactivated as $box)
1041 1041
         	{
1042
-        		if (! empty($boxidactivatedforuser[$box->id])) continue;	// Already visible for user
1043
-        		$label=$langs->transnoentitiesnoconv($box->boxlabel);
1042
+        		if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user
1043
+        		$label = $langs->transnoentitiesnoconv($box->boxlabel);
1044 1044
         		//if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1045
-        		if (preg_match('/graph/',$box->class) && $conf->browser->layout != 'phone')
1045
+        		if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone')
1046 1046
         		{
1047
-        			$label=$label.' <span class="fa fa-bar-chart"></span>';
1047
+        			$label = $label.' <span class="fa fa-bar-chart"></span>';
1048 1048
         		}
1049
-        		$arrayboxtoactivatelabel[$box->id]=$label;			// We keep only boxes not shown for user, to show into combo list
1049
+        		$arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list
1050 1050
         	}
1051
-            foreach($boxidactivatedforuser as $boxid)
1051
+            foreach ($boxidactivatedforuser as $boxid)
1052 1052
         	{
1053
-       			if (empty($boxorder)) $boxorder.='A:';
1054
-  				$boxorder.=$boxid.',';
1053
+       			if (empty($boxorder)) $boxorder .= 'A:';
1054
+  				$boxorder .= $boxid.',';
1055 1055
         	}
1056 1056
 
1057 1057
         	//var_dump($boxidactivatedforuser);
1058 1058
 
1059 1059
         	// Class Form must have been already loaded
1060
-        	$selectboxlist.='<!-- Form with select box list -->'."\n";
1061
-			$selectboxlist.='<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1062
-			$selectboxlist.='<input type="hidden" name="addbox" value="addbox">';
1063
-			$selectboxlist.='<input type="hidden" name="userid" value="'.$user->id.'">';
1064
-			$selectboxlist.='<input type="hidden" name="areacode" value="'.$areacode.'">';
1065
-			$selectboxlist.='<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1066
-			$selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1067
-            if (empty($conf->use_javascript_ajax)) $selectboxlist.=' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1068
-            $selectboxlist.='</form>';
1069
-            if (! empty($conf->use_javascript_ajax))
1060
+        	$selectboxlist .= '<!-- Form with select box list -->'."\n";
1061
+			$selectboxlist .= '<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1062
+			$selectboxlist .= '<input type="hidden" name="addbox" value="addbox">';
1063
+			$selectboxlist .= '<input type="hidden" name="userid" value="'.$user->id.'">';
1064
+			$selectboxlist .= '<input type="hidden" name="areacode" value="'.$areacode.'">';
1065
+			$selectboxlist .= '<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1066
+			$selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1067
+            if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1068
+            $selectboxlist .= '</form>';
1069
+            if (!empty($conf->use_javascript_ajax))
1070 1070
             {
1071
-            	include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1072
-            	$selectboxlist.=ajax_combobox("boxcombo");
1071
+            	include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1072
+            	$selectboxlist .= ajax_combobox("boxcombo");
1073 1073
             }
1074 1074
         }
1075 1075
 
1076 1076
         // Javascript code for dynamic actions
1077
-        if (! empty($conf->use_javascript_ajax))
1077
+        if (!empty($conf->use_javascript_ajax))
1078 1078
         {
1079
-	        $selectboxlist.='<script type="text/javascript" language="javascript">
1079
+	        $selectboxlist .= '<script type="text/javascript" language="javascript">
1080 1080
 
1081 1081
 	        // To update list of activated boxes
1082 1082
 	        function updateBoxOrder(closing) {
@@ -1090,7 +1090,7 @@  discard block
 block discarded – undo
1090 1090
 	        			async: false
1091 1091
 	        		});
1092 1092
 	        		// We force reload to be sure to get all boxes into list
1093
-	        		window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=delbox\';
1093
+	        		window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=delbox\';
1094 1094
 	        	}
1095 1095
 	        	else
1096 1096
 	        	{
@@ -1112,11 +1112,11 @@  discard block
 block discarded – undo
1112 1112
 	    					url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&boxid=\'+boxid+\'&zone='.$areacode.'&userid='.$user->id.'\',
1113 1113
 	    			        async: false
1114 1114
 	    		        });
1115
-	        			window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=addbox&boxid=\'+boxid;
1115
+	        			window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=addbox&boxid=\'+boxid;
1116 1116
 	                }
1117 1117
 	        	});';
1118
-	        	if (! count($arrayboxtoactivatelabel)) $selectboxlist.='jQuery("#boxcombo").hide();';
1119
-	        	$selectboxlist.='
1118
+	        	if (!count($arrayboxtoactivatelabel)) $selectboxlist .= 'jQuery("#boxcombo").hide();';
1119
+	        	$selectboxlist .= '
1120 1120
 
1121 1121
 	        	jQuery("#boxhalfleft, #boxhalfright").sortable({
1122 1122
 	    	    	handle: \'.boxhandle\',
@@ -1141,80 +1141,80 @@  discard block
 block discarded – undo
1141 1141
 
1142 1142
         	});'."\n";
1143 1143
 
1144
-	        $selectboxlist.='</script>'."\n";
1144
+	        $selectboxlist .= '</script>'."\n";
1145 1145
         }
1146 1146
 
1147 1147
         // Define boxlista and boxlistb
1148
-        $nbboxactivated=count($boxidactivatedforuser);
1148
+        $nbboxactivated = count($boxidactivatedforuser);
1149 1149
 
1150 1150
         if ($nbboxactivated)
1151 1151
         {
1152 1152
         	// Load translation files required by the page
1153
-            $langs->loadLangs(array("boxes","projects"));
1153
+            $langs->loadLangs(array("boxes", "projects"));
1154 1154
 
1155
-        	$emptybox=new ModeleBoxes($db);
1155
+        	$emptybox = new ModeleBoxes($db);
1156 1156
 
1157
-            $boxlista.="\n<!-- Box left container -->\n";
1157
+            $boxlista .= "\n<!-- Box left container -->\n";
1158 1158
 
1159 1159
             // Define $box_max_lines
1160
-            $box_max_lines=5;
1161
-            if (! empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines=$conf->global->MAIN_BOXES_MAXLINES;
1160
+            $box_max_lines = 5;
1161
+            if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES;
1162 1162
 
1163
-            $ii=0;
1163
+            $ii = 0;
1164 1164
             foreach ($boxactivated as $key => $box)
1165 1165
             {
1166
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1167
-				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1168
-            	if (preg_match('/^A/i',$box->box_order)) // column A
1166
+            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1167
+				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1168
+            	if (preg_match('/^A/i', $box->box_order)) // column A
1169 1169
                 {
1170 1170
                     $ii++;
1171 1171
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1172 1172
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1173 1173
                     // Show box
1174 1174
                     $box->loadBox($box_max_lines);
1175
-                    $boxlista.= $box->outputBox();
1175
+                    $boxlista .= $box->outputBox();
1176 1176
                 }
1177 1177
             }
1178 1178
 
1179 1179
             if ($conf->browser->layout != 'phone')
1180 1180
             {
1181
-            	$emptybox->box_id='A';
1182
-            	$emptybox->info_box_head=array();
1183
-            	$emptybox->info_box_contents=array();
1184
-            	$boxlista.= $emptybox->outputBox(array(),array());
1181
+            	$emptybox->box_id = 'A';
1182
+            	$emptybox->info_box_head = array();
1183
+            	$emptybox->info_box_contents = array();
1184
+            	$boxlista .= $emptybox->outputBox(array(), array());
1185 1185
             }
1186
-            $boxlista.= "<!-- End box left container -->\n";
1186
+            $boxlista .= "<!-- End box left container -->\n";
1187 1187
 
1188
-            $boxlistb.= "\n<!-- Box right container -->\n";
1188
+            $boxlistb .= "\n<!-- Box right container -->\n";
1189 1189
 
1190
-            $ii=0;
1190
+            $ii = 0;
1191 1191
             foreach ($boxactivated as $key => $box)
1192 1192
             {
1193
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1194
-            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1195
-            	if (preg_match('/^B/i',$box->box_order)) // colonne B
1193
+            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1194
+            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1195
+            	if (preg_match('/^B/i', $box->box_order)) // colonne B
1196 1196
                 {
1197 1197
                     $ii++;
1198 1198
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1199 1199
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1200 1200
                     // Show box
1201 1201
                     $box->loadBox($box_max_lines);
1202
-                    $boxlistb.= $box->outputBox();
1202
+                    $boxlistb .= $box->outputBox();
1203 1203
                 }
1204 1204
             }
1205 1205
 
1206 1206
             if ($conf->browser->layout != 'phone')
1207 1207
             {
1208
-            	$emptybox->box_id='B';
1209
-            	$emptybox->info_box_head=array();
1210
-            	$emptybox->info_box_contents=array();
1211
-            	$boxlistb.= $emptybox->outputBox(array(),array());
1208
+            	$emptybox->box_id = 'B';
1209
+            	$emptybox->info_box_head = array();
1210
+            	$emptybox->info_box_contents = array();
1211
+            	$boxlistb .= $emptybox->outputBox(array(), array());
1212 1212
             }
1213 1213
 
1214
-            $boxlistb.= "<!-- End box right container -->\n";
1214
+            $boxlistb .= "<!-- End box right container -->\n";
1215 1215
         }
1216 1216
 
1217
-        return array('selectboxlist'=>count($boxactivated)?$selectboxlist:'', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb);
1217
+        return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb);
1218 1218
     }
1219 1219
 
1220 1220
 
@@ -1231,7 +1231,7 @@  discard block
 block discarded – undo
1231 1231
      *  @param  string  $moreattrib         More attributes on HTML select tag
1232 1232
      * 	@return	void
1233 1233
      */
1234
-    function select_dictionary($htmlname,$dictionarytable,$keyfield='code',$labelfield='label',$selected='',$useempty=0,$moreattrib='')
1234
+    function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '')
1235 1235
     {
1236 1236
         // phpcs:enable
1237 1237
         global $langs, $conf;
@@ -1239,8 +1239,8 @@  discard block
 block discarded – undo
1239 1239
         $langs->load("admin");
1240 1240
 
1241 1241
         $sql = "SELECT rowid, ".$keyfield.", ".$labelfield;
1242
-        $sql.= " FROM ".MAIN_DB_PREFIX.$dictionarytable;
1243
-        $sql.= " ORDER BY ".$labelfield;
1242
+        $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable;
1243
+        $sql .= " ORDER BY ".$labelfield;
1244 1244
 
1245 1245
         dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG);
1246 1246
         $result = $this->db->query($sql);
@@ -1250,7 +1250,7 @@  discard block
 block discarded – undo
1250 1250
             $i = 0;
1251 1251
             if ($num)
1252 1252
             {
1253
-                print '<select id="select'.$htmlname.'" class="flat selectdictionary" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
1253
+                print '<select id="select'.$htmlname.'" class="flat selectdictionary" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
1254 1254
                 if ($useempty == 1 || ($useempty == 2 && $num > 1))
1255 1255
                 {
1256 1256
                     print '<option value="-1">&nbsp;</option>';
Please login to merge, or discard this patch.
Braces   +145 added lines, -83 removed lines patch added patch discarded remove patch
@@ -73,7 +73,9 @@  discard block
 block discarded – undo
73 73
         $sql = "SELECT rowid, label";
74 74
         $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
75 75
         $sql.= " WHERE type = '".$type."'";
76
-		if (!empty($fk_user)) $sql.=" AND fk_user=".$fk_user;
76
+		if (!empty($fk_user)) {
77
+		    $sql.=" AND fk_user=".$fk_user;
78
+		}
77 79
         $sql.= " ORDER BY rowid";
78 80
         $result = $this->db->query($sql);
79 81
         if ($result)
@@ -92,8 +94,7 @@  discard block
 block discarded – undo
92 94
                 if ($selected == $obj->rowid)
93 95
                 {
94 96
                     print '<option value="'.$obj->rowid.'" selected>';
95
-                }
96
-                else
97
+                } else
97 98
                 {
98 99
                     print '<option value="'.$obj->rowid.'">';
99 100
                 }
@@ -102,8 +103,7 @@  discard block
 block discarded – undo
102 103
                 $i++;
103 104
             }
104 105
             print "</select>";
105
-        }
106
-        else {
106
+        } else {
107 107
             dol_print_error($this->db);
108 108
         }
109 109
     }
@@ -143,8 +143,7 @@  discard block
 block discarded – undo
143 143
                 if ($selected == $obj->rowid)
144 144
                 {
145 145
                     print '<option value="'.$obj->rowid.'" selected>';
146
-                }
147
-                else
146
+                } else
148 147
                 {
149 148
                     print '<option value="'.$obj->rowid.'">';
150 149
                 }
@@ -153,8 +152,7 @@  discard block
 block discarded – undo
153 152
                 $i++;
154 153
             }
155 154
             print "</select>";
156
-        }
157
-        else {
155
+        } else {
158 156
             dol_print_error($this->db);
159 157
         }
160 158
     }
@@ -195,8 +193,7 @@  discard block
 block discarded – undo
195 193
                     if ($selected && $selected == $obj->rowid)
196 194
                     {
197 195
                         print '<option value="'.$obj->rowid.'" selected>';
198
-                    }
199
-                    else
196
+                    } else
200 197
                     {
201 198
                         print '<option value="'.$obj->rowid.'">';
202 199
                         //print '<option onmouseover="showtip(\''.$obj->label.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
@@ -209,8 +206,7 @@  discard block
 block discarded – undo
209 206
             }
210 207
             print '</select>';
211 208
             return 0;
212
-        }
213
-        else
209
+        } else
214 210
         {
215 211
             dol_print_error($this->db);
216 212
             return 1;
@@ -255,8 +251,7 @@  discard block
 block discarded – undo
255 251
     				if (($selected && $selected == $obj->taux) || $num == 1)
256 252
     				{
257 253
     					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
258
-    				}
259
-    				else
254
+    				} else
260 255
     				{
261 256
     					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
262 257
     					//print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
@@ -268,8 +263,7 @@  discard block
 block discarded – undo
268 263
     		}
269 264
     		$out.='</select>';
270 265
     		return $out;
271
-    	}
272
-    	else
266
+    	} else
273 267
     	{
274 268
     		dol_print_error($this->db);
275 269
     		return '';
@@ -294,15 +288,16 @@  discard block
 block discarded – undo
294 288
     {
295 289
         // phpcs:enable
296 290
         $return = '<select class="flat" name="'.$htmlname.'" '.($disabled?'disabled':'').'>';
297
-        if ($showempty) $return.='<option value="-1"'.(($selected == -1 || $selected == '')?' selected':'').'>&nbsp;</option>';
291
+        if ($showempty) {
292
+            $return.='<option value="-1"'.(($selected == -1 || $selected == '')?' selected':'').'>&nbsp;</option>';
293
+        }
298 294
 
299 295
         for ($i = $start ; $i <= $end ; $i += $increment)
300 296
         {
301 297
             if ($selected != '' && (int) $selected == $i)
302 298
             {
303 299
                 $return.= '<option value="'.$i.'" selected>';
304
-            }
305
-            else
300
+            } else
306 301
             {
307 302
                 $return.= '<option value="'.$i.'">';
308 303
             }
@@ -355,14 +350,19 @@  discard block
 block discarded – undo
355 350
 
356 351
         // Print a select with each of them
357 352
         $moreforfilter.='<select class="flat minwidth100'.($morecss?' '.$morecss:'').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
358
-        if ($showempty) $moreforfilter.='<option value="0">&nbsp;</option>';	// Should use -1 to say nothing
353
+        if ($showempty) {
354
+            $moreforfilter.='<option value="0">&nbsp;</option>';
355
+        }
356
+        // Should use -1 to say nothing
359 357
 
360 358
         if (is_array($tab_categs))
361 359
         {
362 360
             foreach ($tab_categs as $categ)
363 361
             {
364 362
                 $moreforfilter.='<option value="'.$categ['id'].'"';
365
-                if ($categ['id'] == $selected) $moreforfilter.=' selected';
363
+                if ($categ['id'] == $selected) {
364
+                    $moreforfilter.=' selected';
365
+                }
366 366
                 $moreforfilter.='>'.dol_trunc($categ['fulllabel'],50,'middle').'</option>';
367 367
             }
368 368
         }
@@ -409,14 +409,20 @@  discard block
 block discarded – undo
409 409
         }
410 410
         // Select each sales and print them in a select input
411 411
         $out.='<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
412
-        if ($showempty) $out.='<option value="0">&nbsp;</option>';
412
+        if ($showempty) {
413
+            $out.='<option value="0">&nbsp;</option>';
414
+        }
413 415
 
414 416
         // Get list of users allowed to be viewed
415 417
         $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login";
416 418
         $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u";
417 419
         $sql_usr.= " WHERE u.entity IN (0,".$conf->entity.")";
418
-        if (empty($user->rights->user->user->lire)) $sql_usr.=" AND u.rowid = ".$user->id;
419
-        if (! empty($user->societe_id)) $sql_usr.=" AND u.fk_soc = ".$user->societe_id;
420
+        if (empty($user->rights->user->user->lire)) {
421
+            $sql_usr.=" AND u.rowid = ".$user->id;
422
+        }
423
+        if (! empty($user->societe_id)) {
424
+            $sql_usr.=" AND u.fk_soc = ".$user->societe_id;
425
+        }
420 426
         // Add existing sales representatives of thirdparty of external user
421 427
         if (empty($user->rights->user->user->lire) && $user->societe_id)
422 428
         {
@@ -437,7 +443,9 @@  discard block
 block discarded – undo
437 443
 
438 444
                 $out.='<option value="'.$obj_usr->rowid.'"';
439 445
 
440
-                if ($obj_usr->rowid == $selected) $out.=' selected';
446
+                if ($obj_usr->rowid == $selected) {
447
+                    $out.=' selected';
448
+                }
441 449
 
442 450
                 $out.='>';
443 451
                 $out.=dolGetFirstLastname($obj_usr->firstname,$obj_usr->lastname);
@@ -465,8 +473,7 @@  discard block
 block discarded – undo
465 473
                 $out.='</option>';
466 474
             }
467 475
             $this->db->free($resql_usr);
468
-        }
469
-        else
476
+        } else
470 477
         {
471 478
             dol_print_error($this->db);
472 479
         }
@@ -502,15 +509,16 @@  discard block
 block discarded – undo
502 509
         if ($tasksarray)
503 510
         {
504 511
         	print '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
505
-            if ($useempty) print '<option value="0">&nbsp;</option>';
512
+            if ($useempty) {
513
+                print '<option value="0">&nbsp;</option>';
514
+            }
506 515
             $j=0;
507 516
             $level=0;
508 517
             $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid);
509 518
             print '</select>';
510 519
 
511 520
             print ajax_combobox($htmlname);
512
-        }
513
-        else
521
+        } else
514 522
         {
515 523
             print '<div class="warning">'.$langs->trans("NoProject").'</div>';
516 524
         }
@@ -544,20 +552,23 @@  discard block
 block discarded – undo
544 552
 				//var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id);		// $lines[$i]->id may be empty if project has no lines
545 553
 
546 554
                 // Break on a new project
547
-                if ($parent == 0)	// We are on a task at first level
555
+                if ($parent == 0) {
556
+                    // We are on a task at first level
548 557
                 {
549 558
                     if ($lines[$i]->fk_project != $lastprojectid)	// Break found on project
550 559
                     {
551 560
                         if ($i > 0) print '<option value="0" disabled>----------</option>';
561
+                }
552 562
                         print '<option value="'.$lines[$i]->fk_project.'_0"';
553
-                        if ($selectedproject == $lines[$i]->fk_project) print ' selected';
563
+                        if ($selectedproject == $lines[$i]->fk_project) {
564
+                            print ' selected';
565
+                        }
554 566
                         print '>';	// Project -> Task
555 567
                         print $langs->trans("Project").' '.$lines[$i]->projectref;
556 568
                         if (empty($lines[$i]->public))
557 569
                         {
558 570
                             print ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')';
559
-                        }
560
-                        else
571
+                        } else
561 572
                         {
562 573
                             print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
563 574
                         }
@@ -572,31 +583,41 @@  discard block
 block discarded – undo
572 583
                 $newdisablechildoftaskid=$disablechildoftaskid;
573 584
 
574 585
                 // Print task
575
-                if (isset($lines[$i]->id))		// We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
586
+                if (isset($lines[$i]->id)) {
587
+                    // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
576 588
                 {
577 589
                 	// Check if we must disable entry
578 590
                 	$disabled=0;
591
+                }
579 592
                 	if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
580 593
                 	{
581 594
                			$disabled++;
582
-               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id;	// If task is child of a disabled parent, we will propagate id to disable next child too
595
+               			if ($lines[$i]->fk_parent == $disablechildoftaskid) {
596
+               			    $newdisablechildoftaskid=$lines[$i]->id;
597
+               			}
598
+               			// If task is child of a disabled parent, we will propagate id to disable next child too
583 599
                 	}
584 600
 
585 601
                     print '<option value="'.$lines[$i]->fk_project.'_'.$lines[$i]->id.'"';
586
-                    if (($lines[$i]->id == $selectedtask) || ($lines[$i]->fk_project.'_'.$lines[$i]->id == $selectedtask)) print ' selected';
587
-                    if ($disabled) print ' disabled';
602
+                    if (($lines[$i]->id == $selectedtask) || ($lines[$i]->fk_project.'_'.$lines[$i]->id == $selectedtask)) {
603
+                        print ' selected';
604
+                    }
605
+                    if ($disabled) {
606
+                        print ' disabled';
607
+                    }
588 608
                     print '>';
589 609
                     print $langs->trans("Project").' '.$lines[$i]->projectref;
590 610
                     print ' '.$lines[$i]->projectlabel;
591 611
                     if (empty($lines[$i]->public))
592 612
                     {
593 613
                         print ' ('.$langs->trans("Visibility").': '.$langs->trans("PrivateProject").')';
594
-                    }
595
-                    else
614
+                    } else
596 615
                     {
597 616
                         print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
598 617
                     }
599
-                    if ($lines[$i]->id) print ' > ';
618
+                    if ($lines[$i]->id) {
619
+                        print ' > ';
620
+                    }
600 621
                     for ($k = 0 ; $k < $level ; $k++)
601 622
                     {
602 623
                         print "&nbsp;&nbsp;&nbsp;";
@@ -606,7 +627,9 @@  discard block
 block discarded – undo
606 627
                 }
607 628
 
608 629
                 $level++;
609
-                if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid);
630
+                if ($lines[$i]->id) {
631
+                    $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid);
632
+                }
610 633
                 $level--;
611 634
             }
612 635
         }
@@ -625,12 +648,17 @@  discard block
 block discarded – undo
625 648
     {
626 649
     	$textcolor='FFF';
627 650
     	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
628
-    	if(colorIsLight($color)) $textcolor='000';
651
+    	if(colorIsLight($color)) {
652
+    	    $textcolor='000';
653
+    	}
629 654
 
630 655
     	$color = colorArrayToHex(colorStringToArray($color,array()),'');
631 656
 
632
-		if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
633
-		else print $textifnotdefined;
657
+		if ($color) {
658
+		    print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
659
+		} else {
660
+		    print $textifnotdefined;
661
+		}
634 662
     }
635 663
 
636 664
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -721,8 +749,7 @@  discard block
 block discarded – undo
721 749
 	             </script>';
722 750
             }
723 751
             $out.= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss?' '.$morecss:'').'" type="text" value="'.$set_color.'" />';
724
-        }
725
-        else  // In most cases, this is not used. We used instead function with no specific list of colors
752
+        } else  // In most cases, this is not used. We used instead function with no specific list of colors
726 753
         {
727 754
             if (empty($conf->dol_use_jmobile))
728 755
             {
@@ -743,7 +770,9 @@  discard block
 block discarded – undo
743 770
             foreach ($arrayofcolors as $val)
744 771
             {
745 772
                 $out.= '<option value="'.$val.'"';
746
-                if ($set_color == $val) $out.= ' selected';
773
+                if ($set_color == $val) {
774
+                    $out.= ' selected';
775
+                }
747 776
                 $out.= '>'.$val.'</option>';
748 777
             }
749 778
             $out.= '</select>';
@@ -827,8 +856,7 @@  discard block
 block discarded – undo
827 856
             if ($selected == $key)
828 857
             {
829 858
                 $select_week .= '<option value="'.$key.'" selected>';
830
-            }
831
-            else
859
+            } else
832 860
             {
833 861
                 $select_week .= '<option value="'.$key.'">';
834 862
             }
@@ -857,8 +885,13 @@  discard block
 block discarded – undo
857 885
 
858 886
         require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
859 887
 
860
-        if ($longlabel) $montharray = monthArray($langs, 0);	// Get array
861
-        else $montharray = monthArray($langs, 1);
888
+        if ($longlabel) {
889
+            $montharray = monthArray($langs, 0);
890
+        }
891
+        // Get array
892
+        else {
893
+            $montharray = monthArray($langs, 1);
894
+        }
862 895
 
863 896
         $select_month = '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
864 897
         if ($useempty)
@@ -870,8 +903,7 @@  discard block
 block discarded – undo
870 903
             if ($selected == $key)
871 904
             {
872 905
                 $select_month .= '<option value="'.$key.'" selected>';
873
-            }
874
-            else
906
+            } else
875 907
             {
876 908
                 $select_month .= '<option value="'.$key.'">';
877 909
             }
@@ -924,13 +956,17 @@  discard block
 block discarded – undo
924 956
         $currentyear = date("Y")+$offset;
925 957
         $max_year = $currentyear+$max_year;
926 958
         $min_year = $currentyear-$min_year;
927
-        if(empty($selected) && empty($useempty)) $selected = $currentyear;
959
+        if(empty($selected) && empty($useempty)) {
960
+            $selected = $currentyear;
961
+        }
928 962
 
929 963
         $out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="' . $htmlname . '" name="' . $htmlname . '"'.$option.' >';
930 964
         if($useempty)
931 965
         {
932 966
         	$selected_html='';
933
-            if ($selected == '') $selected_html = ' selected';
967
+            if ($selected == '') {
968
+                $selected_html = ' selected';
969
+            }
934 970
             $out.= '<option value=""' . $selected_html . '>&nbsp;</option>';
935 971
         }
936 972
         if (! $invert)
@@ -938,16 +974,19 @@  discard block
 block discarded – undo
938 974
             for ($y = $max_year; $y >= $min_year; $y--)
939 975
             {
940 976
                 $selected_html='';
941
-                if ($selected > 0 && $y == $selected) $selected_html = ' selected';
977
+                if ($selected > 0 && $y == $selected) {
978
+                    $selected_html = ' selected';
979
+                }
942 980
                 $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
943 981
             }
944
-        }
945
-        else
982
+        } else
946 983
         {
947 984
             for ($y = $min_year; $y <= $max_year; $y++)
948 985
             {
949 986
                 $selected_html='';
950
-                if ($selected > 0 && $y == $selected) $selected_html = ' selected';
987
+                if ($selected > 0 && $y == $selected) {
988
+                    $selected_html = ' selected';
989
+                }
951 990
                 $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
952 991
             }
953 992
         }
@@ -984,8 +1023,7 @@  discard block
 block discarded – undo
984 1023
             $langs->load("companies");
985 1024
             print ' &nbsp; <a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$socid.'&action=create&origin='.$origin.'&originid='.$originid.'>'.$langs->trans("AddAddress").'</a>';
986 1025
             print '</form>';
987
-        }
988
-        else
1026
+        } else
989 1027
         {
990 1028
             if ($selected)
991 1029
             {
@@ -993,8 +1031,7 @@  discard block
 block discarded – undo
993 1031
                 $address=new Address($this->db);
994 1032
                 $result=$address->fetch_address($selected);
995 1033
                 print '<a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$address->socid.'&id='.$address->id.'&action=edit&origin='.$origin.'&originid='.$originid.'>'.$address->label.'</a>';
996
-            }
997
-            else
1034
+            } else
998 1035
             {
999 1036
                 print "&nbsp;";
1000 1037
             }
@@ -1028,7 +1065,10 @@  discard block
 block discarded – undo
1028 1065
         $boxidactivatedforuser=array();
1029 1066
         foreach($boxactivated as $box)
1030 1067
         {
1031
-        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id;	// We keep only boxes to show for user
1068
+        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) {
1069
+        	    $boxidactivatedforuser[$box->id]=$box->id;
1070
+        	}
1071
+        	// We keep only boxes to show for user
1032 1072
         }
1033 1073
 
1034 1074
         // Define selectboxlist
@@ -1039,7 +1079,10 @@  discard block
 block discarded – undo
1039 1079
         	$langs->load("boxes");	// Load label of boxes
1040 1080
         	foreach($boxactivated as $box)
1041 1081
         	{
1042
-        		if (! empty($boxidactivatedforuser[$box->id])) continue;	// Already visible for user
1082
+        		if (! empty($boxidactivatedforuser[$box->id])) {
1083
+        		    continue;
1084
+        		}
1085
+        		// Already visible for user
1043 1086
         		$label=$langs->transnoentitiesnoconv($box->boxlabel);
1044 1087
         		//if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1045 1088
         		if (preg_match('/graph/',$box->class) && $conf->browser->layout != 'phone')
@@ -1050,7 +1093,9 @@  discard block
 block discarded – undo
1050 1093
         	}
1051 1094
             foreach($boxidactivatedforuser as $boxid)
1052 1095
         	{
1053
-       			if (empty($boxorder)) $boxorder.='A:';
1096
+       			if (empty($boxorder)) {
1097
+       			    $boxorder.='A:';
1098
+       			}
1054 1099
   				$boxorder.=$boxid.',';
1055 1100
         	}
1056 1101
 
@@ -1064,7 +1109,9 @@  discard block
 block discarded – undo
1064 1109
 			$selectboxlist.='<input type="hidden" name="areacode" value="'.$areacode.'">';
1065 1110
 			$selectboxlist.='<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1066 1111
 			$selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1067
-            if (empty($conf->use_javascript_ajax)) $selectboxlist.=' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1112
+            if (empty($conf->use_javascript_ajax)) {
1113
+                $selectboxlist.=' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1114
+            }
1068 1115
             $selectboxlist.='</form>';
1069 1116
             if (! empty($conf->use_javascript_ajax))
1070 1117
             {
@@ -1115,7 +1162,9 @@  discard block
 block discarded – undo
1115 1162
 	        			window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=addbox&boxid=\'+boxid;
1116 1163
 	                }
1117 1164
 	        	});';
1118
-	        	if (! count($arrayboxtoactivatelabel)) $selectboxlist.='jQuery("#boxcombo").hide();';
1165
+	        	if (! count($arrayboxtoactivatelabel)) {
1166
+	        	    $selectboxlist.='jQuery("#boxcombo").hide();';
1167
+	        	}
1119 1168
 	        	$selectboxlist.='
1120 1169
 
1121 1170
 	        	jQuery("#boxhalfleft, #boxhalfright").sortable({
@@ -1158,16 +1207,25 @@  discard block
 block discarded – undo
1158 1207
 
1159 1208
             // Define $box_max_lines
1160 1209
             $box_max_lines=5;
1161
-            if (! empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines=$conf->global->MAIN_BOXES_MAXLINES;
1210
+            if (! empty($conf->global->MAIN_BOXES_MAXLINES)) {
1211
+                $box_max_lines=$conf->global->MAIN_BOXES_MAXLINES;
1212
+            }
1162 1213
 
1163 1214
             $ii=0;
1164 1215
             foreach ($boxactivated as $key => $box)
1165 1216
             {
1166
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1167
-				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1168
-            	if (preg_match('/^A/i',$box->box_order)) // column A
1217
+            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) {
1218
+            	    continue;
1219
+            	}
1220
+				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) {
1221
+				    $box->box_order='A'.sprintf("%02d",($ii+1));
1222
+				}
1223
+				// When box_order was not yet set to Axx or Bxx and is still 0
1224
+            	if (preg_match('/^A/i',$box->box_order)) {
1225
+            	    // column A
1169 1226
                 {
1170 1227
                     $ii++;
1228
+            	}
1171 1229
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1172 1230
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1173 1231
                     // Show box
@@ -1190,11 +1248,18 @@  discard block
 block discarded – undo
1190 1248
             $ii=0;
1191 1249
             foreach ($boxactivated as $key => $box)
1192 1250
             {
1193
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1194
-            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1195
-            	if (preg_match('/^B/i',$box->box_order)) // colonne B
1251
+            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) {
1252
+            	    continue;
1253
+            	}
1254
+            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) {
1255
+            	    $box->box_order='B'.sprintf("%02d",($ii+1));
1256
+            	}
1257
+            	// When box_order was not yet set to Axx or Bxx and is still 0
1258
+            	if (preg_match('/^B/i',$box->box_order)) {
1259
+            	    // colonne B
1196 1260
                 {
1197 1261
                     $ii++;
1262
+            	}
1198 1263
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1199 1264
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1200 1265
                     // Show box
@@ -1262,8 +1327,7 @@  discard block
 block discarded – undo
1262 1327
                     if ($selected == $obj->rowid || $selected == $obj->$keyfield)
1263 1328
                     {
1264 1329
                         print '<option value="'.$obj->$keyfield.'" selected>';
1265
-                    }
1266
-                    else
1330
+                    } else
1267 1331
                     {
1268 1332
                         print '<option value="'.$obj->$keyfield.'">';
1269 1333
                     }
@@ -1272,13 +1336,11 @@  discard block
 block discarded – undo
1272 1336
                     $i++;
1273 1337
                 }
1274 1338
                 print "</select>";
1275
-            }
1276
-            else
1339
+            } else
1277 1340
 			{
1278 1341
                 print $langs->trans("DictionaryEmpty");
1279 1342
             }
1280
-        }
1281
-        else {
1343
+        } else {
1282 1344
             dol_print_error($this->db);
1283 1345
         }
1284 1346
     }
Please login to merge, or discard this patch.