Test Failed
Push — master ( e0c20c...b8c830 )
by Alxarafe
39:29
created
dolibarr/htdocs/ftp/index.php 3 patches
Indentation   +560 added lines, -560 removed lines patch added patch discarded remove patch
@@ -83,268 +83,268 @@  discard block
 block discarded – undo
83 83
 // Submit file
84 84
 if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC))
85 85
 {
86
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
87
-
88
-	$result=$ecmdir->fetch($_REQUEST["section"]);
89
-	if (! $result > 0)
90
-	{
91
-		dol_print_error($db,$ecmdir->error);
92
-		exit;
93
-	}
94
-	$relativepath=$ecmdir->getRelativePath();
95
-	$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
96
-
97
-	if (dol_mkdir($upload_dir) >= 0)
98
-	{
99
-		$resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0);
100
-		if (is_numeric($resupload) && $resupload > 0)
101
-		{
102
-			$result=$ecmdir->changeNbOfFiles('+');
103
-		}
104
-		else {
105
-			$langs->load("errors");
106
-			if ($resupload < 0)	// Unknown error
107
-			{
108
-				setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
109
-			}
110
-			else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
111
-			{
112
-				setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
113
-			}
114
-			else	// Known error
115
-			{
116
-				setEventMessages($langs->trans($resupload), null, 'errors');
117
-			}
118
-		}
119
-	}
120
-	else
121
-	{
122
-		// Echec transfert (fichier depassant la limite ?)
123
-		$langs->load("errors");
124
-		setEventMessages($langs->trans("ErrorFailToCreateDir",$upload_dir), null, 'errors');
125
-	}
86
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
87
+
88
+    $result=$ecmdir->fetch($_REQUEST["section"]);
89
+    if (! $result > 0)
90
+    {
91
+        dol_print_error($db,$ecmdir->error);
92
+        exit;
93
+    }
94
+    $relativepath=$ecmdir->getRelativePath();
95
+    $upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
96
+
97
+    if (dol_mkdir($upload_dir) >= 0)
98
+    {
99
+        $resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0);
100
+        if (is_numeric($resupload) && $resupload > 0)
101
+        {
102
+            $result=$ecmdir->changeNbOfFiles('+');
103
+        }
104
+        else {
105
+            $langs->load("errors");
106
+            if ($resupload < 0)	// Unknown error
107
+            {
108
+                setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
109
+            }
110
+            else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
111
+            {
112
+                setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
113
+            }
114
+            else	// Known error
115
+            {
116
+                setEventMessages($langs->trans($resupload), null, 'errors');
117
+            }
118
+        }
119
+    }
120
+    else
121
+    {
122
+        // Echec transfert (fichier depassant la limite ?)
123
+        $langs->load("errors");
124
+        setEventMessages($langs->trans("ErrorFailToCreateDir",$upload_dir), null, 'errors');
125
+    }
126 126
 }
127 127
 
128 128
 // Action ajout d'un rep
129 129
 if ($action == 'add' && $user->rights->ftp->setup)
130 130
 {
131
-	$ecmdir->ref                = $_POST["ref"];
132
-	$ecmdir->label              = $_POST["label"];
133
-	$ecmdir->description        = $_POST["desc"];
134
-
135
-	$id = $ecmdir->create($user);
136
-	if ($id > 0)
137
-	{
138
-		header("Location: ".$_SERVER["PHP_SELF"]);
139
-		exit;
140
-	}
141
-	else
142
-	{
143
-		setEventMessages($langs->trans("ErrorFailToCreateDir"), null, 'errors');
144
-		$action = "create";
145
-	}
131
+    $ecmdir->ref                = $_POST["ref"];
132
+    $ecmdir->label              = $_POST["label"];
133
+    $ecmdir->description        = $_POST["desc"];
134
+
135
+    $id = $ecmdir->create($user);
136
+    if ($id > 0)
137
+    {
138
+        header("Location: ".$_SERVER["PHP_SELF"]);
139
+        exit;
140
+    }
141
+    else
142
+    {
143
+        setEventMessages($langs->trans("ErrorFailToCreateDir"), null, 'errors');
144
+        $action = "create";
145
+    }
146 146
 }
147 147
 
148 148
 // Remove file
149 149
 if ($action == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes')
150 150
 {
151
-	// set up a connection or die
152
-	if (! $conn_id)
153
-	{
154
-		$newsectioniso=utf8_decode($section);
155
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
156
-		$conn_id=$resultarray['conn_id'];
157
-		$ok=$resultarray['ok'];
158
-		$mesg=$resultarray['mesg'];
159
-	}
160
-
161
-	if ($conn_id && $ok && ! $mesg)
162
-	{
163
-	    $langs->load("other");
164
-
165
-		// Remote file
166
-		$filename=$file;
167
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
168
-		$newremotefileiso=utf8_decode($remotefile);
169
-
170
-		//print "x".$newremotefileiso;
171
-		dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
172
-		$result=@ftp_delete($conn_id, $newremotefileiso);
173
-		if ($result)
174
-		{
175
-			setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
176
-		}
177
-		else
178
-		{
179
-			dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
180
-			setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
181
-		}
182
-
183
-		//ftp_close($conn_id);	Close later
151
+    // set up a connection or die
152
+    if (! $conn_id)
153
+    {
154
+        $newsectioniso=utf8_decode($section);
155
+        $resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
156
+        $conn_id=$resultarray['conn_id'];
157
+        $ok=$resultarray['ok'];
158
+        $mesg=$resultarray['mesg'];
159
+    }
184 160
 
185
-		$action='';
186
-	}
187
-	else
188
-	{
189
-		dol_print_error('',$mesg);
190
-	}
161
+    if ($conn_id && $ok && ! $mesg)
162
+    {
163
+        $langs->load("other");
164
+
165
+        // Remote file
166
+        $filename=$file;
167
+        $remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
168
+        $newremotefileiso=utf8_decode($remotefile);
169
+
170
+        //print "x".$newremotefileiso;
171
+        dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
172
+        $result=@ftp_delete($conn_id, $newremotefileiso);
173
+        if ($result)
174
+        {
175
+            setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
176
+        }
177
+        else
178
+        {
179
+            dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
180
+            setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
181
+        }
182
+
183
+        //ftp_close($conn_id);	Close later
184
+
185
+        $action='';
186
+    }
187
+    else
188
+    {
189
+        dol_print_error('',$mesg);
190
+    }
191 191
 }
192 192
 
193 193
 // Delete several lines at once
194 194
 if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("Delete"))
195 195
 {
196
-	// set up a connection or die
197
-	if (! $conn_id)
198
-	{
199
-		$newsectioniso=utf8_decode($section);
200
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
201
-		$conn_id=$resultarray['conn_id'];
202
-		$ok=$resultarray['ok'];
203
-		$mesg=$resultarray['mesg'];
204
-	}
205
-
206
-	if ($conn_id && $ok && ! $mesg)
207
-	{
208
-		foreach($_POST["const"] as $const)
209
-		{
210
-			if ($const["check"])	// Is checkbox checked
211
-			{
212
-			    $langs->load("other");
213
-
214
-				// Remote file
215
-				$file=$const["file"];
216
-				$section=$const["section"];
217
-				$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
218
-				$newremotefileiso=utf8_decode($remotefile);
219
-
220
-				//print "x".$newremotefileiso;
221
-				dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
222
-				$result=@ftp_delete($conn_id, $newremotefileiso);
223
-				if ($result)
224
-				{
225
-					setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
226
-				}
227
-				else
228
-				{
229
-					dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
230
-					setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
231
-				}
232
-
233
-				//ftp_close($conn_id);	Close later
234
-
235
-				$action='';
236
-			}
237
-		}
238
-	}
239
-	else
240
-	{
241
-		dol_print_error('',$mesg);
242
-	}
196
+    // set up a connection or die
197
+    if (! $conn_id)
198
+    {
199
+        $newsectioniso=utf8_decode($section);
200
+        $resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
201
+        $conn_id=$resultarray['conn_id'];
202
+        $ok=$resultarray['ok'];
203
+        $mesg=$resultarray['mesg'];
204
+    }
205
+
206
+    if ($conn_id && $ok && ! $mesg)
207
+    {
208
+        foreach($_POST["const"] as $const)
209
+        {
210
+            if ($const["check"])	// Is checkbox checked
211
+            {
212
+                $langs->load("other");
213
+
214
+                // Remote file
215
+                $file=$const["file"];
216
+                $section=$const["section"];
217
+                $remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
218
+                $newremotefileiso=utf8_decode($remotefile);
219
+
220
+                //print "x".$newremotefileiso;
221
+                dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
222
+                $result=@ftp_delete($conn_id, $newremotefileiso);
223
+                if ($result)
224
+                {
225
+                    setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
226
+                }
227
+                else
228
+                {
229
+                    dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
230
+                    setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
231
+                }
232
+
233
+                //ftp_close($conn_id);	Close later
234
+
235
+                $action='';
236
+            }
237
+        }
238
+    }
239
+    else
240
+    {
241
+        dol_print_error('',$mesg);
242
+    }
243 243
 }
244 244
 
245 245
 // Remove directory
246 246
 if ($action == 'confirm_deletesection' && $confirm == 'yes')
247 247
 {
248
-	// set up a connection or die
249
-	if (! $conn_id)
250
-	{
251
-		$newsectioniso=utf8_decode($section);
252
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
253
-		$conn_id=$resultarray['conn_id'];
254
-		$ok=$resultarray['ok'];
255
-		$mesg=$resultarray['mesg'];
256
-	}
257
-
258
-	if ($conn_id && $ok && ! $mesg)
259
-	{
260
-		// Remote file
261
-		$filename=$file;
262
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
263
-		$newremotefileiso=utf8_decode($remotefile);
264
-
265
-		$result=@ftp_rmdir($conn_id, $newremotefileiso);
266
-		if ($result)
267
-		{
268
-			setEventMessages($langs->trans("DirWasRemoved",$file), null, 'mesgs');
269
-		}
270
-		else
271
-		{
272
-			setEventMessages($langs->trans("FTPFailedToRemoveDir",$file), null, 'errors');
273
-		}
274
-
275
-		//ftp_close($conn_id);	Close later
248
+    // set up a connection or die
249
+    if (! $conn_id)
250
+    {
251
+        $newsectioniso=utf8_decode($section);
252
+        $resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
253
+        $conn_id=$resultarray['conn_id'];
254
+        $ok=$resultarray['ok'];
255
+        $mesg=$resultarray['mesg'];
256
+    }
276 257
 
277
-		$action='';
278
-	}
279
-	else
280
-	{
281
-		dol_print_error('',$mesg);
282
-	}
258
+    if ($conn_id && $ok && ! $mesg)
259
+    {
260
+        // Remote file
261
+        $filename=$file;
262
+        $remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
263
+        $newremotefileiso=utf8_decode($remotefile);
264
+
265
+        $result=@ftp_rmdir($conn_id, $newremotefileiso);
266
+        if ($result)
267
+        {
268
+            setEventMessages($langs->trans("DirWasRemoved",$file), null, 'mesgs');
269
+        }
270
+        else
271
+        {
272
+            setEventMessages($langs->trans("FTPFailedToRemoveDir",$file), null, 'errors');
273
+        }
274
+
275
+        //ftp_close($conn_id);	Close later
276
+
277
+        $action='';
278
+    }
279
+    else
280
+    {
281
+        dol_print_error('',$mesg);
282
+    }
283 283
 }
284 284
 
285 285
 // Download directory
286 286
 if ($action == 'download')
287 287
 {
288
-	// set up a connection or die
289
-	if (! $conn_id)
290
-	{
291
-		$newsectioniso=utf8_decode($section);
292
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
293
-		$conn_id=$resultarray['conn_id'];
294
-		$ok=$resultarray['ok'];
295
-		$mesg=$resultarray['mesg'];
296
-	}
297
-
298
-	if ($conn_id && $ok && ! $mesg)
299
-	{
300
-		// Local file
301
-		$localfile=tempnam($download_dir,'dol_');
302
-
303
-		// Remote file
304
-		$filename=$file;
305
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
306
-		$newremotefileiso=utf8_decode($remotefile);
307
-
308
-		$result=ftp_get($conn_id,$localfile,$newremotefileiso,FTP_BINARY);
309
-		if ($result)
310
-		{
311
-			if (! empty($conf->global->MAIN_UMASK))
312
-			@chmod($localfile, octdec($conf->global->MAIN_UMASK));
313
-
314
-			// Define mime type
315
-			$type = 'application/octet-stream';
316
-			if (! empty($_GET["type"])) $type=$_GET["type"];
317
-			else $type=dol_mimetype($original_file);
318
-
319
-			// Define attachment (attachment=true to force choice popup 'open'/'save as')
320
-			$attachment = true;
321
-
322
-			if ($encoding)   header('Content-Encoding: '.$encoding);
323
-			if ($type)       header('Content-Type: '.$type);
324
-			if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
325
-			else header('Content-Disposition: inline; filename="'.$filename.'"');
326
-
327
-			// Ajout directives pour resoudre bug IE
328
-			header('Cache-Control: Public, must-revalidate');
329
-			header('Pragma: public');
330
-
331
-			readfile($localfile);
332
-
333
-			ftp_close($conn_id);
288
+    // set up a connection or die
289
+    if (! $conn_id)
290
+    {
291
+        $newsectioniso=utf8_decode($section);
292
+        $resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
293
+        $conn_id=$resultarray['conn_id'];
294
+        $ok=$resultarray['ok'];
295
+        $mesg=$resultarray['mesg'];
296
+    }
334 297
 
335
-			exit;
336
-		}
337
-		else
338
-		{
339
-			setEventMessages($langs->transnoentitiesnoconv('FailedToGetFile',$remotefile), null, 'errors');
340
-		}
341
-	}
342
-	else
343
-	{
344
-		dol_print_error('',$mesg);
345
-	}
298
+    if ($conn_id && $ok && ! $mesg)
299
+    {
300
+        // Local file
301
+        $localfile=tempnam($download_dir,'dol_');
302
+
303
+        // Remote file
304
+        $filename=$file;
305
+        $remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
306
+        $newremotefileiso=utf8_decode($remotefile);
307
+
308
+        $result=ftp_get($conn_id,$localfile,$newremotefileiso,FTP_BINARY);
309
+        if ($result)
310
+        {
311
+            if (! empty($conf->global->MAIN_UMASK))
312
+            @chmod($localfile, octdec($conf->global->MAIN_UMASK));
313
+
314
+            // Define mime type
315
+            $type = 'application/octet-stream';
316
+            if (! empty($_GET["type"])) $type=$_GET["type"];
317
+            else $type=dol_mimetype($original_file);
318
+
319
+            // Define attachment (attachment=true to force choice popup 'open'/'save as')
320
+            $attachment = true;
321
+
322
+            if ($encoding)   header('Content-Encoding: '.$encoding);
323
+            if ($type)       header('Content-Type: '.$type);
324
+            if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
325
+            else header('Content-Disposition: inline; filename="'.$filename.'"');
326
+
327
+            // Ajout directives pour resoudre bug IE
328
+            header('Cache-Control: Public, must-revalidate');
329
+            header('Pragma: public');
330
+
331
+            readfile($localfile);
332
+
333
+            ftp_close($conn_id);
334
+
335
+            exit;
336
+        }
337
+        else
338
+        {
339
+            setEventMessages($langs->transnoentitiesnoconv('FailedToGetFile',$remotefile), null, 'errors');
340
+        }
341
+    }
342
+    else
343
+    {
344
+        dol_print_error('',$mesg);
345
+    }
346 346
 
347
-	//ftp_close($conn_id);	Close later
347
+    //ftp_close($conn_id);	Close later
348 348
 }
349 349
 
350 350
 
@@ -396,231 +396,231 @@  discard block
 block discarded – undo
396 396
 
397 397
 if (! function_exists('ftp_connect'))
398 398
 {
399
-	print $langs->trans("FTPFeatureNotSupportedByYourPHP");
399
+    print $langs->trans("FTPFeatureNotSupportedByYourPHP");
400 400
 }
401 401
 else
402 402
 {
403 403
     if (! empty($ftp_server))
404
-	{
405
-		// Confirm remove file
406
-		if ($action == 'delete')
407
-		{
408
-			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile','','',1);
409
-		}
410
-
411
-		// Confirmation de la suppression d'une ligne categorie
412
-		if ($action == 'delete_section')
413
-		{
414
-			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection',$ecmdir->label), 'confirm_deletesection','','',1);
415
-		}
416
-
417
-		print $langs->trans("Server").': <b>'.$ftp_server.'</b><br>';
418
-		print $langs->trans("Port").': <b>'.$ftp_port.'</b> '.($ftp_passive?"(Passive)":"(Active)").'<br>';
419
-		print $langs->trans("User").': <b>'.$ftp_user.'</b><br>';
404
+    {
405
+        // Confirm remove file
406
+        if ($action == 'delete')
407
+        {
408
+            print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile','','',1);
409
+        }
410
+
411
+        // Confirmation de la suppression d'une ligne categorie
412
+        if ($action == 'delete_section')
413
+        {
414
+            print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection',$ecmdir->label), 'confirm_deletesection','','',1);
415
+        }
416
+
417
+        print $langs->trans("Server").': <b>'.$ftp_server.'</b><br>';
418
+        print $langs->trans("Port").': <b>'.$ftp_port.'</b> '.($ftp_passive?"(Passive)":"(Active)").'<br>';
419
+        print $langs->trans("User").': <b>'.$ftp_user.'</b><br>';
420 420
         print $langs->trans("FTPs (FTP over SSH)").': <b>'.yn($conf->global->FTP_CONNECT_WITH_SSL).'</b><br>';
421 421
         print $langs->trans("SFTP (FTP as a subsytem of SSH)").': <b>'.yn($conf->global->FTP_CONNECT_WITH_SFTP).'</b><br>';
422 422
         print $langs->trans("Directory").': ';
423
-		$sectionarray=preg_split('|[\/]|',$section);
424
-		// For /
425
-		$newsection='/';
426
-		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
427
-		print '/';
428
-		print '</a> ';
429
-		// For other directories
430
-		$i=0;
431
-		foreach($sectionarray as $val)
432
-		{
433
-			if (empty($val)) continue;	// Discard first and last entry that should be empty as section start/end with /
434
-			if ($i > 0)
435
-			{
436
-				print ' / ';
437
-				$newsection.='/';
438
-			}
439
-			$newsection.=$val;
440
-			print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
441
-			print $val;
442
-			print '</a>';
443
-			$i++;
444
-		}
445
-		print '<br>';
446
-		print "<br>\n";
447
-
448
-		print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
423
+        $sectionarray=preg_split('|[\/]|',$section);
424
+        // For /
425
+        $newsection='/';
426
+        print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
427
+        print '/';
428
+        print '</a> ';
429
+        // For other directories
430
+        $i=0;
431
+        foreach($sectionarray as $val)
432
+        {
433
+            if (empty($val)) continue;	// Discard first and last entry that should be empty as section start/end with /
434
+            if ($i > 0)
435
+            {
436
+                print ' / ';
437
+                $newsection.='/';
438
+            }
439
+            $newsection.=$val;
440
+            print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
441
+            print $val;
442
+            print '</a>';
443
+            $i++;
444
+        }
445
+        print '<br>';
446
+        print "<br>\n";
447
+
448
+        print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
449 449
         print '<input type="hidden" name="numero_ftp" value="'.$numero_ftp.'">';
450
-		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
451
-
452
-
453
-		// Construit liste des repertoires
454
-		print '<table width="100%" class="noborder">'."\n";
455
-
456
-		print '<tr class="liste_titre">'."\n";
457
-		print '<td class="liste_titre" align="left">'.$langs->trans("Content").'</td>'."\n";
458
-		print '<td class="liste_titre" align="center">'.$langs->trans("Size").'</td>'."\n";
459
-		print '<td class="liste_titre" align="center">'.$langs->trans("Date").'</td>'."\n";
460
-		print '<td class="liste_titre" align="center">'.$langs->trans("Owner").'</td>'."\n";
461
-		print '<td class="liste_titre" align="center">'.$langs->trans("Group").'</td>'."\n";
462
-		print '<td class="liste_titre" align="center">'.$langs->trans("Permissions").'</td>'."\n";
463
-		print '<td class="liste_titre nowrap" align="right">';
464
-		if ($conf->use_javascript_ajax) print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> ';
465
-		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section?'&section='.urlencode($section):'').'">'.img_picto($langs->trans("Refresh"),'refresh').'</a>&nbsp;';
466
-		print '</td>'."\n";
467
-		print '</tr>'."\n";
468
-
469
-		// set up a connection or die
470
-		if (empty($conn_id))
471
-		{
472
-			$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive);
473
-
474
-			$conn_id=$resultarray['conn_id'];
475
-			$ok=$resultarray['ok'];
476
-			$mesg=$resultarray['mesg'];
477
-		}
478
-
479
-		if ($ok)
480
-		{
481
-			//$type = ftp_systype($conn_id);
482
-
483
-			$newsection=$section;
484
-		    $newsectioniso=utf8_decode($section);
485
-			//$newsection='/home';
486
-
487
-			// List content of directory ($newsection = '/', '/home', ...)
488
-			if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
489
-			{
490
-			    if ($newsection == '/') $newsection='/./';  // workaround for bug https://bugs.php.net/bug.php?id=64169
491
-			    //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
492
-			    //var_dump($dirHandle);
450
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
451
+
452
+
453
+        // Construit liste des repertoires
454
+        print '<table width="100%" class="noborder">'."\n";
455
+
456
+        print '<tr class="liste_titre">'."\n";
457
+        print '<td class="liste_titre" align="left">'.$langs->trans("Content").'</td>'."\n";
458
+        print '<td class="liste_titre" align="center">'.$langs->trans("Size").'</td>'."\n";
459
+        print '<td class="liste_titre" align="center">'.$langs->trans("Date").'</td>'."\n";
460
+        print '<td class="liste_titre" align="center">'.$langs->trans("Owner").'</td>'."\n";
461
+        print '<td class="liste_titre" align="center">'.$langs->trans("Group").'</td>'."\n";
462
+        print '<td class="liste_titre" align="center">'.$langs->trans("Permissions").'</td>'."\n";
463
+        print '<td class="liste_titre nowrap" align="right">';
464
+        if ($conf->use_javascript_ajax) print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> ';
465
+        print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section?'&section='.urlencode($section):'').'">'.img_picto($langs->trans("Refresh"),'refresh').'</a>&nbsp;';
466
+        print '</td>'."\n";
467
+        print '</tr>'."\n";
468
+
469
+        // set up a connection or die
470
+        if (empty($conn_id))
471
+        {
472
+            $resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive);
473
+
474
+            $conn_id=$resultarray['conn_id'];
475
+            $ok=$resultarray['ok'];
476
+            $mesg=$resultarray['mesg'];
477
+        }
478
+
479
+        if ($ok)
480
+        {
481
+            //$type = ftp_systype($conn_id);
482
+
483
+            $newsection=$section;
484
+            $newsectioniso=utf8_decode($section);
485
+            //$newsection='/home';
486
+
487
+            // List content of directory ($newsection = '/', '/home', ...)
488
+            if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
489
+            {
490
+                if ($newsection == '/') $newsection='/./';  // workaround for bug https://bugs.php.net/bug.php?id=64169
491
+                //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
492
+                //var_dump($dirHandle);
493 493
                 $contents = scandir('ssh2.sftp://' . $conn_id . $newsection);
494 494
                 $buff=array();
495 495
                 foreach($contents as $i => $key)
496 496
                 {
497 497
                     $buff[$i]="---------- - root root 1234 Aug 01 2000 ".$key;
498 498
                 }
499
-    		}
500
-    		else
501
-    		{
499
+            }
500
+            else
501
+            {
502 502
                 $buff = ftp_rawlist($conn_id, $newsectioniso);
503 503
                 $contents = ftp_nlist($conn_id, $newsectioniso);	// Sometimes rawlist fails but never nlist
504
-        		//var_dump($contents);
505
-		        //var_dump($buff);
506
-    		}
507
-
508
-			$nboflines=count($contents);
509
-			$rawlisthasfailed=false;
510
-			$i=0;
511
-			while ($i < $nboflines && $i < 1000)
512
-			{
513
-				$vals=preg_split('@ +@',utf8_encode($buff[$i]),9);
514
-				//$vals=preg_split('@ +@','drwxr-xr-x 2 root root 4096 Aug 30 2008 backup_apollon1',9);
515
-				//var_dump($vals);
516
-				$file=$vals[8];
517
-				if (empty($file))
518
-				{
519
-					$rawlisthasfailed=true;
520
-					$file=utf8_encode($contents[$i]);
521
-				}
522
-
523
-				if ($file == '.' || ($file == '..' && $section == '/'))
524
-				{
525
-					$i++;
526
-					continue;
527
-				}
528
-
529
-				// Is it a directory ?
530
-				$is_directory=0;
531
-				if ($file == '..') $is_directory=1;
532
-				else if (! $rawlisthasfailed)
533
-				{
534
-					if (preg_match('/^d/',$vals[0])) $is_directory=1;
535
-					if (preg_match('/^l/',$vals[0])) $is_link=1;
536
-				}
537
-				else
538
-				{
539
-					// Remote file
540
-					$filename=$file;
541
-					//print "section=".$section.' file='.$file.'X';
542
-					//print preg_match('@[\/]$@','aaa/').'Y';
543
-					//print preg_match('@[\\\/]$@',"aaa\\").'Y';
544
-					$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').preg_replace('@^[\\\/]@','',$file);
545
-					//print 'A'.$remotefile.'A';
546
-					$newremotefileiso=utf8_decode($remotefile);
547
-					//print 'Z'.$newremotefileiso.'Z';
548
-					$is_directory=ftp_isdir($conn_id, $newremotefileiso);
549
-				}
550
-
551
-
552
-				print '<tr class="oddeven" height="18">';
553
-				// Name
554
-				print '<td>';
555
-				$newsection=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
556
-				$newsection=preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@','/',$newsection);	// Change aaa/xxx/.. to new aaa
557
-				if ($is_directory) print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">';
558
-				print $file;
559
-				if ($is_directory) print '</a>';
560
-				print '</td>';
561
-				// Size
562
-				print '<td align="center" class="nowrap">';
563
-				if (! $is_directory && ! $is_link) print $vals[4];
564
-				else print '&nbsp;';
565
-				print '</td>';
566
-				// Date
567
-				print '<td align="center" class="nowrap">';
568
-				print $vals[5].' '.$vals[6].' '.$vals[7];
569
-				print '</td>';
570
-				// User
571
-				print '<td align="center" class="nowrap">';
572
-				print $vals[2];
573
-				print '</td>';
574
-				// Group
575
-				print '<td align="center" class="nowrap">';
576
-				print $vals[3];
577
-				print '</td>';
578
-				// Permissions
579
-				print '<td align="center" class="nowrap">';
580
-				print $vals[0];
581
-				print '</td>';
582
-				// Action
583
-				print '<td align="right" width="64" class="nowrap">';
584
-				if ($is_directory)
585
-				{
586
-					if ($file != '..') print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
587
-					else print '&nbsp;';
588
-				}
589
-				else if ($is_link)
590
-				{
591
-					$newfile=$file;
592
-					$newfile=preg_replace('/ ->.*/','',$newfile);
593
-					print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($newfile).'">'.img_delete().'</a>';
594
-				}
595
-				else
596
-				{
597
-					print '<a href="'.$_SERVER["PHP_SELF"].'?action=download&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_picto('','file').'</a>';
598
-					print ' &nbsp; ';
599
-					print '<input type="checkbox" class="flat checkboxfordelete" id="check_'.$i.'" name="const['.$i.'][check]" value="1">';
600
-					print ' &nbsp; ';
601
-					print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
602
-					print '<input type="hidden" name="const['.$i.'][section]" value="'.$section.'">';
603
-					print '<input type="hidden" name="const['.$i.'][file]" value="'.$file.'">';
604
-				}
605
-				print '</td>';
606
-				print '</tr>'."\n";
607
-				$i++;
608
-				$nbofentries++;
609
-			}
610
-		}
504
+                //var_dump($contents);
505
+                //var_dump($buff);
506
+            }
507
+
508
+            $nboflines=count($contents);
509
+            $rawlisthasfailed=false;
510
+            $i=0;
511
+            while ($i < $nboflines && $i < 1000)
512
+            {
513
+                $vals=preg_split('@ +@',utf8_encode($buff[$i]),9);
514
+                //$vals=preg_split('@ +@','drwxr-xr-x 2 root root 4096 Aug 30 2008 backup_apollon1',9);
515
+                //var_dump($vals);
516
+                $file=$vals[8];
517
+                if (empty($file))
518
+                {
519
+                    $rawlisthasfailed=true;
520
+                    $file=utf8_encode($contents[$i]);
521
+                }
611 522
 
612
-		print "</table>";
523
+                if ($file == '.' || ($file == '..' && $section == '/'))
524
+                {
525
+                    $i++;
526
+                    continue;
527
+                }
613 528
 
529
+                // Is it a directory ?
530
+                $is_directory=0;
531
+                if ($file == '..') $is_directory=1;
532
+                else if (! $rawlisthasfailed)
533
+                {
534
+                    if (preg_match('/^d/',$vals[0])) $is_directory=1;
535
+                    if (preg_match('/^l/',$vals[0])) $is_link=1;
536
+                }
537
+                else
538
+                {
539
+                    // Remote file
540
+                    $filename=$file;
541
+                    //print "section=".$section.' file='.$file.'X';
542
+                    //print preg_match('@[\/]$@','aaa/').'Y';
543
+                    //print preg_match('@[\\\/]$@',"aaa\\").'Y';
544
+                    $remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').preg_replace('@^[\\\/]@','',$file);
545
+                    //print 'A'.$remotefile.'A';
546
+                    $newremotefileiso=utf8_decode($remotefile);
547
+                    //print 'Z'.$newremotefileiso.'Z';
548
+                    $is_directory=ftp_isdir($conn_id, $newremotefileiso);
549
+                }
614 550
 
615
-		if (! $ok)
616
-		{
617
-		      print $mesg.'<br>'."\n";
618
-		      setEventMessages($mesg, null, 'errors');
619
-		}
551
+
552
+                print '<tr class="oddeven" height="18">';
553
+                // Name
554
+                print '<td>';
555
+                $newsection=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
556
+                $newsection=preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@','/',$newsection);	// Change aaa/xxx/.. to new aaa
557
+                if ($is_directory) print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">';
558
+                print $file;
559
+                if ($is_directory) print '</a>';
560
+                print '</td>';
561
+                // Size
562
+                print '<td align="center" class="nowrap">';
563
+                if (! $is_directory && ! $is_link) print $vals[4];
564
+                else print '&nbsp;';
565
+                print '</td>';
566
+                // Date
567
+                print '<td align="center" class="nowrap">';
568
+                print $vals[5].' '.$vals[6].' '.$vals[7];
569
+                print '</td>';
570
+                // User
571
+                print '<td align="center" class="nowrap">';
572
+                print $vals[2];
573
+                print '</td>';
574
+                // Group
575
+                print '<td align="center" class="nowrap">';
576
+                print $vals[3];
577
+                print '</td>';
578
+                // Permissions
579
+                print '<td align="center" class="nowrap">';
580
+                print $vals[0];
581
+                print '</td>';
582
+                // Action
583
+                print '<td align="right" width="64" class="nowrap">';
584
+                if ($is_directory)
585
+                {
586
+                    if ($file != '..') print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
587
+                    else print '&nbsp;';
588
+                }
589
+                else if ($is_link)
590
+                {
591
+                    $newfile=$file;
592
+                    $newfile=preg_replace('/ ->.*/','',$newfile);
593
+                    print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($newfile).'">'.img_delete().'</a>';
594
+                }
595
+                else
596
+                {
597
+                    print '<a href="'.$_SERVER["PHP_SELF"].'?action=download&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_picto('','file').'</a>';
598
+                    print ' &nbsp; ';
599
+                    print '<input type="checkbox" class="flat checkboxfordelete" id="check_'.$i.'" name="const['.$i.'][check]" value="1">';
600
+                    print ' &nbsp; ';
601
+                    print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
602
+                    print '<input type="hidden" name="const['.$i.'][section]" value="'.$section.'">';
603
+                    print '<input type="hidden" name="const['.$i.'][file]" value="'.$file.'">';
604
+                }
605
+                print '</td>';
606
+                print '</tr>'."\n";
607
+                $i++;
608
+                $nbofentries++;
609
+            }
610
+        }
611
+
612
+        print "</table>";
613
+
614
+
615
+        if (! $ok)
616
+        {
617
+                print $mesg.'<br>'."\n";
618
+                setEventMessages($mesg, null, 'errors');
619
+        }
620 620
 
621 621
 
622
-		// Actions
623
-		/*
622
+        // Actions
623
+        /*
624 624
 		if ($user->rights->ftp->write && ! empty($section))
625 625
 		{
626 626
 		$formfile->form_attach_new_file(DOL_URL_ROOT.'/ftp/index.php','',0,$section,1);
@@ -628,38 +628,38 @@  discard block
 block discarded – undo
628 628
 		else print '&nbsp;';
629 629
 		*/
630 630
 
631
-		print '<br>';
632
-		print '<div id="delconst" align="right">';
633
-		print '<input type="submit" name="delete" class="button" value="'.$langs->trans("Delete").'">';
634
-		print '</div>';
635
-
636
-		print "</form>";
637
-	}
638
-	else
639
-	{
640
-		$foundsetup=false;
641
-		$MAXFTP=20;
642
-		$i=1;
643
-		while ($i <= $MAXFTP)
644
-		{
645
-			$paramkey='FTP_NAME_'.$i;
646
-			//print $paramkey;
647
-			if (! empty($conf->global->$paramkey))
648
-			{
649
-				$foundsetup=true;
650
-				break;
651
-			}
652
-			$i++;
653
-		}
654
-	    if (! $foundsetup)
655
-	    {
631
+        print '<br>';
632
+        print '<div id="delconst" align="right">';
633
+        print '<input type="submit" name="delete" class="button" value="'.$langs->trans("Delete").'">';
634
+        print '</div>';
635
+
636
+        print "</form>";
637
+    }
638
+    else
639
+    {
640
+        $foundsetup=false;
641
+        $MAXFTP=20;
642
+        $i=1;
643
+        while ($i <= $MAXFTP)
644
+        {
645
+            $paramkey='FTP_NAME_'.$i;
646
+            //print $paramkey;
647
+            if (! empty($conf->global->$paramkey))
648
+            {
649
+                $foundsetup=true;
650
+                break;
651
+            }
652
+            $i++;
653
+        }
654
+        if (! $foundsetup)
655
+        {
656 656
             print $langs->trans("SetupOfFTPClientModuleNotComplete");
657
-	    }
658
-	    else
659
-	    {
660
-	        print $langs->trans("ChooseAFTPEntryIntoMenu");
661
-	    }
662
-	}
657
+        }
658
+        else
659
+        {
660
+            print $langs->trans("ChooseAFTPEntryIntoMenu");
661
+        }
662
+    }
663 663
 }
664 664
 
665 665
 print '<br>';
@@ -700,94 +700,94 @@  discard block
 block discarded – undo
700 700
  */
701 701
 function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive=0)
702 702
 {
703
-	global $langs, $conf;
703
+    global $langs, $conf;
704 704
 
705
-	$ok=1;
705
+    $ok=1;
706 706
     $conn_id=null;
707 707
 
708
-	if (! is_numeric($ftp_port))
709
-	{
710
-		$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
711
-		$ok=0;
712
-	}
708
+    if (! is_numeric($ftp_port))
709
+    {
710
+        $mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
711
+        $ok=0;
712
+    }
713 713
 
714
-	if ($ok)
715
-	{
716
-		$connecttimeout=(empty($conf->global->FTP_CONNECT_TIMEOUT)?40:$conf->global->FTP_CONNECT_TIMEOUT);
717
-		if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
718
-		{
719
-		    dol_syslog('Try to connect with ssh2_ftp');
720
-		    $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
721
-		}
722
-		else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
723
-		{
724
-		    dol_syslog('Try to connect with ftp_ssl_connect');
725
-		    $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
726
-		}
727
-		else
728
-		{
729
-		    dol_syslog('Try to connect with ftp_connect');
730
-		    $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout);
731
-		}
732
-		if ($conn_id || $tmp_conn_id)
733
-		{
734
-			if ($ftp_user)
735
-			{
736
-				if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
737
-				{
738
-				    if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password))
739
-    				{
740
-    					// Turn on passive mode transfers (must be after a successful login
741
-    					//if ($ftp_passive) ftp_pasv($conn_id, true);
742
-
743
-    					// Change the dir
744
-    					$newsectioniso=utf8_decode($section);
745
-    					//ftp_chdir($conn_id, $newsectioniso);
746
-		                $conn_id = ssh2_sftp($tmp_conn_id);
747
-		                if (! $conn_id)
748
-		                {
749
-        					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
750
-    	   				    $ok=0;
751
-        				    $error++;
752
-		                }
753
-    				}
754
-    				else
755
-    				{
756
-    					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
757
-	   				    $ok=0;
758
-    				    $error++;
759
-    				}
760
-				}
761
-				else
762
-				{
763
-				    if (ftp_login($conn_id, $ftp_user, $ftp_password))
764
-    				{
765
-    					// Turn on passive mode transfers (must be after a successful login
766
-    					if ($ftp_passive) ftp_pasv($conn_id, true);
767
-
768
-    					// Change the dir
769
-    					$newsectioniso=utf8_decode($section);
770
-    					ftp_chdir($conn_id, $newsectioniso);
771
-    				}
772
-    				else
773
-    				{
774
-    					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
775
-	   				    $ok=0;
776
-    				    $error++;
777
-    				}
778
-				}
779
-			}
780
-		}
781
-		else
782
-		{
783
-		    dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
784
-			$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
785
-			$ok=0;
786
-		}
787
-	}
714
+    if ($ok)
715
+    {
716
+        $connecttimeout=(empty($conf->global->FTP_CONNECT_TIMEOUT)?40:$conf->global->FTP_CONNECT_TIMEOUT);
717
+        if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
718
+        {
719
+            dol_syslog('Try to connect with ssh2_ftp');
720
+            $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
721
+        }
722
+        else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
723
+        {
724
+            dol_syslog('Try to connect with ftp_ssl_connect');
725
+            $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
726
+        }
727
+        else
728
+        {
729
+            dol_syslog('Try to connect with ftp_connect');
730
+            $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout);
731
+        }
732
+        if ($conn_id || $tmp_conn_id)
733
+        {
734
+            if ($ftp_user)
735
+            {
736
+                if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
737
+                {
738
+                    if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password))
739
+                    {
740
+                        // Turn on passive mode transfers (must be after a successful login
741
+                        //if ($ftp_passive) ftp_pasv($conn_id, true);
742
+
743
+                        // Change the dir
744
+                        $newsectioniso=utf8_decode($section);
745
+                        //ftp_chdir($conn_id, $newsectioniso);
746
+                        $conn_id = ssh2_sftp($tmp_conn_id);
747
+                        if (! $conn_id)
748
+                        {
749
+                            $mesg=$langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
750
+                                $ok=0;
751
+                            $error++;
752
+                        }
753
+                    }
754
+                    else
755
+                    {
756
+                        $mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
757
+                            $ok=0;
758
+                        $error++;
759
+                    }
760
+                }
761
+                else
762
+                {
763
+                    if (ftp_login($conn_id, $ftp_user, $ftp_password))
764
+                    {
765
+                        // Turn on passive mode transfers (must be after a successful login
766
+                        if ($ftp_passive) ftp_pasv($conn_id, true);
767
+
768
+                        // Change the dir
769
+                        $newsectioniso=utf8_decode($section);
770
+                        ftp_chdir($conn_id, $newsectioniso);
771
+                    }
772
+                    else
773
+                    {
774
+                        $mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
775
+                            $ok=0;
776
+                        $error++;
777
+                    }
778
+                }
779
+            }
780
+        }
781
+        else
782
+        {
783
+            dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
784
+            $mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
785
+            $ok=0;
786
+        }
787
+    }
788 788
 
789
-	$arrayresult=array('conn_id'=>$conn_id, 'ok'=>$ok, 'mesg'=>$mesg, 'curdir'=>$section, 'curdiriso'=>$newsectioniso);
790
-	return $arrayresult;
789
+    $arrayresult=array('conn_id'=>$conn_id, 'ok'=>$ok, 'mesg'=>$mesg, 'curdir'=>$section, 'curdiriso'=>$newsectioniso);
790
+    return $arrayresult;
791 791
 }
792 792
 
793 793
 
@@ -800,14 +800,14 @@  discard block
 block discarded – undo
800 800
  */
801 801
 function ftp_isdir($connect_id,$dir)
802 802
 {
803
-	if (@ftp_chdir($connect_id,$dir))
804
-	{
805
-		ftp_cdup($connect_id);
806
-		return 1;
807
-	}
808
-	else
809
-	{
810
-		return 0;
811
-	}
803
+    if (@ftp_chdir($connect_id,$dir))
804
+    {
805
+        ftp_cdup($connect_id);
806
+        return 1;
807
+    }
808
+    else
809
+    {
810
+        return 0;
811
+    }
812 812
 }
813 813
 
Please login to merge, or discard this patch.
Spacing   +187 added lines, -187 removed lines patch added patch discarded remove patch
@@ -31,48 +31,48 @@  discard block
 block discarded – undo
31 31
 $langs->loadLangs(array('ftp', 'companies', 'other'));
32 32
 
33 33
 // Security check
34
-if ($user->societe_id) $socid=$user->societe_id;
35
-$result = restrictedArea($user, 'ftp','');
34
+if ($user->societe_id) $socid = $user->societe_id;
35
+$result = restrictedArea($user, 'ftp', '');
36 36
 
37 37
 // Get parameters
38
-$action=GETPOST('action','aZ09');
39
-$section=GETPOST('section');
40
-if (! $section) $section='/';
38
+$action = GETPOST('action', 'aZ09');
39
+$section = GETPOST('section');
40
+if (!$section) $section = '/';
41 41
 $numero_ftp = GETPOST("numero_ftp");
42 42
 /* if (! $numero_ftp) $numero_ftp=1; */
43
-$file=GETPOST("file");
44
-$confirm=GETPOST('confirm');
43
+$file = GETPOST("file");
44
+$confirm = GETPOST('confirm');
45 45
 
46 46
 $upload_dir = $conf->ftp->dir_temp;
47 47
 $download_dir = $conf->ftp->dir_temp;
48 48
 
49
-$sortfield = GETPOST("sortfield",'alpha');
50
-$sortorder = GETPOST("sortorder",'alpha');
51
-$page = GETPOST("page",'int');
49
+$sortfield = GETPOST("sortfield", 'alpha');
50
+$sortorder = GETPOST("sortorder", 'alpha');
51
+$page = GETPOST("page", 'int');
52 52
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
53 53
 $offset = $conf->liste_limit * $page;
54 54
 $pageprev = $page - 1;
55 55
 $pagenext = $page + 1;
56
-if (! $sortorder) $sortorder="ASC";
57
-if (! $sortfield) $sortfield="label";
58
-
59
-$s_ftp_name='FTP_NAME_'.$numero_ftp;
60
-$s_ftp_server='FTP_SERVER_'.$numero_ftp;
61
-$s_ftp_port='FTP_PORT_'.$numero_ftp;
62
-$s_ftp_user='FTP_USER_'.$numero_ftp;
63
-$s_ftp_password='FTP_PASSWORD_'.$numero_ftp;
64
-$s_ftp_passive='FTP_PASSIVE_'.$numero_ftp;
65
-$ftp_name=$conf->global->$s_ftp_name;
66
-$ftp_server=$conf->global->$s_ftp_server;
67
-$ftp_port=$conf->global->$s_ftp_port; if (empty($ftp_port)) $ftp_port=21;
68
-$ftp_user=$conf->global->$s_ftp_user;
69
-$ftp_password=$conf->global->$s_ftp_password;
70
-$ftp_passive=$conf->global->$s_ftp_passive;
56
+if (!$sortorder) $sortorder = "ASC";
57
+if (!$sortfield) $sortfield = "label";
58
+
59
+$s_ftp_name = 'FTP_NAME_'.$numero_ftp;
60
+$s_ftp_server = 'FTP_SERVER_'.$numero_ftp;
61
+$s_ftp_port = 'FTP_PORT_'.$numero_ftp;
62
+$s_ftp_user = 'FTP_USER_'.$numero_ftp;
63
+$s_ftp_password = 'FTP_PASSWORD_'.$numero_ftp;
64
+$s_ftp_passive = 'FTP_PASSIVE_'.$numero_ftp;
65
+$ftp_name = $conf->global->$s_ftp_name;
66
+$ftp_server = $conf->global->$s_ftp_server;
67
+$ftp_port = $conf->global->$s_ftp_port; if (empty($ftp_port)) $ftp_port = 21;
68
+$ftp_user = $conf->global->$s_ftp_user;
69
+$ftp_password = $conf->global->$s_ftp_password;
70
+$ftp_passive = $conf->global->$s_ftp_passive;
71 71
 
72 72
 // For result on connection
73
-$ok=0;
74
-$conn_id=null;	// FTP connection ID
75
-$mesg='';
73
+$ok = 0;
74
+$conn_id = null; // FTP connection ID
75
+$mesg = '';
76 76
 
77 77
 
78 78
 
@@ -81,25 +81,25 @@  discard block
 block discarded – undo
81 81
  */
82 82
 
83 83
 // Submit file
84
-if (GETPOST("sendit") && ! empty($conf->global->MAIN_UPLOAD_DOC))
84
+if (GETPOST("sendit") && !empty($conf->global->MAIN_UPLOAD_DOC))
85 85
 {
86 86
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
87 87
 
88
-	$result=$ecmdir->fetch($_REQUEST["section"]);
89
-	if (! $result > 0)
88
+	$result = $ecmdir->fetch($_REQUEST["section"]);
89
+	if (!$result > 0)
90 90
 	{
91
-		dol_print_error($db,$ecmdir->error);
91
+		dol_print_error($db, $ecmdir->error);
92 92
 		exit;
93 93
 	}
94
-	$relativepath=$ecmdir->getRelativePath();
94
+	$relativepath = $ecmdir->getRelativePath();
95 95
 	$upload_dir = $conf->ecm->dir_output.'/'.$relativepath;
96 96
 
97 97
 	if (dol_mkdir($upload_dir) >= 0)
98 98
 	{
99
-		$resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir . "/" . dol_unescapefile($_FILES['userfile']['name']),0);
99
+		$resupload = dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $upload_dir."/".dol_unescapefile($_FILES['userfile']['name']), 0);
100 100
 		if (is_numeric($resupload) && $resupload > 0)
101 101
 		{
102
-			$result=$ecmdir->changeNbOfFiles('+');
102
+			$result = $ecmdir->changeNbOfFiles('+');
103 103
 		}
104 104
 		else {
105 105
 			$langs->load("errors");
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 			{
108 108
 				setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
109 109
 			}
110
-			else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
110
+			else if (preg_match('/ErrorFileIsInfectedWithAVirus/', $resupload))	// Files infected by a virus
111 111
 			{
112 112
 				setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
113 113
 			}
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	{
122 122
 		// Echec transfert (fichier depassant la limite ?)
123 123
 		$langs->load("errors");
124
-		setEventMessages($langs->trans("ErrorFailToCreateDir",$upload_dir), null, 'errors');
124
+		setEventMessages($langs->trans("ErrorFailToCreateDir", $upload_dir), null, 'errors');
125 125
 	}
126 126
 }
127 127
 
@@ -149,44 +149,44 @@  discard block
 block discarded – undo
149 149
 if ($action == 'confirm_deletefile' && $_REQUEST['confirm'] == 'yes')
150 150
 {
151 151
 	// set up a connection or die
152
-	if (! $conn_id)
152
+	if (!$conn_id)
153 153
 	{
154
-		$newsectioniso=utf8_decode($section);
155
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
156
-		$conn_id=$resultarray['conn_id'];
157
-		$ok=$resultarray['ok'];
158
-		$mesg=$resultarray['mesg'];
154
+		$newsectioniso = utf8_decode($section);
155
+		$resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
156
+		$conn_id = $resultarray['conn_id'];
157
+		$ok = $resultarray['ok'];
158
+		$mesg = $resultarray['mesg'];
159 159
 	}
160 160
 
161
-	if ($conn_id && $ok && ! $mesg)
161
+	if ($conn_id && $ok && !$mesg)
162 162
 	{
163 163
 	    $langs->load("other");
164 164
 
165 165
 		// Remote file
166
-		$filename=$file;
167
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
168
-		$newremotefileiso=utf8_decode($remotefile);
166
+		$filename = $file;
167
+		$remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file;
168
+		$newremotefileiso = utf8_decode($remotefile);
169 169
 
170 170
 		//print "x".$newremotefileiso;
171 171
 		dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
172
-		$result=@ftp_delete($conn_id, $newremotefileiso);
172
+		$result = @ftp_delete($conn_id, $newremotefileiso);
173 173
 		if ($result)
174 174
 		{
175
-			setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
175
+			setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs');
176 176
 		}
177 177
 		else
178 178
 		{
179 179
 			dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
180
-			setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
180
+			setEventMessages($langs->trans("FTPFailedToRemoveFile", $file), null, 'errors');
181 181
 		}
182 182
 
183 183
 		//ftp_close($conn_id);	Close later
184 184
 
185
-		$action='';
185
+		$action = '';
186 186
 	}
187 187
 	else
188 188
 	{
189
-		dol_print_error('',$mesg);
189
+		dol_print_error('', $mesg);
190 190
 	}
191 191
 }
192 192
 
@@ -194,51 +194,51 @@  discard block
 block discarded – undo
194 194
 if ($_POST["const"] && $_POST["delete"] && $_POST["delete"] == $langs->trans("Delete"))
195 195
 {
196 196
 	// set up a connection or die
197
-	if (! $conn_id)
197
+	if (!$conn_id)
198 198
 	{
199
-		$newsectioniso=utf8_decode($section);
200
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
201
-		$conn_id=$resultarray['conn_id'];
202
-		$ok=$resultarray['ok'];
203
-		$mesg=$resultarray['mesg'];
199
+		$newsectioniso = utf8_decode($section);
200
+		$resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
201
+		$conn_id = $resultarray['conn_id'];
202
+		$ok = $resultarray['ok'];
203
+		$mesg = $resultarray['mesg'];
204 204
 	}
205 205
 
206
-	if ($conn_id && $ok && ! $mesg)
206
+	if ($conn_id && $ok && !$mesg)
207 207
 	{
208
-		foreach($_POST["const"] as $const)
208
+		foreach ($_POST["const"] as $const)
209 209
 		{
210 210
 			if ($const["check"])	// Is checkbox checked
211 211
 			{
212 212
 			    $langs->load("other");
213 213
 
214 214
 				// Remote file
215
-				$file=$const["file"];
216
-				$section=$const["section"];
217
-				$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
218
-				$newremotefileiso=utf8_decode($remotefile);
215
+				$file = $const["file"];
216
+				$section = $const["section"];
217
+				$remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file;
218
+				$newremotefileiso = utf8_decode($remotefile);
219 219
 
220 220
 				//print "x".$newremotefileiso;
221 221
 				dol_syslog("ftp/index.php ftp_delete ".$newremotefileiso);
222
-				$result=@ftp_delete($conn_id, $newremotefileiso);
222
+				$result = @ftp_delete($conn_id, $newremotefileiso);
223 223
 				if ($result)
224 224
 				{
225
-					setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
225
+					setEventMessages($langs->trans("FileWasRemoved", $file), null, 'mesgs');
226 226
 				}
227 227
 				else
228 228
 				{
229 229
 					dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
230
-					setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
230
+					setEventMessages($langs->trans("FTPFailedToRemoveFile", $file), null, 'errors');
231 231
 				}
232 232
 
233 233
 				//ftp_close($conn_id);	Close later
234 234
 
235
-				$action='';
235
+				$action = '';
236 236
 			}
237 237
 		}
238 238
 	}
239 239
 	else
240 240
 	{
241
-		dol_print_error('',$mesg);
241
+		dol_print_error('', $mesg);
242 242
 	}
243 243
 }
244 244
 
@@ -246,39 +246,39 @@  discard block
 block discarded – undo
246 246
 if ($action == 'confirm_deletesection' && $confirm == 'yes')
247 247
 {
248 248
 	// set up a connection or die
249
-	if (! $conn_id)
249
+	if (!$conn_id)
250 250
 	{
251
-		$newsectioniso=utf8_decode($section);
252
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
253
-		$conn_id=$resultarray['conn_id'];
254
-		$ok=$resultarray['ok'];
255
-		$mesg=$resultarray['mesg'];
251
+		$newsectioniso = utf8_decode($section);
252
+		$resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
253
+		$conn_id = $resultarray['conn_id'];
254
+		$ok = $resultarray['ok'];
255
+		$mesg = $resultarray['mesg'];
256 256
 	}
257 257
 
258
-	if ($conn_id && $ok && ! $mesg)
258
+	if ($conn_id && $ok && !$mesg)
259 259
 	{
260 260
 		// Remote file
261
-		$filename=$file;
262
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
263
-		$newremotefileiso=utf8_decode($remotefile);
261
+		$filename = $file;
262
+		$remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file;
263
+		$newremotefileiso = utf8_decode($remotefile);
264 264
 
265
-		$result=@ftp_rmdir($conn_id, $newremotefileiso);
265
+		$result = @ftp_rmdir($conn_id, $newremotefileiso);
266 266
 		if ($result)
267 267
 		{
268
-			setEventMessages($langs->trans("DirWasRemoved",$file), null, 'mesgs');
268
+			setEventMessages($langs->trans("DirWasRemoved", $file), null, 'mesgs');
269 269
 		}
270 270
 		else
271 271
 		{
272
-			setEventMessages($langs->trans("FTPFailedToRemoveDir",$file), null, 'errors');
272
+			setEventMessages($langs->trans("FTPFailedToRemoveDir", $file), null, 'errors');
273 273
 		}
274 274
 
275 275
 		//ftp_close($conn_id);	Close later
276 276
 
277
-		$action='';
277
+		$action = '';
278 278
 	}
279 279
 	else
280 280
 	{
281
-		dol_print_error('',$mesg);
281
+		dol_print_error('', $mesg);
282 282
 	}
283 283
 }
284 284
 
@@ -286,35 +286,35 @@  discard block
 block discarded – undo
286 286
 if ($action == 'download')
287 287
 {
288 288
 	// set up a connection or die
289
-	if (! $conn_id)
289
+	if (!$conn_id)
290 290
 	{
291
-		$newsectioniso=utf8_decode($section);
292
-		$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
293
-		$conn_id=$resultarray['conn_id'];
294
-		$ok=$resultarray['ok'];
295
-		$mesg=$resultarray['mesg'];
291
+		$newsectioniso = utf8_decode($section);
292
+		$resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $newsectioniso, $ftp_passive);
293
+		$conn_id = $resultarray['conn_id'];
294
+		$ok = $resultarray['ok'];
295
+		$mesg = $resultarray['mesg'];
296 296
 	}
297 297
 
298
-	if ($conn_id && $ok && ! $mesg)
298
+	if ($conn_id && $ok && !$mesg)
299 299
 	{
300 300
 		// Local file
301
-		$localfile=tempnam($download_dir,'dol_');
301
+		$localfile = tempnam($download_dir, 'dol_');
302 302
 
303 303
 		// Remote file
304
-		$filename=$file;
305
-		$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
306
-		$newremotefileiso=utf8_decode($remotefile);
304
+		$filename = $file;
305
+		$remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file;
306
+		$newremotefileiso = utf8_decode($remotefile);
307 307
 
308
-		$result=ftp_get($conn_id,$localfile,$newremotefileiso,FTP_BINARY);
308
+		$result = ftp_get($conn_id, $localfile, $newremotefileiso, FTP_BINARY);
309 309
 		if ($result)
310 310
 		{
311
-			if (! empty($conf->global->MAIN_UMASK))
311
+			if (!empty($conf->global->MAIN_UMASK))
312 312
 			@chmod($localfile, octdec($conf->global->MAIN_UMASK));
313 313
 
314 314
 			// Define mime type
315 315
 			$type = 'application/octet-stream';
316
-			if (! empty($_GET["type"])) $type=$_GET["type"];
317
-			else $type=dol_mimetype($original_file);
316
+			if (!empty($_GET["type"])) $type = $_GET["type"];
317
+			else $type = dol_mimetype($original_file);
318 318
 
319 319
 			// Define attachment (attachment=true to force choice popup 'open'/'save as')
320 320
 			$attachment = true;
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
 		}
337 337
 		else
338 338
 		{
339
-			setEventMessages($langs->transnoentitiesnoconv('FailedToGetFile',$remotefile), null, 'errors');
339
+			setEventMessages($langs->transnoentitiesnoconv('FailedToGetFile', $remotefile), null, 'errors');
340 340
 		}
341 341
 	}
342 342
 	else
343 343
 	{
344
-		dol_print_error('',$mesg);
344
+		dol_print_error('', $mesg);
345 345
 	}
346 346
 
347 347
 	//ftp_close($conn_id);	Close later
@@ -384,8 +384,8 @@  discard block
 block discarded – undo
384 384
 <?php
385 385
 }
386 386
 
387
-$form=new Form($db);
388
-$formfile=new FormFile($db);
387
+$form = new Form($db);
388
+$formfile = new FormFile($db);
389 389
 $userstatic = new User($db);
390 390
 
391 391
 
@@ -394,50 +394,50 @@  discard block
 block discarded – undo
394 394
 
395 395
 print $langs->trans("FTPAreaDesc")."<br>";
396 396
 
397
-if (! function_exists('ftp_connect'))
397
+if (!function_exists('ftp_connect'))
398 398
 {
399 399
 	print $langs->trans("FTPFeatureNotSupportedByYourPHP");
400 400
 }
401 401
 else
402 402
 {
403
-    if (! empty($ftp_server))
403
+    if (!empty($ftp_server))
404 404
 	{
405 405
 		// Confirm remove file
406 406
 		if ($action == 'delete')
407 407
 		{
408
-			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile','','',1);
408
+			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 1);
409 409
 		}
410 410
 
411 411
 		// Confirmation de la suppression d'une ligne categorie
412 412
 		if ($action == 'delete_section')
413 413
 		{
414
-			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection',$ecmdir->label), 'confirm_deletesection','','',1);
414
+			print $form->formconfirm($_SERVER["PHP_SELF"].'?numero_ftp='.$numero_ftp.'&section='.urlencode($_REQUEST["section"]).'&file='.urlencode($_GET["file"]), $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1);
415 415
 		}
416 416
 
417 417
 		print $langs->trans("Server").': <b>'.$ftp_server.'</b><br>';
418
-		print $langs->trans("Port").': <b>'.$ftp_port.'</b> '.($ftp_passive?"(Passive)":"(Active)").'<br>';
418
+		print $langs->trans("Port").': <b>'.$ftp_port.'</b> '.($ftp_passive ? "(Passive)" : "(Active)").'<br>';
419 419
 		print $langs->trans("User").': <b>'.$ftp_user.'</b><br>';
420 420
         print $langs->trans("FTPs (FTP over SSH)").': <b>'.yn($conf->global->FTP_CONNECT_WITH_SSL).'</b><br>';
421 421
         print $langs->trans("SFTP (FTP as a subsytem of SSH)").': <b>'.yn($conf->global->FTP_CONNECT_WITH_SFTP).'</b><br>';
422 422
         print $langs->trans("Directory").': ';
423
-		$sectionarray=preg_split('|[\/]|',$section);
423
+		$sectionarray = preg_split('|[\/]|', $section);
424 424
 		// For /
425
-		$newsection='/';
426
-		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
425
+		$newsection = '/';
426
+		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection ? '&section='.urlencode($newsection) : '').'">';
427 427
 		print '/';
428 428
 		print '</a> ';
429 429
 		// For other directories
430
-		$i=0;
431
-		foreach($sectionarray as $val)
430
+		$i = 0;
431
+		foreach ($sectionarray as $val)
432 432
 		{
433
-			if (empty($val)) continue;	// Discard first and last entry that should be empty as section start/end with /
433
+			if (empty($val)) continue; // Discard first and last entry that should be empty as section start/end with /
434 434
 			if ($i > 0)
435 435
 			{
436 436
 				print ' / ';
437
-				$newsection.='/';
437
+				$newsection .= '/';
438 438
 			}
439
-			$newsection.=$val;
440
-			print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection?'&section='.urlencode($newsection):'').'">';
439
+			$newsection .= $val;
440
+			print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($newsection ? '&section='.urlencode($newsection) : '').'">';
441 441
 			print $val;
442 442
 			print '</a>';
443 443
 			$i++;
@@ -462,62 +462,62 @@  discard block
 block discarded – undo
462 462
 		print '<td class="liste_titre" align="center">'.$langs->trans("Permissions").'</td>'."\n";
463 463
 		print '<td class="liste_titre nowrap" align="right">';
464 464
 		if ($conf->use_javascript_ajax) print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> ';
465
-		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section?'&section='.urlencode($section):'').'">'.img_picto($langs->trans("Refresh"),'refresh').'</a>&nbsp;';
465
+		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section ? '&section='.urlencode($section) : '').'">'.img_picto($langs->trans("Refresh"), 'refresh').'</a>&nbsp;';
466 466
 		print '</td>'."\n";
467 467
 		print '</tr>'."\n";
468 468
 
469 469
 		// set up a connection or die
470 470
 		if (empty($conn_id))
471 471
 		{
472
-			$resultarray=dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive);
472
+			$resultarray = dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive);
473 473
 
474
-			$conn_id=$resultarray['conn_id'];
475
-			$ok=$resultarray['ok'];
476
-			$mesg=$resultarray['mesg'];
474
+			$conn_id = $resultarray['conn_id'];
475
+			$ok = $resultarray['ok'];
476
+			$mesg = $resultarray['mesg'];
477 477
 		}
478 478
 
479 479
 		if ($ok)
480 480
 		{
481 481
 			//$type = ftp_systype($conn_id);
482 482
 
483
-			$newsection=$section;
484
-		    $newsectioniso=utf8_decode($section);
483
+			$newsection = $section;
484
+		    $newsectioniso = utf8_decode($section);
485 485
 			//$newsection='/home';
486 486
 
487 487
 			// List content of directory ($newsection = '/', '/home', ...)
488
-			if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
488
+			if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
489 489
 			{
490
-			    if ($newsection == '/') $newsection='/./';  // workaround for bug https://bugs.php.net/bug.php?id=64169
490
+			    if ($newsection == '/') $newsection = '/./'; // workaround for bug https://bugs.php.net/bug.php?id=64169
491 491
 			    //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
492 492
 			    //var_dump($dirHandle);
493
-                $contents = scandir('ssh2.sftp://' . $conn_id . $newsection);
494
-                $buff=array();
495
-                foreach($contents as $i => $key)
493
+                $contents = scandir('ssh2.sftp://'.$conn_id.$newsection);
494
+                $buff = array();
495
+                foreach ($contents as $i => $key)
496 496
                 {
497
-                    $buff[$i]="---------- - root root 1234 Aug 01 2000 ".$key;
497
+                    $buff[$i] = "---------- - root root 1234 Aug 01 2000 ".$key;
498 498
                 }
499 499
     		}
500 500
     		else
501 501
     		{
502 502
                 $buff = ftp_rawlist($conn_id, $newsectioniso);
503
-                $contents = ftp_nlist($conn_id, $newsectioniso);	// Sometimes rawlist fails but never nlist
503
+                $contents = ftp_nlist($conn_id, $newsectioniso); // Sometimes rawlist fails but never nlist
504 504
         		//var_dump($contents);
505 505
 		        //var_dump($buff);
506 506
     		}
507 507
 
508
-			$nboflines=count($contents);
509
-			$rawlisthasfailed=false;
510
-			$i=0;
508
+			$nboflines = count($contents);
509
+			$rawlisthasfailed = false;
510
+			$i = 0;
511 511
 			while ($i < $nboflines && $i < 1000)
512 512
 			{
513
-				$vals=preg_split('@ +@',utf8_encode($buff[$i]),9);
513
+				$vals = preg_split('@ +@', utf8_encode($buff[$i]), 9);
514 514
 				//$vals=preg_split('@ +@','drwxr-xr-x 2 root root 4096 Aug 30 2008 backup_apollon1',9);
515 515
 				//var_dump($vals);
516
-				$file=$vals[8];
516
+				$file = $vals[8];
517 517
 				if (empty($file))
518 518
 				{
519
-					$rawlisthasfailed=true;
520
-					$file=utf8_encode($contents[$i]);
519
+					$rawlisthasfailed = true;
520
+					$file = utf8_encode($contents[$i]);
521 521
 				}
522 522
 
523 523
 				if ($file == '.' || ($file == '..' && $section == '/'))
@@ -527,40 +527,40 @@  discard block
 block discarded – undo
527 527
 				}
528 528
 
529 529
 				// Is it a directory ?
530
-				$is_directory=0;
531
-				if ($file == '..') $is_directory=1;
532
-				else if (! $rawlisthasfailed)
530
+				$is_directory = 0;
531
+				if ($file == '..') $is_directory = 1;
532
+				else if (!$rawlisthasfailed)
533 533
 				{
534
-					if (preg_match('/^d/',$vals[0])) $is_directory=1;
535
-					if (preg_match('/^l/',$vals[0])) $is_link=1;
534
+					if (preg_match('/^d/', $vals[0])) $is_directory = 1;
535
+					if (preg_match('/^l/', $vals[0])) $is_link = 1;
536 536
 				}
537 537
 				else
538 538
 				{
539 539
 					// Remote file
540
-					$filename=$file;
540
+					$filename = $file;
541 541
 					//print "section=".$section.' file='.$file.'X';
542 542
 					//print preg_match('@[\/]$@','aaa/').'Y';
543 543
 					//print preg_match('@[\\\/]$@',"aaa\\").'Y';
544
-					$remotefile=$section.(preg_match('@[\\\/]$@',$section)?'':'/').preg_replace('@^[\\\/]@','',$file);
544
+					$remotefile = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').preg_replace('@^[\\\/]@', '', $file);
545 545
 					//print 'A'.$remotefile.'A';
546
-					$newremotefileiso=utf8_decode($remotefile);
546
+					$newremotefileiso = utf8_decode($remotefile);
547 547
 					//print 'Z'.$newremotefileiso.'Z';
548
-					$is_directory=ftp_isdir($conn_id, $newremotefileiso);
548
+					$is_directory = ftp_isdir($conn_id, $newremotefileiso);
549 549
 				}
550 550
 
551 551
 
552 552
 				print '<tr class="oddeven" height="18">';
553 553
 				// Name
554 554
 				print '<td>';
555
-				$newsection=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
556
-				$newsection=preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@','/',$newsection);	// Change aaa/xxx/.. to new aaa
555
+				$newsection = $section.(preg_match('@[\\\/]$@', $section) ? '' : '/').$file;
556
+				$newsection = preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@', '/', $newsection); // Change aaa/xxx/.. to new aaa
557 557
 				if ($is_directory) print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">';
558 558
 				print $file;
559 559
 				if ($is_directory) print '</a>';
560 560
 				print '</td>';
561 561
 				// Size
562 562
 				print '<td align="center" class="nowrap">';
563
-				if (! $is_directory && ! $is_link) print $vals[4];
563
+				if (!$is_directory && !$is_link) print $vals[4];
564 564
 				else print '&nbsp;';
565 565
 				print '</td>';
566 566
 				// Date
@@ -588,13 +588,13 @@  discard block
 block discarded – undo
588 588
 				}
589 589
 				else if ($is_link)
590 590
 				{
591
-					$newfile=$file;
592
-					$newfile=preg_replace('/ ->.*/','',$newfile);
591
+					$newfile = $file;
592
+					$newfile = preg_replace('/ ->.*/', '', $newfile);
593 593
 					print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($newfile).'">'.img_delete().'</a>';
594 594
 				}
595 595
 				else
596 596
 				{
597
-					print '<a href="'.$_SERVER["PHP_SELF"].'?action=download&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_picto('','file').'</a>';
597
+					print '<a href="'.$_SERVER["PHP_SELF"].'?action=download&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_picto('', 'file').'</a>';
598 598
 					print ' &nbsp; ';
599 599
 					print '<input type="checkbox" class="flat checkboxfordelete" id="check_'.$i.'" name="const['.$i.'][check]" value="1">';
600 600
 					print ' &nbsp; ';
@@ -612,7 +612,7 @@  discard block
 block discarded – undo
612 612
 		print "</table>";
613 613
 
614 614
 
615
-		if (! $ok)
615
+		if (!$ok)
616 616
 		{
617 617
 		      print $mesg.'<br>'."\n";
618 618
 		      setEventMessages($mesg, null, 'errors');
@@ -637,21 +637,21 @@  discard block
 block discarded – undo
637 637
 	}
638 638
 	else
639 639
 	{
640
-		$foundsetup=false;
641
-		$MAXFTP=20;
642
-		$i=1;
640
+		$foundsetup = false;
641
+		$MAXFTP = 20;
642
+		$i = 1;
643 643
 		while ($i <= $MAXFTP)
644 644
 		{
645
-			$paramkey='FTP_NAME_'.$i;
645
+			$paramkey = 'FTP_NAME_'.$i;
646 646
 			//print $paramkey;
647
-			if (! empty($conf->global->$paramkey))
647
+			if (!empty($conf->global->$paramkey))
648 648
 			{
649
-				$foundsetup=true;
649
+				$foundsetup = true;
650 650
 				break;
651 651
 			}
652 652
 			$i++;
653 653
 		}
654
-	    if (! $foundsetup)
654
+	    if (!$foundsetup)
655 655
 	    {
656 656
             print $langs->trans("SetupOfFTPClientModuleNotComplete");
657 657
 	    }
@@ -667,11 +667,11 @@  discard block
 block discarded – undo
667 667
 // Close FTP connection
668 668
 if ($conn_id)
669 669
 {
670
-    if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
670
+    if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
671 671
     {
672 672
 
673 673
     }
674
-    else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
674
+    else if (!empty($conf->global->FTP_CONNECT_WITH_SSL))
675 675
     {
676 676
         ftp_close($conn_id);
677 677
     }
@@ -698,28 +698,28 @@  discard block
 block discarded – undo
698 698
  * @param	integer	$ftp_passive	Use a passive mode
699 699
  * @return	int 	<0 if OK, >0 if KO
700 700
  */
701
-function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive=0)
701
+function dol_ftp_connect($ftp_server, $ftp_port, $ftp_user, $ftp_password, $section, $ftp_passive = 0)
702 702
 {
703 703
 	global $langs, $conf;
704 704
 
705
-	$ok=1;
706
-    $conn_id=null;
705
+	$ok = 1;
706
+    $conn_id = null;
707 707
 
708
-	if (! is_numeric($ftp_port))
708
+	if (!is_numeric($ftp_port))
709 709
 	{
710
-		$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
711
-		$ok=0;
710
+		$mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServer", $ftp_server, $ftp_port);
711
+		$ok = 0;
712 712
 	}
713 713
 
714 714
 	if ($ok)
715 715
 	{
716
-		$connecttimeout=(empty($conf->global->FTP_CONNECT_TIMEOUT)?40:$conf->global->FTP_CONNECT_TIMEOUT);
717
-		if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
716
+		$connecttimeout = (empty($conf->global->FTP_CONNECT_TIMEOUT) ? 40 : $conf->global->FTP_CONNECT_TIMEOUT);
717
+		if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
718 718
 		{
719 719
 		    dol_syslog('Try to connect with ssh2_ftp');
720 720
 		    $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
721 721
 		}
722
-		else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
722
+		else if (!empty($conf->global->FTP_CONNECT_WITH_SSL))
723 723
 		{
724 724
 		    dol_syslog('Try to connect with ftp_ssl_connect');
725 725
 		    $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
@@ -733,7 +733,7 @@  discard block
 block discarded – undo
733 733
 		{
734 734
 			if ($ftp_user)
735 735
 			{
736
-				if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
736
+				if (!empty($conf->global->FTP_CONNECT_WITH_SFTP))
737 737
 				{
738 738
 				    if (ssh2_auth_password($tmp_conn_id, $ftp_user, $ftp_password))
739 739
     				{
@@ -741,20 +741,20 @@  discard block
 block discarded – undo
741 741
     					//if ($ftp_passive) ftp_pasv($conn_id, true);
742 742
 
743 743
     					// Change the dir
744
-    					$newsectioniso=utf8_decode($section);
744
+    					$newsectioniso = utf8_decode($section);
745 745
     					//ftp_chdir($conn_id, $newsectioniso);
746 746
 		                $conn_id = ssh2_sftp($tmp_conn_id);
747
-		                if (! $conn_id)
747
+		                if (!$conn_id)
748 748
 		                {
749
-        					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
750
-    	   				    $ok=0;
749
+        					$mesg = $langs->transnoentitiesnoconv("FailedToConnectToSFTPAfterSSHAuthentication");
750
+    	   				    $ok = 0;
751 751
         				    $error++;
752 752
 		                }
753 753
     				}
754 754
     				else
755 755
     				{
756
-    					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
757
-	   				    $ok=0;
756
+    					$mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
757
+	   				    $ok = 0;
758 758
     				    $error++;
759 759
     				}
760 760
 				}
@@ -766,13 +766,13 @@  discard block
 block discarded – undo
766 766
     					if ($ftp_passive) ftp_pasv($conn_id, true);
767 767
 
768 768
     					// Change the dir
769
-    					$newsectioniso=utf8_decode($section);
769
+    					$newsectioniso = utf8_decode($section);
770 770
     					ftp_chdir($conn_id, $newsectioniso);
771 771
     				}
772 772
     				else
773 773
     				{
774
-    					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
775
-	   				    $ok=0;
774
+    					$mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
775
+	   				    $ok = 0;
776 776
     				    $error++;
777 777
     				}
778 778
 				}
@@ -781,12 +781,12 @@  discard block
 block discarded – undo
781 781
 		else
782 782
 		{
783 783
 		    dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
784
-			$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
785
-			$ok=0;
784
+			$mesg = $langs->transnoentitiesnoconv("FailedToConnectToFTPServer", $ftp_server, $ftp_port);
785
+			$ok = 0;
786 786
 		}
787 787
 	}
788 788
 
789
-	$arrayresult=array('conn_id'=>$conn_id, 'ok'=>$ok, 'mesg'=>$mesg, 'curdir'=>$section, 'curdiriso'=>$newsectioniso);
789
+	$arrayresult = array('conn_id'=>$conn_id, 'ok'=>$ok, 'mesg'=>$mesg, 'curdir'=>$section, 'curdiriso'=>$newsectioniso);
790 790
 	return $arrayresult;
791 791
 }
792 792
 
@@ -798,9 +798,9 @@  discard block
 block discarded – undo
798 798
  * @param 		string		$dir			Directory
799 799
  * @return		int			1=directory, 0=not a directory
800 800
  */
801
-function ftp_isdir($connect_id,$dir)
801
+function ftp_isdir($connect_id, $dir)
802 802
 {
803
-	if (@ftp_chdir($connect_id,$dir))
803
+	if (@ftp_chdir($connect_id, $dir))
804 804
 	{
805 805
 		ftp_cdup($connect_id);
806 806
 		return 1;
Please login to merge, or discard this patch.
Braces   +108 added lines, -85 removed lines patch added patch discarded remove patch
@@ -31,13 +31,17 @@  discard block
 block discarded – undo
31 31
 $langs->loadLangs(array('ftp', 'companies', 'other'));
32 32
 
33 33
 // Security check
34
-if ($user->societe_id) $socid=$user->societe_id;
34
+if ($user->societe_id) {
35
+    $socid=$user->societe_id;
36
+}
35 37
 $result = restrictedArea($user, 'ftp','');
36 38
 
37 39
 // Get parameters
38 40
 $action=GETPOST('action','aZ09');
39 41
 $section=GETPOST('section');
40
-if (! $section) $section='/';
42
+if (! $section) {
43
+    $section='/';
44
+}
41 45
 $numero_ftp = GETPOST("numero_ftp");
42 46
 /* if (! $numero_ftp) $numero_ftp=1; */
43 47
 $file=GETPOST("file");
@@ -53,8 +57,12 @@  discard block
 block discarded – undo
53 57
 $offset = $conf->liste_limit * $page;
54 58
 $pageprev = $page - 1;
55 59
 $pagenext = $page + 1;
56
-if (! $sortorder) $sortorder="ASC";
57
-if (! $sortfield) $sortfield="label";
60
+if (! $sortorder) {
61
+    $sortorder="ASC";
62
+}
63
+if (! $sortfield) {
64
+    $sortfield="label";
65
+}
58 66
 
59 67
 $s_ftp_name='FTP_NAME_'.$numero_ftp;
60 68
 $s_ftp_server='FTP_SERVER_'.$numero_ftp;
@@ -64,7 +72,9 @@  discard block
 block discarded – undo
64 72
 $s_ftp_passive='FTP_PASSIVE_'.$numero_ftp;
65 73
 $ftp_name=$conf->global->$s_ftp_name;
66 74
 $ftp_server=$conf->global->$s_ftp_server;
67
-$ftp_port=$conf->global->$s_ftp_port; if (empty($ftp_port)) $ftp_port=21;
75
+$ftp_port=$conf->global->$s_ftp_port; if (empty($ftp_port)) {
76
+    $ftp_port=21;
77
+}
68 78
 $ftp_user=$conf->global->$s_ftp_user;
69 79
 $ftp_password=$conf->global->$s_ftp_password;
70 80
 $ftp_passive=$conf->global->$s_ftp_passive;
@@ -100,24 +110,24 @@  discard block
 block discarded – undo
100 110
 		if (is_numeric($resupload) && $resupload > 0)
101 111
 		{
102 112
 			$result=$ecmdir->changeNbOfFiles('+');
103
-		}
104
-		else {
113
+		} else {
105 114
 			$langs->load("errors");
106
-			if ($resupload < 0)	// Unknown error
115
+			if ($resupload < 0) {
116
+			    // Unknown error
107 117
 			{
108 118
 				setEventMessages($langs->trans("ErrorFileNotUploaded"), null, 'errors');
109 119
 			}
110
-			else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload))	// Files infected by a virus
120
+			} else if (preg_match('/ErrorFileIsInfectedWithAVirus/',$resupload)) {
121
+			    // Files infected by a virus
111 122
 			{
112 123
 				setEventMessages($langs->trans("ErrorFileIsInfectedWithAVirus"), null, 'errors');
113 124
 			}
114
-			else	// Known error
125
+			} else	// Known error
115 126
 			{
116 127
 				setEventMessages($langs->trans($resupload), null, 'errors');
117 128
 			}
118 129
 		}
119
-	}
120
-	else
130
+	} else
121 131
 	{
122 132
 		// Echec transfert (fichier depassant la limite ?)
123 133
 		$langs->load("errors");
@@ -137,8 +147,7 @@  discard block
 block discarded – undo
137 147
 	{
138 148
 		header("Location: ".$_SERVER["PHP_SELF"]);
139 149
 		exit;
140
-	}
141
-	else
150
+	} else
142 151
 	{
143 152
 		setEventMessages($langs->trans("ErrorFailToCreateDir"), null, 'errors');
144 153
 		$action = "create";
@@ -173,8 +182,7 @@  discard block
 block discarded – undo
173 182
 		if ($result)
174 183
 		{
175 184
 			setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
176
-		}
177
-		else
185
+		} else
178 186
 		{
179 187
 			dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
180 188
 			setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
@@ -183,8 +191,7 @@  discard block
 block discarded – undo
183 191
 		//ftp_close($conn_id);	Close later
184 192
 
185 193
 		$action='';
186
-	}
187
-	else
194
+	} else
188 195
 	{
189 196
 		dol_print_error('',$mesg);
190 197
 	}
@@ -207,9 +214,11 @@  discard block
 block discarded – undo
207 214
 	{
208 215
 		foreach($_POST["const"] as $const)
209 216
 		{
210
-			if ($const["check"])	// Is checkbox checked
217
+			if ($const["check"]) {
218
+			    // Is checkbox checked
211 219
 			{
212 220
 			    $langs->load("other");
221
+			}
213 222
 
214 223
 				// Remote file
215 224
 				$file=$const["file"];
@@ -223,8 +232,7 @@  discard block
 block discarded – undo
223 232
 				if ($result)
224 233
 				{
225 234
 					setEventMessages($langs->trans("FileWasRemoved",$file), null, 'mesgs');
226
-				}
227
-				else
235
+				} else
228 236
 				{
229 237
 					dol_syslog("ftp/index.php ftp_delete", LOG_ERR);
230 238
 					setEventMessages($langs->trans("FTPFailedToRemoveFile",$file), null, 'errors');
@@ -235,8 +243,7 @@  discard block
 block discarded – undo
235 243
 				$action='';
236 244
 			}
237 245
 		}
238
-	}
239
-	else
246
+	} else
240 247
 	{
241 248
 		dol_print_error('',$mesg);
242 249
 	}
@@ -266,8 +273,7 @@  discard block
 block discarded – undo
266 273
 		if ($result)
267 274
 		{
268 275
 			setEventMessages($langs->trans("DirWasRemoved",$file), null, 'mesgs');
269
-		}
270
-		else
276
+		} else
271 277
 		{
272 278
 			setEventMessages($langs->trans("FTPFailedToRemoveDir",$file), null, 'errors');
273 279
 		}
@@ -275,8 +281,7 @@  discard block
 block discarded – undo
275 281
 		//ftp_close($conn_id);	Close later
276 282
 
277 283
 		$action='';
278
-	}
279
-	else
284
+	} else
280 285
 	{
281 286
 		dol_print_error('',$mesg);
282 287
 	}
@@ -308,21 +313,32 @@  discard block
 block discarded – undo
308 313
 		$result=ftp_get($conn_id,$localfile,$newremotefileiso,FTP_BINARY);
309 314
 		if ($result)
310 315
 		{
311
-			if (! empty($conf->global->MAIN_UMASK))
312
-			@chmod($localfile, octdec($conf->global->MAIN_UMASK));
316
+			if (! empty($conf->global->MAIN_UMASK)) {
317
+						@chmod($localfile, octdec($conf->global->MAIN_UMASK));
318
+			}
313 319
 
314 320
 			// Define mime type
315 321
 			$type = 'application/octet-stream';
316
-			if (! empty($_GET["type"])) $type=$_GET["type"];
317
-			else $type=dol_mimetype($original_file);
322
+			if (! empty($_GET["type"])) {
323
+			    $type=$_GET["type"];
324
+			} else {
325
+			    $type=dol_mimetype($original_file);
326
+			}
318 327
 
319 328
 			// Define attachment (attachment=true to force choice popup 'open'/'save as')
320 329
 			$attachment = true;
321 330
 
322
-			if ($encoding)   header('Content-Encoding: '.$encoding);
323
-			if ($type)       header('Content-Type: '.$type);
324
-			if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"');
325
-			else header('Content-Disposition: inline; filename="'.$filename.'"');
331
+			if ($encoding) {
332
+			    header('Content-Encoding: '.$encoding);
333
+			}
334
+			if ($type) {
335
+			    header('Content-Type: '.$type);
336
+			}
337
+			if ($attachment) {
338
+			    header('Content-Disposition: attachment; filename="'.$filename.'"');
339
+			} else {
340
+			    header('Content-Disposition: inline; filename="'.$filename.'"');
341
+			}
326 342
 
327 343
 			// Ajout directives pour resoudre bug IE
328 344
 			header('Cache-Control: Public, must-revalidate');
@@ -333,13 +349,11 @@  discard block
 block discarded – undo
333 349
 			ftp_close($conn_id);
334 350
 
335 351
 			exit;
336
-		}
337
-		else
352
+		} else
338 353
 		{
339 354
 			setEventMessages($langs->transnoentitiesnoconv('FailedToGetFile',$remotefile), null, 'errors');
340 355
 		}
341
-	}
342
-	else
356
+	} else
343 357
 	{
344 358
 		dol_print_error('',$mesg);
345 359
 	}
@@ -397,8 +411,7 @@  discard block
 block discarded – undo
397 411
 if (! function_exists('ftp_connect'))
398 412
 {
399 413
 	print $langs->trans("FTPFeatureNotSupportedByYourPHP");
400
-}
401
-else
414
+} else
402 415
 {
403 416
     if (! empty($ftp_server))
404 417
 	{
@@ -430,7 +443,10 @@  discard block
 block discarded – undo
430 443
 		$i=0;
431 444
 		foreach($sectionarray as $val)
432 445
 		{
433
-			if (empty($val)) continue;	// Discard first and last entry that should be empty as section start/end with /
446
+			if (empty($val)) {
447
+			    continue;
448
+			}
449
+			// Discard first and last entry that should be empty as section start/end with /
434 450
 			if ($i > 0)
435 451
 			{
436 452
 				print ' / ';
@@ -461,7 +477,9 @@  discard block
 block discarded – undo
461 477
 		print '<td class="liste_titre" align="center">'.$langs->trans("Group").'</td>'."\n";
462 478
 		print '<td class="liste_titre" align="center">'.$langs->trans("Permissions").'</td>'."\n";
463 479
 		print '<td class="liste_titre nowrap" align="right">';
464
-		if ($conf->use_javascript_ajax) print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> ';
480
+		if ($conf->use_javascript_ajax) {
481
+		    print '<a href="#" id="checkall">'.$langs->trans("All").'</a> / <a href="#" id="checknone">'.$langs->trans("None").'</a> ';
482
+		}
465 483
 		print '<a href="'.$_SERVER["PHP_SELF"].'?action=refreshmanual&numero_ftp='.$numero_ftp.($section?'&section='.urlencode($section):'').'">'.img_picto($langs->trans("Refresh"),'refresh').'</a>&nbsp;';
466 484
 		print '</td>'."\n";
467 485
 		print '</tr>'."\n";
@@ -487,7 +505,10 @@  discard block
 block discarded – undo
487 505
 			// List content of directory ($newsection = '/', '/home', ...)
488 506
 			if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
489 507
 			{
490
-			    if ($newsection == '/') $newsection='/./';  // workaround for bug https://bugs.php.net/bug.php?id=64169
508
+			    if ($newsection == '/') {
509
+			        $newsection='/./';
510
+			    }
511
+			    // workaround for bug https://bugs.php.net/bug.php?id=64169
491 512
 			    //$dirHandle = opendir("ssh2.sftp://$conn_id".$newsection);
492 513
 			    //var_dump($dirHandle);
493 514
                 $contents = scandir('ssh2.sftp://' . $conn_id . $newsection);
@@ -496,8 +517,7 @@  discard block
 block discarded – undo
496 517
                 {
497 518
                     $buff[$i]="---------- - root root 1234 Aug 01 2000 ".$key;
498 519
                 }
499
-    		}
500
-    		else
520
+    		} else
501 521
     		{
502 522
                 $buff = ftp_rawlist($conn_id, $newsectioniso);
503 523
                 $contents = ftp_nlist($conn_id, $newsectioniso);	// Sometimes rawlist fails but never nlist
@@ -528,13 +548,17 @@  discard block
 block discarded – undo
528 548
 
529 549
 				// Is it a directory ?
530 550
 				$is_directory=0;
531
-				if ($file == '..') $is_directory=1;
532
-				else if (! $rawlisthasfailed)
551
+				if ($file == '..') {
552
+				    $is_directory=1;
553
+				} else if (! $rawlisthasfailed)
533 554
 				{
534
-					if (preg_match('/^d/',$vals[0])) $is_directory=1;
535
-					if (preg_match('/^l/',$vals[0])) $is_link=1;
536
-				}
537
-				else
555
+					if (preg_match('/^d/',$vals[0])) {
556
+					    $is_directory=1;
557
+					}
558
+					if (preg_match('/^l/',$vals[0])) {
559
+					    $is_link=1;
560
+					}
561
+				} else
538 562
 				{
539 563
 					// Remote file
540 564
 					$filename=$file;
@@ -554,14 +578,21 @@  discard block
 block discarded – undo
554 578
 				print '<td>';
555 579
 				$newsection=$section.(preg_match('@[\\\/]$@',$section)?'':'/').$file;
556 580
 				$newsection=preg_replace('@[\\\/][^\\\/]+[\\\/]\.\.$@','/',$newsection);	// Change aaa/xxx/.. to new aaa
557
-				if ($is_directory) print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">';
581
+				if ($is_directory) {
582
+				    print '<a href="'.$_SERVER["PHP_SELF"].'?section='.urlencode($newsection).'&numero_ftp='.$numero_ftp.'">';
583
+				}
558 584
 				print $file;
559
-				if ($is_directory) print '</a>';
585
+				if ($is_directory) {
586
+				    print '</a>';
587
+				}
560 588
 				print '</td>';
561 589
 				// Size
562 590
 				print '<td align="center" class="nowrap">';
563
-				if (! $is_directory && ! $is_link) print $vals[4];
564
-				else print '&nbsp;';
591
+				if (! $is_directory && ! $is_link) {
592
+				    print $vals[4];
593
+				} else {
594
+				    print '&nbsp;';
595
+				}
565 596
 				print '</td>';
566 597
 				// Date
567 598
 				print '<td align="center" class="nowrap">';
@@ -583,16 +614,17 @@  discard block
 block discarded – undo
583 614
 				print '<td align="right" width="64" class="nowrap">';
584 615
 				if ($is_directory)
585 616
 				{
586
-					if ($file != '..') print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
587
-					else print '&nbsp;';
588
-				}
589
-				else if ($is_link)
617
+					if ($file != '..') {
618
+					    print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete_section&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_delete().'</a>';
619
+					} else {
620
+					    print '&nbsp;';
621
+					}
622
+				} else if ($is_link)
590 623
 				{
591 624
 					$newfile=$file;
592 625
 					$newfile=preg_replace('/ ->.*/','',$newfile);
593 626
 					print '<a href="'.$_SERVER["PHP_SELF"].'?action=delete&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($newfile).'">'.img_delete().'</a>';
594
-				}
595
-				else
627
+				} else
596 628
 				{
597 629
 					print '<a href="'.$_SERVER["PHP_SELF"].'?action=download&numero_ftp='.$numero_ftp.'&section='.urlencode($section).'&file='.urlencode($file).'">'.img_picto('','file').'</a>';
598 630
 					print ' &nbsp; ';
@@ -634,8 +666,7 @@  discard block
 block discarded – undo
634 666
 		print '</div>';
635 667
 
636 668
 		print "</form>";
637
-	}
638
-	else
669
+	} else
639 670
 	{
640 671
 		$foundsetup=false;
641 672
 		$MAXFTP=20;
@@ -654,8 +685,7 @@  discard block
 block discarded – undo
654 685
 	    if (! $foundsetup)
655 686
 	    {
656 687
             print $langs->trans("SetupOfFTPClientModuleNotComplete");
657
-	    }
658
-	    else
688
+	    } else
659 689
 	    {
660 690
 	        print $langs->trans("ChooseAFTPEntryIntoMenu");
661 691
 	    }
@@ -670,12 +700,10 @@  discard block
 block discarded – undo
670 700
     if (! empty($conf->global->FTP_CONNECT_WITH_SFTP))
671 701
     {
672 702
 
673
-    }
674
-    else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
703
+    } else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
675 704
     {
676 705
         ftp_close($conn_id);
677
-    }
678
-    else
706
+    } else
679 707
     {
680 708
         ftp_close($conn_id);
681 709
     }
@@ -718,13 +746,11 @@  discard block
 block discarded – undo
718 746
 		{
719 747
 		    dol_syslog('Try to connect with ssh2_ftp');
720 748
 		    $tmp_conn_id = ssh2_connect($ftp_server, $ftp_port);
721
-		}
722
-		else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
749
+		} else if (! empty($conf->global->FTP_CONNECT_WITH_SSL))
723 750
 		{
724 751
 		    dol_syslog('Try to connect with ftp_ssl_connect');
725 752
 		    $conn_id = ftp_ssl_connect($ftp_server, $ftp_port, $connecttimeout);
726
-		}
727
-		else
753
+		} else
728 754
 		{
729 755
 		    dol_syslog('Try to connect with ftp_connect');
730 756
 		    $conn_id = ftp_connect($ftp_server, $ftp_port, $connecttimeout);
@@ -750,26 +776,25 @@  discard block
 block discarded – undo
750 776
     	   				    $ok=0;
751 777
         				    $error++;
752 778
 		                }
753
-    				}
754
-    				else
779
+    				} else
755 780
     				{
756 781
     					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
757 782
 	   				    $ok=0;
758 783
     				    $error++;
759 784
     				}
760
-				}
761
-				else
785
+				} else
762 786
 				{
763 787
 				    if (ftp_login($conn_id, $ftp_user, $ftp_password))
764 788
     				{
765 789
     					// Turn on passive mode transfers (must be after a successful login
766
-    					if ($ftp_passive) ftp_pasv($conn_id, true);
790
+    					if ($ftp_passive) {
791
+    					    ftp_pasv($conn_id, true);
792
+    					}
767 793
 
768 794
     					// Change the dir
769 795
     					$newsectioniso=utf8_decode($section);
770 796
     					ftp_chdir($conn_id, $newsectioniso);
771
-    				}
772
-    				else
797
+    				} else
773 798
     				{
774 799
     					$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServerWithCredentials");
775 800
 	   				    $ok=0;
@@ -777,8 +802,7 @@  discard block
 block discarded – undo
777 802
     				}
778 803
 				}
779 804
 			}
780
-		}
781
-		else
805
+		} else
782 806
 		{
783 807
 		    dol_syslog('FailedToConnectToFTPServer '.$ftp_server.' '.$ftp_port, LOG_ERR);
784 808
 			$mesg=$langs->transnoentitiesnoconv("FailedToConnectToFTPServer",$ftp_server,$ftp_port);
@@ -804,8 +828,7 @@  discard block
 block discarded – undo
804 828
 	{
805 829
 		ftp_cdup($connect_id);
806 830
 		return 1;
807
-	}
808
-	else
831
+	} else
809 832
 	{
810 833
 		return 0;
811 834
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/dav/dav.class.php 3 patches
Indentation   +205 added lines, -205 removed lines patch added patch discarded remove patch
@@ -28,11 +28,11 @@  discard block
 block discarded – undo
28 28
 class CdavLib
29 29
 {
30 30
 
31
-	private $db;
31
+    private $db;
32 32
 
33
-	private $user;
33
+    private $user;
34 34
 
35
-	private $langs;
35
+    private $langs;
36 36
 
37 37
     /**
38 38
      * Constructor
@@ -41,25 +41,25 @@  discard block
 block discarded – undo
41 41
      * @param   DoliDB      $db     Database handler
42 42
      * @param   Translate   $langs  translation
43 43
      */
44
-	function __construct($user, $db, $langs)
45
-	{
46
-		$this->user = $user;
47
-		$this->db = $db;
48
-		$this->langs = $langs;
49
-	}
44
+    function __construct($user, $db, $langs)
45
+    {
46
+        $this->user = $user;
47
+        $this->db = $db;
48
+        $this->langs = $langs;
49
+    }
50 50
 
51
-	/**
52
-	 * Base sql request for calendar events
53
-	 *
54
-	 * @param 	int 		$calid 			Calendard id
55
-	 * @param 	int|boolean	$oid			Oid
56
-	 * @param	int|boolean	$ouri			Ouri
57
-	 * @return string
58
-	 */
59
-	public function getSqlCalEvents($calid, $oid=false, $ouri=false)
60
-	{
61
-		// TODO : replace GROUP_CONCAT by
62
-		$sql = 'SELECT
51
+    /**
52
+     * Base sql request for calendar events
53
+     *
54
+     * @param 	int 		$calid 			Calendard id
55
+     * @param 	int|boolean	$oid			Oid
56
+     * @param	int|boolean	$ouri			Ouri
57
+     * @return string
58
+     */
59
+    public function getSqlCalEvents($calid, $oid=false, $ouri=false)
60
+    {
61
+        // TODO : replace GROUP_CONCAT by
62
+        $sql = 'SELECT
63 63
 					a.tms AS lastupd,
64 64
 					a.*,
65 65
 					sp.firstname,
@@ -82,223 +82,223 @@  discard block
 block discarded – undo
82 82
 						LEFT OUTER JOIN '.MAIN_DB_PREFIX.'user AS u ON (u.rowid=fk_element)
83 83
 						WHERE ar.element_type=\'user\' AND fk_actioncomm=a.id) AS other_users
84 84
 				FROM '.MAIN_DB_PREFIX.'actioncomm AS a';
85
-		if (! $this->user->rights->societe->client->voir )//FIXME si 'voir' on voit plus de chose ?
86
-		{
87
-			$sql.=' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.')
85
+        if (! $this->user->rights->societe->client->voir )//FIXME si 'voir' on voit plus de chose ?
86
+        {
87
+            $sql.=' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.')
88 88
 					LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = sc.fk_soc)
89 89
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.fk_soc = sc.fk_soc AND sp.rowid = a.fk_contact)
90 90
 					LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_cdav AS ac ON (a.id = ac.fk_object)';
91
-		}
92
-		else
93
-		{
94
-			$sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = a.fk_soc)
91
+        }
92
+        else
93
+        {
94
+            $sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = a.fk_soc)
95 95
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.rowid = a.fk_contact)
96 96
 					LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_cdav AS ac ON (a.id = ac.fk_object)';
97
-		}
97
+        }
98 98
 
99
-		$sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co ON co.rowid = sp.fk_pays
99
+        $sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co ON co.rowid = sp.fk_pays
100 100
 				LEFT JOIN '.MAIN_DB_PREFIX.'c_country as cos ON cos.rowid = s.fk_pays
101 101
 				WHERE 	a.id IN (SELECT ar.fk_actioncomm FROM '.MAIN_DB_PREFIX.'actioncomm_resources ar WHERE ar.element_type=\'user\' AND ar.fk_element='.intval($calid).')
102 102
 						AND a.code IN (SELECT cac.code FROM '.MAIN_DB_PREFIX.'c_actioncomm cac WHERE cac.type<>\'systemauto\')
103 103
 						AND a.entity IN ('.getEntity('societe', 1).')';
104
-		if($oid!==false) {
105
-			if($ouri===false)
106
-			{
107
-				$sql.=' AND a.id = '.intval($oid);
108
-			}
109
-			else
110
-			{
111
-				$sql.=' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')';
112
-			}
113
-		}
104
+        if($oid!==false) {
105
+            if($ouri===false)
106
+            {
107
+                $sql.=' AND a.id = '.intval($oid);
108
+            }
109
+            else
110
+            {
111
+                $sql.=' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')';
112
+            }
113
+        }
114 114
 
115
-		return $sql;
116
-	}
115
+        return $sql;
116
+    }
117 117
 
118
-	/**
119
-	 * Convert calendar row to VCalendar string
120
-	 *
121
-	 * @param 	int		$calid		Calendar id
122
-	 * @param	Object	$obj		Object id
123
-	 * @return string
124
-	 */
125
-	public function toVCalendar($calid, $obj)
126
-	{
127
-		/*$categ = array();
118
+    /**
119
+     * Convert calendar row to VCalendar string
120
+     *
121
+     * @param 	int		$calid		Calendar id
122
+     * @param	Object	$obj		Object id
123
+     * @return string
124
+     */
125
+    public function toVCalendar($calid, $obj)
126
+    {
127
+        /*$categ = array();
128 128
 		if($obj->soc_client)
129 129
 		{
130 130
 			$nick[] = $obj->soc_code_client;
131 131
 			$categ[] = $this->langs->transnoentitiesnoconv('Customer');
132 132
 		}*/
133 133
 
134
-		$location=$obj->location;
134
+        $location=$obj->location;
135 135
 
136
-		// contact address
137
-		if(empty($location) && !empty($obj->address))
138
-		{
139
-			$location = trim(str_replace(array("\r","\t","\n"),' ', $obj->address));
140
-			$location = trim($location.', '.$obj->zip);
141
-			$location = trim($location.' '.$obj->town);
142
-			$location = trim($location.', '.$obj->country_label);
143
-		}
136
+        // contact address
137
+        if(empty($location) && !empty($obj->address))
138
+        {
139
+            $location = trim(str_replace(array("\r","\t","\n"),' ', $obj->address));
140
+            $location = trim($location.', '.$obj->zip);
141
+            $location = trim($location.' '.$obj->town);
142
+            $location = trim($location.', '.$obj->country_label);
143
+        }
144 144
 
145
-		// contact address
146
-		if(empty($location) && !empty($obj->soc_address))
147
-		{
148
-			$location = trim(str_replace(array("\r","\t","\n"),' ', $obj->soc_address));
149
-			$location = trim($location.', '.$obj->soc_zip);
150
-			$location = trim($location.' '.$obj->soc_town);
151
-			$location = trim($location.', '.$obj->soc_country_label);
152
-		}
145
+        // contact address
146
+        if(empty($location) && !empty($obj->soc_address))
147
+        {
148
+            $location = trim(str_replace(array("\r","\t","\n"),' ', $obj->soc_address));
149
+            $location = trim($location.', '.$obj->soc_zip);
150
+            $location = trim($location.' '.$obj->soc_town);
151
+            $location = trim($location.', '.$obj->soc_country_label);
152
+        }
153 153
 
154
-		$address=explode("\n",$obj->address,2);
155
-		foreach($address as $kAddr => $vAddr)
156
-		{
157
-			$address[$kAddr] = trim(str_replace(array("\r","\t"),' ', str_replace("\n",' | ', trim($vAddr))));
158
-		}
159
-		$address[]='';
160
-		$address[]='';
154
+        $address=explode("\n",$obj->address,2);
155
+        foreach($address as $kAddr => $vAddr)
156
+        {
157
+            $address[$kAddr] = trim(str_replace(array("\r","\t"),' ', str_replace("\n",' | ', trim($vAddr))));
158
+        }
159
+        $address[]='';
160
+        $address[]='';
161 161
 
162
-		if($obj->percent==-1 && trim($obj->datep)!='')
163
-			$type='VEVENT';
164
-		else
165
-			$type='VTODO';
162
+        if($obj->percent==-1 && trim($obj->datep)!='')
163
+            $type='VEVENT';
164
+        else
165
+            $type='VTODO';
166 166
 
167
-		$timezone = date_default_timezone_get();
167
+        $timezone = date_default_timezone_get();
168 168
 
169
-		$caldata ="BEGIN:VCALENDAR\n";
170
-		$caldata.="VERSION:2.0\n";
171
-		$caldata.="METHOD:PUBLISH\n";
172
-		$caldata.="PRODID:-//Dolibarr CDav//FR\n";
173
-		$caldata.="BEGIN:".$type."\n";
174
-		$caldata.="CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n";
175
-		$caldata.="LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
176
-		$caldata.="DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
177
-		if($obj->sourceuid=='')
178
-			$caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
179
-		else
180
-			$caldata.="UID:".$obj->sourceuid."\n";
181
-		$caldata.="SUMMARY:".$obj->label."\n";
182
-		$caldata.="LOCATION:".$location."\n";
183
-		$caldata.="PRIORITY:".$obj->priority."\n";
184
-		if($obj->fulldayevent)
185
-		{
186
-			$caldata.="DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n";
187
-			if($type=='VEVENT')
188
-			{
189
-				if(trim($obj->datep2)!='')
190
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
191
-				else
192
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep)+(25*3600))."\n";
193
-			}
194
-			elseif(trim($obj->datep2)!='')
195
-				$caldata.="DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
196
-		}
197
-		else
198
-		{
199
-			$caldata.="DTSTART;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
200
-			if($type=='VEVENT')
201
-			{
202
-				if(trim($obj->datep2)!='')
203
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
204
-				else
205
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
206
-			}
207
-			elseif(trim($obj->datep2)!='')
208
-				$caldata.="DUE;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
209
-		}
210
-		$caldata.="CLASS:PUBLIC\n";
211
-		if($obj->transparency==1)
212
-			$caldata.="TRANSP:TRANSPARENT\n";
213
-		else
214
-			$caldata.="TRANSP:OPAQUE\n";
169
+        $caldata ="BEGIN:VCALENDAR\n";
170
+        $caldata.="VERSION:2.0\n";
171
+        $caldata.="METHOD:PUBLISH\n";
172
+        $caldata.="PRODID:-//Dolibarr CDav//FR\n";
173
+        $caldata.="BEGIN:".$type."\n";
174
+        $caldata.="CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n";
175
+        $caldata.="LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
176
+        $caldata.="DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
177
+        if($obj->sourceuid=='')
178
+            $caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
179
+        else
180
+            $caldata.="UID:".$obj->sourceuid."\n";
181
+        $caldata.="SUMMARY:".$obj->label."\n";
182
+        $caldata.="LOCATION:".$location."\n";
183
+        $caldata.="PRIORITY:".$obj->priority."\n";
184
+        if($obj->fulldayevent)
185
+        {
186
+            $caldata.="DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n";
187
+            if($type=='VEVENT')
188
+            {
189
+                if(trim($obj->datep2)!='')
190
+                    $caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
191
+                else
192
+                    $caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep)+(25*3600))."\n";
193
+            }
194
+            elseif(trim($obj->datep2)!='')
195
+                $caldata.="DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
196
+        }
197
+        else
198
+        {
199
+            $caldata.="DTSTART;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
200
+            if($type=='VEVENT')
201
+            {
202
+                if(trim($obj->datep2)!='')
203
+                    $caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
204
+                else
205
+                    $caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
206
+            }
207
+            elseif(trim($obj->datep2)!='')
208
+                $caldata.="DUE;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
209
+        }
210
+        $caldata.="CLASS:PUBLIC\n";
211
+        if($obj->transparency==1)
212
+            $caldata.="TRANSP:TRANSPARENT\n";
213
+        else
214
+            $caldata.="TRANSP:OPAQUE\n";
215 215
 
216
-		if($type=='VEVENT')
217
-			$caldata.="STATUS:CONFIRMED\n";
218
-		elseif($obj->percent==0)
219
-			$caldata.="STATUS:NEEDS-ACTION\n";
220
-		elseif($obj->percent==100)
221
-			$caldata.="STATUS:COMPLETED\n";
222
-		else
223
-		{
224
-			$caldata.="STATUS:IN-PROCESS\n";
225
-			$caldata.="PERCENT-COMPLETE:".$obj->percent."\n";
226
-		}
216
+        if($type=='VEVENT')
217
+            $caldata.="STATUS:CONFIRMED\n";
218
+        elseif($obj->percent==0)
219
+            $caldata.="STATUS:NEEDS-ACTION\n";
220
+        elseif($obj->percent==100)
221
+            $caldata.="STATUS:COMPLETED\n";
222
+        else
223
+        {
224
+            $caldata.="STATUS:IN-PROCESS\n";
225
+            $caldata.="PERCENT-COMPLETE:".$obj->percent."\n";
226
+        }
227 227
 
228
-		$caldata.="DESCRIPTION:";
229
-		$caldata.=strtr($obj->note, array("\n"=>"\\n", "\r"=>""));
230
-		if(!empty($obj->soc_nom))
231
-			$caldata.="\\n*DOLIBARR-SOC: ".$obj->soc_nom;
232
-		if(!empty($obj->soc_phone))
233
-			$caldata.="\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
234
-		if(!empty($obj->firstname) || !empty($obj->lastname))
235
-			$caldata.="\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
236
-		if(!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile))
237
-			$caldata.="\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
238
-		if(strpos($obj->other_users,',')) // several
239
-			$caldata.="\\n*DOLIBARR-USR: ".$obj->other_users;
240
-		$caldata.="\n";
228
+        $caldata.="DESCRIPTION:";
229
+        $caldata.=strtr($obj->note, array("\n"=>"\\n", "\r"=>""));
230
+        if(!empty($obj->soc_nom))
231
+            $caldata.="\\n*DOLIBARR-SOC: ".$obj->soc_nom;
232
+        if(!empty($obj->soc_phone))
233
+            $caldata.="\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
234
+        if(!empty($obj->firstname) || !empty($obj->lastname))
235
+            $caldata.="\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
236
+        if(!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile))
237
+            $caldata.="\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
238
+        if(strpos($obj->other_users,',')) // several
239
+            $caldata.="\\n*DOLIBARR-USR: ".$obj->other_users;
240
+        $caldata.="\n";
241 241
 
242
-		$caldata.="END:".$type."\n";
243
-		$caldata.="END:VCALENDAR\n";
242
+        $caldata.="END:".$type."\n";
243
+        $caldata.="END:VCALENDAR\n";
244 244
 
245
-		return $caldata;
246
-	}
245
+        return $caldata;
246
+    }
247 247
 
248
-	/**
249
-	 * getFullCalendarObjects
250
-	 *
251
-	 * @param int	 	$calendarId			Calendar id
252
-	 * @param int		$bCalendarData		Add calendar data
253
-	 * @return array|string[][]
254
-	 */
255
-	public function getFullCalendarObjects($calendarId, $bCalendarData)
256
-	{
257
-		$calid = ($calendarId*1);
258
-		$calevents = array();
248
+    /**
249
+     * getFullCalendarObjects
250
+     *
251
+     * @param int	 	$calendarId			Calendar id
252
+     * @param int		$bCalendarData		Add calendar data
253
+     * @return array|string[][]
254
+     */
255
+    public function getFullCalendarObjects($calendarId, $bCalendarData)
256
+    {
257
+        $calid = ($calendarId*1);
258
+        $calevents = array();
259 259
 
260
-		if(! $this->user->rights->agenda->myactions->read)
261
-			return $calevents;
260
+        if(! $this->user->rights->agenda->myactions->read)
261
+            return $calevents;
262 262
 
263
-		if($calid!=$this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read))
264
-			return $calevents;
263
+        if($calid!=$this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read))
264
+            return $calevents;
265 265
 
266
-		$sql = $this->getSqlCalEvents($calid);
266
+        $sql = $this->getSqlCalEvents($calid);
267 267
 
268
-		$result = $this->db->query($sql);
268
+        $result = $this->db->query($sql);
269 269
 
270
-		if ($result)
271
-		{
272
-			while ($obj = $this->db->fetch_object($result))
273
-			{
274
-				$calendardata = $this->toVCalendar($calid, $obj);
270
+        if ($result)
271
+        {
272
+            while ($obj = $this->db->fetch_object($result))
273
+            {
274
+                $calendardata = $this->toVCalendar($calid, $obj);
275 275
 
276
-				if($bCalendarData)
277
-				{
278
-					$calevents[] = array(
279
-						'calendardata' => $calendardata,
280
-						'uri' => $obj->id.'-ev-'.CDAV_URI_KEY,
281
-						'lastmodified' => strtotime($obj->lastupd),
282
-						'etag' => '"'.md5($calendardata).'"',
283
-						'calendarid'   => $calendarId,
284
-						'size' => strlen($calendardata),
285
-						'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
286
-					);
287
-				}
288
-				else
289
-				{
290
-					$calevents[] = array(
291
-						// 'calendardata' => $calendardata,  not necessary because etag+size are present
292
-						'uri' => $obj->id.'-ev-'.CDAV_URI_KEY,
293
-						'lastmodified' => strtotime($obj->lastupd),
294
-						'etag' => '"'.md5($calendardata).'"',
295
-						'calendarid'   => $calendarId,
296
-						'size' => strlen($calendardata),
297
-						'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
298
-					);
299
-				}
300
-			}
301
-		}
302
-		return $calevents;
303
-	}
276
+                if($bCalendarData)
277
+                {
278
+                    $calevents[] = array(
279
+                        'calendardata' => $calendardata,
280
+                        'uri' => $obj->id.'-ev-'.CDAV_URI_KEY,
281
+                        'lastmodified' => strtotime($obj->lastupd),
282
+                        'etag' => '"'.md5($calendardata).'"',
283
+                        'calendarid'   => $calendarId,
284
+                        'size' => strlen($calendardata),
285
+                        'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
286
+                    );
287
+                }
288
+                else
289
+                {
290
+                    $calevents[] = array(
291
+                        // 'calendardata' => $calendardata,  not necessary because etag+size are present
292
+                        'uri' => $obj->id.'-ev-'.CDAV_URI_KEY,
293
+                        'lastmodified' => strtotime($obj->lastupd),
294
+                        'etag' => '"'.md5($calendardata).'"',
295
+                        'calendarid'   => $calendarId,
296
+                        'size' => strlen($calendardata),
297
+                        'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
298
+                    );
299
+                }
300
+            }
301
+        }
302
+        return $calevents;
303
+    }
304 304
 }
Please login to merge, or discard this patch.
Spacing   +84 added lines, -84 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 	 * @param	int|boolean	$ouri			Ouri
57 57
 	 * @return string
58 58
 	 */
59
-	public function getSqlCalEvents($calid, $oid=false, $ouri=false)
59
+	public function getSqlCalEvents($calid, $oid = false, $ouri = false)
60 60
 	{
61 61
 		// TODO : replace GROUP_CONCAT by
62 62
 		$sql = 'SELECT
@@ -82,33 +82,33 @@  discard block
 block discarded – undo
82 82
 						LEFT OUTER JOIN '.MAIN_DB_PREFIX.'user AS u ON (u.rowid=fk_element)
83 83
 						WHERE ar.element_type=\'user\' AND fk_actioncomm=a.id) AS other_users
84 84
 				FROM '.MAIN_DB_PREFIX.'actioncomm AS a';
85
-		if (! $this->user->rights->societe->client->voir )//FIXME si 'voir' on voit plus de chose ?
85
+		if (!$this->user->rights->societe->client->voir)//FIXME si 'voir' on voit plus de chose ?
86 86
 		{
87
-			$sql.=' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.')
87
+			$sql .= ' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.')
88 88
 					LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = sc.fk_soc)
89 89
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.fk_soc = sc.fk_soc AND sp.rowid = a.fk_contact)
90 90
 					LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_cdav AS ac ON (a.id = ac.fk_object)';
91 91
 		}
92 92
 		else
93 93
 		{
94
-			$sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = a.fk_soc)
94
+			$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = a.fk_soc)
95 95
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.rowid = a.fk_contact)
96 96
 					LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_cdav AS ac ON (a.id = ac.fk_object)';
97 97
 		}
98 98
 
99
-		$sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co ON co.rowid = sp.fk_pays
99
+		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as co ON co.rowid = sp.fk_pays
100 100
 				LEFT JOIN '.MAIN_DB_PREFIX.'c_country as cos ON cos.rowid = s.fk_pays
101 101
 				WHERE 	a.id IN (SELECT ar.fk_actioncomm FROM '.MAIN_DB_PREFIX.'actioncomm_resources ar WHERE ar.element_type=\'user\' AND ar.fk_element='.intval($calid).')
102 102
 						AND a.code IN (SELECT cac.code FROM '.MAIN_DB_PREFIX.'c_actioncomm cac WHERE cac.type<>\'systemauto\')
103 103
 						AND a.entity IN ('.getEntity('societe', 1).')';
104
-		if($oid!==false) {
105
-			if($ouri===false)
104
+		if ($oid !== false) {
105
+			if ($ouri === false)
106 106
 			{
107
-				$sql.=' AND a.id = '.intval($oid);
107
+				$sql .= ' AND a.id = '.intval($oid);
108 108
 			}
109 109
 			else
110 110
 			{
111
-				$sql.=' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')';
111
+				$sql .= ' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')';
112 112
 			}
113 113
 		}
114 114
 
@@ -131,116 +131,116 @@  discard block
 block discarded – undo
131 131
 			$categ[] = $this->langs->transnoentitiesnoconv('Customer');
132 132
 		}*/
133 133
 
134
-		$location=$obj->location;
134
+		$location = $obj->location;
135 135
 
136 136
 		// contact address
137
-		if(empty($location) && !empty($obj->address))
137
+		if (empty($location) && !empty($obj->address))
138 138
 		{
139
-			$location = trim(str_replace(array("\r","\t","\n"),' ', $obj->address));
139
+			$location = trim(str_replace(array("\r", "\t", "\n"), ' ', $obj->address));
140 140
 			$location = trim($location.', '.$obj->zip);
141 141
 			$location = trim($location.' '.$obj->town);
142 142
 			$location = trim($location.', '.$obj->country_label);
143 143
 		}
144 144
 
145 145
 		// contact address
146
-		if(empty($location) && !empty($obj->soc_address))
146
+		if (empty($location) && !empty($obj->soc_address))
147 147
 		{
148
-			$location = trim(str_replace(array("\r","\t","\n"),' ', $obj->soc_address));
148
+			$location = trim(str_replace(array("\r", "\t", "\n"), ' ', $obj->soc_address));
149 149
 			$location = trim($location.', '.$obj->soc_zip);
150 150
 			$location = trim($location.' '.$obj->soc_town);
151 151
 			$location = trim($location.', '.$obj->soc_country_label);
152 152
 		}
153 153
 
154
-		$address=explode("\n",$obj->address,2);
155
-		foreach($address as $kAddr => $vAddr)
154
+		$address = explode("\n", $obj->address, 2);
155
+		foreach ($address as $kAddr => $vAddr)
156 156
 		{
157
-			$address[$kAddr] = trim(str_replace(array("\r","\t"),' ', str_replace("\n",' | ', trim($vAddr))));
157
+			$address[$kAddr] = trim(str_replace(array("\r", "\t"), ' ', str_replace("\n", ' | ', trim($vAddr))));
158 158
 		}
159
-		$address[]='';
160
-		$address[]='';
159
+		$address[] = '';
160
+		$address[] = '';
161 161
 
162
-		if($obj->percent==-1 && trim($obj->datep)!='')
163
-			$type='VEVENT';
162
+		if ($obj->percent == -1 && trim($obj->datep) != '')
163
+			$type = 'VEVENT';
164 164
 		else
165
-			$type='VTODO';
165
+			$type = 'VTODO';
166 166
 
167 167
 		$timezone = date_default_timezone_get();
168 168
 
169
-		$caldata ="BEGIN:VCALENDAR\n";
170
-		$caldata.="VERSION:2.0\n";
171
-		$caldata.="METHOD:PUBLISH\n";
172
-		$caldata.="PRODID:-//Dolibarr CDav//FR\n";
173
-		$caldata.="BEGIN:".$type."\n";
174
-		$caldata.="CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n";
175
-		$caldata.="LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
176
-		$caldata.="DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
177
-		if($obj->sourceuid=='')
178
-			$caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
169
+		$caldata = "BEGIN:VCALENDAR\n";
170
+		$caldata .= "VERSION:2.0\n";
171
+		$caldata .= "METHOD:PUBLISH\n";
172
+		$caldata .= "PRODID:-//Dolibarr CDav//FR\n";
173
+		$caldata .= "BEGIN:".$type."\n";
174
+		$caldata .= "CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n";
175
+		$caldata .= "LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
176
+		$caldata .= "DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
177
+		if ($obj->sourceuid == '')
178
+			$caldata .= "UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
179 179
 		else
180
-			$caldata.="UID:".$obj->sourceuid."\n";
181
-		$caldata.="SUMMARY:".$obj->label."\n";
182
-		$caldata.="LOCATION:".$location."\n";
183
-		$caldata.="PRIORITY:".$obj->priority."\n";
184
-		if($obj->fulldayevent)
180
+			$caldata .= "UID:".$obj->sourceuid."\n";
181
+		$caldata .= "SUMMARY:".$obj->label."\n";
182
+		$caldata .= "LOCATION:".$location."\n";
183
+		$caldata .= "PRIORITY:".$obj->priority."\n";
184
+		if ($obj->fulldayevent)
185 185
 		{
186
-			$caldata.="DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n";
187
-			if($type=='VEVENT')
186
+			$caldata .= "DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n";
187
+			if ($type == 'VEVENT')
188 188
 			{
189
-				if(trim($obj->datep2)!='')
190
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
189
+				if (trim($obj->datep2) != '')
190
+					$caldata .= "DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2) + 1)."\n";
191 191
 				else
192
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep)+(25*3600))."\n";
192
+					$caldata .= "DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep) + (25 * 3600))."\n";
193 193
 			}
194
-			elseif(trim($obj->datep2)!='')
195
-				$caldata.="DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
194
+			elseif (trim($obj->datep2) != '')
195
+				$caldata .= "DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2) + 1)."\n";
196 196
 		}
197 197
 		else
198 198
 		{
199
-			$caldata.="DTSTART;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
200
-			if($type=='VEVENT')
199
+			$caldata .= "DTSTART;TZID=".$timezone.":".strtr($obj->datep, array(" "=>"T", ":"=>"", "-"=>""))."\n";
200
+			if ($type == 'VEVENT')
201 201
 			{
202
-				if(trim($obj->datep2)!='')
203
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
202
+				if (trim($obj->datep2) != '')
203
+					$caldata .= "DTEND;TZID=".$timezone.":".strtr($obj->datep2, array(" "=>"T", ":"=>"", "-"=>""))."\n";
204 204
 				else
205
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
205
+					$caldata .= "DTEND;TZID=".$timezone.":".strtr($obj->datep, array(" "=>"T", ":"=>"", "-"=>""))."\n";
206 206
 			}
207
-			elseif(trim($obj->datep2)!='')
208
-				$caldata.="DUE;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
207
+			elseif (trim($obj->datep2) != '')
208
+				$caldata .= "DUE;TZID=".$timezone.":".strtr($obj->datep2, array(" "=>"T", ":"=>"", "-"=>""))."\n";
209 209
 		}
210
-		$caldata.="CLASS:PUBLIC\n";
211
-		if($obj->transparency==1)
212
-			$caldata.="TRANSP:TRANSPARENT\n";
210
+		$caldata .= "CLASS:PUBLIC\n";
211
+		if ($obj->transparency == 1)
212
+			$caldata .= "TRANSP:TRANSPARENT\n";
213 213
 		else
214
-			$caldata.="TRANSP:OPAQUE\n";
214
+			$caldata .= "TRANSP:OPAQUE\n";
215 215
 
216
-		if($type=='VEVENT')
217
-			$caldata.="STATUS:CONFIRMED\n";
218
-		elseif($obj->percent==0)
219
-			$caldata.="STATUS:NEEDS-ACTION\n";
220
-		elseif($obj->percent==100)
221
-			$caldata.="STATUS:COMPLETED\n";
216
+		if ($type == 'VEVENT')
217
+			$caldata .= "STATUS:CONFIRMED\n";
218
+		elseif ($obj->percent == 0)
219
+			$caldata .= "STATUS:NEEDS-ACTION\n";
220
+		elseif ($obj->percent == 100)
221
+			$caldata .= "STATUS:COMPLETED\n";
222 222
 		else
223 223
 		{
224
-			$caldata.="STATUS:IN-PROCESS\n";
225
-			$caldata.="PERCENT-COMPLETE:".$obj->percent."\n";
224
+			$caldata .= "STATUS:IN-PROCESS\n";
225
+			$caldata .= "PERCENT-COMPLETE:".$obj->percent."\n";
226 226
 		}
227 227
 
228
-		$caldata.="DESCRIPTION:";
229
-		$caldata.=strtr($obj->note, array("\n"=>"\\n", "\r"=>""));
230
-		if(!empty($obj->soc_nom))
231
-			$caldata.="\\n*DOLIBARR-SOC: ".$obj->soc_nom;
232
-		if(!empty($obj->soc_phone))
233
-			$caldata.="\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
234
-		if(!empty($obj->firstname) || !empty($obj->lastname))
235
-			$caldata.="\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
236
-		if(!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile))
237
-			$caldata.="\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
238
-		if(strpos($obj->other_users,',')) // several
239
-			$caldata.="\\n*DOLIBARR-USR: ".$obj->other_users;
240
-		$caldata.="\n";
228
+		$caldata .= "DESCRIPTION:";
229
+		$caldata .= strtr($obj->note, array("\n"=>"\\n", "\r"=>""));
230
+		if (!empty($obj->soc_nom))
231
+			$caldata .= "\\n*DOLIBARR-SOC: ".$obj->soc_nom;
232
+		if (!empty($obj->soc_phone))
233
+			$caldata .= "\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
234
+		if (!empty($obj->firstname) || !empty($obj->lastname))
235
+			$caldata .= "\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
236
+		if (!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile))
237
+			$caldata .= "\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
238
+		if (strpos($obj->other_users, ',')) // several
239
+			$caldata .= "\\n*DOLIBARR-USR: ".$obj->other_users;
240
+		$caldata .= "\n";
241 241
 
242
-		$caldata.="END:".$type."\n";
243
-		$caldata.="END:VCALENDAR\n";
242
+		$caldata .= "END:".$type."\n";
243
+		$caldata .= "END:VCALENDAR\n";
244 244
 
245 245
 		return $caldata;
246 246
 	}
@@ -254,13 +254,13 @@  discard block
 block discarded – undo
254 254
 	 */
255 255
 	public function getFullCalendarObjects($calendarId, $bCalendarData)
256 256
 	{
257
-		$calid = ($calendarId*1);
257
+		$calid = ($calendarId * 1);
258 258
 		$calevents = array();
259 259
 
260
-		if(! $this->user->rights->agenda->myactions->read)
260
+		if (!$this->user->rights->agenda->myactions->read)
261 261
 			return $calevents;
262 262
 
263
-		if($calid!=$this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read))
263
+		if ($calid != $this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read))
264 264
 			return $calevents;
265 265
 
266 266
 		$sql = $this->getSqlCalEvents($calid);
@@ -273,7 +273,7 @@  discard block
 block discarded – undo
273 273
 			{
274 274
 				$calendardata = $this->toVCalendar($calid, $obj);
275 275
 
276
-				if($bCalendarData)
276
+				if ($bCalendarData)
277 277
 				{
278 278
 					$calevents[] = array(
279 279
 						'calendardata' => $calendardata,
@@ -282,7 +282,7 @@  discard block
 block discarded – undo
282 282
 						'etag' => '"'.md5($calendardata).'"',
283 283
 						'calendarid'   => $calendarId,
284 284
 						'size' => strlen($calendardata),
285
-						'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
285
+						'component' => strpos($calendardata, 'BEGIN:VEVENT') > 0 ? 'vevent' : 'vtodo',
286 286
 					);
287 287
 				}
288 288
 				else
@@ -294,7 +294,7 @@  discard block
 block discarded – undo
294 294
 						'etag' => '"'.md5($calendardata).'"',
295 295
 						'calendarid'   => $calendarId,
296 296
 						'size' => strlen($calendardata),
297
-						'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
297
+						'component' => strpos($calendardata, 'BEGIN:VEVENT') > 0 ? 'vevent' : 'vtodo',
298 298
 					);
299 299
 				}
300 300
 			}
Please login to merge, or discard this patch.
Braces   +63 added lines, -52 removed lines patch added patch discarded remove patch
@@ -82,14 +82,15 @@  discard block
 block discarded – undo
82 82
 						LEFT OUTER JOIN '.MAIN_DB_PREFIX.'user AS u ON (u.rowid=fk_element)
83 83
 						WHERE ar.element_type=\'user\' AND fk_actioncomm=a.id) AS other_users
84 84
 				FROM '.MAIN_DB_PREFIX.'actioncomm AS a';
85
-		if (! $this->user->rights->societe->client->voir )//FIXME si 'voir' on voit plus de chose ?
85
+		if (! $this->user->rights->societe->client->voir ) {
86
+		    //FIXME si 'voir' on voit plus de chose ?
86 87
 		{
87 88
 			$sql.=' LEFT OUTER JOIN '.MAIN_DB_PREFIX.'societe_commerciaux AS sc ON (a.fk_soc = sc.fk_soc AND sc.fk_user='.$this->user->id.')
88 89
 					LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = sc.fk_soc)
89 90
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.fk_soc = sc.fk_soc AND sp.rowid = a.fk_contact)
90 91
 					LEFT JOIN '.MAIN_DB_PREFIX.'actioncomm_cdav AS ac ON (a.id = ac.fk_object)';
91 92
 		}
92
-		else
93
+		} else
93 94
 		{
94 95
 			$sql.=' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON (s.rowid = a.fk_soc)
95 96
 					LEFT JOIN '.MAIN_DB_PREFIX.'socpeople AS sp ON (sp.rowid = a.fk_contact)
@@ -105,8 +106,7 @@  discard block
 block discarded – undo
105 106
 			if($ouri===false)
106 107
 			{
107 108
 				$sql.=' AND a.id = '.intval($oid);
108
-			}
109
-			else
109
+			} else
110 110
 			{
111 111
 				$sql.=' AND (a.id = '.intval($oid).' OR ac.uuidext = \''.$this->db->escape($ouri).'\')';
112 112
 			}
@@ -159,10 +159,11 @@  discard block
 block discarded – undo
159 159
 		$address[]='';
160 160
 		$address[]='';
161 161
 
162
-		if($obj->percent==-1 && trim($obj->datep)!='')
163
-			$type='VEVENT';
164
-		else
165
-			$type='VTODO';
162
+		if($obj->percent==-1 && trim($obj->datep)!='') {
163
+					$type='VEVENT';
164
+		} else {
165
+					$type='VTODO';
166
+		}
166 167
 
167 168
 		$timezone = date_default_timezone_get();
168 169
 
@@ -174,10 +175,11 @@  discard block
 block discarded – undo
174 175
 		$caldata.="CREATED:".gmdate('Ymd\THis', strtotime($obj->datec))."Z\n";
175 176
 		$caldata.="LAST-MODIFIED:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
176 177
 		$caldata.="DTSTAMP:".gmdate('Ymd\THis', strtotime($obj->lastupd))."Z\n";
177
-		if($obj->sourceuid=='')
178
-			$caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
179
-		else
180
-			$caldata.="UID:".$obj->sourceuid."\n";
178
+		if($obj->sourceuid=='') {
179
+					$caldata.="UID:".$obj->id.'-ev-'.$calid.'-cal-'.CDAV_URI_KEY."\n";
180
+		} else {
181
+					$caldata.="UID:".$obj->sourceuid."\n";
182
+		}
181 183
 		$caldata.="SUMMARY:".$obj->label."\n";
182 184
 		$caldata.="LOCATION:".$location."\n";
183 185
 		$caldata.="PRIORITY:".$obj->priority."\n";
@@ -186,40 +188,42 @@  discard block
 block discarded – undo
186 188
 			$caldata.="DTSTART;VALUE=DATE:".date('Ymd', strtotime($obj->datep))."\n";
187 189
 			if($type=='VEVENT')
188 190
 			{
189
-				if(trim($obj->datep2)!='')
190
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
191
-				else
192
-					$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep)+(25*3600))."\n";
191
+				if(trim($obj->datep2)!='') {
192
+									$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
193
+				} else {
194
+									$caldata.="DTEND;VALUE=DATE:".date('Ymd', strtotime($obj->datep)+(25*3600))."\n";
195
+				}
196
+			} elseif(trim($obj->datep2)!='') {
197
+							$caldata.="DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
193 198
 			}
194
-			elseif(trim($obj->datep2)!='')
195
-				$caldata.="DUE;VALUE=DATE:".date('Ymd', strtotime($obj->datep2)+1)."\n";
196
-		}
197
-		else
199
+		} else
198 200
 		{
199 201
 			$caldata.="DTSTART;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
200 202
 			if($type=='VEVENT')
201 203
 			{
202
-				if(trim($obj->datep2)!='')
203
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
204
-				else
205
-					$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
204
+				if(trim($obj->datep2)!='') {
205
+									$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
206
+				} else {
207
+									$caldata.="DTEND;TZID=".$timezone.":".strtr($obj->datep,array(" "=>"T", ":"=>"", "-"=>""))."\n";
208
+				}
209
+			} elseif(trim($obj->datep2)!='') {
210
+							$caldata.="DUE;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
206 211
 			}
207
-			elseif(trim($obj->datep2)!='')
208
-				$caldata.="DUE;TZID=".$timezone.":".strtr($obj->datep2,array(" "=>"T", ":"=>"", "-"=>""))."\n";
209 212
 		}
210 213
 		$caldata.="CLASS:PUBLIC\n";
211
-		if($obj->transparency==1)
212
-			$caldata.="TRANSP:TRANSPARENT\n";
213
-		else
214
-			$caldata.="TRANSP:OPAQUE\n";
214
+		if($obj->transparency==1) {
215
+					$caldata.="TRANSP:TRANSPARENT\n";
216
+		} else {
217
+					$caldata.="TRANSP:OPAQUE\n";
218
+		}
215 219
 
216
-		if($type=='VEVENT')
217
-			$caldata.="STATUS:CONFIRMED\n";
218
-		elseif($obj->percent==0)
219
-			$caldata.="STATUS:NEEDS-ACTION\n";
220
-		elseif($obj->percent==100)
221
-			$caldata.="STATUS:COMPLETED\n";
222
-		else
220
+		if($type=='VEVENT') {
221
+					$caldata.="STATUS:CONFIRMED\n";
222
+		} elseif($obj->percent==0) {
223
+					$caldata.="STATUS:NEEDS-ACTION\n";
224
+		} elseif($obj->percent==100) {
225
+					$caldata.="STATUS:COMPLETED\n";
226
+		} else
223 227
 		{
224 228
 			$caldata.="STATUS:IN-PROCESS\n";
225 229
 			$caldata.="PERCENT-COMPLETE:".$obj->percent."\n";
@@ -227,16 +231,22 @@  discard block
 block discarded – undo
227 231
 
228 232
 		$caldata.="DESCRIPTION:";
229 233
 		$caldata.=strtr($obj->note, array("\n"=>"\\n", "\r"=>""));
230
-		if(!empty($obj->soc_nom))
231
-			$caldata.="\\n*DOLIBARR-SOC: ".$obj->soc_nom;
232
-		if(!empty($obj->soc_phone))
233
-			$caldata.="\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
234
-		if(!empty($obj->firstname) || !empty($obj->lastname))
235
-			$caldata.="\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
236
-		if(!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile))
237
-			$caldata.="\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
238
-		if(strpos($obj->other_users,',')) // several
234
+		if(!empty($obj->soc_nom)) {
235
+					$caldata.="\\n*DOLIBARR-SOC: ".$obj->soc_nom;
236
+		}
237
+		if(!empty($obj->soc_phone)) {
238
+					$caldata.="\\n*DOLIBARR-SOC-TEL: ".$obj->soc_phone;
239
+		}
240
+		if(!empty($obj->firstname) || !empty($obj->lastname)) {
241
+					$caldata.="\\n*DOLIBARR-CTC: ".trim($obj->firstname.' '.$obj->lastname);
242
+		}
243
+		if(!empty($obj->phone) || !empty($obj->phone_perso) || !empty($obj->phone_mobile)) {
244
+					$caldata.="\\n*DOLIBARR-CTC-TEL: ".trim($obj->phone.' '.$obj->phone_perso.' '.$obj->phone_mobile);
245
+		}
246
+		if(strpos($obj->other_users,',')) {
247
+		    // several
239 248
 			$caldata.="\\n*DOLIBARR-USR: ".$obj->other_users;
249
+		}
240 250
 		$caldata.="\n";
241 251
 
242 252
 		$caldata.="END:".$type."\n";
@@ -257,11 +267,13 @@  discard block
 block discarded – undo
257 267
 		$calid = ($calendarId*1);
258 268
 		$calevents = array();
259 269
 
260
-		if(! $this->user->rights->agenda->myactions->read)
261
-			return $calevents;
270
+		if(! $this->user->rights->agenda->myactions->read) {
271
+					return $calevents;
272
+		}
262 273
 
263
-		if($calid!=$this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read))
264
-			return $calevents;
274
+		if($calid!=$this->user->id && (!isset($this->user->rights->agenda->allactions->read) || !$this->user->rights->agenda->allactions->read)) {
275
+					return $calevents;
276
+		}
265 277
 
266 278
 		$sql = $this->getSqlCalEvents($calid);
267 279
 
@@ -284,8 +296,7 @@  discard block
 block discarded – undo
284 296
 						'size' => strlen($calendardata),
285 297
 						'component' => strpos($calendardata, 'BEGIN:VEVENT')>0 ? 'vevent' : 'vtodo',
286 298
 					);
287
-				}
288
-				else
299
+				} else
289 300
 				{
290 301
 					$calevents[] = array(
291 302
 						// 'calendardata' => $calendardata,  not necessary because etag+size are present
Please login to merge, or discard this patch.
dolibarr/htdocs/dav/dav.lib.php 3 patches
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -24,19 +24,19 @@  discard block
 block discarded – undo
24 24
 // define CDAV_CONTACT_TAG if not
25 25
 if(!defined('CDAV_CONTACT_TAG'))
26 26
 {
27
-	if(isset($conf->global->CDAV_CONTACT_TAG))
28
-		define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG);
29
-		else
30
-			define('CDAV_CONTACT_TAG', '');
27
+    if(isset($conf->global->CDAV_CONTACT_TAG))
28
+        define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG);
29
+        else
30
+            define('CDAV_CONTACT_TAG', '');
31 31
 }
32 32
 
33 33
 // define CDAV_URI_KEY if not
34 34
 if(!defined('CDAV_URI_KEY'))
35 35
 {
36
-	if(isset($conf->global->CDAV_URI_KEY))
37
-		define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY);
38
-		else
39
-			define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']),0,8));
36
+    if(isset($conf->global->CDAV_URI_KEY))
37
+        define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY);
38
+        else
39
+            define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']),0,8));
40 40
 }
41 41
 
42 42
 
@@ -49,24 +49,24 @@  discard block
 block discarded – undo
49 49
  */
50 50
 function dav_admin_prepare_head()
51 51
 {
52
-	global $db, $langs, $conf;
52
+    global $db, $langs, $conf;
53 53
 
54
-	$h = 0;
55
-	$head = array();
54
+    $h = 0;
55
+    $head = array();
56 56
 
57
-	$head[$h][0] = DOL_URL_ROOT.'/admin/dav.php?id='.$object->id;
58
-	$head[$h][1] = $langs->trans("WebDAV");
59
-	$head[$h][2] = 'webdav';
60
-	$h++;
57
+    $head[$h][0] = DOL_URL_ROOT.'/admin/dav.php?id='.$object->id;
58
+    $head[$h][1] = $langs->trans("WebDAV");
59
+    $head[$h][2] = 'webdav';
60
+    $h++;
61 61
 
62
-	// Show more tabs from modules
63
-	// Entries must be declared in modules descriptor with line
64
-	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
65
-	// $this->tabs = array('entity:-tabname);   												to remove a tab
66
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav');
62
+    // Show more tabs from modules
63
+    // Entries must be declared in modules descriptor with line
64
+    // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
65
+    // $this->tabs = array('entity:-tabname);   												to remove a tab
66
+    complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav');
67 67
 
68
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav','remove');
68
+    complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav','remove');
69 69
 
70
-	return $head;
70
+    return $head;
71 71
 }
72 72
 
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -22,21 +22,21 @@  discard block
 block discarded – undo
22 22
  */
23 23
 
24 24
 // define CDAV_CONTACT_TAG if not
25
-if(!defined('CDAV_CONTACT_TAG'))
25
+if (!defined('CDAV_CONTACT_TAG'))
26 26
 {
27
-	if(isset($conf->global->CDAV_CONTACT_TAG))
27
+	if (isset($conf->global->CDAV_CONTACT_TAG))
28 28
 		define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG);
29 29
 		else
30 30
 			define('CDAV_CONTACT_TAG', '');
31 31
 }
32 32
 
33 33
 // define CDAV_URI_KEY if not
34
-if(!defined('CDAV_URI_KEY'))
34
+if (!defined('CDAV_URI_KEY'))
35 35
 {
36
-	if(isset($conf->global->CDAV_URI_KEY))
36
+	if (isset($conf->global->CDAV_URI_KEY))
37 37
 		define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY);
38 38
 		else
39
-			define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']),0,8));
39
+			define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']), 0, 8));
40 40
 }
41 41
 
42 42
 
@@ -63,9 +63,9 @@  discard block
 block discarded – undo
63 63
 	// Entries must be declared in modules descriptor with line
64 64
 	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
65 65
 	// $this->tabs = array('entity:-tabname);   												to remove a tab
66
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav');
66
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'admindav');
67 67
 
68
-	complete_head_from_modules($conf,$langs,$object,$head,$h,'admindav','remove');
68
+	complete_head_from_modules($conf, $langs, $object, $head, $h, 'admindav', 'remove');
69 69
 
70 70
 	return $head;
71 71
 }
Please login to merge, or discard this patch.
Braces   +12 added lines, -10 removed lines patch added patch discarded remove patch
@@ -24,20 +24,22 @@
 block discarded – undo
24 24
 // define CDAV_CONTACT_TAG if not
25 25
 if(!defined('CDAV_CONTACT_TAG'))
26 26
 {
27
-	if(isset($conf->global->CDAV_CONTACT_TAG))
28
-		define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG);
29
-		else
30
-			define('CDAV_CONTACT_TAG', '');
31
-}
27
+	if(isset($conf->global->CDAV_CONTACT_TAG)) {
28
+			define('CDAV_CONTACT_TAG', $conf->global->CDAV_CONTACT_TAG);
29
+	} else {
30
+					define('CDAV_CONTACT_TAG', '');
31
+		}
32
+		}
32 33
 
33 34
 // define CDAV_URI_KEY if not
34 35
 if(!defined('CDAV_URI_KEY'))
35 36
 {
36
-	if(isset($conf->global->CDAV_URI_KEY))
37
-		define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY);
38
-		else
39
-			define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']),0,8));
40
-}
37
+	if(isset($conf->global->CDAV_URI_KEY)) {
38
+			define('CDAV_URI_KEY', $conf->global->CDAV_URI_KEY);
39
+	} else {
40
+					define('CDAV_URI_KEY', substr(md5($_SERVER['HTTP_HOST']),0,8));
41
+		}
42
+		}
41 43
 
42 44
 
43 45
 
Please login to merge, or discard this patch.
dolibarr/htdocs/dav/fileserver.php 3 patches
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -39,8 +39,8 @@  discard block
 block discarded – undo
39 39
 $user = new User($db);
40 40
 if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']!='')
41 41
 {
42
-	$user->fetch('',$_SERVER['PHP_AUTH_USER']);
43
-	$user->getrights();
42
+    $user->fetch('',$_SERVER['PHP_AUTH_USER']);
43
+    $user->getrights();
44 44
 }
45 45
 
46 46
 // Load translation files required by the page
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 
49 49
 
50 50
 if(empty($conf->dav->enabled))
51
-	accessforbidden();
51
+    accessforbidden();
52 52
 
53 53
 
54 54
 // settings
@@ -59,27 +59,27 @@  discard block
 block discarded – undo
59 59
 
60 60
 // Authentication callback function
61 61
 $authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $password) {
62
-	global $user;
63
-	global $conf;
64
-	global $dolibarr_main_authentication;
65
-
66
-	if (empty($user->login))
67
-		return false;
68
-	if ($user->socid > 0)
69
-		return false;
70
-	if ($user->login != $username)
71
-		return false;
72
-
73
-	// Authentication mode
74
-	if (empty($dolibarr_main_authentication))
75
-		$dolibarr_main_authentication='http,dolibarr';
76
-	$authmode = explode(',',$dolibarr_main_authentication);
77
-	$entity = (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
78
-
79
-	if (checkLoginPassEntity($username,$password,$entity,$authmode) != $username)
80
-		return false;
81
-
82
-	return true;
62
+    global $user;
63
+    global $conf;
64
+    global $dolibarr_main_authentication;
65
+
66
+    if (empty($user->login))
67
+        return false;
68
+    if ($user->socid > 0)
69
+        return false;
70
+    if ($user->login != $username)
71
+        return false;
72
+
73
+    // Authentication mode
74
+    if (empty($dolibarr_main_authentication))
75
+        $dolibarr_main_authentication='http,dolibarr';
76
+    $authmode = explode(',',$dolibarr_main_authentication);
77
+    $entity = (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
78
+
79
+    if (checkLoginPassEntity($username,$password,$entity,$authmode) != $username)
80
+        return false;
81
+
82
+    return true;
83 83
 });
84 84
 
85 85
 $authBackend->setRealm(constant('DOL_APPLICATION_TITLE'));
@@ -100,14 +100,14 @@  discard block
 block discarded – undo
100 100
 // Public dir
101 101
 if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR))
102 102
 {
103
-	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/dav/public');
103
+    $nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/dav/public');
104 104
 }
105 105
 // Private dir
106 106
 $nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/dav/private');
107 107
 // ECM dir
108 108
 if (! empty($conf->ecm->enabled) && ! empty($conf->global->DAV_ALLOW_ECM_DIR))
109 109
 {
110
-	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/ecm');
110
+    $nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/ecm');
111 111
 }
112 112
 
113 113
 
@@ -135,12 +135,12 @@  discard block
 block discarded – undo
135 135
 
136 136
 // Add authentication function
137 137
 if ((empty($conf->global->DAV_ALLOW_PUBLIC_DIR)
138
-	|| ! preg_match('/'.preg_quote(DOL_URL_ROOT.'/dav/fileserver.php/public','/').'/', $_SERVER["PHP_SELF"]))
139
-	&& ! preg_match('/^sabreAction=asset&assetName=[a-zA-Z0-9%\-\/]+\.(png|css|woff|ico|ttf)$/', $_SERVER["QUERY_STRING"])	// URL for Sabre browser resources
140
-	)
138
+    || ! preg_match('/'.preg_quote(DOL_URL_ROOT.'/dav/fileserver.php/public','/').'/', $_SERVER["PHP_SELF"]))
139
+    && ! preg_match('/^sabreAction=asset&assetName=[a-zA-Z0-9%\-\/]+\.(png|css|woff|ico|ttf)$/', $_SERVER["QUERY_STRING"])	// URL for Sabre browser resources
140
+    )
141 141
 {
142
-	//var_dump($_SERVER["QUERY_STRING"]);exit;
143
-	$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend));
142
+    //var_dump($_SERVER["QUERY_STRING"]);exit;
143
+    $server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend));
144 144
 }
145 145
 // Support for LOCK and UNLOCK
146 146
 $lockBackend = new \Sabre\DAV\Locks\Backend\File($tmpDir . '/.locksdb');
Please login to merge, or discard this patch.
Spacing   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -21,12 +21,12 @@  discard block
 block discarded – undo
21 21
  *      \brief      Server DAV
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1'); // If there is no menu to show
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOLOGIN'))  		 define("NOLOGIN",1);		// This means this output page does not require to be logged.
29
-if (! defined('NOCSRFCHECK'))  	 define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
24
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1');
25
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1'); // If there is no menu to show
26
+if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
27
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
28
+if (!defined('NOLOGIN'))  		 define("NOLOGIN", 1); // This means this output page does not require to be logged.
29
+if (!defined('NOCSRFCHECK'))  	 define("NOCSRFCHECK", 1); // We accept to go on this page from external web site.
30 30
 
31 31
 require "../main.inc.php";
32 32
 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
@@ -37,17 +37,17 @@  discard block
 block discarded – undo
37 37
 
38 38
 
39 39
 $user = new User($db);
40
-if(isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER']!='')
40
+if (isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != '')
41 41
 {
42
-	$user->fetch('',$_SERVER['PHP_AUTH_USER']);
42
+	$user->fetch('', $_SERVER['PHP_AUTH_USER']);
43 43
 	$user->getrights();
44 44
 }
45 45
 
46 46
 // Load translation files required by the page
47
-$langs->loadLangs(array("main","other"));
47
+$langs->loadLangs(array("main", "other"));
48 48
 
49 49
 
50
-if(empty($conf->dav->enabled))
50
+if (empty($conf->dav->enabled))
51 51
 	accessforbidden();
52 52
 
53 53
 
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 //var_dump($tmpDir);exit;
59 59
 
60 60
 // Authentication callback function
61
-$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $password) {
61
+$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function($username, $password) {
62 62
 	global $user;
63 63
 	global $conf;
64 64
 	global $dolibarr_main_authentication;
@@ -72,11 +72,11 @@  discard block
 block discarded – undo
72 72
 
73 73
 	// Authentication mode
74 74
 	if (empty($dolibarr_main_authentication))
75
-		$dolibarr_main_authentication='http,dolibarr';
76
-	$authmode = explode(',',$dolibarr_main_authentication);
77
-	$entity = (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
75
+		$dolibarr_main_authentication = 'http,dolibarr';
76
+	$authmode = explode(',', $dolibarr_main_authentication);
77
+	$entity = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1));
78 78
 
79
-	if (checkLoginPassEntity($username,$password,$entity,$authmode) != $username)
79
+	if (checkLoginPassEntity($username, $password, $entity, $authmode) != $username)
80 80
 		return false;
81 81
 
82 82
 	return true;
@@ -100,14 +100,14 @@  discard block
 block discarded – undo
100 100
 // Public dir
101 101
 if (!empty($conf->global->DAV_ALLOW_PUBLIC_DIR))
102 102
 {
103
-	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/dav/public');
103
+	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root.'/dav/public');
104 104
 }
105 105
 // Private dir
106
-$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/dav/private');
106
+$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root.'/dav/private');
107 107
 // ECM dir
108
-if (! empty($conf->ecm->enabled) && ! empty($conf->global->DAV_ALLOW_ECM_DIR))
108
+if (!empty($conf->ecm->enabled) && !empty($conf->global->DAV_ALLOW_ECM_DIR))
109 109
 {
110
-	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root. '/ecm');
110
+	$nodes[] = new \Sabre\DAV\FS\Directory($dolibarr_main_data_root.'/ecm');
111 111
 }
112 112
 
113 113
 
@@ -135,15 +135,15 @@  discard block
 block discarded – undo
135 135
 
136 136
 // Add authentication function
137 137
 if ((empty($conf->global->DAV_ALLOW_PUBLIC_DIR)
138
-	|| ! preg_match('/'.preg_quote(DOL_URL_ROOT.'/dav/fileserver.php/public','/').'/', $_SERVER["PHP_SELF"]))
139
-	&& ! preg_match('/^sabreAction=asset&assetName=[a-zA-Z0-9%\-\/]+\.(png|css|woff|ico|ttf)$/', $_SERVER["QUERY_STRING"])	// URL for Sabre browser resources
138
+	|| !preg_match('/'.preg_quote(DOL_URL_ROOT.'/dav/fileserver.php/public', '/').'/', $_SERVER["PHP_SELF"]))
139
+	&& !preg_match('/^sabreAction=asset&assetName=[a-zA-Z0-9%\-\/]+\.(png|css|woff|ico|ttf)$/', $_SERVER["QUERY_STRING"])	// URL for Sabre browser resources
140 140
 	)
141 141
 {
142 142
 	//var_dump($_SERVER["QUERY_STRING"]);exit;
143 143
 	$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend));
144 144
 }
145 145
 // Support for LOCK and UNLOCK
146
-$lockBackend = new \Sabre\DAV\Locks\Backend\File($tmpDir . '/.locksdb');
146
+$lockBackend = new \Sabre\DAV\Locks\Backend\File($tmpDir.'/.locksdb');
147 147
 $lockPlugin = new \Sabre\DAV\Locks\Plugin($lockBackend);
148 148
 $server->addPlugin($lockPlugin);
149 149
 
Please login to merge, or discard this patch.
Braces   +45 added lines, -19 removed lines patch added patch discarded remove patch
@@ -21,12 +21,28 @@  discard block
 block discarded – undo
21 21
  *      \brief      Server DAV
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1');
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1'); // If there is no menu to show
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOLOGIN'))  		 define("NOLOGIN",1);		// This means this output page does not require to be logged.
29
-if (! defined('NOCSRFCHECK'))  	 define("NOCSRFCHECK",1);	// We accept to go on this page from external web site.
24
+if (! defined('NOTOKENRENEWAL')) {
25
+    define('NOTOKENRENEWAL','1');
26
+}
27
+if (! defined('NOREQUIREMENU')) {
28
+    define('NOREQUIREMENU','1');
29
+}
30
+// If there is no menu to show
31
+if (! defined('NOREQUIREHTML')) {
32
+    define('NOREQUIREHTML','1');
33
+}
34
+// If we don't need to load the html.form.class.php
35
+if (! defined('NOREQUIREAJAX')) {
36
+    define('NOREQUIREAJAX','1');
37
+}
38
+if (! defined('NOLOGIN')) {
39
+    define("NOLOGIN",1);
40
+}
41
+// This means this output page does not require to be logged.
42
+if (! defined('NOCSRFCHECK')) {
43
+    define("NOCSRFCHECK",1);
44
+}
45
+// We accept to go on this page from external web site.
30 46
 
31 47
 require "../main.inc.php";
32 48
 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
@@ -47,8 +63,9 @@  discard block
 block discarded – undo
47 63
 $langs->loadLangs(array("main","other"));
48 64
 
49 65
 
50
-if(empty($conf->dav->enabled))
66
+if(empty($conf->dav->enabled)) {
51 67
 	accessforbidden();
68
+}
52 69
 
53 70
 
54 71
 // settings
@@ -63,21 +80,26 @@  discard block
 block discarded – undo
63 80
 	global $conf;
64 81
 	global $dolibarr_main_authentication;
65 82
 
66
-	if (empty($user->login))
67
-		return false;
68
-	if ($user->socid > 0)
69
-		return false;
70
-	if ($user->login != $username)
71
-		return false;
83
+	if (empty($user->login)) {
84
+			return false;
85
+	}
86
+	if ($user->socid > 0) {
87
+			return false;
88
+	}
89
+	if ($user->login != $username) {
90
+			return false;
91
+	}
72 92
 
73 93
 	// Authentication mode
74
-	if (empty($dolibarr_main_authentication))
75
-		$dolibarr_main_authentication='http,dolibarr';
94
+	if (empty($dolibarr_main_authentication)) {
95
+			$dolibarr_main_authentication='http,dolibarr';
96
+	}
76 97
 	$authmode = explode(',',$dolibarr_main_authentication);
77 98
 	$entity = (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
78 99
 
79
-	if (checkLoginPassEntity($username,$password,$entity,$authmode) != $username)
80
-		return false;
100
+	if (checkLoginPassEntity($username,$password,$entity,$authmode) != $username) {
101
+			return false;
102
+	}
81 103
 
82 104
 	return true;
83 105
 });
@@ -131,7 +153,9 @@  discard block
 block discarded – undo
131 153
 // If you want to run the SabreDAV server in a custom location (using mod_rewrite for instance)
132 154
 // You can override the baseUri here.
133 155
 $baseUri = DOL_URL_ROOT.'/dav/fileserver.php/';
134
-if (isset($baseUri)) $server->setBaseUri($baseUri);
156
+if (isset($baseUri)) {
157
+    $server->setBaseUri($baseUri);
158
+}
135 159
 
136 160
 // Add authentication function
137 161
 if ((empty($conf->global->DAV_ALLOW_PUBLIC_DIR)
@@ -166,4 +190,6 @@  discard block
 block discarded – undo
166 190
 // And off we go!
167 191
 $server->exec();
168 192
 
169
-if (is_object($db)) $db->close();
193
+if (is_object($db)) {
194
+    $db->close();
195
+}
Please login to merge, or discard this patch.
dolibarr/htdocs/main.inc.php 3 patches
Indentation   +1481 added lines, -1481 removed lines patch added patch discarded remove patch
@@ -38,34 +38,34 @@  discard block
 block discarded – undo
38 38
 $micro_start_time = 0;
39 39
 if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
40 40
 {
41
-	list($usec, $sec) = explode(" ", microtime());
42
-	$micro_start_time=((float) $usec + (float) $sec);
43
-	// Add Xdebug code coverage
44
-	//define('XDEBUGCOVERAGE',1);
45
-	if (defined('XDEBUGCOVERAGE')) {
46
-		xdebug_start_code_coverage();
47
-	}
41
+    list($usec, $sec) = explode(" ", microtime());
42
+    $micro_start_time=((float) $usec + (float) $sec);
43
+    // Add Xdebug code coverage
44
+    //define('XDEBUGCOVERAGE',1);
45
+    if (defined('XDEBUGCOVERAGE')) {
46
+        xdebug_start_code_coverage();
47
+    }
48 48
 }
49 49
 
50 50
 // Removed magic_quotes
51 51
 if (function_exists('get_magic_quotes_gpc'))	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
52 52
 {
53
-	if (get_magic_quotes_gpc())
54
-	{
55
-		// Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
-		// (Otherwise he would have for each position, condition
57
-		// Reading stripslashes variable according to state get_magic_quotes_gpc).
58
-		// Off mode recommended (just do $db->escape for insert / update).
59
-		function stripslashes_deep($value)
60
-		{
61
-			return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
-		}
63
-		$_GET     = array_map('stripslashes_deep', $_GET);
64
-		$_POST    = array_map('stripslashes_deep', $_POST);
65
-		$_FILES   = array_map('stripslashes_deep', $_FILES);
66
-		//$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
-		@set_magic_quotes_runtime(0);
68
-	}
53
+    if (get_magic_quotes_gpc())
54
+    {
55
+        // Forcing parameter setting magic_quotes_gpc and cleaning parameters
56
+        // (Otherwise he would have for each position, condition
57
+        // Reading stripslashes variable according to state get_magic_quotes_gpc).
58
+        // Off mode recommended (just do $db->escape for insert / update).
59
+        function stripslashes_deep($value)
60
+        {
61
+            return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
62
+        }
63
+        $_GET     = array_map('stripslashes_deep', $_GET);
64
+        $_POST    = array_map('stripslashes_deep', $_POST);
65
+        $_FILES   = array_map('stripslashes_deep', $_FILES);
66
+        //$_COOKIE  = array_map('stripslashes_deep', $_COOKIE); // Useless because a cookie should never be outputed on screen nor used into sql
67
+        @set_magic_quotes_runtime(0);
68
+    }
69 69
 }
70 70
 
71 71
 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -93,58 +93,58 @@  discard block
 block discarded – undo
93 93
  */
94 94
 function testSqlAndScriptInject($val, $type)
95 95
 {
96
-	$inj = 0;
97
-	// For SQL Injection (only GET are used to be included into bad escaped SQL requests)
98
-	if ($type == 1 || $type == 3)
99
-	{
100
-		$inj += preg_match('/delete\s+from/i',	 $val);
101
-		$inj += preg_match('/create\s+table/i',	 $val);
102
-		$inj += preg_match('/insert\s+into/i', 	 $val);
103
-		$inj += preg_match('/select\s+from/i', 	 $val);
104
-		$inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
105
-		$inj += preg_match('/user\s*\(/i',  $val);						// avoid to use function user() that return current database login
106
-		$inj += preg_match('/information_schema/i',  $val);				// avoid to use request that read information_schema database
107
-	}
108
-	if ($type == 3)
109
-	{
110
-		$inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
111
-	}
112
-	if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
113
-	{
114
-		$inj += preg_match('/updatexml\(/i', 	 $val);
115
-		$inj += preg_match('/update.+set.+=/i',  $val);
116
-		$inj += preg_match('/union.+select/i', 	 $val);
117
-		$inj += preg_match('/(\.\.%2f)+/i',		 $val);
118
-	}
119
-	// For XSS Injection done by adding javascript with script
120
-	// This is all cases a browser consider text is javascript:
121
-	// When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
122
-	// All examples on page: http://ha.ckers.org/xss.html#XSScalc
123
-	// More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
124
-	$inj += preg_match('/<script/i', $val);
125
-	$inj += preg_match('/<iframe/i', $val);
126
-	$inj += preg_match('/<audio/i', $val);
127
-	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
-	if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
129
-	$inj += preg_match('/base[\s]+href/si', $val);
130
-	$inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
-	$inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
-	$inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
-	$inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
-	$inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
135
-	$inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
136
-	$inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
137
-	//$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
138
-	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
139
-	//if ($type == 1)
140
-	//{
141
-		$inj += preg_match('/javascript:/i', $val);
142
-		$inj += preg_match('/vbscript:/i', $val);
143
-	//}
144
-	// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
-	if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
-	if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
147
-	return $inj;
96
+    $inj = 0;
97
+    // For SQL Injection (only GET are used to be included into bad escaped SQL requests)
98
+    if ($type == 1 || $type == 3)
99
+    {
100
+        $inj += preg_match('/delete\s+from/i',	 $val);
101
+        $inj += preg_match('/create\s+table/i',	 $val);
102
+        $inj += preg_match('/insert\s+into/i', 	 $val);
103
+        $inj += preg_match('/select\s+from/i', 	 $val);
104
+        $inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
105
+        $inj += preg_match('/user\s*\(/i',  $val);						// avoid to use function user() that return current database login
106
+        $inj += preg_match('/information_schema/i',  $val);				// avoid to use request that read information_schema database
107
+    }
108
+    if ($type == 3)
109
+    {
110
+        $inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
111
+    }
112
+    if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
113
+    {
114
+        $inj += preg_match('/updatexml\(/i', 	 $val);
115
+        $inj += preg_match('/update.+set.+=/i',  $val);
116
+        $inj += preg_match('/union.+select/i', 	 $val);
117
+        $inj += preg_match('/(\.\.%2f)+/i',		 $val);
118
+    }
119
+    // For XSS Injection done by adding javascript with script
120
+    // This is all cases a browser consider text is javascript:
121
+    // When it found '<script', 'javascript:', '<style', 'onload\s=' on body tag, '="&' on a tag size with old browsers
122
+    // All examples on page: http://ha.ckers.org/xss.html#XSScalc
123
+    // More on https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
124
+    $inj += preg_match('/<script/i', $val);
125
+    $inj += preg_match('/<iframe/i', $val);
126
+    $inj += preg_match('/<audio/i', $val);
127
+    $inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
+    if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
129
+    $inj += preg_match('/base[\s]+href/si', $val);
130
+    $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
+    $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
+    $inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
+    $inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
+    $inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
135
+    $inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
136
+    $inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
137
+    //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
138
+    $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
139
+    //if ($type == 1)
140
+    //{
141
+        $inj += preg_match('/javascript:/i', $val);
142
+        $inj += preg_match('/vbscript:/i', $val);
143
+    //}
144
+    // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
+    if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
+    if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
147
+    return $inj;
148 148
 }
149 149
 
150 150
 /**
@@ -156,58 +156,58 @@  discard block
 block discarded – undo
156 156
  */
157 157
 function analyseVarsForSqlAndScriptsInjection(&$var, $type)
158 158
 {
159
-	if (is_array($var))
160
-	{
161
-		foreach ($var as $key => $value)	// Warning, $key may also be used for attacks
162
-		{
163
-			if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))
164
-			{
165
-				//$var[$key] = $value;	// This is useless
166
-			}
167
-			else
168
-			{
169
-				print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
170
-				exit;
171
-			}
172
-		}
173
-		return true;
174
-	}
175
-	else
176
-	{
177
-		return (testSqlAndScriptInject($var, $type) <= 0);
178
-	}
159
+    if (is_array($var))
160
+    {
161
+        foreach ($var as $key => $value)	// Warning, $key may also be used for attacks
162
+        {
163
+            if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))
164
+            {
165
+                //$var[$key] = $value;	// This is useless
166
+            }
167
+            else
168
+            {
169
+                print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
170
+                exit;
171
+            }
172
+        }
173
+        return true;
174
+    }
175
+    else
176
+    {
177
+        return (testSqlAndScriptInject($var, $type) <= 0);
178
+    }
179 179
 }
180 180
 
181 181
 
182 182
 // Check consistency of NOREQUIREXXX DEFINES
183 183
 if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU'))
184 184
 {
185
-	print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
186
-	exit;
185
+    print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
186
+    exit;
187 187
 }
188 188
 
189 189
 // Sanity check on URL
190 190
 if (! empty($_SERVER["PHP_SELF"]))
191 191
 {
192
-	$morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
193
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
192
+    $morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
193
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
194 194
 }
195 195
 // Sanity check on GET parameters
196 196
 if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"]))
197 197
 {
198
-	$morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
199
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
198
+    $morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
199
+    analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
200 200
 }
201 201
 // Sanity check on POST
202 202
 if (! defined('NOSCANPOSTFORINJECTION'))
203 203
 {
204
-	analyseVarsForSqlAndScriptsInjection($_POST,0);
204
+    analyseVarsForSqlAndScriptsInjection($_POST,0);
205 205
 }
206 206
 
207 207
 // This is to make Dolibarr working with Plesk
208 208
 if (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
209 209
 {
210
-	set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
210
+    set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
211 211
 }
212 212
 
213 213
 // Include the conf.php and functions.lib.php
@@ -218,20 +218,20 @@  discard block
 block discarded – undo
218 218
 // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and  cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
219 219
 if (! empty($_POST["DOL_AUTOSET_COOKIE"]))
220 220
 {
221
-	$tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
222
-	$tmplist=explode(',',$tmpautoset[1]);
223
-	$cookiearrayvalue=array();
224
-	foreach ($tmplist as $tmpkey)
225
-	{
226
-		$postkey=$tmpautoset[0].'_'.$tmpkey;
227
-		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
229
-	}
230
-	$cookiename=$tmpautoset[0];
231
-	$cookievalue=json_encode($cookiearrayvalue);
232
-	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233
-	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
234
-	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
221
+    $tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
222
+    $tmplist=explode(',',$tmpautoset[1]);
223
+    $cookiearrayvalue=array();
224
+    foreach ($tmplist as $tmpkey)
225
+    {
226
+        $postkey=$tmpautoset[0].'_'.$tmpkey;
227
+        //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
+        if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
229
+    }
230
+    $cookiename=$tmpautoset[0];
231
+    $cookievalue=json_encode($cookiearrayvalue);
232
+    //var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233
+    setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
234
+    if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
235 235
 }
236 236
 
237 237
 
@@ -248,8 +248,8 @@  discard block
 block discarded – undo
248 248
 // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
249 249
 if (! defined('NOSESSION'))
250 250
 {
251
-	session_start();
252
-	/*if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
251
+    session_start();
252
+    /*if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
253 253
 	{
254 254
 		foreach ($_SESSION as $key=>$value)
255 255
 		{
@@ -267,72 +267,72 @@  discard block
 block discarded – undo
267 267
 // Detection browser
268 268
 if (isset($_SERVER["HTTP_USER_AGENT"]))
269 269
 {
270
-	$tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
-	$conf->browser->name=$tmp['browsername'];
272
-	$conf->browser->os=$tmp['browseros'];
273
-	$conf->browser->version=$tmp['browserversion'];
274
-	$conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
275
-	//var_dump($conf->browser);
276
-
277
-	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
-	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
270
+    $tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
+    $conf->browser->name=$tmp['browsername'];
272
+    $conf->browser->os=$tmp['browseros'];
273
+    $conf->browser->version=$tmp['browserversion'];
274
+    $conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
275
+    //var_dump($conf->browser);
276
+
277
+    if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
+    if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
279 279
 }
280 280
 
281 281
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
282 282
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
283 283
 if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
284 284
 {
285
-	$newurl='';
286
-	if (is_numeric($conf->file->main_force_https))
287
-	{
288
-		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
289
-		{
290
-			if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
291
-			{
292
-				$newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
293
-			}
294
-		}
295
-		else	// Check HTTPS environment variable (Apache/mod_ssl only)
296
-		{
297
-			$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298
-		}
299
-	}
300
-	else
301
-	{
302
-		// Check HTTPS environment variable (Apache/mod_ssl only)
303
-		$newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
304
-	}
305
-	// Start redirect
306
-	if ($newurl)
307
-	{
308
-		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
309
-		header("Location: ".$newurl);
310
-		exit;
311
-	}
312
-	else
313
-	{
314
-		dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
315
-	}
285
+    $newurl='';
286
+    if (is_numeric($conf->file->main_force_https))
287
+    {
288
+        if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
289
+        {
290
+            if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
291
+            {
292
+                $newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
293
+            }
294
+        }
295
+        else	// Check HTTPS environment variable (Apache/mod_ssl only)
296
+        {
297
+            $newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298
+        }
299
+    }
300
+    else
301
+    {
302
+        // Check HTTPS environment variable (Apache/mod_ssl only)
303
+        $newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
304
+    }
305
+    // Start redirect
306
+    if ($newurl)
307
+    {
308
+        dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
309
+        header("Location: ".$newurl);
310
+        exit;
311
+    }
312
+    else
313
+    {
314
+        dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
315
+    }
316 316
 }
317 317
 
318 318
 if (! defined('NOLOGIN') && ! defined('NOIPCHECK') && ! empty($dolibarr_main_restrict_ip))
319 319
 {
320
-	$listofip=explode(',', $dolibarr_main_restrict_ip);
321
-	$found = false;
322
-	foreach($listofip as $ip)
323
-	{
324
-		$ip=trim($ip);
325
-		if ($ip == $_SERVER['REMOTE_ADDR'])
326
-		{
327
-			$found = true;
328
-			break;
329
-		}
330
-	}
331
-	if (! $found)
332
-	{
333
-		print 'Access refused by IP protection';
334
-		exit;
335
-	}
320
+    $listofip=explode(',', $dolibarr_main_restrict_ip);
321
+    $found = false;
322
+    foreach($listofip as $ip)
323
+    {
324
+        $ip=trim($ip);
325
+        if ($ip == $_SERVER['REMOTE_ADDR'])
326
+        {
327
+            $found = true;
328
+            break;
329
+        }
330
+    }
331
+    if (! $found)
332
+    {
333
+        print 'Access refused by IP protection';
334
+        exit;
335
+    }
336 336
 }
337 337
 
338 338
 // Loading of additional presentation includes
@@ -342,75 +342,75 @@  discard block
 block discarded – undo
342 342
 // If install or upgrade process not done or not completely finished, we call the install page.
343 343
 if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
344 344
 {
345
-	dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
346
-	header("Location: ".DOL_URL_ROOT."/install/index.php");
347
-	exit;
345
+    dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
346
+    header("Location: ".DOL_URL_ROOT."/install/index.php");
347
+    exit;
348 348
 }
349 349
 // If an upgrade process is required, we call the install page.
350 350
 if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
351 351
 || (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
352 352
 {
353
-	$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
354
-	require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
355
-	$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356
-	$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357
-	$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
358
-	if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359
-	{
360
-		dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
361
-		header("Location: ".DOL_URL_ROOT."/install/index.php");
362
-		exit;
363
-	}
353
+    $versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
354
+    require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
355
+    $dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356
+    $dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357
+    $rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
358
+    if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359
+    {
360
+        dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
361
+        header("Location: ".DOL_URL_ROOT."/install/index.php");
362
+        exit;
363
+    }
364 364
 }
365 365
 
366 366
 // Creation of a token against CSRF vulnerabilities
367 367
 if (! defined('NOTOKENRENEWAL'))
368 368
 {
369
-	// roulement des jetons car cree a chaque appel
370
-	if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
369
+    // roulement des jetons car cree a chaque appel
370
+    if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
371 371
 
372
-	// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
373
-	$token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374
-	$_SESSION['newtoken'] = $token;
372
+    // Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
373
+    $token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374
+    $_SESSION['newtoken'] = $token;
375 375
 }
376 376
 if ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
377
-	|| defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
377
+    || defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
378 378
 {
379
-	if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
380
-	{
381
-		print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
382
-		print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
383
-		die;
384
-	}
385
-	if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
386
-	{
387
-		if (GETPOST('token', 'alpha') != $_SESSION['token'])
388
-		{
389
-			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
390
-			//print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391
-			unset($_POST);
392
-		}
393
-	}
379
+    if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
380
+    {
381
+        print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
382
+        print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
383
+        die;
384
+    }
385
+    if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
386
+    {
387
+        if (GETPOST('token', 'alpha') != $_SESSION['token'])
388
+        {
389
+            dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
390
+            //print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391
+            unset($_POST);
392
+        }
393
+    }
394 394
 }
395 395
 
396 396
 // Disable modules (this must be after session_start and after conf has been loaded)
397 397
 if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
398 398
 if (! empty($_SESSION["disablemodules"]))
399 399
 {
400
-	$disabled_modules=explode(',',$_SESSION["disablemodules"]);
401
-	foreach($disabled_modules as $module)
402
-	{
403
-		if ($module)
404
-		{
405
-			if (empty($conf->$module)) $conf->$module=new stdClass();
406
-			$conf->$module->enabled=false;
407
-			if ($module == 'fournisseur')		// Special case
408
-			{
409
-				$conf->supplier_order->enabled=0;
410
-				$conf->supplier_invoice->enabled=0;
411
-			}
412
-		}
413
-	}
400
+    $disabled_modules=explode(',',$_SESSION["disablemodules"]);
401
+    foreach($disabled_modules as $module)
402
+    {
403
+        if ($module)
404
+        {
405
+            if (empty($conf->$module)) $conf->$module=new stdClass();
406
+            $conf->$module->enabled=false;
407
+            if ($module == 'fournisseur')		// Special case
408
+            {
409
+                $conf->supplier_order->enabled=0;
410
+                $conf->supplier_invoice->enabled=0;
411
+            }
412
+        }
413
+    }
414 414
 }
415 415
 
416 416
 /*
@@ -419,481 +419,481 @@  discard block
 block discarded – undo
419 419
 $login='';
420 420
 if (! defined('NOLOGIN'))
421 421
 {
422
-	// $authmode lists the different means of identification to be tested in order of preference.
423
-	// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
422
+    // $authmode lists the different means of identification to be tested in order of preference.
423
+    // Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
424 424
 
425
-	if (defined('MAIN_AUTHENTICATION_MODE'))
426
-	{
427
-		$dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
428
-	}
429
-	else
430
-	{
431
-		// Authentication mode
432
-		if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
433
-		// Authentication mode: forceuser
434
-		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
435
-	}
436
-	// Set authmode
437
-	$authmode=explode(',',$dolibarr_main_authentication);
438
-
439
-	// No authentication mode
440
-	if (! count($authmode))
441
-	{
442
-		$langs->load('main');
443
-		dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
444
-		exit;
445
-	}
446
-
447
-	// If login request was already post, we retrieve login from the session
448
-	// Call module if not realized that his request.
449
-	// At the end of this phase, the variable $login is defined.
450
-	$resultFetchUser='';
451
-	$test=true;
452
-	if (! isset($_SESSION["dol_login"]))
453
-	{
454
-		// It is not already authenticated and it requests the login / password
455
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
456
-
457
-		$dol_dst_observed=GETPOST("dst_observed",'int',3);
458
-		$dol_dst_first=GETPOST("dst_first",'int',3);
459
-		$dol_dst_second=GETPOST("dst_second",'int',3);
460
-		$dol_screenwidth=GETPOST("screenwidth",'int',3);
461
-		$dol_screenheight=GETPOST("screenheight",'int',3);
462
-		$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
463
-		$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
464
-		$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
465
-		$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
466
-		$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
467
-		//dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468
-
469
-		// If in demo mode, we check we go to home page through the public/demo/index.php page
470
-		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
471
-		{
472
-			if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
473
-			{
474
-				dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
475
-				$url='';
476
-				$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477
-				$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
478
-				$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
479
-				$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
480
-				$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
481
-				$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
482
-				header("Location: ".$url);
483
-				exit;
484
-			}
485
-		}
425
+    if (defined('MAIN_AUTHENTICATION_MODE'))
426
+    {
427
+        $dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
428
+    }
429
+    else
430
+    {
431
+        // Authentication mode
432
+        if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
433
+        // Authentication mode: forceuser
434
+        if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
435
+    }
436
+    // Set authmode
437
+    $authmode=explode(',',$dolibarr_main_authentication);
438
+
439
+    // No authentication mode
440
+    if (! count($authmode))
441
+    {
442
+        $langs->load('main');
443
+        dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
444
+        exit;
445
+    }
486 446
 
487
-		// Verification security graphic code
488
-		if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
489
-		{
490
-			$sessionkey = 'dol_antispam_value';
491
-			$ok=(array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
492
-
493
-			// Check code
494
-			if (! $ok)
495
-			{
496
-				dol_syslog('Bad value for code, connexion refused');
497
-				// Load translation files required by page
498
-				$langs->loadLangs(array('main', 'errors'));
499
-
500
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
501
-				$test=false;
502
-
503
-				// Call trigger for the "security events" log
504
-				$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
505
-				// Call of triggers
506
-				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
507
-				$interface=new Interfaces($db);
508
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
509
-				if ($result < 0) {
510
-					$error++;
511
-				}
512
-				// End Call of triggers
513
-
514
-				// Hooks on failed login
515
-				$action='';
516
-				$hookmanager->initHooks(array('login'));
517
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
519
-				if ($reshook < 0) $error++;
520
-
521
-				// Note: exit is done later
522
-			}
523
-		}
447
+    // If login request was already post, we retrieve login from the session
448
+    // Call module if not realized that his request.
449
+    // At the end of this phase, the variable $login is defined.
450
+    $resultFetchUser='';
451
+    $test=true;
452
+    if (! isset($_SESSION["dol_login"]))
453
+    {
454
+        // It is not already authenticated and it requests the login / password
455
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
456
+
457
+        $dol_dst_observed=GETPOST("dst_observed",'int',3);
458
+        $dol_dst_first=GETPOST("dst_first",'int',3);
459
+        $dol_dst_second=GETPOST("dst_second",'int',3);
460
+        $dol_screenwidth=GETPOST("screenwidth",'int',3);
461
+        $dol_screenheight=GETPOST("screenheight",'int',3);
462
+        $dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
463
+        $dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
464
+        $dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
465
+        $dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
466
+        $dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
467
+        //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468
+
469
+        // If in demo mode, we check we go to home page through the public/demo/index.php page
470
+        if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
471
+        {
472
+            if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
473
+            {
474
+                dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
475
+                $url='';
476
+                $url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477
+                $url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
478
+                $url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
479
+                $url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
480
+                $url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
481
+                $url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
482
+                header("Location: ".$url);
483
+                exit;
484
+            }
485
+        }
524 486
 
525
-		$allowedmethodtopostusername = 2;
526
-		if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
527
-		$usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528
-		$passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529
-		$entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
487
+        // Verification security graphic code
488
+        if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
489
+        {
490
+            $sessionkey = 'dol_antispam_value';
491
+            $ok=(array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
530 492
 
531
-		// Define if we received data to test the login.
532
-		$goontestloop=false;
533
-		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
-		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
-		if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
493
+            // Check code
494
+            if (! $ok)
495
+            {
496
+                dol_syslog('Bad value for code, connexion refused');
497
+                // Load translation files required by page
498
+                $langs->loadLangs(array('main', 'errors'));
499
+
500
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
501
+                $test=false;
502
+
503
+                // Call trigger for the "security events" log
504
+                $user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
505
+                // Call of triggers
506
+                include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
507
+                $interface=new Interfaces($db);
508
+                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
509
+                if ($result < 0) {
510
+                    $error++;
511
+                }
512
+                // End Call of triggers
536 513
 
537
-		if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538
-		{
539
-			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
540
-			$langs=new Translate("",$conf);
541
-			$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
-			if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
543
-			$langs->setDefaultLang($langcode);
544
-		}
514
+                // Hooks on failed login
515
+                $action='';
516
+                $hookmanager->initHooks(array('login'));
517
+                $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
+                $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
519
+                if ($reshook < 0) $error++;
545 520
 
546
-		// Validation of login/pass/entity
547
-		// If ok, the variable login will be returned
548
-		// If error, we will put error message in session under the name dol_loginmesg
549
-		if ($test && $goontestloop)
550
-		{
551
-			$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
552
-			if ($login)
553
-			{
554
-				$dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
555
-				$dol_tz=$_POST["tz"];
556
-				$dol_tz_string=$_POST["tz_string"];
557
-				$dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
558
-				$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
559
-				$dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
560
-				$dol_dst=0;
561
-				if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
562
-				{
563
-					include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
564
-					$datenow=dol_now();
565
-					$datefirst=dol_stringtotime($_POST["dst_first"]);
566
-					$datesecond=dol_stringtotime($_POST["dst_second"]);
567
-					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
568
-				}
569
-				//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570
-			}
571
-
572
-			if (! $login)
573
-			{
574
-				dol_syslog('Bad password, connexion refused',LOG_DEBUG);
575
-				// Load translation files required by page
576
-				$langs->loadLangs(array('main', 'errors'));
577
-
578
-				// Bad password. No authmode has found a good password.
579
-				// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
-				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
581
-
582
-				// Call trigger for the "security events" log
583
-				$user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
584
-				// Call of triggers
585
-				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
586
-				$interface=new Interfaces($db);
587
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
588
-				if ($result < 0) {
589
-					$error++;
590
-				}
591
-				// End Call of triggers
592
-
593
-				// Hooks on failed login
594
-				$action='';
595
-				$hookmanager->initHooks(array('login'));
596
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
598
-				if ($reshook < 0) $error++;
599
-
600
-				// Note: exit is done in next chapter
601
-			}
602
-		}
521
+                // Note: exit is done later
522
+            }
523
+        }
603 524
 
604
-		// End test login / passwords
605
-		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606
-		{
607
-			// No data to test login, so we show the login page
608
-			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609
-			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
-			else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
611
-			exit;
612
-		}
525
+        $allowedmethodtopostusername = 2;
526
+        if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
527
+        $usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528
+        $passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529
+        $entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
613 530
 
614
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
615
-		if ($resultFetchUser <= 0)
616
-		{
617
-			dol_syslog('User not found, connexion refused');
618
-			session_destroy();
619
-			session_name($sessionname);
620
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
621
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
622
-
623
-			if ($resultFetchUser == 0)
624
-			{
625
-				// Load translation files required by page
626
-				$langs->loadLangs(array('main', 'errors'));
627
-
628
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
629
-
630
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
631
-			}
632
-			if ($resultFetchUser < 0)
633
-			{
634
-				$_SESSION["dol_loginmesg"]=$user->error;
635
-
636
-				$user->trigger_mesg=$user->error;
637
-			}
638
-
639
-			// Call triggers for the "security events" log
640
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
641
-			$interface=new Interfaces($db);
642
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
643
-			if ($result < 0) {
644
-				$error++;
645
-			}
646
-			// End call triggers
647
-
648
-			// Hooks on failed login
649
-			$action='';
650
-			$hookmanager->initHooks(array('login'));
651
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
653
-			if ($reshook < 0) $error++;
654
-
655
-			$paramsurl=array();
656
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
659
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
660
-			exit;
661
-		}
662
-	}
663
-	else
664
-	{
665
-		// We are already into an authenticated session
666
-		$login=$_SESSION["dol_login"];
667
-		$entity=$_SESSION["dol_entity"];
668
-		dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
531
+        // Define if we received data to test the login.
532
+        $goontestloop=false;
533
+        if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
+        if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
+        if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
669 536
 
670
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
671
-		if ($resultFetchUser <= 0)
672
-		{
673
-			// Account has been removed after login
674
-			dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
675
-			session_destroy();
676
-			session_name($sessionname);
677
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
678
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
679
-
680
-			if ($resultFetchUser == 0)
681
-			{
682
-				// Load translation files required by page
683
-				$langs->loadLangs(array('main', 'errors'));
684
-
685
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
686
-
687
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
688
-			}
689
-			if ($resultFetchUser < 0)
690
-			{
691
-				$_SESSION["dol_loginmesg"]=$user->error;
692
-
693
-				$user->trigger_mesg=$user->error;
694
-			}
695
-
696
-			// Call triggers for the "security events" log
697
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
698
-			$interface=new Interfaces($db);
699
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
700
-			if ($result < 0) {
701
-				$error++;
702
-			}
703
-			// End call triggers
704
-
705
-			// Hooks on failed login
706
-			$action='';
707
-			$hookmanager->initHooks(array('login'));
708
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
710
-			if ($reshook < 0) $error++;
711
-
712
-			$paramsurl=array();
713
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
716
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
717
-			exit;
718
-		}
719
-		else
720
-		{
721
-		    // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
722
-		    $hookmanager->initHooks(array('main'));
723
-
724
-		    // Code for search criteria persistence.
725
-		    if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
726
-		    {
727
-			    $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
728
-			    $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
729
-			    // Clean $relativepathstring
730
-   			    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
731
-			    $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732
-			    $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733
-			    //var_dump($relativepathstring);
734
-
735
-			    // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
736
-			    if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
737
-			    {
738
-			    	$_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
739
-				    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
740
-			    }
741
-			    if (! empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
742
-			    {
743
-			    	$_SESSION['lastsearch_contextpage_'.$relativepathstring]=$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
744
-			    	unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
745
-			    }
746
-			    if (! empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
747
-			    {
748
-			    	$_SESSION['lastsearch_page_'.$relativepathstring]=$_SESSION['lastsearch_page_tmp_'.$relativepathstring];
749
-			    	unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
750
-			    }
751
-			    if (! empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
752
-			    {
753
-			    	$_SESSION['lastsearch_limit_'.$relativepathstring]=$_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
754
-			    	unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
755
-			    }
756
-		    }
757
-
758
-		    $action = '';
759
-		    $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
760
-		    if ($reshook < 0) {
761
-			    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
762
-		    }
763
-		}
764
-	}
537
+        if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538
+        {
539
+            include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
540
+            $langs=new Translate("",$conf);
541
+            $langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
+            if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
543
+            $langs->setDefaultLang($langcode);
544
+        }
765 545
 
766
-	// Is it a new session that has started ?
767
-	// If we are here, this means authentication was successfull.
768
-	if (! isset($_SESSION["dol_login"]))
769
-	{
770
-		// New session for this login has started.
771
-		$error=0;
772
-
773
-		// Store value into session (values always stored)
774
-		$_SESSION["dol_login"]=$user->login;
775
-		$_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
776
-		$_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
777
-		$_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
778
-		$_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
779
-		$_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
780
-		$_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
781
-		$_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
782
-		$_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
783
-		$_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
784
-		$_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785
-		$_SESSION["dol_entity"]=$conf->entity;
786
-		// Store value into session (values stored only if defined)
787
-		if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
-		if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
-		if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
-		if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
-		if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
792
-
793
-		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794
-
795
-		$db->begin();
796
-
797
-		$user->update_last_login_date();
798
-
799
-		$loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
800
-
801
-		// Call triggers for the "security events" log
802
-		$user->trigger_mesg = $loginfo;
803
-		// Call triggers
804
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
805
-		$interface=new Interfaces($db);
806
-		$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
807
-		if ($result < 0) {
808
-			$error++;
809
-		}
810
-		// End call triggers
546
+        // Validation of login/pass/entity
547
+        // If ok, the variable login will be returned
548
+        // If error, we will put error message in session under the name dol_loginmesg
549
+        if ($test && $goontestloop)
550
+        {
551
+            $login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
552
+            if ($login)
553
+            {
554
+                $dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
555
+                $dol_tz=$_POST["tz"];
556
+                $dol_tz_string=$_POST["tz_string"];
557
+                $dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
558
+                $dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
559
+                $dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
560
+                $dol_dst=0;
561
+                if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
562
+                {
563
+                    include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
564
+                    $datenow=dol_now();
565
+                    $datefirst=dol_stringtotime($_POST["dst_first"]);
566
+                    $datesecond=dol_stringtotime($_POST["dst_second"]);
567
+                    if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
568
+                }
569
+                //print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570
+            }
811 571
 
812
-		// Hooks on successfull login
813
-		$action='';
814
-		$hookmanager->initHooks(array('login'));
815
-		$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
-		$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
817
-		if ($reshook < 0) $error++;
572
+            if (! $login)
573
+            {
574
+                dol_syslog('Bad password, connexion refused',LOG_DEBUG);
575
+                // Load translation files required by page
576
+                $langs->loadLangs(array('main', 'errors'));
577
+
578
+                // Bad password. No authmode has found a good password.
579
+                // We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
+                if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
581
+
582
+                // Call trigger for the "security events" log
583
+                $user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
584
+                // Call of triggers
585
+                include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
586
+                $interface=new Interfaces($db);
587
+                $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
588
+                if ($result < 0) {
589
+                    $error++;
590
+                }
591
+                // End Call of triggers
818 592
 
819
-		if ($error)
820
-		{
821
-			$db->rollback();
822
-			session_destroy();
823
-			dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824
-			exit;
825
-		}
826
-		else
827
-		{
828
-			$db->commit();
829
-		}
593
+                // Hooks on failed login
594
+                $action='';
595
+                $hookmanager->initHooks(array('login'));
596
+                $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
+                $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
598
+                if ($reshook < 0) $error++;
830 599
 
831
-		// Change landing page if defined.
832
-		$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
-		if (! empty($landingpage))    // Example: /index.php
834
-		{
835
-			$newpath=dol_buildpath($landingpage, 1);
836
-			if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
837
-			{
838
-				header('Location: '.$newpath);
839
-				exit;
840
-			}
841
-		}
842
-	}
600
+                // Note: exit is done in next chapter
601
+            }
602
+        }
603
+
604
+        // End test login / passwords
605
+        if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606
+        {
607
+            // No data to test login, so we show the login page
608
+            dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609
+            if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
+            else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
611
+            exit;
612
+        }
843 613
 
614
+        $resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
615
+        if ($resultFetchUser <= 0)
616
+        {
617
+            dol_syslog('User not found, connexion refused');
618
+            session_destroy();
619
+            session_name($sessionname);
620
+            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
621
+            session_start();    // Fixing the bug of register_globals here is useless since session is empty
844 622
 
845
-	// If user admin, we force the rights-based modules
846
-	if ($user->admin)
847
-	{
848
-		$user->rights->user->user->lire=1;
849
-		$user->rights->user->user->creer=1;
850
-		$user->rights->user->user->password=1;
851
-		$user->rights->user->user->supprimer=1;
852
-		$user->rights->user->self->creer=1;
853
-		$user->rights->user->self->password=1;
854
-	}
855
-
856
-	/*
623
+            if ($resultFetchUser == 0)
624
+            {
625
+                // Load translation files required by page
626
+                $langs->loadLangs(array('main', 'errors'));
627
+
628
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
629
+
630
+                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
631
+            }
632
+            if ($resultFetchUser < 0)
633
+            {
634
+                $_SESSION["dol_loginmesg"]=$user->error;
635
+
636
+                $user->trigger_mesg=$user->error;
637
+            }
638
+
639
+            // Call triggers for the "security events" log
640
+            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
641
+            $interface=new Interfaces($db);
642
+            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
643
+            if ($result < 0) {
644
+                $error++;
645
+            }
646
+            // End call triggers
647
+
648
+            // Hooks on failed login
649
+            $action='';
650
+            $hookmanager->initHooks(array('login'));
651
+            $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
+            $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
653
+            if ($reshook < 0) $error++;
654
+
655
+            $paramsurl=array();
656
+            if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
+            if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
+            if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
659
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
660
+            exit;
661
+        }
662
+    }
663
+    else
664
+    {
665
+        // We are already into an authenticated session
666
+        $login=$_SESSION["dol_login"];
667
+        $entity=$_SESSION["dol_entity"];
668
+        dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
669
+
670
+        $resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
671
+        if ($resultFetchUser <= 0)
672
+        {
673
+            // Account has been removed after login
674
+            dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
675
+            session_destroy();
676
+            session_name($sessionname);
677
+            session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
678
+            session_start();    // Fixing the bug of register_globals here is useless since session is empty
679
+
680
+            if ($resultFetchUser == 0)
681
+            {
682
+                // Load translation files required by page
683
+                $langs->loadLangs(array('main', 'errors'));
684
+
685
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
686
+
687
+                $user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
688
+            }
689
+            if ($resultFetchUser < 0)
690
+            {
691
+                $_SESSION["dol_loginmesg"]=$user->error;
692
+
693
+                $user->trigger_mesg=$user->error;
694
+            }
695
+
696
+            // Call triggers for the "security events" log
697
+            include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
698
+            $interface=new Interfaces($db);
699
+            $result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
700
+            if ($result < 0) {
701
+                $error++;
702
+            }
703
+            // End call triggers
704
+
705
+            // Hooks on failed login
706
+            $action='';
707
+            $hookmanager->initHooks(array('login'));
708
+            $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
+            $reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
710
+            if ($reshook < 0) $error++;
711
+
712
+            $paramsurl=array();
713
+            if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
+            if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
+            if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
716
+            header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
717
+            exit;
718
+        }
719
+        else
720
+        {
721
+            // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
722
+            $hookmanager->initHooks(array('main'));
723
+
724
+            // Code for search criteria persistence.
725
+            if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
726
+            {
727
+                $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
728
+                $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
729
+                // Clean $relativepathstring
730
+                    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
731
+                $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732
+                $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733
+                //var_dump($relativepathstring);
734
+
735
+                // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
736
+                if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
737
+                {
738
+                    $_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
739
+                    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
740
+                }
741
+                if (! empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
742
+                {
743
+                    $_SESSION['lastsearch_contextpage_'.$relativepathstring]=$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
744
+                    unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
745
+                }
746
+                if (! empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
747
+                {
748
+                    $_SESSION['lastsearch_page_'.$relativepathstring]=$_SESSION['lastsearch_page_tmp_'.$relativepathstring];
749
+                    unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
750
+                }
751
+                if (! empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
752
+                {
753
+                    $_SESSION['lastsearch_limit_'.$relativepathstring]=$_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
754
+                    unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
755
+                }
756
+            }
757
+
758
+            $action = '';
759
+            $reshook = $hookmanager->executeHooks('updateSession', array(), $user, $action);
760
+            if ($reshook < 0) {
761
+                setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
762
+            }
763
+        }
764
+    }
765
+
766
+    // Is it a new session that has started ?
767
+    // If we are here, this means authentication was successfull.
768
+    if (! isset($_SESSION["dol_login"]))
769
+    {
770
+        // New session for this login has started.
771
+        $error=0;
772
+
773
+        // Store value into session (values always stored)
774
+        $_SESSION["dol_login"]=$user->login;
775
+        $_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
776
+        $_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
777
+        $_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
778
+        $_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
779
+        $_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
780
+        $_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
781
+        $_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
782
+        $_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
783
+        $_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
784
+        $_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785
+        $_SESSION["dol_entity"]=$conf->entity;
786
+        // Store value into session (values stored only if defined)
787
+        if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
+        if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
+        if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
+        if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
+        if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
792
+
793
+        dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794
+
795
+        $db->begin();
796
+
797
+        $user->update_last_login_date();
798
+
799
+        $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
800
+
801
+        // Call triggers for the "security events" log
802
+        $user->trigger_mesg = $loginfo;
803
+        // Call triggers
804
+        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
805
+        $interface=new Interfaces($db);
806
+        $result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
807
+        if ($result < 0) {
808
+            $error++;
809
+        }
810
+        // End call triggers
811
+
812
+        // Hooks on successfull login
813
+        $action='';
814
+        $hookmanager->initHooks(array('login'));
815
+        $parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
+        $reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
817
+        if ($reshook < 0) $error++;
818
+
819
+        if ($error)
820
+        {
821
+            $db->rollback();
822
+            session_destroy();
823
+            dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824
+            exit;
825
+        }
826
+        else
827
+        {
828
+            $db->commit();
829
+        }
830
+
831
+        // Change landing page if defined.
832
+        $landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
+        if (! empty($landingpage))    // Example: /index.php
834
+        {
835
+            $newpath=dol_buildpath($landingpage, 1);
836
+            if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
837
+            {
838
+                header('Location: '.$newpath);
839
+                exit;
840
+            }
841
+        }
842
+    }
843
+
844
+
845
+    // If user admin, we force the rights-based modules
846
+    if ($user->admin)
847
+    {
848
+        $user->rights->user->user->lire=1;
849
+        $user->rights->user->user->creer=1;
850
+        $user->rights->user->user->password=1;
851
+        $user->rights->user->user->supprimer=1;
852
+        $user->rights->user->self->creer=1;
853
+        $user->rights->user->self->password=1;
854
+    }
855
+
856
+    /*
857 857
      * Overwrite some configs globals (try to avoid this and have code to use instead $user->conf->xxx)
858 858
      */
859 859
 
860
-	// Set liste_limit
861
-	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
-	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
860
+    // Set liste_limit
861
+    if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
+    if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
863 863
 
864
-	// Replace conf->css by personalized value if theme not forced
865
-	if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
866
-	{
867
-		$conf->theme=$user->conf->MAIN_THEME;
868
-		$conf->css  = "/theme/".$conf->theme."/style.css.php";
869
-	}
864
+    // Replace conf->css by personalized value if theme not forced
865
+    if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
866
+    {
867
+        $conf->theme=$user->conf->MAIN_THEME;
868
+        $conf->css  = "/theme/".$conf->theme."/style.css.php";
869
+    }
870 870
 }
871 871
 
872 872
 // Case forcing style from url
873 873
 if (GETPOST('theme','alpha'))
874 874
 {
875
-	$conf->theme=GETPOST('theme','alpha',1);
876
-	$conf->css  = "/theme/".$conf->theme."/style.css.php";
875
+    $conf->theme=GETPOST('theme','alpha',1);
876
+    $conf->css  = "/theme/".$conf->theme."/style.css.php";
877 877
 }
878 878
 
879 879
 
880 880
 // Set javascript option
881 881
 if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
882 882
 {
883
-	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884
-	{
885
-		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
886
-	}
883
+    if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884
+    {
885
+        $conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
886
+    }
887 887
 }
888 888
 else $conf->use_javascript_ajax=0;
889 889
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
890 890
 if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
891 891
 {
892
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
892
+    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
893 893
 }
894 894
 elseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
895 895
 {
896
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
896
+    $conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
897 897
 }
898 898
 
899 899
 // Set terminal output option according to conf->browser.
@@ -904,56 +904,56 @@  discard block
 block discarded – undo
904 904
 if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
905 905
 if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
906 906
 if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
907
-	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
-	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
907
+    || (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
+    || (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
909 909
 )
910 910
 {
911
-	$conf->dol_optimize_smallscreen=1;
911
+    $conf->dol_optimize_smallscreen=1;
912 912
 }
913 913
 // If we force to use jmobile, then we reenable javascript
914 914
 if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
915 915
 // Replace themes bugged with jmobile with eldy
916 916
 if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
917 917
 {
918
-	$conf->theme='eldy';
919
-	$conf->css  =  "/theme/".$conf->theme."/style.css.php";
918
+    $conf->theme='eldy';
919
+    $conf->css  =  "/theme/".$conf->theme."/style.css.php";
920 920
 }
921 921
 
922 922
 if (! defined('NOREQUIRETRAN'))
923 923
 {
924
-	if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
925
-	{
926
-		// If user has chosen its own language
927
-		if (! empty($user->conf->MAIN_LANG_DEFAULT))
928
-		{
929
-			// If different than current language
930
-			//print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
931
-			if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
932
-			{
933
-				$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
934
-			}
935
-		}
936
-	}
924
+    if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
925
+    {
926
+        // If user has chosen its own language
927
+        if (! empty($user->conf->MAIN_LANG_DEFAULT))
928
+        {
929
+            // If different than current language
930
+            //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
931
+            if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
932
+            {
933
+                $langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
934
+            }
935
+        }
936
+    }
937 937
 }
938 938
 
939 939
 if (! defined('NOLOGIN'))
940 940
 {
941
-	// If the login is not recovered, it is identified with an account that does not exist.
942
-	// Hacking attempt?
943
-	if (! $user->login) accessforbidden();
941
+    // If the login is not recovered, it is identified with an account that does not exist.
942
+    // Hacking attempt?
943
+    if (! $user->login) accessforbidden();
944
+
945
+    // Check if user is active
946
+    if ($user->statut < 1)
947
+    {
948
+        // If not active, we refuse the user
949
+        $langs->load("other");
950
+        dol_syslog("Authentification ko as login is disabled");
951
+        accessforbidden($langs->trans("ErrorLoginDisabled"));
952
+        exit;
953
+    }
944 954
 
945
-	// Check if user is active
946
-	if ($user->statut < 1)
947
-	{
948
-		// If not active, we refuse the user
949
-		$langs->load("other");
950
-		dol_syslog("Authentification ko as login is disabled");
951
-		accessforbidden($langs->trans("ErrorLoginDisabled"));
952
-		exit;
953
-	}
954
-
955
-	// Load permissions
956
-	$user->getrights();
955
+    // Load permissions
956
+    $user->getrights();
957 957
 }
958 958
 
959 959
 
@@ -964,8 +964,8 @@  discard block
 block discarded – undo
964 964
 // Load main languages files
965 965
 if (! defined('NOREQUIRETRAN'))
966 966
 {
967
-	// Load translation files required by page
968
-	$langs->loadLangs(array('main', 'dict'));
967
+    // Load translation files required by page
968
+    $langs->loadLangs(array('main', 'dict'));
969 969
 }
970 970
 
971 971
 // Define some constants used for style of arrays
@@ -982,27 +982,27 @@  discard block
 block discarded – undo
982 982
 // Constants used to defined number of lines in textarea
983 983
 if (empty($conf->browser->firefox))
984 984
 {
985
-	define('ROWS_1',1);
986
-	define('ROWS_2',2);
987
-	define('ROWS_3',3);
988
-	define('ROWS_4',4);
989
-	define('ROWS_5',5);
990
-	define('ROWS_6',6);
991
-	define('ROWS_7',7);
992
-	define('ROWS_8',8);
993
-	define('ROWS_9',9);
985
+    define('ROWS_1',1);
986
+    define('ROWS_2',2);
987
+    define('ROWS_3',3);
988
+    define('ROWS_4',4);
989
+    define('ROWS_5',5);
990
+    define('ROWS_6',6);
991
+    define('ROWS_7',7);
992
+    define('ROWS_8',8);
993
+    define('ROWS_9',9);
994 994
 }
995 995
 else
996 996
 {
997
-	define('ROWS_1',0);
998
-	define('ROWS_2',1);
999
-	define('ROWS_3',2);
1000
-	define('ROWS_4',3);
1001
-	define('ROWS_5',4);
1002
-	define('ROWS_6',5);
1003
-	define('ROWS_7',6);
1004
-	define('ROWS_8',7);
1005
-	define('ROWS_9',8);
997
+    define('ROWS_1',0);
998
+    define('ROWS_2',1);
999
+    define('ROWS_3',2);
1000
+    define('ROWS_4',3);
1001
+    define('ROWS_5',4);
1002
+    define('ROWS_6',5);
1003
+    define('ROWS_7',6);
1004
+    define('ROWS_8',7);
1005
+    define('ROWS_9',8);
1006 1006
 }
1007 1007
 
1008 1008
 $heightforframes=50;
@@ -1010,36 +1010,36 @@  discard block
 block discarded – undo
1010 1010
 // Init menu manager
1011 1011
 if (! defined('NOREQUIREMENU'))
1012 1012
 {
1013
-	if (empty($user->societe_id))    // If internal user or not defined
1014
-	{
1015
-		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1016
-	}
1017
-	else                        // If external user
1018
-	{
1019
-		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020
-	}
1013
+    if (empty($user->societe_id))    // If internal user or not defined
1014
+    {
1015
+        $conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1016
+    }
1017
+    else                        // If external user
1018
+    {
1019
+        $conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020
+    }
1021 1021
 
1022
-	// Load the menu manager (only if not already done)
1023
-	$file_menu=$conf->standard_menu;
1024
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1025
-	if (! class_exists('MenuManager'))
1026
-	{
1027
-		$menufound=0;
1028
-		$dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
1029
-		foreach($dirmenus as $dirmenu)
1030
-		{
1031
-			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
1032
-			if (class_exists('MenuManager')) break;
1033
-		}
1034
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1035
-		{
1036
-			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1037
-			$file_menu='eldy_menu.php';
1038
-			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039
-		}
1040
-	}
1041
-	$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
1042
-	$menumanager->loadMenu();
1022
+    // Load the menu manager (only if not already done)
1023
+    $file_menu=$conf->standard_menu;
1024
+    if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1025
+    if (! class_exists('MenuManager'))
1026
+    {
1027
+        $menufound=0;
1028
+        $dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
1029
+        foreach($dirmenus as $dirmenu)
1030
+        {
1031
+            $menufound=dol_include_once($dirmenu."standard/".$file_menu);
1032
+            if (class_exists('MenuManager')) break;
1033
+        }
1034
+        if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1035
+        {
1036
+            dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1037
+            $file_menu='eldy_menu.php';
1038
+            include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039
+        }
1040
+    }
1041
+    $menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
1042
+    $menumanager->loadMenu();
1043 1043
 }
1044 1044
 
1045 1045
 
@@ -1048,52 +1048,52 @@  discard block
 block discarded – undo
1048 1048
 
1049 1049
 if (! function_exists("llxHeader"))
1050 1050
 {
1051
-	/**
1052
-	 *	Show HTML header HTML + BODY + Top menu + left menu + DIV
1053
-	 *
1054
-	 * @param 	string 	$head				Optionnal head lines
1055
-	 * @param 	string 	$title				HTML title
1056
-	 * @param	string	$help_url			Url links to help page
1057
-	 * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
1058
-	 *                                  	For other external page: http://server/url
1059
-	 * @param	string	$target				Target to use on links
1060
-	 * @param 	int    	$disablejs			More content into html header
1061
-	 * @param 	int    	$disablehead		More content into html header
1062
-	 * @param 	array  	$arrayofjs			Array of complementary js files
1063
-	 * @param 	array  	$arrayofcss			Array of complementary css files
1064
-	 * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
1065
-	 * @param   string  $morecssonbody      More CSS on body tag.
1066
-	 * @param	string	$replacemainareaby	Replace call to main_area() by a print of this string
1067
-	 * @return	void
1068
-	 */
1069
-	function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')
1070
-	{
1071
-		global $conf;
1051
+    /**
1052
+     *	Show HTML header HTML + BODY + Top menu + left menu + DIV
1053
+     *
1054
+     * @param 	string 	$head				Optionnal head lines
1055
+     * @param 	string 	$title				HTML title
1056
+     * @param	string	$help_url			Url links to help page
1057
+     * 		                            	Syntax is: For a wiki page: EN:EnglishPage|FR:FrenchPage|ES:SpanishPage
1058
+     *                                  	For other external page: http://server/url
1059
+     * @param	string	$target				Target to use on links
1060
+     * @param 	int    	$disablejs			More content into html header
1061
+     * @param 	int    	$disablehead		More content into html header
1062
+     * @param 	array  	$arrayofjs			Array of complementary js files
1063
+     * @param 	array  	$arrayofcss			Array of complementary css files
1064
+     * @param	string	$morequerystring	Query string to add to the link "print" to get same parameters (use only if autodetect fails)
1065
+     * @param   string  $morecssonbody      More CSS on body tag.
1066
+     * @param	string	$replacemainareaby	Replace call to main_area() by a print of this string
1067
+     * @return	void
1068
+     */
1069
+    function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')
1070
+    {
1071
+        global $conf;
1072 1072
 
1073
-		// html header
1074
-		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1073
+        // html header
1074
+        top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1075 1075
 
1076
-		print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
1076
+        print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
1077 1077
 
1078
-		// top menu and left menu area
1079
-		if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int'))
1080
-		{
1081
-			top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1082
-		}
1078
+        // top menu and left menu area
1079
+        if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int'))
1080
+        {
1081
+            top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1082
+        }
1083 1083
 
1084
-		if (empty($conf->dol_hide_leftmenu))
1085
-		{
1086
-			left_menu('', $help_url, '', '', 1, $title, 1);		// $menumanager is retreived with a global $menumanager inside this function
1087
-		}
1084
+        if (empty($conf->dol_hide_leftmenu))
1085
+        {
1086
+            left_menu('', $help_url, '', '', 1, $title, 1);		// $menumanager is retreived with a global $menumanager inside this function
1087
+        }
1088 1088
 
1089
-		// main area
1090
-		if ($replacemainareaby)
1091
-		{
1092
-			print $replacemainareaby;
1093
-			return;
1094
-		}
1095
-		main_area($title);
1096
-	}
1089
+        // main area
1090
+        if ($replacemainareaby)
1091
+        {
1092
+            print $replacemainareaby;
1093
+            return;
1094
+        }
1095
+        main_area($title);
1096
+    }
1097 1097
 }
1098 1098
 
1099 1099
 
@@ -1106,53 +1106,53 @@  discard block
 block discarded – undo
1106 1106
  */
1107 1107
 function top_httphead($contenttype='text/html', $forcenocache=0)
1108 1108
 {
1109
-	global $db, $conf, $hookmanager;
1110
-
1111
-	if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112
-	else header("Content-Type: ".$contenttype);
1113
-	// Security options
1114
-	header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
-	header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1116
-	//header("X-XSS-Protection: 1");      		// XSS protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1117
-	if (! defined('FORCECSP'))
1118
-	{
1119
-		//if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1120
-		//{
1121
-		//	// A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1122
-		//	$contentsecuritypolicy = "font-src *; img-src *; style-src * 'unsafe-inline' 'unsafe-eval'; default-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; script-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; frame-src 'self' *.stripe.com; connect-src 'self';";
1123
-		//}
1124
-		//else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125
-		$contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126
-
1127
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1128
-		$hookmanager->initHooks("main");
1129
-
1130
-		$parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
-		$result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
-		if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
-		else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1134
-
1135
-		if (! empty($contentsecuritypolicy))
1136
-		{
1137
-			// For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1138
-			// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
1139
-			// For example, to restrict everything to one domain, except 'object', ...:
1140
-			// default-src https://cdn.example.net; object-src 'none'
1141
-			// For example, to restrict everything to itself except img that can be on other servers:
1142
-			// default-src 'self'; img-src *;
1143
-			// Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
1144
-			// default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1145
-			header("Content-Security-Policy: ".$contentsecuritypolicy);
1146
-		}
1147
-	}
1148
-	elseif (constant('FORCECSP'))
1149
-	{
1150
-		header("Content-Security-Policy: ".constant('FORCECSP'));
1151
-	}
1152
-	if ($forcenocache)
1153
-	{
1154
-		header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1155
-	}
1109
+    global $db, $conf, $hookmanager;
1110
+
1111
+    if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112
+    else header("Content-Type: ".$contenttype);
1113
+    // Security options
1114
+    header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
+    header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1116
+    //header("X-XSS-Protection: 1");      		// XSS protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1117
+    if (! defined('FORCECSP'))
1118
+    {
1119
+        //if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1120
+        //{
1121
+        //	// A default security policy that keep usage of js external component like ckeditor, stripe, google, working
1122
+        //	$contentsecuritypolicy = "font-src *; img-src *; style-src * 'unsafe-inline' 'unsafe-eval'; default-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; script-src 'self' *.stripe.com 'unsafe-inline' 'unsafe-eval'; frame-src 'self' *.stripe.com; connect-src 'self';";
1123
+        //}
1124
+        //else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125
+        $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126
+
1127
+        if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1128
+        $hookmanager->initHooks("main");
1129
+
1130
+        $parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
+        $result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
+        if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
+        else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1134
+
1135
+        if (! empty($contentsecuritypolicy))
1136
+        {
1137
+            // For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1138
+            // script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
1139
+            // For example, to restrict everything to one domain, except 'object', ...:
1140
+            // default-src https://cdn.example.net; object-src 'none'
1141
+            // For example, to restrict everything to itself except img that can be on other servers:
1142
+            // default-src 'self'; img-src *;
1143
+            // Pre-existing site that uses too much inline code to fix but wants to ensure resources are loaded only over https and disable plugins:
1144
+            // default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1145
+            header("Content-Security-Policy: ".$contentsecuritypolicy);
1146
+        }
1147
+    }
1148
+    elseif (constant('FORCECSP'))
1149
+    {
1150
+        header("Content-Security-Policy: ".constant('FORCECSP'));
1151
+    }
1152
+    if ($forcenocache)
1153
+    {
1154
+        header("Cache-Control: no-cache, no-store, must-revalidate, max-age=0");
1155
+    }
1156 1156
 }
1157 1157
 
1158 1158
 /**
@@ -1171,220 +1171,220 @@  discard block
 block discarded – undo
1171 1171
  */
1172 1172
 function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
1173 1173
 {
1174
-	global $db, $conf, $langs, $user, $hookmanager;
1174
+    global $db, $conf, $langs, $user, $hookmanager;
1175 1175
 
1176
-	top_httphead();
1176
+    top_httphead();
1177 1177
 
1178
-	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1178
+    if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1179 1179
 
1180
-	print '<!doctype html>'."\n";
1180
+    print '<!doctype html>'."\n";
1181 1181
 
1182
-	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
-	else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1184
-	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185
-	if (empty($disablehead))
1186
-	{
1187
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1188
-
1189
-		print "<head>\n";
1190
-
1191
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1192
-
1193
-		// Displays meta
1194
-		print '<meta charset="UTF-8">'."\n";
1195
-		print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";	// Do not index
1196
-		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";		// Scale for mobile device
1197
-		print '<meta name="author" content="Dolibarr Development Team">'."\n";
1198
-
1199
-		// Favicon
1200
-		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
-		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
-		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1203
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205
-		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1206
-
1207
-		// Auto refresh page
1208
-		if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1209
-
1210
-		// Displays title
1211
-		$appli=constant('DOL_APPLICATION_TITLE');
1212
-		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1213
-
1214
-		print '<title>';
1215
-		$titletoshow='';
1216
-		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217
-		else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218
-		else $titletoshow = dol_htmlentities($appli);
1219
-
1220
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1221
-		$hookmanager->initHooks("main");
1222
-		$parameters=array('title'=>$titletoshow);
1223
-		$result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
-		if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
-		else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1226
-
1227
-		print $titletoshow;
1228
-		print '</title>';
1229
-
1230
-		print "\n";
1231
-
1232
-		if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
-		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1234
-
1235
-		$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
-		$themeparam.=($ext?'&amp;'.$ext:'');
1237
-		if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
-		if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239
-		if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240
-		if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1241
-		if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1242
-		if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1243
-
1244
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1245
-		{
1246
-			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247
-			$jquerytheme = 'base';
1248
-			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
-			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
-			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
-			if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
-			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253
-			{
1254
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1256
-			}
1257
-		}
1182
+    if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
+    else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1184
+    //print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185
+    if (empty($disablehead))
1186
+    {
1187
+        $ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1258 1188
 
1259
-		if (! defined('DISABLE_FONT_AWSOME'))
1260
-		{
1261
-			print '<!-- Includes CSS for font awesome -->'."\n";
1262
-			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1263
-		}
1189
+        print "<head>\n";
1264 1190
 
1265
-		print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1266
-		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267
-		$themepath=dol_buildpath($conf->css,1);
1268
-		$themesubdir='';
1269
-		if (! empty($conf->modules_parts['theme']))	// This slow down
1270
-		{
1271
-			foreach($conf->modules_parts['theme'] as $reldir)
1272
-			{
1273
-				if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274
-				{
1275
-					$themepath=dol_buildpath($reldir.$conf->css, 1);
1276
-					$themesubdir=$reldir;
1277
-					break;
1278
-				}
1279
-			}
1280
-		}
1191
+        if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1281 1192
 
1282
-		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283
-		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
-		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1193
+        // Displays meta
1194
+        print '<meta charset="UTF-8">'."\n";
1195
+        print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";	// Do not index
1196
+        print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";		// Scale for mobile device
1197
+        print '<meta name="author" content="Dolibarr Development Team">'."\n";
1285 1198
 
1286
-		// CSS forced by modules (relative url starting with /)
1287
-		if (! empty($conf->modules_parts['css']))
1288
-		{
1289
-			$arraycss=(array) $conf->modules_parts['css'];
1290
-			foreach($arraycss as $modcss => $filescss)
1291
-			{
1292
-				$filescss=(array) $filescss;	// To be sure filecss is an array
1293
-				foreach($filescss as $cssfile)
1294
-				{
1295
-					if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1296
-					// cssfile is a relative path
1297
-					print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1298
-					// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
-					if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1300
-					print '">'."\n";
1301
-				}
1302
-			}
1303
-		}
1304
-		// CSS forced by page in top_htmlhead call (relative url starting with /)
1305
-		if (is_array($arrayofcss))
1306
-		{
1307
-			foreach($arrayofcss as $cssfile)
1308
-			{
1309
-				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1310
-				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
-				if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1312
-				print '">'."\n";
1313
-			}
1314
-		}
1199
+        // Favicon
1200
+        $favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
+        if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
+        if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1203
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205
+        //if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1315 1206
 
1316
-		// Output standard javascript links
1317
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1318
-		{
1319
-			// JQuery. Must be before other includes
1320
-			print '<!-- Includes JS for JQuery -->'."\n";
1321
-			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1323
-			if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1324
-			{
1325
-				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
-				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1327
-			}
1328
-			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
-			if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1331
-			// jQuery jnotify
1332
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1333
-			{
1334
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1335
-			}
1336
-			// Flot
1337
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1338
-			{
1339
-				if (constant('JS_JQUERY_FLOT'))
1340
-				{
1341
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1344
-				}
1345
-				else
1346
-				{
1347
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1349
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1350
-				}
1351
-			}
1352
-			// jQuery jeditable
1353
-			if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1354
-			{
1355
-				print '<!-- JS to manage editInPlace feature -->'."\n";
1356
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1357
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1358
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1359
-				print '<script type="text/javascript">'."\n";
1360
-				print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1361
-				print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1362
-				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1363
-				print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1364
-				print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1365
-				print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1366
-				print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1367
-				print 'var withInPlace = 300;';		// width in pixel for default string edit
1368
-				print '</script>'."\n";
1369
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1370
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1371
-			}
1207
+        // Auto refresh page
1208
+        if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1209
+
1210
+        // Displays title
1211
+        $appli=constant('DOL_APPLICATION_TITLE');
1212
+        if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1213
+
1214
+        print '<title>';
1215
+        $titletoshow='';
1216
+        if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217
+        else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218
+        else $titletoshow = dol_htmlentities($appli);
1219
+
1220
+        if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1221
+        $hookmanager->initHooks("main");
1222
+        $parameters=array('title'=>$titletoshow);
1223
+        $result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
+        if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
+        else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1226
+
1227
+        print $titletoshow;
1228
+        print '</title>';
1229
+
1230
+        print "\n";
1231
+
1232
+        if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
+        if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1234
+
1235
+        $themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
+        $themeparam.=($ext?'&amp;'.$ext:'');
1237
+        if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
+        if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239
+        if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240
+        if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1241
+        if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1242
+        if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1243
+
1244
+        if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1245
+        {
1246
+            print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247
+            $jquerytheme = 'base';
1248
+            if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
+            if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
+            else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
+            if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
+            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253
+            {
1254
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
+                print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1256
+            }
1257
+        }
1258
+
1259
+        if (! defined('DISABLE_FONT_AWSOME'))
1260
+        {
1261
+            print '<!-- Includes CSS for font awesome -->'."\n";
1262
+            print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1263
+        }
1264
+
1265
+        print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1266
+        // Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267
+        $themepath=dol_buildpath($conf->css,1);
1268
+        $themesubdir='';
1269
+        if (! empty($conf->modules_parts['theme']))	// This slow down
1270
+        {
1271
+            foreach($conf->modules_parts['theme'] as $reldir)
1272
+            {
1273
+                if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274
+                {
1275
+                    $themepath=dol_buildpath($reldir.$conf->css, 1);
1276
+                    $themesubdir=$reldir;
1277
+                    break;
1278
+                }
1279
+            }
1280
+        }
1281
+
1282
+        //print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283
+        print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
+        if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1285
+
1286
+        // CSS forced by modules (relative url starting with /)
1287
+        if (! empty($conf->modules_parts['css']))
1288
+        {
1289
+            $arraycss=(array) $conf->modules_parts['css'];
1290
+            foreach($arraycss as $modcss => $filescss)
1291
+            {
1292
+                $filescss=(array) $filescss;	// To be sure filecss is an array
1293
+                foreach($filescss as $cssfile)
1294
+                {
1295
+                    if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1296
+                    // cssfile is a relative path
1297
+                    print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1298
+                    // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
+                    if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1300
+                    print '">'."\n";
1301
+                }
1302
+            }
1303
+        }
1304
+        // CSS forced by page in top_htmlhead call (relative url starting with /)
1305
+        if (is_array($arrayofcss))
1306
+        {
1307
+            foreach($arrayofcss as $cssfile)
1308
+            {
1309
+                print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1310
+                // We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
+                if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1312
+                print '">'."\n";
1313
+            }
1314
+        }
1315
+
1316
+        // Output standard javascript links
1317
+        if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1318
+        {
1319
+            // JQuery. Must be before other includes
1320
+            print '<!-- Includes JS for JQuery -->'."\n";
1321
+            if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1323
+            if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1324
+            {
1325
+                if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
+                else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1327
+            }
1328
+            if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
+            else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
+            if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1331
+            // jQuery jnotify
1332
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1333
+            {
1334
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1335
+            }
1336
+            // Flot
1337
+            if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1338
+            {
1339
+                if (constant('JS_JQUERY_FLOT'))
1340
+                {
1341
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343
+                    print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1344
+                }
1345
+                else
1346
+                {
1347
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1349
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1350
+                }
1351
+            }
1352
+            // jQuery jeditable
1353
+            if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1354
+            {
1355
+                print '<!-- JS to manage editInPlace feature -->'."\n";
1356
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1357
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1358
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1359
+                print '<script type="text/javascript">'."\n";
1360
+                print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1361
+                print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1362
+                print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1363
+                print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1364
+                print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1365
+                print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1366
+                print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1367
+                print 'var withInPlace = 300;';		// width in pixel for default string edit
1368
+                print '</script>'."\n";
1369
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1370
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1371
+            }
1372 1372
             // jQuery Timepicker
1373 1373
             if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1374 1374
             {
1375
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1375
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1377 1377
             }
1378 1378
             if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1379 1379
             {
1380
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1380
+                $tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1382 1382
             }
1383 1383
             if (! defined('DISABLE_MULTISELECT'))     // jQuery plugin "mutiselect" to select with checkboxes
1384 1384
             {
1385
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1385
+                print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1386 1386
             }
1387
-		}
1387
+        }
1388 1388
 
1389 1389
         if (! $disablejs && ! empty($conf->use_javascript_ajax))
1390 1390
         {
@@ -1396,7 +1396,7 @@  discard block
 block discarded – undo
1396 1396
                 $jsckeditor='ckeditor.js';
1397 1397
                 if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1398 1398
                 {
1399
-                	$pathckeditor=constant('JS_CKEDITOR');
1399
+                    $pathckeditor=constant('JS_CKEDITOR');
1400 1400
                 }
1401 1401
                 print '<script type="text/javascript">';
1402 1402
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
@@ -1426,18 +1426,18 @@  discard block
 block discarded – undo
1426 1426
 
1427 1427
             // JS forced by modules (relative url starting with /)
1428 1428
             if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1429
-        	{
1430
-        		$arrayjs=(array) $conf->modules_parts['js'];
1431
-	            foreach($arrayjs as $modjs => $filesjs)
1432
-	            {
1433
-        			$filesjs=(array) $filesjs;	// To be sure filejs is an array
1434
-		            foreach($filesjs as $jsfile)
1435
-		            {
1436
-	    	    		// jsfile is a relative path
1437
-	        	    	print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1438
-		            }
1439
-	            }
1440
-        	}
1429
+            {
1430
+                $arrayjs=(array) $conf->modules_parts['js'];
1431
+                foreach($arrayjs as $modjs => $filesjs)
1432
+                {
1433
+                    $filesjs=(array) $filesjs;	// To be sure filejs is an array
1434
+                    foreach($filesjs as $jsfile)
1435
+                    {
1436
+                        // jsfile is a relative path
1437
+                        print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1438
+                    }
1439
+                }
1440
+            }
1441 1441
             // JS forced by page in top_htmlhead (relative url starting with /)
1442 1442
             if (is_array($arrayofjs))
1443 1443
             {
@@ -1484,192 +1484,192 @@  discard block
 block discarded – undo
1484 1484
  */
1485 1485
 function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')
1486 1486
 {
1487
-	global $user, $conf, $langs, $db;
1488
-	global $dolibarr_main_authentication, $dolibarr_main_demo;
1489
-	global $hookmanager,$menumanager;
1487
+    global $user, $conf, $langs, $db;
1488
+    global $dolibarr_main_authentication, $dolibarr_main_demo;
1489
+    global $hookmanager,$menumanager;
1490 1490
 
1491
-	$searchform='';
1492
-	$bookmarks='';
1491
+    $searchform='';
1492
+    $bookmarks='';
1493 1493
 
1494
-	// Instantiate hooks of thirdparty module
1495
-	$hookmanager->initHooks(array('toprightmenu'));
1494
+    // Instantiate hooks of thirdparty module
1495
+    $hookmanager->initHooks(array('toprightmenu'));
1496 1496
 
1497
-	$toprightmenu='';
1497
+    $toprightmenu='';
1498 1498
 
1499
-	// For backward compatibility with old modules
1500
-	if (empty($conf->headerdone))
1501
-	{
1502
-		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1503
-		print '<body id="mainbody">';
1504
-	}
1499
+    // For backward compatibility with old modules
1500
+    if (empty($conf->headerdone))
1501
+    {
1502
+        top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1503
+        print '<body id="mainbody">';
1504
+    }
1505 1505
 
1506
-	/*
1506
+    /*
1507 1507
      * Top menu
1508 1508
      */
1509
-	if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1510
-	{
1511
-		print "\n".'<!-- Start top horizontal -->'."\n";
1509
+    if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1510
+    {
1511
+        print "\n".'<!-- Start top horizontal -->'."\n";
1512 1512
 
1513
-		print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu','int')?' hidden':'').'"><div id="id-top">';		// dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1513
+        print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu','int')?' hidden':'').'"><div id="id-top">';		// dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1514 1514
 
1515
-		// Show menu entries
1516
-		print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1517
-		$menumanager->atarget=$target;
1518
-		$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1519
-		print "</div>\n";
1515
+        // Show menu entries
1516
+        print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1517
+        $menumanager->atarget=$target;
1518
+        $menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1519
+        print "</div>\n";
1520 1520
 
1521
-		// Define link to login card
1522
-		$appli=constant('DOL_APPLICATION_TITLE');
1523
-		if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1524
-		{
1525
-			$appli=$conf->global->MAIN_APPLICATION_TITLE;
1526
-			if (preg_match('/\d\.\d/', $appli))
1527
-			{
1528
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1529
-			}
1530
-			else $appli.=" ".DOL_VERSION;
1531
-		}
1532
-		else $appli.=" ".DOL_VERSION;
1521
+        // Define link to login card
1522
+        $appli=constant('DOL_APPLICATION_TITLE');
1523
+        if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1524
+        {
1525
+            $appli=$conf->global->MAIN_APPLICATION_TITLE;
1526
+            if (preg_match('/\d\.\d/', $appli))
1527
+            {
1528
+                if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1529
+            }
1530
+            else $appli.=" ".DOL_VERSION;
1531
+        }
1532
+        else $appli.=" ".DOL_VERSION;
1533 1533
 
1534
-		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1534
+        if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1535 1535
 
1536
-		$logouttext='';
1537
-		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1538
-		{
1539
-			//$logouthtmltext=$appli.'<br>';
1540
-			if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1541
-			{
1542
-				$logouthtmltext.=$langs->trans("Logout").'<br>';
1543
-
1544
-				$logouttext .='<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1545
-				//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546
-				$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547
-				$logouttext .='</a>';
1548
-			}
1549
-			else
1550
-			{
1551
-				$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1552
-				$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1553
-			}
1554
-		}
1536
+        $logouttext='';
1537
+        if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1538
+        {
1539
+            //$logouthtmltext=$appli.'<br>';
1540
+            if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1541
+            {
1542
+                $logouthtmltext.=$langs->trans("Logout").'<br>';
1555 1543
 
1556
-		print '<div class="login_block">'."\n";
1544
+                $logouttext .='<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1545
+                //$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546
+                $logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547
+                $logouttext .='</a>';
1548
+            }
1549
+            else
1550
+            {
1551
+                $logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1552
+                $logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1553
+            }
1554
+        }
1557 1555
 
1558
-		// Add login user link
1559
-		$toprightmenu.='<div class="login_block_user">';
1556
+        print '<div class="login_block">'."\n";
1560 1557
 
1561
-		// Login name with photo and tooltip
1562
-		$mode=-1;
1563
-		$toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
-		$toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1565
-		$toprightmenu.='</div></div>';
1558
+        // Add login user link
1559
+        $toprightmenu.='<div class="login_block_user">';
1566 1560
 
1567
-		$toprightmenu.='</div>'."\n";
1561
+        // Login name with photo and tooltip
1562
+        $mode=-1;
1563
+        $toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
+        $toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1565
+        $toprightmenu.='</div></div>';
1568 1566
 
1569
-		$toprightmenu.='<div class="login_block_other">';
1567
+        $toprightmenu.='</div>'."\n";
1570 1568
 
1571
-		// Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1572
-		$parameters=array();
1573
-		$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1574
-		if (is_numeric($result))
1575
-		{
1576
-			if ($result == 0)
1577
-				$toprightmenu.=$hookmanager->resPrint;		// add
1578
-			else
1579
-				$toprightmenu=$hookmanager->resPrint;						// replace
1580
-		}
1581
-		else
1582
-		{
1583
-			$toprightmenu.=$result;	// For backward compatibility
1584
-		}
1569
+        $toprightmenu.='<div class="login_block_other">';
1585 1570
 
1586
-		// Link to module builder
1587
-		if (! empty($conf->modulebuilder->enabled))
1588
-		{
1589
-			$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1590
-			//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1591
-			$text.='<span class="fa fa-bug atoplogin"></span>';
1592
-			$text.='</a>';
1593
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1594
-		}
1571
+        // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1572
+        $parameters=array();
1573
+        $result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1574
+        if (is_numeric($result))
1575
+        {
1576
+            if ($result == 0)
1577
+                $toprightmenu.=$hookmanager->resPrint;		// add
1578
+            else
1579
+                $toprightmenu=$hookmanager->resPrint;						// replace
1580
+        }
1581
+        else
1582
+        {
1583
+            $toprightmenu.=$result;	// For backward compatibility
1584
+        }
1595 1585
 
1596
-		// Link to print main content area
1597
-		if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1598
-		{
1599
-			$qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1600
-
1601
-			if (is_array($_POST))
1602
-			{
1603
-				foreach($_POST as $key=>$value) {
1604
-					if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1605
-				}
1606
-			}
1607
-			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1608
-			$text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1609
-			//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1610
-			$text.='<span class="fa fa-print atoplogin"></span>';
1611
-			$text.='</a>';
1612
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1613
-		}
1586
+        // Link to module builder
1587
+        if (! empty($conf->modulebuilder->enabled))
1588
+        {
1589
+            $text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1590
+            //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1591
+            $text.='<span class="fa fa-bug atoplogin"></span>';
1592
+            $text.='</a>';
1593
+            $toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1594
+        }
1614 1595
 
1615
-		// Link to Dolibarr wiki pages
1616
-		if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1617
-		{
1618
-			$langs->load("help");
1596
+        // Link to print main content area
1597
+        if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1598
+        {
1599
+            $qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1600
+
1601
+            if (is_array($_POST))
1602
+            {
1603
+                foreach($_POST as $key=>$value) {
1604
+                    if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1605
+                }
1606
+            }
1607
+            $qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1608
+            $text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1609
+            //$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1610
+            $text.='<span class="fa fa-print atoplogin"></span>';
1611
+            $text.='</a>';
1612
+            $toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1613
+        }
1614
+
1615
+        // Link to Dolibarr wiki pages
1616
+        if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1617
+        {
1618
+            $langs->load("help");
1619 1619
 
1620
-			$helpbaseurl='';
1621
-			$helppage='';
1622
-			$mode='';
1620
+            $helpbaseurl='';
1621
+            $helppage='';
1622
+            $mode='';
1623 1623
 
1624
-			if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1624
+            if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1625 1625
 
1626
-			// Get helpbaseurl, helppage and mode from helppagename and langs
1627
-			$arrayres=getHelpParamFor($helppagename,$langs);
1628
-			$helpbaseurl=$arrayres['helpbaseurl'];
1629
-			$helppage=$arrayres['helppage'];
1630
-			$mode=$arrayres['mode'];
1626
+            // Get helpbaseurl, helppage and mode from helppagename and langs
1627
+            $arrayres=getHelpParamFor($helppagename,$langs);
1628
+            $helpbaseurl=$arrayres['helpbaseurl'];
1629
+            $helppage=$arrayres['helppage'];
1630
+            $mode=$arrayres['mode'];
1631 1631
 
1632
-			// Link to help pages
1633
-			if ($helpbaseurl && $helppage)
1634
-			{
1635
-				$text='';
1636
-	            if(!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1632
+            // Link to help pages
1633
+            if ($helpbaseurl && $helppage)
1634
+            {
1635
+                $text='';
1636
+                if(!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1637 1637
                     $langs->load('admin');
1638 1638
                     $appli .= '<br>' . $langs->trans("Database") . ': ' . $db->database_name;
1639 1639
                 }
1640
-				$title=$appli.'<br>';
1641
-				$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
-				if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1643
-				$text.='<a class="help" target="_blank" rel="noopener" href="';
1644
-				if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
-				else $text.=sprintf($helpbaseurl,$helppage);
1646
-				$text.='">';
1647
-				//$text.=img_picto('', 'helpdoc_top').' ';
1648
-				$text.='<span class="fa fa-question-circle atoplogin"></span>';
1649
-				//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1650
-				//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1651
-				$text.='</a>';
1652
-				//$toprightmenu.='</div>'."\n";
1653
-				$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1654
-			}
1655
-		}
1640
+                $title=$appli.'<br>';
1641
+                $title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
+                if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1643
+                $text.='<a class="help" target="_blank" rel="noopener" href="';
1644
+                if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
+                else $text.=sprintf($helpbaseurl,$helppage);
1646
+                $text.='">';
1647
+                //$text.=img_picto('', 'helpdoc_top').' ';
1648
+                $text.='<span class="fa fa-question-circle atoplogin"></span>';
1649
+                //$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1650
+                //if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1651
+                $text.='</a>';
1652
+                //$toprightmenu.='</div>'."\n";
1653
+                $toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1654
+            }
1655
+        }
1656 1656
 
1657
-		// Logout link
1658
-		$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1657
+        // Logout link
1658
+        $toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1659 1659
 
1660
-		$toprightmenu.='</div>';
1660
+        $toprightmenu.='</div>';
1661 1661
 
1662
-		print $toprightmenu;
1662
+        print $toprightmenu;
1663 1663
 
1664
-		print "</div>\n";		// end div class="login_block"
1664
+        print "</div>\n";		// end div class="login_block"
1665 1665
 
1666
-		print '</div></div>';
1666
+        print '</div></div>';
1667 1667
 
1668
-		print '<div style="clear: both;"></div>';
1669
-		print "<!-- End top horizontal menu -->\n\n";
1670
-	}
1668
+        print '<div style="clear: both;"></div>';
1669
+        print "<!-- End top horizontal menu -->\n\n";
1670
+    }
1671 1671
 
1672
-	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1672
+    if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1673 1673
 }
1674 1674
 
1675 1675
 
@@ -1689,172 +1689,172 @@  discard block
 block discarded – undo
1689 1689
  */
1690 1690
 function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
1691 1691
 {
1692
-	global $user, $conf, $langs, $db, $form;
1693
-	global $hookmanager, $menumanager;
1692
+    global $user, $conf, $langs, $db, $form;
1693
+    global $hookmanager, $menumanager;
1694 1694
 
1695
-	$searchform='';
1696
-	$bookmarks='';
1695
+    $searchform='';
1696
+    $bookmarks='';
1697 1697
 
1698
-	if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1698
+    if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1699 1699
 
1700
-	if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1701
-	{
1702
-		// Instantiate hooks of thirdparty module
1703
-		$hookmanager->initHooks(array('searchform','leftblock'));
1700
+    if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1701
+    {
1702
+        // Instantiate hooks of thirdparty module
1703
+        $hookmanager->initHooks(array('searchform','leftblock'));
1704 1704
 
1705
-		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1705
+        print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1706 1706
 
1707
-		if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1707
+        if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1708 1708
 
1709
-		print "\n";
1709
+        print "\n";
1710 1710
 
1711
-		if (! is_object($form)) $form=new Form($db);
1712
-		$selected=-1;
1713
-		$usedbyinclude=1;
1714
-		include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
1711
+        if (! is_object($form)) $form=new Form($db);
1712
+        $selected=-1;
1713
+        $usedbyinclude=1;
1714
+        include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
1715 1715
 
1716
-		if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1717
-		{
1718
-			//$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
-			$searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720
-		}
1721
-		else
1722
-		{
1723
-			foreach($arrayresult as $key => $val)
1724
-			{
1725
-				//$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));
1726
-				$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1727
-			}
1728
-		}
1716
+        if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1717
+        {
1718
+            //$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
+            $searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720
+        }
1721
+        else
1722
+        {
1723
+            foreach($arrayresult as $key => $val)
1724
+            {
1725
+                //$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));
1726
+                $searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1727
+            }
1728
+        }
1729 1729
 
1730
-		// Execute hook printSearchForm
1731
-		$parameters=array('searchform'=>$searchform);
1732
-		$reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1733
-		if (empty($reshook))
1734
-		{
1735
-			$searchform.=$hookmanager->resPrint;
1736
-		}
1737
-		else $searchform=$hookmanager->resPrint;
1730
+        // Execute hook printSearchForm
1731
+        $parameters=array('searchform'=>$searchform);
1732
+        $reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1733
+        if (empty($reshook))
1734
+        {
1735
+            $searchform.=$hookmanager->resPrint;
1736
+        }
1737
+        else $searchform=$hookmanager->resPrint;
1738 1738
 
1739
-		// Force special value for $searchform
1740
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741
-		{
1742
-			$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744
-		}
1745
-		elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746
-		{
1747
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
-			$searchform.='<script type="text/javascript">
1739
+        // Force special value for $searchform
1740
+        if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741
+        {
1742
+            $urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
+            $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744
+        }
1745
+        elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746
+        {
1747
+            $searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
+            $searchform.='<script type="text/javascript">
1749 1749
             	jQuery(document).ready(function () {
1750 1750
             		jQuery("#divsearchforms1").click(function(){
1751 1751
 	                   jQuery("#divsearchforms2").toggle();
1752 1752
 	               });
1753 1753
             	});
1754 1754
                 </script>' . "\n";
1755
-			$searchform.='</div>';
1756
-		}
1755
+            $searchform.='</div>';
1756
+        }
1757 1757
 
1758
-		// Define $bookmarks
1759
-		if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1760
-		{
1761
-			include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
1762
-			$langs->load("bookmarks");
1758
+        // Define $bookmarks
1759
+        if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1760
+        {
1761
+            include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
1762
+            $langs->load("bookmarks");
1763 1763
 
1764
-			$bookmarks=printBookmarksList($db, $langs);
1765
-		}
1764
+            $bookmarks=printBookmarksList($db, $langs);
1765
+        }
1766 1766
 
1767
-		// Left column
1768
-		print '<!-- Begin left menu -->'."\n";
1767
+        // Left column
1768
+        print '<!-- Begin left menu -->'."\n";
1769 1769
 
1770
-		print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1770
+        print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1771 1771
 
1772
-		// Show left menu with other forms
1773
-		$menumanager->menu_array = $menu_array_before;
1774
-		$menumanager->menu_array_after = $menu_array_after;
1775
-		$menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1772
+        // Show left menu with other forms
1773
+        $menumanager->menu_array = $menu_array_before;
1774
+        $menumanager->menu_array_after = $menu_array_after;
1775
+        $menumanager->showmenu('left', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // output menu_array and menu found in database
1776 1776
 
1777
-		// Dolibarr version + help + bug report link
1778
-		print "\n";
1779
-		print "<!-- Begin Help Block-->\n";
1780
-		print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1777
+        // Dolibarr version + help + bug report link
1778
+        print "\n";
1779
+        print "<!-- Begin Help Block-->\n";
1780
+        print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1781 1781
 
1782
-		// Version
1783
-		if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1784
-		{
1785
-			$doliurl='https://www.dolibarr.org';
1786
-			//local communities
1787
-			if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
-			if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
-			if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
-			if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
-			if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1792
-
1793
-			$appli=constant('DOL_APPLICATION_TITLE');
1794
-			if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1795
-			{
1796
-				$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1797
-				if (preg_match('/\d\.\d/', $appli))
1798
-				{
1799
-					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1800
-				}
1801
-				else $appli.=" ".DOL_VERSION;
1802
-			}
1803
-			else $appli.=" ".DOL_VERSION;
1804
-			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805
-			if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806
-			else print '<span class="help">';
1807
-			print $appli;
1808
-			if ($doliurl) print '</a>';
1809
-			else print '</span>';
1810
-			print '</div>'."\n";
1811
-		}
1782
+        // Version
1783
+        if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1784
+        {
1785
+            $doliurl='https://www.dolibarr.org';
1786
+            //local communities
1787
+            if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
+            if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
+            if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
+            if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
+            if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1792
+
1793
+            $appli=constant('DOL_APPLICATION_TITLE');
1794
+            if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1795
+            {
1796
+                $appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1797
+                if (preg_match('/\d\.\d/', $appli))
1798
+                {
1799
+                    if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1800
+                }
1801
+                else $appli.=" ".DOL_VERSION;
1802
+            }
1803
+            else $appli.=" ".DOL_VERSION;
1804
+            print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805
+            if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806
+            else print '<span class="help">';
1807
+            print $appli;
1808
+            if ($doliurl) print '</a>';
1809
+            else print '</span>';
1810
+            print '</div>'."\n";
1811
+        }
1812 1812
 
1813
-		// Link to bugtrack
1814
-		if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1815
-		{
1816
-			require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1817
-
1818
-			$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1819
-			$bugbaseurl.= '?title=';
1820
-			$bugbaseurl.= urlencode("Bug: ");
1821
-			$bugbaseurl.= '&body=';
1822
-			$bugbaseurl.= urlencode("# Bug\n");
1823
-			$bugbaseurl.= urlencode("\n");
1824
-			$bugbaseurl.= urlencode("## Environment\n");
1825
-			$bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1826
-			$bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1827
-			$bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1828
-			$bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1829
-			$bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1830
-			$bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1831
-			$bugbaseurl.= urlencode("\n");
1832
-			$bugbaseurl.= urlencode("## Report\n");
1833
-			print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1834
-			print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1835
-			print '</div>';
1836
-		}
1813
+        // Link to bugtrack
1814
+        if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1815
+        {
1816
+            require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1817
+
1818
+            $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1819
+            $bugbaseurl.= '?title=';
1820
+            $bugbaseurl.= urlencode("Bug: ");
1821
+            $bugbaseurl.= '&body=';
1822
+            $bugbaseurl.= urlencode("# Bug\n");
1823
+            $bugbaseurl.= urlencode("\n");
1824
+            $bugbaseurl.= urlencode("## Environment\n");
1825
+            $bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1826
+            $bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1827
+            $bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1828
+            $bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1829
+            $bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1830
+            $bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1831
+            $bugbaseurl.= urlencode("\n");
1832
+            $bugbaseurl.= urlencode("## Report\n");
1833
+            print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1834
+            print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1835
+            print '</div>';
1836
+        }
1837 1837
 
1838
-		print "</div>\n";
1839
-		print "<!-- End Help Block-->\n";
1840
-		print "\n";
1838
+        print "</div>\n";
1839
+        print "<!-- End Help Block-->\n";
1840
+        print "\n";
1841 1841
 
1842
-		print "</div>\n";
1843
-		print "<!-- End left menu -->\n";
1844
-		print "\n";
1842
+        print "</div>\n";
1843
+        print "<!-- End left menu -->\n";
1844
+        print "\n";
1845 1845
 
1846
-		// Execute hook printLeftBlock
1847
-		$parameters=array();
1848
-		$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1849
-		print $hookmanager->resPrint;
1846
+        // Execute hook printLeftBlock
1847
+        $parameters=array();
1848
+        $reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1849
+        print $hookmanager->resPrint;
1850 1850
 
1851
-		print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1852
-	}
1851
+        print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1852
+    }
1853 1853
 
1854
-	print "\n";
1855
-	print '<!-- Begin right area -->'."\n";
1854
+    print "\n";
1855
+    print '<!-- Begin right area -->'."\n";
1856 1856
 
1857
-	if (empty($leftmenuwithoutmainarea)) main_area($title);
1857
+    if (empty($leftmenuwithoutmainarea)) main_area($title);
1858 1858
 }
1859 1859
 
1860 1860
 
@@ -1866,15 +1866,15 @@  discard block
 block discarded – undo
1866 1866
  */
1867 1867
 function main_area($title='')
1868 1868
 {
1869
-	global $conf, $langs;
1869
+    global $conf, $langs;
1870 1870
 
1871
-	if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
1871
+    if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
1872 1872
 
1873
-	print "\n";
1873
+    print "\n";
1874 1874
 
1875
-	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1875
+    print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1876 1876
 
1877
-	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1877
+    if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1878 1878
 }
1879 1879
 
1880 1880
 
@@ -1887,38 +1887,38 @@  discard block
 block discarded – undo
1887 1887
  */
1888 1888
 function getHelpParamFor($helppagename,$langs)
1889 1889
 {
1890
-	$helpbaseurl='';
1891
-	$helppage='';
1892
-	$mode='';
1893
-
1894
-	if (preg_match('/^http/i',$helppagename))
1895
-	{
1896
-		// If complete URL
1897
-		$helpbaseurl='%s';
1898
-		$helppage=$helppagename;
1899
-		$mode='local';
1900
-	}
1901
-	else
1902
-	{
1903
-		// If WIKI URL
1904
-		if (preg_match('/^es/i',$langs->defaultlang))
1905
-		{
1906
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
-			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1908
-		}
1909
-		if (preg_match('/^fr/i',$langs->defaultlang))
1910
-		{
1911
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
-			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1913
-		}
1914
-		if (empty($helppage))	// If help page not already found
1915
-		{
1916
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
-			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1918
-		}
1919
-		$mode='wiki';
1920
-	}
1921
-	return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1890
+    $helpbaseurl='';
1891
+    $helppage='';
1892
+    $mode='';
1893
+
1894
+    if (preg_match('/^http/i',$helppagename))
1895
+    {
1896
+        // If complete URL
1897
+        $helpbaseurl='%s';
1898
+        $helppage=$helppagename;
1899
+        $mode='local';
1900
+    }
1901
+    else
1902
+    {
1903
+        // If WIKI URL
1904
+        if (preg_match('/^es/i',$langs->defaultlang))
1905
+        {
1906
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
+            if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1908
+        }
1909
+        if (preg_match('/^fr/i',$langs->defaultlang))
1910
+        {
1911
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
+            if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1913
+        }
1914
+        if (empty($helppage))	// If help page not already found
1915
+        {
1916
+            $helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
+            if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1918
+        }
1919
+        $mode='wiki';
1920
+    }
1921
+    return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1922 1922
 }
1923 1923
 
1924 1924
 
@@ -1939,138 +1939,138 @@  discard block
 block discarded – undo
1939 1939
  */
1940 1940
 function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='', $showtitlebefore=0)
1941 1941
 {
1942
-	global $conf,$langs,$user;
1943
-
1944
-	$ret='';
1945
-	$ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1946
-	$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
-	$ret.='<input type="hidden" name="mode" value="search">';
1948
-	$ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
-	if ($showtitlebefore) $ret.=$title.' ';
1950
-	$ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951
-	$ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
-	$ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1953
-	$ret.=' placeholder="'.strip_tags($title).'"';
1954
-	$ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1955
-	//$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1956
-	$ret.='<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
-	$ret.='<span class="fa fa-search"></span>';
1958
-	$ret.='</button>';
1959
-	$ret.="</form>\n";
1960
-	return $ret;
1942
+    global $conf,$langs,$user;
1943
+
1944
+    $ret='';
1945
+    $ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1946
+    $ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
+    $ret.='<input type="hidden" name="mode" value="search">';
1948
+    $ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
+    if ($showtitlebefore) $ret.=$title.' ';
1950
+    $ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951
+    $ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
+    $ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1953
+    $ret.=' placeholder="'.strip_tags($title).'"';
1954
+    $ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1955
+    //$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1956
+    $ret.='<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
+    $ret.='<span class="fa fa-search"></span>';
1958
+    $ret.='</button>';
1959
+    $ret.="</form>\n";
1960
+    return $ret;
1961 1961
 }
1962 1962
 
1963 1963
 
1964 1964
 if (! function_exists("llxFooter"))
1965 1965
 {
1966
-	/**
1967
-	 * Show HTML footer
1968
-	 * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1969
-	 * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1970
-	 *
1971
-	 * @param	string	$comment    				A text to add as HTML comment into HTML generated page
1972
-	 * @param	string	$zone						'private' (for private pages) or 'public' (for public pages)
1973
-	 * @param	int		$disabledoutputofmessages	Clear all messages stored into session without diplaying them
1974
-	 * @return	void
1975
-	 */
1976
-	function llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)
1977
-	{
1978
-		global $conf, $langs, $user, $object;
1979
-		global $delayedhtmlcontent;
1980
-		global $contextpage, $page, $limit;
1966
+    /**
1967
+     * Show HTML footer
1968
+     * Close div /DIV class=fiche + /DIV id-right + /DIV id-container + /BODY + /HTML.
1969
+     * If global var $delayedhtmlcontent was filled, we output it just before closing the body.
1970
+     *
1971
+     * @param	string	$comment    				A text to add as HTML comment into HTML generated page
1972
+     * @param	string	$zone						'private' (for private pages) or 'public' (for public pages)
1973
+     * @param	int		$disabledoutputofmessages	Clear all messages stored into session without diplaying them
1974
+     * @return	void
1975
+     */
1976
+    function llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)
1977
+    {
1978
+        global $conf, $langs, $user, $object;
1979
+        global $delayedhtmlcontent;
1980
+        global $contextpage, $page, $limit;
1981 1981
 
1982
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1982
+        $ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1983 1983
 
1984
-		// Global html output events ($mesgs, $errors, $warnings)
1985
-		dol_htmloutput_events($disabledoutputofmessages);
1984
+        // Global html output events ($mesgs, $errors, $warnings)
1985
+        dol_htmloutput_events($disabledoutputofmessages);
1986 1986
 
1987
-		// Code for search criteria persistence.
1988
-		// $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
1989
-		if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1990
-		{
1991
-			// Clean and save data
1992
-			foreach($user->lastsearch_values_tmp as $key => $val)
1993
-			{
1994
-				unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1995
-				if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
1996
-				{
1997
-					if (empty($val['sortfield'])) unset($val['sortfield']);
1998
-					if (empty($val['sortorder'])) unset($val['sortorder']);
1999
-					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000
-					$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2001
-					unset($_SESSION['lastsearch_values_'.$key]);
2002
-				}
2003
-			}
2004
-		}
1987
+        // Code for search criteria persistence.
1988
+        // $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
1989
+        if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1990
+        {
1991
+            // Clean and save data
1992
+            foreach($user->lastsearch_values_tmp as $key => $val)
1993
+            {
1994
+                unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1995
+                if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
1996
+                {
1997
+                    if (empty($val['sortfield'])) unset($val['sortfield']);
1998
+                    if (empty($val['sortorder'])) unset($val['sortorder']);
1999
+                    dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000
+                    $_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2001
+                    unset($_SESSION['lastsearch_values_'.$key]);
2002
+                }
2003
+            }
2004
+        }
2005 2005
 
2006 2006
 
2007
-		$relativepathstring = $_SERVER["PHP_SELF"];
2008
-		// Clean $relativepathstring
2009
-		if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2010
-		$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011
-		$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012
-		if (preg_match('/list\.php$/', $relativepathstring))
2013
-		{
2014
-			unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
2015
-			unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016
-			unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2007
+        $relativepathstring = $_SERVER["PHP_SELF"];
2008
+        // Clean $relativepathstring
2009
+        if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2010
+        $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011
+        $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012
+        if (preg_match('/list\.php$/', $relativepathstring))
2013
+        {
2014
+            unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
2015
+            unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016
+            unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2017 2017
 
2018
-			if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
-			if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
-			if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2018
+            if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
+            if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
+            if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2021 2021
 
2022
-			unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023
-			unset($_SESSION['lastsearch_page_'.$relativepathstring]);
2024
-			unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
2025
-		}
2022
+            unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023
+            unset($_SESSION['lastsearch_page_'.$relativepathstring]);
2024
+            unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
2025
+        }
2026 2026
 
2027
-		// Core error message
2028
-		if (! empty($conf->global->MAIN_CORE_ERROR))
2029
-		{
2030
-			// Ajax version
2031
-			if ($conf->use_javascript_ajax)
2032
-			{
2033
-				$title = img_warning().' '.$langs->trans('CoreErrorTitle');
2034
-				print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
2035
-			}
2036
-			// html version
2037
-			else
2038
-			{
2039
-				$msg = img_warning().' '.$langs->trans('CoreErrorMessage');
2040
-				print '<div class="error">'.$msg.'</div>';
2041
-			}
2042
-
2043
-			//define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
2044
-		}
2027
+        // Core error message
2028
+        if (! empty($conf->global->MAIN_CORE_ERROR))
2029
+        {
2030
+            // Ajax version
2031
+            if ($conf->use_javascript_ajax)
2032
+            {
2033
+                $title = img_warning().' '.$langs->trans('CoreErrorTitle');
2034
+                print ajax_dialog($title, $langs->trans('CoreErrorMessage'));
2035
+            }
2036
+            // html version
2037
+            else
2038
+            {
2039
+                $msg = img_warning().' '.$langs->trans('CoreErrorMessage');
2040
+                print '<div class="error">'.$msg.'</div>';
2041
+            }
2045 2042
 
2046
-		print "\n\n";
2043
+            //define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
2044
+        }
2047 2045
 
2048
-		print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2046
+        print "\n\n";
2049 2047
 
2050
-		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2048
+        print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2051 2049
 
2052
-		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2050
+        if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2053 2051
 
2054
-		print "\n";
2055
-		if ($comment) print '<!-- '.$comment.' -->'."\n";
2052
+        if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2056 2053
 
2057
-		printCommonFooter($zone);
2054
+        print "\n";
2055
+        if ($comment) print '<!-- '.$comment.' -->'."\n";
2058 2056
 
2059
-		if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2057
+        printCommonFooter($zone);
2060 2058
 
2061
-		if (! empty($conf->use_javascript_ajax))
2062
-		{
2063
-			print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2064
-			print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
2065
-		}
2059
+        if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2066 2060
 
2067
-		// Wrapper to add log when clicking on download or preview
2068
-		if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069
-		{
2070
-			if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2071
-			{
2072
-				print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2073
-				?>
2061
+        if (! empty($conf->use_javascript_ajax))
2062
+        {
2063
+            print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2064
+            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
2065
+        }
2066
+
2067
+        // Wrapper to add log when clicking on download or preview
2068
+        if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069
+        {
2070
+            if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2071
+            {
2072
+                print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2073
+                ?>
2074 2074
     			<script type="text/javascript">
2075 2075
     			jQuery(document).ready(function () {
2076 2076
     				$('a.documentpreview').click(function() {
@@ -2094,14 +2094,14 @@  discard block
 block discarded – undo
2094 2094
     			});
2095 2095
     			</script>
2096 2096
 				<?php
2097
-			}
2098
-	   	}
2097
+            }
2098
+            }
2099 2099
 
2100
-		// A div for the address popup
2101
-		print "\n<!-- A div to allow dialog popup -->\n";
2102
-		print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2100
+        // A div for the address popup
2101
+        print "\n<!-- A div to allow dialog popup -->\n";
2102
+        print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
2103 2103
 
2104
-		print "</body>\n";
2105
-		print "</html>\n";
2106
-	}
2104
+        print "</body>\n";
2105
+        print "</html>\n";
2106
+    }
2107 2107
 }
Please login to merge, or discard this patch.
Spacing   +646 added lines, -646 removed lines patch added patch discarded remove patch
@@ -36,10 +36,10 @@  discard block
 block discarded – undo
36 36
 
37 37
 // For optional tuning. Enabled if environment variable MAIN_SHOW_TUNING_INFO is defined.
38 38
 $micro_start_time = 0;
39
-if (! empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
39
+if (!empty($_SERVER['MAIN_SHOW_TUNING_INFO']))
40 40
 {
41 41
 	list($usec, $sec) = explode(" ", microtime());
42
-	$micro_start_time=((float) $usec + (float) $sec);
42
+	$micro_start_time = ((float) $usec + (float) $sec);
43 43
 	// Add Xdebug code coverage
44 44
 	//define('XDEBUGCOVERAGE',1);
45 45
 	if (defined('XDEBUGCOVERAGE')) {
@@ -97,24 +97,24 @@  discard block
 block discarded – undo
97 97
 	// For SQL Injection (only GET are used to be included into bad escaped SQL requests)
98 98
 	if ($type == 1 || $type == 3)
99 99
 	{
100
-		$inj += preg_match('/delete\s+from/i',	 $val);
101
-		$inj += preg_match('/create\s+table/i',	 $val);
102
-		$inj += preg_match('/insert\s+into/i', 	 $val);
103
-		$inj += preg_match('/select\s+from/i', 	 $val);
104
-		$inj += preg_match('/into\s+(outfile|dumpfile)/i',  $val);
105
-		$inj += preg_match('/user\s*\(/i',  $val);						// avoid to use function user() that return current database login
106
-		$inj += preg_match('/information_schema/i',  $val);				// avoid to use request that read information_schema database
100
+		$inj += preg_match('/delete\s+from/i', $val);
101
+		$inj += preg_match('/create\s+table/i', $val);
102
+		$inj += preg_match('/insert\s+into/i', $val);
103
+		$inj += preg_match('/select\s+from/i', $val);
104
+		$inj += preg_match('/into\s+(outfile|dumpfile)/i', $val);
105
+		$inj += preg_match('/user\s*\(/i', $val); // avoid to use function user() that return current database login
106
+		$inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database
107 107
 	}
108 108
 	if ($type == 3)
109 109
 	{
110
-		$inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
110
+		$inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i', $val);
111 111
 	}
112 112
 	if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
113 113
 	{
114
-		$inj += preg_match('/updatexml\(/i', 	 $val);
115
-		$inj += preg_match('/update.+set.+=/i',  $val);
116
-		$inj += preg_match('/union.+select/i', 	 $val);
117
-		$inj += preg_match('/(\.\.%2f)+/i',		 $val);
114
+		$inj += preg_match('/updatexml\(/i', $val);
115
+		$inj += preg_match('/update.+set.+=/i', $val);
116
+		$inj += preg_match('/union.+select/i', $val);
117
+		$inj += preg_match('/(\.\.%2f)+/i', $val);
118 118
 	}
119 119
 	// For XSS Injection done by adding javascript with script
120 120
 	// This is all cases a browser consider text is javascript:
@@ -124,26 +124,26 @@  discard block
 block discarded – undo
124 124
 	$inj += preg_match('/<script/i', $val);
125 125
 	$inj += preg_match('/<iframe/i', $val);
126 126
 	$inj += preg_match('/<audio/i', $val);
127
-	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
-	if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
127
+	$inj += preg_match('/Set\.constructor/i', $val); // ECMA script 6
128
+	if (!defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
129 129
 	$inj += preg_match('/base[\s]+href/si', $val);
130
-	$inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
-	$inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
-	$inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
-	$inj += preg_match('/onload\s*=/i', $val);        // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
-	$inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
135
-	$inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
136
-	$inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
130
+	$inj += preg_match('/<.*onmouse/si', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131
+	$inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
132
+	$inj += preg_match('/onfocus\s*=/i', $val); // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
133
+	$inj += preg_match('/onload\s*=/i', $val); // onload can be set on svg tag <svg/onload=alert(1)> or other tag like body <body onload=alert(1)>
134
+	$inj += preg_match('/onloadstart\s*=/i', $val); // onload can be set on audio tag <audio onloadstart=alert(1)>
135
+	$inj += preg_match('/onclick\s*=/i', $val); // onclick can be set on img text html tag like <img onclick = alert(1)>
136
+	$inj += preg_match('/onscroll\s*=/i', $val); // onscroll can be on textarea
137 137
 	//$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
138
-	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);		// refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
138
+	$inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
139 139
 	//if ($type == 1)
140 140
 	//{
141 141
 		$inj += preg_match('/javascript:/i', $val);
142 142
 		$inj += preg_match('/vbscript:/i', $val);
143 143
 	//}
144 144
 	// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
-	if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
-	if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
145
+	if ($type == 1) $inj += preg_match('/"/i', $val); // We refused " in GET parameters value
146
+	if ($type == 2) $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces.
147 147
 	return $inj;
148 148
 }
149 149
 
@@ -180,34 +180,34 @@  discard block
 block discarded – undo
180 180
 
181 181
 
182 182
 // Check consistency of NOREQUIREXXX DEFINES
183
-if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && ! defined('NOREQUIREMENU'))
183
+if ((defined('NOREQUIREDB') || defined('NOREQUIRETRAN')) && !defined('NOREQUIREMENU'))
184 184
 {
185 185
 	print 'If define NOREQUIREDB or NOREQUIRETRAN are set, you must also set NOREQUIREMENU or not set them';
186 186
 	exit;
187 187
 }
188 188
 
189 189
 // Sanity check on URL
190
-if (! empty($_SERVER["PHP_SELF"]))
190
+if (!empty($_SERVER["PHP_SELF"]))
191 191
 {
192
-	$morevaltochecklikepost=array($_SERVER["PHP_SELF"]);
193
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost,2);
192
+	$morevaltochecklikepost = array($_SERVER["PHP_SELF"]);
193
+	analyseVarsForSqlAndScriptsInjection($morevaltochecklikepost, 2);
194 194
 }
195 195
 // Sanity check on GET parameters
196
-if (! defined('NOSCANGETFORINJECTION') && ! empty($_SERVER["QUERY_STRING"]))
196
+if (!defined('NOSCANGETFORINJECTION') && !empty($_SERVER["QUERY_STRING"]))
197 197
 {
198
-	$morevaltochecklikeget=array($_SERVER["QUERY_STRING"]);
199
-	analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget,1);
198
+	$morevaltochecklikeget = array($_SERVER["QUERY_STRING"]);
199
+	analyseVarsForSqlAndScriptsInjection($morevaltochecklikeget, 1);
200 200
 }
201 201
 // Sanity check on POST
202
-if (! defined('NOSCANPOSTFORINJECTION'))
202
+if (!defined('NOSCANPOSTFORINJECTION'))
203 203
 {
204
-	analyseVarsForSqlAndScriptsInjection($_POST,0);
204
+	analyseVarsForSqlAndScriptsInjection($_POST, 0);
205 205
 }
206 206
 
207 207
 // This is to make Dolibarr working with Plesk
208
-if (! empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
208
+if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs')
209 209
 {
210
-	set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
210
+	set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
211 211
 }
212 212
 
213 213
 // Include the conf.php and functions.lib.php
@@ -216,37 +216,37 @@  discard block
 block discarded – undo
216 216
 // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.
217 217
 // This is used for example by form of boxes to save personalization of some options.
218 218
 // DOL_AUTOSET_COOKIE=cookiename:val1,val2 and  cookiename_val1=aaa cookiename_val2=bbb will set cookie_name with value json_encode(array('val1'=> , ))
219
-if (! empty($_POST["DOL_AUTOSET_COOKIE"]))
219
+if (!empty($_POST["DOL_AUTOSET_COOKIE"]))
220 220
 {
221
-	$tmpautoset=explode(':',$_POST["DOL_AUTOSET_COOKIE"],2);
222
-	$tmplist=explode(',',$tmpautoset[1]);
223
-	$cookiearrayvalue=array();
221
+	$tmpautoset = explode(':', $_POST["DOL_AUTOSET_COOKIE"], 2);
222
+	$tmplist = explode(',', $tmpautoset[1]);
223
+	$cookiearrayvalue = array();
224 224
 	foreach ($tmplist as $tmpkey)
225 225
 	{
226
-		$postkey=$tmpautoset[0].'_'.$tmpkey;
226
+		$postkey = $tmpautoset[0].'_'.$tmpkey;
227 227
 		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
228
+		if (!empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey] = $_POST[$postkey];
229 229
 	}
230
-	$cookiename=$tmpautoset[0];
231
-	$cookievalue=json_encode($cookiearrayvalue);
230
+	$cookiename = $tmpautoset[0];
231
+	$cookievalue = json_encode($cookiearrayvalue);
232 232
 	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233
-	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
233
+	setcookie($cookiename, empty($cookievalue) ? '' : $cookievalue, empty($cookievalue) ? 0 : (time() + (86400 * 354)), '/', null, false, true); // keep cookie 1 year and add tag httponly
234 234
 	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
235 235
 }
236 236
 
237 237
 
238 238
 // Init session. Name of session is specific to Dolibarr instance.
239 239
 // Note: the function dol_getprefix may have been redefined to return a different key to manage another area to protect.
240
-$prefix=dol_getprefix('');
240
+$prefix = dol_getprefix('');
241 241
 
242
-$sessionname='DOLSESSID_'.$prefix;
243
-$sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
244
-if (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
242
+$sessionname = 'DOLSESSID_'.$prefix;
243
+$sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
244
+if (!empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]);
245 245
 session_name($sessionname);
246
-session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
246
+session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
247 247
 // This create lock, released when session_write_close() or end of page.
248 248
 // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
249
-if (! defined('NOSESSION'))
249
+if (!defined('NOSESSION'))
250 250
 {
251 251
 	session_start();
252 252
 	/*if (ini_get('register_globals'))    // Deprecated in 5.3 and removed in 5.4. To solve bug in using $_SESSION
@@ -267,40 +267,40 @@  discard block
 block discarded – undo
267 267
 // Detection browser
268 268
 if (isset($_SERVER["HTTP_USER_AGENT"]))
269 269
 {
270
-	$tmp=getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
-	$conf->browser->name=$tmp['browsername'];
272
-	$conf->browser->os=$tmp['browseros'];
273
-	$conf->browser->version=$tmp['browserversion'];
274
-	$conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
270
+	$tmp = getBrowserInfo($_SERVER["HTTP_USER_AGENT"]);
271
+	$conf->browser->name = $tmp['browsername'];
272
+	$conf->browser->os = $tmp['browseros'];
273
+	$conf->browser->version = $tmp['browserversion'];
274
+	$conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet'
275 275
 	//var_dump($conf->browser);
276 276
 
277
-	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
-	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
277
+	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover = 1;
278
+	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER = 1;
279 279
 }
280 280
 
281 281
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
282 282
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
283
-if (! empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
283
+if (!empty($conf->file->main_force_https) && (empty($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != 'on'))
284 284
 {
285
-	$newurl='';
285
+	$newurl = '';
286 286
 	if (is_numeric($conf->file->main_force_https))
287 287
 	{
288
-		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
288
+		if ($conf->file->main_force_https == '1' && !empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
289 289
 		{
290
-			if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
290
+			if (preg_match('/^http:/i', $_SERVER["SCRIPT_URI"]) && !preg_match('/^https:/i', $_SERVER["SCRIPT_URI"]))	// If link is http
291 291
 			{
292
-				$newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
292
+				$newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]);
293 293
 			}
294 294
 		}
295 295
 		else	// Check HTTPS environment variable (Apache/mod_ssl only)
296 296
 		{
297
-			$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
297
+			$newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298 298
 		}
299 299
 	}
300 300
 	else
301 301
 	{
302 302
 		// Check HTTPS environment variable (Apache/mod_ssl only)
303
-		$newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
303
+		$newurl = $conf->file->main_force_https.$_SERVER["REQUEST_URI"];
304 304
 	}
305 305
 	// Start redirect
306 306
 	if ($newurl)
@@ -315,20 +315,20 @@  discard block
 block discarded – undo
315 315
 	}
316 316
 }
317 317
 
318
-if (! defined('NOLOGIN') && ! defined('NOIPCHECK') && ! empty($dolibarr_main_restrict_ip))
318
+if (!defined('NOLOGIN') && !defined('NOIPCHECK') && !empty($dolibarr_main_restrict_ip))
319 319
 {
320
-	$listofip=explode(',', $dolibarr_main_restrict_ip);
320
+	$listofip = explode(',', $dolibarr_main_restrict_ip);
321 321
 	$found = false;
322
-	foreach($listofip as $ip)
322
+	foreach ($listofip as $ip)
323 323
 	{
324
-		$ip=trim($ip);
324
+		$ip = trim($ip);
325 325
 		if ($ip == $_SERVER['REMOTE_ADDR'])
326 326
 		{
327 327
 			$found = true;
328 328
 			break;
329 329
 		}
330 330
 	}
331
-	if (! $found)
331
+	if (!$found)
332 332
 	{
333 333
 		print 'Access refused by IP protection';
334 334
 		exit;
@@ -336,25 +336,25 @@  discard block
 block discarded – undo
336 336
 }
337 337
 
338 338
 // Loading of additional presentation includes
339
-if (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';	    // Need 660ko memory (800ko in 2.2)
340
-if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';	// Need 22ko memory
339
+if (!defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
340
+if (!defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; // Need 22ko memory
341 341
 
342 342
 // If install or upgrade process not done or not completely finished, we call the install page.
343
-if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
343
+if (!empty($conf->global->MAIN_NOT_INSTALLED) || !empty($conf->global->MAIN_NOT_UPGRADED))
344 344
 {
345 345
 	dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
346 346
 	header("Location: ".DOL_URL_ROOT."/install/index.php");
347 347
 	exit;
348 348
 }
349 349
 // If an upgrade process is required, we call the install page.
350
-if ((! empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
351
-|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ! empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
350
+if ((!empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && ($conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION))
351
+|| (empty($conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty($conf->global->MAIN_VERSION_LAST_INSTALL) && ($conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION)))
352 352
 {
353
-	$versiontocompare=empty($conf->global->MAIN_VERSION_LAST_UPGRADE)?$conf->global->MAIN_VERSION_LAST_INSTALL:$conf->global->MAIN_VERSION_LAST_UPGRADE;
354
-	require_once DOL_DOCUMENT_ROOT .'/core/lib/admin.lib.php';
355
-	$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356
-	$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357
-	$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
353
+	$versiontocompare = empty($conf->global->MAIN_VERSION_LAST_UPGRADE) ? $conf->global->MAIN_VERSION_LAST_INSTALL : $conf->global->MAIN_VERSION_LAST_UPGRADE;
354
+	require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
355
+	$dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
356
+	$dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
357
+	$rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
358 358
 	if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359 359
 	{
360 360
 		dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 }
365 365
 
366 366
 // Creation of a token against CSRF vulnerabilities
367
-if (! defined('NOTOKENRENEWAL'))
367
+if (!defined('NOTOKENRENEWAL'))
368 368
 {
369 369
 	// roulement des jetons car cree a chaque appel
370 370
 	if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
@@ -373,10 +373,10 @@  discard block
 block discarded – undo
373 373
 	$token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374 374
 	$_SESSION['newtoken'] = $token;
375 375
 }
376
-if ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
376
+if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
377 377
 	|| defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
378 378
 {
379
-	if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
379
+	if ($_SERVER['REQUEST_METHOD'] == 'POST' && !GETPOST('token', 'alpha')) // Note, offender can still send request by GET
380 380
 	{
381 381
 		print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
382 382
 		print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 	{
387 387
 		if (GETPOST('token', 'alpha') != $_SESSION['token'])
388 388
 		{
389
-			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
389
+			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action', 'aZ09').", _POST['token']=".GETPOST('token', 'alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
390 390
 			//print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391 391
 			unset($_POST);
392 392
 		}
@@ -394,20 +394,20 @@  discard block
 block discarded – undo
394 394
 }
395 395
 
396 396
 // Disable modules (this must be after session_start and after conf has been loaded)
397
-if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
398
-if (! empty($_SESSION["disablemodules"]))
397
+if (GETPOST('disablemodules', 'alpha'))  $_SESSION["disablemodules"] = GETPOST('disablemodules', 'alpha');
398
+if (!empty($_SESSION["disablemodules"]))
399 399
 {
400
-	$disabled_modules=explode(',',$_SESSION["disablemodules"]);
401
-	foreach($disabled_modules as $module)
400
+	$disabled_modules = explode(',', $_SESSION["disablemodules"]);
401
+	foreach ($disabled_modules as $module)
402 402
 	{
403 403
 		if ($module)
404 404
 		{
405
-			if (empty($conf->$module)) $conf->$module=new stdClass();
406
-			$conf->$module->enabled=false;
405
+			if (empty($conf->$module)) $conf->$module = new stdClass();
406
+			$conf->$module->enabled = false;
407 407
 			if ($module == 'fournisseur')		// Special case
408 408
 			{
409
-				$conf->supplier_order->enabled=0;
410
-				$conf->supplier_invoice->enabled=0;
409
+				$conf->supplier_order->enabled = 0;
410
+				$conf->supplier_invoice->enabled = 0;
411 411
 			}
412 412
 		}
413 413
 	}
@@ -416,8 +416,8 @@  discard block
 block discarded – undo
416 416
 /*
417 417
  * Phase authentication / login
418 418
  */
419
-$login='';
420
-if (! defined('NOLOGIN'))
419
+$login = '';
420
+if (!defined('NOLOGIN'))
421 421
 {
422 422
 	// $authmode lists the different means of identification to be tested in order of preference.
423 423
 	// Example: 'http', 'dolibarr', 'ldap', 'http,forceuser', '...'
@@ -429,93 +429,93 @@  discard block
 block discarded – undo
429 429
 	else
430 430
 	{
431 431
 		// Authentication mode
432
-		if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
432
+		if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'http,dolibarr';
433 433
 		// Authentication mode: forceuser
434
-		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
434
+		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto';
435 435
 	}
436 436
 	// Set authmode
437
-	$authmode=explode(',',$dolibarr_main_authentication);
437
+	$authmode = explode(',', $dolibarr_main_authentication);
438 438
 
439 439
 	// No authentication mode
440
-	if (! count($authmode))
440
+	if (!count($authmode))
441 441
 	{
442 442
 		$langs->load('main');
443
-		dol_print_error('',$langs->trans("ErrorConfigParameterNotDefined",'dolibarr_main_authentication'));
443
+		dol_print_error('', $langs->trans("ErrorConfigParameterNotDefined", 'dolibarr_main_authentication'));
444 444
 		exit;
445 445
 	}
446 446
 
447 447
 	// If login request was already post, we retrieve login from the session
448 448
 	// Call module if not realized that his request.
449 449
 	// At the end of this phase, the variable $login is defined.
450
-	$resultFetchUser='';
451
-	$test=true;
452
-	if (! isset($_SESSION["dol_login"]))
450
+	$resultFetchUser = '';
451
+	$test = true;
452
+	if (!isset($_SESSION["dol_login"]))
453 453
 	{
454 454
 		// It is not already authenticated and it requests the login / password
455 455
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
456 456
 
457
-		$dol_dst_observed=GETPOST("dst_observed",'int',3);
458
-		$dol_dst_first=GETPOST("dst_first",'int',3);
459
-		$dol_dst_second=GETPOST("dst_second",'int',3);
460
-		$dol_screenwidth=GETPOST("screenwidth",'int',3);
461
-		$dol_screenheight=GETPOST("screenheight",'int',3);
462
-		$dol_hide_topmenu=GETPOST('dol_hide_topmenu','int',3);
463
-		$dol_hide_leftmenu=GETPOST('dol_hide_leftmenu','int',3);
464
-		$dol_optimize_smallscreen=GETPOST('dol_optimize_smallscreen','int',3);
465
-		$dol_no_mouse_hover=GETPOST('dol_no_mouse_hover','int',3);
466
-		$dol_use_jmobile=GETPOST('dol_use_jmobile','int',3);
457
+		$dol_dst_observed = GETPOST("dst_observed", 'int', 3);
458
+		$dol_dst_first = GETPOST("dst_first", 'int', 3);
459
+		$dol_dst_second = GETPOST("dst_second", 'int', 3);
460
+		$dol_screenwidth = GETPOST("screenwidth", 'int', 3);
461
+		$dol_screenheight = GETPOST("screenheight", 'int', 3);
462
+		$dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int', 3);
463
+		$dol_hide_leftmenu = GETPOST('dol_hide_leftmenu', 'int', 3);
464
+		$dol_optimize_smallscreen = GETPOST('dol_optimize_smallscreen', 'int', 3);
465
+		$dol_no_mouse_hover = GETPOST('dol_no_mouse_hover', 'int', 3);
466
+		$dol_use_jmobile = GETPOST('dol_use_jmobile', 'int', 3);
467 467
 		//dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468 468
 
469 469
 		// If in demo mode, we check we go to home page through the public/demo/index.php page
470
-		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
470
+		if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
471 471
 		{
472
-			if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
472
+			if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER']))
473 473
 			{
474 474
 				dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
475
-				$url='';
476
-				$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477
-				$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
478
-				$url.=($url?'&':'').($dol_optimize_smallscreen?'dol_optimize_smallscreen='.$dol_optimize_smallscreen:'');
479
-				$url.=($url?'&':'').($dol_no_mouse_hover?'dol_no_mouse_hover='.$dol_no_mouse_hover:'');
480
-				$url.=($url?'&':'').($dol_use_jmobile?'dol_use_jmobile='.$dol_use_jmobile:'');
481
-				$url=DOL_URL_ROOT.'/public/demo/index.php'.($url?'?'.$url:'');
475
+				$url = '';
476
+				$url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : '');
477
+				$url .= ($url ? '&' : '').($dol_hide_leftmenu ? 'dol_hide_leftmenu='.$dol_hide_leftmenu : '');
478
+				$url .= ($url ? '&' : '').($dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$dol_optimize_smallscreen : '');
479
+				$url .= ($url ? '&' : '').($dol_no_mouse_hover ? 'dol_no_mouse_hover='.$dol_no_mouse_hover : '');
480
+				$url .= ($url ? '&' : '').($dol_use_jmobile ? 'dol_use_jmobile='.$dol_use_jmobile : '');
481
+				$url = DOL_URL_ROOT.'/public/demo/index.php'.($url ? '?'.$url : '');
482 482
 				header("Location: ".$url);
483 483
 				exit;
484 484
 			}
485 485
 		}
486 486
 
487 487
 		// Verification security graphic code
488
-		if (GETPOST("username","alpha",2) && ! empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
488
+		if (GETPOST("username", "alpha", 2) && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA))
489 489
 		{
490 490
 			$sessionkey = 'dol_antispam_value';
491
-			$ok=(array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
491
+			$ok = (array_key_exists($sessionkey, $_SESSION) === true && (strtolower($_SESSION[$sessionkey]) == strtolower($_POST['code'])));
492 492
 
493 493
 			// Check code
494
-			if (! $ok)
494
+			if (!$ok)
495 495
 			{
496 496
 				dol_syslog('Bad value for code, connexion refused');
497 497
 				// Load translation files required by page
498 498
 				$langs->loadLangs(array('main', 'errors'));
499 499
 
500
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadValueForCode");
501
-				$test=false;
500
+				$_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadValueForCode");
501
+				$test = false;
502 502
 
503 503
 				// Call trigger for the "security events" log
504
-				$user->trigger_mesg='ErrorBadValueForCode - login='.GETPOST("username","alpha",2);
504
+				$user->trigger_mesg = 'ErrorBadValueForCode - login='.GETPOST("username", "alpha", 2);
505 505
 				// Call of triggers
506
-				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
507
-				$interface=new Interfaces($db);
508
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
506
+				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
507
+				$interface = new Interfaces($db);
508
+				$result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
509 509
 				if ($result < 0) {
510 510
 					$error++;
511 511
 				}
512 512
 				// End Call of triggers
513 513
 
514 514
 				// Hooks on failed login
515
-				$action='';
515
+				$action = '';
516 516
 				$hookmanager->initHooks(array('login'));
517
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
517
+				$parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518
+				$reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
519 519
 				if ($reshook < 0) $error++;
520 520
 
521 521
 				// Note: exit is done later
@@ -524,22 +524,22 @@  discard block
 block discarded – undo
524 524
 
525 525
 		$allowedmethodtopostusername = 2;
526 526
 		if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
527
-		$usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528
-		$passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529
-		$entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
527
+		$usertotest = (!empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username", "alpha", $allowedmethodtopostusername));
528
+		$passwordtotest = GETPOST('password', 'none', $allowedmethodtopostusername);
529
+		$entitytotest = (GETPOST('entity', 'int') ? GETPOST('entity', 'int') : (!empty($conf->entity) ? $conf->entity : 1));
530 530
 
531 531
 		// Define if we received data to test the login.
532
-		$goontestloop=false;
533
-		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
-		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
-		if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
532
+		$goontestloop = false;
533
+		if (isset($_SERVER["REMOTE_USER"]) && in_array('http', $authmode)) $goontestloop = true;
534
+		if ($dolibarr_main_authentication == 'forceuser' && !empty($dolibarr_auto_user)) $goontestloop = true;
535
+		if (GETPOST("username", "alpha", $allowedmethodtopostusername) || !empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode', 'alpha', 1)) $goontestloop = true;
536 536
 
537
-		if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
537
+		if (!is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538 538
 		{
539 539
 			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
540
-			$langs=new Translate("",$conf);
541
-			$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
-			if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
540
+			$langs = new Translate("", $conf);
541
+			$langcode = (GETPOST('lang', 'aZ09', 1) ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT));
542
+			if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT');
543 543
 			$langs->setDefaultLang($langcode);
544 544
 		}
545 545
 
@@ -548,53 +548,53 @@  discard block
 block discarded – undo
548 548
 		// If error, we will put error message in session under the name dol_loginmesg
549 549
 		if ($test && $goontestloop)
550 550
 		{
551
-			$login = checkLoginPassEntity($usertotest,$passwordtotest,$entitytotest,$authmode);
551
+			$login = checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $authmode);
552 552
 			if ($login)
553 553
 			{
554
-				$dol_authmode=$conf->authmode;	// This properties is defined only when logged, to say what mode was successfully used
555
-				$dol_tz=$_POST["tz"];
556
-				$dol_tz_string=$_POST["tz_string"];
557
-				$dol_tz_string=preg_replace('/\s*\(.+\)$/','',$dol_tz_string);
558
-				$dol_tz_string=preg_replace('/,/','/',$dol_tz_string);
559
-				$dol_tz_string=preg_replace('/\s/','_',$dol_tz_string);
560
-				$dol_dst=0;
554
+				$dol_authmode = $conf->authmode; // This properties is defined only when logged, to say what mode was successfully used
555
+				$dol_tz = $_POST["tz"];
556
+				$dol_tz_string = $_POST["tz_string"];
557
+				$dol_tz_string = preg_replace('/\s*\(.+\)$/', '', $dol_tz_string);
558
+				$dol_tz_string = preg_replace('/,/', '/', $dol_tz_string);
559
+				$dol_tz_string = preg_replace('/\s/', '_', $dol_tz_string);
560
+				$dol_dst = 0;
561 561
 				if (isset($_POST["dst_first"]) && isset($_POST["dst_second"]))
562 562
 				{
563 563
 					include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
564
-					$datenow=dol_now();
565
-					$datefirst=dol_stringtotime($_POST["dst_first"]);
566
-					$datesecond=dol_stringtotime($_POST["dst_second"]);
567
-					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
564
+					$datenow = dol_now();
565
+					$datefirst = dol_stringtotime($_POST["dst_first"]);
566
+					$datesecond = dol_stringtotime($_POST["dst_second"]);
567
+					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst = 1;
568 568
 				}
569 569
 				//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570 570
 			}
571 571
 
572
-			if (! $login)
572
+			if (!$login)
573 573
 			{
574
-				dol_syslog('Bad password, connexion refused',LOG_DEBUG);
574
+				dol_syslog('Bad password, connexion refused', LOG_DEBUG);
575 575
 				// Load translation files required by page
576 576
 				$langs->loadLangs(array('main', 'errors'));
577 577
 
578 578
 				// Bad password. No authmode has found a good password.
579 579
 				// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
-				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
580
+				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword");
581 581
 
582 582
 				// Call trigger for the "security events" log
583
-				$user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
583
+				$user->trigger_mesg = $langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username", "alpha", 2);
584 584
 				// Call of triggers
585 585
 				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
586
-				$interface=new Interfaces($db);
587
-				$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf,GETPOST("username","alpha",2));
586
+				$interface = new Interfaces($db);
587
+				$result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf, GETPOST("username", "alpha", 2));
588 588
 				if ($result < 0) {
589 589
 					$error++;
590 590
 				}
591 591
 				// End Call of triggers
592 592
 
593 593
 				// Hooks on failed login
594
-				$action='';
594
+				$action = '';
595 595
 				$hookmanager->initHooks(array('login'));
596
-				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
-				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
596
+				$parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597
+				$reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
598 598
 				if ($reshook < 0) $error++;
599 599
 
600 600
 				// Note: exit is done in next chapter
@@ -602,118 +602,118 @@  discard block
 block discarded – undo
602 602
 		}
603 603
 
604 604
 		// End test login / passwords
605
-		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
605
+		if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606 606
 		{
607 607
 			// No data to test login, so we show the login page
608 608
 			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609 609
 			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
-			else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
610
+			else dol_loginfunction($langs, $conf, (!empty($mysoc) ? $mysoc : ''));
611 611
 			exit;
612 612
 		}
613 613
 
614
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
614
+		$resultFetchUser = $user->fetch('', $login, '', 1, ($entitytotest > 0 ? $entitytotest : -1));
615 615
 		if ($resultFetchUser <= 0)
616 616
 		{
617 617
 			dol_syslog('User not found, connexion refused');
618 618
 			session_destroy();
619 619
 			session_name($sessionname);
620
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
621
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
620
+			session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
621
+			session_start(); // Fixing the bug of register_globals here is useless since session is empty
622 622
 
623 623
 			if ($resultFetchUser == 0)
624 624
 			{
625 625
 				// Load translation files required by page
626 626
 				$langs->loadLangs(array('main', 'errors'));
627 627
 
628
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
628
+				$_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
629 629
 
630
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
630
+				$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
631 631
 			}
632 632
 			if ($resultFetchUser < 0)
633 633
 			{
634
-				$_SESSION["dol_loginmesg"]=$user->error;
634
+				$_SESSION["dol_loginmesg"] = $user->error;
635 635
 
636
-				$user->trigger_mesg=$user->error;
636
+				$user->trigger_mesg = $user->error;
637 637
 			}
638 638
 
639 639
 			// Call triggers for the "security events" log
640
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
641
-			$interface=new Interfaces($db);
642
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
640
+			include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
641
+			$interface = new Interfaces($db);
642
+			$result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
643 643
 			if ($result < 0) {
644 644
 				$error++;
645 645
 			}
646 646
 			// End call triggers
647 647
 
648 648
 			// Hooks on failed login
649
-			$action='';
649
+			$action = '';
650 650
 			$hookmanager->initHooks(array('login'));
651
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
651
+			$parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652
+			$reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
653 653
 			if ($reshook < 0) $error++;
654 654
 
655
-			$paramsurl=array();
656
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
659
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
655
+			$paramsurl = array();
656
+			if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
657
+			if (GETPOST('nojs', 'int'))        $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
658
+			if (GETPOST('lang', 'aZ09'))       $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
659
+			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
660 660
 			exit;
661 661
 		}
662 662
 	}
663 663
 	else
664 664
 	{
665 665
 		// We are already into an authenticated session
666
-		$login=$_SESSION["dol_login"];
667
-		$entity=$_SESSION["dol_entity"];
666
+		$login = $_SESSION["dol_login"];
667
+		$entity = $_SESSION["dol_entity"];
668 668
 		dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
669 669
 
670
-		$resultFetchUser=$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
670
+		$resultFetchUser = $user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
671 671
 		if ($resultFetchUser <= 0)
672 672
 		{
673 673
 			// Account has been removed after login
674 674
 			dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
675 675
 			session_destroy();
676 676
 			session_name($sessionname);
677
-			session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
678
-			session_start();    // Fixing the bug of register_globals here is useless since session is empty
677
+			session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
678
+			session_start(); // Fixing the bug of register_globals here is useless since session is empty
679 679
 
680 680
 			if ($resultFetchUser == 0)
681 681
 			{
682 682
 				// Load translation files required by page
683 683
 				$langs->loadLangs(array('main', 'errors'));
684 684
 
685
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorCantLoadUserFromDolibarrDatabase",$login);
685
+				$_SESSION["dol_loginmesg"] = $langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
686 686
 
687
-				$user->trigger_mesg='ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
687
+				$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
688 688
 			}
689 689
 			if ($resultFetchUser < 0)
690 690
 			{
691
-				$_SESSION["dol_loginmesg"]=$user->error;
691
+				$_SESSION["dol_loginmesg"] = $user->error;
692 692
 
693
-				$user->trigger_mesg=$user->error;
693
+				$user->trigger_mesg = $user->error;
694 694
 			}
695 695
 
696 696
 			// Call triggers for the "security events" log
697
-			include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
698
-			$interface=new Interfaces($db);
699
-			$result=$interface->run_triggers('USER_LOGIN_FAILED',$user,$user,$langs,$conf);
697
+			include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
698
+			$interface = new Interfaces($db);
699
+			$result = $interface->run_triggers('USER_LOGIN_FAILED', $user, $user, $langs, $conf);
700 700
 			if ($result < 0) {
701 701
 				$error++;
702 702
 			}
703 703
 			// End call triggers
704 704
 
705 705
 			// Hooks on failed login
706
-			$action='';
706
+			$action = '';
707 707
 			$hookmanager->initHooks(array('login'));
708
-			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
-			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
708
+			$parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709
+			$reshook = $hookmanager->executeHooks('afterLoginFailed', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
710 710
 			if ($reshook < 0) $error++;
711 711
 
712
-			$paramsurl=array();
713
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
716
-			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
712
+			$paramsurl = array();
713
+			if (GETPOST('textbrowser', 'int')) $paramsurl[] = 'textbrowser='.GETPOST('textbrowser', 'int');
714
+			if (GETPOST('nojs', 'int'))        $paramsurl[] = 'nojs='.GETPOST('nojs', 'int');
715
+			if (GETPOST('lang', 'aZ09'))       $paramsurl[] = 'lang='.GETPOST('lang', 'aZ09');
716
+			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
717 717
 			exit;
718 718
 		}
719 719
 		else
@@ -722,35 +722,35 @@  discard block
 block discarded – undo
722 722
 		    $hookmanager->initHooks(array('main'));
723 723
 
724 724
 		    // Code for search criteria persistence.
725
-		    if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
725
+		    if (!empty($_GET['save_lastsearch_values']))    // We must use $_GET here
726 726
 		    {
727
-			    $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
728
-			    $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
727
+			    $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]);
728
+			    $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
729 729
 			    // Clean $relativepathstring
730
-   			    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
730
+   			    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
731 731
 			    $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732 732
 			    $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733 733
 			    //var_dump($relativepathstring);
734 734
 
735 735
 			    // We click on a link that leave a page we have to save search criteria, contextpage, limit and page. We save them from tmp to no tmp
736
-			    if (! empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
736
+			    if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring]))
737 737
 			    {
738
-			    	$_SESSION['lastsearch_values_'.$relativepathstring]=$_SESSION['lastsearch_values_tmp_'.$relativepathstring];
738
+			    	$_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
739 739
 				    unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
740 740
 			    }
741
-			    if (! empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
741
+			    if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]))
742 742
 			    {
743
-			    	$_SESSION['lastsearch_contextpage_'.$relativepathstring]=$_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
743
+			    	$_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
744 744
 			    	unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
745 745
 			    }
746
-			    if (! empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
746
+			    if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1)
747 747
 			    {
748
-			    	$_SESSION['lastsearch_page_'.$relativepathstring]=$_SESSION['lastsearch_page_tmp_'.$relativepathstring];
748
+			    	$_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring];
749 749
 			    	unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
750 750
 			    }
751
-			    if (! empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
751
+			    if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != $conf->liste_limit)
752 752
 			    {
753
-			    	$_SESSION['lastsearch_limit_'.$relativepathstring]=$_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
753
+			    	$_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
754 754
 			    	unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
755 755
 			    }
756 756
 		    }
@@ -765,30 +765,30 @@  discard block
 block discarded – undo
765 765
 
766 766
 	// Is it a new session that has started ?
767 767
 	// If we are here, this means authentication was successfull.
768
-	if (! isset($_SESSION["dol_login"]))
768
+	if (!isset($_SESSION["dol_login"]))
769 769
 	{
770 770
 		// New session for this login has started.
771
-		$error=0;
771
+		$error = 0;
772 772
 
773 773
 		// Store value into session (values always stored)
774
-		$_SESSION["dol_login"]=$user->login;
775
-		$_SESSION["dol_authmode"]=isset($dol_authmode)?$dol_authmode:'';
776
-		$_SESSION["dol_tz"]=isset($dol_tz)?$dol_tz:'';
777
-		$_SESSION["dol_tz_string"]=isset($dol_tz_string)?$dol_tz_string:'';
778
-		$_SESSION["dol_dst"]=isset($dol_dst)?$dol_dst:'';
779
-		$_SESSION["dol_dst_observed"]=isset($dol_dst_observed)?$dol_dst_observed:'';
780
-		$_SESSION["dol_dst_first"]=isset($dol_dst_first)?$dol_dst_first:'';
781
-		$_SESSION["dol_dst_second"]=isset($dol_dst_second)?$dol_dst_second:'';
782
-		$_SESSION["dol_screenwidth"]=isset($dol_screenwidth)?$dol_screenwidth:'';
783
-		$_SESSION["dol_screenheight"]=isset($dol_screenheight)?$dol_screenheight:'';
784
-		$_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785
-		$_SESSION["dol_entity"]=$conf->entity;
774
+		$_SESSION["dol_login"] = $user->login;
775
+		$_SESSION["dol_authmode"] = isset($dol_authmode) ? $dol_authmode : '';
776
+		$_SESSION["dol_tz"] = isset($dol_tz) ? $dol_tz : '';
777
+		$_SESSION["dol_tz_string"] = isset($dol_tz_string) ? $dol_tz_string : '';
778
+		$_SESSION["dol_dst"] = isset($dol_dst) ? $dol_dst : '';
779
+		$_SESSION["dol_dst_observed"] = isset($dol_dst_observed) ? $dol_dst_observed : '';
780
+		$_SESSION["dol_dst_first"] = isset($dol_dst_first) ? $dol_dst_first : '';
781
+		$_SESSION["dol_dst_second"] = isset($dol_dst_second) ? $dol_dst_second : '';
782
+		$_SESSION["dol_screenwidth"] = isset($dol_screenwidth) ? $dol_screenwidth : '';
783
+		$_SESSION["dol_screenheight"] = isset($dol_screenheight) ? $dol_screenheight : '';
784
+		$_SESSION["dol_company"] = $conf->global->MAIN_INFO_SOCIETE_NOM;
785
+		$_SESSION["dol_entity"] = $conf->entity;
786 786
 		// Store value into session (values stored only if defined)
787
-		if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
-		if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
-		if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
-		if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
-		if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
787
+		if (!empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu'] = $dol_hide_topmenu;
788
+		if (!empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu'] = $dol_hide_leftmenu;
789
+		if (!empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen'] = $dol_optimize_smallscreen;
790
+		if (!empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover'] = $dol_no_mouse_hover;
791
+		if (!empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
792 792
 
793 793
 		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794 794
 
@@ -801,26 +801,26 @@  discard block
 block discarded – undo
801 801
 		// Call triggers for the "security events" log
802 802
 		$user->trigger_mesg = $loginfo;
803 803
 		// Call triggers
804
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
805
-		$interface=new Interfaces($db);
806
-		$result=$interface->run_triggers('USER_LOGIN',$user,$user,$langs,$conf);
804
+		include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
805
+		$interface = new Interfaces($db);
806
+		$result = $interface->run_triggers('USER_LOGIN', $user, $user, $langs, $conf);
807 807
 		if ($result < 0) {
808 808
 			$error++;
809 809
 		}
810 810
 		// End call triggers
811 811
 
812 812
 		// Hooks on successfull login
813
-		$action='';
813
+		$action = '';
814 814
 		$hookmanager->initHooks(array('login'));
815
-		$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
-		$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
815
+		$parameters = array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816
+		$reshook = $hookmanager->executeHooks('afterLogin', $parameters, $user, $action); // Note that $action and $object may have been modified by some hooks
817 817
 		if ($reshook < 0) $error++;
818 818
 
819 819
 		if ($error)
820 820
 		{
821 821
 			$db->rollback();
822 822
 			session_destroy();
823
-			dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
823
+			dol_print_error($db, 'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824 824
 			exit;
825 825
 		}
826 826
 		else
@@ -829,10 +829,10 @@  discard block
 block discarded – undo
829 829
 		}
830 830
 
831 831
 		// Change landing page if defined.
832
-		$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
-		if (! empty($landingpage))    // Example: /index.php
832
+		$landingpage = (empty($user->conf->MAIN_LANDING_PAGE) ? (empty($conf->global->MAIN_LANDING_PAGE) ? '' : $conf->global->MAIN_LANDING_PAGE) : $user->conf->MAIN_LANDING_PAGE);
833
+		if (!empty($landingpage))    // Example: /index.php
834 834
 		{
835
-			$newpath=dol_buildpath($landingpage, 1);
835
+			$newpath = dol_buildpath($landingpage, 1);
836 836
 			if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
837 837
 			{
838 838
 				header('Location: '.$newpath);
@@ -845,12 +845,12 @@  discard block
 block discarded – undo
845 845
 	// If user admin, we force the rights-based modules
846 846
 	if ($user->admin)
847 847
 	{
848
-		$user->rights->user->user->lire=1;
849
-		$user->rights->user->user->creer=1;
850
-		$user->rights->user->user->password=1;
851
-		$user->rights->user->user->supprimer=1;
852
-		$user->rights->user->self->creer=1;
853
-		$user->rights->user->self->password=1;
848
+		$user->rights->user->user->lire = 1;
849
+		$user->rights->user->user->creer = 1;
850
+		$user->rights->user->user->password = 1;
851
+		$user->rights->user->user->supprimer = 1;
852
+		$user->rights->user->self->creer = 1;
853
+		$user->rights->user->self->password = 1;
854 854
 	}
855 855
 
856 856
 	/*
@@ -858,73 +858,73 @@  discard block
 block discarded – undo
858 858
      */
859 859
 
860 860
 	// Set liste_limit
861
-	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
-	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
861
+	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT; // Can be 0
862
+	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE; // Can be 0
863 863
 
864 864
 	// Replace conf->css by personalized value if theme not forced
865
-	if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
865
+	if (empty($conf->global->MAIN_FORCETHEME) && !empty($user->conf->MAIN_THEME))
866 866
 	{
867
-		$conf->theme=$user->conf->MAIN_THEME;
867
+		$conf->theme = $user->conf->MAIN_THEME;
868 868
 		$conf->css  = "/theme/".$conf->theme."/style.css.php";
869 869
 	}
870 870
 }
871 871
 
872 872
 // Case forcing style from url
873
-if (GETPOST('theme','alpha'))
873
+if (GETPOST('theme', 'alpha'))
874 874
 {
875
-	$conf->theme=GETPOST('theme','alpha',1);
875
+	$conf->theme = GETPOST('theme', 'alpha', 1);
876 876
 	$conf->css  = "/theme/".$conf->theme."/style.css.php";
877 877
 }
878 878
 
879 879
 
880 880
 // Set javascript option
881
-if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
881
+if (!GETPOST('nojs', 'int'))   // If javascript was not disabled on URL
882 882
 {
883
-	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
883
+	if (!empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884 884
 	{
885
-		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
885
+		$conf->use_javascript_ajax = !$user->conf->MAIN_DISABLE_JAVASCRIPT;
886 886
 	}
887 887
 }
888
-else $conf->use_javascript_ajax=0;
888
+else $conf->use_javascript_ajax = 0;
889 889
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
890
-if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
890
+if (GETPOST('textbrowser', 'int') || (!empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || !empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
891 891
 {
892
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
892
+	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = 1;
893 893
 }
894
-elseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
894
+elseif (!empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
895 895
 {
896
-	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
896
+	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER = $user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
897 897
 }
898 898
 
899 899
 // Set terminal output option according to conf->browser.
900
-if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu=1;
901
-if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu=1;
902
-if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;
903
-if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover=1;
904
-if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
905
-if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
906
-if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
907
-	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
-	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
900
+if (GETPOST('dol_hide_leftmenu', 'int') || !empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu = 1;
901
+if (GETPOST('dol_hide_topmenu', 'int') || !empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu = 1;
902
+if (GETPOST('dol_optimize_smallscreen', 'int') || !empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen = 1;
903
+if (GETPOST('dol_no_mouse_hover', 'int') || !empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover = 1;
904
+if (GETPOST('dol_use_jmobile', 'int') || !empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile = 1;
905
+if (!empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover = 1;
906
+if ((!empty($conf->browser->layout) && $conf->browser->layout == 'phone')
907
+	|| (!empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908
+	|| (!empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
909 909
 )
910 910
 {
911
-	$conf->dol_optimize_smallscreen=1;
911
+	$conf->dol_optimize_smallscreen = 1;
912 912
 }
913 913
 // If we force to use jmobile, then we reenable javascript
914
-if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
914
+if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1;
915 915
 // Replace themes bugged with jmobile with eldy
916
-if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
916
+if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea', 'cameleo', 'amarok')))
917 917
 {
918
-	$conf->theme='eldy';
919
-	$conf->css  =  "/theme/".$conf->theme."/style.css.php";
918
+	$conf->theme = 'eldy';
919
+	$conf->css  = "/theme/".$conf->theme."/style.css.php";
920 920
 }
921 921
 
922
-if (! defined('NOREQUIRETRAN'))
922
+if (!defined('NOREQUIRETRAN'))
923 923
 {
924
-	if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
924
+	if (!GETPOST('lang', 'aZ09'))	// If language was not forced on URL
925 925
 	{
926 926
 		// If user has chosen its own language
927
-		if (! empty($user->conf->MAIN_LANG_DEFAULT))
927
+		if (!empty($user->conf->MAIN_LANG_DEFAULT))
928 928
 		{
929 929
 			// If different than current language
930 930
 			//print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT;
@@ -936,11 +936,11 @@  discard block
 block discarded – undo
936 936
 	}
937 937
 }
938 938
 
939
-if (! defined('NOLOGIN'))
939
+if (!defined('NOLOGIN'))
940 940
 {
941 941
 	// If the login is not recovered, it is identified with an account that does not exist.
942 942
 	// Hacking attempt?
943
-	if (! $user->login) accessforbidden();
943
+	if (!$user->login) accessforbidden();
944 944
 
945 945
 	// Check if user is active
946 946
 	if ($user->statut < 1)
@@ -957,88 +957,88 @@  discard block
 block discarded – undo
957 957
 }
958 958
 
959 959
 
960
-dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action','az09').', massaction='.GETPOST('massaction','az09'));
960
+dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.GETPOST('action', 'az09').', massaction='.GETPOST('massaction', 'az09'));
961 961
 //Another call for easy debugg
962 962
 //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
963 963
 
964 964
 // Load main languages files
965
-if (! defined('NOREQUIRETRAN'))
965
+if (!defined('NOREQUIRETRAN'))
966 966
 {
967 967
 	// Load translation files required by page
968 968
 	$langs->loadLangs(array('main', 'dict'));
969 969
 }
970 970
 
971 971
 // Define some constants used for style of arrays
972
-$bc=array(0=>'class="impair"',1=>'class="pair"');
973
-$bcdd=array(0=>'class="drag drop oddeven"',1=>'class="drag drop oddeven"');
974
-$bcnd=array(0=>'class="nodrag nodrop nohover"',1=>'class="nodrag nodrop nohoverpair"');		// Used for tr to add new lines
975
-$bctag=array(0=>'class="impair tagtr"',1=>'class="pair tagtr"');
972
+$bc = array(0=>'class="impair"', 1=>'class="pair"');
973
+$bcdd = array(0=>'class="drag drop oddeven"', 1=>'class="drag drop oddeven"');
974
+$bcnd = array(0=>'class="nodrag nodrop nohover"', 1=>'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines
975
+$bctag = array(0=>'class="impair tagtr"', 1=>'class="pair tagtr"');
976 976
 
977 977
 // Define messages variables
978
-$mesg=''; $warning=''; $error=0;
978
+$mesg = ''; $warning = ''; $error = 0;
979 979
 // deprecated, see setEventMessages() and dol_htmloutput_events()
980
-$mesgs=array(); $warnings=array(); $errors=array();
980
+$mesgs = array(); $warnings = array(); $errors = array();
981 981
 
982 982
 // Constants used to defined number of lines in textarea
983 983
 if (empty($conf->browser->firefox))
984 984
 {
985
-	define('ROWS_1',1);
986
-	define('ROWS_2',2);
987
-	define('ROWS_3',3);
988
-	define('ROWS_4',4);
989
-	define('ROWS_5',5);
990
-	define('ROWS_6',6);
991
-	define('ROWS_7',7);
992
-	define('ROWS_8',8);
993
-	define('ROWS_9',9);
985
+	define('ROWS_1', 1);
986
+	define('ROWS_2', 2);
987
+	define('ROWS_3', 3);
988
+	define('ROWS_4', 4);
989
+	define('ROWS_5', 5);
990
+	define('ROWS_6', 6);
991
+	define('ROWS_7', 7);
992
+	define('ROWS_8', 8);
993
+	define('ROWS_9', 9);
994 994
 }
995 995
 else
996 996
 {
997
-	define('ROWS_1',0);
998
-	define('ROWS_2',1);
999
-	define('ROWS_3',2);
1000
-	define('ROWS_4',3);
1001
-	define('ROWS_5',4);
1002
-	define('ROWS_6',5);
1003
-	define('ROWS_7',6);
1004
-	define('ROWS_8',7);
1005
-	define('ROWS_9',8);
997
+	define('ROWS_1', 0);
998
+	define('ROWS_2', 1);
999
+	define('ROWS_3', 2);
1000
+	define('ROWS_4', 3);
1001
+	define('ROWS_5', 4);
1002
+	define('ROWS_6', 5);
1003
+	define('ROWS_7', 6);
1004
+	define('ROWS_8', 7);
1005
+	define('ROWS_9', 8);
1006 1006
 }
1007 1007
 
1008
-$heightforframes=50;
1008
+$heightforframes = 50;
1009 1009
 
1010 1010
 // Init menu manager
1011
-if (! defined('NOREQUIREMENU'))
1011
+if (!defined('NOREQUIREMENU'))
1012 1012
 {
1013 1013
 	if (empty($user->societe_id))    // If internal user or not defined
1014 1014
 	{
1015
-		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1015
+		$conf->standard_menu = (empty($conf->global->MAIN_MENU_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENU_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENU_STANDARD) : $conf->global->MAIN_MENU_STANDARD_FORCED);
1016 1016
 	}
1017 1017
 	else                        // If external user
1018 1018
 	{
1019
-		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1019
+		$conf->standard_menu = (empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED) ? (empty($conf->global->MAIN_MENUFRONT_STANDARD) ? 'eldy_menu.php' : $conf->global->MAIN_MENUFRONT_STANDARD) : $conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020 1020
 	}
1021 1021
 
1022 1022
 	// Load the menu manager (only if not already done)
1023
-	$file_menu=$conf->standard_menu;
1024
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1025
-	if (! class_exists('MenuManager'))
1023
+	$file_menu = $conf->standard_menu;
1024
+	if (GETPOST('menu', 'alpha')) $file_menu = GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php
1025
+	if (!class_exists('MenuManager'))
1026 1026
 	{
1027
-		$menufound=0;
1028
-		$dirmenus=array_merge(array("/core/menus/"),(array) $conf->modules_parts['menus']);
1029
-		foreach($dirmenus as $dirmenu)
1027
+		$menufound = 0;
1028
+		$dirmenus = array_merge(array("/core/menus/"), (array) $conf->modules_parts['menus']);
1029
+		foreach ($dirmenus as $dirmenu)
1030 1030
 		{
1031
-			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
1031
+			$menufound = dol_include_once($dirmenu."standard/".$file_menu);
1032 1032
 			if (class_exists('MenuManager')) break;
1033 1033
 		}
1034
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1034
+		if (!class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1035 1035
 		{
1036 1036
 			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1037
-			$file_menu='eldy_menu.php';
1037
+			$file_menu = 'eldy_menu.php';
1038 1038
 			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039 1039
 		}
1040 1040
 	}
1041
-	$menumanager = new MenuManager($db, empty($user->societe_id)?0:1);
1041
+	$menumanager = new MenuManager($db, empty($user->societe_id) ? 0 : 1);
1042 1042
 	$menumanager->loadMenu();
1043 1043
 }
1044 1044
 
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 
1047 1047
 // Functions
1048 1048
 
1049
-if (! function_exists("llxHeader"))
1049
+if (!function_exists("llxHeader"))
1050 1050
 {
1051 1051
 	/**
1052 1052
 	 *	Show HTML header HTML + BODY + Top menu + left menu + DIV
@@ -1066,24 +1066,24 @@  discard block
 block discarded – undo
1066 1066
 	 * @param	string	$replacemainareaby	Replace call to main_area() by a print of this string
1067 1067
 	 * @return	void
1068 1068
 	 */
1069
-	function llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='')
1069
+	function llxHeader($head = '', $title = '', $help_url = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $morecssonbody = '', $replacemainareaby = '')
1070 1070
 	{
1071 1071
 		global $conf;
1072 1072
 
1073 1073
 		// html header
1074 1074
 		top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
1075 1075
 
1076
-		print '<body id="mainbody"'.($morecssonbody?' class="'.$morecssonbody.'"':'').'>' . "\n";
1076
+		print '<body id="mainbody"'.($morecssonbody ? ' class="'.$morecssonbody.'"' : '').'>'."\n";
1077 1077
 
1078 1078
 		// top menu and left menu area
1079
-		if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int'))
1079
+		if (empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int'))
1080 1080
 		{
1081 1081
 			top_menu($head, $title, $target, $disablejs, $disablehead, $arrayofjs, $arrayofcss, $morequerystring, $help_url);
1082 1082
 		}
1083 1083
 
1084 1084
 		if (empty($conf->dol_hide_leftmenu))
1085 1085
 		{
1086
-			left_menu('', $help_url, '', '', 1, $title, 1);		// $menumanager is retreived with a global $menumanager inside this function
1086
+			left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retreived with a global $menumanager inside this function
1087 1087
 		}
1088 1088
 
1089 1089
 		// main area
@@ -1104,17 +1104,17 @@  discard block
 block discarded – undo
1104 1104
  *  @param	int		$forcenocache	Force disabling of cache for the page
1105 1105
  *  @return	void
1106 1106
  */
1107
-function top_httphead($contenttype='text/html', $forcenocache=0)
1107
+function top_httphead($contenttype = 'text/html', $forcenocache = 0)
1108 1108
 {
1109 1109
 	global $db, $conf, $hookmanager;
1110 1110
 
1111
-	if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1111
+	if ($contenttype == 'text/html') header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112 1112
 	else header("Content-Type: ".$contenttype);
1113 1113
 	// Security options
1114
-	header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
-	header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
1114
+	header("X-Content-Type-Options: nosniff"); // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115
+	header("X-Frame-Options: SAMEORIGIN"); // Frames allowed only if on same domain (stop some XSS attacks)
1116 1116
 	//header("X-XSS-Protection: 1");      		// XSS protection of some browsers (note: use of Content-Security-Policy is more efficient). Disabled as deprecated.
1117
-	if (! defined('FORCECSP'))
1117
+	if (!defined('FORCECSP'))
1118 1118
 	{
1119 1119
 		//if (! isset($conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY))
1120 1120
 		//{
@@ -1124,15 +1124,15 @@  discard block
 block discarded – undo
1124 1124
 		//else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125 1125
 		$contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126 1126
 
1127
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1127
+		if (!is_object($hookmanager)) $hookmanager = new HookManager($db);
1128 1128
 		$hookmanager->initHooks("main");
1129 1129
 
1130
-		$parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
-		$result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
-		if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
-		else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1130
+		$parameters = array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131
+		$result = $hookmanager->executeHooks('setContentSecurityPolicy', $parameters); // Note that $action and $object may have been modified by some hooks
1132
+		if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint; // Replace CSP
1133
+		else $contentsecuritypolicy .= $hookmanager->resPrint; // Concat CSP
1134 1134
 
1135
-		if (! empty($contentsecuritypolicy))
1135
+		if (!empty($contentsecuritypolicy))
1136 1136
 		{
1137 1137
 			// For example, to restrict 'script', 'object', 'frames' or 'img' to some domains:
1138 1138
 			// script-src https://api.google.com https://anotherhost.com; object-src https://youtube.com; frame-src https://youtube.com; img-src: https://static.example.com
@@ -1169,111 +1169,111 @@  discard block
 block discarded – undo
1169 1169
  * @param   int     $disablenofollow Disable no follow tag
1170 1170
  * @return	void
1171 1171
  */
1172
-function top_htmlhead($head, $title='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $disablejmobile=0, $disablenofollow=0)
1172
+function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $disablejmobile = 0, $disablenofollow = 0)
1173 1173
 {
1174 1174
 	global $db, $conf, $langs, $user, $hookmanager;
1175 1175
 
1176 1176
 	top_httphead();
1177 1177
 
1178
-	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1178
+	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php'; // If not defined, eldy by default
1179 1179
 
1180 1180
 	print '<!doctype html>'."\n";
1181 1181
 
1182
-	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
-	else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1182
+	if (!empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang, 0, 2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
+	else print '<html lang="'.substr($langs->defaultlang, 0, 2).'">'."\n";
1184 1184
 	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185 1185
 	if (empty($disablehead))
1186 1186
 	{
1187
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1187
+		$ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1188 1188
 
1189 1189
 		print "<head>\n";
1190 1190
 
1191
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1191
+		if (GETPOST('dol_basehref', 'alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref', 'alpha')).'">'."\n";
1192 1192
 
1193 1193
 		// Displays meta
1194 1194
 		print '<meta charset="UTF-8">'."\n";
1195
-		print '<meta name="robots" content="noindex'.($disablenofollow?'':',nofollow').'">'."\n";	// Do not index
1196
-		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";		// Scale for mobile device
1195
+		print '<meta name="robots" content="noindex'.($disablenofollow ? '' : ',nofollow').'">'."\n"; // Do not index
1196
+		print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n"; // Scale for mobile device
1197 1197
 		print '<meta name="author" content="Dolibarr Development Team">'."\n";
1198 1198
 
1199 1199
 		// Favicon
1200
-		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
-		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
-		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1200
+		$favicon = dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico', 1);
1201
+		if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL;
1202
+		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n"; // Not required into an Android webview
1203 1203
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204 1204
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205 1205
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1206 1206
 
1207 1207
 		// Auto refresh page
1208
-		if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1208
+		if (GETPOST('autorefresh', 'int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh', 'int').'">';
1209 1209
 
1210 1210
 		// Displays title
1211
-		$appli=constant('DOL_APPLICATION_TITLE');
1212
-		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1211
+		$appli = constant('DOL_APPLICATION_TITLE');
1212
+		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli = $conf->global->MAIN_APPLICATION_TITLE;
1213 1213
 
1214 1214
 		print '<title>';
1215
-		$titletoshow='';
1216
-		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1215
+		$titletoshow = '';
1216
+		if ($title && !empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/', $conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217 1217
 		else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218 1218
 		else $titletoshow = dol_htmlentities($appli);
1219 1219
 
1220
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1220
+		if (!is_object($hookmanager)) $hookmanager = new HookManager($db);
1221 1221
 		$hookmanager->initHooks("main");
1222
-		$parameters=array('title'=>$titletoshow);
1223
-		$result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
-		if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
-		else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1222
+		$parameters = array('title'=>$titletoshow);
1223
+		$result = $hookmanager->executeHooks('setHtmlTitle', $parameters); // Note that $action and $object may have been modified by some hooks
1224
+		if ($result > 0) $titletoshow = $hookmanager->resPrint; // Replace Title to show
1225
+		else $titletoshow .= $hookmanager->resPrint; // Concat to Title to show
1226 1226
 
1227 1227
 		print $titletoshow;
1228 1228
 		print '</title>';
1229 1229
 
1230 1230
 		print "\n";
1231 1231
 
1232
-		if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
-		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1232
+		if (GETPOST('version', 'int')) $ext = 'version='.GETPOST('version', 'int'); // usefull to force no cache on css/js
1233
+		if (GETPOST('testmenuhider', 'int') || !empty($conf->global->MAIN_TESTMENUHIDER)) $ext .= '&testmenuhider='.(GETPOST('testmenuhider', 'int') ?GETPOST('testmenuhider', 'int') : $conf->global->MAIN_TESTMENUHIDER);
1234 1234
 
1235
-		$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
-		$themeparam.=($ext?'&amp;'.$ext:'');
1237
-		if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
-		if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239
-		if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240
-		if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
1241
-		if (GETPOST('dol_no_mouse_hover','int'))         { $themeparam.='&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover','int'); }
1242
-		if (GETPOST('dol_use_jmobile','int'))            { $themeparam.='&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile','int'); $conf->dol_use_jmobile=GETPOST('dol_use_jmobile','int'); }
1235
+		$themeparam = '?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss', 'aZ09') ? '&amp;optioncss='.GETPOST('optioncss', 'aZ09', 1) : '').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236
+		$themeparam .= ($ext ? '&amp;'.$ext : '');
1237
+		if (!empty($_SESSION['dol_resetcache'])) $themeparam .= '&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1238
+		if (GETPOST('dol_hide_topmenu', 'int')) { $themeparam .= '&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu', 'int'); }
1239
+		if (GETPOST('dol_hide_leftmenu', 'int')) { $themeparam .= '&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu', 'int'); }
1240
+		if (GETPOST('dol_optimize_smallscreen', 'int')) { $themeparam .= '&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen', 'int'); }
1241
+		if (GETPOST('dol_no_mouse_hover', 'int')) { $themeparam .= '&amp;dol_no_mouse_hover='.GETPOST('dol_no_mouse_hover', 'int'); }
1242
+		if (GETPOST('dol_use_jmobile', 'int')) { $themeparam .= '&amp;dol_use_jmobile='.GETPOST('dol_use_jmobile', 'int'); $conf->dol_use_jmobile = GETPOST('dol_use_jmobile', 'int'); }
1243 1243
 
1244
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && $conf->use_javascript_ajax)
1244
+		if (!defined('DISABLE_JQUERY') && !$disablejs && $conf->use_javascript_ajax)
1245 1245
 		{
1246 1246
 			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247 1247
 			$jquerytheme = 'base';
1248 1248
 			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
-			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
-			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
-			if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
-			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1249
+			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
1250
+			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext ? '?'.$ext : '').'">'."\n"; // JQuery
1251
+			if (!defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext ? '?'.$ext : '').'">'."\n"; // JNotify
1252
+			if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253 1253
 			{
1254
-				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
-				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1254
+				$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1255
+				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext ? '?'.$ext : '').'">'."\n";
1256 1256
 			}
1257 1257
 		}
1258 1258
 
1259
-		if (! defined('DISABLE_FONT_AWSOME'))
1259
+		if (!defined('DISABLE_FONT_AWSOME'))
1260 1260
 		{
1261 1261
 			print '<!-- Includes CSS for font awesome -->'."\n";
1262
-			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext?'?'.$ext:'').'">'."\n";
1262
+			print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/theme/common/fontawesome/css/font-awesome.min.css'.($ext ? '?'.$ext : '').'">'."\n";
1263 1263
 		}
1264 1264
 
1265 1265
 		print '<!-- Includes CSS for Dolibarr theme -->'."\n";
1266 1266
 		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267
-		$themepath=dol_buildpath($conf->css,1);
1268
-		$themesubdir='';
1269
-		if (! empty($conf->modules_parts['theme']))	// This slow down
1267
+		$themepath = dol_buildpath($conf->css, 1);
1268
+		$themesubdir = '';
1269
+		if (!empty($conf->modules_parts['theme']))	// This slow down
1270 1270
 		{
1271
-			foreach($conf->modules_parts['theme'] as $reldir)
1271
+			foreach ($conf->modules_parts['theme'] as $reldir)
1272 1272
 			{
1273 1273
 				if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274 1274
 				{
1275
-					$themepath=dol_buildpath($reldir.$conf->css, 1);
1276
-					$themesubdir=$reldir;
1275
+					$themepath = dol_buildpath($reldir.$conf->css, 1);
1276
+					$themesubdir = $reldir;
1277 1277
 					break;
1278 1278
 				}
1279 1279
 			}
@@ -1281,22 +1281,22 @@  discard block
 block discarded – undo
1281 1281
 
1282 1282
 		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283 1283
 		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
-		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1284
+		if (!empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1285 1285
 
1286 1286
 		// CSS forced by modules (relative url starting with /)
1287
-		if (! empty($conf->modules_parts['css']))
1287
+		if (!empty($conf->modules_parts['css']))
1288 1288
 		{
1289
-			$arraycss=(array) $conf->modules_parts['css'];
1290
-			foreach($arraycss as $modcss => $filescss)
1289
+			$arraycss = (array) $conf->modules_parts['css'];
1290
+			foreach ($arraycss as $modcss => $filescss)
1291 1291
 			{
1292
-				$filescss=(array) $filescss;	// To be sure filecss is an array
1293
-				foreach($filescss as $cssfile)
1292
+				$filescss = (array) $filescss; // To be sure filecss is an array
1293
+				foreach ($filescss as $cssfile)
1294 1294
 				{
1295 1295
 					if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1296 1296
 					// cssfile is a relative path
1297
-					print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1297
+					print '<!-- Includes CSS added by module '.$modcss.' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile, 1);
1298 1298
 					// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
-					if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1299
+					if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1300 1300
 					print '">'."\n";
1301 1301
 				}
1302 1302
 			}
@@ -1304,137 +1304,137 @@  discard block
 block discarded – undo
1304 1304
 		// CSS forced by page in top_htmlhead call (relative url starting with /)
1305 1305
 		if (is_array($arrayofcss))
1306 1306
 		{
1307
-			foreach($arrayofcss as $cssfile)
1307
+			foreach ($arrayofcss as $cssfile)
1308 1308
 			{
1309
-				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1309
+				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile, 1);
1310 1310
 				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
-				if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1311
+				if (!preg_match('/\.css$/i', $cssfile)) print $themeparam;
1312 1312
 				print '">'."\n";
1313 1313
 			}
1314 1314
 		}
1315 1315
 
1316 1316
 		// Output standard javascript links
1317
-		if (! defined('DISABLE_JQUERY') && ! $disablejs && ! empty($conf->use_javascript_ajax))
1317
+		if (!defined('DISABLE_JQUERY') && !$disablejs && !empty($conf->use_javascript_ajax))
1318 1318
 		{
1319 1319
 			// JQuery. Must be before other includes
1320 1320
 			print '<!-- Includes JS for JQuery -->'."\n";
1321
-			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1323
-			if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1321
+			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1322
+			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1323
+			if (!empty($conf->global->MAIN_FEATURES_LEVEL) && !defined('JS_JQUERY_MIGRATE_DISABLED'))
1324 1324
 			{
1325
-				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
-				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1325
+				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1326
+				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1327 1327
 			}
1328
-			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
-			if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1328
+			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1329
+			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1330
+			if (!defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1331 1331
 			// jQuery jnotify
1332
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1332
+			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY'))
1333 1333
 			{
1334
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1334
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1335 1335
 			}
1336 1336
 			// Flot
1337
-			if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && ! defined('DISABLE_JQUERY_FLOT'))
1337
+			if (empty($conf->global->MAIN_DISABLE_JQUERY_FLOT) && !defined('DISABLE_JQUERY_FLOT'))
1338 1338
 			{
1339 1339
 				if (constant('JS_JQUERY_FLOT'))
1340 1340
 				{
1341
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343
-					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1341
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1342
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1343
+					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1344 1344
 				}
1345 1345
 				else
1346 1346
 				{
1347
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1349
-					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1347
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1348
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1349
+					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.stack.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1350 1350
 				}
1351 1351
 			}
1352 1352
 			// jQuery jeditable
1353
-			if (! empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && ! defined('DISABLE_JQUERY_JEDITABLE'))
1353
+			if (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE) && !defined('DISABLE_JQUERY_JEDITABLE'))
1354 1354
 			{
1355 1355
 				print '<!-- JS to manage editInPlace feature -->'."\n";
1356
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1357
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1358
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1356
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1357
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-datepicker.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1358
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ui-autocomplete.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1359 1359
 				print '<script type="text/javascript">'."\n";
1360 1360
 				print 'var urlSaveInPlace = \''.DOL_URL_ROOT.'/core/ajax/saveinplace.php\';'."\n";
1361 1361
 				print 'var urlLoadInPlace = \''.DOL_URL_ROOT.'/core/ajax/loadinplace.php\';'."\n";
1362
-				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n";	// Added in title attribute of span
1363
-				print 'var placeholderInPlace = \'&nbsp;\';'."\n";	// If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1362
+				print 'var tooltipInPlace = \''.$langs->transnoentities('ClickToEdit').'\';'."\n"; // Added in title attribute of span
1363
+				print 'var placeholderInPlace = \'&nbsp;\';'."\n"; // If we put another string than $langs->trans("ClickToEdit") here, nothing is shown. If we put empty string, there is error, Why ?
1364 1364
 				print 'var cancelInPlace = \''.$langs->trans('Cancel').'\';'."\n";
1365 1365
 				print 'var submitInPlace = \''.$langs->trans('Ok').'\';'."\n";
1366 1366
 				print 'var indicatorInPlace = \'<img src="'.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'">\';'."\n";
1367
-				print 'var withInPlace = 300;';		// width in pixel for default string edit
1367
+				print 'var withInPlace = 300;'; // width in pixel for default string edit
1368 1368
 				print '</script>'."\n";
1369
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1370
-				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1369
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/editinplace.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1370
+				print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jeditable/jquery.jeditable.ckeditor.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1371 1371
 			}
1372 1372
             // jQuery Timepicker
1373
-            if (! empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1373
+            if (!empty($conf->global->MAIN_USE_JQUERY_TIMEPICKER) || defined('REQUIRE_JQUERY_TIMEPICKER'))
1374 1374
             {
1375
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1375
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1376
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext ? '&amp;'.$ext : '').'"></script>'."\n";
1377 1377
             }
1378
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1378
+            if (!defined('DISABLE_SELECT2') && (!empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1379 1379
             {
1380
-            	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1380
+            	$tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT;
1381
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext ? '?'.$ext : '').'"></script>'."\n"; // We include full because we need the support of containerCssClass
1382 1382
             }
1383
-            if (! defined('DISABLE_MULTISELECT'))     // jQuery plugin "mutiselect" to select with checkboxes
1383
+            if (!defined('DISABLE_MULTISELECT'))     // jQuery plugin "mutiselect" to select with checkboxes
1384 1384
             {
1385
-            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1385
+            	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext ? '?'.$ext : '').'"></script>'."\n";
1386 1386
             }
1387 1387
 		}
1388 1388
 
1389
-        if (! $disablejs && ! empty($conf->use_javascript_ajax))
1389
+        if (!$disablejs && !empty($conf->use_javascript_ajax))
1390 1390
         {
1391 1391
             // CKEditor
1392
-            if (! empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && ! defined('DISABLE_CKEDITOR'))
1392
+            if (!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR'))
1393 1393
             {
1394 1394
                 print '<!-- Includes JS for CKEditor -->'."\n";
1395
-                $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1396
-                $jsckeditor='ckeditor.js';
1395
+                $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/';
1396
+                $jsckeditor = 'ckeditor.js';
1397 1397
                 if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1398 1398
                 {
1399
-                	$pathckeditor=constant('JS_CKEDITOR');
1399
+                	$pathckeditor = constant('JS_CKEDITOR');
1400 1400
                 }
1401 1401
                 print '<script type="text/javascript">';
1402 1402
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1403
-                print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
1403
+                print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext ? '?'.$ext : ''), 1).'\';'."\n"; // $themesubdir='' in standard usage
1404 1404
                 print 'var ckeditorFilebrowserBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1405 1405
                 print 'var ckeditorFilebrowserImageBrowseUrl = \''.DOL_URL_ROOT.'/core/filemanagerdol/browser/default/browser.php?Type=Image&Connector='.DOL_URL_ROOT.'/core/filemanagerdol/connectors/php/connector.php\';'."\n";
1406 1406
                 print '</script>'."\n";
1407
-                print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext?'?'.$ext:'').'"></script>'."\n";
1407
+                print '<script type="text/javascript" src="'.$pathckeditor.$jsckeditor.($ext ? '?'.$ext : '').'"></script>'."\n";
1408 1408
             }
1409 1409
 
1410 1410
             // Browser notifications
1411
-            if (! defined('DISABLE_BROWSER_NOTIF'))
1411
+            if (!defined('DISABLE_BROWSER_NOTIF'))
1412 1412
             {
1413
-                $enablebrowsernotif=false;
1414
-                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1415
-                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1413
+                $enablebrowsernotif = false;
1414
+                if (!empty($conf->agenda->enabled) && !empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif = true;
1415
+                if ($conf->browser->layout == 'phone') $enablebrowsernotif = false;
1416 1416
                 if ($enablebrowsernotif)
1417 1417
                 {
1418 1418
                     print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
1419
-                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext?'?'.$ext:'').'"></script>'."\n";
1419
+                    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_notification.js.php'.($ext ? '?'.$ext : '').'"></script>'."\n";
1420 1420
                 }
1421 1421
             }
1422 1422
 
1423 1423
             // Global js function
1424 1424
             print '<!-- Includes JS of Dolibarr -->'."\n";
1425
-            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
1425
+            print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
1426 1426
 
1427 1427
             // JS forced by modules (relative url starting with /)
1428
-            if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1428
+            if (!empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1429 1429
         	{
1430
-        		$arrayjs=(array) $conf->modules_parts['js'];
1431
-	            foreach($arrayjs as $modjs => $filesjs)
1430
+        		$arrayjs = (array) $conf->modules_parts['js'];
1431
+	            foreach ($arrayjs as $modjs => $filesjs)
1432 1432
 	            {
1433
-        			$filesjs=(array) $filesjs;	// To be sure filejs is an array
1434
-		            foreach($filesjs as $jsfile)
1433
+        			$filesjs = (array) $filesjs; // To be sure filejs is an array
1434
+		            foreach ($filesjs as $jsfile)
1435 1435
 		            {
1436 1436
 	    	    		// jsfile is a relative path
1437
-	        	    	print '<!-- Include JS added by module '.$modjs. '-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1437
+	        	    	print '<!-- Include JS added by module '.$modjs.'-->'."\n".'<script type="text/javascript" src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1438 1438
 		            }
1439 1439
 	            }
1440 1440
         	}
@@ -1442,27 +1442,27 @@  discard block
 block discarded – undo
1442 1442
             if (is_array($arrayofjs))
1443 1443
             {
1444 1444
                 print '<!-- Includes JS added by page -->'."\n";
1445
-                foreach($arrayofjs as $jsfile)
1445
+                foreach ($arrayofjs as $jsfile)
1446 1446
                 {
1447
-                    if (preg_match('/^http/i',$jsfile))
1447
+                    if (preg_match('/^http/i', $jsfile))
1448 1448
                     {
1449 1449
                         print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1450 1450
                     }
1451 1451
                     else
1452 1452
                     {
1453
-                        print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1453
+                        print '<script type="text/javascript" src="'.dol_buildpath($jsfile, 1).'"></script>'."\n";
1454 1454
                     }
1455 1455
                 }
1456 1456
             }
1457 1457
         }
1458 1458
 
1459
-        if (! empty($head)) print $head."\n";
1460
-        if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1459
+        if (!empty($head)) print $head."\n";
1460
+        if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1461 1461
 
1462 1462
         print "</head>\n\n";
1463 1463
     }
1464 1464
 
1465
-    $conf->headerdone=1;	// To tell header was output
1465
+    $conf->headerdone = 1; // To tell header was output
1466 1466
 }
1467 1467
 
1468 1468
 
@@ -1482,19 +1482,19 @@  discard block
 block discarded – undo
1482 1482
  * 						                    For other external page: http://server/url
1483 1483
  *  @return		void
1484 1484
  */
1485
-function top_menu($head, $title='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $helppagename='')
1485
+function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead = 0, $arrayofjs = '', $arrayofcss = '', $morequerystring = '', $helppagename = '')
1486 1486
 {
1487 1487
 	global $user, $conf, $langs, $db;
1488 1488
 	global $dolibarr_main_authentication, $dolibarr_main_demo;
1489
-	global $hookmanager,$menumanager;
1489
+	global $hookmanager, $menumanager;
1490 1490
 
1491
-	$searchform='';
1492
-	$bookmarks='';
1491
+	$searchform = '';
1492
+	$bookmarks = '';
1493 1493
 
1494 1494
 	// Instantiate hooks of thirdparty module
1495 1495
 	$hookmanager->initHooks(array('toprightmenu'));
1496 1496
 
1497
-	$toprightmenu='';
1497
+	$toprightmenu = '';
1498 1498
 
1499 1499
 	// For backward compatibility with old modules
1500 1500
 	if (empty($conf->headerdone))
@@ -1506,49 +1506,49 @@  discard block
 block discarded – undo
1506 1506
 	/*
1507 1507
      * Top menu
1508 1508
      */
1509
-	if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu','int')) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1509
+	if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
1510 1510
 	{
1511 1511
 		print "\n".'<!-- Start top horizontal -->'."\n";
1512 1512
 
1513
-		print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu','int')?' hidden':'').'"><div id="id-top">';		// dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1513
+		print '<div class="side-nav-vert'.(GETPOST('dol_invisible_topmenu', 'int') ? ' hidden' : '').'"><div id="id-top">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
1514 1514
 
1515 1515
 		// Show menu entries
1516
-		print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT)?'':'invert').'" class="tmenu">'."\n";
1517
-		$menumanager->atarget=$target;
1518
-		$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks));      // This contains a \n
1516
+		print '<div id="tmenu_tooltip'.(empty($conf->global->MAIN_MENU_INVERT) ? '' : 'invert').'" class="tmenu">'."\n";
1517
+		$menumanager->atarget = $target;
1518
+		$menumanager->showmenu('top', array('searchform'=>$searchform, 'bookmarks'=>$bookmarks)); // This contains a \n
1519 1519
 		print "</div>\n";
1520 1520
 
1521 1521
 		// Define link to login card
1522
-		$appli=constant('DOL_APPLICATION_TITLE');
1523
-		if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1522
+		$appli = constant('DOL_APPLICATION_TITLE');
1523
+		if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1524 1524
 		{
1525
-			$appli=$conf->global->MAIN_APPLICATION_TITLE;
1525
+			$appli = $conf->global->MAIN_APPLICATION_TITLE;
1526 1526
 			if (preg_match('/\d\.\d/', $appli))
1527 1527
 			{
1528
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1528
+				if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1529 1529
 			}
1530
-			else $appli.=" ".DOL_VERSION;
1530
+			else $appli .= " ".DOL_VERSION;
1531 1531
 		}
1532
-		else $appli.=" ".DOL_VERSION;
1532
+		else $appli .= " ".DOL_VERSION;
1533 1533
 
1534
-		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1534
+		if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1535 1535
 
1536
-		$logouttext='';
1536
+		$logouttext = '';
1537 1537
 		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1538 1538
 		{
1539 1539
 			//$logouthtmltext=$appli.'<br>';
1540 1540
 			if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http')
1541 1541
 			{
1542
-				$logouthtmltext.=$langs->trans("Logout").'<br>';
1542
+				$logouthtmltext .= $langs->trans("Logout").'<br>';
1543 1543
 
1544
-				$logouttext .='<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1544
+				$logouttext .= '<a accesskey="l" href="'.DOL_URL_ROOT.'/user/logout.php">';
1545 1545
 				//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546
-				$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547
-				$logouttext .='</a>';
1546
+				$logouttext .= '<span class="fa fa-sign-out atoplogin"></span>';
1547
+				$logouttext .= '</a>';
1548 1548
 			}
1549 1549
 			else
1550 1550
 			{
1551
-				$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1551
+				$logouthtmltext .= $langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
1552 1552
 				$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1553 1553
 			}
1554 1554
 		}
@@ -1556,60 +1556,60 @@  discard block
 block discarded – undo
1556 1556
 		print '<div class="login_block">'."\n";
1557 1557
 
1558 1558
 		// Add login user link
1559
-		$toprightmenu.='<div class="login_block_user">';
1559
+		$toprightmenu .= '<div class="login_block_user">';
1560 1560
 
1561 1561
 		// Login name with photo and tooltip
1562
-		$mode=-1;
1563
-		$toprightmenu.='<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
-		$toprightmenu.=$user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1),'atoplogin');
1565
-		$toprightmenu.='</div></div>';
1562
+		$mode = -1;
1563
+		$toprightmenu .= '<div class="inline-block nowrap"><div class="inline-block login_block_elem login_block_elem_name" style="padding: 0px;">';
1564
+		$toprightmenu .= $user->getNomUrl($mode, '', 1, 0, 11, 0, ($user->firstname ? 'firstname' : -1), 'atoplogin');
1565
+		$toprightmenu .= '</div></div>';
1566 1566
 
1567
-		$toprightmenu.='</div>'."\n";
1567
+		$toprightmenu .= '</div>'."\n";
1568 1568
 
1569
-		$toprightmenu.='<div class="login_block_other">';
1569
+		$toprightmenu .= '<div class="login_block_other">';
1570 1570
 
1571 1571
 		// Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
1572
-		$parameters=array();
1573
-		$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1572
+		$parameters = array();
1573
+		$result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
1574 1574
 		if (is_numeric($result))
1575 1575
 		{
1576 1576
 			if ($result == 0)
1577
-				$toprightmenu.=$hookmanager->resPrint;		// add
1577
+				$toprightmenu .= $hookmanager->resPrint; // add
1578 1578
 			else
1579
-				$toprightmenu=$hookmanager->resPrint;						// replace
1579
+				$toprightmenu = $hookmanager->resPrint; // replace
1580 1580
 		}
1581 1581
 		else
1582 1582
 		{
1583
-			$toprightmenu.=$result;	// For backward compatibility
1583
+			$toprightmenu .= $result; // For backward compatibility
1584 1584
 		}
1585 1585
 
1586 1586
 		// Link to module builder
1587
-		if (! empty($conf->modulebuilder->enabled))
1587
+		if (!empty($conf->modulebuilder->enabled))
1588 1588
 		{
1589
-			$text ='<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1589
+			$text = '<a href="'.DOL_URL_ROOT.'/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
1590 1590
 			//$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
1591
-			$text.='<span class="fa fa-bug atoplogin"></span>';
1592
-			$text.='</a>';
1593
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("ModuleBuilder"),2,1,$text,'login_block_elem',2);
1591
+			$text .= '<span class="fa fa-bug atoplogin"></span>';
1592
+			$text .= '</a>';
1593
+			$toprightmenu .= @Form::textwithtooltip('', $langs->trans("ModuleBuilder"), 2, 1, $text, 'login_block_elem', 2);
1594 1594
 		}
1595 1595
 
1596 1596
 		// Link to print main content area
1597 1597
 		if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone')
1598 1598
 		{
1599
-			$qs=dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1599
+			$qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]);
1600 1600
 
1601 1601
 			if (is_array($_POST))
1602 1602
 			{
1603
-				foreach($_POST as $key=>$value) {
1604
-					if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1603
+				foreach ($_POST as $key=>$value) {
1604
+					if ($key !== 'action' && $key !== 'password' && !is_array($value)) $qs .= '&'.$key.'='.urlencode($value);
1605 1605
 				}
1606 1606
 			}
1607
-			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
1608
-			$text ='<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs?'&':'').'optioncss=print" target="_blank">';
1607
+			$qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
1608
+			$text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank">';
1609 1609
 			//$text.= img_picto(":".$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
1610
-			$text.='<span class="fa fa-print atoplogin"></span>';
1611
-			$text.='</a>';
1612
-			$toprightmenu.=@Form::textwithtooltip('',$langs->trans("PrintContentArea"),2,1,$text,'login_block_elem',2);
1610
+			$text .= '<span class="fa fa-print atoplogin"></span>';
1611
+			$text .= '</a>';
1612
+			$toprightmenu .= @Form::textwithtooltip('', $langs->trans("PrintContentArea"), 2, 1, $text, 'login_block_elem', 2);
1613 1613
 		}
1614 1614
 
1615 1615
 		// Link to Dolibarr wiki pages
@@ -1617,51 +1617,51 @@  discard block
 block discarded – undo
1617 1617
 		{
1618 1618
 			$langs->load("help");
1619 1619
 
1620
-			$helpbaseurl='';
1621
-			$helppage='';
1622
-			$mode='';
1620
+			$helpbaseurl = '';
1621
+			$helppage = '';
1622
+			$mode = '';
1623 1623
 
1624
-			if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1624
+			if (empty($helppagename)) $helppagename = 'EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1625 1625
 
1626 1626
 			// Get helpbaseurl, helppage and mode from helppagename and langs
1627
-			$arrayres=getHelpParamFor($helppagename,$langs);
1628
-			$helpbaseurl=$arrayres['helpbaseurl'];
1629
-			$helppage=$arrayres['helppage'];
1630
-			$mode=$arrayres['mode'];
1627
+			$arrayres = getHelpParamFor($helppagename, $langs);
1628
+			$helpbaseurl = $arrayres['helpbaseurl'];
1629
+			$helppage = $arrayres['helppage'];
1630
+			$mode = $arrayres['mode'];
1631 1631
 
1632 1632
 			// Link to help pages
1633 1633
 			if ($helpbaseurl && $helppage)
1634 1634
 			{
1635
-				$text='';
1636
-	            if(!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1635
+				$text = '';
1636
+	            if (!empty($conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
1637 1637
                     $langs->load('admin');
1638
-                    $appli .= '<br>' . $langs->trans("Database") . ': ' . $db->database_name;
1638
+                    $appli .= '<br>'.$langs->trans("Database").': '.$db->database_name;
1639 1639
                 }
1640
-				$title=$appli.'<br>';
1641
-				$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
-				if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1643
-				$text.='<a class="help" target="_blank" rel="noopener" href="';
1644
-				if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
-				else $text.=sprintf($helpbaseurl,$helppage);
1646
-				$text.='">';
1640
+				$title = $appli.'<br>';
1641
+				$title .= $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage');
1642
+				if ($mode == 'wiki') $title .= ' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage, '_', ' ')).'&quot;';
1643
+				$text .= '<a class="help" target="_blank" rel="noopener" href="';
1644
+				if ($mode == 'wiki') $text .= sprintf($helpbaseurl, urlencode(html_entity_decode($helppage)));
1645
+				else $text .= sprintf($helpbaseurl, $helppage);
1646
+				$text .= '">';
1647 1647
 				//$text.=img_picto('', 'helpdoc_top').' ';
1648
-				$text.='<span class="fa fa-question-circle atoplogin"></span>';
1648
+				$text .= '<span class="fa fa-question-circle atoplogin"></span>';
1649 1649
 				//$toprightmenu.=$langs->trans($mode == 'wiki' ? 'OnlineHelp': 'Help');
1650 1650
 				//if ($mode == 'wiki') $text.=' ('.dol_trunc(strtr($helppage,'_',' '),8).')';
1651
-				$text.='</a>';
1651
+				$text .= '</a>';
1652 1652
 				//$toprightmenu.='</div>'."\n";
1653
-				$toprightmenu.=@Form::textwithtooltip('',$title,2,1,$text,'login_block_elem',2);
1653
+				$toprightmenu .= @Form::textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2);
1654 1654
 			}
1655 1655
 		}
1656 1656
 
1657 1657
 		// Logout link
1658
-		$toprightmenu.=@Form::textwithtooltip('',$logouthtmltext,2,1,$logouttext,'login_block_elem',2);
1658
+		$toprightmenu .= @Form::textwithtooltip('', $logouthtmltext, 2, 1, $logouttext, 'login_block_elem', 2);
1659 1659
 
1660
-		$toprightmenu.='</div>';
1660
+		$toprightmenu .= '</div>';
1661 1661
 
1662 1662
 		print $toprightmenu;
1663 1663
 
1664
-		print "</div>\n";		// end div class="login_block"
1664
+		print "</div>\n"; // end div class="login_block"
1665 1665
 
1666 1666
 		print '</div></div>';
1667 1667
 
@@ -1669,7 +1669,7 @@  discard block
 block discarded – undo
1669 1669
 		print "<!-- End top horizontal menu -->\n\n";
1670 1670
 	}
1671 1671
 
1672
-	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1672
+	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss ? ' '.$morecss : '').'">';
1673 1673
 }
1674 1674
 
1675 1675
 
@@ -1687,87 +1687,87 @@  discard block
 block discarded – undo
1687 1687
  *  @param  string  $acceptdelayedhtml          1 if caller request to have html delayed content not returned but saved into global $delayedhtmlcontent (so caller can show it at end of page to avoid flash FOUC effect)
1688 1688
  *  @return	void
1689 1689
  */
1690
-function left_menu($menu_array_before, $helppagename='', $notused='', $menu_array_after='', $leftmenuwithoutmainarea=0, $title='', $acceptdelayedhtml=0)
1690
+function left_menu($menu_array_before, $helppagename = '', $notused = '', $menu_array_after = '', $leftmenuwithoutmainarea = 0, $title = '', $acceptdelayedhtml = 0)
1691 1691
 {
1692 1692
 	global $user, $conf, $langs, $db, $form;
1693 1693
 	global $hookmanager, $menumanager;
1694 1694
 
1695
-	$searchform='';
1696
-	$bookmarks='';
1695
+	$searchform = '';
1696
+	$bookmarks = '';
1697 1697
 
1698
-	if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1698
+	if (!empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1699 1699
 
1700
-	if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1700
+	if (empty($conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU')))
1701 1701
 	{
1702 1702
 		// Instantiate hooks of thirdparty module
1703
-		$hookmanager->initHooks(array('searchform','leftblock'));
1703
+		$hookmanager->initHooks(array('searchform', 'leftblock'));
1704 1704
 
1705 1705
 		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1706 1706
 
1707
-		if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1707
+		if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1708 1708
 
1709 1709
 		print "\n";
1710 1710
 
1711
-		if (! is_object($form)) $form=new Form($db);
1712
-		$selected=-1;
1713
-		$usedbyinclude=1;
1714
-		include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
1711
+		if (!is_object($form)) $form = new Form($db);
1712
+		$selected = -1;
1713
+		$usedbyinclude = 1;
1714
+		include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php'; // This set $arrayresult
1715 1715
 
1716 1716
 		if ($conf->use_javascript_ajax && empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1717 1717
 		{
1718 1718
 			//$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
-			$searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719
+			$searchform .= $form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY) ? 1 : 0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720 1720
 		}
1721 1721
 		else
1722 1722
 		{
1723
-			foreach($arrayresult as $key => $val)
1723
+			foreach ($arrayresult as $key => $val)
1724 1724
 			{
1725 1725
 				//$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth100', 'sall', $val['shortcut'], 'searchleft', img_picto('',$val['img']));
1726
-				$searchform.=printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1726
+				$searchform .= printSearchForm($val['url'], $val['url'], $val['label'], 'maxwidth125', 'sall', $val['shortcut'], 'searchleft', img_picto('', $val['img'], '', false, 1, 1));
1727 1727
 			}
1728 1728
 		}
1729 1729
 
1730 1730
 		// Execute hook printSearchForm
1731
-		$parameters=array('searchform'=>$searchform);
1732
-		$reshook=$hookmanager->executeHooks('printSearchForm',$parameters);    // Note that $action and $object may have been modified by some hooks
1731
+		$parameters = array('searchform'=>$searchform);
1732
+		$reshook = $hookmanager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
1733 1733
 		if (empty($reshook))
1734 1734
 		{
1735
-			$searchform.=$hookmanager->resPrint;
1735
+			$searchform .= $hookmanager->resPrint;
1736 1736
 		}
1737
-		else $searchform=$hookmanager->resPrint;
1737
+		else $searchform = $hookmanager->resPrint;
1738 1738
 
1739 1739
 		// Force special value for $searchform
1740
-		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1740
+		if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741 1741
 		{
1742
-			$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1742
+			$urltosearch = DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743
+			$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744 1744
 		}
1745
-		elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1745
+		elseif ($conf->use_javascript_ajax && !empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746 1746
 		{
1747
-			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
-			$searchform.='<script type="text/javascript">
1747
+			$searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748
+			$searchform .= '<script type="text/javascript">
1749 1749
             	jQuery(document).ready(function () {
1750 1750
             		jQuery("#divsearchforms1").click(function(){
1751 1751
 	                   jQuery("#divsearchforms2").toggle();
1752 1752
 	               });
1753 1753
             	});
1754 1754
                 </script>' . "\n";
1755
-			$searchform.='</div>';
1755
+			$searchform .= '</div>';
1756 1756
 		}
1757 1757
 
1758 1758
 		// Define $bookmarks
1759
-		if (! empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1759
+		if (!empty($conf->bookmark->enabled) && $user->rights->bookmark->lire)
1760 1760
 		{
1761 1761
 			include_once DOL_DOCUMENT_ROOT.'/bookmarks/bookmarks.lib.php';
1762 1762
 			$langs->load("bookmarks");
1763 1763
 
1764
-			$bookmarks=printBookmarksList($db, $langs);
1764
+			$bookmarks = printBookmarksList($db, $langs);
1765 1765
 		}
1766 1766
 
1767 1767
 		// Left column
1768 1768
 		print '<!-- Begin left menu -->'."\n";
1769 1769
 
1770
-		print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)?'':' title="Left menu"').'>'."\n\n";
1770
+		print '<div class="vmenu"'.(empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"').'>'."\n\n";
1771 1771
 
1772 1772
 		// Show left menu with other forms
1773 1773
 		$menumanager->menu_array = $menu_array_before;
@@ -1782,25 +1782,25 @@  discard block
 block discarded – undo
1782 1782
 		// Version
1783 1783
 		if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
1784 1784
 		{
1785
-			$doliurl='https://www.dolibarr.org';
1785
+			$doliurl = 'https://www.dolibarr.org';
1786 1786
 			//local communities
1787
-			if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
-			if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
-			if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
-			if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
-			if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
1792
-
1793
-			$appli=constant('DOL_APPLICATION_TITLE');
1794
-			if (! empty($conf->global->MAIN_APPLICATION_TITLE))
1787
+			if (preg_match('/fr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.fr';
1788
+			if (preg_match('/es/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.es';
1789
+			if (preg_match('/de/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.de';
1790
+			if (preg_match('/it/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.it';
1791
+			if (preg_match('/gr/i', $langs->defaultlang)) $doliurl = 'https://www.dolibarr.gr';
1792
+
1793
+			$appli = constant('DOL_APPLICATION_TITLE');
1794
+			if (!empty($conf->global->MAIN_APPLICATION_TITLE))
1795 1795
 			{
1796
-				$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1796
+				$appli = $conf->global->MAIN_APPLICATION_TITLE; $doliurl = '';
1797 1797
 				if (preg_match('/\d\.\d/', $appli))
1798 1798
 				{
1799
-					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1799
+					if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
1800 1800
 				}
1801
-				else $appli.=" ".DOL_VERSION;
1801
+				else $appli .= " ".DOL_VERSION;
1802 1802
 			}
1803
-			else $appli.=" ".DOL_VERSION;
1803
+			else $appli .= " ".DOL_VERSION;
1804 1804
 			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805 1805
 			if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806 1806
 			else print '<span class="help">';
@@ -1811,25 +1811,25 @@  discard block
 block discarded – undo
1811 1811
 		}
1812 1812
 
1813 1813
 		// Link to bugtrack
1814
-		if (! empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1814
+		if (!empty($conf->global->MAIN_BUGTRACK_ENABLELINK))
1815 1815
 		{
1816 1816
 			require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
1817 1817
 
1818 1818
 			$bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
1819
-			$bugbaseurl.= '?title=';
1820
-			$bugbaseurl.= urlencode("Bug: ");
1821
-			$bugbaseurl.= '&body=';
1822
-			$bugbaseurl.= urlencode("# Bug\n");
1823
-			$bugbaseurl.= urlencode("\n");
1824
-			$bugbaseurl.= urlencode("## Environment\n");
1825
-			$bugbaseurl.= urlencode("- **Version**: " . DOL_VERSION . "\n");
1826
-			$bugbaseurl.= urlencode("- **OS**: " . php_uname('s') . "\n");
1827
-			$bugbaseurl.= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
1828
-			$bugbaseurl.= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
1829
-			$bugbaseurl.= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
1830
-			$bugbaseurl.= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
1831
-			$bugbaseurl.= urlencode("\n");
1832
-			$bugbaseurl.= urlencode("## Report\n");
1819
+			$bugbaseurl .= '?title=';
1820
+			$bugbaseurl .= urlencode("Bug: ");
1821
+			$bugbaseurl .= '&body=';
1822
+			$bugbaseurl .= urlencode("# Bug\n");
1823
+			$bugbaseurl .= urlencode("\n");
1824
+			$bugbaseurl .= urlencode("## Environment\n");
1825
+			$bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
1826
+			$bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
1827
+			$bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
1828
+			$bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
1829
+			$bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
1830
+			$bugbaseurl .= urlencode("- **URL**: ".$_SERVER["REQUEST_URI"]."\n");
1831
+			$bugbaseurl .= urlencode("\n");
1832
+			$bugbaseurl .= urlencode("## Report\n");
1833 1833
 			print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
1834 1834
 			print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.$langs->trans("FindBug").'</a>';
1835 1835
 			print '</div>';
@@ -1844,11 +1844,11 @@  discard block
 block discarded – undo
1844 1844
 		print "\n";
1845 1845
 
1846 1846
 		// Execute hook printLeftBlock
1847
-		$parameters=array();
1848
-		$reshook=$hookmanager->executeHooks('printLeftBlock',$parameters);    // Note that $action and $object may have been modified by some hooks
1847
+		$parameters = array();
1848
+		$reshook = $hookmanager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
1849 1849
 		print $hookmanager->resPrint;
1850 1850
 
1851
-		print '</div></div> <!-- End side-nav id-left -->';	// End div id="side-nav" div id="id-left"
1851
+		print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
1852 1852
 	}
1853 1853
 
1854 1854
 	print "\n";
@@ -1864,7 +1864,7 @@  discard block
 block discarded – undo
1864 1864
  *  @param	string	$title		Title
1865 1865
  *  @return	void
1866 1866
  */
1867
-function main_area($title='')
1867
+function main_area($title = '')
1868 1868
 {
1869 1869
 	global $conf, $langs;
1870 1870
 
@@ -1874,7 +1874,7 @@  discard block
 block discarded – undo
1874 1874
 
1875 1875
 	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1876 1876
 
1877
-	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1877
+	if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode", $conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1878 1878
 }
1879 1879
 
1880 1880
 
@@ -1885,40 +1885,40 @@  discard block
 block discarded – undo
1885 1885
  *  @param  Translate	$langs				Language
1886 1886
  *  @return	array		Array of help urls
1887 1887
  */
1888
-function getHelpParamFor($helppagename,$langs)
1888
+function getHelpParamFor($helppagename, $langs)
1889 1889
 {
1890
-	$helpbaseurl='';
1891
-	$helppage='';
1892
-	$mode='';
1890
+	$helpbaseurl = '';
1891
+	$helppage = '';
1892
+	$mode = '';
1893 1893
 
1894
-	if (preg_match('/^http/i',$helppagename))
1894
+	if (preg_match('/^http/i', $helppagename))
1895 1895
 	{
1896 1896
 		// If complete URL
1897
-		$helpbaseurl='%s';
1898
-		$helppage=$helppagename;
1899
-		$mode='local';
1897
+		$helpbaseurl = '%s';
1898
+		$helppage = $helppagename;
1899
+		$mode = 'local';
1900 1900
 	}
1901 1901
 	else
1902 1902
 	{
1903 1903
 		// If WIKI URL
1904
-		if (preg_match('/^es/i',$langs->defaultlang))
1904
+		if (preg_match('/^es/i', $langs->defaultlang))
1905 1905
 		{
1906
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
-			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1906
+			$helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1907
+			if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1908 1908
 		}
1909
-		if (preg_match('/^fr/i',$langs->defaultlang))
1909
+		if (preg_match('/^fr/i', $langs->defaultlang))
1910 1910
 		{
1911
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
-			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1911
+			$helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1912
+			if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1913 1913
 		}
1914 1914
 		if (empty($helppage))	// If help page not already found
1915 1915
 		{
1916
-			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
-			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
1916
+			$helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
1917
+			if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) $helppage = $reg[1];
1918 1918
 		}
1919
-		$mode='wiki';
1919
+		$mode = 'wiki';
1920 1920
 	}
1921
-	return array('helpbaseurl'=>$helpbaseurl,'helppage'=>$helppage,'mode'=>$mode);
1921
+	return array('helpbaseurl'=>$helpbaseurl, 'helppage'=>$helppage, 'mode'=>$mode);
1922 1922
 }
1923 1923
 
1924 1924
 
@@ -1937,31 +1937,31 @@  discard block
 block discarded – undo
1937 1937
  *  @param	string	$showtitlebefore	Show title before input text instead of into placeholder. This can be set when output is dedicated for text browsers.
1938 1938
  *  @return	string
1939 1939
  */
1940
-function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey='', $prefhtmlinputname='',$img='', $showtitlebefore=0)
1940
+function printSearchForm($urlaction, $urlobject, $title, $htmlmorecss, $htmlinputname, $accesskey = '', $prefhtmlinputname = '', $img = '', $showtitlebefore = 0)
1941 1941
 {
1942
-	global $conf,$langs,$user;
1943
-
1944
-	$ret='';
1945
-	$ret.='<form action="'.$urlaction.'" method="post" class="searchform">';
1946
-	$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
-	$ret.='<input type="hidden" name="mode" value="search">';
1948
-	$ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
-	if ($showtitlebefore) $ret.=$title.' ';
1950
-	$ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951
-	$ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
-	$ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
1953
-	$ret.=' placeholder="'.strip_tags($title).'"';
1954
-	$ret.=' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1942
+	global $conf, $langs, $user;
1943
+
1944
+	$ret = '';
1945
+	$ret .= '<form action="'.$urlaction.'" method="post" class="searchform">';
1946
+	$ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947
+	$ret .= '<input type="hidden" name="mode" value="search">';
1948
+	$ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
+	if ($showtitlebefore) $ret .= $title.' ';
1950
+	$ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
1951
+	$ret .= ' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952
+	$ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
1953
+	$ret .= ' placeholder="'.strip_tags($title).'"';
1954
+	$ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
1955 1955
 	//$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.$langs->trans("Go").'">';
1956
-	$ret.='<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
-	$ret.='<span class="fa fa-search"></span>';
1958
-	$ret.='</button>';
1959
-	$ret.="</form>\n";
1956
+	$ret .= '<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
1957
+	$ret .= '<span class="fa fa-search"></span>';
1958
+	$ret .= '</button>';
1959
+	$ret .= "</form>\n";
1960 1960
 	return $ret;
1961 1961
 }
1962 1962
 
1963 1963
 
1964
-if (! function_exists("llxFooter"))
1964
+if (!function_exists("llxFooter"))
1965 1965
 {
1966 1966
 	/**
1967 1967
 	 * Show HTML footer
@@ -1973,31 +1973,31 @@  discard block
 block discarded – undo
1973 1973
 	 * @param	int		$disabledoutputofmessages	Clear all messages stored into session without diplaying them
1974 1974
 	 * @return	void
1975 1975
 	 */
1976
-	function llxFooter($comment='',$zone='private', $disabledoutputofmessages=0)
1976
+	function llxFooter($comment = '', $zone = 'private', $disabledoutputofmessages = 0)
1977 1977
 	{
1978 1978
 		global $conf, $langs, $user, $object;
1979 1979
 		global $delayedhtmlcontent;
1980 1980
 		global $contextpage, $page, $limit;
1981 1981
 
1982
-		$ext='layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1982
+		$ext = 'layout='.$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
1983 1983
 
1984 1984
 		// Global html output events ($mesgs, $errors, $warnings)
1985 1985
 		dol_htmloutput_events($disabledoutputofmessages);
1986 1986
 
1987 1987
 		// Code for search criteria persistence.
1988 1988
 		// $user->lastsearch_values was set by the GETPOST when form field search_xxx exists
1989
-		if (is_object($user) && ! empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1989
+		if (is_object($user) && !empty($user->lastsearch_values_tmp) && is_array($user->lastsearch_values_tmp))
1990 1990
 		{
1991 1991
 			// Clean and save data
1992
-			foreach($user->lastsearch_values_tmp as $key => $val)
1992
+			foreach ($user->lastsearch_values_tmp as $key => $val)
1993 1993
 			{
1994
-				unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1994
+				unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
1995 1995
 				if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
1996 1996
 				{
1997 1997
 					if (empty($val['sortfield'])) unset($val['sortfield']);
1998 1998
 					if (empty($val['sortorder'])) unset($val['sortorder']);
1999 1999
 					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000
-					$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2000
+					$_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
2001 2001
 					unset($_SESSION['lastsearch_values_'.$key]);
2002 2002
 				}
2003 2003
 			}
@@ -2006,7 +2006,7 @@  discard block
 block discarded – undo
2006 2006
 
2007 2007
 		$relativepathstring = $_SERVER["PHP_SELF"];
2008 2008
 		// Clean $relativepathstring
2009
-		if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2009
+		if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'), '/').'/', '', $relativepathstring);
2010 2010
 		$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011 2011
 		$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012 2012
 		if (preg_match('/list\.php$/', $relativepathstring))
@@ -2015,9 +2015,9 @@  discard block
 block discarded – undo
2015 2015
 			unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016 2016
 			unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2017 2017
 
2018
-			if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
-			if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
-			if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2018
+			if (!empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
2019
+			if (!empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
2020
+			if (!empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
2021 2021
 
2022 2022
 			unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023 2023
 			unset($_SESSION['lastsearch_page_'.$relativepathstring]);
@@ -2025,7 +2025,7 @@  discard block
 block discarded – undo
2025 2025
 		}
2026 2026
 
2027 2027
 		// Core error message
2028
-		if (! empty($conf->global->MAIN_CORE_ERROR))
2028
+		if (!empty($conf->global->MAIN_CORE_ERROR))
2029 2029
 		{
2030 2030
 			// Ajax version
2031 2031
 			if ($conf->use_javascript_ajax)
@@ -2049,23 +2049,23 @@  discard block
 block discarded – undo
2049 2049
 
2050 2050
 		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2051 2051
 
2052
-		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2052
+		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n"; // End div container
2053 2053
 
2054 2054
 		print "\n";
2055 2055
 		if ($comment) print '<!-- '.$comment.' -->'."\n";
2056 2056
 
2057 2057
 		printCommonFooter($zone);
2058 2058
 
2059
-		if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2059
+		if (!empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2060 2060
 
2061
-		if (! empty($conf->use_javascript_ajax))
2061
+		if (!empty($conf->use_javascript_ajax))
2062 2062
 		{
2063 2063
 			print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
2064
-			print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
2064
+			print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_foot.js.php?lang='.$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
2065 2065
 		}
2066 2066
 
2067 2067
 		// Wrapper to add log when clicking on download or preview
2068
-		if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2068
+		if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069 2069
 		{
2070 2070
 			if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2071 2071
 			{
Please login to merge, or discard this patch.
Braces   +533 added lines, -211 removed lines patch added patch discarded remove patch
@@ -48,7 +48,8 @@  discard block
 block discarded – undo
48 48
 }
49 49
 
50 50
 // Removed magic_quotes
51
-if (function_exists('get_magic_quotes_gpc'))	// magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
51
+if (function_exists('get_magic_quotes_gpc')) {
52
+    // magic_quotes_* deprecated in PHP 5.0 and removed in PHP 5.5
52 53
 {
53 54
 	if (get_magic_quotes_gpc())
54 55
 	{
@@ -59,6 +60,7 @@  discard block
 block discarded – undo
59 60
 		function stripslashes_deep($value)
60 61
 		{
61 62
 			return (is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value));
63
+}
62 64
 		}
63 65
 		$_GET     = array_map('stripslashes_deep', $_GET);
64 66
 		$_POST    = array_map('stripslashes_deep', $_POST);
@@ -109,9 +111,11 @@  discard block
 block discarded – undo
109 111
 	{
110 112
 		$inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i',	 $val);
111 113
 	}
112
-	if ($type != 2)	// Not common key strings, so we can check them both on GET and POST
114
+	if ($type != 2) {
115
+	    // Not common key strings, so we can check them both on GET and POST
113 116
 	{
114 117
 		$inj += preg_match('/updatexml\(/i', 	 $val);
118
+	}
115 119
 		$inj += preg_match('/update.+set.+=/i',  $val);
116 120
 		$inj += preg_match('/union.+select/i', 	 $val);
117 121
 		$inj += preg_match('/(\.\.%2f)+/i',		 $val);
@@ -125,7 +129,9 @@  discard block
 block discarded – undo
125 129
 	$inj += preg_match('/<iframe/i', $val);
126 130
 	$inj += preg_match('/<audio/i', $val);
127 131
 	$inj += preg_match('/Set\.constructor/i', $val);	// ECMA script 6
128
-	if (! defined('NOSTYLECHECK')) $inj += preg_match('/<style/i', $val);
132
+	if (! defined('NOSTYLECHECK')) {
133
+	    $inj += preg_match('/<style/i', $val);
134
+	}
129 135
 	$inj += preg_match('/base[\s]+href/si', $val);
130 136
 	$inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
131 137
 	$inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
@@ -142,8 +148,14 @@  discard block
 block discarded – undo
142 148
 		$inj += preg_match('/vbscript:/i', $val);
143 149
 	//}
144 150
 	// For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
145
-	if ($type == 1) $inj += preg_match('/"/i', $val);		// We refused " in GET parameters value
146
-	if ($type == 2) $inj += preg_match('/[;"]/', $val);		// PHP_SELF is a file system path. It can contains spaces.
151
+	if ($type == 1) {
152
+	    $inj += preg_match('/"/i', $val);
153
+	}
154
+	// We refused " in GET parameters value
155
+	if ($type == 2) {
156
+	    $inj += preg_match('/[;"]/', $val);
157
+	}
158
+	// PHP_SELF is a file system path. It can contains spaces.
147 159
 	return $inj;
148 160
 }
149 161
 
@@ -158,7 +170,8 @@  discard block
 block discarded – undo
158 170
 {
159 171
 	if (is_array($var))
160 172
 	{
161
-		foreach ($var as $key => $value)	// Warning, $key may also be used for attacks
173
+		foreach ($var as $key => $value) {
174
+		    // Warning, $key may also be used for attacks
162 175
 		{
163 176
 			if (analyseVarsForSqlAndScriptsInjection($key, $type) && analyseVarsForSqlAndScriptsInjection($value, $type))
164 177
 			{
@@ -167,12 +180,12 @@  discard block
 block discarded – undo
167 180
 			else
168 181
 			{
169 182
 				print 'Access refused by SQL/Script injection protection in main.inc.php (type='.htmlentities($type).' key='.htmlentities($key).' value='.htmlentities($value).' page='.htmlentities($_SERVER["REQUEST_URI"]).')';
183
+		}
170 184
 				exit;
171 185
 			}
172 186
 		}
173 187
 		return true;
174
-	}
175
-	else
188
+	} else
176 189
 	{
177 190
 		return (testSqlAndScriptInject($var, $type) <= 0);
178 191
 	}
@@ -225,14 +238,18 @@  discard block
 block discarded – undo
225 238
 	{
226 239
 		$postkey=$tmpautoset[0].'_'.$tmpkey;
227 240
 		//var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
228
-		if (! empty($_POST[$postkey])) $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
241
+		if (! empty($_POST[$postkey])) {
242
+		    $cookiearrayvalue[$tmpkey]=$_POST[$postkey];
243
+		}
229 244
 	}
230 245
 	$cookiename=$tmpautoset[0];
231 246
 	$cookievalue=json_encode($cookiearrayvalue);
232 247
 	//var_dump('setcookie cookiename='.$cookiename.' cookievalue='.$cookievalue);
233 248
 	setcookie($cookiename, empty($cookievalue)?'':$cookievalue, empty($cookievalue)?0:(time()+(86400*354)), '/', null, false, true);	// keep cookie 1 year and add tag httponly
234
-	if (empty($cookievalue)) unset($_COOKIE[$cookiename]);
235
-}
249
+	if (empty($cookievalue)) {
250
+	    unset($_COOKIE[$cookiename]);
251
+	}
252
+	}
236 253
 
237 254
 
238 255
 // Init session. Name of session is specific to Dolibarr instance.
@@ -241,7 +258,9 @@  discard block
 block discarded – undo
241 258
 
242 259
 $sessionname='DOLSESSID_'.$prefix;
243 260
 $sessiontimeout='DOLSESSTIMEOUT_'.$prefix;
244
-if (! empty($_COOKIE[$sessiontimeout])) ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
261
+if (! empty($_COOKIE[$sessiontimeout])) {
262
+    ini_set('session.gc_maxlifetime',$_COOKIE[$sessiontimeout]);
263
+}
245 264
 session_name($sessionname);
246 265
 session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie (same as setting session.cookie_httponly into php.ini). Must be called before the session_start.
247 266
 // This create lock, released when session_write_close() or end of page.
@@ -274,9 +293,13 @@  discard block
 block discarded – undo
274 293
 	$conf->browser->layout=$tmp['layout'];     // 'classic', 'phone', 'tablet'
275 294
 	//var_dump($conf->browser);
276 295
 
277
-	if ($conf->browser->layout == 'phone') $conf->dol_no_mouse_hover=1;
278
-	if ($conf->browser->layout == 'phone') $conf->global->MAIN_TESTMENUHIDER=1;
279
-}
296
+	if ($conf->browser->layout == 'phone') {
297
+	    $conf->dol_no_mouse_hover=1;
298
+	}
299
+	if ($conf->browser->layout == 'phone') {
300
+	    $conf->global->MAIN_TESTMENUHIDER=1;
301
+	}
302
+	}
280 303
 
281 304
 // Force HTTPS if required ($conf->file->main_force_https is 0/1 or https dolibarr root url)
282 305
 // $_SERVER["HTTPS"] is 'on' when link is https, otherwise $_SERVER["HTTPS"] is empty or 'off'
@@ -285,19 +308,19 @@  discard block
 block discarded – undo
285 308
 	$newurl='';
286 309
 	if (is_numeric($conf->file->main_force_https))
287 310
 	{
288
-		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"]))	// If SCRIPT_URI supported by server
311
+		if ($conf->file->main_force_https == '1' && ! empty($_SERVER["SCRIPT_URI"])) {
312
+		    // If SCRIPT_URI supported by server
289 313
 		{
290 314
 			if (preg_match('/^http:/i',$_SERVER["SCRIPT_URI"]) && ! preg_match('/^https:/i',$_SERVER["SCRIPT_URI"]))	// If link is http
291 315
 			{
292 316
 				$newurl=preg_replace('/^http:/i','https:',$_SERVER["SCRIPT_URI"]);
293
-			}
294 317
 		}
295
-		else	// Check HTTPS environment variable (Apache/mod_ssl only)
318
+			}
319
+		} else	// Check HTTPS environment variable (Apache/mod_ssl only)
296 320
 		{
297 321
 			$newurl=preg_replace('/^http:/i','https:',DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
298 322
 		}
299
-	}
300
-	else
323
+	} else
301 324
 	{
302 325
 		// Check HTTPS environment variable (Apache/mod_ssl only)
303 326
 		$newurl=$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
@@ -308,8 +331,7 @@  discard block
 block discarded – undo
308 331
 		dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
309 332
 		header("Location: ".$newurl);
310 333
 		exit;
311
-	}
312
-	else
334
+	} else
313 335
 	{
314 336
 		dol_syslog("main.inc: dolibarr_main_force_https is on but we failed to forge new https url so no redirect is done", LOG_WARNING);
315 337
 	}
@@ -336,8 +358,14 @@  discard block
 block discarded – undo
336 358
 }
337 359
 
338 360
 // Loading of additional presentation includes
339
-if (! defined('NOREQUIREHTML')) require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';	    // Need 660ko memory (800ko in 2.2)
340
-if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';	// Need 22ko memory
361
+if (! defined('NOREQUIREHTML')) {
362
+    require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
363
+}
364
+// Need 660ko memory (800ko in 2.2)
365
+if (! defined('NOREQUIREAJAX') && $conf->use_javascript_ajax) {
366
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
367
+}
368
+// Need 22ko memory
341 369
 
342 370
 // If install or upgrade process not done or not completely finished, we call the install page.
343 371
 if (! empty($conf->global->MAIN_NOT_INSTALLED) || ! empty($conf->global->MAIN_NOT_UPGRADED))
@@ -355,9 +383,11 @@  discard block
 block discarded – undo
355 383
 	$dolibarrversionlastupgrade=preg_split('/[.-]/',$versiontocompare);
356 384
 	$dolibarrversionprogram=preg_split('/[.-]/',DOL_VERSION);
357 385
 	$rescomp=versioncompare($dolibarrversionprogram,$dolibarrversionlastupgrade);
358
-	if ($rescomp > 0)   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
386
+	if ($rescomp > 0) {
387
+	    // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
359 388
 	{
360 389
 		dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
390
+	}
361 391
 		header("Location: ".DOL_URL_ROOT."/install/index.php");
362 392
 		exit;
363 393
 	}
@@ -367,26 +397,32 @@  discard block
 block discarded – undo
367 397
 if (! defined('NOTOKENRENEWAL'))
368 398
 {
369 399
 	// roulement des jetons car cree a chaque appel
370
-	if (isset($_SESSION['newtoken'])) $_SESSION['token'] = $_SESSION['newtoken'];
400
+	if (isset($_SESSION['newtoken'])) {
401
+	    $_SESSION['token'] = $_SESSION['newtoken'];
402
+	}
371 403
 
372 404
 	// Save in $_SESSION['newtoken'] what will be next token. Into forms, we will add param token = $_SESSION['newtoken']
373 405
 	$token = dol_hash(uniqid(mt_rand(), true)); // Generates a hash of a random number
374 406
 	$_SESSION['newtoken'] = $token;
375 407
 }
376 408
 if ((! defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && ! empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN))
377
-	|| defined('CSRFCHECK_WITH_TOKEN'))	// Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
409
+	|| defined('CSRFCHECK_WITH_TOKEN')) {
410
+    // Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set
378 411
 {
379 412
 	if ($_SERVER['REQUEST_METHOD'] == 'POST' && ! GETPOST('token','alpha')) // Note, offender can still send request by GET
380 413
 	{
381 414
 		print "Access refused by CSRF protection in main.inc.php. Token not provided.\n";
415
+}
382 416
 		print "If you access your server behind a proxy using url rewriting, you might check that all HTTP header is propagated (or add the line \$dolibarr_nocsrfcheck=1 into your conf.php file).\n";
383 417
 		die;
384 418
 	}
385
-	if ($_SERVER['REQUEST_METHOD'] === 'POST')  // This test must be after loading $_SESSION['token'].
419
+	if ($_SERVER['REQUEST_METHOD'] === 'POST') {
420
+	    // This test must be after loading $_SESSION['token'].
386 421
 	{
387 422
 		if (GETPOST('token', 'alpha') != $_SESSION['token'])
388 423
 		{
389 424
 			dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".GETPOST('action','aZ09').", _POST['token']=".GETPOST('token','alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
425
+	}
390 426
 			//print 'Unset POST by CSRF protection in main.inc.php.';	// Do not output anything because this create problems when using the BACK button on browsers.
391 427
 			unset($_POST);
392 428
 		}
@@ -394,7 +430,9 @@  discard block
 block discarded – undo
394 430
 }
395 431
 
396 432
 // Disable modules (this must be after session_start and after conf has been loaded)
397
-if (GETPOST('disablemodules','alpha'))  $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
433
+if (GETPOST('disablemodules','alpha')) {
434
+    $_SESSION["disablemodules"]=GETPOST('disablemodules','alpha');
435
+}
398 436
 if (! empty($_SESSION["disablemodules"]))
399 437
 {
400 438
 	$disabled_modules=explode(',',$_SESSION["disablemodules"]);
@@ -402,11 +440,15 @@  discard block
 block discarded – undo
402 440
 	{
403 441
 		if ($module)
404 442
 		{
405
-			if (empty($conf->$module)) $conf->$module=new stdClass();
443
+			if (empty($conf->$module)) {
444
+			    $conf->$module=new stdClass();
445
+			}
406 446
 			$conf->$module->enabled=false;
407
-			if ($module == 'fournisseur')		// Special case
447
+			if ($module == 'fournisseur') {
448
+			    // Special case
408 449
 			{
409 450
 				$conf->supplier_order->enabled=0;
451
+			}
410 452
 				$conf->supplier_invoice->enabled=0;
411 453
 			}
412 454
 		}
@@ -425,13 +467,16 @@  discard block
 block discarded – undo
425 467
 	if (defined('MAIN_AUTHENTICATION_MODE'))
426 468
 	{
427 469
 		$dolibarr_main_authentication = constant('MAIN_AUTHENTICATION_MODE');
428
-	}
429
-	else
470
+	} else
430 471
 	{
431 472
 		// Authentication mode
432
-		if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication='http,dolibarr';
473
+		if (empty($dolibarr_main_authentication)) {
474
+		    $dolibarr_main_authentication='http,dolibarr';
475
+		}
433 476
 		// Authentication mode: forceuser
434
-		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) $dolibarr_auto_user='auto';
477
+		if ($dolibarr_main_authentication == 'forceuser' && empty($dolibarr_auto_user)) {
478
+		    $dolibarr_auto_user='auto';
479
+		}
435 480
 	}
436 481
 	// Set authmode
437 482
 	$authmode=explode(',',$dolibarr_main_authentication);
@@ -467,11 +512,13 @@  discard block
 block discarded – undo
467 512
 		//dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
468 513
 
469 514
 		// If in demo mode, we check we go to home page through the public/demo/index.php page
470
-		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php')  // We ask index page
515
+		if (! empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_URL_ROOT.'/index.php') {
516
+		    // We ask index page
471 517
 		{
472 518
 			if (empty($_SERVER['HTTP_REFERER']) || ! preg_match('/public/',$_SERVER['HTTP_REFERER']))
473 519
 			{
474 520
 				dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
521
+		}
475 522
 				$url='';
476 523
 				$url.=($url?'&':'').($dol_hide_topmenu?'dol_hide_topmenu='.$dol_hide_topmenu:'');
477 524
 				$url.=($url?'&':'').($dol_hide_leftmenu?'dol_hide_leftmenu='.$dol_hide_leftmenu:'');
@@ -516,30 +563,44 @@  discard block
 block discarded – undo
516 563
 				$hookmanager->initHooks(array('login'));
517 564
 				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
518 565
 				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
519
-				if ($reshook < 0) $error++;
566
+				if ($reshook < 0) {
567
+				    $error++;
568
+				}
520 569
 
521 570
 				// Note: exit is done later
522 571
 			}
523 572
 		}
524 573
 
525 574
 		$allowedmethodtopostusername = 2;
526
-		if (defined('MAIN_AUTHENTICATION_POST_METHOD')) $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
575
+		if (defined('MAIN_AUTHENTICATION_POST_METHOD')) {
576
+		    $allowedmethodtopostusername = constant('MAIN_AUTHENTICATION_POST_METHOD');
577
+		}
527 578
 		$usertotest		= (! empty($_COOKIE['login_dolibarr']) ? $_COOKIE['login_dolibarr'] : GETPOST("username","alpha",$allowedmethodtopostusername));
528 579
 		$passwordtotest	= GETPOST('password','none',$allowedmethodtopostusername);
529 580
 		$entitytotest	= (GETPOST('entity','int') ? GETPOST('entity','int') : (!empty($conf->entity) ? $conf->entity : 1));
530 581
 
531 582
 		// Define if we received data to test the login.
532 583
 		$goontestloop=false;
533
-		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) $goontestloop=true;
534
-		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) $goontestloop=true;
535
-		if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) $goontestloop=true;
584
+		if (isset($_SERVER["REMOTE_USER"]) && in_array('http',$authmode)) {
585
+		    $goontestloop=true;
586
+		}
587
+		if ($dolibarr_main_authentication == 'forceuser' && ! empty($dolibarr_auto_user)) {
588
+		    $goontestloop=true;
589
+		}
590
+		if (GETPOST("username","alpha",$allowedmethodtopostusername) || ! empty($_COOKIE['login_dolibarr']) || GETPOST('openid_mode','alpha',1)) {
591
+		    $goontestloop=true;
592
+		}
536 593
 
537
-		if (! is_object($langs)) // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
594
+		if (! is_object($langs)) {
595
+		    // This can occurs when calling page with NOREQUIRETRAN defined, however we need langs for error messages.
538 596
 		{
539 597
 			include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
598
+		}
540 599
 			$langs=new Translate("",$conf);
541 600
 			$langcode=(GETPOST('lang','aZ09',1)?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
542
-			if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
601
+			if (defined('MAIN_LANG_DEFAULT')) {
602
+			    $langcode=constant('MAIN_LANG_DEFAULT');
603
+			}
543 604
 			$langs->setDefaultLang($langcode);
544 605
 		}
545 606
 
@@ -564,7 +625,9 @@  discard block
 block discarded – undo
564 625
 					$datenow=dol_now();
565 626
 					$datefirst=dol_stringtotime($_POST["dst_first"]);
566 627
 					$datesecond=dol_stringtotime($_POST["dst_second"]);
567
-					if ($datenow >= $datefirst && $datenow < $datesecond) $dol_dst=1;
628
+					if ($datenow >= $datefirst && $datenow < $datesecond) {
629
+					    $dol_dst=1;
630
+					}
568 631
 				}
569 632
 				//print $datefirst.'-'.$datesecond.'-'.$datenow.'-'.$dol_tz.'-'.$dol_tzstring.'-'.$dol_dst; exit;
570 633
 			}
@@ -577,7 +640,9 @@  discard block
 block discarded – undo
577 640
 
578 641
 				// Bad password. No authmode has found a good password.
579 642
 				// We set a generic message if not defined inside function checkLoginPassEntity or subfunctions
580
-				if (empty($_SESSION["dol_loginmesg"])) $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
643
+				if (empty($_SESSION["dol_loginmesg"])) {
644
+				    $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
645
+				}
581 646
 
582 647
 				// Call trigger for the "security events" log
583 648
 				$user->trigger_mesg=$langs->trans("ErrorBadLoginPassword").' - login='.GETPOST("username","alpha",2);
@@ -595,19 +660,26 @@  discard block
 block discarded – undo
595 660
 				$hookmanager->initHooks(array('login'));
596 661
 				$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
597 662
 				$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
598
-				if ($reshook < 0) $error++;
663
+				if ($reshook < 0) {
664
+				    $error++;
665
+				}
599 666
 
600 667
 				// Note: exit is done in next chapter
601 668
 			}
602 669
 		}
603 670
 
604 671
 		// End test login / passwords
605
-		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest)))	// With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
672
+		if (! $login || (in_array('ldap',$authmode) && empty($passwordtotest))) {
673
+		    // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
606 674
 		{
607 675
 			// No data to test login, so we show the login page
608 676
 			dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
609
-			if (defined('NOREDIRECTBYMAINTOLOGIN')) return 'ERROR_NOT_LOGGED';
610
-			else dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
677
+		}
678
+			if (defined('NOREDIRECTBYMAINTOLOGIN')) {
679
+			    return 'ERROR_NOT_LOGGED';
680
+			} else {
681
+			    dol_loginfunction($langs,$conf,(! empty($mysoc)?$mysoc:''));
682
+			}
611 683
 			exit;
612 684
 		}
613 685
 
@@ -650,17 +722,24 @@  discard block
 block discarded – undo
650 722
 			$hookmanager->initHooks(array('login'));
651 723
 			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
652 724
 			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
653
-			if ($reshook < 0) $error++;
725
+			if ($reshook < 0) {
726
+			    $error++;
727
+			}
654 728
 
655 729
 			$paramsurl=array();
656
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
657
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
658
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
730
+			if (GETPOST('textbrowser','int')) {
731
+			    $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
732
+			}
733
+			if (GETPOST('nojs','int')) {
734
+			    $paramsurl[]='nojs='.GETPOST('nojs','int');
735
+			}
736
+			if (GETPOST('lang','aZ09')) {
737
+			    $paramsurl[]='lang='.GETPOST('lang','aZ09');
738
+			}
659 739
 			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
660 740
 			exit;
661 741
 		}
662
-	}
663
-	else
742
+	} else
664 743
 	{
665 744
 		// We are already into an authenticated session
666 745
 		$login=$_SESSION["dol_login"];
@@ -707,27 +786,38 @@  discard block
 block discarded – undo
707 786
 			$hookmanager->initHooks(array('login'));
708 787
 			$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginmesg'=>$_SESSION["dol_loginmesg"]);
709 788
 			$reshook=$hookmanager->executeHooks('afterLoginFailed',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
710
-			if ($reshook < 0) $error++;
789
+			if ($reshook < 0) {
790
+			    $error++;
791
+			}
711 792
 
712 793
 			$paramsurl=array();
713
-			if (GETPOST('textbrowser','int')) $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
714
-			if (GETPOST('nojs','int'))        $paramsurl[]='nojs='.GETPOST('nojs','int');
715
-			if (GETPOST('lang','aZ09'))       $paramsurl[]='lang='.GETPOST('lang','aZ09');
794
+			if (GETPOST('textbrowser','int')) {
795
+			    $paramsurl[]='textbrowser='.GETPOST('textbrowser','int');
796
+			}
797
+			if (GETPOST('nojs','int')) {
798
+			    $paramsurl[]='nojs='.GETPOST('nojs','int');
799
+			}
800
+			if (GETPOST('lang','aZ09')) {
801
+			    $paramsurl[]='lang='.GETPOST('lang','aZ09');
802
+			}
716 803
 			header('Location: '.DOL_URL_ROOT.'/index.php'.(count($paramsurl)?'?'.implode('&',$paramsurl):''));
717 804
 			exit;
718
-		}
719
-		else
805
+		} else
720 806
 		{
721 807
 		    // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
722 808
 		    $hookmanager->initHooks(array('main'));
723 809
 
724 810
 		    // Code for search criteria persistence.
725
-		    if (! empty($_GET['save_lastsearch_values']))    // We must use $_GET here
811
+		    if (! empty($_GET['save_lastsearch_values'])) {
812
+		        // We must use $_GET here
726 813
 		    {
727 814
 			    $relativepathstring = preg_replace('/\?.*$/','',$_SERVER["HTTP_REFERER"]);
815
+		    }
728 816
 			    $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/','',$relativepathstring);     // Get full path except host server
729 817
 			    // Clean $relativepathstring
730
-   			    if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
818
+   			    if (constant('DOL_URL_ROOT')) {
819
+   			        $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
820
+   			    }
731 821
 			    $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
732 822
 			    $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
733 823
 			    //var_dump($relativepathstring);
@@ -784,11 +874,21 @@  discard block
 block discarded – undo
784 874
 		$_SESSION["dol_company"]=$conf->global->MAIN_INFO_SOCIETE_NOM;
785 875
 		$_SESSION["dol_entity"]=$conf->entity;
786 876
 		// Store value into session (values stored only if defined)
787
-		if (! empty($dol_hide_topmenu))         $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
788
-		if (! empty($dol_hide_leftmenu))        $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
789
-		if (! empty($dol_optimize_smallscreen)) $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
790
-		if (! empty($dol_no_mouse_hover))       $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
791
-		if (! empty($dol_use_jmobile))          $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
877
+		if (! empty($dol_hide_topmenu)) {
878
+		    $_SESSION['dol_hide_topmenu']=$dol_hide_topmenu;
879
+		}
880
+		if (! empty($dol_hide_leftmenu)) {
881
+		    $_SESSION['dol_hide_leftmenu']=$dol_hide_leftmenu;
882
+		}
883
+		if (! empty($dol_optimize_smallscreen)) {
884
+		    $_SESSION['dol_optimize_smallscreen']=$dol_optimize_smallscreen;
885
+		}
886
+		if (! empty($dol_no_mouse_hover)) {
887
+		    $_SESSION['dol_no_mouse_hover']=$dol_no_mouse_hover;
888
+		}
889
+		if (! empty($dol_use_jmobile)) {
890
+		    $_SESSION['dol_use_jmobile']=$dol_use_jmobile;
891
+		}
792 892
 
793 893
 		dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
794 894
 
@@ -814,7 +914,9 @@  discard block
 block discarded – undo
814 914
 		$hookmanager->initHooks(array('login'));
815 915
 		$parameters=array('dol_authmode'=>$dol_authmode, 'dol_loginfo'=>$loginfo);
816 916
 		$reshook=$hookmanager->executeHooks('afterLogin',$parameters,$user,$action);    // Note that $action and $object may have been modified by some hooks
817
-		if ($reshook < 0) $error++;
917
+		if ($reshook < 0) {
918
+		    $error++;
919
+		}
818 920
 
819 921
 		if ($error)
820 922
 		{
@@ -822,20 +924,23 @@  discard block
 block discarded – undo
822 924
 			session_destroy();
823 925
 			dol_print_error($db,'Error in some triggers USER_LOGIN or in some hooks afterLogin');
824 926
 			exit;
825
-		}
826
-		else
927
+		} else
827 928
 		{
828 929
 			$db->commit();
829 930
 		}
830 931
 
831 932
 		// Change landing page if defined.
832 933
 		$landingpage=(empty($user->conf->MAIN_LANDING_PAGE)?(empty($conf->global->MAIN_LANDING_PAGE)?'':$conf->global->MAIN_LANDING_PAGE):$user->conf->MAIN_LANDING_PAGE);
833
-		if (! empty($landingpage))    // Example: /index.php
934
+		if (! empty($landingpage)) {
935
+		    // Example: /index.php
834 936
 		{
835 937
 			$newpath=dol_buildpath($landingpage, 1);
836
-			if ($_SERVER["PHP_SELF"] != $newpath)   // not already on landing page (avoid infinite loop)
938
+		}
939
+			if ($_SERVER["PHP_SELF"] != $newpath) {
940
+			    // not already on landing page (avoid infinite loop)
837 941
 			{
838 942
 				header('Location: '.$newpath);
943
+			}
839 944
 				exit;
840 945
 			}
841 946
 		}
@@ -858,8 +963,14 @@  discard block
 block discarded – undo
858 963
      */
859 964
 
860 965
 	// Set liste_limit
861
-	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT))	$conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;	// Can be 0
862
-	if (isset($user->conf->PRODUIT_LIMIT_SIZE))	$conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;	// Can be 0
966
+	if (isset($user->conf->MAIN_SIZE_LISTE_LIMIT)) {
967
+	    $conf->liste_limit = $user->conf->MAIN_SIZE_LISTE_LIMIT;
968
+	}
969
+	// Can be 0
970
+	if (isset($user->conf->PRODUIT_LIMIT_SIZE)) {
971
+	    $conf->product->limit_size = $user->conf->PRODUIT_LIMIT_SIZE;
972
+	}
973
+	// Can be 0
863 974
 
864 975
 	// Replace conf->css by personalized value if theme not forced
865 976
 	if (empty($conf->global->MAIN_FORCETHEME) && ! empty($user->conf->MAIN_THEME))
@@ -878,31 +989,47 @@  discard block
 block discarded – undo
878 989
 
879 990
 
880 991
 // Set javascript option
881
-if (! GETPOST('nojs','int'))   // If javascript was not disabled on URL
992
+if (! GETPOST('nojs','int')) {
993
+    // If javascript was not disabled on URL
882 994
 {
883 995
 	if (! empty($user->conf->MAIN_DISABLE_JAVASCRIPT))
884 996
 	{
885 997
 		$conf->use_javascript_ajax=! $user->conf->MAIN_DISABLE_JAVASCRIPT;
998
+}
886 999
 	}
1000
+} else {
1001
+    $conf->use_javascript_ajax=0;
887 1002
 }
888
-else $conf->use_javascript_ajax=0;
889 1003
 // Set MAIN_OPTIMIZEFORTEXTBROWSER
890
-if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))   // If we must enable text browser
1004
+if (GETPOST('textbrowser','int') || (! empty($conf->browser->name) && $conf->browser->name == 'lynxlinks') || ! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1005
+    // If we must enable text browser
891 1006
 {
892 1007
 	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=1;
893 1008
 }
894
-elseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
1009
+} elseif (! empty($user->conf->MAIN_OPTIMIZEFORTEXTBROWSER))
895 1010
 {
896 1011
 	$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER=$user->conf->MAIN_OPTIMIZEFORTEXTBROWSER;
897 1012
 }
898 1013
 
899 1014
 // Set terminal output option according to conf->browser.
900
-if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu']))               $conf->dol_hide_leftmenu=1;
901
-if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu']))                 $conf->dol_hide_topmenu=1;
902
-if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) $conf->dol_optimize_smallscreen=1;
903
-if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover']))             $conf->dol_no_mouse_hover=1;
904
-if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile']))                   $conf->dol_use_jmobile=1;
905
-if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') $conf->dol_no_mouse_hover=1;
1015
+if (GETPOST('dol_hide_leftmenu','int') || ! empty($_SESSION['dol_hide_leftmenu'])) {
1016
+    $conf->dol_hide_leftmenu=1;
1017
+}
1018
+if (GETPOST('dol_hide_topmenu','int') || ! empty($_SESSION['dol_hide_topmenu'])) {
1019
+    $conf->dol_hide_topmenu=1;
1020
+}
1021
+if (GETPOST('dol_optimize_smallscreen','int') || ! empty($_SESSION['dol_optimize_smallscreen'])) {
1022
+    $conf->dol_optimize_smallscreen=1;
1023
+}
1024
+if (GETPOST('dol_no_mouse_hover','int') || ! empty($_SESSION['dol_no_mouse_hover'])) {
1025
+    $conf->dol_no_mouse_hover=1;
1026
+}
1027
+if (GETPOST('dol_use_jmobile','int') || ! empty($_SESSION['dol_use_jmobile'])) {
1028
+    $conf->dol_use_jmobile=1;
1029
+}
1030
+if (! empty($conf->browser->layout) && $conf->browser->layout != 'classic') {
1031
+    $conf->dol_no_mouse_hover=1;
1032
+}
906 1033
 if ((! empty($conf->browser->layout) && $conf->browser->layout == 'phone')
907 1034
 	|| (! empty($_SESSION['dol_screenwidth']) && $_SESSION['dol_screenwidth'] < 400)
908 1035
 	|| (! empty($_SESSION['dol_screenheight']) && $_SESSION['dol_screenheight'] < 400)
@@ -911,7 +1038,9 @@  discard block
 block discarded – undo
911 1038
 	$conf->dol_optimize_smallscreen=1;
912 1039
 }
913 1040
 // If we force to use jmobile, then we reenable javascript
914
-if (! empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax=1;
1041
+if (! empty($conf->dol_use_jmobile)) {
1042
+    $conf->use_javascript_ajax=1;
1043
+}
915 1044
 // Replace themes bugged with jmobile with eldy
916 1045
 if (! empty($conf->dol_use_jmobile) && in_array($conf->theme,array('bureau2crea','cameleo','amarok')))
917 1046
 {
@@ -921,7 +1050,8 @@  discard block
 block discarded – undo
921 1050
 
922 1051
 if (! defined('NOREQUIRETRAN'))
923 1052
 {
924
-	if (! GETPOST('lang','aZ09'))	// If language was not forced on URL
1053
+	if (! GETPOST('lang','aZ09')) {
1054
+	    // If language was not forced on URL
925 1055
 	{
926 1056
 		// If user has chosen its own language
927 1057
 		if (! empty($user->conf->MAIN_LANG_DEFAULT))
@@ -931,6 +1061,7 @@  discard block
 block discarded – undo
931 1061
 			if ($langs->getDefaultLang() != $user->conf->MAIN_LANG_DEFAULT)
932 1062
 			{
933 1063
 				$langs->setDefaultLang($user->conf->MAIN_LANG_DEFAULT);
1064
+	}
934 1065
 			}
935 1066
 		}
936 1067
 	}
@@ -940,7 +1071,9 @@  discard block
 block discarded – undo
940 1071
 {
941 1072
 	// If the login is not recovered, it is identified with an account that does not exist.
942 1073
 	// Hacking attempt?
943
-	if (! $user->login) accessforbidden();
1074
+	if (! $user->login) {
1075
+	    accessforbidden();
1076
+	}
944 1077
 
945 1078
 	// Check if user is active
946 1079
 	if ($user->statut < 1)
@@ -991,8 +1124,7 @@  discard block
 block discarded – undo
991 1124
 	define('ROWS_7',7);
992 1125
 	define('ROWS_8',8);
993 1126
 	define('ROWS_9',9);
994
-}
995
-else
1127
+} else
996 1128
 {
997 1129
 	define('ROWS_1',0);
998 1130
 	define('ROWS_2',1);
@@ -1010,18 +1142,22 @@  discard block
 block discarded – undo
1010 1142
 // Init menu manager
1011 1143
 if (! defined('NOREQUIREMENU'))
1012 1144
 {
1013
-	if (empty($user->societe_id))    // If internal user or not defined
1145
+	if (empty($user->societe_id)) {
1146
+	    // If internal user or not defined
1014 1147
 	{
1015 1148
 		$conf->standard_menu=(empty($conf->global->MAIN_MENU_STANDARD_FORCED)?(empty($conf->global->MAIN_MENU_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENU_STANDARD):$conf->global->MAIN_MENU_STANDARD_FORCED);
1016 1149
 	}
1017
-	else                        // If external user
1150
+	} else                        // If external user
1018 1151
 	{
1019 1152
 		$conf->standard_menu=(empty($conf->global->MAIN_MENUFRONT_STANDARD_FORCED)?(empty($conf->global->MAIN_MENUFRONT_STANDARD)?'eldy_menu.php':$conf->global->MAIN_MENUFRONT_STANDARD):$conf->global->MAIN_MENUFRONT_STANDARD_FORCED);
1020 1153
 	}
1021 1154
 
1022 1155
 	// Load the menu manager (only if not already done)
1023 1156
 	$file_menu=$conf->standard_menu;
1024
-	if (GETPOST('menu','alpha')) $file_menu=GETPOST('menu','alpha');     // example: menu=eldy_menu.php
1157
+	if (GETPOST('menu','alpha')) {
1158
+	    $file_menu=GETPOST('menu','alpha');
1159
+	}
1160
+	// example: menu=eldy_menu.php
1025 1161
 	if (! class_exists('MenuManager'))
1026 1162
 	{
1027 1163
 		$menufound=0;
@@ -1029,11 +1165,15 @@  discard block
 block discarded – undo
1029 1165
 		foreach($dirmenus as $dirmenu)
1030 1166
 		{
1031 1167
 			$menufound=dol_include_once($dirmenu."standard/".$file_menu);
1032
-			if (class_exists('MenuManager')) break;
1168
+			if (class_exists('MenuManager')) {
1169
+			    break;
1170
+			}
1033 1171
 		}
1034
-		if (! class_exists('MenuManager'))	// If failed to include, we try with standard eldy_menu.php
1172
+		if (! class_exists('MenuManager')) {
1173
+		    // If failed to include, we try with standard eldy_menu.php
1035 1174
 		{
1036 1175
 			dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
1176
+		}
1037 1177
 			$file_menu='eldy_menu.php';
1038 1178
 			include_once DOL_DOCUMENT_ROOT."/core/menus/standard/".$file_menu;
1039 1179
 		}
@@ -1108,8 +1248,11 @@  discard block
 block discarded – undo
1108 1248
 {
1109 1249
 	global $db, $conf, $hookmanager;
1110 1250
 
1111
-	if ($contenttype == 'text/html' ) header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1112
-	else header("Content-Type: ".$contenttype);
1251
+	if ($contenttype == 'text/html' ) {
1252
+	    header("Content-Type: text/html; charset=".$conf->file->character_set_client);
1253
+	} else {
1254
+	    header("Content-Type: ".$contenttype);
1255
+	}
1113 1256
 	// Security options
1114 1257
 	header("X-Content-Type-Options: nosniff");  // With the nosniff option, if the server says the content is text/html, the browser will render it as text/html (note that most browsers now force this option to on)
1115 1258
 	header("X-Frame-Options: SAMEORIGIN");      // Frames allowed only if on same domain (stop some XSS attacks)
@@ -1124,13 +1267,21 @@  discard block
 block discarded – undo
1124 1267
 		//else $contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1125 1268
 		$contentsecuritypolicy = $conf->global->MAIN_HTTP_CONTENT_SECURITY_POLICY;
1126 1269
 
1127
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1270
+		if (! is_object($hookmanager)) {
1271
+		    $hookmanager = new HookManager($db);
1272
+		}
1128 1273
 		$hookmanager->initHooks("main");
1129 1274
 
1130 1275
 		$parameters=array('contentsecuritypolicy'=>$contentsecuritypolicy);
1131 1276
 		$result=$hookmanager->executeHooks('setContentSecurityPolicy',$parameters);    // Note that $action and $object may have been modified by some hooks
1132
-		if ($result > 0) $contentsecuritypolicy = $hookmanager->resPrint;	// Replace CSP
1133
-		else $contentsecuritypolicy .= $hookmanager->resPrint;				// Concat CSP
1277
+		if ($result > 0) {
1278
+		    $contentsecuritypolicy = $hookmanager->resPrint;
1279
+		}
1280
+		// Replace CSP
1281
+		else {
1282
+		    $contentsecuritypolicy .= $hookmanager->resPrint;
1283
+		}
1284
+		// Concat CSP
1134 1285
 
1135 1286
 		if (! empty($contentsecuritypolicy))
1136 1287
 		{
@@ -1144,8 +1295,7 @@  discard block
 block discarded – undo
1144 1295
 			// default-src http: https: 'unsafe-eval' 'unsafe-inline'; object-src 'none'
1145 1296
 			header("Content-Security-Policy: ".$contentsecuritypolicy);
1146 1297
 		}
1147
-	}
1148
-	elseif (constant('FORCECSP'))
1298
+	} elseif (constant('FORCECSP'))
1149 1299
 	{
1150 1300
 		header("Content-Security-Policy: ".constant('FORCECSP'));
1151 1301
 	}
@@ -1175,12 +1325,18 @@  discard block
 block discarded – undo
1175 1325
 
1176 1326
 	top_httphead();
1177 1327
 
1178
-	if (empty($conf->css)) $conf->css = '/theme/eldy/style.css.php';	// If not defined, eldy by default
1328
+	if (empty($conf->css)) {
1329
+	    $conf->css = '/theme/eldy/style.css.php';
1330
+	}
1331
+	// If not defined, eldy by default
1179 1332
 
1180 1333
 	print '<!doctype html>'."\n";
1181 1334
 
1182
-	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1183
-	else print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1335
+	if (! empty($conf->global->MAIN_USE_CACHE_MANIFEST)) {
1336
+	    print '<html lang="'.substr($langs->defaultlang,0,2).'" manifest="'.DOL_URL_ROOT.'/cache.manifest">'."\n";
1337
+	} else {
1338
+	    print '<html lang="'.substr($langs->defaultlang,0,2).'">'."\n";
1339
+	}
1184 1340
 	//print '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">'."\n";
1185 1341
 	if (empty($disablehead))
1186 1342
 	{
@@ -1188,7 +1344,9 @@  discard block
 block discarded – undo
1188 1344
 
1189 1345
 		print "<head>\n";
1190 1346
 
1191
-		if (GETPOST('dol_basehref','alpha')) print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1347
+		if (GETPOST('dol_basehref','alpha')) {
1348
+		    print '<base href="'.dol_escape_htmltag(GETPOST('dol_basehref','alpha')).'">'."\n";
1349
+		}
1192 1350
 
1193 1351
 		// Displays meta
1194 1352
 		print '<meta charset="UTF-8">'."\n";
@@ -1198,43 +1356,71 @@  discard block
 block discarded – undo
1198 1356
 
1199 1357
 		// Favicon
1200 1358
 		$favicon=dol_buildpath('/theme/'.$conf->theme.'/img/favicon.ico',1);
1201
-		if (! empty($conf->global->MAIN_FAVICON_URL)) $favicon=$conf->global->MAIN_FAVICON_URL;
1202
-		if (empty($conf->dol_use_jmobile)) print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";	// Not required into an Android webview
1359
+		if (! empty($conf->global->MAIN_FAVICON_URL)) {
1360
+		    $favicon=$conf->global->MAIN_FAVICON_URL;
1361
+		}
1362
+		if (empty($conf->dol_use_jmobile)) {
1363
+		    print '<link rel="shortcut icon" type="image/x-icon" href="'.$favicon.'"/>'."\n";
1364
+		}
1365
+		// Not required into an Android webview
1203 1366
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="top" title="'.$langs->trans("Home").'" href="'.(DOL_URL_ROOT?DOL_URL_ROOT:'/').'">'."\n";
1204 1367
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="copyright" title="GNU General Public License" href="http://www.gnu.org/copyleft/gpl.html#SEC1">'."\n";
1205 1368
 		//if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) print '<link rel="author" title="Dolibarr Development Team" href="https://www.dolibarr.org">'."\n";
1206 1369
 
1207 1370
 		// Auto refresh page
1208
-		if (GETPOST('autorefresh','int') > 0) print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1371
+		if (GETPOST('autorefresh','int') > 0) {
1372
+		    print '<meta http-equiv="refresh" content="'.GETPOST('autorefresh','int').'">';
1373
+		}
1209 1374
 
1210 1375
 		// Displays title
1211 1376
 		$appli=constant('DOL_APPLICATION_TITLE');
1212
-		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $appli=$conf->global->MAIN_APPLICATION_TITLE;
1377
+		if (!empty($conf->global->MAIN_APPLICATION_TITLE)) {
1378
+		    $appli=$conf->global->MAIN_APPLICATION_TITLE;
1379
+		}
1213 1380
 
1214 1381
 		print '<title>';
1215 1382
 		$titletoshow='';
1216
-		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) $titletoshow = dol_htmlentities($title);
1217
-		else if ($title) $titletoshow = dol_htmlentities($appli.' - '.$title);
1218
-		else $titletoshow = dol_htmlentities($appli);
1383
+		if ($title && ! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/noapp/',$conf->global->MAIN_HTML_TITLE)) {
1384
+		    $titletoshow = dol_htmlentities($title);
1385
+		} else if ($title) {
1386
+		    $titletoshow = dol_htmlentities($appli.' - '.$title);
1387
+		} else {
1388
+		    $titletoshow = dol_htmlentities($appli);
1389
+		}
1219 1390
 
1220
-		if (! is_object($hookmanager)) $hookmanager = new HookManager($db);
1391
+		if (! is_object($hookmanager)) {
1392
+		    $hookmanager = new HookManager($db);
1393
+		}
1221 1394
 		$hookmanager->initHooks("main");
1222 1395
 		$parameters=array('title'=>$titletoshow);
1223 1396
 		$result=$hookmanager->executeHooks('setHtmlTitle',$parameters);		// Note that $action and $object may have been modified by some hooks
1224
-		if ($result > 0) $titletoshow = $hookmanager->resPrint;				// Replace Title to show
1225
-		else $titletoshow .= $hookmanager->resPrint;						// Concat to Title to show
1397
+		if ($result > 0) {
1398
+		    $titletoshow = $hookmanager->resPrint;
1399
+		}
1400
+		// Replace Title to show
1401
+		else {
1402
+		    $titletoshow .= $hookmanager->resPrint;
1403
+		}
1404
+		// Concat to Title to show
1226 1405
 
1227 1406
 		print $titletoshow;
1228 1407
 		print '</title>';
1229 1408
 
1230 1409
 		print "\n";
1231 1410
 
1232
-		if (GETPOST('version','int')) $ext='version='.GETPOST('version','int');	// usefull to force no cache on css/js
1233
-		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1411
+		if (GETPOST('version','int')) {
1412
+		    $ext='version='.GETPOST('version','int');
1413
+		}
1414
+		// usefull to force no cache on css/js
1415
+		if (GETPOST('testmenuhider','int') || ! empty($conf->global->MAIN_TESTMENUHIDER)) {
1416
+		    $ext.='&testmenuhider='.(GETPOST('testmenuhider','int')?GETPOST('testmenuhider','int'):$conf->global->MAIN_TESTMENUHIDER);
1417
+		}
1234 1418
 
1235 1419
 		$themeparam='?lang='.$langs->defaultlang.'&amp;theme='.$conf->theme.(GETPOST('optioncss','aZ09')?'&amp;optioncss='.GETPOST('optioncss','aZ09',1):'').'&amp;userid='.$user->id.'&amp;entity='.$conf->entity;
1236 1420
 		$themeparam.=($ext?'&amp;'.$ext:'');
1237
-		if (! empty($_SESSION['dol_resetcache'])) $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1421
+		if (! empty($_SESSION['dol_resetcache'])) {
1422
+		    $themeparam.='&amp;dol_resetcache='.$_SESSION['dol_resetcache'];
1423
+		}
1238 1424
 		if (GETPOST('dol_hide_topmenu','int'))           { $themeparam.='&amp;dol_hide_topmenu='.GETPOST('dol_hide_topmenu','int'); }
1239 1425
 		if (GETPOST('dol_hide_leftmenu','int'))          { $themeparam.='&amp;dol_hide_leftmenu='.GETPOST('dol_hide_leftmenu','int'); }
1240 1426
 		if (GETPOST('dol_optimize_smallscreen','int'))   { $themeparam.='&amp;dol_optimize_smallscreen='.GETPOST('dol_optimize_smallscreen','int'); }
@@ -1245,13 +1431,26 @@  discard block
 block discarded – undo
1245 1431
 		{
1246 1432
 			print '<!-- Includes CSS for JQuery (Ajax library) -->'."\n";
1247 1433
 			$jquerytheme = 'base';
1248
-			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1249
-			if (constant('JS_JQUERY_UI')) print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";  // JQuery
1250
-			else print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";    // JQuery
1251
-			if (! defined('DISABLE_JQUERY_JNOTIFY')) print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";          // JNotify
1252
-			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2"...
1434
+			if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) {
1435
+			    $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME;
1436
+			}
1437
+			if (constant('JS_JQUERY_UI')) {
1438
+			    print '<link rel="stylesheet" type="text/css" href="'.JS_JQUERY_UI.'css/'.$jquerytheme.'/jquery-ui.min.css'.($ext?'?'.$ext:'').'">'."\n";
1439
+			}
1440
+			// JQuery
1441
+			else {
1442
+			    print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.css'.($ext?'?'.$ext:'').'">'."\n";
1443
+			}
1444
+			// JQuery
1445
+			if (! defined('DISABLE_JQUERY_JNOTIFY')) {
1446
+			    print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jnotify/jquery.jnotify-alt.min.css'.($ext?'?'.$ext:'').'">'."\n";
1447
+			}
1448
+			// JNotify
1449
+			if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) {
1450
+			    // jQuery plugin "mutiselect", "multiple-select", "select2"...
1253 1451
 			{
1254 1452
 				$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1453
+			}
1255 1454
 				print '<link rel="stylesheet" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/css/'.$tmpplugin.'.css'.($ext?'?'.$ext:'').'">'."\n";
1256 1455
 			}
1257 1456
 		}
@@ -1266,13 +1465,15 @@  discard block
 block discarded – undo
1266 1465
 		// Output style sheets (optioncss='print' or ''). Note: $conf->css looks like '/theme/eldy/style.css.php'
1267 1466
 		$themepath=dol_buildpath($conf->css,1);
1268 1467
 		$themesubdir='';
1269
-		if (! empty($conf->modules_parts['theme']))	// This slow down
1468
+		if (! empty($conf->modules_parts['theme'])) {
1469
+		    // This slow down
1270 1470
 		{
1271 1471
 			foreach($conf->modules_parts['theme'] as $reldir)
1272 1472
 			{
1273 1473
 				if (file_exists(dol_buildpath($reldir.$conf->css, 0)))
1274 1474
 				{
1275 1475
 					$themepath=dol_buildpath($reldir.$conf->css, 1);
1476
+		}
1276 1477
 					$themesubdir=$reldir;
1277 1478
 					break;
1278 1479
 				}
@@ -1281,7 +1482,9 @@  discard block
 block discarded – undo
1281 1482
 
1282 1483
 		//print 'themepath='.$themepath.' themeparam='.$themeparam;exit;
1283 1484
 		print '<link rel="stylesheet" type="text/css" href="'.$themepath.$themeparam.'">'."\n";
1284
-		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1485
+		if (! empty($conf->global->MAIN_FIX_FLASH_ON_CHROME)) {
1486
+		    print '<!-- Includes CSS that does not exists as a workaround of flash bug of chrome -->'."\n".'<link rel="stylesheet" type="text/css" href="filethatdoesnotexiststosolvechromeflashbug">'."\n";
1487
+		}
1285 1488
 
1286 1489
 		// CSS forced by modules (relative url starting with /)
1287 1490
 		if (! empty($conf->modules_parts['css']))
@@ -1292,11 +1495,15 @@  discard block
 block discarded – undo
1292 1495
 				$filescss=(array) $filescss;	// To be sure filecss is an array
1293 1496
 				foreach($filescss as $cssfile)
1294 1497
 				{
1295
-					if (empty($cssfile)) dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1498
+					if (empty($cssfile)) {
1499
+					    dol_syslog("Warning: module ".$modcss." declared a css path file into its descriptor that is empty.", LOG_WARNING);
1500
+					}
1296 1501
 					// cssfile is a relative path
1297 1502
 					print '<!-- Includes CSS added by module '.$modcss. ' -->'."\n".'<link rel="stylesheet" type="text/css" href="'.dol_buildpath($cssfile,1);
1298 1503
 					// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters, so browser cache is not used.
1299
-					if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1504
+					if (!preg_match('/\.css$/i',$cssfile)) {
1505
+					    print $themeparam;
1506
+					}
1300 1507
 					print '">'."\n";
1301 1508
 				}
1302 1509
 			}
@@ -1308,7 +1515,9 @@  discard block
 block discarded – undo
1308 1515
 			{
1309 1516
 				print '<!-- Includes CSS added by page -->'."\n".'<link rel="stylesheet" type="text/css" title="default" href="'.dol_buildpath($cssfile,1);
1310 1517
 				// We add params only if page is not static, because some web server setup does not return content type text/css if url has parameters and browser cache is not used.
1311
-				if (!preg_match('/\.css$/i',$cssfile)) print $themeparam;
1518
+				if (!preg_match('/\.css$/i',$cssfile)) {
1519
+				    print $themeparam;
1520
+				}
1312 1521
 				print '">'."\n";
1313 1522
 			}
1314 1523
 		}
@@ -1318,16 +1527,27 @@  discard block
 block discarded – undo
1318 1527
 		{
1319 1528
 			// JQuery. Must be before other includes
1320 1529
 			print '<!-- Includes JS for JQuery -->'."\n";
1321
-			if (defined('JS_JQUERY') && constant('JS_JQUERY')) print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1322
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1530
+			if (defined('JS_JQUERY') && constant('JS_JQUERY')) {
1531
+			    print '<script type="text/javascript" src="'.JS_JQUERY.'jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1532
+			} else {
1533
+			    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1534
+			}
1323 1535
 			if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED'))
1324 1536
 			{
1325
-				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1326
-				else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1537
+				if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) {
1538
+				    print '<script type="text/javascript" src="'.JS_JQUERY_MIGRATE.'jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1539
+				} else {
1540
+				    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-migrate.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1541
+				}
1542
+			}
1543
+			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) {
1544
+			    print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1545
+			} else {
1546
+			    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1547
+			}
1548
+			if (! defined('DISABLE_JQUERY_TABLEDND')) {
1549
+			    print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1327 1550
 			}
1328
-			if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print '<script type="text/javascript" src="'.JS_JQUERY_UI.'jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1329
-			else print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/js/jquery-ui.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1330
-			if (! defined('DISABLE_JQUERY_TABLEDND')) print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/tablednd/jquery.tablednd.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1331 1551
 			// jQuery jnotify
1332 1552
 			if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && ! defined('DISABLE_JQUERY_JNOTIFY'))
1333 1553
 			{
@@ -1341,8 +1561,7 @@  discard block
 block discarded – undo
1341 1561
 					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1342 1562
 					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.pie.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1343 1563
 					print '<script type="text/javascript" src="'.JS_JQUERY_FLOT.'jquery.flot.stack.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1344
-				}
1345
-				else
1564
+				} else
1346 1565
 				{
1347 1566
 					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1348 1567
 					print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/flot/jquery.flot.pie.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";
@@ -1375,15 +1594,19 @@  discard block
 block discarded – undo
1375 1594
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1376 1595
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/timepicker.js.php?lang='.$langs->defaultlang.($ext?'&amp;'.$ext:'').'"></script>'."\n";
1377 1596
             }
1378
-            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT')))     // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1597
+            if (! defined('DISABLE_SELECT2') && (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))) {
1598
+                // jQuery plugin "mutiselect", "multiple-select", "select2", ...
1379 1599
             {
1380 1600
             	$tmpplugin=empty($conf->global->MAIN_USE_JQUERY_MULTISELECT)?constant('REQUIRE_JQUERY_MULTISELECT'):$conf->global->MAIN_USE_JQUERY_MULTISELECT;
1601
+            }
1381 1602
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/'.$tmpplugin.'/dist/js/'.$tmpplugin.'.full.min.js'.($ext?'?'.$ext:'').'"></script>'."\n";	// We include full because we need the support of containerCssClass
1382 1603
             }
1383
-            if (! defined('DISABLE_MULTISELECT'))     // jQuery plugin "mutiselect" to select with checkboxes
1604
+            if (! defined('DISABLE_MULTISELECT')) {
1605
+                // jQuery plugin "mutiselect" to select with checkboxes
1384 1606
             {
1385 1607
             	print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/multiselect/jquery.multi-select.js'.($ext?'?'.$ext:'').'"></script>'."\n";
1386 1608
             }
1609
+            }
1387 1610
 		}
1388 1611
 
1389 1612
         if (! $disablejs && ! empty($conf->use_javascript_ajax))
@@ -1394,10 +1617,12 @@  discard block
 block discarded – undo
1394 1617
                 print '<!-- Includes JS for CKEditor -->'."\n";
1395 1618
                 $pathckeditor = DOL_URL_ROOT . '/includes/ckeditor/ckeditor/';
1396 1619
                 $jsckeditor='ckeditor.js';
1397
-                if (constant('JS_CKEDITOR'))	// To use external ckeditor 4 js lib
1620
+                if (constant('JS_CKEDITOR')) {
1621
+                    // To use external ckeditor 4 js lib
1398 1622
                 {
1399 1623
                 	$pathckeditor=constant('JS_CKEDITOR');
1400 1624
                 }
1625
+                }
1401 1626
                 print '<script type="text/javascript">';
1402 1627
                 print 'var CKEDITOR_BASEPATH = \''.$pathckeditor.'\';'."\n";
1403 1628
                 print 'var ckeditorConfig = \''.dol_buildpath($themesubdir.'/theme/'.$conf->theme.'/ckeditor/config.js'.($ext?'?'.$ext:''),1).'\';'."\n";		// $themesubdir='' in standard usage
@@ -1411,8 +1636,12 @@  discard block
 block discarded – undo
1411 1636
             if (! defined('DISABLE_BROWSER_NOTIF'))
1412 1637
             {
1413 1638
                 $enablebrowsernotif=false;
1414
-                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) $enablebrowsernotif=true;
1415
-                if ($conf->browser->layout == 'phone') $enablebrowsernotif=false;
1639
+                if (! empty($conf->agenda->enabled) && ! empty($conf->global->AGENDA_REMINDER_BROWSER)) {
1640
+                    $enablebrowsernotif=true;
1641
+                }
1642
+                if ($conf->browser->layout == 'phone') {
1643
+                    $enablebrowsernotif=false;
1644
+                }
1416 1645
                 if ($enablebrowsernotif)
1417 1646
                 {
1418 1647
                     print '<!-- Includes JS of Dolibarr (brwoser layout = '.$conf->browser->layout.')-->'."\n";
@@ -1425,9 +1654,11 @@  discard block
 block discarded – undo
1425 1654
             print '<script type="text/javascript" src="'.DOL_URL_ROOT.'/core/js/lib_head.js.php?lang='.$langs->defaultlang.($ext?'&'.$ext:'').'"></script>'."\n";
1426 1655
 
1427 1656
             // JS forced by modules (relative url starting with /)
1428
-            if (! empty($conf->modules_parts['js']))		// $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1657
+            if (! empty($conf->modules_parts['js'])) {
1658
+                // $conf->modules_parts['js'] is array('module'=>array('file1','file2'))
1429 1659
         	{
1430 1660
         		$arrayjs=(array) $conf->modules_parts['js'];
1661
+            }
1431 1662
 	            foreach($arrayjs as $modjs => $filesjs)
1432 1663
 	            {
1433 1664
         			$filesjs=(array) $filesjs;	// To be sure filejs is an array
@@ -1447,8 +1678,7 @@  discard block
 block discarded – undo
1447 1678
                     if (preg_match('/^http/i',$jsfile))
1448 1679
                     {
1449 1680
                         print '<script type="text/javascript" src="'.$jsfile.'"></script>'."\n";
1450
-                    }
1451
-                    else
1681
+                    } else
1452 1682
                     {
1453 1683
                         print '<script type="text/javascript" src="'.dol_buildpath($jsfile,1).'"></script>'."\n";
1454 1684
                     }
@@ -1456,8 +1686,12 @@  discard block
 block discarded – undo
1456 1686
             }
1457 1687
         }
1458 1688
 
1459
-        if (! empty($head)) print $head."\n";
1460
-        if (! empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n";
1689
+        if (! empty($head)) {
1690
+            print $head."\n";
1691
+        }
1692
+        if (! empty($conf->global->MAIN_HTML_HEADER)) {
1693
+            print $conf->global->MAIN_HTML_HEADER."\n";
1694
+        }
1461 1695
 
1462 1696
         print "</head>\n\n";
1463 1697
     }
@@ -1525,13 +1759,20 @@  discard block
 block discarded – undo
1525 1759
 			$appli=$conf->global->MAIN_APPLICATION_TITLE;
1526 1760
 			if (preg_match('/\d\.\d/', $appli))
1527 1761
 			{
1528
-				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
1762
+				if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
1763
+				    $appli.=" (".DOL_VERSION.")";
1764
+				}
1765
+				// If new title contains a version that is different than core
1766
+			} else {
1767
+			    $appli.=" ".DOL_VERSION;
1529 1768
 			}
1530
-			else $appli.=" ".DOL_VERSION;
1769
+		} else {
1770
+		    $appli.=" ".DOL_VERSION;
1531 1771
 		}
1532
-		else $appli.=" ".DOL_VERSION;
1533 1772
 
1534
-		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1773
+		if (! empty($conf->global->MAIN_FEATURES_LEVEL)) {
1774
+		    $appli.="<br>".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL;
1775
+		}
1535 1776
 
1536 1777
 		$logouttext='';
1537 1778
 		if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
@@ -1545,8 +1786,7 @@  discard block
 block discarded – undo
1545 1786
 				//$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
1546 1787
 				$logouttext .='<span class="fa fa-sign-out atoplogin"></span>';
1547 1788
 				$logouttext .='</a>';
1548
-			}
1549
-			else
1789
+			} else
1550 1790
 			{
1551 1791
 				$logouthtmltext.=$langs->trans("NoLogoutProcessWithAuthMode",$_SESSION["dol_authmode"]);
1552 1792
 				$logouttext .= img_picto($langs->trans('Logout').":".$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
@@ -1573,12 +1813,15 @@  discard block
 block discarded – undo
1573 1813
 		$result=$hookmanager->executeHooks('printTopRightMenu',$parameters);    // Note that $action and $object may have been modified by some hooks
1574 1814
 		if (is_numeric($result))
1575 1815
 		{
1576
-			if ($result == 0)
1577
-				$toprightmenu.=$hookmanager->resPrint;		// add
1578
-			else
1579
-				$toprightmenu=$hookmanager->resPrint;						// replace
1580
-		}
1581
-		else
1816
+			if ($result == 0) {
1817
+							$toprightmenu.=$hookmanager->resPrint;
1818
+			}
1819
+			// add
1820
+			else {
1821
+							$toprightmenu=$hookmanager->resPrint;
1822
+			}
1823
+			// replace
1824
+		} else
1582 1825
 		{
1583 1826
 			$toprightmenu.=$result;	// For backward compatibility
1584 1827
 		}
@@ -1601,7 +1844,9 @@  discard block
 block discarded – undo
1601 1844
 			if (is_array($_POST))
1602 1845
 			{
1603 1846
 				foreach($_POST as $key=>$value) {
1604
-					if ($key!=='action' && $key!=='password' && !is_array($value)) $qs.='&'.$key.'='.urlencode($value);
1847
+					if ($key!=='action' && $key!=='password' && !is_array($value)) {
1848
+					    $qs.='&'.$key.'='.urlencode($value);
1849
+					}
1605 1850
 				}
1606 1851
 			}
1607 1852
 			$qs.=(($qs && $morequerystring)?'&':'').$morequerystring;
@@ -1621,7 +1866,9 @@  discard block
 block discarded – undo
1621 1866
 			$helppage='';
1622 1867
 			$mode='';
1623 1868
 
1624
-			if (empty($helppagename)) $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1869
+			if (empty($helppagename)) {
1870
+			    $helppagename='EN:User_documentation|FR:Documentation_utilisateur|ES:Documentación_usuarios';
1871
+			}
1625 1872
 
1626 1873
 			// Get helpbaseurl, helppage and mode from helppagename and langs
1627 1874
 			$arrayres=getHelpParamFor($helppagename,$langs);
@@ -1639,10 +1886,15 @@  discard block
 block discarded – undo
1639 1886
                 }
1640 1887
 				$title=$appli.'<br>';
1641 1888
 				$title.=$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage': 'GoToHelpPage');
1642
-				if ($mode == 'wiki') $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1889
+				if ($mode == 'wiki') {
1890
+				    $title.=' - '.$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage,'_',' ')).'&quot;';
1891
+				}
1643 1892
 				$text.='<a class="help" target="_blank" rel="noopener" href="';
1644
-				if ($mode == 'wiki') $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1645
-				else $text.=sprintf($helpbaseurl,$helppage);
1893
+				if ($mode == 'wiki') {
1894
+				    $text.=sprintf($helpbaseurl,urlencode(html_entity_decode($helppage)));
1895
+				} else {
1896
+				    $text.=sprintf($helpbaseurl,$helppage);
1897
+				}
1646 1898
 				$text.='">';
1647 1899
 				//$text.=img_picto('', 'helpdoc_top').' ';
1648 1900
 				$text.='<span class="fa fa-question-circle atoplogin"></span>';
@@ -1669,8 +1921,10 @@  discard block
 block discarded – undo
1669 1921
 		print "<!-- End top horizontal menu -->\n\n";
1670 1922
 	}
1671 1923
 
1672
-	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1673
-}
1924
+	if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
1925
+	    print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss?' '.$morecss:'').'">';
1926
+	}
1927
+	}
1674 1928
 
1675 1929
 
1676 1930
 /**
@@ -1695,7 +1949,9 @@  discard block
 block discarded – undo
1695 1949
 	$searchform='';
1696 1950
 	$bookmarks='';
1697 1951
 
1698
-	if (! empty($menu_array_before)) dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1952
+	if (! empty($menu_array_before)) {
1953
+	    dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
1954
+	}
1699 1955
 
1700 1956
 	if (empty($conf->dol_hide_leftmenu) && (! defined('NOREQUIREMENU') || ! constant('NOREQUIREMENU')))
1701 1957
 	{
@@ -1704,11 +1960,16 @@  discard block
 block discarded – undo
1704 1960
 
1705 1961
 		print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
1706 1962
 
1707
-		if ($conf->browser->layout == 'phone') $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;	// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1963
+		if ($conf->browser->layout == 'phone') {
1964
+		    $conf->global->MAIN_USE_OLD_SEARCH_FORM=1;
1965
+		}
1966
+		// Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
1708 1967
 
1709 1968
 		print "\n";
1710 1969
 
1711
-		if (! is_object($form)) $form=new Form($db);
1970
+		if (! is_object($form)) {
1971
+		    $form=new Form($db);
1972
+		}
1712 1973
 		$selected=-1;
1713 1974
 		$usedbyinclude=1;
1714 1975
 		include_once DOL_DOCUMENT_ROOT.'/core/ajax/selectsearchbox.php';	// This set $arrayresult
@@ -1717,8 +1978,7 @@  discard block
 block discarded – undo
1717 1978
 		{
1718 1979
 			//$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_URL_ROOT.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1719 1980
 			$searchform.=$form->selectArrayFilter('searchselectcombo', $arrayresult, $selected, '', 1, 0, (empty($conf->global->MAIN_SEARCHBOX_CONTENT_LOADED_BEFORE_KEY)?1:0), 'vmenusearchselectcombo', 1, $langs->trans("Search"), 1);
1720
-		}
1721
-		else
1981
+		} else
1722 1982
 		{
1723 1983
 			foreach($arrayresult as $key => $val)
1724 1984
 			{
@@ -1733,16 +1993,16 @@  discard block
 block discarded – undo
1733 1993
 		if (empty($reshook))
1734 1994
 		{
1735 1995
 			$searchform.=$hookmanager->resPrint;
1996
+		} else {
1997
+		    $searchform=$hookmanager->resPrint;
1736 1998
 		}
1737
-		else $searchform=$hookmanager->resPrint;
1738 1999
 
1739 2000
 		// Force special value for $searchform
1740 2001
 		if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty($conf->use_javascript_ajax))
1741 2002
 		{
1742 2003
 			$urltosearch=DOL_URL_ROOT.'/core/search_page.php?showtitlebefore=1';
1743 2004
 			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div></div>';
1744
-		}
1745
-		elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
2005
+		} elseif ($conf->use_javascript_ajax && ! empty($conf->global->MAIN_USE_OLD_SEARCH_FORM))
1746 2006
 		{
1747 2007
 			$searchform='<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag($langs->trans("ShowSearchFields")).'">'.$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
1748 2008
 			$searchform.='<script type="text/javascript">
@@ -1780,15 +2040,27 @@  discard block
 block discarded – undo
1780 2040
 		print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
1781 2041
 
1782 2042
 		// Version
1783
-		if (empty($conf->global->MAIN_HIDE_VERSION))    // Version is already on help picto and on login page.
2043
+		if (empty($conf->global->MAIN_HIDE_VERSION)) {
2044
+		    // Version is already on help picto and on login page.
1784 2045
 		{
1785 2046
 			$doliurl='https://www.dolibarr.org';
2047
+		}
1786 2048
 			//local communities
1787
-			if (preg_match('/fr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.fr';
1788
-			if (preg_match('/es/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.es';
1789
-			if (preg_match('/de/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.de';
1790
-			if (preg_match('/it/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.it';
1791
-			if (preg_match('/gr/i',$langs->defaultlang)) $doliurl='https://www.dolibarr.gr';
2049
+			if (preg_match('/fr/i',$langs->defaultlang)) {
2050
+			    $doliurl='https://www.dolibarr.fr';
2051
+			}
2052
+			if (preg_match('/es/i',$langs->defaultlang)) {
2053
+			    $doliurl='https://www.dolibarr.es';
2054
+			}
2055
+			if (preg_match('/de/i',$langs->defaultlang)) {
2056
+			    $doliurl='https://www.dolibarr.de';
2057
+			}
2058
+			if (preg_match('/it/i',$langs->defaultlang)) {
2059
+			    $doliurl='https://www.dolibarr.it';
2060
+			}
2061
+			if (preg_match('/gr/i',$langs->defaultlang)) {
2062
+			    $doliurl='https://www.dolibarr.gr';
2063
+			}
1792 2064
 
1793 2065
 			$appli=constant('DOL_APPLICATION_TITLE');
1794 2066
 			if (! empty($conf->global->MAIN_APPLICATION_TITLE))
@@ -1796,17 +2068,28 @@  discard block
 block discarded – undo
1796 2068
 				$appli=$conf->global->MAIN_APPLICATION_TITLE; $doliurl='';
1797 2069
 				if (preg_match('/\d\.\d/', $appli))
1798 2070
 				{
1799
-					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli.=" (".DOL_VERSION.")";	// If new title contains a version that is different than core
2071
+					if (! preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
2072
+					    $appli.=" (".DOL_VERSION.")";
2073
+					}
2074
+					// If new title contains a version that is different than core
2075
+				} else {
2076
+				    $appli.=" ".DOL_VERSION;
1800 2077
 				}
1801
-				else $appli.=" ".DOL_VERSION;
2078
+			} else {
2079
+			    $appli.=" ".DOL_VERSION;
1802 2080
 			}
1803
-			else $appli.=" ".DOL_VERSION;
1804 2081
 			print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
1805
-			if ($doliurl) print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
1806
-			else print '<span class="help">';
2082
+			if ($doliurl) {
2083
+			    print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
2084
+			} else {
2085
+			    print '<span class="help">';
2086
+			}
1807 2087
 			print $appli;
1808
-			if ($doliurl) print '</a>';
1809
-			else print '</span>';
2088
+			if ($doliurl) {
2089
+			    print '</a>';
2090
+			} else {
2091
+			    print '</span>';
2092
+			}
1810 2093
 			print '</div>'."\n";
1811 2094
 		}
1812 2095
 
@@ -1854,8 +2137,10 @@  discard block
 block discarded – undo
1854 2137
 	print "\n";
1855 2138
 	print '<!-- Begin right area -->'."\n";
1856 2139
 
1857
-	if (empty($leftmenuwithoutmainarea)) main_area($title);
1858
-}
2140
+	if (empty($leftmenuwithoutmainarea)) {
2141
+	    main_area($title);
2142
+	}
2143
+	}
1859 2144
 
1860 2145
 
1861 2146
 /**
@@ -1868,14 +2153,18 @@  discard block
 block discarded – undo
1868 2153
 {
1869 2154
 	global $conf, $langs;
1870 2155
 
1871
-	if (empty($conf->dol_hide_leftmenu)) print '<div id="id-right">';
2156
+	if (empty($conf->dol_hide_leftmenu)) {
2157
+	    print '<div id="id-right">';
2158
+	}
1872 2159
 
1873 2160
 	print "\n";
1874 2161
 
1875 2162
 	print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
1876 2163
 
1877
-	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
1878
-}
2164
+	if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED)) {
2165
+	    print info_admin($langs->trans("WarningYouAreInMaintenanceMode",$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
2166
+	}
2167
+	}
1879 2168
 
1880 2169
 
1881 2170
 /**
@@ -1897,24 +2186,31 @@  discard block
 block discarded – undo
1897 2186
 		$helpbaseurl='%s';
1898 2187
 		$helppage=$helppagename;
1899 2188
 		$mode='local';
1900
-	}
1901
-	else
2189
+	} else
1902 2190
 	{
1903 2191
 		// If WIKI URL
1904 2192
 		if (preg_match('/^es/i',$langs->defaultlang))
1905 2193
 		{
1906 2194
 			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1907
-			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2195
+			if (preg_match('/ES:([^|]+)/i',$helppagename,$reg)) {
2196
+			    $helppage=$reg[1];
2197
+			}
1908 2198
 		}
1909 2199
 		if (preg_match('/^fr/i',$langs->defaultlang))
1910 2200
 		{
1911 2201
 			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1912
-			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2202
+			if (preg_match('/FR:([^|]+)/i',$helppagename,$reg)) {
2203
+			    $helppage=$reg[1];
2204
+			}
1913 2205
 		}
1914
-		if (empty($helppage))	// If help page not already found
2206
+		if (empty($helppage)) {
2207
+		    // If help page not already found
1915 2208
 		{
1916 2209
 			$helpbaseurl='http://wiki.dolibarr.org/index.php/%s';
1917
-			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) $helppage=$reg[1];
2210
+		}
2211
+			if (preg_match('/EN:([^|]+)/i',$helppagename,$reg)) {
2212
+			    $helppage=$reg[1];
2213
+			}
1918 2214
 		}
1919 2215
 		$mode='wiki';
1920 2216
 	}
@@ -1946,7 +2242,9 @@  discard block
 block discarded – undo
1946 2242
 	$ret.='<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1947 2243
 	$ret.='<input type="hidden" name="mode" value="search">';
1948 2244
 	$ret.='<input type="hidden" name="savelogin" value="'.dol_escape_htmltag($user->login).'">';
1949
-	if ($showtitlebefore) $ret.=$title.' ';
2245
+	if ($showtitlebefore) {
2246
+	    $ret.=$title.' ';
2247
+	}
1950 2248
 	$ret.='<input type="text" class="flat '.$htmlmorecss.'"';
1951 2249
 	$ret.=' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
1952 2250
 	$ret.=($accesskey?' accesskey="'.$accesskey.'"':'');
@@ -1992,10 +2290,14 @@  discard block
 block discarded – undo
1992 2290
 			foreach($user->lastsearch_values_tmp as $key => $val)
1993 2291
 			{
1994 2292
 				unset($_SESSION['lastsearch_values_tmp_'.$key]);			// Clean array to rebuild it just after
1995
-				if (count($val) && empty($_POST['button_removefilter']))	// If there is search criteria to save and we did not click on 'Clear filter' button
2293
+				if (count($val) && empty($_POST['button_removefilter'])) {
2294
+				    // If there is search criteria to save and we did not click on 'Clear filter' button
1996 2295
 				{
1997 2296
 					if (empty($val['sortfield'])) unset($val['sortfield']);
1998
-					if (empty($val['sortorder'])) unset($val['sortorder']);
2297
+				}
2298
+					if (empty($val['sortorder'])) {
2299
+					    unset($val['sortorder']);
2300
+					}
1999 2301
 					dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
2000 2302
 					$_SESSION['lastsearch_values_tmp_'.$key]=json_encode($val);
2001 2303
 					unset($_SESSION['lastsearch_values_'.$key]);
@@ -2006,7 +2308,9 @@  discard block
 block discarded – undo
2006 2308
 
2007 2309
 		$relativepathstring = $_SERVER["PHP_SELF"];
2008 2310
 		// Clean $relativepathstring
2009
-		if (constant('DOL_URL_ROOT')) $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2311
+		if (constant('DOL_URL_ROOT')) {
2312
+		    $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_URL_ROOT'),'/').'/', '', $relativepathstring);
2313
+		}
2010 2314
 		$relativepathstring = preg_replace('/^\//', '', $relativepathstring);
2011 2315
 		$relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
2012 2316
 		if (preg_match('/list\.php$/', $relativepathstring))
@@ -2015,9 +2319,15 @@  discard block
 block discarded – undo
2015 2319
 			unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
2016 2320
 			unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
2017 2321
 
2018
-			if (! empty($contextpage))                     $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2019
-			if (! empty($page) && $page > 1)               $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2020
-			if (! empty($limit) && $limit != $conf->limit) $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2322
+			if (! empty($contextpage)) {
2323
+			    $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]=$contextpage;
2324
+			}
2325
+			if (! empty($page) && $page > 1) {
2326
+			    $_SESSION['lastsearch_page_tmp_'.$relativepathstring]=$page;
2327
+			}
2328
+			if (! empty($limit) && $limit != $conf->limit) {
2329
+			    $_SESSION['lastsearch_limit_tmp_'.$relativepathstring]=$limit;
2330
+			}
2021 2331
 
2022 2332
 			unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
2023 2333
 			unset($_SESSION['lastsearch_page_'.$relativepathstring]);
@@ -2047,16 +2357,26 @@  discard block
 block discarded – undo
2047 2357
 
2048 2358
 		print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
2049 2359
 
2050
-		if (empty($conf->dol_hide_leftmenu)) print '</div> <!-- End div id-right -->'."\n"; // End div id-right
2360
+		if (empty($conf->dol_hide_leftmenu)) {
2361
+		    print '</div> <!-- End div id-right -->'."\n";
2362
+		}
2363
+		// End div id-right
2051 2364
 
2052
-		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '</div> <!-- End div id-container -->'."\n";	// End div container
2365
+		if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) {
2366
+		    print '</div> <!-- End div id-container -->'."\n";
2367
+		}
2368
+		// End div container
2053 2369
 
2054 2370
 		print "\n";
2055
-		if ($comment) print '<!-- '.$comment.' -->'."\n";
2371
+		if ($comment) {
2372
+		    print '<!-- '.$comment.' -->'."\n";
2373
+		}
2056 2374
 
2057 2375
 		printCommonFooter($zone);
2058 2376
 
2059
-		if (! empty($delayedhtmlcontent)) print $delayedhtmlcontent;
2377
+		if (! empty($delayedhtmlcontent)) {
2378
+		    print $delayedhtmlcontent;
2379
+		}
2060 2380
 
2061 2381
 		if (! empty($conf->use_javascript_ajax))
2062 2382
 		{
@@ -2067,9 +2387,11 @@  discard block
 block discarded – undo
2067 2387
 		// Wrapper to add log when clicking on download or preview
2068 2388
 		if (! empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0)
2069 2389
 		{
2070
-			if (in_array($object->element, array('facture')))       // Restrict for the moment to element 'facture'
2390
+			if (in_array($object->element, array('facture'))) {
2391
+			    // Restrict for the moment to element 'facture'
2071 2392
 			{
2072 2393
 				print "\n<!-- JS CODE TO ENABLE log when making a download or a preview of a document -->\n";
2394
+			}
2073 2395
 				?>
2074 2396
     			<script type="text/javascript">
2075 2397
     			jQuery(document).ready(function () {
Please login to merge, or discard this patch.
dolibarr/htdocs/exports/class/export.class.php 3 patches
Indentation   +796 added lines, -796 removed lines patch added patch discarded remove patch
@@ -30,60 +30,60 @@  discard block
 block discarded – undo
30 30
  */
31 31
 class Export
32 32
 {
33
-	/**
33
+    /**
34 34
      * @var DoliDB Database handler.
35 35
      */
36 36
     public $db;
37 37
 
38
-	var $array_export_code=array();             // Tableau de "idmodule_numlot"
39
-	var $array_export_module=array();           // Tableau de "nom de modules"
40
-	var $array_export_label=array();            // Tableau de "libelle de lots"
41
-	var $array_export_sql_start=array();        // Tableau des "requetes sql"
42
-	var $array_export_sql_end=array();          // Tableau des "requetes sql"
43
-	var $array_export_sql_order=array();        // Tableau des "requetes sql"
44
-
45
-	var $array_export_fields=array();           // Tableau des listes de champ+libelle a exporter
46
-	var $array_export_TypeFields=array();		// Tableau des listes de champ+Type de filtre
47
-	var $array_export_FilterValue=array();		// Tableau des listes de champ+Valeur a filtrer
48
-	var $array_export_entities=array();         // Tableau des listes de champ+alias a exporter
49
-	var $array_export_dependencies=array();     // array of list of entities that must take care of the DISTINCT if a field is added into export
50
-	var $array_export_special=array();          // Tableau des operations speciales sur champ
38
+    var $array_export_code=array();             // Tableau de "idmodule_numlot"
39
+    var $array_export_module=array();           // Tableau de "nom de modules"
40
+    var $array_export_label=array();            // Tableau de "libelle de lots"
41
+    var $array_export_sql_start=array();        // Tableau des "requetes sql"
42
+    var $array_export_sql_end=array();          // Tableau des "requetes sql"
43
+    var $array_export_sql_order=array();        // Tableau des "requetes sql"
44
+
45
+    var $array_export_fields=array();           // Tableau des listes de champ+libelle a exporter
46
+    var $array_export_TypeFields=array();		// Tableau des listes de champ+Type de filtre
47
+    var $array_export_FilterValue=array();		// Tableau des listes de champ+Valeur a filtrer
48
+    var $array_export_entities=array();         // Tableau des listes de champ+alias a exporter
49
+    var $array_export_dependencies=array();     // array of list of entities that must take care of the DISTINCT if a field is added into export
50
+    var $array_export_special=array();          // Tableau des operations speciales sur champ
51 51
     var $array_export_examplevalues=array();    // array with examples
52 52
 
53
-	// To store export modules
54
-	var $hexa;
55
-	var $hexafiltervalue;
56
-	var $datatoexport;
57
-	var $model_name;
53
+    // To store export modules
54
+    var $hexa;
55
+    var $hexafiltervalue;
56
+    var $datatoexport;
57
+    var $model_name;
58 58
 
59
-	var $sqlusedforexport;
59
+    var $sqlusedforexport;
60 60
 
61 61
 
62
-	/**
63
-	 *    Constructor
64
-	 *
65
-	 *    @param  	DoliDB		$db		Database handler
66
-	 */
67
-	function __construct($db)
68
-	{
69
-		$this->db=$db;
70
-	}
62
+    /**
63
+     *    Constructor
64
+     *
65
+     *    @param  	DoliDB		$db		Database handler
66
+     */
67
+    function __construct($db)
68
+    {
69
+        $this->db=$db;
70
+    }
71 71
 
72 72
 
73 73
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
74
-	/**
75
-	 *    Load an exportable dataset
76
-	 *
77
-	 *    @param  	User		$user      	Object user making export
78
-	 *    @param  	string		$filter    	Load a particular dataset only
79
-	 *    @return	int						<0 if KO, >0 if OK
80
-	 */
81
-	function load_arrays($user,$filter='')
82
-	{
74
+    /**
75
+     *    Load an exportable dataset
76
+     *
77
+     *    @param  	User		$user      	Object user making export
78
+     *    @param  	string		$filter    	Load a particular dataset only
79
+     *    @return	int						<0 if KO, >0 if OK
80
+     */
81
+    function load_arrays($user,$filter='')
82
+    {
83 83
         // phpcs:enable
84
-		global $langs,$conf,$mysoc;
84
+        global $langs,$conf,$mysoc;
85 85
 
86
-		dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
86
+        dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
87 87
 
88 88
         $i=0;
89 89
 
@@ -92,798 +92,798 @@  discard block
 block discarded – undo
92 92
 
93 93
         $modulesdir = dolGetModulesDirs();
94 94
 
95
-		foreach($modulesdir as $dir)
96
-		{
97
-			// Search available exports
98
-			$handle=@opendir(dol_osencode($dir));
99
-			if (is_resource($handle))
100
-			{
95
+        foreach($modulesdir as $dir)
96
+        {
97
+            // Search available exports
98
+            $handle=@opendir(dol_osencode($dir));
99
+            if (is_resource($handle))
100
+            {
101 101
                 // Search module files
102
-			    while (($file = readdir($handle))!==false)
103
-				{
104
-					if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i",$file,$reg))
105
-					{
106
-						$modulename=$reg[1];
107
-
108
-						// Defined if module is enabled
109
-						$enabled=true;
110
-						$part=strtolower(preg_replace('/^mod/i','',$modulename));
111
-						if ($part == 'propale') $part='propal';
112
-						if (empty($conf->$part->enabled)) $enabled=false;
113
-
114
-						if ($enabled)
115
-						{
116
-							// Loading Class
117
-							$file = $dir.$modulename.".class.php";
118
-							$classname = $modulename;
119
-							require_once $file;
120
-							$module = new $classname($this->db);
121
-
122
-							if (isset($module->export_code) && is_array($module->export_code))
123
-							{
124
-							    foreach($module->export_code as $r => $value)
125
-								{
102
+                while (($file = readdir($handle))!==false)
103
+                {
104
+                    if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i",$file,$reg))
105
+                    {
106
+                        $modulename=$reg[1];
107
+
108
+                        // Defined if module is enabled
109
+                        $enabled=true;
110
+                        $part=strtolower(preg_replace('/^mod/i','',$modulename));
111
+                        if ($part == 'propale') $part='propal';
112
+                        if (empty($conf->$part->enabled)) $enabled=false;
113
+
114
+                        if ($enabled)
115
+                        {
116
+                            // Loading Class
117
+                            $file = $dir.$modulename.".class.php";
118
+                            $classname = $modulename;
119
+                            require_once $file;
120
+                            $module = new $classname($this->db);
121
+
122
+                            if (isset($module->export_code) && is_array($module->export_code))
123
+                            {
124
+                                foreach($module->export_code as $r => $value)
125
+                                {
126 126
                                     //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
127
-								    if ($filter && ($filter != $module->export_code[$r])) continue;
127
+                                    if ($filter && ($filter != $module->export_code[$r])) continue;
128 128
 
129 129
                                     // Test if condition to show are ok
130 130
                                     if (! empty($module->export_enabled[$r]) && ! verifCond($module->export_enabled[$r])) continue;
131 131
 
132 132
                                     // Test if permissions are ok
133
-									$bool=true;
134
-									if (isset($module->export_permission))
135
-									{
136
-										foreach($module->export_permission[$r] as $val)
137
-										{
138
-	    									$perm=$val;
139
-	    									//print_r("$perm[0]-$perm[1]-$perm[2]<br>");
140
-	    									if (! empty($perm[2]))
141
-	    									{
142
-	    										$bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
143
-	    									}
144
-	    									else
145
-	    									{
146
-	    										$bool=$user->rights->{$perm[0]}->{$perm[1]};
147
-	    									}
148
-	    									if ($perm[0]=='user' && $user->admin) $bool=true;
149
-	    									if (! $bool) break;
150
-										}
151
-									}
152
-									//print $bool." $perm[0]"."<br>";
153
-
154
-									// Permissions ok
155
-									//	          if ($bool)
156
-									//	          {
157
-									// Charge fichier lang en rapport
158
-									$langtoload=$module->getLangFilesArray();
159
-									if (is_array($langtoload))
160
-									{
161
-										foreach($langtoload as $key)
162
-										{
163
-											$langs->load($key);
164
-										}
165
-									}
166
-
167
-									// Module
168
-									$this->array_export_module[$i]=$module;
169
-									// Permission
170
-									$this->array_export_perms[$i]=$bool;
171
-									// Icon
172
-									$this->array_export_icon[$i]=(isset($module->export_icon[$r])?$module->export_icon[$r]:$module->picto);
173
-									// Code du dataset export
174
-									$this->array_export_code[$i]=$module->export_code[$r];
175
-									// Libelle du dataset export
176
-									$this->array_export_label[$i]=$module->getExportDatasetLabel($r);
177
-									// Tableau des champ a exporter (cle=champ, valeur=libelle)
178
-									$this->array_export_fields[$i]=$module->export_fields_array[$r];
179
-									// Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
180
-									$this->array_export_TypeFields[$i]=(isset($module->export_TypeFields_array[$r])?$module->export_TypeFields_array[$r]:'');
181
-									// Tableau des entites a exporter (cle=champ, valeur=entite)
182
-									$this->array_export_entities[$i]=$module->export_entities_array[$r];
183
-									// Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
184
-									$this->array_export_dependencies[$i]=(! empty($module->export_dependencies_array[$r])?$module->export_dependencies_array[$r]:'');
185
-									// Tableau des operations speciales sur champ
186
-									$this->array_export_special[$i]=(! empty($module->export_special_array[$r])?$module->export_special_array[$r]:'');
187
-            						// Array of examples
188
-            						$this->array_export_examplevalues[$i]=$module->export_examplevalues_array[$r];
189
-
190
-									// Requete sql du dataset
191
-									$this->array_export_sql_start[$i]=$module->export_sql_start[$r];
192
-									$this->array_export_sql_end[$i]=$module->export_sql_end[$r];
193
-									$this->array_export_sql_order[$i]=$module->export_sql_order[$r];
194
-									//$this->array_export_sql[$i]=$module->export_sql[$r];
195
-
196
-									dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(! empty($module->export_fields_code[$r])?count($module->export_fields_code[$r]):''));
197
-									$i++;
198
-									//	          }
199
-								}
200
-							}
201
-						}
202
-					}
203
-				}
133
+                                    $bool=true;
134
+                                    if (isset($module->export_permission))
135
+                                    {
136
+                                        foreach($module->export_permission[$r] as $val)
137
+                                        {
138
+                                            $perm=$val;
139
+                                            //print_r("$perm[0]-$perm[1]-$perm[2]<br>");
140
+                                            if (! empty($perm[2]))
141
+                                            {
142
+                                                $bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
143
+                                            }
144
+                                            else
145
+                                            {
146
+                                                $bool=$user->rights->{$perm[0]}->{$perm[1]};
147
+                                            }
148
+                                            if ($perm[0]=='user' && $user->admin) $bool=true;
149
+                                            if (! $bool) break;
150
+                                        }
151
+                                    }
152
+                                    //print $bool." $perm[0]"."<br>";
153
+
154
+                                    // Permissions ok
155
+                                    //	          if ($bool)
156
+                                    //	          {
157
+                                    // Charge fichier lang en rapport
158
+                                    $langtoload=$module->getLangFilesArray();
159
+                                    if (is_array($langtoload))
160
+                                    {
161
+                                        foreach($langtoload as $key)
162
+                                        {
163
+                                            $langs->load($key);
164
+                                        }
165
+                                    }
166
+
167
+                                    // Module
168
+                                    $this->array_export_module[$i]=$module;
169
+                                    // Permission
170
+                                    $this->array_export_perms[$i]=$bool;
171
+                                    // Icon
172
+                                    $this->array_export_icon[$i]=(isset($module->export_icon[$r])?$module->export_icon[$r]:$module->picto);
173
+                                    // Code du dataset export
174
+                                    $this->array_export_code[$i]=$module->export_code[$r];
175
+                                    // Libelle du dataset export
176
+                                    $this->array_export_label[$i]=$module->getExportDatasetLabel($r);
177
+                                    // Tableau des champ a exporter (cle=champ, valeur=libelle)
178
+                                    $this->array_export_fields[$i]=$module->export_fields_array[$r];
179
+                                    // Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
180
+                                    $this->array_export_TypeFields[$i]=(isset($module->export_TypeFields_array[$r])?$module->export_TypeFields_array[$r]:'');
181
+                                    // Tableau des entites a exporter (cle=champ, valeur=entite)
182
+                                    $this->array_export_entities[$i]=$module->export_entities_array[$r];
183
+                                    // Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
184
+                                    $this->array_export_dependencies[$i]=(! empty($module->export_dependencies_array[$r])?$module->export_dependencies_array[$r]:'');
185
+                                    // Tableau des operations speciales sur champ
186
+                                    $this->array_export_special[$i]=(! empty($module->export_special_array[$r])?$module->export_special_array[$r]:'');
187
+                                    // Array of examples
188
+                                    $this->array_export_examplevalues[$i]=$module->export_examplevalues_array[$r];
189
+
190
+                                    // Requete sql du dataset
191
+                                    $this->array_export_sql_start[$i]=$module->export_sql_start[$r];
192
+                                    $this->array_export_sql_end[$i]=$module->export_sql_end[$r];
193
+                                    $this->array_export_sql_order[$i]=$module->export_sql_order[$r];
194
+                                    //$this->array_export_sql[$i]=$module->export_sql[$r];
195
+
196
+                                    dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(! empty($module->export_fields_code[$r])?count($module->export_fields_code[$r]):''));
197
+                                    $i++;
198
+                                    //	          }
199
+                                }
200
+                            }
201
+                        }
202
+                    }
203
+                }
204 204
                 closedir($handle);
205
-			}
206
-		}
205
+            }
206
+        }
207 207
 
208
-		return 1;
209
-	}
208
+        return 1;
209
+    }
210 210
 
211 211
 
212 212
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
213
-	/**
214
-	 *      Build the sql export request.
215
-	 *      Arrays this->array_export_xxx are already loaded for required datatoexport
216
-	 *
217
-	 *      @param      int		$indice				Indice of export
218
-	 *      @param      array	$array_selected     Filter fields on array of fields to export
219
-	 *      @param      array	$array_filterValue  Filter records on array of value for fields
220
-	 *      @return		string						SQL String. Example "select s.rowid as r_rowid, s.status as s_status from ..."
221
-	 */
222
-	function build_sql($indice, $array_selected, $array_filterValue)
223
-	{
213
+    /**
214
+     *      Build the sql export request.
215
+     *      Arrays this->array_export_xxx are already loaded for required datatoexport
216
+     *
217
+     *      @param      int		$indice				Indice of export
218
+     *      @param      array	$array_selected     Filter fields on array of fields to export
219
+     *      @param      array	$array_filterValue  Filter records on array of value for fields
220
+     *      @return		string						SQL String. Example "select s.rowid as r_rowid, s.status as s_status from ..."
221
+     */
222
+    function build_sql($indice, $array_selected, $array_filterValue)
223
+    {
224 224
         // phpcs:enable
225
-		// Build the sql request
226
-		$sql=$this->array_export_sql_start[$indice];
227
-		$i=0;
228
-
229
-		//print_r($array_selected);
230
-		foreach ($this->array_export_fields[$indice] as $key => $value)
231
-		{
232
-			if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
225
+        // Build the sql request
226
+        $sql=$this->array_export_sql_start[$indice];
227
+        $i=0;
228
+
229
+        //print_r($array_selected);
230
+        foreach ($this->array_export_fields[$indice] as $key => $value)
231
+        {
232
+            if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
233 233
             if (preg_match('/^none\./', $key)) continue;                    // A field that must not appears into SQL
234
-			if ($i > 0) $sql.=', ';
235
-			else $i++;
236
-
237
-			if (strpos($key, ' as ')===false) {
238
-				$newfield=$key.' as '.str_replace(array('.', '-','(',')'),'_',$key);
239
-			} else {
240
-				$newfield=$key;
241
-			}
242
-
243
-			$sql.=$newfield;
244
-		}
245
-		$sql.=$this->array_export_sql_end[$indice];
246
-
247
-		// Add the WHERE part. Filtering into sql if a filtering array is provided
248
-		if (is_array($array_filterValue) && !empty($array_filterValue))
249
-		{
250
-			$sqlWhere='';
251
-			// Loop on each condition to add
252
-			foreach ($array_filterValue as $key => $value)
253
-			{
254
-			    if (preg_match('/GROUP_CONCAT/i', $key)) continue;
255
-				if ($value != '') $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
256
-			}
257
-			$sql.=$sqlWhere;
258
-		}
259
-
260
-		// Add the order
261
-		$sql.=$this->array_export_sql_order[$indice];
262
-
263
-		// Add the HAVING part.
264
-		if (is_array($array_filterValue) && !empty($array_filterValue))
265
-		{
266
-		    // Loop on each condition to add
267
-		    foreach ($array_filterValue as $key => $value)
268
-		    {
269
-		        if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
270
-		    }
271
-		}
272
-
273
-		return $sql;
274
-	}
234
+            if ($i > 0) $sql.=', ';
235
+            else $i++;
236
+
237
+            if (strpos($key, ' as ')===false) {
238
+                $newfield=$key.' as '.str_replace(array('.', '-','(',')'),'_',$key);
239
+            } else {
240
+                $newfield=$key;
241
+            }
242
+
243
+            $sql.=$newfield;
244
+        }
245
+        $sql.=$this->array_export_sql_end[$indice];
246
+
247
+        // Add the WHERE part. Filtering into sql if a filtering array is provided
248
+        if (is_array($array_filterValue) && !empty($array_filterValue))
249
+        {
250
+            $sqlWhere='';
251
+            // Loop on each condition to add
252
+            foreach ($array_filterValue as $key => $value)
253
+            {
254
+                if (preg_match('/GROUP_CONCAT/i', $key)) continue;
255
+                if ($value != '') $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
256
+            }
257
+            $sql.=$sqlWhere;
258
+        }
259
+
260
+        // Add the order
261
+        $sql.=$this->array_export_sql_order[$indice];
262
+
263
+        // Add the HAVING part.
264
+        if (is_array($array_filterValue) && !empty($array_filterValue))
265
+        {
266
+            // Loop on each condition to add
267
+            foreach ($array_filterValue as $key => $value)
268
+            {
269
+                if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
270
+            }
271
+        }
272
+
273
+        return $sql;
274
+    }
275 275
 
276 276
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
277
-	/**
278
-	 *      Build the conditionnal string from filter the query
279
-	 *
280
-	 *      @param		string	$TypeField		Type of Field to filter
281
-	 *      @param		string	$NameField		Name of the field to filter
282
-	 *      @param		string	$ValueField		Value of the field for filter. Must not be ''
283
-	 *      @return		string					sql string of then field ex : "field='xxx'>"
284
-	 */
285
-	function build_filterQuery($TypeField, $NameField, $ValueField)
286
-	{
277
+    /**
278
+     *      Build the conditionnal string from filter the query
279
+     *
280
+     *      @param		string	$TypeField		Type of Field to filter
281
+     *      @param		string	$NameField		Name of the field to filter
282
+     *      @param		string	$ValueField		Value of the field for filter. Must not be ''
283
+     *      @return		string					sql string of then field ex : "field='xxx'>"
284
+     */
285
+    function build_filterQuery($TypeField, $NameField, $ValueField)
286
+    {
287 287
         // phpcs:enable
288
-		//print $TypeField." ".$NameField." ".$ValueField;
289
-		$InfoFieldList = explode(":", $TypeField);
290
-		// build the input field on depend of the type of file
291
-		switch ($InfoFieldList[0]) {
292
-			case 'Text':
293
-				if (! (strpos($ValueField, '%') === false))
294
-					$szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'";
295
-				else
296
-					$szFilterQuery.=" ".$NameField." = '".$ValueField."'";
297
-				break;
298
-			case 'Date':
299
-				if (strpos($ValueField, "+") > 0)
300
-				{
301
-					// mode plage
302
-					$ValueArray = explode("+", $ValueField);
303
-					$szFilterQuery ="(".$this->conditionDate($NameField,trim($ValueArray[0]),">=");
304
-					$szFilterQuery.=" AND ".$this->conditionDate($NameField,trim($ValueArray[1]),"<=").")";
305
-				}
306
-				else
307
-				{
308
-					if (is_numeric(substr($ValueField,0,1)))
309
-						$szFilterQuery=$this->conditionDate($NameField,trim($ValueField),"=");
310
-					else
311
-						$szFilterQuery=$this->conditionDate($NameField,trim(substr($ValueField,1)),substr($ValueField,0,1));
312
-				}
313
-				break;
314
-			case 'Duree':
315
-				break;
316
-			case 'Numeric':
317
-				// si le signe -
318
-				if (strpos($ValueField, "+") > 0)
319
-				{
320
-					// mode plage
321
-					$ValueArray = explode("+", $ValueField);
322
-					$szFilterQuery ="(".$NameField.">=".$ValueArray[0];
323
-					$szFilterQuery.=" AND ".$NameField."<=".$ValueArray[1].")";
324
-				}
325
-				else
326
-				{
327
-					if (is_numeric(substr($ValueField,0,1)))
328
-						$szFilterQuery=" ".$NameField."=".$ValueField;
329
-					else
330
-						$szFilterQuery=" ".$NameField.substr($ValueField,0,1).substr($ValueField,1);
331
-				}
332
-				break;
333
-			case 'Boolean':
334
-				$szFilterQuery=" ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField =='yes' ? 1: 0) );
335
-				break;
336
-			case 'Status':
337
-			case 'List':
338
-				if (is_numeric($ValueField))
339
-					$szFilterQuery=" ".$NameField."=".$ValueField;
340
-				else {
288
+        //print $TypeField." ".$NameField." ".$ValueField;
289
+        $InfoFieldList = explode(":", $TypeField);
290
+        // build the input field on depend of the type of file
291
+        switch ($InfoFieldList[0]) {
292
+            case 'Text':
293
+                if (! (strpos($ValueField, '%') === false))
294
+                    $szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'";
295
+                else
296
+                    $szFilterQuery.=" ".$NameField." = '".$ValueField."'";
297
+                break;
298
+            case 'Date':
299
+                if (strpos($ValueField, "+") > 0)
300
+                {
301
+                    // mode plage
302
+                    $ValueArray = explode("+", $ValueField);
303
+                    $szFilterQuery ="(".$this->conditionDate($NameField,trim($ValueArray[0]),">=");
304
+                    $szFilterQuery.=" AND ".$this->conditionDate($NameField,trim($ValueArray[1]),"<=").")";
305
+                }
306
+                else
307
+                {
308
+                    if (is_numeric(substr($ValueField,0,1)))
309
+                        $szFilterQuery=$this->conditionDate($NameField,trim($ValueField),"=");
310
+                    else
311
+                        $szFilterQuery=$this->conditionDate($NameField,trim(substr($ValueField,1)),substr($ValueField,0,1));
312
+                }
313
+                break;
314
+            case 'Duree':
315
+                break;
316
+            case 'Numeric':
317
+                // si le signe -
318
+                if (strpos($ValueField, "+") > 0)
319
+                {
320
+                    // mode plage
321
+                    $ValueArray = explode("+", $ValueField);
322
+                    $szFilterQuery ="(".$NameField.">=".$ValueArray[0];
323
+                    $szFilterQuery.=" AND ".$NameField."<=".$ValueArray[1].")";
324
+                }
325
+                else
326
+                {
327
+                    if (is_numeric(substr($ValueField,0,1)))
328
+                        $szFilterQuery=" ".$NameField."=".$ValueField;
329
+                    else
330
+                        $szFilterQuery=" ".$NameField.substr($ValueField,0,1).substr($ValueField,1);
331
+                }
332
+                break;
333
+            case 'Boolean':
334
+                $szFilterQuery=" ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField =='yes' ? 1: 0) );
335
+                break;
336
+            case 'Status':
337
+            case 'List':
338
+                if (is_numeric($ValueField))
339
+                    $szFilterQuery=" ".$NameField."=".$ValueField;
340
+                else {
341 341
                     if (! (strpos($ValueField, '%') === false))
342 342
                         $szFilterQuery=" ".$NameField." LIKE '".$ValueField."'";
343 343
                     else
344 344
                         $szFilterQuery=" ".$NameField." = '".$ValueField."'";
345
-				}
346
-				break;
347
-			default:
348
-			    dol_syslog("Error we try to forge an sql export request with a condition on a field with type '".$InfoFieldList[0]."' (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
349
-		}
350
-
351
-		return $szFilterQuery;
352
-	}
353
-
354
-	/**
355
-	 *	conditionDate
356
-	 *
357
-	 *  @param 	string	$Field		Field operand 1
358
-	 *  @param 	string	$Value		Value operand 2
359
-	 *  @param 	string	$Sens		Comparison operator
360
-	 *  @return string
361
-	 */
362
-	function conditionDate($Field, $Value, $Sens)
363
-	{
364
-		// TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN
365
-		if (strlen($Value)==4) $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
366
-		elseif (strlen($Value)==6) $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
367
-		else  $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
368
-		return $Condition;
369
-	}
345
+                }
346
+                break;
347
+            default:
348
+                dol_syslog("Error we try to forge an sql export request with a condition on a field with type '".$InfoFieldList[0]."' (defined into module descriptor) but this type is unknown/not supported. It looks like a bug into module descriptor.", LOG_ERR);
349
+        }
350
+
351
+        return $szFilterQuery;
352
+    }
353
+
354
+    /**
355
+     *	conditionDate
356
+     *
357
+     *  @param 	string	$Field		Field operand 1
358
+     *  @param 	string	$Value		Value operand 2
359
+     *  @param 	string	$Sens		Comparison operator
360
+     *  @return string
361
+     */
362
+    function conditionDate($Field, $Value, $Sens)
363
+    {
364
+        // TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN
365
+        if (strlen($Value)==4) $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
366
+        elseif (strlen($Value)==6) $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
367
+        else  $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
368
+        return $Condition;
369
+    }
370 370
 
371 371
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
372
-	/**
373
-	 *      Build an input field used to filter the query
374
-	 *
375
-	 *      @param		string	$TypeField		Type of Field to filter. Example: Text, Date, List:c_country:label:rowid, List:c_stcom:label:code, Numeric or Number, Boolean
376
-	 *      @param		string	$NameField		Name of the field to filter
377
-	 *      @param		string	$ValueField		Initial value of the field to filter
378
-	 *      @return		string					html string of the input field ex : "<input type=text name=... value=...>"
379
-	 */
380
-	function build_filterField($TypeField, $NameField, $ValueField)
381
-	{
372
+    /**
373
+     *      Build an input field used to filter the query
374
+     *
375
+     *      @param		string	$TypeField		Type of Field to filter. Example: Text, Date, List:c_country:label:rowid, List:c_stcom:label:code, Numeric or Number, Boolean
376
+     *      @param		string	$NameField		Name of the field to filter
377
+     *      @param		string	$ValueField		Initial value of the field to filter
378
+     *      @return		string					html string of the input field ex : "<input type=text name=... value=...>"
379
+     */
380
+    function build_filterField($TypeField, $NameField, $ValueField)
381
+    {
382 382
         // phpcs:enable
383
-		global $conf,$langs;
384
-
385
-		$szFilterField='';
386
-		$InfoFieldList = explode(":", $TypeField);
387
-
388
-		// build the input field on depend of the type of file
389
-		switch ($InfoFieldList[0])
390
-		{
391
-			case 'Text':
392
-			case 'Date':
393
-				$szFilterField='<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
394
-				break;
395
-			case 'Duree':
396
-			case 'Numeric':
397
-			case 'Number':
398
-				// Must be a string text to allow to use comparison strings like "<= 999"
399
-			    $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
400
-				break;
401
-			case 'Status':
402
-				if (! empty($conf->global->MAIN_ACTIVATE_HTML5)) $szFilterField='<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
403
-				else $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
404
-				break;
405
-			case 'Boolean':
406
-				$szFilterField='<select name="'.$NameField.'" class="flat">';
407
-				$szFilterField.='<option ';
408
-				if ($ValueField=='') $szFilterField.=' selected ';
409
-				$szFilterField.=' value="">&nbsp;</option>';
410
-
411
-				$szFilterField.='<option ';
412
-				if ($ValueField=='yes' || $ValueField == '1') $szFilterField.=' selected ';
413
-				$szFilterField.=' value="1">'.yn(1).'</option>';
414
-
415
-				$szFilterField.='<option ';
416
-				if ($ValueField=='no' || $ValueField=='0') $szFilterField.=' selected ';
417
-				$szFilterField.=' value="0">'.yn(0).'</option>';
418
-				$szFilterField.="</select>";
419
-				break;
420
-			case 'List':
421
-				// 0 : Type du champ
422
-				// 1 : Nom de la table
423
-				// 2 : Nom du champ contenant le libelle
424
-				// 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
425
-				if (count($InfoFieldList)==4)
426
-					$keyList=$InfoFieldList[3];
427
-				else
428
-					$keyList='rowid';
429
-				$sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
430
-				if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
431
-				if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code';
432
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[1];
433
-
434
-				$resql = $this->db->query($sql);
435
-				if ($resql)
436
-				{
437
-					$szFilterField='<select class="flat" name="'.$NameField.'">';
438
-					$szFilterField.='<option value="0">&nbsp;</option>';
439
-					$num = $this->db->num_rows($resql);
440
-
441
-					$i = 0;
442
-					if ($num)
443
-					{
444
-						while ($i < $num)
445
-						{
446
-							$obj = $this->db->fetch_object($resql);
447
-							if ($obj->label == '-')
448
-							{
449
-								// Discard entry '-'
450
-								$i++;
451
-								continue;
452
-							}
453
-							//var_dump($InfoFieldList[1]);
454
-							$labeltoshow=dol_trunc($obj->label,18);
455
-							if ($InfoFieldList[1] == 'c_stcomm')
456
-							{
457
-								$langs->load("companies");
458
-								$labeltoshow=(($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id)?$langs->trans("StatusProspect".$obj->id):$obj->label);
459
-							}
460
-							if ($InfoFieldList[1] == 'c_country')
461
-							{
462
-								//var_dump($sql);
463
-								$langs->load("dict");
464
-								$labeltoshow=(($langs->trans("Country".$obj->code) != "Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label);
465
-							}
466
-							if (!empty($ValueField) && $ValueField == $obj->rowid)
467
-							{
468
-								$szFilterField.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
469
-							}
470
-							else
471
-							{
472
-								$szFilterField.='<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
473
-							}
474
-							$i++;
475
-						}
476
-					}
477
-					$szFilterField.="</select>";
478
-
479
-					$this->db->free($resql);
480
-				}
481
-				else dol_print_error($this->db);
482
-				break;
483
-		}
484
-
485
-		return $szFilterField;
486
-	}
487
-
488
-	/**
489
-	 *      Build an input field used to filter the query
490
-	 *
491
-	 *      @param		string	$TypeField		Type of Field to filter
492
-	 *      @return		string					html string of the input field ex : "<input type=text name=... value=...>"
493
-	 */
494
-	function genDocFilter($TypeField)
495
-	{
383
+        global $conf,$langs;
384
+
385
+        $szFilterField='';
386
+        $InfoFieldList = explode(":", $TypeField);
387
+
388
+        // build the input field on depend of the type of file
389
+        switch ($InfoFieldList[0])
390
+        {
391
+            case 'Text':
392
+            case 'Date':
393
+                $szFilterField='<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
394
+                break;
395
+            case 'Duree':
396
+            case 'Numeric':
397
+            case 'Number':
398
+                // Must be a string text to allow to use comparison strings like "<= 999"
399
+                $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
400
+                break;
401
+            case 'Status':
402
+                if (! empty($conf->global->MAIN_ACTIVATE_HTML5)) $szFilterField='<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
403
+                else $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
404
+                break;
405
+            case 'Boolean':
406
+                $szFilterField='<select name="'.$NameField.'" class="flat">';
407
+                $szFilterField.='<option ';
408
+                if ($ValueField=='') $szFilterField.=' selected ';
409
+                $szFilterField.=' value="">&nbsp;</option>';
410
+
411
+                $szFilterField.='<option ';
412
+                if ($ValueField=='yes' || $ValueField == '1') $szFilterField.=' selected ';
413
+                $szFilterField.=' value="1">'.yn(1).'</option>';
414
+
415
+                $szFilterField.='<option ';
416
+                if ($ValueField=='no' || $ValueField=='0') $szFilterField.=' selected ';
417
+                $szFilterField.=' value="0">'.yn(0).'</option>';
418
+                $szFilterField.="</select>";
419
+                break;
420
+            case 'List':
421
+                // 0 : Type du champ
422
+                // 1 : Nom de la table
423
+                // 2 : Nom du champ contenant le libelle
424
+                // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
425
+                if (count($InfoFieldList)==4)
426
+                    $keyList=$InfoFieldList[3];
427
+                else
428
+                    $keyList='rowid';
429
+                $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
430
+                if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
431
+                if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code';
432
+                $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[1];
433
+
434
+                $resql = $this->db->query($sql);
435
+                if ($resql)
436
+                {
437
+                    $szFilterField='<select class="flat" name="'.$NameField.'">';
438
+                    $szFilterField.='<option value="0">&nbsp;</option>';
439
+                    $num = $this->db->num_rows($resql);
440
+
441
+                    $i = 0;
442
+                    if ($num)
443
+                    {
444
+                        while ($i < $num)
445
+                        {
446
+                            $obj = $this->db->fetch_object($resql);
447
+                            if ($obj->label == '-')
448
+                            {
449
+                                // Discard entry '-'
450
+                                $i++;
451
+                                continue;
452
+                            }
453
+                            //var_dump($InfoFieldList[1]);
454
+                            $labeltoshow=dol_trunc($obj->label,18);
455
+                            if ($InfoFieldList[1] == 'c_stcomm')
456
+                            {
457
+                                $langs->load("companies");
458
+                                $labeltoshow=(($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id)?$langs->trans("StatusProspect".$obj->id):$obj->label);
459
+                            }
460
+                            if ($InfoFieldList[1] == 'c_country')
461
+                            {
462
+                                //var_dump($sql);
463
+                                $langs->load("dict");
464
+                                $labeltoshow=(($langs->trans("Country".$obj->code) != "Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label);
465
+                            }
466
+                            if (!empty($ValueField) && $ValueField == $obj->rowid)
467
+                            {
468
+                                $szFilterField.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
469
+                            }
470
+                            else
471
+                            {
472
+                                $szFilterField.='<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
473
+                            }
474
+                            $i++;
475
+                        }
476
+                    }
477
+                    $szFilterField.="</select>";
478
+
479
+                    $this->db->free($resql);
480
+                }
481
+                else dol_print_error($this->db);
482
+                break;
483
+        }
484
+
485
+        return $szFilterField;
486
+    }
487
+
488
+    /**
489
+     *      Build an input field used to filter the query
490
+     *
491
+     *      @param		string	$TypeField		Type of Field to filter
492
+     *      @return		string					html string of the input field ex : "<input type=text name=... value=...>"
493
+     */
494
+    function genDocFilter($TypeField)
495
+    {
496 496
         global $langs;
497 497
 
498
-		$szMsg='';
499
-		$InfoFieldList = explode(":", $TypeField);
500
-		// build the input field on depend of the type of file
501
-		switch ($InfoFieldList[0]) {
502
-			case 'Text':
503
-				$szMsg= $langs->trans('ExportStringFilter');
504
-				break;
505
-			case 'Date':
506
-				$szMsg = $langs->trans('ExportDateFilter');
507
-				break;
508
-			case 'Duree':
509
-				break;
510
-			case 'Numeric':
511
-				$szMsg = $langs->trans('ExportNumericFilter');
512
-				break;
513
-			case 'Boolean':
514
-				break;
515
-			case 'List':
516
-				break;
517
-		}
518
-		return $szMsg;
519
-	}
498
+        $szMsg='';
499
+        $InfoFieldList = explode(":", $TypeField);
500
+        // build the input field on depend of the type of file
501
+        switch ($InfoFieldList[0]) {
502
+            case 'Text':
503
+                $szMsg= $langs->trans('ExportStringFilter');
504
+                break;
505
+            case 'Date':
506
+                $szMsg = $langs->trans('ExportDateFilter');
507
+                break;
508
+            case 'Duree':
509
+                break;
510
+            case 'Numeric':
511
+                $szMsg = $langs->trans('ExportNumericFilter');
512
+                break;
513
+            case 'Boolean':
514
+                break;
515
+            case 'List':
516
+                break;
517
+        }
518
+        return $szMsg;
519
+    }
520 520
 
521 521
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
522
-	/**
523
-	 *      Build export file.
524
-	 *      File is built into directory $conf->export->dir_temp.'/'.$user->id
525
-	 *      Arrays this->array_export_xxx are already loaded for required datatoexport
526
-	 *
527
-	 *      @param      User		$user               User that export
528
-	 *      @param      string		$model              Export format
529
-	 *      @param      string		$datatoexport       Name of dataset to export
530
-	 *      @param      array		$array_selected     Filter on array of fields to export
531
-	 *      @param      array		$array_filterValue  Filter on array of fields with a filter
532
-	 *      @param		string		$sqlquery			If set, transmit the sql request for select (otherwise, sql request is generated from arrays)
533
-	 *      @return		int								<0 if KO, >0 if OK
534
-	 */
535
-	function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
536
- 	{
522
+    /**
523
+     *      Build export file.
524
+     *      File is built into directory $conf->export->dir_temp.'/'.$user->id
525
+     *      Arrays this->array_export_xxx are already loaded for required datatoexport
526
+     *
527
+     *      @param      User		$user               User that export
528
+     *      @param      string		$model              Export format
529
+     *      @param      string		$datatoexport       Name of dataset to export
530
+     *      @param      array		$array_selected     Filter on array of fields to export
531
+     *      @param      array		$array_filterValue  Filter on array of fields with a filter
532
+     *      @param		string		$sqlquery			If set, transmit the sql request for select (otherwise, sql request is generated from arrays)
533
+     *      @return		int								<0 if KO, >0 if OK
534
+     */
535
+    function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
536
+        {
537 537
         // phpcs:enable
538
-		global $conf,$langs;
538
+        global $conf,$langs;
539 539
 
540
-		$indice=0;
541
-		asort($array_selected);
540
+        $indice=0;
541
+        asort($array_selected);
542 542
 
543
-		dol_syslog(get_class($this)."::".__FUNCTION__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
543
+        dol_syslog(get_class($this)."::".__FUNCTION__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
544 544
 
545
-		// Check parameters or context properties
546
-		if (empty($this->array_export_fields) || ! is_array($this->array_export_fields))
547
-		{
548
-			$this->error="ErrorBadParameter";
549
-			return -1;
550
-		}
545
+        // Check parameters or context properties
546
+        if (empty($this->array_export_fields) || ! is_array($this->array_export_fields))
547
+        {
548
+            $this->error="ErrorBadParameter";
549
+            return -1;
550
+        }
551 551
 
552
-		// Creation of class to export using model ExportXXX
553
-		$dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
554
-		$file = "export_".$model.".modules.php";
555
-		$classname = "Export".$model;
556
-		require_once $dir.$file;
557
-		$objmodel = new $classname($this->db);
552
+        // Creation of class to export using model ExportXXX
553
+        $dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
554
+        $file = "export_".$model.".modules.php";
555
+        $classname = "Export".$model;
556
+        require_once $dir.$file;
557
+        $objmodel = new $classname($this->db);
558 558
 
559
-		if (! empty($sqlquery)) $sql = $sqlquery;
559
+        if (! empty($sqlquery)) $sql = $sqlquery;
560
+        else
561
+        {
562
+            // Define value for indice from $datatoexport
563
+            $foundindice=0;
564
+            foreach($this->array_export_code as $key => $dataset)
565
+            {
566
+                if ($datatoexport == $dataset)
567
+                {
568
+                    $indice=$key;
569
+                    $foundindice++;
570
+                    //print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
571
+                    break;
572
+                }
573
+            }
574
+            if (empty($foundindice))
575
+            {
576
+                $this->error="ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
577
+                return -1;
578
+            }
579
+            $sql=$this->build_sql($indice, $array_selected, $array_filterValue);
580
+        }
581
+
582
+        // Run the sql
583
+        $this->sqlusedforexport=$sql;
584
+        dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
585
+        $resql = $this->db->query($sql);
586
+        if ($resql)
587
+        {
588
+            //$this->array_export_label[$indice]
589
+            if ($conf->global->EXPORT_PREFIX_SPEC)
590
+                $filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
591
+            else
592
+                $filename="export_".$datatoexport;
593
+            $filename.='.'.$objmodel->getDriverExtension();
594
+            $dirname=$conf->export->dir_temp.'/'.$user->id;
595
+
596
+            $outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value
597
+
598
+            // Open file
599
+            dol_mkdir($dirname);
600
+            $result=$objmodel->open_file($dirname."/".$filename, $outputlangs);
601
+
602
+            if ($result >= 0)
603
+            {
604
+                // Genere en-tete
605
+                $objmodel->write_header($outputlangs);
606
+
607
+                // Genere ligne de titre
608
+                $objmodel->write_title($this->array_export_fields[$indice],$array_selected,$outputlangs,$this->array_export_TypeFields[$indice]);
609
+
610
+                while ($obj = $this->db->fetch_object($resql))
611
+                {
612
+                    // Process special operations
613
+                    if (! empty($this->array_export_special[$indice]))
614
+                    {
615
+                        foreach ($this->array_export_special[$indice] as $key => $value)
616
+                        {
617
+                            if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
618
+                            // Operation NULLIFNEG
619
+                            if ($this->array_export_special[$indice][$key]=='NULLIFNEG')
620
+                            {
621
+                                //$alias=$this->array_export_alias[$indice][$key];
622
+                                $alias=str_replace(array('.', '-','(',')'),'_',$key);
623
+                                if ($obj->$alias < 0) $obj->$alias='';
624
+                            }
625
+                            // Operation ZEROIFNEG
626
+                            elseif ($this->array_export_special[$indice][$key]=='ZEROIFNEG')
627
+                            {
628
+                                //$alias=$this->array_export_alias[$indice][$key];
629
+                                $alias=str_replace(array('.', '-','(',')'),'_',$key);
630
+                                if ($obj->$alias < 0) $obj->$alias='0';
631
+                            }
632
+                            // Operation INVOICEREMAINTOPAY
633
+                            elseif ($this->array_export_special[$indice][$key]=='getRemainToPay')
634
+                            {
635
+                                //$alias=$this->array_export_alias[$indice][$key];
636
+                                $alias=str_replace(array('.', '-','(',')'),'_',$key);
637
+                                $remaintopay='';
638
+                                if ($obj->f_rowid > 0)
639
+                                {
640
+                                    global $tmpobjforcomputecall;
641
+                                    if (! is_object($tmpobjforcomputecall))
642
+                                    {
643
+                                        include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
644
+                                        $tmpobjforcomputecall=new Facture($this->db);
645
+                                    }
646
+                                    $tmpobjforcomputecall->id = $obj->f_rowid;
647
+                                    $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
648
+                                    $remaintopay=$tmpobjforcomputecall->getRemainToPay();
649
+                                }
650
+                                $obj->$alias=$remaintopay;
651
+                            }
652
+                            else
653
+                            {
654
+                                // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
655
+                                $computestring=$this->array_export_special[$indice][$key];
656
+                                $tmp=dol_eval($computestring, 1, 0);
657
+                                $obj->$alias=$tmp;
658
+
659
+                                $this->error="ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
660
+                                return -1;
661
+                            }
662
+                        }
663
+                    }
664
+                    // end of special operation processing
665
+                    $objmodel->write_record($array_selected,$obj,$outputlangs,$this->array_export_TypeFields[$indice]);
666
+                }
667
+
668
+                // Genere en-tete
669
+                $objmodel->write_footer($outputlangs);
670
+
671
+                // Close file
672
+                $objmodel->close_file();
673
+
674
+                return 1;
675
+            }
676
+            else
677
+            {
678
+                $this->error=$objmodel->error;
679
+                dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
680
+                return -1;
681
+            }
682
+        }
683
+        else
684
+        {
685
+            $this->error=$this->db->error()." - sql=".$sql;
686
+            return -1;
687
+        }
688
+    }
689
+
690
+    /**
691
+     *  Save an export model in database
692
+     *
693
+     *  @param		User	$user 	Object user that save
694
+     *  @return		int				<0 if KO, >0 if OK
695
+     */
696
+    function create($user)
697
+    {
698
+        global $conf;
699
+
700
+        dol_syslog("Export.class.php::create");
701
+
702
+        $this->db->begin();
703
+
704
+        $filter='';
705
+
706
+        $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
707
+        $sql.= 'label,';
708
+        $sql.= 'type,';
709
+        $sql.= 'field,';
710
+        $sql.= 'fk_user,';
711
+        $sql.= 'filter';
712
+        $sql.= ') VALUES (';
713
+        $sql.= "'".$this->db->escape($this->model_name)."',";
714
+        $sql.= "'".$this->db->escape($this->datatoexport)."',";
715
+        $sql.= "'".$this->db->escape($this->hexa)."',";
716
+        $sql.= "'".$user->id."',";
717
+        $sql.= "'".$this->db->escape($this->hexafiltervalue)."'";
718
+        $sql.= ")";
719
+
720
+        dol_syslog(get_class($this)."::create", LOG_DEBUG);
721
+        $resql=$this->db->query($sql);
722
+        if ($resql)
723
+        {
724
+            $this->db->commit();
725
+            return 1;
726
+        }
560 727
         else
561
-		{
562
-			// Define value for indice from $datatoexport
563
-			$foundindice=0;
564
-			foreach($this->array_export_code as $key => $dataset)
565
-			{
566
-				if ($datatoexport == $dataset)
567
-				{
568
-					$indice=$key;
569
-					$foundindice++;
570
-					//print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
571
-					break;
572
-				}
573
-			}
574
-			if (empty($foundindice))
575
-			{
576
-				$this->error="ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
577
-				return -1;
578
-			}
579
-        	$sql=$this->build_sql($indice, $array_selected, $array_filterValue);
580
-		}
581
-
582
-		// Run the sql
583
-		$this->sqlusedforexport=$sql;
584
-		dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
585
-		$resql = $this->db->query($sql);
586
-		if ($resql)
587
-		{
588
-			//$this->array_export_label[$indice]
589
-			if ($conf->global->EXPORT_PREFIX_SPEC)
590
-				$filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
591
-			else
592
-				$filename="export_".$datatoexport;
593
-			$filename.='.'.$objmodel->getDriverExtension();
594
-			$dirname=$conf->export->dir_temp.'/'.$user->id;
595
-
596
-			$outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value
597
-
598
-			// Open file
599
-			dol_mkdir($dirname);
600
-			$result=$objmodel->open_file($dirname."/".$filename, $outputlangs);
601
-
602
-			if ($result >= 0)
603
-			{
604
-				// Genere en-tete
605
-				$objmodel->write_header($outputlangs);
606
-
607
-				// Genere ligne de titre
608
-				$objmodel->write_title($this->array_export_fields[$indice],$array_selected,$outputlangs,$this->array_export_TypeFields[$indice]);
609
-
610
-				while ($obj = $this->db->fetch_object($resql))
611
-				{
612
-					// Process special operations
613
-					if (! empty($this->array_export_special[$indice]))
614
-					{
615
-						foreach ($this->array_export_special[$indice] as $key => $value)
616
-						{
617
-							if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
618
-							// Operation NULLIFNEG
619
-							if ($this->array_export_special[$indice][$key]=='NULLIFNEG')
620
-							{
621
-								//$alias=$this->array_export_alias[$indice][$key];
622
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
623
-								if ($obj->$alias < 0) $obj->$alias='';
624
-							}
625
-							// Operation ZEROIFNEG
626
-							elseif ($this->array_export_special[$indice][$key]=='ZEROIFNEG')
627
-							{
628
-								//$alias=$this->array_export_alias[$indice][$key];
629
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
630
-								if ($obj->$alias < 0) $obj->$alias='0';
631
-							}
632
-							// Operation INVOICEREMAINTOPAY
633
-							elseif ($this->array_export_special[$indice][$key]=='getRemainToPay')
634
-							{
635
-								//$alias=$this->array_export_alias[$indice][$key];
636
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
637
-								$remaintopay='';
638
-								if ($obj->f_rowid > 0)
639
-								{
640
-								    global $tmpobjforcomputecall;
641
-								    if (! is_object($tmpobjforcomputecall))
642
-								    {
643
-								        include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
644
-								        $tmpobjforcomputecall=new Facture($this->db);
645
-								    }
646
-								    $tmpobjforcomputecall->id = $obj->f_rowid;
647
-								    $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
648
-								    $remaintopay=$tmpobjforcomputecall->getRemainToPay();
649
-								}
650
-								$obj->$alias=$remaintopay;
651
-							}
652
-							else
653
-							{
654
-							    // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
655
-							    $computestring=$this->array_export_special[$indice][$key];
656
-							    $tmp=dol_eval($computestring, 1, 0);
657
-							    $obj->$alias=$tmp;
658
-
659
-							    $this->error="ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
660
-							    return -1;
661
-							}
662
-						}
663
-					}
664
-					// end of special operation processing
665
-					$objmodel->write_record($array_selected,$obj,$outputlangs,$this->array_export_TypeFields[$indice]);
666
-				}
667
-
668
-				// Genere en-tete
669
-				$objmodel->write_footer($outputlangs);
670
-
671
-				// Close file
672
-				$objmodel->close_file();
673
-
674
-        		return 1;
675
-			}
676
-			else
677
-			{
678
-				$this->error=$objmodel->error;
679
-				dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
680
-				return -1;
681
-			}
682
-		}
683
-		else
684
-		{
685
-			$this->error=$this->db->error()." - sql=".$sql;
686
-			return -1;
687
-		}
688
-	}
689
-
690
-	/**
691
-	 *  Save an export model in database
692
-	 *
693
-	 *  @param		User	$user 	Object user that save
694
-	 *  @return		int				<0 if KO, >0 if OK
695
-	 */
696
-	function create($user)
697
-	{
698
-		global $conf;
699
-
700
-		dol_syslog("Export.class.php::create");
701
-
702
-		$this->db->begin();
703
-
704
-		$filter='';
705
-
706
-		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
707
-		$sql.= 'label,';
708
-		$sql.= 'type,';
709
-		$sql.= 'field,';
710
-		$sql.= 'fk_user,';
711
-		$sql.= 'filter';
712
-		$sql.= ') VALUES (';
713
-		$sql.= "'".$this->db->escape($this->model_name)."',";
714
-		$sql.= "'".$this->db->escape($this->datatoexport)."',";
715
-		$sql.= "'".$this->db->escape($this->hexa)."',";
716
-		$sql.= "'".$user->id."',";
717
-		$sql.= "'".$this->db->escape($this->hexafiltervalue)."'";
718
-		$sql.= ")";
719
-
720
-		dol_syslog(get_class($this)."::create", LOG_DEBUG);
721
-		$resql=$this->db->query($sql);
722
-		if ($resql)
723
-		{
724
-			$this->db->commit();
725
-			return 1;
726
-		}
727
-		else
728
-		{
729
-			$this->error=$this->db->lasterror();
730
-			$this->errno=$this->db->lasterrno();
731
-			$this->db->rollback();
732
-			return -1;
733
-		}
734
-	}
735
-
736
-	/**
737
-	 *  Load an export profil from database
738
-	 *
739
-	 *  @param		int		$id		Id of profil to load
740
-	 *  @return		int				<0 if KO, >0 if OK
741
-	 */
742
-	function fetch($id)
743
-	{
744
-		$sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
745
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
746
-		$sql.= ' WHERE em.rowid = '.$id;
747
-
748
-		dol_syslog("Export::fetch", LOG_DEBUG);
749
-		$result = $this->db->query($sql);
750
-		if ($result)
751
-		{
752
-			$obj = $this->db->fetch_object($result);
753
-			if ($obj)
754
-			{
755
-				$this->id				= $obj->rowid;
756
-				$this->model_name		= $obj->label;
757
-				$this->datatoexport		= $obj->type;
758
-
759
-				$this->hexa				= $obj->field;
760
-				$this->hexafiltervalue	= $obj->filter;
761
-
762
-				return 1;
763
-			}
764
-			else
765
-			{
766
-				$this->error="ModelNotFound";
767
-				return -2;
768
-			}
769
-		}
770
-		else
771
-		{
772
-			dol_print_error($this->db);
773
-			return -3;
774
-		}
775
-	}
776
-
777
-
778
-	/**
779
-	 *	Delete object in database
780
-	 *
781
-	 *	@param      User		$user        	User that delete
782
-	 *  @param      int			$notrigger	    0=launch triggers after, 1=disable triggers
783
-	 *	@return		int							<0 if KO, >0 if OK
784
-	 */
785
-	function delete($user, $notrigger=0)
786
-	{
787
-		global $conf, $langs;
788
-		$error=0;
789
-
790
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
791
-		$sql.= " WHERE rowid=".$this->id;
792
-
793
-		$this->db->begin();
794
-
795
-		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
796
-		$resql = $this->db->query($sql);
797
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
798
-
799
-		if (! $error)
800
-		{
801
-			if (! $notrigger)
802
-			{
803
-				// Uncomment this and change MYOBJECT to your own tag if you
804
-				// want this action call a trigger.
805
-
806
-				//// Call triggers
807
-				//include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
808
-				//$interface=new Interfaces($this->db);
809
-				//$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
810
-				//if ($result < 0) { $error++; $this->errors=$interface->errors; }
811
-				//// End call triggers
812
-			}
813
-		}
814
-
815
-		// Commit or rollback
816
-		if ($error)
817
-		{
818
-			foreach($this->errors as $errmsg)
819
-			{
820
-				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
821
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
822
-			}
823
-			$this->db->rollback();
824
-			return -1*$error;
825
-		}
826
-		else
827
-		{
828
-			$this->db->commit();
829
-			return 1;
830
-		}
831
-	}
728
+        {
729
+            $this->error=$this->db->lasterror();
730
+            $this->errno=$this->db->lasterrno();
731
+            $this->db->rollback();
732
+            return -1;
733
+        }
734
+    }
735
+
736
+    /**
737
+     *  Load an export profil from database
738
+     *
739
+     *  @param		int		$id		Id of profil to load
740
+     *  @return		int				<0 if KO, >0 if OK
741
+     */
742
+    function fetch($id)
743
+    {
744
+        $sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
745
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
746
+        $sql.= ' WHERE em.rowid = '.$id;
747
+
748
+        dol_syslog("Export::fetch", LOG_DEBUG);
749
+        $result = $this->db->query($sql);
750
+        if ($result)
751
+        {
752
+            $obj = $this->db->fetch_object($result);
753
+            if ($obj)
754
+            {
755
+                $this->id				= $obj->rowid;
756
+                $this->model_name		= $obj->label;
757
+                $this->datatoexport		= $obj->type;
758
+
759
+                $this->hexa				= $obj->field;
760
+                $this->hexafiltervalue	= $obj->filter;
761
+
762
+                return 1;
763
+            }
764
+            else
765
+            {
766
+                $this->error="ModelNotFound";
767
+                return -2;
768
+            }
769
+        }
770
+        else
771
+        {
772
+            dol_print_error($this->db);
773
+            return -3;
774
+        }
775
+    }
776
+
777
+
778
+    /**
779
+     *	Delete object in database
780
+     *
781
+     *	@param      User		$user        	User that delete
782
+     *  @param      int			$notrigger	    0=launch triggers after, 1=disable triggers
783
+     *	@return		int							<0 if KO, >0 if OK
784
+     */
785
+    function delete($user, $notrigger=0)
786
+    {
787
+        global $conf, $langs;
788
+        $error=0;
789
+
790
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
791
+        $sql.= " WHERE rowid=".$this->id;
792
+
793
+        $this->db->begin();
794
+
795
+        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
796
+        $resql = $this->db->query($sql);
797
+        if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
798
+
799
+        if (! $error)
800
+        {
801
+            if (! $notrigger)
802
+            {
803
+                // Uncomment this and change MYOBJECT to your own tag if you
804
+                // want this action call a trigger.
805
+
806
+                //// Call triggers
807
+                //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
808
+                //$interface=new Interfaces($this->db);
809
+                //$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
810
+                //if ($result < 0) { $error++; $this->errors=$interface->errors; }
811
+                //// End call triggers
812
+            }
813
+        }
814
+
815
+        // Commit or rollback
816
+        if ($error)
817
+        {
818
+            foreach($this->errors as $errmsg)
819
+            {
820
+                dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
821
+                $this->error.=($this->error?', '.$errmsg:$errmsg);
822
+            }
823
+            $this->db->rollback();
824
+            return -1*$error;
825
+        }
826
+        else
827
+        {
828
+            $this->db->commit();
829
+            return 1;
830
+        }
831
+    }
832 832
 
833 833
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
834
-	/**
835
-	 *	Output list all export models
836
-	 *  TODO Move this into a class htmlxxx.class.php
837
-	 *
838
-	 *	@return	void
839
-	 */
840
-	function list_export_model()
841
-	{
834
+    /**
835
+     *	Output list all export models
836
+     *  TODO Move this into a class htmlxxx.class.php
837
+     *
838
+     *	@return	void
839
+     */
840
+    function list_export_model()
841
+    {
842 842
         // phpcs:enable
843
-		global $conf, $langs;
844
-
845
-		$sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
846
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model as em";
847
-		$sql.= " ORDER BY rowid";
848
-
849
-		$result = $this->db->query($sql);
850
-		if ($result)
851
-		{
852
-			$num = $this->db->num_rows($result);
853
-			$i = 0;
854
-			while ($i < $num)
855
-			{
856
-				$obj = $this->db->fetch_object($result);
857
-				$keyModel = array_search($obj->type, $this->array_export_code);
858
-				print "<tr>";
859
-				print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
860
-				print '<td>';
861
-				print img_object($this->array_export_module[$keyModel]->getName(),$this->array_export_icon[$keyModel]).' ';
862
-				print $this->array_export_module[$keyModel]->getName().' - ';
863
-				// recuperation du nom de l'export
864
-
865
-				$string=$langs->trans($this->array_export_label[$keyModel]);
866
-				print ($string!=$this->array_export_label[$keyModel]?$string:$this->array_export_label[$keyModel]);
867
-				print '</td>';
868
-				//print '<td>'.$obj->type.$keyModel.'</td>';
869
-				print '<td>'.str_replace(',',' , ',$obj->field).'</td>';
870
-				if (! empty($obj->filter)) {
871
-					$filter = json_decode($obj->filter, true);
872
-					print '<td>'.str_replace(',',' , ',$filter['field']).'</td>';
873
-					print '<td>'.str_replace(',',' , ',$filter['value']).'</td>';
874
-				}
875
-				// suppression de l'export
876
-				print '<td align="right">';
877
-				print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&id='.$obj->rowid.'">';
878
-				print img_delete();
879
-				print '</a>';
880
-				print "</tr>";
881
-
882
-				$i++;
883
-			}
884
-		}
885
-		else {
886
-			dol_print_error($this->db);
887
-		}
888
-	}
843
+        global $conf, $langs;
844
+
845
+        $sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
846
+        $sql.= " FROM ".MAIN_DB_PREFIX."export_model as em";
847
+        $sql.= " ORDER BY rowid";
848
+
849
+        $result = $this->db->query($sql);
850
+        if ($result)
851
+        {
852
+            $num = $this->db->num_rows($result);
853
+            $i = 0;
854
+            while ($i < $num)
855
+            {
856
+                $obj = $this->db->fetch_object($result);
857
+                $keyModel = array_search($obj->type, $this->array_export_code);
858
+                print "<tr>";
859
+                print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
860
+                print '<td>';
861
+                print img_object($this->array_export_module[$keyModel]->getName(),$this->array_export_icon[$keyModel]).' ';
862
+                print $this->array_export_module[$keyModel]->getName().' - ';
863
+                // recuperation du nom de l'export
864
+
865
+                $string=$langs->trans($this->array_export_label[$keyModel]);
866
+                print ($string!=$this->array_export_label[$keyModel]?$string:$this->array_export_label[$keyModel]);
867
+                print '</td>';
868
+                //print '<td>'.$obj->type.$keyModel.'</td>';
869
+                print '<td>'.str_replace(',',' , ',$obj->field).'</td>';
870
+                if (! empty($obj->filter)) {
871
+                    $filter = json_decode($obj->filter, true);
872
+                    print '<td>'.str_replace(',',' , ',$filter['field']).'</td>';
873
+                    print '<td>'.str_replace(',',' , ',$filter['value']).'</td>';
874
+                }
875
+                // suppression de l'export
876
+                print '<td align="right">';
877
+                print '<a href="'.$_SERVER["PHP_SELF"].'?action=deleteprof&id='.$obj->rowid.'">';
878
+                print img_delete();
879
+                print '</a>';
880
+                print "</tr>";
881
+
882
+                $i++;
883
+            }
884
+        }
885
+        else {
886
+            dol_print_error($this->db);
887
+        }
888
+    }
889 889
 }
Please login to merge, or discard this patch.
Spacing   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -35,20 +35,20 @@  discard block
 block discarded – undo
35 35
      */
36 36
     public $db;
37 37
 
38
-	var $array_export_code=array();             // Tableau de "idmodule_numlot"
39
-	var $array_export_module=array();           // Tableau de "nom de modules"
40
-	var $array_export_label=array();            // Tableau de "libelle de lots"
41
-	var $array_export_sql_start=array();        // Tableau des "requetes sql"
42
-	var $array_export_sql_end=array();          // Tableau des "requetes sql"
43
-	var $array_export_sql_order=array();        // Tableau des "requetes sql"
44
-
45
-	var $array_export_fields=array();           // Tableau des listes de champ+libelle a exporter
46
-	var $array_export_TypeFields=array();		// Tableau des listes de champ+Type de filtre
47
-	var $array_export_FilterValue=array();		// Tableau des listes de champ+Valeur a filtrer
48
-	var $array_export_entities=array();         // Tableau des listes de champ+alias a exporter
49
-	var $array_export_dependencies=array();     // array of list of entities that must take care of the DISTINCT if a field is added into export
50
-	var $array_export_special=array();          // Tableau des operations speciales sur champ
51
-    var $array_export_examplevalues=array();    // array with examples
38
+	var $array_export_code = array(); // Tableau de "idmodule_numlot"
39
+	var $array_export_module = array(); // Tableau de "nom de modules"
40
+	var $array_export_label = array(); // Tableau de "libelle de lots"
41
+	var $array_export_sql_start = array(); // Tableau des "requetes sql"
42
+	var $array_export_sql_end = array(); // Tableau des "requetes sql"
43
+	var $array_export_sql_order = array(); // Tableau des "requetes sql"
44
+
45
+	var $array_export_fields = array(); // Tableau des listes de champ+libelle a exporter
46
+	var $array_export_TypeFields = array(); // Tableau des listes de champ+Type de filtre
47
+	var $array_export_FilterValue = array(); // Tableau des listes de champ+Valeur a filtrer
48
+	var $array_export_entities = array(); // Tableau des listes de champ+alias a exporter
49
+	var $array_export_dependencies = array(); // array of list of entities that must take care of the DISTINCT if a field is added into export
50
+	var $array_export_special = array(); // Tableau des operations speciales sur champ
51
+    var $array_export_examplevalues = array(); // array with examples
52 52
 
53 53
 	// To store export modules
54 54
 	var $hexa;
@@ -66,7 +66,7 @@  discard block
 block discarded – undo
66 66
 	 */
67 67
 	function __construct($db)
68 68
 	{
69
-		$this->db=$db;
69
+		$this->db = $db;
70 70
 	}
71 71
 
72 72
 
@@ -78,38 +78,38 @@  discard block
 block discarded – undo
78 78
 	 *    @param  	string		$filter    	Load a particular dataset only
79 79
 	 *    @return	int						<0 if KO, >0 if OK
80 80
 	 */
81
-	function load_arrays($user,$filter='')
81
+	function load_arrays($user, $filter = '')
82 82
 	{
83 83
         // phpcs:enable
84
-		global $langs,$conf,$mysoc;
84
+		global $langs, $conf, $mysoc;
85 85
 
86 86
 		dol_syslog(get_class($this)."::load_arrays user=".$user->id." filter=".$filter);
87 87
 
88
-        $i=0;
88
+        $i = 0;
89 89
 
90 90
         // Define list of modules directories into modulesdir
91 91
         require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
92 92
 
93 93
         $modulesdir = dolGetModulesDirs();
94 94
 
95
-		foreach($modulesdir as $dir)
95
+		foreach ($modulesdir as $dir)
96 96
 		{
97 97
 			// Search available exports
98
-			$handle=@opendir(dol_osencode($dir));
98
+			$handle = @opendir(dol_osencode($dir));
99 99
 			if (is_resource($handle))
100 100
 			{
101 101
                 // Search module files
102
-			    while (($file = readdir($handle))!==false)
102
+			    while (($file = readdir($handle)) !== false)
103 103
 				{
104
-					if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i",$file,$reg))
104
+					if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg))
105 105
 					{
106
-						$modulename=$reg[1];
106
+						$modulename = $reg[1];
107 107
 
108 108
 						// Defined if module is enabled
109
-						$enabled=true;
110
-						$part=strtolower(preg_replace('/^mod/i','',$modulename));
111
-						if ($part == 'propale') $part='propal';
112
-						if (empty($conf->$part->enabled)) $enabled=false;
109
+						$enabled = true;
110
+						$part = strtolower(preg_replace('/^mod/i', '', $modulename));
111
+						if ($part == 'propale') $part = 'propal';
112
+						if (empty($conf->$part->enabled)) $enabled = false;
113 113
 
114 114
 						if ($enabled)
115 115
 						{
@@ -121,32 +121,32 @@  discard block
 block discarded – undo
121 121
 
122 122
 							if (isset($module->export_code) && is_array($module->export_code))
123 123
 							{
124
-							    foreach($module->export_code as $r => $value)
124
+							    foreach ($module->export_code as $r => $value)
125 125
 								{
126 126
                                     //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
127 127
 								    if ($filter && ($filter != $module->export_code[$r])) continue;
128 128
 
129 129
                                     // Test if condition to show are ok
130
-                                    if (! empty($module->export_enabled[$r]) && ! verifCond($module->export_enabled[$r])) continue;
130
+                                    if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue;
131 131
 
132 132
                                     // Test if permissions are ok
133
-									$bool=true;
133
+									$bool = true;
134 134
 									if (isset($module->export_permission))
135 135
 									{
136
-										foreach($module->export_permission[$r] as $val)
136
+										foreach ($module->export_permission[$r] as $val)
137 137
 										{
138
-	    									$perm=$val;
138
+	    									$perm = $val;
139 139
 	    									//print_r("$perm[0]-$perm[1]-$perm[2]<br>");
140
-	    									if (! empty($perm[2]))
140
+	    									if (!empty($perm[2]))
141 141
 	    									{
142
-	    										$bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
142
+	    										$bool = $user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
143 143
 	    									}
144 144
 	    									else
145 145
 	    									{
146
-	    										$bool=$user->rights->{$perm[0]}->{$perm[1]};
146
+	    										$bool = $user->rights->{$perm[0]}->{$perm[1]};
147 147
 	    									}
148
-	    									if ($perm[0]=='user' && $user->admin) $bool=true;
149
-	    									if (! $bool) break;
148
+	    									if ($perm[0] == 'user' && $user->admin) $bool = true;
149
+	    									if (!$bool) break;
150 150
 										}
151 151
 									}
152 152
 									//print $bool." $perm[0]"."<br>";
@@ -155,45 +155,45 @@  discard block
 block discarded – undo
155 155
 									//	          if ($bool)
156 156
 									//	          {
157 157
 									// Charge fichier lang en rapport
158
-									$langtoload=$module->getLangFilesArray();
158
+									$langtoload = $module->getLangFilesArray();
159 159
 									if (is_array($langtoload))
160 160
 									{
161
-										foreach($langtoload as $key)
161
+										foreach ($langtoload as $key)
162 162
 										{
163 163
 											$langs->load($key);
164 164
 										}
165 165
 									}
166 166
 
167 167
 									// Module
168
-									$this->array_export_module[$i]=$module;
168
+									$this->array_export_module[$i] = $module;
169 169
 									// Permission
170
-									$this->array_export_perms[$i]=$bool;
170
+									$this->array_export_perms[$i] = $bool;
171 171
 									// Icon
172
-									$this->array_export_icon[$i]=(isset($module->export_icon[$r])?$module->export_icon[$r]:$module->picto);
172
+									$this->array_export_icon[$i] = (isset($module->export_icon[$r]) ? $module->export_icon[$r] : $module->picto);
173 173
 									// Code du dataset export
174
-									$this->array_export_code[$i]=$module->export_code[$r];
174
+									$this->array_export_code[$i] = $module->export_code[$r];
175 175
 									// Libelle du dataset export
176
-									$this->array_export_label[$i]=$module->getExportDatasetLabel($r);
176
+									$this->array_export_label[$i] = $module->getExportDatasetLabel($r);
177 177
 									// Tableau des champ a exporter (cle=champ, valeur=libelle)
178
-									$this->array_export_fields[$i]=$module->export_fields_array[$r];
178
+									$this->array_export_fields[$i] = $module->export_fields_array[$r];
179 179
 									// Tableau des champs a filtrer (cle=champ, valeur1=type de donnees) on verifie que le module a des filtres
180
-									$this->array_export_TypeFields[$i]=(isset($module->export_TypeFields_array[$r])?$module->export_TypeFields_array[$r]:'');
180
+									$this->array_export_TypeFields[$i] = (isset($module->export_TypeFields_array[$r]) ? $module->export_TypeFields_array[$r] : '');
181 181
 									// Tableau des entites a exporter (cle=champ, valeur=entite)
182
-									$this->array_export_entities[$i]=$module->export_entities_array[$r];
182
+									$this->array_export_entities[$i] = $module->export_entities_array[$r];
183 183
 									// Tableau des entites qui requiert abandon du DISTINCT (cle=entite, valeur=champ id child records)
184
-									$this->array_export_dependencies[$i]=(! empty($module->export_dependencies_array[$r])?$module->export_dependencies_array[$r]:'');
184
+									$this->array_export_dependencies[$i] = (!empty($module->export_dependencies_array[$r]) ? $module->export_dependencies_array[$r] : '');
185 185
 									// Tableau des operations speciales sur champ
186
-									$this->array_export_special[$i]=(! empty($module->export_special_array[$r])?$module->export_special_array[$r]:'');
186
+									$this->array_export_special[$i] = (!empty($module->export_special_array[$r]) ? $module->export_special_array[$r] : '');
187 187
             						// Array of examples
188
-            						$this->array_export_examplevalues[$i]=$module->export_examplevalues_array[$r];
188
+            						$this->array_export_examplevalues[$i] = $module->export_examplevalues_array[$r];
189 189
 
190 190
 									// Requete sql du dataset
191
-									$this->array_export_sql_start[$i]=$module->export_sql_start[$r];
192
-									$this->array_export_sql_end[$i]=$module->export_sql_end[$r];
193
-									$this->array_export_sql_order[$i]=$module->export_sql_order[$r];
191
+									$this->array_export_sql_start[$i] = $module->export_sql_start[$r];
192
+									$this->array_export_sql_end[$i] = $module->export_sql_end[$r];
193
+									$this->array_export_sql_order[$i] = $module->export_sql_order[$r];
194 194
 									//$this->array_export_sql[$i]=$module->export_sql[$r];
195 195
 
196
-									dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(! empty($module->export_fields_code[$r])?count($module->export_fields_code[$r]):''));
196
+									dol_syslog(get_class($this)."::load_arrays loaded for module ".$modulename." with index ".$i.", dataset=".$module->export_code[$r].", nb of fields=".(!empty($module->export_fields_code[$r]) ?count($module->export_fields_code[$r]) : ''));
197 197
 									$i++;
198 198
 									//	          }
199 199
 								}
@@ -223,42 +223,42 @@  discard block
 block discarded – undo
223 223
 	{
224 224
         // phpcs:enable
225 225
 		// Build the sql request
226
-		$sql=$this->array_export_sql_start[$indice];
227
-		$i=0;
226
+		$sql = $this->array_export_sql_start[$indice];
227
+		$i = 0;
228 228
 
229 229
 		//print_r($array_selected);
230 230
 		foreach ($this->array_export_fields[$indice] as $key => $value)
231 231
 		{
232
-			if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
233
-            if (preg_match('/^none\./', $key)) continue;                    // A field that must not appears into SQL
234
-			if ($i > 0) $sql.=', ';
232
+			if (!array_key_exists($key, $array_selected)) continue; // Field not selected
233
+            if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL
234
+			if ($i > 0) $sql .= ', ';
235 235
 			else $i++;
236 236
 
237
-			if (strpos($key, ' as ')===false) {
238
-				$newfield=$key.' as '.str_replace(array('.', '-','(',')'),'_',$key);
237
+			if (strpos($key, ' as ') === false) {
238
+				$newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key);
239 239
 			} else {
240
-				$newfield=$key;
240
+				$newfield = $key;
241 241
 			}
242 242
 
243
-			$sql.=$newfield;
243
+			$sql .= $newfield;
244 244
 		}
245
-		$sql.=$this->array_export_sql_end[$indice];
245
+		$sql .= $this->array_export_sql_end[$indice];
246 246
 
247 247
 		// Add the WHERE part. Filtering into sql if a filtering array is provided
248 248
 		if (is_array($array_filterValue) && !empty($array_filterValue))
249 249
 		{
250
-			$sqlWhere='';
250
+			$sqlWhere = '';
251 251
 			// Loop on each condition to add
252 252
 			foreach ($array_filterValue as $key => $value)
253 253
 			{
254 254
 			    if (preg_match('/GROUP_CONCAT/i', $key)) continue;
255
-				if ($value != '') $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
255
+				if ($value != '') $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
256 256
 			}
257
-			$sql.=$sqlWhere;
257
+			$sql .= $sqlWhere;
258 258
 		}
259 259
 
260 260
 		// Add the order
261
-		$sql.=$this->array_export_sql_order[$indice];
261
+		$sql .= $this->array_export_sql_order[$indice];
262 262
 
263 263
 		// Add the HAVING part.
264 264
 		if (is_array($array_filterValue) && !empty($array_filterValue))
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 		    // Loop on each condition to add
267 267
 		    foreach ($array_filterValue as $key => $value)
268 268
 		    {
269
-		        if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
269
+		        if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
270 270
 		    }
271 271
 		}
272 272
 
@@ -290,25 +290,25 @@  discard block
 block discarded – undo
290 290
 		// build the input field on depend of the type of file
291 291
 		switch ($InfoFieldList[0]) {
292 292
 			case 'Text':
293
-				if (! (strpos($ValueField, '%') === false))
294
-					$szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'";
293
+				if (!(strpos($ValueField, '%') === false))
294
+					$szFilterQuery .= " ".$NameField." LIKE '".$ValueField."'";
295 295
 				else
296
-					$szFilterQuery.=" ".$NameField." = '".$ValueField."'";
296
+					$szFilterQuery .= " ".$NameField." = '".$ValueField."'";
297 297
 				break;
298 298
 			case 'Date':
299 299
 				if (strpos($ValueField, "+") > 0)
300 300
 				{
301 301
 					// mode plage
302 302
 					$ValueArray = explode("+", $ValueField);
303
-					$szFilterQuery ="(".$this->conditionDate($NameField,trim($ValueArray[0]),">=");
304
-					$szFilterQuery.=" AND ".$this->conditionDate($NameField,trim($ValueArray[1]),"<=").")";
303
+					$szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">=");
304
+					$szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")";
305 305
 				}
306 306
 				else
307 307
 				{
308
-					if (is_numeric(substr($ValueField,0,1)))
309
-						$szFilterQuery=$this->conditionDate($NameField,trim($ValueField),"=");
308
+					if (is_numeric(substr($ValueField, 0, 1)))
309
+						$szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "=");
310 310
 					else
311
-						$szFilterQuery=$this->conditionDate($NameField,trim(substr($ValueField,1)),substr($ValueField,0,1));
311
+						$szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1));
312 312
 				}
313 313
 				break;
314 314
 			case 'Duree':
@@ -319,29 +319,29 @@  discard block
 block discarded – undo
319 319
 				{
320 320
 					// mode plage
321 321
 					$ValueArray = explode("+", $ValueField);
322
-					$szFilterQuery ="(".$NameField.">=".$ValueArray[0];
323
-					$szFilterQuery.=" AND ".$NameField."<=".$ValueArray[1].")";
322
+					$szFilterQuery = "(".$NameField.">=".$ValueArray[0];
323
+					$szFilterQuery .= " AND ".$NameField."<=".$ValueArray[1].")";
324 324
 				}
325 325
 				else
326 326
 				{
327
-					if (is_numeric(substr($ValueField,0,1)))
328
-						$szFilterQuery=" ".$NameField."=".$ValueField;
327
+					if (is_numeric(substr($ValueField, 0, 1)))
328
+						$szFilterQuery = " ".$NameField."=".$ValueField;
329 329
 					else
330
-						$szFilterQuery=" ".$NameField.substr($ValueField,0,1).substr($ValueField,1);
330
+						$szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1);
331 331
 				}
332 332
 				break;
333 333
 			case 'Boolean':
334
-				$szFilterQuery=" ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField =='yes' ? 1: 0) );
334
+				$szFilterQuery = " ".$NameField."=".(is_numeric($ValueField) ? $ValueField : ($ValueField == 'yes' ? 1 : 0));
335 335
 				break;
336 336
 			case 'Status':
337 337
 			case 'List':
338 338
 				if (is_numeric($ValueField))
339
-					$szFilterQuery=" ".$NameField."=".$ValueField;
339
+					$szFilterQuery = " ".$NameField."=".$ValueField;
340 340
 				else {
341
-                    if (! (strpos($ValueField, '%') === false))
342
-                        $szFilterQuery=" ".$NameField." LIKE '".$ValueField."'";
341
+                    if (!(strpos($ValueField, '%') === false))
342
+                        $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'";
343 343
                     else
344
-                        $szFilterQuery=" ".$NameField." = '".$ValueField."'";
344
+                        $szFilterQuery = " ".$NameField." = '".$ValueField."'";
345 345
 				}
346 346
 				break;
347 347
 			default:
@@ -362,9 +362,9 @@  discard block
 block discarded – undo
362 362
 	function conditionDate($Field, $Value, $Sens)
363 363
 	{
364 364
 		// TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN
365
-		if (strlen($Value)==4) $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
366
-		elseif (strlen($Value)==6) $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
367
-		else  $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
365
+		if (strlen($Value) == 4) $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
366
+		elseif (strlen($Value) == 6) $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
367
+		else  $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
368 368
 		return $Condition;
369 369
 	}
370 370
 
@@ -380,9 +380,9 @@  discard block
 block discarded – undo
380 380
 	function build_filterField($TypeField, $NameField, $ValueField)
381 381
 	{
382 382
         // phpcs:enable
383
-		global $conf,$langs;
383
+		global $conf, $langs;
384 384
 
385
-		$szFilterField='';
385
+		$szFilterField = '';
386 386
 		$InfoFieldList = explode(":", $TypeField);
387 387
 
388 388
 		// build the input field on depend of the type of file
@@ -390,52 +390,52 @@  discard block
 block discarded – undo
390 390
 		{
391 391
 			case 'Text':
392 392
 			case 'Date':
393
-				$szFilterField='<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
393
+				$szFilterField = '<input type="text" name="'.$NameField.'" value="'.$ValueField.'">';
394 394
 				break;
395 395
 			case 'Duree':
396 396
 			case 'Numeric':
397 397
 			case 'Number':
398 398
 				// Must be a string text to allow to use comparison strings like "<= 999"
399
-			    $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
399
+			    $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
400 400
 				break;
401 401
 			case 'Status':
402
-				if (! empty($conf->global->MAIN_ACTIVATE_HTML5)) $szFilterField='<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
403
-				else $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
402
+				if (!empty($conf->global->MAIN_ACTIVATE_HTML5)) $szFilterField = '<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
403
+				else $szFilterField = '<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
404 404
 				break;
405 405
 			case 'Boolean':
406
-				$szFilterField='<select name="'.$NameField.'" class="flat">';
407
-				$szFilterField.='<option ';
408
-				if ($ValueField=='') $szFilterField.=' selected ';
409
-				$szFilterField.=' value="">&nbsp;</option>';
410
-
411
-				$szFilterField.='<option ';
412
-				if ($ValueField=='yes' || $ValueField == '1') $szFilterField.=' selected ';
413
-				$szFilterField.=' value="1">'.yn(1).'</option>';
414
-
415
-				$szFilterField.='<option ';
416
-				if ($ValueField=='no' || $ValueField=='0') $szFilterField.=' selected ';
417
-				$szFilterField.=' value="0">'.yn(0).'</option>';
418
-				$szFilterField.="</select>";
406
+				$szFilterField = '<select name="'.$NameField.'" class="flat">';
407
+				$szFilterField .= '<option ';
408
+				if ($ValueField == '') $szFilterField .= ' selected ';
409
+				$szFilterField .= ' value="">&nbsp;</option>';
410
+
411
+				$szFilterField .= '<option ';
412
+				if ($ValueField == 'yes' || $ValueField == '1') $szFilterField .= ' selected ';
413
+				$szFilterField .= ' value="1">'.yn(1).'</option>';
414
+
415
+				$szFilterField .= '<option ';
416
+				if ($ValueField == 'no' || $ValueField == '0') $szFilterField .= ' selected ';
417
+				$szFilterField .= ' value="0">'.yn(0).'</option>';
418
+				$szFilterField .= "</select>";
419 419
 				break;
420 420
 			case 'List':
421 421
 				// 0 : Type du champ
422 422
 				// 1 : Nom de la table
423 423
 				// 2 : Nom du champ contenant le libelle
424 424
 				// 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
425
-				if (count($InfoFieldList)==4)
426
-					$keyList=$InfoFieldList[3];
425
+				if (count($InfoFieldList) == 4)
426
+					$keyList = $InfoFieldList[3];
427 427
 				else
428
-					$keyList='rowid';
429
-				$sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
430
-				if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
428
+					$keyList = 'rowid';
429
+				$sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code');
430
+				if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code');
431 431
 				if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code';
432
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[1];
432
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[1];
433 433
 
434 434
 				$resql = $this->db->query($sql);
435 435
 				if ($resql)
436 436
 				{
437
-					$szFilterField='<select class="flat" name="'.$NameField.'">';
438
-					$szFilterField.='<option value="0">&nbsp;</option>';
437
+					$szFilterField = '<select class="flat" name="'.$NameField.'">';
438
+					$szFilterField .= '<option value="0">&nbsp;</option>';
439 439
 					$num = $this->db->num_rows($resql);
440 440
 
441 441
 					$i = 0;
@@ -451,30 +451,30 @@  discard block
 block discarded – undo
451 451
 								continue;
452 452
 							}
453 453
 							//var_dump($InfoFieldList[1]);
454
-							$labeltoshow=dol_trunc($obj->label,18);
454
+							$labeltoshow = dol_trunc($obj->label, 18);
455 455
 							if ($InfoFieldList[1] == 'c_stcomm')
456 456
 							{
457 457
 								$langs->load("companies");
458
-								$labeltoshow=(($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id)?$langs->trans("StatusProspect".$obj->id):$obj->label);
458
+								$labeltoshow = (($langs->trans("StatusProspect".$obj->id) != "StatusProspect".$obj->id) ? $langs->trans("StatusProspect".$obj->id) : $obj->label);
459 459
 							}
460 460
 							if ($InfoFieldList[1] == 'c_country')
461 461
 							{
462 462
 								//var_dump($sql);
463 463
 								$langs->load("dict");
464
-								$labeltoshow=(($langs->trans("Country".$obj->code) != "Country".$obj->code)?$langs->trans("Country".$obj->code):$obj->label);
464
+								$labeltoshow = (($langs->trans("Country".$obj->code) != "Country".$obj->code) ? $langs->trans("Country".$obj->code) : $obj->label);
465 465
 							}
466 466
 							if (!empty($ValueField) && $ValueField == $obj->rowid)
467 467
 							{
468
-								$szFilterField.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
468
+								$szFilterField .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
469 469
 							}
470 470
 							else
471 471
 							{
472
-								$szFilterField.='<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
472
+								$szFilterField .= '<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
473 473
 							}
474 474
 							$i++;
475 475
 						}
476 476
 					}
477
-					$szFilterField.="</select>";
477
+					$szFilterField .= "</select>";
478 478
 
479 479
 					$this->db->free($resql);
480 480
 				}
@@ -495,12 +495,12 @@  discard block
 block discarded – undo
495 495
 	{
496 496
         global $langs;
497 497
 
498
-		$szMsg='';
498
+		$szMsg = '';
499 499
 		$InfoFieldList = explode(":", $TypeField);
500 500
 		// build the input field on depend of the type of file
501 501
 		switch ($InfoFieldList[0]) {
502 502
 			case 'Text':
503
-				$szMsg= $langs->trans('ExportStringFilter');
503
+				$szMsg = $langs->trans('ExportStringFilter');
504 504
 				break;
505 505
 			case 'Date':
506 506
 				$szMsg = $langs->trans('ExportDateFilter');
@@ -535,37 +535,37 @@  discard block
 block discarded – undo
535 535
 	function build_file($user, $model, $datatoexport, $array_selected, $array_filterValue, $sqlquery = '')
536 536
  	{
537 537
         // phpcs:enable
538
-		global $conf,$langs;
538
+		global $conf, $langs;
539 539
 
540
-		$indice=0;
540
+		$indice = 0;
541 541
 		asort($array_selected);
542 542
 
543 543
 		dol_syslog(get_class($this)."::".__FUNCTION__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected));
544 544
 
545 545
 		// Check parameters or context properties
546
-		if (empty($this->array_export_fields) || ! is_array($this->array_export_fields))
546
+		if (empty($this->array_export_fields) || !is_array($this->array_export_fields))
547 547
 		{
548
-			$this->error="ErrorBadParameter";
548
+			$this->error = "ErrorBadParameter";
549 549
 			return -1;
550 550
 		}
551 551
 
552 552
 		// Creation of class to export using model ExportXXX
553
-		$dir = DOL_DOCUMENT_ROOT . "/core/modules/export/";
553
+		$dir = DOL_DOCUMENT_ROOT."/core/modules/export/";
554 554
 		$file = "export_".$model.".modules.php";
555 555
 		$classname = "Export".$model;
556 556
 		require_once $dir.$file;
557 557
 		$objmodel = new $classname($this->db);
558 558
 
559
-		if (! empty($sqlquery)) $sql = $sqlquery;
559
+		if (!empty($sqlquery)) $sql = $sqlquery;
560 560
         else
561 561
 		{
562 562
 			// Define value for indice from $datatoexport
563
-			$foundindice=0;
564
-			foreach($this->array_export_code as $key => $dataset)
563
+			$foundindice = 0;
564
+			foreach ($this->array_export_code as $key => $dataset)
565 565
 			{
566 566
 				if ($datatoexport == $dataset)
567 567
 				{
568
-					$indice=$key;
568
+					$indice = $key;
569 569
 					$foundindice++;
570 570
 					//print "Found indice = ".$indice." for dataset=".$datatoexport."\n";
571 571
 					break;
@@ -573,31 +573,31 @@  discard block
 block discarded – undo
573 573
 			}
574 574
 			if (empty($foundindice))
575 575
 			{
576
-				$this->error="ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
576
+				$this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code";
577 577
 				return -1;
578 578
 			}
579
-        	$sql=$this->build_sql($indice, $array_selected, $array_filterValue);
579
+        	$sql = $this->build_sql($indice, $array_selected, $array_filterValue);
580 580
 		}
581 581
 
582 582
 		// Run the sql
583
-		$this->sqlusedforexport=$sql;
583
+		$this->sqlusedforexport = $sql;
584 584
 		dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
585 585
 		$resql = $this->db->query($sql);
586 586
 		if ($resql)
587 587
 		{
588 588
 			//$this->array_export_label[$indice]
589 589
 			if ($conf->global->EXPORT_PREFIX_SPEC)
590
-				$filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
590
+				$filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
591 591
 			else
592
-				$filename="export_".$datatoexport;
593
-			$filename.='.'.$objmodel->getDriverExtension();
594
-			$dirname=$conf->export->dir_temp.'/'.$user->id;
592
+				$filename = "export_".$datatoexport;
593
+			$filename .= '.'.$objmodel->getDriverExtension();
594
+			$dirname = $conf->export->dir_temp.'/'.$user->id;
595 595
 
596 596
 			$outputlangs = clone $langs; // We clone to have an object we can modify (for example to change output charset by csv handler) without changing original value
597 597
 
598 598
 			// Open file
599 599
 			dol_mkdir($dirname);
600
-			$result=$objmodel->open_file($dirname."/".$filename, $outputlangs);
600
+			$result = $objmodel->open_file($dirname."/".$filename, $outputlangs);
601 601
 
602 602
 			if ($result >= 0)
603 603
 			{
@@ -605,64 +605,64 @@  discard block
 block discarded – undo
605 605
 				$objmodel->write_header($outputlangs);
606 606
 
607 607
 				// Genere ligne de titre
608
-				$objmodel->write_title($this->array_export_fields[$indice],$array_selected,$outputlangs,$this->array_export_TypeFields[$indice]);
608
+				$objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, $this->array_export_TypeFields[$indice]);
609 609
 
610 610
 				while ($obj = $this->db->fetch_object($resql))
611 611
 				{
612 612
 					// Process special operations
613
-					if (! empty($this->array_export_special[$indice]))
613
+					if (!empty($this->array_export_special[$indice]))
614 614
 					{
615 615
 						foreach ($this->array_export_special[$indice] as $key => $value)
616 616
 						{
617
-							if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
617
+							if (!array_key_exists($key, $array_selected)) continue; // Field not selected
618 618
 							// Operation NULLIFNEG
619
-							if ($this->array_export_special[$indice][$key]=='NULLIFNEG')
619
+							if ($this->array_export_special[$indice][$key] == 'NULLIFNEG')
620 620
 							{
621 621
 								//$alias=$this->array_export_alias[$indice][$key];
622
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
623
-								if ($obj->$alias < 0) $obj->$alias='';
622
+								$alias = str_replace(array('.', '-', '(', ')'), '_', $key);
623
+								if ($obj->$alias < 0) $obj->$alias = '';
624 624
 							}
625 625
 							// Operation ZEROIFNEG
626
-							elseif ($this->array_export_special[$indice][$key]=='ZEROIFNEG')
626
+							elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG')
627 627
 							{
628 628
 								//$alias=$this->array_export_alias[$indice][$key];
629
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
630
-								if ($obj->$alias < 0) $obj->$alias='0';
629
+								$alias = str_replace(array('.', '-', '(', ')'), '_', $key);
630
+								if ($obj->$alias < 0) $obj->$alias = '0';
631 631
 							}
632 632
 							// Operation INVOICEREMAINTOPAY
633
-							elseif ($this->array_export_special[$indice][$key]=='getRemainToPay')
633
+							elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay')
634 634
 							{
635 635
 								//$alias=$this->array_export_alias[$indice][$key];
636
-								$alias=str_replace(array('.', '-','(',')'),'_',$key);
637
-								$remaintopay='';
636
+								$alias = str_replace(array('.', '-', '(', ')'), '_', $key);
637
+								$remaintopay = '';
638 638
 								if ($obj->f_rowid > 0)
639 639
 								{
640 640
 								    global $tmpobjforcomputecall;
641
-								    if (! is_object($tmpobjforcomputecall))
641
+								    if (!is_object($tmpobjforcomputecall))
642 642
 								    {
643 643
 								        include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
644
-								        $tmpobjforcomputecall=new Facture($this->db);
644
+								        $tmpobjforcomputecall = new Facture($this->db);
645 645
 								    }
646 646
 								    $tmpobjforcomputecall->id = $obj->f_rowid;
647 647
 								    $tmpobjforcomputecall->total_ttc = $obj->f_total_ttc;
648
-								    $remaintopay=$tmpobjforcomputecall->getRemainToPay();
648
+								    $remaintopay = $tmpobjforcomputecall->getRemainToPay();
649 649
 								}
650
-								$obj->$alias=$remaintopay;
650
+								$obj->$alias = $remaintopay;
651 651
 							}
652 652
 							else
653 653
 							{
654 654
 							    // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
655
-							    $computestring=$this->array_export_special[$indice][$key];
656
-							    $tmp=dol_eval($computestring, 1, 0);
657
-							    $obj->$alias=$tmp;
655
+							    $computestring = $this->array_export_special[$indice][$key];
656
+							    $tmp = dol_eval($computestring, 1, 0);
657
+							    $obj->$alias = $tmp;
658 658
 
659
-							    $this->error="ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
659
+							    $this->error = "ERROPNOTSUPPORTED. Operation ".$this->array_export_special[$indice][$key]." not supported. Export of 'computed' extrafields is not yet supported, please remove field.";
660 660
 							    return -1;
661 661
 							}
662 662
 						}
663 663
 					}
664 664
 					// end of special operation processing
665
-					$objmodel->write_record($array_selected,$obj,$outputlangs,$this->array_export_TypeFields[$indice]);
665
+					$objmodel->write_record($array_selected, $obj, $outputlangs, $this->array_export_TypeFields[$indice]);
666 666
 				}
667 667
 
668 668
 				// Genere en-tete
@@ -675,14 +675,14 @@  discard block
 block discarded – undo
675 675
 			}
676 676
 			else
677 677
 			{
678
-				$this->error=$objmodel->error;
678
+				$this->error = $objmodel->error;
679 679
 				dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
680 680
 				return -1;
681 681
 			}
682 682
 		}
683 683
 		else
684 684
 		{
685
-			$this->error=$this->db->error()." - sql=".$sql;
685
+			$this->error = $this->db->error()." - sql=".$sql;
686 686
 			return -1;
687 687
 		}
688 688
 	}
@@ -701,24 +701,24 @@  discard block
 block discarded – undo
701 701
 
702 702
 		$this->db->begin();
703 703
 
704
-		$filter='';
704
+		$filter = '';
705 705
 
706 706
 		$sql = 'INSERT INTO '.MAIN_DB_PREFIX.'export_model (';
707
-		$sql.= 'label,';
708
-		$sql.= 'type,';
709
-		$sql.= 'field,';
710
-		$sql.= 'fk_user,';
711
-		$sql.= 'filter';
712
-		$sql.= ') VALUES (';
713
-		$sql.= "'".$this->db->escape($this->model_name)."',";
714
-		$sql.= "'".$this->db->escape($this->datatoexport)."',";
715
-		$sql.= "'".$this->db->escape($this->hexa)."',";
716
-		$sql.= "'".$user->id."',";
717
-		$sql.= "'".$this->db->escape($this->hexafiltervalue)."'";
718
-		$sql.= ")";
707
+		$sql .= 'label,';
708
+		$sql .= 'type,';
709
+		$sql .= 'field,';
710
+		$sql .= 'fk_user,';
711
+		$sql .= 'filter';
712
+		$sql .= ') VALUES (';
713
+		$sql .= "'".$this->db->escape($this->model_name)."',";
714
+		$sql .= "'".$this->db->escape($this->datatoexport)."',";
715
+		$sql .= "'".$this->db->escape($this->hexa)."',";
716
+		$sql .= "'".$user->id."',";
717
+		$sql .= "'".$this->db->escape($this->hexafiltervalue)."'";
718
+		$sql .= ")";
719 719
 
720 720
 		dol_syslog(get_class($this)."::create", LOG_DEBUG);
721
-		$resql=$this->db->query($sql);
721
+		$resql = $this->db->query($sql);
722 722
 		if ($resql)
723 723
 		{
724 724
 			$this->db->commit();
@@ -726,8 +726,8 @@  discard block
 block discarded – undo
726 726
 		}
727 727
 		else
728 728
 		{
729
-			$this->error=$this->db->lasterror();
730
-			$this->errno=$this->db->lasterrno();
729
+			$this->error = $this->db->lasterror();
730
+			$this->errno = $this->db->lasterrno();
731 731
 			$this->db->rollback();
732 732
 			return -1;
733 733
 		}
@@ -742,8 +742,8 @@  discard block
 block discarded – undo
742 742
 	function fetch($id)
743 743
 	{
744 744
 		$sql = 'SELECT em.rowid, em.label, em.type, em.field, em.filter';
745
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
746
-		$sql.= ' WHERE em.rowid = '.$id;
745
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'export_model as em';
746
+		$sql .= ' WHERE em.rowid = '.$id;
747 747
 
748 748
 		dol_syslog("Export::fetch", LOG_DEBUG);
749 749
 		$result = $this->db->query($sql);
@@ -752,18 +752,18 @@  discard block
 block discarded – undo
752 752
 			$obj = $this->db->fetch_object($result);
753 753
 			if ($obj)
754 754
 			{
755
-				$this->id				= $obj->rowid;
756
-				$this->model_name		= $obj->label;
757
-				$this->datatoexport		= $obj->type;
755
+				$this->id = $obj->rowid;
756
+				$this->model_name = $obj->label;
757
+				$this->datatoexport = $obj->type;
758 758
 
759
-				$this->hexa				= $obj->field;
760
-				$this->hexafiltervalue	= $obj->filter;
759
+				$this->hexa = $obj->field;
760
+				$this->hexafiltervalue = $obj->filter;
761 761
 
762 762
 				return 1;
763 763
 			}
764 764
 			else
765 765
 			{
766
-				$this->error="ModelNotFound";
766
+				$this->error = "ModelNotFound";
767 767
 				return -2;
768 768
 			}
769 769
 		}
@@ -782,23 +782,23 @@  discard block
 block discarded – undo
782 782
 	 *  @param      int			$notrigger	    0=launch triggers after, 1=disable triggers
783 783
 	 *	@return		int							<0 if KO, >0 if OK
784 784
 	 */
785
-	function delete($user, $notrigger=0)
785
+	function delete($user, $notrigger = 0)
786 786
 	{
787 787
 		global $conf, $langs;
788
-		$error=0;
788
+		$error = 0;
789 789
 
790 790
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."export_model";
791
-		$sql.= " WHERE rowid=".$this->id;
791
+		$sql .= " WHERE rowid=".$this->id;
792 792
 
793 793
 		$this->db->begin();
794 794
 
795 795
 		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
796 796
 		$resql = $this->db->query($sql);
797
-		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
797
+		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
798 798
 
799
-		if (! $error)
799
+		if (!$error)
800 800
 		{
801
-			if (! $notrigger)
801
+			if (!$notrigger)
802 802
 			{
803 803
 				// Uncomment this and change MYOBJECT to your own tag if you
804 804
 				// want this action call a trigger.
@@ -815,13 +815,13 @@  discard block
 block discarded – undo
815 815
 		// Commit or rollback
816 816
 		if ($error)
817 817
 		{
818
-			foreach($this->errors as $errmsg)
818
+			foreach ($this->errors as $errmsg)
819 819
 			{
820 820
 				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
821
-				$this->error.=($this->error?', '.$errmsg:$errmsg);
821
+				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
822 822
 			}
823 823
 			$this->db->rollback();
824
-			return -1*$error;
824
+			return -1 * $error;
825 825
 		}
826 826
 		else
827 827
 		{
@@ -843,8 +843,8 @@  discard block
 block discarded – undo
843 843
 		global $conf, $langs;
844 844
 
845 845
 		$sql = "SELECT em.rowid, em.field, em.label, em.type, em.filter";
846
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model as em";
847
-		$sql.= " ORDER BY rowid";
846
+		$sql .= " FROM ".MAIN_DB_PREFIX."export_model as em";
847
+		$sql .= " ORDER BY rowid";
848 848
 
849 849
 		$result = $this->db->query($sql);
850 850
 		if ($result)
@@ -858,19 +858,19 @@  discard block
 block discarded – undo
858 858
 				print "<tr>";
859 859
 				print '<td><a href=export.php?step=2&action=select_model&exportmodelid='.$obj->rowid.'&datatoexport='.$obj->type.'>'.$obj->label.'</a></td>';
860 860
 				print '<td>';
861
-				print img_object($this->array_export_module[$keyModel]->getName(),$this->array_export_icon[$keyModel]).' ';
861
+				print img_object($this->array_export_module[$keyModel]->getName(), $this->array_export_icon[$keyModel]).' ';
862 862
 				print $this->array_export_module[$keyModel]->getName().' - ';
863 863
 				// recuperation du nom de l'export
864 864
 
865
-				$string=$langs->trans($this->array_export_label[$keyModel]);
866
-				print ($string!=$this->array_export_label[$keyModel]?$string:$this->array_export_label[$keyModel]);
865
+				$string = $langs->trans($this->array_export_label[$keyModel]);
866
+				print ($string != $this->array_export_label[$keyModel] ? $string : $this->array_export_label[$keyModel]);
867 867
 				print '</td>';
868 868
 				//print '<td>'.$obj->type.$keyModel.'</td>';
869
-				print '<td>'.str_replace(',',' , ',$obj->field).'</td>';
870
-				if (! empty($obj->filter)) {
869
+				print '<td>'.str_replace(',', ' , ', $obj->field).'</td>';
870
+				if (!empty($obj->filter)) {
871 871
 					$filter = json_decode($obj->filter, true);
872
-					print '<td>'.str_replace(',',' , ',$filter['field']).'</td>';
873
-					print '<td>'.str_replace(',',' , ',$filter['value']).'</td>';
872
+					print '<td>'.str_replace(',', ' , ', $filter['field']).'</td>';
873
+					print '<td>'.str_replace(',', ' , ', $filter['value']).'</td>';
874 874
 				}
875 875
 				// suppression de l'export
876 876
 				print '<td align="right">';
Please login to merge, or discard this patch.
Braces   +127 added lines, -80 removed lines patch added patch discarded remove patch
@@ -108,8 +108,12 @@  discard block
 block discarded – undo
108 108
 						// Defined if module is enabled
109 109
 						$enabled=true;
110 110
 						$part=strtolower(preg_replace('/^mod/i','',$modulename));
111
-						if ($part == 'propale') $part='propal';
112
-						if (empty($conf->$part->enabled)) $enabled=false;
111
+						if ($part == 'propale') {
112
+						    $part='propal';
113
+						}
114
+						if (empty($conf->$part->enabled)) {
115
+						    $enabled=false;
116
+						}
113 117
 
114 118
 						if ($enabled)
115 119
 						{
@@ -124,10 +128,14 @@  discard block
 block discarded – undo
124 128
 							    foreach($module->export_code as $r => $value)
125 129
 								{
126 130
                                     //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'<br>';
127
-								    if ($filter && ($filter != $module->export_code[$r])) continue;
131
+								    if ($filter && ($filter != $module->export_code[$r])) {
132
+								        continue;
133
+								    }
128 134
 
129 135
                                     // Test if condition to show are ok
130
-                                    if (! empty($module->export_enabled[$r]) && ! verifCond($module->export_enabled[$r])) continue;
136
+                                    if (! empty($module->export_enabled[$r]) && ! verifCond($module->export_enabled[$r])) {
137
+                                        continue;
138
+                                    }
131 139
 
132 140
                                     // Test if permissions are ok
133 141
 									$bool=true;
@@ -140,13 +148,16 @@  discard block
 block discarded – undo
140 148
 	    									if (! empty($perm[2]))
141 149
 	    									{
142 150
 	    										$bool=$user->rights->{$perm[0]}->{$perm[1]}->{$perm[2]};
143
-	    									}
144
-	    									else
151
+	    									} else
145 152
 	    									{
146 153
 	    										$bool=$user->rights->{$perm[0]}->{$perm[1]};
147 154
 	    									}
148
-	    									if ($perm[0]=='user' && $user->admin) $bool=true;
149
-	    									if (! $bool) break;
155
+	    									if ($perm[0]=='user' && $user->admin) {
156
+	    									    $bool=true;
157
+	    									}
158
+	    									if (! $bool) {
159
+	    									    break;
160
+	    									}
150 161
 										}
151 162
 									}
152 163
 									//print $bool." $perm[0]"."<br>";
@@ -229,10 +240,19 @@  discard block
 block discarded – undo
229 240
 		//print_r($array_selected);
230 241
 		foreach ($this->array_export_fields[$indice] as $key => $value)
231 242
 		{
232
-			if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
233
-            if (preg_match('/^none\./', $key)) continue;                    // A field that must not appears into SQL
234
-			if ($i > 0) $sql.=', ';
235
-			else $i++;
243
+			if (! array_key_exists($key, $array_selected)) {
244
+			    continue;
245
+			}
246
+			// Field not selected
247
+            if (preg_match('/^none\./', $key)) {
248
+                continue;
249
+            }
250
+            // A field that must not appears into SQL
251
+			if ($i > 0) {
252
+			    $sql.=', ';
253
+			} else {
254
+			    $i++;
255
+			}
236 256
 
237 257
 			if (strpos($key, ' as ')===false) {
238 258
 				$newfield=$key.' as '.str_replace(array('.', '-','(',')'),'_',$key);
@@ -251,8 +271,12 @@  discard block
 block discarded – undo
251 271
 			// Loop on each condition to add
252 272
 			foreach ($array_filterValue as $key => $value)
253 273
 			{
254
-			    if (preg_match('/GROUP_CONCAT/i', $key)) continue;
255
-				if ($value != '') $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
274
+			    if (preg_match('/GROUP_CONCAT/i', $key)) {
275
+			        continue;
276
+			    }
277
+				if ($value != '') {
278
+				    $sqlWhere.=" and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
279
+				}
256 280
 			}
257 281
 			$sql.=$sqlWhere;
258 282
 		}
@@ -266,7 +290,9 @@  discard block
 block discarded – undo
266 290
 		    // Loop on each condition to add
267 291
 		    foreach ($array_filterValue as $key => $value)
268 292
 		    {
269
-		        if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
293
+		        if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') {
294
+		            $sql.=" HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]);
295
+		        }
270 296
 		    }
271 297
 		}
272 298
 
@@ -290,10 +316,11 @@  discard block
 block discarded – undo
290 316
 		// build the input field on depend of the type of file
291 317
 		switch ($InfoFieldList[0]) {
292 318
 			case 'Text':
293
-				if (! (strpos($ValueField, '%') === false))
294
-					$szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'";
295
-				else
296
-					$szFilterQuery.=" ".$NameField." = '".$ValueField."'";
319
+				if (! (strpos($ValueField, '%') === false)) {
320
+									$szFilterQuery.=" ".$NameField." LIKE '".$ValueField."'";
321
+				} else {
322
+									$szFilterQuery.=" ".$NameField." = '".$ValueField."'";
323
+				}
297 324
 				break;
298 325
 			case 'Date':
299 326
 				if (strpos($ValueField, "+") > 0)
@@ -302,13 +329,13 @@  discard block
 block discarded – undo
302 329
 					$ValueArray = explode("+", $ValueField);
303 330
 					$szFilterQuery ="(".$this->conditionDate($NameField,trim($ValueArray[0]),">=");
304 331
 					$szFilterQuery.=" AND ".$this->conditionDate($NameField,trim($ValueArray[1]),"<=").")";
305
-				}
306
-				else
332
+				} else
307 333
 				{
308
-					if (is_numeric(substr($ValueField,0,1)))
309
-						$szFilterQuery=$this->conditionDate($NameField,trim($ValueField),"=");
310
-					else
311
-						$szFilterQuery=$this->conditionDate($NameField,trim(substr($ValueField,1)),substr($ValueField,0,1));
334
+					if (is_numeric(substr($ValueField,0,1))) {
335
+											$szFilterQuery=$this->conditionDate($NameField,trim($ValueField),"=");
336
+					} else {
337
+											$szFilterQuery=$this->conditionDate($NameField,trim(substr($ValueField,1)),substr($ValueField,0,1));
338
+					}
312 339
 				}
313 340
 				break;
314 341
 			case 'Duree':
@@ -321,13 +348,13 @@  discard block
 block discarded – undo
321 348
 					$ValueArray = explode("+", $ValueField);
322 349
 					$szFilterQuery ="(".$NameField.">=".$ValueArray[0];
323 350
 					$szFilterQuery.=" AND ".$NameField."<=".$ValueArray[1].")";
324
-				}
325
-				else
351
+				} else
326 352
 				{
327
-					if (is_numeric(substr($ValueField,0,1)))
328
-						$szFilterQuery=" ".$NameField."=".$ValueField;
329
-					else
330
-						$szFilterQuery=" ".$NameField.substr($ValueField,0,1).substr($ValueField,1);
353
+					if (is_numeric(substr($ValueField,0,1))) {
354
+											$szFilterQuery=" ".$NameField."=".$ValueField;
355
+					} else {
356
+											$szFilterQuery=" ".$NameField.substr($ValueField,0,1).substr($ValueField,1);
357
+					}
331 358
 				}
332 359
 				break;
333 360
 			case 'Boolean':
@@ -335,13 +362,14 @@  discard block
 block discarded – undo
335 362
 				break;
336 363
 			case 'Status':
337 364
 			case 'List':
338
-				if (is_numeric($ValueField))
339
-					$szFilterQuery=" ".$NameField."=".$ValueField;
340
-				else {
341
-                    if (! (strpos($ValueField, '%') === false))
342
-                        $szFilterQuery=" ".$NameField." LIKE '".$ValueField."'";
343
-                    else
344
-                        $szFilterQuery=" ".$NameField." = '".$ValueField."'";
365
+				if (is_numeric($ValueField)) {
366
+									$szFilterQuery=" ".$NameField."=".$ValueField;
367
+				} else {
368
+                    if (! (strpos($ValueField, '%') === false)) {
369
+                                            $szFilterQuery=" ".$NameField." LIKE '".$ValueField."'";
370
+                    } else {
371
+                                            $szFilterQuery=" ".$NameField." = '".$ValueField."'";
372
+                    }
345 373
 				}
346 374
 				break;
347 375
 			default:
@@ -362,9 +390,13 @@  discard block
 block discarded – undo
362 390
 	function conditionDate($Field, $Value, $Sens)
363 391
 	{
364 392
 		// TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN
365
-		if (strlen($Value)==4) $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
366
-		elseif (strlen($Value)==6) $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
367
-		else  $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
393
+		if (strlen($Value)==4) {
394
+		    $Condition=" date_format(".$Field.",'%Y') ".$Sens." '".$Value."'";
395
+		} elseif (strlen($Value)==6) {
396
+		    $Condition=" date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'";
397
+		} else {
398
+		    $Condition=" date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value;
399
+		}
368 400
 		return $Condition;
369 401
 	}
370 402
 
@@ -399,21 +431,30 @@  discard block
 block discarded – undo
399 431
 			    $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
400 432
 				break;
401 433
 			case 'Status':
402
-				if (! empty($conf->global->MAIN_ACTIVATE_HTML5)) $szFilterField='<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
403
-				else $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
434
+				if (! empty($conf->global->MAIN_ACTIVATE_HTML5)) {
435
+				    $szFilterField='<input type="number" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
436
+				} else {
437
+				    $szFilterField='<input type="text" size="6" name="'.$NameField.'" value="'.$ValueField.'">';
438
+				}
404 439
 				break;
405 440
 			case 'Boolean':
406 441
 				$szFilterField='<select name="'.$NameField.'" class="flat">';
407 442
 				$szFilterField.='<option ';
408
-				if ($ValueField=='') $szFilterField.=' selected ';
443
+				if ($ValueField=='') {
444
+				    $szFilterField.=' selected ';
445
+				}
409 446
 				$szFilterField.=' value="">&nbsp;</option>';
410 447
 
411 448
 				$szFilterField.='<option ';
412
-				if ($ValueField=='yes' || $ValueField == '1') $szFilterField.=' selected ';
449
+				if ($ValueField=='yes' || $ValueField == '1') {
450
+				    $szFilterField.=' selected ';
451
+				}
413 452
 				$szFilterField.=' value="1">'.yn(1).'</option>';
414 453
 
415 454
 				$szFilterField.='<option ';
416
-				if ($ValueField=='no' || $ValueField=='0') $szFilterField.=' selected ';
455
+				if ($ValueField=='no' || $ValueField=='0') {
456
+				    $szFilterField.=' selected ';
457
+				}
417 458
 				$szFilterField.=' value="0">'.yn(0).'</option>';
418 459
 				$szFilterField.="</select>";
419 460
 				break;
@@ -422,13 +463,18 @@  discard block
 block discarded – undo
422 463
 				// 1 : Nom de la table
423 464
 				// 2 : Nom du champ contenant le libelle
424 465
 				// 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list.
425
-				if (count($InfoFieldList)==4)
426
-					$keyList=$InfoFieldList[3];
427
-				else
428
-					$keyList='rowid';
466
+				if (count($InfoFieldList)==4) {
467
+									$keyList=$InfoFieldList[3];
468
+				} else {
469
+									$keyList='rowid';
470
+				}
429 471
 				$sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
430
-				if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
431
-				if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code';
472
+				if ($InfoFieldList[1] == 'c_stcomm') {
473
+				    $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3])?'':', '.$InfoFieldList[3].' as code');
474
+				}
475
+				if ($InfoFieldList[1] == 'c_country') {
476
+				    $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code';
477
+				}
432 478
 				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[1];
433 479
 
434 480
 				$resql = $this->db->query($sql);
@@ -466,8 +512,7 @@  discard block
 block discarded – undo
466 512
 							if (!empty($ValueField) && $ValueField == $obj->rowid)
467 513
 							{
468 514
 								$szFilterField.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
469
-							}
470
-							else
515
+							} else
471 516
 							{
472 517
 								$szFilterField.='<option value="'.$obj->rowid.'" >'.$labeltoshow.'</option>';
473 518
 							}
@@ -477,8 +522,9 @@  discard block
 block discarded – undo
477 522
 					$szFilterField.="</select>";
478 523
 
479 524
 					$this->db->free($resql);
525
+				} else {
526
+				    dol_print_error($this->db);
480 527
 				}
481
-				else dol_print_error($this->db);
482 528
 				break;
483 529
 		}
484 530
 
@@ -556,8 +602,9 @@  discard block
 block discarded – undo
556 602
 		require_once $dir.$file;
557 603
 		$objmodel = new $classname($this->db);
558 604
 
559
-		if (! empty($sqlquery)) $sql = $sqlquery;
560
-        else
605
+		if (! empty($sqlquery)) {
606
+		    $sql = $sqlquery;
607
+		} else
561 608
 		{
562 609
 			// Define value for indice from $datatoexport
563 610
 			$foundindice=0;
@@ -586,10 +633,11 @@  discard block
 block discarded – undo
586 633
 		if ($resql)
587 634
 		{
588 635
 			//$this->array_export_label[$indice]
589
-			if ($conf->global->EXPORT_PREFIX_SPEC)
590
-				$filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
591
-			else
592
-				$filename="export_".$datatoexport;
636
+			if ($conf->global->EXPORT_PREFIX_SPEC) {
637
+							$filename=$conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport;
638
+			} else {
639
+							$filename="export_".$datatoexport;
640
+			}
593 641
 			$filename.='.'.$objmodel->getDriverExtension();
594 642
 			$dirname=$conf->export->dir_temp.'/'.$user->id;
595 643
 
@@ -614,20 +662,27 @@  discard block
 block discarded – undo
614 662
 					{
615 663
 						foreach ($this->array_export_special[$indice] as $key => $value)
616 664
 						{
617
-							if (! array_key_exists($key, $array_selected)) continue;		// Field not selected
665
+							if (! array_key_exists($key, $array_selected)) {
666
+							    continue;
667
+							}
668
+							// Field not selected
618 669
 							// Operation NULLIFNEG
619 670
 							if ($this->array_export_special[$indice][$key]=='NULLIFNEG')
620 671
 							{
621 672
 								//$alias=$this->array_export_alias[$indice][$key];
622 673
 								$alias=str_replace(array('.', '-','(',')'),'_',$key);
623
-								if ($obj->$alias < 0) $obj->$alias='';
674
+								if ($obj->$alias < 0) {
675
+								    $obj->$alias='';
676
+								}
624 677
 							}
625 678
 							// Operation ZEROIFNEG
626 679
 							elseif ($this->array_export_special[$indice][$key]=='ZEROIFNEG')
627 680
 							{
628 681
 								//$alias=$this->array_export_alias[$indice][$key];
629 682
 								$alias=str_replace(array('.', '-','(',')'),'_',$key);
630
-								if ($obj->$alias < 0) $obj->$alias='0';
683
+								if ($obj->$alias < 0) {
684
+								    $obj->$alias='0';
685
+								}
631 686
 							}
632 687
 							// Operation INVOICEREMAINTOPAY
633 688
 							elseif ($this->array_export_special[$indice][$key]=='getRemainToPay')
@@ -648,8 +703,7 @@  discard block
 block discarded – undo
648 703
 								    $remaintopay=$tmpobjforcomputecall->getRemainToPay();
649 704
 								}
650 705
 								$obj->$alias=$remaintopay;
651
-							}
652
-							else
706
+							} else
653 707
 							{
654 708
 							    // TODO FIXME Export of compute field does not work. $obj containt $obj->alias_field and formulat will contains $obj->field
655 709
 							    $computestring=$this->array_export_special[$indice][$key];
@@ -672,15 +726,13 @@  discard block
 block discarded – undo
672 726
 				$objmodel->close_file();
673 727
 
674 728
         		return 1;
675
-			}
676
-			else
729
+			} else
677 730
 			{
678 731
 				$this->error=$objmodel->error;
679 732
 				dol_syslog("Export::build_file Error: ".$this->error, LOG_ERR);
680 733
 				return -1;
681 734
 			}
682
-		}
683
-		else
735
+		} else
684 736
 		{
685 737
 			$this->error=$this->db->error()." - sql=".$sql;
686 738
 			return -1;
@@ -723,8 +775,7 @@  discard block
 block discarded – undo
723 775
 		{
724 776
 			$this->db->commit();
725 777
 			return 1;
726
-		}
727
-		else
778
+		} else
728 779
 		{
729 780
 			$this->error=$this->db->lasterror();
730 781
 			$this->errno=$this->db->lasterrno();
@@ -760,14 +811,12 @@  discard block
 block discarded – undo
760 811
 				$this->hexafiltervalue	= $obj->filter;
761 812
 
762 813
 				return 1;
763
-			}
764
-			else
814
+			} else
765 815
 			{
766 816
 				$this->error="ModelNotFound";
767 817
 				return -2;
768 818
 			}
769
-		}
770
-		else
819
+		} else
771 820
 		{
772 821
 			dol_print_error($this->db);
773 822
 			return -3;
@@ -822,8 +871,7 @@  discard block
 block discarded – undo
822 871
 			}
823 872
 			$this->db->rollback();
824 873
 			return -1*$error;
825
-		}
826
-		else
874
+		} else
827 875
 		{
828 876
 			$this->db->commit();
829 877
 			return 1;
@@ -881,8 +929,7 @@  discard block
 block discarded – undo
881 929
 
882 930
 				$i++;
883 931
 			}
884
-		}
885
-		else {
932
+		} else {
886 933
 			dol_print_error($this->db);
887 934
 		}
888 935
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/exports/export.php 3 patches
Indentation   +477 added lines, -477 removed lines patch added patch discarded remove patch
@@ -40,85 +40,85 @@  discard block
 block discarded – undo
40 40
 //  accessforbidden();
41 41
 
42 42
 $entitytoicon = array(
43
-	'invoice'      => 'bill',
43
+    'invoice'      => 'bill',
44 44
     'invoice_line' => 'bill',
45
-	'order'        => 'order',
45
+    'order'        => 'order',
46 46
     'order_line'   => 'order',
47
-	'propal'       => 'propal',
47
+    'propal'       => 'propal',
48 48
     'propal_line'  => 'propal',
49
-	'intervention' => 'intervention',
49
+    'intervention' => 'intervention',
50 50
     'inter_line'   => 'intervention',
51
-	'member'       => 'user',
51
+    'member'       => 'user',
52 52
     'member_type'  => 'group',
53 53
     'subscription' => 'payment',
54 54
     'payment'      => 'payment',
55
-	'tax'          => 'generic',
55
+    'tax'          => 'generic',
56 56
     'tax_type'     => 'generic',
57 57
     'stock'        => 'generic',
58 58
     'other'        => 'generic',
59
-	'account'      => 'account',
60
-	'product'      => 'product',
59
+    'account'      => 'account',
60
+    'product'      => 'product',
61 61
     'virtualproduct'=>'product',
62
-	'subproduct'   => 'product',
63
-	'product_supplier_ref'      => 'product',
64
-	'warehouse'    => 'stock',
65
-	'batch'        => 'stock',
66
-	'stockbatch'   => 'stock',
67
-	'category'     => 'category',
68
-	'shipment'     => 'sending',
62
+    'subproduct'   => 'product',
63
+    'product_supplier_ref'      => 'product',
64
+    'warehouse'    => 'stock',
65
+    'batch'        => 'stock',
66
+    'stockbatch'   => 'stock',
67
+    'category'     => 'category',
68
+    'shipment'     => 'sending',
69 69
     'shipment_line'=> 'sending',
70 70
     'reception'=> 'sending',
71 71
     'reception_line'=> 'sending',
72
-	'expensereport'=> 'trip',
72
+    'expensereport'=> 'trip',
73 73
     'expensereport_line'=> 'trip',
74
-	'holiday'      => 'holiday',
74
+    'holiday'      => 'holiday',
75 75
     'contract_line' => 'contract',
76 76
     'translation'  => 'generic'
77 77
 );
78 78
 
79 79
 // Translation code
80 80
 $entitytolang = array(
81
-	'user'         => 'User',
82
-	'company'      => 'Company',
81
+    'user'         => 'User',
82
+    'company'      => 'Company',
83 83
     'contact'      => 'Contact',
84
-	'invoice'      => 'Bill',
84
+    'invoice'      => 'Bill',
85 85
     'invoice_line' => 'InvoiceLine',
86
-	'order'        => 'Order',
86
+    'order'        => 'Order',
87 87
     'order_line'   => 'OrderLine',
88 88
     'propal'       => 'Proposal',
89 89
     'propal_line'  => 'ProposalLine',
90
-	'intervention' => 'Intervention',
90
+    'intervention' => 'Intervention',
91 91
     'inter_line'   => 'InterLine',
92
-	'member'       => 'Member',
92
+    'member'       => 'Member',
93 93
     'member_type'  => 'MemberType',
94 94
     'subscription' => 'Subscription',
95
-	'tax'          => 'SocialContribution',
95
+    'tax'          => 'SocialContribution',
96 96
     'tax_type'     => 'DictionarySocialContributions',
97
-	'account'      => 'BankTransactions',
98
-	'payment'      => 'Payment',
99
-	'product'      => 'Product',
100
-	'virtualproduct'  => 'AssociatedProducts',
101
-	'subproduct'      => 'SubProduct',
102
-	'product_supplier_ref'      => 'SupplierPrices',
103
-	'service'      => 'Service',
97
+    'account'      => 'BankTransactions',
98
+    'payment'      => 'Payment',
99
+    'product'      => 'Product',
100
+    'virtualproduct'  => 'AssociatedProducts',
101
+    'subproduct'      => 'SubProduct',
102
+    'product_supplier_ref'      => 'SupplierPrices',
103
+    'service'      => 'Service',
104 104
     'stock'        => 'Stock',
105
-	'movement'	   => 'StockMovement',
106
-	'batch'        => 'Batch',
107
-	'stockbatch'   => 'StockDetailPerBatch',
108
-	'warehouse'    => 'Warehouse',
109
-	'category'     => 'Category',
110
-	'other'        => 'Other',
105
+    'movement'	   => 'StockMovement',
106
+    'batch'        => 'Batch',
107
+    'stockbatch'   => 'StockDetailPerBatch',
108
+    'warehouse'    => 'Warehouse',
109
+    'category'     => 'Category',
110
+    'other'        => 'Other',
111 111
     'trip'         => 'TripsAndExpenses',
112 112
     'shipment'     => 'Shipments',
113 113
     'shipment_line'=> 'ShipmentLine',
114 114
     'project'      => 'Projects',
115 115
     'projecttask'  => 'Tasks',
116 116
     'task_time'    => 'TaskTimeSpent',
117
-	'action'       => 'Event',
118
-	'expensereport'=> 'ExpenseReport',
119
-	'expensereport_line'=> 'ExpenseReportLine',
120
-	'holiday'      => 'TitreRequestCP',
121
-	'contract'     => 'Contract',
117
+    'action'       => 'Event',
118
+    'expensereport'=> 'ExpenseReport',
119
+    'expensereport_line'=> 'ExpenseReportLine',
120
+    'holiday'      => 'TitreRequestCP',
121
+    'contract'     => 'Contract',
122 122
     'contract_line'=> 'ContractLine',
123 123
     'translation'  => 'Translation'
124 124
 );
@@ -155,19 +155,19 @@  discard block
 block discarded – undo
155 155
 
156 156
 if ($action=='selectfield')     // Selection of field at step 2
157 157
 {
158
-	$fieldsarray=$objexport->array_export_fields[0];
159
-	$fieldsentitiesarray=$objexport->array_export_entities[0];
158
+    $fieldsarray=$objexport->array_export_fields[0];
159
+    $fieldsentitiesarray=$objexport->array_export_entities[0];
160 160
     $fieldsdependenciesarray=$objexport->array_export_dependencies[0];
161 161
 
162 162
     if ($field=='all')
163 163
     {
164
-		foreach($fieldsarray as $key=>$val)
165
-		{
166
-			if (! empty($array_selected[$key])) continue;		// If already selected, check next
167
-			$array_selected[$key]=count($array_selected)+1;
168
-		    //print_r($array_selected);
169
-		    $_SESSION["export_selected_fields"]=$array_selected;
170
-		}
164
+        foreach($fieldsarray as $key=>$val)
165
+        {
166
+            if (! empty($array_selected[$key])) continue;		// If already selected, check next
167
+            $array_selected[$key]=count($array_selected)+1;
168
+            //print_r($array_selected);
169
+            $_SESSION["export_selected_fields"]=$array_selected;
170
+        }
171 171
     }
172 172
     else
173 173
     {
@@ -205,33 +205,33 @@  discard block
 block discarded – undo
205 205
                 }
206 206
             }
207 207
         }
208
-	    //print_r($array_selected);
209
-	    $_SESSION["export_selected_fields"]=$array_selected;
208
+        //print_r($array_selected);
209
+        $_SESSION["export_selected_fields"]=$array_selected;
210 210
 
211
-	    setEventMessages($warnings, null, 'warnings');
211
+        setEventMessages($warnings, null, 'warnings');
212 212
     }
213 213
 }
214 214
 if ($action=='unselectfield')
215 215
 {
216 216
     if ($_GET["field"]=='all')
217 217
     {
218
-		$array_selected=array();
219
-		$_SESSION["export_selected_fields"]=$array_selected;
218
+        $array_selected=array();
219
+        $_SESSION["export_selected_fields"]=$array_selected;
220 220
     }
221 221
     else
222 222
     {
223
-	    unset($array_selected[$_GET["field"]]);
224
-	    // Renumber fields of array_selected (from 1 to nb_elements)
225
-	    asort($array_selected);
226
-	    $i=0;
227
-	    $array_selected_save=$array_selected;
228
-	    foreach($array_selected as $code=>$value)
229
-	    {
230
-	        $i++;
231
-	        $array_selected[$code]=$i;
232
-	        //print "x $code x $i y<br>";
233
-	    }
234
-	    $_SESSION["export_selected_fields"]=$array_selected;
223
+        unset($array_selected[$_GET["field"]]);
224
+        // Renumber fields of array_selected (from 1 to nb_elements)
225
+        asort($array_selected);
226
+        $i=0;
227
+        $array_selected_save=$array_selected;
228
+        foreach($array_selected as $code=>$value)
229
+        {
230
+            $i++;
231
+            $array_selected[$code]=$i;
232
+            //print "x $code x $i y<br>";
233
+        }
234
+        $_SESSION["export_selected_fields"]=$array_selected;
235 235
     }
236 236
 }
237 237
 
@@ -277,88 +277,88 @@  discard block
 block discarded – undo
277 277
     }
278 278
 
279 279
     // Build export file
280
-	$result=$objexport->build_file($user, GETPOST('model','alpha'), $datatoexport, $array_selected, $array_filtervalue);
281
-	if ($result < 0)
282
-	{
283
-		setEventMessages($objexport->error, $objexport->errors, 'errors');
284
-		$sqlusedforexport=$objexport->sqlusedforexport;
285
-	}
286
-	else
287
-	{
288
-		setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
289
-	    $sqlusedforexport=$objexport->sqlusedforexport;
280
+    $result=$objexport->build_file($user, GETPOST('model','alpha'), $datatoexport, $array_selected, $array_filtervalue);
281
+    if ($result < 0)
282
+    {
283
+        setEventMessages($objexport->error, $objexport->errors, 'errors');
284
+        $sqlusedforexport=$objexport->sqlusedforexport;
285
+    }
286
+    else
287
+    {
288
+        setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
289
+        $sqlusedforexport=$objexport->sqlusedforexport;
290 290
     }
291 291
 }
292 292
 
293 293
 // Delete file
294 294
 if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes')
295 295
 {
296
-	$file = $upload_dir . "/" . GETPOST('file');	// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
296
+    $file = $upload_dir . "/" . GETPOST('file');	// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
297 297
 
298
-	$ret=dol_delete_file($file);
299
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
300
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
301
-	header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport);
302
-	exit;
298
+    $ret=dol_delete_file($file);
299
+    if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
300
+    else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
301
+    header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport);
302
+    exit;
303 303
 }
304 304
 
305 305
 if ($action == 'deleteprof')
306 306
 {
307
-	if ($_GET["id"])
308
-	{
309
-		$objexport->fetch($_GET["id"]);
310
-		$result=$objexport->delete($user);
311
-	}
307
+    if ($_GET["id"])
308
+    {
309
+        $objexport->fetch($_GET["id"]);
310
+        $result=$objexport->delete($user);
311
+    }
312 312
 }
313 313
 
314 314
 // TODO The export for filter is not yet implemented (old code created conflicts with step 2). We must use same way of working and same combo list of predefined export than step 2.
315 315
 if ($action == 'add_export_model')
316 316
 {
317
-	if ($export_name)
318
-	{
319
-		asort($array_selected);
320
-
321
-		// Set save string
322
-		$hexa='';
323
-		foreach($array_selected as $key=>$val)
324
-		{
325
-			if ($hexa) $hexa.=',';
326
-			$hexa.=$key;
327
-		}
328
-
329
-		$hexafiltervalue='';
330
-		if (! empty($array_filtervalue) && is_array($array_filtervalue))
331
-		{
332
-			foreach($array_filtervalue as $key=>$val)
333
-			{
334
-				if ($hexafiltervalue) $hexafiltervalue.=',';
335
-				$hexafiltervalue.=$key.'='.$val;
336
-			}
337
-		}
338
-
339
-	    $objexport->model_name = $export_name;
340
-	    $objexport->datatoexport = $datatoexport;
341
-	    $objexport->hexa = $hexa;
342
-	    $objexport->hexafiltervalue = $hexafiltervalue;
343
-
344
-	    $result = $objexport->create($user);
345
-		if ($result >= 0)
346
-		{
347
-			setEventMessages($langs->trans("ExportModelSaved",$objexport->model_name), null, 'mesgs');
348
-		}
349
-		else
350
-		{
351
-			$langs->load("errors");
352
-			if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS')
353
-				setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors');
354
-			else
355
-				setEventMessages($objexport->error, $objexport->errors, 'errors');
356
-		}
357
-	}
358
-	else
359
-	{
360
-		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportModelName")), null, 'errors');
361
-	}
317
+    if ($export_name)
318
+    {
319
+        asort($array_selected);
320
+
321
+        // Set save string
322
+        $hexa='';
323
+        foreach($array_selected as $key=>$val)
324
+        {
325
+            if ($hexa) $hexa.=',';
326
+            $hexa.=$key;
327
+        }
328
+
329
+        $hexafiltervalue='';
330
+        if (! empty($array_filtervalue) && is_array($array_filtervalue))
331
+        {
332
+            foreach($array_filtervalue as $key=>$val)
333
+            {
334
+                if ($hexafiltervalue) $hexafiltervalue.=',';
335
+                $hexafiltervalue.=$key.'='.$val;
336
+            }
337
+        }
338
+
339
+        $objexport->model_name = $export_name;
340
+        $objexport->datatoexport = $datatoexport;
341
+        $objexport->hexa = $hexa;
342
+        $objexport->hexafiltervalue = $hexafiltervalue;
343
+
344
+        $result = $objexport->create($user);
345
+        if ($result >= 0)
346
+        {
347
+            setEventMessages($langs->trans("ExportModelSaved",$objexport->model_name), null, 'mesgs');
348
+        }
349
+        else
350
+        {
351
+            $langs->load("errors");
352
+            if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS')
353
+                setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors');
354
+            else
355
+                setEventMessages($objexport->error, $objexport->errors, 'errors');
356
+        }
357
+    }
358
+    else
359
+    {
360
+        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportModelName")), null, 'errors');
361
+    }
362 362
 }
363 363
 
364 364
 // Reload an predefined export model
@@ -373,50 +373,50 @@  discard block
 block discarded – undo
373 373
     $result = $objexport->fetch($exportmodelid);
374 374
     if ($result > 0)
375 375
     {
376
-		$fieldsarray=explode(',',$objexport->hexa);
377
-		$i=1;
378
-		foreach($fieldsarray as $val)
379
-		{
380
-			$array_selected[$val]=$i;
381
-			$i++;
382
-		}
383
-		$_SESSION["export_selected_fields"]=$array_selected;
384
-
385
-		$fieldsarrayvalue=explode(',',$objexport->hexafiltervalue);
386
-		$i=1;
387
-		foreach($fieldsarrayvalue as $val)
388
-		{
389
-			$tmp=explode('=',$val);
390
-			$array_filtervalue[$tmp[0]]=$tmp[1];
391
-			$i++;
392
-		}
393
-		$_SESSION["export_filtered_fields"]=$array_filtervalue;
376
+        $fieldsarray=explode(',',$objexport->hexa);
377
+        $i=1;
378
+        foreach($fieldsarray as $val)
379
+        {
380
+            $array_selected[$val]=$i;
381
+            $i++;
382
+        }
383
+        $_SESSION["export_selected_fields"]=$array_selected;
384
+
385
+        $fieldsarrayvalue=explode(',',$objexport->hexafiltervalue);
386
+        $i=1;
387
+        foreach($fieldsarrayvalue as $val)
388
+        {
389
+            $tmp=explode('=',$val);
390
+            $array_filtervalue[$tmp[0]]=$tmp[1];
391
+            $i++;
392
+        }
393
+        $_SESSION["export_filtered_fields"]=$array_filtervalue;
394 394
     }
395 395
 }
396 396
 
397 397
 // Get form with filters
398 398
 if ($step == 4 && $action == 'submitFormField')
399 399
 {
400
-	// on boucle sur les champs selectionne pour recuperer la valeur
401
-	if (is_array($objexport->array_export_TypeFields[0]))
402
-	{
403
-		$_SESSION["export_filtered_fields"]=array();
404
-		foreach($objexport->array_export_TypeFields[0] as $code => $type)	// $code: s.fieldname $value: Text|Boolean|List:ccc
405
-		{
406
-			$newcode=(string) preg_replace('/\./','_',$code);
407
-			//print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n<br>";
408
-			$filterqualified=1;
409
-			if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified=0;
410
-			elseif (preg_match('/^List/',$type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified=0;
411
-			if ($filterqualified)
412
-			{
413
-				//print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n";
414
-				$objexport->array_export_FilterValue[0][$code] = $_POST[$newcode];
415
-			}
416
-		}
417
-		$array_filtervalue=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
418
-		$_SESSION["export_filtered_fields"]=$array_filtervalue;
419
-	}
400
+    // on boucle sur les champs selectionne pour recuperer la valeur
401
+    if (is_array($objexport->array_export_TypeFields[0]))
402
+    {
403
+        $_SESSION["export_filtered_fields"]=array();
404
+        foreach($objexport->array_export_TypeFields[0] as $code => $type)	// $code: s.fieldname $value: Text|Boolean|List:ccc
405
+        {
406
+            $newcode=(string) preg_replace('/\./','_',$code);
407
+            //print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n<br>";
408
+            $filterqualified=1;
409
+            if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified=0;
410
+            elseif (preg_match('/^List/',$type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified=0;
411
+            if ($filterqualified)
412
+            {
413
+                //print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n";
414
+                $objexport->array_export_FilterValue[0][$code] = $_POST[$newcode];
415
+            }
416
+        }
417
+        $array_filtervalue=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
418
+        $_SESSION["export_filtered_fields"]=$array_filtervalue;
419
+    }
420 420
 }
421 421
 
422 422
 
@@ -465,24 +465,24 @@  discard block
 block discarded – undo
465 465
         {
466 466
             $val=!$val;
467 467
             print '<tr '.$bc[$val].'><td nospan="nospan">';
468
-	        //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' ';
468
+            //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' ';
469 469
             print $objexport->array_export_module[$key]->getName();
470 470
             print '</td><td>';
471
-			$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[$key]);
472
-			$label=$objexport->array_export_label[$key];
471
+            $icon=preg_replace('/:.*$/','',$objexport->array_export_icon[$key]);
472
+            $label=$objexport->array_export_label[$key];
473 473
             //print $value.'-'.$icon.'-'.$label."<br>";
474
-			print img_object($objexport->array_export_module[$key]->getName(), $icon).' ';
474
+            print img_object($objexport->array_export_module[$key]->getName(), $icon).' ';
475 475
             print $label;
476 476
             print '</td><td align="right">';
477 477
             if ($objexport->array_export_perms[$key])
478 478
             {
479
-            	print '<a href="'.DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$objexport->array_export_code[$key].'">'.img_picto($langs->trans("NewExport"),'filenew').'</a>';
479
+                print '<a href="'.DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$objexport->array_export_code[$key].'">'.img_picto($langs->trans("NewExport"),'filenew').'</a>';
480 480
             }
481 481
             else
482 482
             {
483
-            	print $langs->trans("NotEnoughPermissions");
483
+                print $langs->trans("NotEnoughPermissions");
484 484
             }
485
-           	print '</td></tr>';
485
+                print '</td></tr>';
486 486
         }
487 487
     }
488 488
     else
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
     // Lot de donnees a exporter
532 532
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
533 533
     print '<td>';
534
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
534
+    $icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
535 535
     $label=$objexport->array_export_label[0];
536 536
     //print $value.'-'.$icon.'-'.$label."<br>";
537 537
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
@@ -554,7 +554,7 @@  discard block
 block discarded – undo
554 554
     print '<table><tr><td colspan="2">';
555 555
     print $langs->trans("SelectExportFields").' ';
556 556
     if(empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1,$user->id);
557
-	else $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1);
557
+    else $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1);
558 558
     print ' ';
559 559
     print '<input type="submit" class="button" value="'.$langs->trans("Select").'">';
560 560
     print '</td></tr></table>';
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 
564 564
     print '<table class="noborder" width="100%">';
565 565
     print '<tr class="liste_titre">';
566
-	print '<td>'.$langs->trans("Entities").'</td>';
566
+    print '<td>'.$langs->trans("Entities").'</td>';
567 567
     print '<td>'.$langs->trans("ExportableFields").'</td>';
568 568
     print '<td width="100" align="center">';
569 569
     print '<a class="liste_titre" title='.$langs->trans("All").' alt='.$langs->trans("All").' href="'.$_SERVER["PHP_SELF"].'?step=2&datatoexport='.$datatoexport.'&action=selectfield&field=all">'.$langs->trans("All")."</a>";
@@ -578,13 +578,13 @@  discard block
 block discarded – undo
578 578
     // Select request if all fields are selected
579 579
     $sqlmaxforexport=$objexport->build_sql(0, array(), array());
580 580
 
581
-	//    $this->array_export_module[0]=$module;
582
-	//    $this->array_export_code[0]=$module->export_code[$r];
583
-	//    $this->array_export_label[0]=$module->export_label[$r];
584
-	//    $this->array_export_sql[0]=$module->export_sql[$r];
585
-	//    $this->array_export_fields[0]=$module->export_fields_array[$r];
586
-	//    $this->array_export_entities[0]=$module->export_fields_entities[$r];
587
-	//    $this->array_export_alias[0]=$module->export_fields_alias[$r];
581
+    //    $this->array_export_module[0]=$module;
582
+    //    $this->array_export_code[0]=$module->export_code[$r];
583
+    //    $this->array_export_label[0]=$module->export_label[$r];
584
+    //    $this->array_export_sql[0]=$module->export_sql[$r];
585
+    //    $this->array_export_fields[0]=$module->export_fields_array[$r];
586
+    //    $this->array_export_entities[0]=$module->export_fields_entities[$r];
587
+    //    $this->array_export_alias[0]=$module->export_fields_alias[$r];
588 588
 
589 589
     $i = 0;
590 590
 
@@ -623,16 +623,16 @@  discard block
 block discarded – undo
623 623
         {
624 624
             $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
625 625
         }
626
-   		if (! empty($objexport->array_export_examplevalues[0][$code]))
627
-		{
628
-		    $htmltext.='<b>'.$langs->trans("SourceExample").':</b> '.$objexport->array_export_examplevalues[0][$code].'<br>';
629
-		}
630
-    	if (! empty($objexport->array_export_TypeFields[0][$code]))
631
-		{
632
-		    $htmltext.='<b>'.$langs->trans("Type").':</b> '.$objexport->array_export_TypeFields[0][$code].'<br>';
633
-		}
634
-
635
-		if (isset($array_selected[$code]) && $array_selected[$code])
626
+            if (! empty($objexport->array_export_examplevalues[0][$code]))
627
+        {
628
+            $htmltext.='<b>'.$langs->trans("SourceExample").':</b> '.$objexport->array_export_examplevalues[0][$code].'<br>';
629
+        }
630
+        if (! empty($objexport->array_export_TypeFields[0][$code]))
631
+        {
632
+            $htmltext.='<b>'.$langs->trans("Type").':</b> '.$objexport->array_export_TypeFields[0][$code].'<br>';
633
+        }
634
+
635
+        if (isset($array_selected[$code]) && $array_selected[$code])
636 636
         {
637 637
             // Selected fields
638 638
             print '<td>&nbsp;</td>';
@@ -640,16 +640,16 @@  discard block
 block discarded – undo
640 640
             print '<td>';
641 641
             //print $text.'-'.$htmltext."<br>";
642 642
             print $form->textwithpicto($text,$htmltext);
643
-			//print ' ('.$code.')';
643
+            //print ' ('.$code.')';
644 644
             print '</td>';
645 645
         }
646 646
         else
647 647
         {
648
-        	// Fields not selected
648
+            // Fields not selected
649 649
             print '<td>';
650
-			//print $text.'-'.$htmltext."<br>";
651
-			print $form->textwithpicto($text,$htmltext);
652
-			//print ' ('.$code.')';
650
+            //print $text.'-'.$htmltext."<br>";
651
+            print $form->textwithpicto($text,$htmltext);
652
+            //print ' ('.$code.')';
653 653
             print '</td>';
654 654
             print '<td align="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?step=2&datatoexport='.$datatoexport.'&action=selectfield&field='.$code.'">'.img_right('default', 0, 'style="max-width: 20px"').'</a></td>';
655 655
             print '<td>&nbsp;</td>';
@@ -667,21 +667,21 @@  discard block
 block discarded – undo
667 667
     print '<div class="tabsAction tabsActionNoBottom">';
668 668
 
669 669
     if (count($array_selected))
670
-	{
671
-		// If filters exist
672
-		if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
673
-		{
674
-			print '<a class="butAction" href="export.php?step=3&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
675
-		}
676
-		else
677
-		{
678
-			print '<a class="butAction" href="export.php?step=4&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
679
-		}
680
-	}
681
-	else
682
-	{
683
-		print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SelectAtLeastOneField")).'">'.$langs->trans("NextStep").'</a>';
684
-	}
670
+    {
671
+        // If filters exist
672
+        if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
673
+        {
674
+            print '<a class="butAction" href="export.php?step=3&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
675
+        }
676
+        else
677
+        {
678
+            print '<a class="butAction" href="export.php?step=4&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
679
+        }
680
+    }
681
+    else
682
+    {
683
+        print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SelectAtLeastOneField")).'">'.$langs->trans("NextStep").'</a>';
684
+    }
685 685
 
686 686
     print '</div>';
687 687
 }
@@ -697,167 +697,167 @@  discard block
 block discarded – undo
697 697
 
698 698
     llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
699 699
 
700
-	/*
700
+    /*
701 701
 	 * Affichage onglets
702 702
 	*/
703
-	$h = 0;
703
+    $h = 0;
704 704
 
705
-	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
706
-	$head[$h][1] = $langs->trans("Step")." 1";
707
-	$h++;
705
+    $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
706
+    $head[$h][1] = $langs->trans("Step")." 1";
707
+    $h++;
708 708
 
709
-	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
710
-	$head[$h][1] = $langs->trans("Step")." 2";
711
-	$h++;
709
+    $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
710
+    $head[$h][1] = $langs->trans("Step")." 2";
711
+    $h++;
712 712
 
713
-	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
714
-	$head[$h][1] = $langs->trans("Step")." 3";
715
-	$hselected=$h;
716
-	$h++;
713
+    $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
714
+    $head[$h][1] = $langs->trans("Step")." 3";
715
+    $hselected=$h;
716
+    $h++;
717 717
 
718
-	dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
718
+    dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
719 719
 
720 720
     print '<div class="fichecenter">';
721 721
     print '<div class="underbanner clearboth"></div>';
722
-	print '<table width="100%" class="border">';
723
-
724
-	// Module
725
-	print '<tr><td class="titlefield">'.$langs->trans("Module").'</td>';
726
-	print '<td>';
727
-	//print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
728
-	print $objexport->array_export_module[0]->getName();
729
-	print '</td></tr>';
730
-
731
-	// Lot de donnees a exporter
732
-	print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
733
-	print '<td>';
734
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
735
-	$label=$objexport->array_export_label[0];
736
-	//print $value.'-'.$icon.'-'.$label."<br>";
737
-	print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
738
-	print $label;
739
-	print '</td></tr>';
740
-
741
-	// Nbre champs exportes
742
-	print '<tr><td>'.$langs->trans("ExportedFields").'</td>';
743
-	$list='';
744
-	foreach($array_selected as $code=>$value)
745
-	{
746
-		$list.=(! empty($list)?', ':'');
747
-		$list.=(isset($objexport->array_export_fields[0][$code])?$langs->trans($objexport->array_export_fields[0][$code]):'');
748
-	}
749
-	print '<td>'.$list.'</td></tr>';
750
-
751
-	print '</table>';
752
-	print '</div>';
753
-
754
-	print '<br>';
755
-
756
-	// Combo list of export models
757
-	print $langs->trans("SelectFilterFields").'<br>';
758
-
759
-
760
-	// un formulaire en plus pour recuperer les filtres
761
-	print '<form action="'.$_SERVER["PHP_SELF"].'?step=4&action=submitFormField&datatoexport='.$datatoexport.'" name="FilterField" method="post">';
762
-	print '<table class="noborder" width="100%">';
763
-	print '<tr class="liste_titre">';
764
-	print '<td>'.$langs->trans("Entities").'</td>';
765
-	//print '<td>'.$langs->trans("ExportableFields").'</td>';
766
-	//print '<td align="center"></td>';
767
-	print '<td>'.$langs->trans("ExportableFields").'</td>';
768
-	print '<td width="25%">'.$langs->trans("FilteredFieldsValues").'</td>';
769
-	print '</tr>';
770
-
771
-	// Champs exportables
772
-	$fieldsarray=$objexport->array_export_fields[0];
773
-	// Champs filtrable
774
-	$Typefieldsarray=$objexport->array_export_TypeFields[0];
775
-	// valeur des filtres
776
-	$ValueFiltersarray=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
777
-	// Select request if all fields are selected
778
-	$sqlmaxforexport=$objexport->build_sql(0, array(), array());
779
-
780
-	$i = 0;
781
-	// on boucle sur les champs
782
-	foreach($fieldsarray as $code => $label)
783
-	{
784
-		print '<tr class="oddeven">';
785
-
786
-		$i++;
787
-		$entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]);
788
-		$entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity);
789
-		$entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity);
790
-
791
-		print '<td class="nowrap">';
792
-		// If value of entityicon=entitylang='icon:Label'
793
-		$tmparray=explode(':',$entityicon);
794
-		if (count($tmparray) >=2)
795
-		{
796
-			$entityicon=$tmparray[0];
797
-			$entitylang=$tmparray[1];
798
-		}
799
-		print img_object('',$entityicon).' '.$langs->trans($entitylang);
800
-		print '</td>';
801
-
802
-		// Field name
803
-		$labelName=(! empty($fieldsarray[$code])?$fieldsarray[$code]:'');
804
-		$ValueFilter=(! empty($array_filtervalue[$code])?$array_filtervalue[$code]:'');
805
-		$text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
806
-
807
-		$tablename=getablenamefromfield($code,$sqlmaxforexport);
808
-		$htmltext ='<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
809
-			if (! empty($objexport->array_export_special[0][$code]))
810
-		{
811
-		    $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
812
-		}
813
-		else
814
-		{
815
-		    $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
816
-		}
817
-		if (! empty($objexport->array_export_examplevalues[0][$code]))
818
-		{
819
-		    $htmltext.=$langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
820
-		}
821
-		if (! empty($objexport->array_export_TypeFields[0][$code]))
822
-		{
823
-		    $htmltext.=$langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
824
-		}
825
-
826
-		print '<td>';
827
-		print $form->textwithpicto($text,$htmltext);
828
-		print '</td>';
829
-
830
-		// Filter value
831
-		print '<td>';
832
-		if (! empty($Typefieldsarray[$code]))	// Example: Text, List:c_country:label:rowid, Number, Boolean
833
-		{
834
-			$szInfoFiltre=$objexport->genDocFilter($Typefieldsarray[$code]);
835
-			if ($szInfoFiltre)	// Is there an info help for this filter ?
836
-			{
837
-				$tmp=$objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
838
-				print $form->textwithpicto($tmp, $szInfoFiltre);
839
-			}
840
-			else
841
-			{
842
-				print $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
843
-			}
844
-		}
845
-		print '</td>';
846
-
847
-		print '</tr>';
848
-	}
849
-
850
-	print '</table>';
851
-
852
-	print '</div>';
853
-
854
-	/*
722
+    print '<table width="100%" class="border">';
723
+
724
+    // Module
725
+    print '<tr><td class="titlefield">'.$langs->trans("Module").'</td>';
726
+    print '<td>';
727
+    //print img_object($objexport->array_export_module[0]->getName(),$objexport->array_export_module[0]->picto).' ';
728
+    print $objexport->array_export_module[0]->getName();
729
+    print '</td></tr>';
730
+
731
+    // Lot de donnees a exporter
732
+    print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
733
+    print '<td>';
734
+    $icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
735
+    $label=$objexport->array_export_label[0];
736
+    //print $value.'-'.$icon.'-'.$label."<br>";
737
+    print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
738
+    print $label;
739
+    print '</td></tr>';
740
+
741
+    // Nbre champs exportes
742
+    print '<tr><td>'.$langs->trans("ExportedFields").'</td>';
743
+    $list='';
744
+    foreach($array_selected as $code=>$value)
745
+    {
746
+        $list.=(! empty($list)?', ':'');
747
+        $list.=(isset($objexport->array_export_fields[0][$code])?$langs->trans($objexport->array_export_fields[0][$code]):'');
748
+    }
749
+    print '<td>'.$list.'</td></tr>';
750
+
751
+    print '</table>';
752
+    print '</div>';
753
+
754
+    print '<br>';
755
+
756
+    // Combo list of export models
757
+    print $langs->trans("SelectFilterFields").'<br>';
758
+
759
+
760
+    // un formulaire en plus pour recuperer les filtres
761
+    print '<form action="'.$_SERVER["PHP_SELF"].'?step=4&action=submitFormField&datatoexport='.$datatoexport.'" name="FilterField" method="post">';
762
+    print '<table class="noborder" width="100%">';
763
+    print '<tr class="liste_titre">';
764
+    print '<td>'.$langs->trans("Entities").'</td>';
765
+    //print '<td>'.$langs->trans("ExportableFields").'</td>';
766
+    //print '<td align="center"></td>';
767
+    print '<td>'.$langs->trans("ExportableFields").'</td>';
768
+    print '<td width="25%">'.$langs->trans("FilteredFieldsValues").'</td>';
769
+    print '</tr>';
770
+
771
+    // Champs exportables
772
+    $fieldsarray=$objexport->array_export_fields[0];
773
+    // Champs filtrable
774
+    $Typefieldsarray=$objexport->array_export_TypeFields[0];
775
+    // valeur des filtres
776
+    $ValueFiltersarray=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
777
+    // Select request if all fields are selected
778
+    $sqlmaxforexport=$objexport->build_sql(0, array(), array());
779
+
780
+    $i = 0;
781
+    // on boucle sur les champs
782
+    foreach($fieldsarray as $code => $label)
783
+    {
784
+        print '<tr class="oddeven">';
785
+
786
+        $i++;
787
+        $entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]);
788
+        $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity);
789
+        $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity);
790
+
791
+        print '<td class="nowrap">';
792
+        // If value of entityicon=entitylang='icon:Label'
793
+        $tmparray=explode(':',$entityicon);
794
+        if (count($tmparray) >=2)
795
+        {
796
+            $entityicon=$tmparray[0];
797
+            $entitylang=$tmparray[1];
798
+        }
799
+        print img_object('',$entityicon).' '.$langs->trans($entitylang);
800
+        print '</td>';
801
+
802
+        // Field name
803
+        $labelName=(! empty($fieldsarray[$code])?$fieldsarray[$code]:'');
804
+        $ValueFilter=(! empty($array_filtervalue[$code])?$array_filtervalue[$code]:'');
805
+        $text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
806
+
807
+        $tablename=getablenamefromfield($code,$sqlmaxforexport);
808
+        $htmltext ='<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
809
+            if (! empty($objexport->array_export_special[0][$code]))
810
+        {
811
+            $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
812
+        }
813
+        else
814
+        {
815
+            $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
816
+        }
817
+        if (! empty($objexport->array_export_examplevalues[0][$code]))
818
+        {
819
+            $htmltext.=$langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
820
+        }
821
+        if (! empty($objexport->array_export_TypeFields[0][$code]))
822
+        {
823
+            $htmltext.=$langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
824
+        }
825
+
826
+        print '<td>';
827
+        print $form->textwithpicto($text,$htmltext);
828
+        print '</td>';
829
+
830
+        // Filter value
831
+        print '<td>';
832
+        if (! empty($Typefieldsarray[$code]))	// Example: Text, List:c_country:label:rowid, Number, Boolean
833
+        {
834
+            $szInfoFiltre=$objexport->genDocFilter($Typefieldsarray[$code]);
835
+            if ($szInfoFiltre)	// Is there an info help for this filter ?
836
+            {
837
+                $tmp=$objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
838
+                print $form->textwithpicto($tmp, $szInfoFiltre);
839
+            }
840
+            else
841
+            {
842
+                print $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
843
+            }
844
+        }
845
+        print '</td>';
846
+
847
+        print '</tr>';
848
+    }
849
+
850
+    print '</table>';
851
+
852
+    print '</div>';
853
+
854
+    /*
855 855
 	 * Barre d'action
856 856
 	 */
857
-	print '<div class="tabsAction tabsActionNoBottom">';
858
-	// il n'est pas obligatoire de filtrer les champs
859
-	print '<a class="butAction" href="javascript:FilterField.submit();">'.$langs->trans("NextStep").'</a>';
860
-	print '</div>';
857
+    print '<div class="tabsAction tabsActionNoBottom">';
858
+    // il n'est pas obligatoire de filtrer les champs
859
+    print '<a class="butAction" href="javascript:FilterField.submit();">'.$langs->trans("NextStep").'</a>';
860
+    print '</div>';
861 861
 }
862 862
 
863 863
 if ($step == 4 && $datatoexport)
@@ -890,10 +890,10 @@  discard block
 block discarded – undo
890 890
     // If filters exist
891 891
     if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
892 892
     {
893
-    	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
894
-    	$head[$h][1] = $langs->trans("Step")." 3";
895
-    	$h++;
896
-    	$stepoffset++;
893
+        $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
894
+        $head[$h][1] = $langs->trans("Step")." 3";
895
+        $h++;
896
+        $stepoffset++;
897 897
     }
898 898
 
899 899
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
@@ -917,7 +917,7 @@  discard block
 block discarded – undo
917 917
     // Lot de donnees a exporter
918 918
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
919 919
     print '<td>';
920
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
920
+    $icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
921 921
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
922 922
     print $objexport->array_export_label[0];
923 923
     print '</td></tr>';
@@ -936,22 +936,22 @@  discard block
 block discarded – undo
936 936
     // List of filtered fiels
937 937
     if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
938 938
     {
939
-    	print '<tr><td width="25%">'.$langs->trans("FilteredFields").'</td>';
940
-    	$list='';
941
-    	if (! empty($array_filtervalue))
942
-    	{
943
-    		foreach($array_filtervalue as $code=>$value)
944
-    		{
945
-    			if (isset($objexport->array_export_fields[0][$code]))
946
-    			{
947
-    				$list.=($list?', ':'');
948
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
949
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
950
-    			}
951
-    		}
952
-    	}
953
-    	print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
954
-    	print '</tr>';
939
+        print '<tr><td width="25%">'.$langs->trans("FilteredFields").'</td>';
940
+        $list='';
941
+        if (! empty($array_filtervalue))
942
+        {
943
+            foreach($array_filtervalue as $code=>$value)
944
+            {
945
+                if (isset($objexport->array_export_fields[0][$code]))
946
+                {
947
+                    $list.=($list?', ':'');
948
+                    if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
949
+                    else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
950
+                }
951
+            }
952
+        }
953
+        print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
954
+        print '</tr>';
955 955
     }
956 956
 
957 957
     print '</table>';
@@ -994,7 +994,7 @@  discard block
 block discarded – undo
994 994
 
995 995
         $labelName=$objexport->array_export_fields[0][$code];
996 996
 
997
-		$text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
997
+        $text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
998 998
 
999 999
         $tablename=getablenamefromfield($code,$sqlmaxforexport);
1000 1000
         $htmltext ='<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
@@ -1017,7 +1017,7 @@  discard block
 block discarded – undo
1017 1017
 
1018 1018
         print '<td>';
1019 1019
         print $form->textwithpicto($text,$htmltext);
1020
-		//print ' ('.$code.')';
1020
+        //print ' ('.$code.')';
1021 1021
         print '</td>';
1022 1022
 
1023 1023
         print '<td align="right" width="100">';
@@ -1051,57 +1051,57 @@  discard block
 block discarded – undo
1051 1051
     print '</div>';
1052 1052
 
1053 1053
 
1054
-	// Area for profils export
1055
-	if (count($array_selected))
1054
+    // Area for profils export
1055
+    if (count($array_selected))
1056 1056
     {
1057
-		print '<br>';
1057
+        print '<br>';
1058 1058
         print $langs->trans("SaveExportModel");
1059 1059
 
1060
-		print '<form class="nocellnopadd" action="export.php" method="post">';
1061
-		print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1060
+        print '<form class="nocellnopadd" action="export.php" method="post">';
1061
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1062 1062
         print '<input type="hidden" name="action" value="add_export_model">';
1063 1063
         print '<input type="hidden" name="step" value="'.$step.'">';
1064 1064
         print '<input type="hidden" name="datatoexport" value="'.$datatoexport.'">';
1065 1065
         print '<input type="hidden" name="hexa" value="'.$hexa.'">';
1066 1066
 
1067 1067
         print '<table class="noborder" width="100%">';
1068
-		print '<tr class="liste_titre">';
1069
-		print '<td>'.$langs->trans("ExportModelName").'</td>';
1070
-		print '<td>&nbsp;</td>';
1071
-		print '</tr>';
1068
+        print '<tr class="liste_titre">';
1069
+        print '<td>'.$langs->trans("ExportModelName").'</td>';
1070
+        print '<td>&nbsp;</td>';
1071
+        print '</tr>';
1072 1072
 
1073
-		print '<tr class="oddeven">';
1074
-		print '<td><input name="export_name" size="32" value=""></td><td align="right">';
1073
+        print '<tr class="oddeven">';
1074
+        print '<td><input name="export_name" size="32" value=""></td><td align="right">';
1075 1075
         print '<input type="submit" class="button" value="'.$langs->trans("Save").'">';
1076 1076
         print '</td></tr>';
1077 1077
 
1078 1078
         // List of existing export profils
1079
-    	$sql = "SELECT rowid, label";
1080
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
1081
-		$sql.= " WHERE type = '".$datatoexport."'";
1082
-		if(empty($conf->global->EXPORTS_SHARE_MODELS))$sql.=" AND fk_user=".$user->id;
1083
-		$sql.= " ORDER BY rowid";
1084
-		$resql = $db->query($sql);
1085
-		if ($resql)
1086
-		{
1087
-			$num = $db->num_rows($resql);
1088
-			$i = 0;
1089
-			while ($i < $num)
1090
-			{
1091
-				$obj = $db->fetch_object($resql);
1092
-				print '<tr class="oddeven"><td>';
1093
-				print $obj->label;
1094
-				print '</td><td align="right">';
1095
-				print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=deleteprof&id='.$obj->rowid.'">';
1096
-				print img_delete();
1097
-				print '</a>';
1098
-				print '</tr>';
1099
-				$i++;
1100
-			}
1101
-		}
1102
-		else {
1103
-			dol_print_error($this->db);
1104
-		}
1079
+        $sql = "SELECT rowid, label";
1080
+        $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
1081
+        $sql.= " WHERE type = '".$datatoexport."'";
1082
+        if(empty($conf->global->EXPORTS_SHARE_MODELS))$sql.=" AND fk_user=".$user->id;
1083
+        $sql.= " ORDER BY rowid";
1084
+        $resql = $db->query($sql);
1085
+        if ($resql)
1086
+        {
1087
+            $num = $db->num_rows($resql);
1088
+            $i = 0;
1089
+            while ($i < $num)
1090
+            {
1091
+                $obj = $db->fetch_object($resql);
1092
+                print '<tr class="oddeven"><td>';
1093
+                print $obj->label;
1094
+                print '</td><td align="right">';
1095
+                print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=deleteprof&id='.$obj->rowid.'">';
1096
+                print img_delete();
1097
+                print '</a>';
1098
+                print '</tr>';
1099
+                $i++;
1100
+            }
1101
+        }
1102
+        else {
1103
+            dol_print_error($this->db);
1104
+        }
1105 1105
 
1106 1106
         print '</table>';
1107 1107
         print '</form>';
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
         exit;
1118 1118
     }
1119 1119
 
1120
-	asort($array_selected);
1120
+    asort($array_selected);
1121 1121
 
1122 1122
     llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
1123 1123
 
@@ -1138,10 +1138,10 @@  discard block
 block discarded – undo
1138 1138
     // si le filtrage est parametre pour l'export ou pas
1139 1139
     if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
1140 1140
     {
1141
-    	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
1142
-    	$head[$h][1] = $langs->trans("Step")." 3";
1143
-    	$h++;
1144
-    	$stepoffset++;
1141
+        $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
1142
+        $head[$h][1] = $langs->trans("Step")." 3";
1143
+        $h++;
1144
+        $stepoffset++;
1145 1145
     }
1146 1146
 
1147 1147
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
@@ -1160,7 +1160,7 @@  discard block
 block discarded – undo
1160 1160
      */
1161 1161
     if ($action == 'remove_file')
1162 1162
     {
1163
-    	print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
1163
+        print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1);
1164 1164
     }
1165 1165
 
1166 1166
     print '<div class="fichecenter">';
@@ -1178,7 +1178,7 @@  discard block
 block discarded – undo
1178 1178
     // Lot de donnees a exporter
1179 1179
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
1180 1180
     print '<td>';
1181
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
1181
+    $icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
1182 1182
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
1183 1183
     print $objexport->array_export_label[0];
1184 1184
     print '</td></tr>';
@@ -1196,22 +1196,22 @@  discard block
 block discarded – undo
1196 1196
     // List of filtered fiels
1197 1197
     if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
1198 1198
     {
1199
-    	print '<tr><td>'.$langs->trans("FilteredFields").'</td>';
1200
-    	$list='';
1201
-    	if (! empty($array_filtervalue))
1202
-    	{
1203
-    		foreach($array_filtervalue as $code=>$value)
1204
-    		{
1205
-    			if (isset($objexport->array_export_fields[0][$code]))
1206
-    			{
1207
-    				$list.=($list?', ':'');
1208
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
1209
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
1210
-    			}
1211
-    		}
1212
-    	}
1213
-    	print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
1214
-    	print '</tr>';
1199
+        print '<tr><td>'.$langs->trans("FilteredFields").'</td>';
1200
+        $list='';
1201
+        if (! empty($array_filtervalue))
1202
+        {
1203
+            foreach($array_filtervalue as $code=>$value)
1204
+            {
1205
+                if (isset($objexport->array_export_fields[0][$code]))
1206
+                {
1207
+                    $list.=($list?', ':'');
1208
+                    if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
1209
+                    else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
1210
+                }
1211
+            }
1212
+        }
1213
+        print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
1214
+        print '</tr>';
1215 1215
     }
1216 1216
 
1217 1217
     print '</table>';
@@ -1233,17 +1233,17 @@  discard block
 block discarded – undo
1233 1233
     $listeall=$liste;
1234 1234
     foreach($listeall as $key => $val)
1235 1235
     {
1236
-    	if (preg_match('/__\(Disabled\)__/',$listeall[$key]))
1237
-    	{
1238
-    		$listeall[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$listeall[$key]);
1239
-    		unset($liste[$key]);
1240
-    	}
1236
+        if (preg_match('/__\(Disabled\)__/',$listeall[$key]))
1237
+        {
1238
+            $listeall[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$listeall[$key]);
1239
+            unset($liste[$key]);
1240
+        }
1241 1241
 
1242 1242
         print '<tr class="oddeven">';
1243 1243
         print '<td width="16">'.img_picto_common($key,$objmodelexport->getPictoForKey($key)).' ';
1244
-	    $text=$objmodelexport->getDriverDescForKey($key);
1245
-	    $label=$listeall[$key];
1246
-	    print $form->textwithpicto($label,$text).'</td>';
1244
+        $text=$objmodelexport->getDriverDescForKey($key);
1245
+        $label=$listeall[$key];
1246
+        print $form->textwithpicto($label,$text).'</td>';
1247 1247
         print '<td>'.$objmodelexport->getLibLabelForKey($key).'</td>';
1248 1248
         print '<td align="right">'.$objmodelexport->getLibVersionForKey($key).'</td>';
1249 1249
         print '</tr>'."\n";
@@ -1257,14 +1257,14 @@  discard block
 block discarded – undo
1257 1257
 
1258 1258
     if ($sqlusedforexport && $user->admin)
1259 1259
     {
1260
-    	print '<tr><td>';
1261
-    	print info_admin($langs->trans("SQLUsedForExport").':<br> '.$sqlusedforexport);
1262
-    	print '</td></tr>';
1260
+        print '<tr><td>';
1261
+        print info_admin($langs->trans("SQLUsedForExport").':<br> '.$sqlusedforexport);
1262
+        print '</td></tr>';
1263 1263
     }
1264
-	print '</table>';
1264
+    print '</table>';
1265 1265
 
1266 1266
 
1267
-	print '<div class="fichecenter"><div class="fichehalfleft">';
1267
+    print '<div class="fichecenter"><div class="fichehalfleft">';
1268 1268
 
1269 1269
     if (! is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
1270 1270
 
@@ -1293,16 +1293,16 @@  discard block
 block discarded – undo
1293 1293
  */
1294 1294
 function getablenamefromfield($code,$sqlmaxforexport)
1295 1295
 {
1296
-	$alias=preg_replace('/\.(.*)$/i','',$code);         // Keep only 'Alias' and remove '.Fieldname'
1297
-	$regexstring='/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i';
1298
-
1299
-	$newsql=$sqlmaxforexport;
1300
-	$newsql=preg_replace('/^(.*) FROM /i','',$newsql);  // Remove part before the FROM
1301
-	$newsql=preg_replace('/WHERE (.*)$/i','',$newsql);	// Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE
1302
-
1303
-	if (preg_match($regexstring,$newsql,$reg))
1304
-	{
1305
-		return $reg[1];   // The tablename
1306
-	}
1307
-	else return '';
1296
+    $alias=preg_replace('/\.(.*)$/i','',$code);         // Keep only 'Alias' and remove '.Fieldname'
1297
+    $regexstring='/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i';
1298
+
1299
+    $newsql=$sqlmaxforexport;
1300
+    $newsql=preg_replace('/^(.*) FROM /i','',$newsql);  // Remove part before the FROM
1301
+    $newsql=preg_replace('/WHERE (.*)$/i','',$newsql);	// Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE
1302
+
1303
+    if (preg_match($regexstring,$newsql,$reg))
1304
+    {
1305
+        return $reg[1];   // The tablename
1306
+    }
1307
+    else return '';
1308 1308
 }
Please login to merge, or discard this patch.
Spacing   +257 added lines, -257 removed lines patch added patch discarded remove patch
@@ -123,153 +123,153 @@  discard block
 block discarded – undo
123 123
     'translation'  => 'Translation'
124 124
 );
125 125
 
126
-$array_selected=isset($_SESSION["export_selected_fields"])?$_SESSION["export_selected_fields"]:array();
127
-$array_filtervalue=isset($_SESSION["export_filtered_fields"])?$_SESSION["export_filtered_fields"]:array();
128
-$datatoexport=GETPOST("datatoexport","aZ09");
129
-$action=GETPOST('action','alpha');
130
-$confirm=GETPOST('confirm','alpha');
131
-$step=GETPOST("step","int")?GETPOST("step","int"):1;
132
-$export_name=GETPOST("export_name","alphanohtml");
133
-$hexa=GETPOST("hexa","alpha");
134
-$exportmodelid=GETPOST("exportmodelid","int");
135
-$field=GETPOST("field","alpa");
136
-
137
-$objexport=new Export($db);
138
-$objexport->load_arrays($user,$datatoexport);
139
-
140
-$objmodelexport=new ModeleExports($db);
126
+$array_selected = isset($_SESSION["export_selected_fields"]) ? $_SESSION["export_selected_fields"] : array();
127
+$array_filtervalue = isset($_SESSION["export_filtered_fields"]) ? $_SESSION["export_filtered_fields"] : array();
128
+$datatoexport = GETPOST("datatoexport", "aZ09");
129
+$action = GETPOST('action', 'alpha');
130
+$confirm = GETPOST('confirm', 'alpha');
131
+$step = GETPOST("step", "int") ?GETPOST("step", "int") : 1;
132
+$export_name = GETPOST("export_name", "alphanohtml");
133
+$hexa = GETPOST("hexa", "alpha");
134
+$exportmodelid = GETPOST("exportmodelid", "int");
135
+$field = GETPOST("field", "alpa");
136
+
137
+$objexport = new Export($db);
138
+$objexport->load_arrays($user, $datatoexport);
139
+
140
+$objmodelexport = new ModeleExports($db);
141 141
 $form = new Form($db);
142 142
 $htmlother = new FormOther($db);
143 143
 $formfile = new FormFile($db);
144
-$sqlusedforexport='';
144
+$sqlusedforexport = '';
145 145
 
146 146
 $upload_dir = $conf->export->dir_temp.'/'.$user->id;
147 147
 
148 148
 //$usefilters=($conf->global->MAIN_FEATURES_LEVEL > 1);
149
-$usefilters=1;
149
+$usefilters = 1;
150 150
 
151 151
 
152 152
 /*
153 153
  * Actions
154 154
  */
155 155
 
156
-if ($action=='selectfield')     // Selection of field at step 2
156
+if ($action == 'selectfield')     // Selection of field at step 2
157 157
 {
158
-	$fieldsarray=$objexport->array_export_fields[0];
159
-	$fieldsentitiesarray=$objexport->array_export_entities[0];
160
-    $fieldsdependenciesarray=$objexport->array_export_dependencies[0];
158
+	$fieldsarray = $objexport->array_export_fields[0];
159
+	$fieldsentitiesarray = $objexport->array_export_entities[0];
160
+    $fieldsdependenciesarray = $objexport->array_export_dependencies[0];
161 161
 
162
-    if ($field=='all')
162
+    if ($field == 'all')
163 163
     {
164
-		foreach($fieldsarray as $key=>$val)
164
+		foreach ($fieldsarray as $key=>$val)
165 165
 		{
166
-			if (! empty($array_selected[$key])) continue;		// If already selected, check next
167
-			$array_selected[$key]=count($array_selected)+1;
166
+			if (!empty($array_selected[$key])) continue; // If already selected, check next
167
+			$array_selected[$key] = count($array_selected) + 1;
168 168
 		    //print_r($array_selected);
169
-		    $_SESSION["export_selected_fields"]=$array_selected;
169
+		    $_SESSION["export_selected_fields"] = $array_selected;
170 170
 		}
171 171
     }
172 172
     else
173 173
     {
174
-        $warnings=array();
174
+        $warnings = array();
175 175
 
176
-        $array_selected[$field]=count($array_selected)+1;    // We tag the key $field as "selected"
176
+        $array_selected[$field] = count($array_selected) + 1; // We tag the key $field as "selected"
177 177
         // We check if there is a dependency to activate
178 178
         /*var_dump($field);
179 179
         var_dump($fieldsentitiesarray[$field]);
180 180
         var_dump($fieldsdependenciesarray);*/
181
-        $listofdependencies=array();
182
-        if (! empty($fieldsentitiesarray[$field]) && ! empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]]))
181
+        $listofdependencies = array();
182
+        if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]]))
183 183
         {
184 184
             // We found a dependency on the type of field
185
-            $tmp=$fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid'))
186
-            if (is_array($tmp)) $listofdependencies=$tmp;
187
-            else $listofdependencies=array($tmp);
185
+            $tmp = $fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid'))
186
+            if (is_array($tmp)) $listofdependencies = $tmp;
187
+            else $listofdependencies = array($tmp);
188 188
         }
189
-        else if (! empty($field) && ! empty($fieldsdependenciesarray[$field]))
189
+        else if (!empty($field) && !empty($fieldsdependenciesarray[$field]))
190 190
         {
191 191
             // We found a dependency on a dedicated field
192
-            $tmp=$fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid'))
193
-            if (is_array($tmp)) $listofdependencies=$tmp;
194
-            else $listofdependencies=array($tmp);
192
+            $tmp = $fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid'))
193
+            if (is_array($tmp)) $listofdependencies = $tmp;
194
+            else $listofdependencies = array($tmp);
195 195
         }
196 196
 
197 197
         if (count($listofdependencies))
198 198
         {
199
-            foreach($listofdependencies as $fieldid)
199
+            foreach ($listofdependencies as $fieldid)
200 200
             {
201 201
                 if (empty($array_selected[$fieldid]))
202 202
                 {
203
-                    $array_selected[$fieldid]=count($array_selected)+1;    // We tag the key $fieldid as "selected"
204
-                    $warnings[]=$langs->trans("ExportFieldAutomaticallyAdded",$langs->transnoentitiesnoconv($fieldsarray[$fieldid]));
203
+                    $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected"
204
+                    $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid]));
205 205
                 }
206 206
             }
207 207
         }
208 208
 	    //print_r($array_selected);
209
-	    $_SESSION["export_selected_fields"]=$array_selected;
209
+	    $_SESSION["export_selected_fields"] = $array_selected;
210 210
 
211 211
 	    setEventMessages($warnings, null, 'warnings');
212 212
     }
213 213
 }
214
-if ($action=='unselectfield')
214
+if ($action == 'unselectfield')
215 215
 {
216
-    if ($_GET["field"]=='all')
216
+    if ($_GET["field"] == 'all')
217 217
     {
218
-		$array_selected=array();
219
-		$_SESSION["export_selected_fields"]=$array_selected;
218
+		$array_selected = array();
219
+		$_SESSION["export_selected_fields"] = $array_selected;
220 220
     }
221 221
     else
222 222
     {
223 223
 	    unset($array_selected[$_GET["field"]]);
224 224
 	    // Renumber fields of array_selected (from 1 to nb_elements)
225 225
 	    asort($array_selected);
226
-	    $i=0;
227
-	    $array_selected_save=$array_selected;
228
-	    foreach($array_selected as $code=>$value)
226
+	    $i = 0;
227
+	    $array_selected_save = $array_selected;
228
+	    foreach ($array_selected as $code=>$value)
229 229
 	    {
230 230
 	        $i++;
231
-	        $array_selected[$code]=$i;
231
+	        $array_selected[$code] = $i;
232 232
 	        //print "x $code x $i y<br>";
233 233
 	    }
234
-	    $_SESSION["export_selected_fields"]=$array_selected;
234
+	    $_SESSION["export_selected_fields"] = $array_selected;
235 235
     }
236 236
 }
237 237
 
238
-if ($action=='downfield' || $action=='upfield')
238
+if ($action == 'downfield' || $action == 'upfield')
239 239
 {
240
-    $pos=$array_selected[$_GET["field"]];
241
-    if ($action=='downfield') $newpos=$pos+1;
242
-    if ($action=='upfield') $newpos=$pos-1;
240
+    $pos = $array_selected[$_GET["field"]];
241
+    if ($action == 'downfield') $newpos = $pos + 1;
242
+    if ($action == 'upfield') $newpos = $pos - 1;
243 243
     // Recherche code avec qui switcher
244
-    $newcode="";
245
-    foreach($array_selected as $code=>$value)
244
+    $newcode = "";
245
+    foreach ($array_selected as $code=>$value)
246 246
     {
247 247
         if ($value == $newpos)
248 248
         {
249
-            $newcode=$code;
249
+            $newcode = $code;
250 250
             break;
251 251
         }
252 252
     }
253 253
     //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
254 254
     if ($newcode)   // Si newcode trouve (protection contre resoumission de page)
255 255
     {
256
-        $array_selected[$_GET["field"]]=$newpos;
257
-        $array_selected[$newcode]=$pos;
258
-        $_SESSION["export_selected_fields"]=$array_selected;
256
+        $array_selected[$_GET["field"]] = $newpos;
257
+        $array_selected[$newcode] = $pos;
258
+        $_SESSION["export_selected_fields"] = $array_selected;
259 259
     }
260 260
 }
261 261
 
262 262
 if ($step == 1 || $action == 'cleanselect')
263 263
 {
264
-    $_SESSION["export_selected_fields"]=array();
265
-    $_SESSION["export_filtered_fields"]=array();
266
-    $array_selected=array();
267
-    $array_filtervalue=array();
264
+    $_SESSION["export_selected_fields"] = array();
265
+    $_SESSION["export_filtered_fields"] = array();
266
+    $array_selected = array();
267
+    $array_filtervalue = array();
268 268
 }
269 269
 
270 270
 if ($action == 'builddoc')
271 271
 {
272
-    $max_execution_time_for_export = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME)?300:$conf->global->EXPORT_MAX_EXECUTION_TIME);    // 5mn if not defined
272
+    $max_execution_time_for_export = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined
273 273
     $max_time = @ini_get("max_execution_time");
274 274
     if ($max_time && $max_time < $max_execution_time_for_export)
275 275
     {
@@ -277,25 +277,25 @@  discard block
 block discarded – undo
277 277
     }
278 278
 
279 279
     // Build export file
280
-	$result=$objexport->build_file($user, GETPOST('model','alpha'), $datatoexport, $array_selected, $array_filtervalue);
280
+	$result = $objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue);
281 281
 	if ($result < 0)
282 282
 	{
283 283
 		setEventMessages($objexport->error, $objexport->errors, 'errors');
284
-		$sqlusedforexport=$objexport->sqlusedforexport;
284
+		$sqlusedforexport = $objexport->sqlusedforexport;
285 285
 	}
286 286
 	else
287 287
 	{
288 288
 		setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
289
-	    $sqlusedforexport=$objexport->sqlusedforexport;
289
+	    $sqlusedforexport = $objexport->sqlusedforexport;
290 290
     }
291 291
 }
292 292
 
293 293
 // Delete file
294 294
 if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes')
295 295
 {
296
-	$file = $upload_dir . "/" . GETPOST('file');	// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
296
+	$file = $upload_dir."/".GETPOST('file'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
297 297
 
298
-	$ret=dol_delete_file($file);
298
+	$ret = dol_delete_file($file);
299 299
 	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
300 300
 	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
301 301
 	header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport);
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 	if ($_GET["id"])
308 308
 	{
309 309
 		$objexport->fetch($_GET["id"]);
310
-		$result=$objexport->delete($user);
310
+		$result = $objexport->delete($user);
311 311
 	}
312 312
 }
313 313
 
@@ -319,20 +319,20 @@  discard block
 block discarded – undo
319 319
 		asort($array_selected);
320 320
 
321 321
 		// Set save string
322
-		$hexa='';
323
-		foreach($array_selected as $key=>$val)
322
+		$hexa = '';
323
+		foreach ($array_selected as $key=>$val)
324 324
 		{
325
-			if ($hexa) $hexa.=',';
326
-			$hexa.=$key;
325
+			if ($hexa) $hexa .= ',';
326
+			$hexa .= $key;
327 327
 		}
328 328
 
329
-		$hexafiltervalue='';
330
-		if (! empty($array_filtervalue) && is_array($array_filtervalue))
329
+		$hexafiltervalue = '';
330
+		if (!empty($array_filtervalue) && is_array($array_filtervalue))
331 331
 		{
332
-			foreach($array_filtervalue as $key=>$val)
332
+			foreach ($array_filtervalue as $key=>$val)
333 333
 			{
334
-				if ($hexafiltervalue) $hexafiltervalue.=',';
335
-				$hexafiltervalue.=$key.'='.$val;
334
+				if ($hexafiltervalue) $hexafiltervalue .= ',';
335
+				$hexafiltervalue .= $key.'='.$val;
336 336
 			}
337 337
 		}
338 338
 
@@ -344,7 +344,7 @@  discard block
 block discarded – undo
344 344
 	    $result = $objexport->create($user);
345 345
 		if ($result >= 0)
346 346
 		{
347
-			setEventMessages($langs->trans("ExportModelSaved",$objexport->model_name), null, 'mesgs');
347
+			setEventMessages($langs->trans("ExportModelSaved", $objexport->model_name), null, 'mesgs');
348 348
 		}
349 349
 		else
350 350
 		{
@@ -364,33 +364,33 @@  discard block
 block discarded – undo
364 364
 // Reload an predefined export model
365 365
 if ($step == 2 && $action == 'select_model')
366 366
 {
367
-    $_SESSION["export_selected_fields"]=array();
368
-    $_SESSION["export_filtered_fields"]=array();
367
+    $_SESSION["export_selected_fields"] = array();
368
+    $_SESSION["export_filtered_fields"] = array();
369 369
 
370
-    $array_selected=array();
371
-    $array_filtervalue=array();
370
+    $array_selected = array();
371
+    $array_filtervalue = array();
372 372
 
373 373
     $result = $objexport->fetch($exportmodelid);
374 374
     if ($result > 0)
375 375
     {
376
-		$fieldsarray=explode(',',$objexport->hexa);
377
-		$i=1;
378
-		foreach($fieldsarray as $val)
376
+		$fieldsarray = explode(',', $objexport->hexa);
377
+		$i = 1;
378
+		foreach ($fieldsarray as $val)
379 379
 		{
380
-			$array_selected[$val]=$i;
380
+			$array_selected[$val] = $i;
381 381
 			$i++;
382 382
 		}
383
-		$_SESSION["export_selected_fields"]=$array_selected;
383
+		$_SESSION["export_selected_fields"] = $array_selected;
384 384
 
385
-		$fieldsarrayvalue=explode(',',$objexport->hexafiltervalue);
386
-		$i=1;
387
-		foreach($fieldsarrayvalue as $val)
385
+		$fieldsarrayvalue = explode(',', $objexport->hexafiltervalue);
386
+		$i = 1;
387
+		foreach ($fieldsarrayvalue as $val)
388 388
 		{
389
-			$tmp=explode('=',$val);
390
-			$array_filtervalue[$tmp[0]]=$tmp[1];
389
+			$tmp = explode('=', $val);
390
+			$array_filtervalue[$tmp[0]] = $tmp[1];
391 391
 			$i++;
392 392
 		}
393
-		$_SESSION["export_filtered_fields"]=$array_filtervalue;
393
+		$_SESSION["export_filtered_fields"] = $array_filtervalue;
394 394
     }
395 395
 }
396 396
 
@@ -400,22 +400,22 @@  discard block
 block discarded – undo
400 400
 	// on boucle sur les champs selectionne pour recuperer la valeur
401 401
 	if (is_array($objexport->array_export_TypeFields[0]))
402 402
 	{
403
-		$_SESSION["export_filtered_fields"]=array();
404
-		foreach($objexport->array_export_TypeFields[0] as $code => $type)	// $code: s.fieldname $value: Text|Boolean|List:ccc
403
+		$_SESSION["export_filtered_fields"] = array();
404
+		foreach ($objexport->array_export_TypeFields[0] as $code => $type)	// $code: s.fieldname $value: Text|Boolean|List:ccc
405 405
 		{
406
-			$newcode=(string) preg_replace('/\./','_',$code);
406
+			$newcode = (string) preg_replace('/\./', '_', $code);
407 407
 			//print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n<br>";
408
-			$filterqualified=1;
409
-			if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified=0;
410
-			elseif (preg_match('/^List/',$type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified=0;
408
+			$filterqualified = 1;
409
+			if (!isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified = 0;
410
+			elseif (preg_match('/^List/', $type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified = 0;
411 411
 			if ($filterqualified)
412 412
 			{
413 413
 				//print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n";
414 414
 				$objexport->array_export_FilterValue[0][$code] = $_POST[$newcode];
415 415
 			}
416 416
 		}
417
-		$array_filtervalue=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
418
-		$_SESSION["export_filtered_fields"]=$array_filtervalue;
417
+		$array_filtervalue = (!empty($objexport->array_export_FilterValue[0]) ? $objexport->array_export_FilterValue[0] : '');
418
+		$_SESSION["export_filtered_fields"] = $array_filtervalue;
419 419
 	}
420 420
 }
421 421
 
@@ -424,9 +424,9 @@  discard block
 block discarded – undo
424 424
  * View
425 425
  */
426 426
 
427
-if ($step == 1 || ! $datatoexport)
427
+if ($step == 1 || !$datatoexport)
428 428
 {
429
-    llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
429
+    llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
430 430
 
431 431
     /*
432 432
      * Affichage onglets
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 
436 436
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
437 437
     $head[$h][1] = $langs->trans("Step")." 1";
438
-    $hselected=$h;
438
+    $hselected = $h;
439 439
     $h++;
440 440
 
441 441
     /*
@@ -458,25 +458,25 @@  discard block
 block discarded – undo
458 458
     print '<td>'.$langs->trans("ExportableDatas").'</td>';
459 459
     print '<td>&nbsp;</td>';
460 460
     print '</tr>';
461
-    $val=true;
461
+    $val = true;
462 462
     if (count($objexport->array_export_code))
463 463
     {
464 464
         foreach ($objexport->array_export_code as $key => $value)
465 465
         {
466
-            $val=!$val;
466
+            $val = !$val;
467 467
             print '<tr '.$bc[$val].'><td nospan="nospan">';
468 468
 	        //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' ';
469 469
             print $objexport->array_export_module[$key]->getName();
470 470
             print '</td><td>';
471
-			$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[$key]);
472
-			$label=$objexport->array_export_label[$key];
471
+			$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[$key]);
472
+			$label = $objexport->array_export_label[$key];
473 473
             //print $value.'-'.$icon.'-'.$label."<br>";
474 474
 			print img_object($objexport->array_export_module[$key]->getName(), $icon).' ';
475 475
             print $label;
476 476
             print '</td><td align="right">';
477 477
             if ($objexport->array_export_perms[$key])
478 478
             {
479
-            	print '<a href="'.DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$objexport->array_export_code[$key].'">'.img_picto($langs->trans("NewExport"),'filenew').'</a>';
479
+            	print '<a href="'.DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$objexport->array_export_code[$key].'">'.img_picto($langs->trans("NewExport"), 'filenew').'</a>';
480 480
             }
481 481
             else
482 482
             {
@@ -498,7 +498,7 @@  discard block
 block discarded – undo
498 498
 
499 499
 if ($step == 2 && $datatoexport)
500 500
 {
501
-    llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
501
+    llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
502 502
 
503 503
 
504 504
     /*
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 
513 513
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport;
514 514
     $head[$h][1] = $langs->trans("Step")." 2";
515
-    $hselected=$h;
515
+    $hselected = $h;
516 516
     $h++;
517 517
 
518 518
     dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
@@ -531,8 +531,8 @@  discard block
 block discarded – undo
531 531
     // Lot de donnees a exporter
532 532
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
533 533
     print '<td>';
534
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
535
-    $label=$objexport->array_export_label[0];
534
+	$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
535
+    $label = $objexport->array_export_label[0];
536 536
     //print $value.'-'.$icon.'-'.$label."<br>";
537 537
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
538 538
     print $label;
@@ -553,8 +553,8 @@  discard block
 block discarded – undo
553 553
     print '<input type="hidden" name="datatoexport" value="'.$datatoexport.'">';
554 554
     print '<table><tr><td colspan="2">';
555 555
     print $langs->trans("SelectExportFields").' ';
556
-    if(empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1,$user->id);
557
-	else $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1);
556
+    if (empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid, 'exportmodelid', $datatoexport, 1, $user->id);
557
+	else $htmlother->select_export_model($exportmodelid, 'exportmodelid', $datatoexport, 1);
558 558
     print ' ';
559 559
     print '<input type="submit" class="button" value="'.$langs->trans("Select").'">';
560 560
     print '</td></tr></table>';
@@ -574,9 +574,9 @@  discard block
 block discarded – undo
574 574
     print '</tr>';
575 575
 
576 576
     // Champs exportables
577
-    $fieldsarray=$objexport->array_export_fields[0];
577
+    $fieldsarray = $objexport->array_export_fields[0];
578 578
     // Select request if all fields are selected
579
-    $sqlmaxforexport=$objexport->build_sql(0, array(), array());
579
+    $sqlmaxforexport = $objexport->build_sql(0, array(), array());
580 580
 
581 581
 	//    $this->array_export_module[0]=$module;
582 582
 	//    $this->array_export_code[0]=$module->export_code[$r];
@@ -588,48 +588,48 @@  discard block
 block discarded – undo
588 588
 
589 589
     $i = 0;
590 590
 
591
-    foreach($fieldsarray as $code=>$label)
591
+    foreach ($fieldsarray as $code=>$label)
592 592
     {
593 593
         print '<tr class="oddeven">';
594 594
 
595 595
         $i++;
596 596
 
597
-        $entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]);
598
-        $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity);
599
-        $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity);
597
+        $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
598
+        $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
599
+        $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
600 600
 
601 601
         print '<td class="nowrap">';
602 602
         // If value of entityicon=entitylang='icon:Label'
603 603
         //print $code.'-'.$label.'-'.$entity;
604 604
 
605
-        $tmparray=explode(':',$entityicon);
606
-        if (count($tmparray) >=2)
605
+        $tmparray = explode(':', $entityicon);
606
+        if (count($tmparray) >= 2)
607 607
         {
608
-            $entityicon=$tmparray[0];
609
-            $entitylang=$tmparray[1];
608
+            $entityicon = $tmparray[0];
609
+            $entitylang = $tmparray[1];
610 610
         }
611
-        print img_object('',$entityicon).' '.$langs->trans($entitylang);
611
+        print img_object('', $entityicon).' '.$langs->trans($entitylang);
612 612
         print '</td>';
613 613
 
614
-        $text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($label).(empty($objexport->array_export_special[0][$code])?'':'</i>');
614
+        $text = (empty($objexport->array_export_special[0][$code]) ? '' : '<i>').$langs->trans($label).(empty($objexport->array_export_special[0][$code]) ? '' : '</i>');
615 615
 
616
-        $tablename=getablenamefromfield($code,$sqlmaxforexport);
617
-        $htmltext ='<b>'.$langs->trans("Name").":</b> ".$text.'<br>';
618
-        if (! empty($objexport->array_export_special[0][$code]))
616
+        $tablename = getablenamefromfield($code, $sqlmaxforexport);
617
+        $htmltext = '<b>'.$langs->trans("Name").":</b> ".$text.'<br>';
618
+        if (!empty($objexport->array_export_special[0][$code]))
619 619
         {
620
-            $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
620
+            $htmltext .= '<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
621 621
         }
622 622
         else
623 623
         {
624
-            $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
624
+            $htmltext .= '<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."<br>";
625 625
         }
626
-   		if (! empty($objexport->array_export_examplevalues[0][$code]))
626
+   		if (!empty($objexport->array_export_examplevalues[0][$code]))
627 627
 		{
628
-		    $htmltext.='<b>'.$langs->trans("SourceExample").':</b> '.$objexport->array_export_examplevalues[0][$code].'<br>';
628
+		    $htmltext .= '<b>'.$langs->trans("SourceExample").':</b> '.$objexport->array_export_examplevalues[0][$code].'<br>';
629 629
 		}
630
-    	if (! empty($objexport->array_export_TypeFields[0][$code]))
630
+    	if (!empty($objexport->array_export_TypeFields[0][$code]))
631 631
 		{
632
-		    $htmltext.='<b>'.$langs->trans("Type").':</b> '.$objexport->array_export_TypeFields[0][$code].'<br>';
632
+		    $htmltext .= '<b>'.$langs->trans("Type").':</b> '.$objexport->array_export_TypeFields[0][$code].'<br>';
633 633
 		}
634 634
 
635 635
 		if (isset($array_selected[$code]) && $array_selected[$code])
@@ -639,7 +639,7 @@  discard block
 block discarded – undo
639 639
             print '<td align="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?step=2&datatoexport='.$datatoexport.'&action=unselectfield&field='.$code.'">'.img_left('default', 0, 'style="max-width: 20px"').'</a></td>';
640 640
             print '<td>';
641 641
             //print $text.'-'.$htmltext."<br>";
642
-            print $form->textwithpicto($text,$htmltext);
642
+            print $form->textwithpicto($text, $htmltext);
643 643
 			//print ' ('.$code.')';
644 644
             print '</td>';
645 645
         }
@@ -648,7 +648,7 @@  discard block
 block discarded – undo
648 648
         	// Fields not selected
649 649
             print '<td>';
650 650
 			//print $text.'-'.$htmltext."<br>";
651
-			print $form->textwithpicto($text,$htmltext);
651
+			print $form->textwithpicto($text, $htmltext);
652 652
 			//print ' ('.$code.')';
653 653
             print '</td>';
654 654
             print '<td align="center"><a class="reposition" href="'.$_SERVER["PHP_SELF"].'?step=2&datatoexport='.$datatoexport.'&action=selectfield&field='.$code.'">'.img_right('default', 0, 'style="max-width: 20px"').'</a></td>';
@@ -695,7 +695,7 @@  discard block
 block discarded – undo
695 695
         exit;
696 696
     }
697 697
 
698
-    llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
698
+    llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
699 699
 
700 700
 	/*
701 701
 	 * Affichage onglets
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
 
713 713
 	$head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport;
714 714
 	$head[$h][1] = $langs->trans("Step")." 3";
715
-	$hselected=$h;
715
+	$hselected = $h;
716 716
 	$h++;
717 717
 
718 718
 	dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
@@ -731,8 +731,8 @@  discard block
 block discarded – undo
731 731
 	// Lot de donnees a exporter
732 732
 	print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
733 733
 	print '<td>';
734
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
735
-	$label=$objexport->array_export_label[0];
734
+	$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
735
+	$label = $objexport->array_export_label[0];
736 736
 	//print $value.'-'.$icon.'-'.$label."<br>";
737 737
 	print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
738 738
 	print $label;
@@ -740,11 +740,11 @@  discard block
 block discarded – undo
740 740
 
741 741
 	// Nbre champs exportes
742 742
 	print '<tr><td>'.$langs->trans("ExportedFields").'</td>';
743
-	$list='';
744
-	foreach($array_selected as $code=>$value)
743
+	$list = '';
744
+	foreach ($array_selected as $code=>$value)
745 745
 	{
746
-		$list.=(! empty($list)?', ':'');
747
-		$list.=(isset($objexport->array_export_fields[0][$code])?$langs->trans($objexport->array_export_fields[0][$code]):'');
746
+		$list .= (!empty($list) ? ', ' : '');
747
+		$list .= (isset($objexport->array_export_fields[0][$code]) ? $langs->trans($objexport->array_export_fields[0][$code]) : '');
748 748
 	}
749 749
 	print '<td>'.$list.'</td></tr>';
750 750
 
@@ -769,72 +769,72 @@  discard block
 block discarded – undo
769 769
 	print '</tr>';
770 770
 
771 771
 	// Champs exportables
772
-	$fieldsarray=$objexport->array_export_fields[0];
772
+	$fieldsarray = $objexport->array_export_fields[0];
773 773
 	// Champs filtrable
774
-	$Typefieldsarray=$objexport->array_export_TypeFields[0];
774
+	$Typefieldsarray = $objexport->array_export_TypeFields[0];
775 775
 	// valeur des filtres
776
-	$ValueFiltersarray=(! empty($objexport->array_export_FilterValue[0])?$objexport->array_export_FilterValue[0]:'');
776
+	$ValueFiltersarray = (!empty($objexport->array_export_FilterValue[0]) ? $objexport->array_export_FilterValue[0] : '');
777 777
 	// Select request if all fields are selected
778
-	$sqlmaxforexport=$objexport->build_sql(0, array(), array());
778
+	$sqlmaxforexport = $objexport->build_sql(0, array(), array());
779 779
 
780 780
 	$i = 0;
781 781
 	// on boucle sur les champs
782
-	foreach($fieldsarray as $code => $label)
782
+	foreach ($fieldsarray as $code => $label)
783 783
 	{
784 784
 		print '<tr class="oddeven">';
785 785
 
786 786
 		$i++;
787
-		$entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]);
788
-		$entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity);
789
-		$entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity);
787
+		$entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
788
+		$entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
789
+		$entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
790 790
 
791 791
 		print '<td class="nowrap">';
792 792
 		// If value of entityicon=entitylang='icon:Label'
793
-		$tmparray=explode(':',$entityicon);
794
-		if (count($tmparray) >=2)
793
+		$tmparray = explode(':', $entityicon);
794
+		if (count($tmparray) >= 2)
795 795
 		{
796
-			$entityicon=$tmparray[0];
797
-			$entitylang=$tmparray[1];
796
+			$entityicon = $tmparray[0];
797
+			$entitylang = $tmparray[1];
798 798
 		}
799
-		print img_object('',$entityicon).' '.$langs->trans($entitylang);
799
+		print img_object('', $entityicon).' '.$langs->trans($entitylang);
800 800
 		print '</td>';
801 801
 
802 802
 		// Field name
803
-		$labelName=(! empty($fieldsarray[$code])?$fieldsarray[$code]:'');
804
-		$ValueFilter=(! empty($array_filtervalue[$code])?$array_filtervalue[$code]:'');
805
-		$text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
803
+		$labelName = (!empty($fieldsarray[$code]) ? $fieldsarray[$code] : '');
804
+		$ValueFilter = (!empty($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
805
+		$text = (empty($objexport->array_export_special[0][$code]) ? '' : '<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code]) ? '' : '</i>');
806 806
 
807
-		$tablename=getablenamefromfield($code,$sqlmaxforexport);
808
-		$htmltext ='<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
809
-			if (! empty($objexport->array_export_special[0][$code]))
807
+		$tablename = getablenamefromfield($code, $sqlmaxforexport);
808
+		$htmltext = '<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
809
+			if (!empty($objexport->array_export_special[0][$code]))
810 810
 		{
811
-		    $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
811
+		    $htmltext .= '<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
812 812
 		}
813 813
 		else
814 814
 		{
815
-		    $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
815
+		    $htmltext .= '<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."<br>";
816 816
 		}
817
-		if (! empty($objexport->array_export_examplevalues[0][$code]))
817
+		if (!empty($objexport->array_export_examplevalues[0][$code]))
818 818
 		{
819
-		    $htmltext.=$langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
819
+		    $htmltext .= $langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
820 820
 		}
821
-		if (! empty($objexport->array_export_TypeFields[0][$code]))
821
+		if (!empty($objexport->array_export_TypeFields[0][$code]))
822 822
 		{
823
-		    $htmltext.=$langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
823
+		    $htmltext .= $langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
824 824
 		}
825 825
 
826 826
 		print '<td>';
827
-		print $form->textwithpicto($text,$htmltext);
827
+		print $form->textwithpicto($text, $htmltext);
828 828
 		print '</td>';
829 829
 
830 830
 		// Filter value
831 831
 		print '<td>';
832
-		if (! empty($Typefieldsarray[$code]))	// Example: Text, List:c_country:label:rowid, Number, Boolean
832
+		if (!empty($Typefieldsarray[$code]))	// Example: Text, List:c_country:label:rowid, Number, Boolean
833 833
 		{
834
-			$szInfoFiltre=$objexport->genDocFilter($Typefieldsarray[$code]);
834
+			$szInfoFiltre = $objexport->genDocFilter($Typefieldsarray[$code]);
835 835
 			if ($szInfoFiltre)	// Is there an info help for this filter ?
836 836
 			{
837
-				$tmp=$objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
837
+				$tmp = $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
838 838
 				print $form->textwithpicto($tmp, $szInfoFiltre);
839 839
 			}
840 840
 			else
@@ -871,12 +871,12 @@  discard block
 block discarded – undo
871 871
 
872 872
     asort($array_selected);
873 873
 
874
-    llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
874
+    llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
875 875
 
876 876
     /*
877 877
      * Affichage onglets
878 878
      */
879
-    $stepoffset=0;
879
+    $stepoffset = 0;
880 880
     $h = 0;
881 881
 
882 882
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
@@ -897,8 +897,8 @@  discard block
 block discarded – undo
897 897
     }
898 898
 
899 899
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
900
-    $head[$h][1] = $langs->trans("Step")." ".(3+$stepoffset);
901
-    $hselected=$h;
900
+    $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
901
+    $hselected = $h;
902 902
     $h++;
903 903
 
904 904
     dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
@@ -917,18 +917,18 @@  discard block
 block discarded – undo
917 917
     // Lot de donnees a exporter
918 918
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
919 919
     print '<td>';
920
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
920
+	$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
921 921
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
922 922
     print $objexport->array_export_label[0];
923 923
     print '</td></tr>';
924 924
 
925 925
     // List of exported fields
926 926
     print '<tr><td>'.$langs->trans("ExportedFields").'</td>';
927
-    $list='';
928
-    foreach($array_selected as $code=>$value)
927
+    $list = '';
928
+    foreach ($array_selected as $code=>$value)
929 929
     {
930
-        $list.=(! empty($list)?', ':'');
931
-        $list.=$langs->trans($objexport->array_export_fields[0][$code]);
930
+        $list .= (!empty($list) ? ', ' : '');
931
+        $list .= $langs->trans($objexport->array_export_fields[0][$code]);
932 932
     }
933 933
     print '<td>'.$list.'</td>';
934 934
     print '</tr>';
@@ -937,20 +937,20 @@  discard block
 block discarded – undo
937 937
     if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
938 938
     {
939 939
     	print '<tr><td width="25%">'.$langs->trans("FilteredFields").'</td>';
940
-    	$list='';
941
-    	if (! empty($array_filtervalue))
940
+    	$list = '';
941
+    	if (!empty($array_filtervalue))
942 942
     	{
943
-    		foreach($array_filtervalue as $code=>$value)
943
+    		foreach ($array_filtervalue as $code=>$value)
944 944
     		{
945 945
     			if (isset($objexport->array_export_fields[0][$code]))
946 946
     			{
947
-    				$list.=($list?', ':'');
948
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
949
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
947
+    				$list .= ($list ? ', ' : '');
948
+    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
949
+    				else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
950 950
     			}
951 951
     		}
952 952
     	}
953
-    	print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
953
+    	print '<td>'.(!empty($list) ? $list : $langs->trans("None")).'</td>';
954 954
     	print '</tr>';
955 955
     }
956 956
 
@@ -960,7 +960,7 @@  discard block
 block discarded – undo
960 960
     print '<br>';
961 961
 
962 962
     // Select request if all fields are selected
963
-    $sqlmaxforexport=$objexport->build_sql(0, array(), array());
963
+    $sqlmaxforexport = $objexport->build_sql(0, array(), array());
964 964
 
965 965
     print $langs->trans("ChooseFieldsOrdersAndTitle").'<br>';
966 966
 
@@ -973,50 +973,50 @@  discard block
 block discarded – undo
973 973
     //print '<td>'.$langs->trans("FieldsTitle").'</td>';
974 974
     print '</tr>';
975 975
 
976
-    foreach($array_selected as $code=>$value)
976
+    foreach ($array_selected as $code=>$value)
977 977
     {
978 978
         print '<tr class="oddeven">';
979 979
 
980
-        $entity=(! empty($objexport->array_export_entities[0][$code])?$objexport->array_export_entities[0][$code]:$objexport->array_export_icon[0]);
981
-        $entityicon=strtolower(! empty($entitytoicon[$entity])?$entitytoicon[$entity]:$entity);
982
-        $entitylang=(! empty($entitytolang[$entity])?$entitytolang[$entity]:$entity);
980
+        $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]);
981
+        $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity);
982
+        $entitylang = (!empty($entitytolang[$entity]) ? $entitytolang[$entity] : $entity);
983 983
 
984 984
         print '<td class="nowrap">';
985 985
         // If value of entityicon=entitylang='icon:Label'
986
-        $tmparray=explode(':',$entityicon);
987
-        if (count($tmparray) >=2)
986
+        $tmparray = explode(':', $entityicon);
987
+        if (count($tmparray) >= 2)
988 988
         {
989
-            $entityicon=$tmparray[0];
990
-            $entitylang=$tmparray[1];
989
+            $entityicon = $tmparray[0];
990
+            $entitylang = $tmparray[1];
991 991
         }
992
-        print img_object('',$entityicon).' '.$langs->trans($entitylang);
992
+        print img_object('', $entityicon).' '.$langs->trans($entitylang);
993 993
         print '</td>';
994 994
 
995
-        $labelName=$objexport->array_export_fields[0][$code];
995
+        $labelName = $objexport->array_export_fields[0][$code];
996 996
 
997
-		$text=(empty($objexport->array_export_special[0][$code])?'':'<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code])?'':'</i>');
997
+		$text = (empty($objexport->array_export_special[0][$code]) ? '' : '<i>').$langs->trans($labelName).(empty($objexport->array_export_special[0][$code]) ? '' : '</i>');
998 998
 
999
-        $tablename=getablenamefromfield($code,$sqlmaxforexport);
1000
-        $htmltext ='<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
1001
-        if (! empty($objexport->array_export_special[0][$code]))
999
+        $tablename = getablenamefromfield($code, $sqlmaxforexport);
1000
+        $htmltext = '<b>'.$langs->trans("Name").':</b> '.$text.'<br>';
1001
+        if (!empty($objexport->array_export_special[0][$code]))
1002 1002
         {
1003
-            $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
1003
+            $htmltext .= '<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
1004 1004
         }
1005 1005
         else
1006 1006
         {
1007
-            $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
1007
+            $htmltext .= '<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."<br>";
1008 1008
         }
1009
-        if (! empty($objexport->array_export_examplevalues[0][$code]))
1009
+        if (!empty($objexport->array_export_examplevalues[0][$code]))
1010 1010
         {
1011
-            $htmltext.=$langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
1011
+            $htmltext .= $langs->trans("SourceExample").': <b>'.$objexport->array_export_examplevalues[0][$code].'</b><br>';
1012 1012
         }
1013
-        if (! empty($objexport->array_export_TypeFields[0][$code]))
1013
+        if (!empty($objexport->array_export_TypeFields[0][$code]))
1014 1014
         {
1015
-            $htmltext.=$langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
1015
+            $htmltext .= $langs->trans("Type").': <b>'.$objexport->array_export_TypeFields[0][$code].'</b><br>';
1016 1016
         }
1017 1017
 
1018 1018
         print '<td>';
1019
-        print $form->textwithpicto($text,$htmltext);
1019
+        print $form->textwithpicto($text, $htmltext);
1020 1020
 		//print ' ('.$code.')';
1021 1021
         print '</td>';
1022 1022
 
@@ -1077,10 +1077,10 @@  discard block
 block discarded – undo
1077 1077
 
1078 1078
         // List of existing export profils
1079 1079
     	$sql = "SELECT rowid, label";
1080
-		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
1081
-		$sql.= " WHERE type = '".$datatoexport."'";
1082
-		if(empty($conf->global->EXPORTS_SHARE_MODELS))$sql.=" AND fk_user=".$user->id;
1083
-		$sql.= " ORDER BY rowid";
1080
+		$sql .= " FROM ".MAIN_DB_PREFIX."export_model";
1081
+		$sql .= " WHERE type = '".$datatoexport."'";
1082
+		if (empty($conf->global->EXPORTS_SHARE_MODELS))$sql .= " AND fk_user=".$user->id;
1083
+		$sql .= " ORDER BY rowid";
1084 1084
 		$resql = $db->query($sql);
1085 1085
 		if ($resql)
1086 1086
 		{
@@ -1119,13 +1119,13 @@  discard block
 block discarded – undo
1119 1119
 
1120 1120
 	asort($array_selected);
1121 1121
 
1122
-    llxHeader('',$langs->trans("NewExport"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
1122
+    llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
1123 1123
 
1124 1124
     /*
1125 1125
      * Affichage onglets
1126 1126
      */
1127 1127
     $h = 0;
1128
-    $stepoffset=0;
1128
+    $stepoffset = 0;
1129 1129
 
1130 1130
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=1';
1131 1131
     $head[$h][1] = $langs->trans("Step")." 1";
@@ -1145,12 +1145,12 @@  discard block
 block discarded – undo
1145 1145
     }
1146 1146
 
1147 1147
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=4&datatoexport='.$datatoexport;
1148
-    $head[$h][1] = $langs->trans("Step")." ".(3+$stepoffset);
1148
+    $head[$h][1] = $langs->trans("Step")." ".(3 + $stepoffset);
1149 1149
     $h++;
1150 1150
 
1151 1151
     $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=5&datatoexport='.$datatoexport;
1152
-    $head[$h][1] = $langs->trans("Step")." ".(4+$stepoffset);
1153
-    $hselected=$h;
1152
+    $head[$h][1] = $langs->trans("Step")." ".(4 + $stepoffset);
1153
+    $hselected = $h;
1154 1154
     $h++;
1155 1155
 
1156 1156
     dol_fiche_head($head, $hselected, $langs->trans("NewExport"), -1);
@@ -1178,18 +1178,18 @@  discard block
 block discarded – undo
1178 1178
     // Lot de donnees a exporter
1179 1179
     print '<tr><td>'.$langs->trans("DatasetToExport").'</td>';
1180 1180
     print '<td>';
1181
-	$icon=preg_replace('/:.*$/','',$objexport->array_export_icon[0]);
1181
+	$icon = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]);
1182 1182
     print img_object($objexport->array_export_module[0]->getName(), $icon).' ';
1183 1183
     print $objexport->array_export_label[0];
1184 1184
     print '</td></tr>';
1185 1185
 
1186 1186
     // List of exported fields
1187 1187
     print '<tr><td>'.$langs->trans("ExportedFields").'</td>';
1188
-    $list='';
1189
-    foreach($array_selected as $code=>$label)
1188
+    $list = '';
1189
+    foreach ($array_selected as $code=>$label)
1190 1190
     {
1191
-        $list.=(! empty($list)?', ':'');
1192
-        $list.=$langs->trans($objexport->array_export_fields[0][$code]);
1191
+        $list .= (!empty($list) ? ', ' : '');
1192
+        $list .= $langs->trans($objexport->array_export_fields[0][$code]);
1193 1193
     }
1194 1194
     print '<td>'.$list.'</td></tr>';
1195 1195
 
@@ -1197,20 +1197,20 @@  discard block
 block discarded – undo
1197 1197
     if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
1198 1198
     {
1199 1199
     	print '<tr><td>'.$langs->trans("FilteredFields").'</td>';
1200
-    	$list='';
1201
-    	if (! empty($array_filtervalue))
1200
+    	$list = '';
1201
+    	if (!empty($array_filtervalue))
1202 1202
     	{
1203
-    		foreach($array_filtervalue as $code=>$value)
1203
+    		foreach ($array_filtervalue as $code=>$value)
1204 1204
     		{
1205 1205
     			if (isset($objexport->array_export_fields[0][$code]))
1206 1206
     			{
1207
-    				$list.=($list?', ':'');
1208
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
1209
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
1207
+    				$list .= ($list ? ', ' : '');
1208
+    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '');
1209
+    				else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'";
1210 1210
     			}
1211 1211
     		}
1212 1212
     	}
1213
-    	print '<td>'.(! empty($list)?$list:$langs->trans("None")).'</td>';
1213
+    	print '<td>'.(!empty($list) ? $list : $langs->trans("None")).'</td>';
1214 1214
     	print '</tr>';
1215 1215
     }
1216 1216
 
@@ -1229,21 +1229,21 @@  discard block
 block discarded – undo
1229 1229
     print '<td align="right">'.$langs->trans("LibraryVersion").'</td>';
1230 1230
     print '</tr>'."\n";
1231 1231
 
1232
-    $liste=$objmodelexport->liste_modeles($db);
1233
-    $listeall=$liste;
1234
-    foreach($listeall as $key => $val)
1232
+    $liste = $objmodelexport->liste_modeles($db);
1233
+    $listeall = $liste;
1234
+    foreach ($listeall as $key => $val)
1235 1235
     {
1236
-    	if (preg_match('/__\(Disabled\)__/',$listeall[$key]))
1236
+    	if (preg_match('/__\(Disabled\)__/', $listeall[$key]))
1237 1237
     	{
1238
-    		$listeall[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$listeall[$key]);
1238
+    		$listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]);
1239 1239
     		unset($liste[$key]);
1240 1240
     	}
1241 1241
 
1242 1242
         print '<tr class="oddeven">';
1243
-        print '<td width="16">'.img_picto_common($key,$objmodelexport->getPictoForKey($key)).' ';
1244
-	    $text=$objmodelexport->getDriverDescForKey($key);
1245
-	    $label=$listeall[$key];
1246
-	    print $form->textwithpicto($label,$text).'</td>';
1243
+        print '<td width="16">'.img_picto_common($key, $objmodelexport->getPictoForKey($key)).' ';
1244
+	    $text = $objmodelexport->getDriverDescForKey($key);
1245
+	    $label = $listeall[$key];
1246
+	    print $form->textwithpicto($label, $text).'</td>';
1247 1247
         print '<td>'.$objmodelexport->getLibLabelForKey($key).'</td>';
1248 1248
         print '<td align="right">'.$objmodelexport->getLibVersionForKey($key).'</td>';
1249 1249
         print '</tr>'."\n";
@@ -1266,11 +1266,11 @@  discard block
 block discarded – undo
1266 1266
 
1267 1267
 	print '<div class="fichecenter"><div class="fichehalfleft">';
1268 1268
 
1269
-    if (! is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
1269
+    if (!is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
1270 1270
 
1271 1271
     // Affiche liste des documents
1272 1272
     // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste
1273
-    print $formfile->showdocuments('export','',$upload_dir,$_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport,$liste,1,(! empty($_POST['model'])?$_POST['model']:'csv'),1,1);
1273
+    print $formfile->showdocuments('export', '', $upload_dir, $_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport, $liste, 1, (!empty($_POST['model']) ? $_POST['model'] : 'csv'), 1, 1);
1274 1274
 
1275 1275
     print '</div><div class="fichehalfright"><div class="ficheaddleft">';
1276 1276
 
@@ -1281,7 +1281,7 @@  discard block
 block discarded – undo
1281 1281
 
1282 1282
 $db->close();
1283 1283
 
1284
-exit;	// don't know why but apache hangs with php 5.3.10-1ubuntu3.12 and apache 2.2.2 if i remove this exit or replace with return
1284
+exit; // don't know why but apache hangs with php 5.3.10-1ubuntu3.12 and apache 2.2.2 if i remove this exit or replace with return
1285 1285
 
1286 1286
 
1287 1287
 /**
@@ -1291,18 +1291,18 @@  discard block
 block discarded – undo
1291 1291
  * 	@param	string	$sqlmaxforexport	SQL request to parse
1292 1292
  * 	@return	string						Table name of field
1293 1293
  */
1294
-function getablenamefromfield($code,$sqlmaxforexport)
1294
+function getablenamefromfield($code, $sqlmaxforexport)
1295 1295
 {
1296
-	$alias=preg_replace('/\.(.*)$/i','',$code);         // Keep only 'Alias' and remove '.Fieldname'
1297
-	$regexstring='/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i';
1296
+	$alias = preg_replace('/\.(.*)$/i', '', $code); // Keep only 'Alias' and remove '.Fieldname'
1297
+	$regexstring = '/([a-zA-Z_]+) as '.preg_quote($alias).'[, \)]/i';
1298 1298
 
1299
-	$newsql=$sqlmaxforexport;
1300
-	$newsql=preg_replace('/^(.*) FROM /i','',$newsql);  // Remove part before the FROM
1301
-	$newsql=preg_replace('/WHERE (.*)$/i','',$newsql);	// Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE
1299
+	$newsql = $sqlmaxforexport;
1300
+	$newsql = preg_replace('/^(.*) FROM /i', '', $newsql); // Remove part before the FROM
1301
+	$newsql = preg_replace('/WHERE (.*)$/i', '', $newsql); // Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE
1302 1302
 
1303
-	if (preg_match($regexstring,$newsql,$reg))
1303
+	if (preg_match($regexstring, $newsql, $reg))
1304 1304
 	{
1305
-		return $reg[1];   // The tablename
1305
+		return $reg[1]; // The tablename
1306 1306
 	}
1307 1307
 	else return '';
1308 1308
 }
Please login to merge, or discard this patch.
Braces   +111 added lines, -69 removed lines patch added patch discarded remove patch
@@ -153,9 +153,11 @@  discard block
 block discarded – undo
153 153
  * Actions
154 154
  */
155 155
 
156
-if ($action=='selectfield')     // Selection of field at step 2
156
+if ($action=='selectfield') {
157
+    // Selection of field at step 2
157 158
 {
158 159
 	$fieldsarray=$objexport->array_export_fields[0];
160
+}
159 161
 	$fieldsentitiesarray=$objexport->array_export_entities[0];
160 162
     $fieldsdependenciesarray=$objexport->array_export_dependencies[0];
161 163
 
@@ -163,13 +165,15 @@  discard block
 block discarded – undo
163 165
     {
164 166
 		foreach($fieldsarray as $key=>$val)
165 167
 		{
166
-			if (! empty($array_selected[$key])) continue;		// If already selected, check next
168
+			if (! empty($array_selected[$key])) {
169
+			    continue;
170
+			}
171
+			// If already selected, check next
167 172
 			$array_selected[$key]=count($array_selected)+1;
168 173
 		    //print_r($array_selected);
169 174
 		    $_SESSION["export_selected_fields"]=$array_selected;
170 175
 		}
171
-    }
172
-    else
176
+    } else
173 177
     {
174 178
         $warnings=array();
175 179
 
@@ -183,15 +187,20 @@  discard block
 block discarded – undo
183 187
         {
184 188
             // We found a dependency on the type of field
185 189
             $tmp=$fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid'))
186
-            if (is_array($tmp)) $listofdependencies=$tmp;
187
-            else $listofdependencies=array($tmp);
188
-        }
189
-        else if (! empty($field) && ! empty($fieldsdependenciesarray[$field]))
190
+            if (is_array($tmp)) {
191
+                $listofdependencies=$tmp;
192
+            } else {
193
+                $listofdependencies=array($tmp);
194
+            }
195
+        } else if (! empty($field) && ! empty($fieldsdependenciesarray[$field]))
190 196
         {
191 197
             // We found a dependency on a dedicated field
192 198
             $tmp=$fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid'))
193
-            if (is_array($tmp)) $listofdependencies=$tmp;
194
-            else $listofdependencies=array($tmp);
199
+            if (is_array($tmp)) {
200
+                $listofdependencies=$tmp;
201
+            } else {
202
+                $listofdependencies=array($tmp);
203
+            }
195 204
         }
196 205
 
197 206
         if (count($listofdependencies))
@@ -217,8 +226,7 @@  discard block
 block discarded – undo
217 226
     {
218 227
 		$array_selected=array();
219 228
 		$_SESSION["export_selected_fields"]=$array_selected;
220
-    }
221
-    else
229
+    } else
222 230
     {
223 231
 	    unset($array_selected[$_GET["field"]]);
224 232
 	    // Renumber fields of array_selected (from 1 to nb_elements)
@@ -238,8 +246,12 @@  discard block
 block discarded – undo
238 246
 if ($action=='downfield' || $action=='upfield')
239 247
 {
240 248
     $pos=$array_selected[$_GET["field"]];
241
-    if ($action=='downfield') $newpos=$pos+1;
242
-    if ($action=='upfield') $newpos=$pos-1;
249
+    if ($action=='downfield') {
250
+        $newpos=$pos+1;
251
+    }
252
+    if ($action=='upfield') {
253
+        $newpos=$pos-1;
254
+    }
243 255
     // Recherche code avec qui switcher
244 256
     $newcode="";
245 257
     foreach($array_selected as $code=>$value)
@@ -251,9 +263,11 @@  discard block
 block discarded – undo
251 263
         }
252 264
     }
253 265
     //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)");
254
-    if ($newcode)   // Si newcode trouve (protection contre resoumission de page)
266
+    if ($newcode) {
267
+        // Si newcode trouve (protection contre resoumission de page)
255 268
     {
256 269
         $array_selected[$_GET["field"]]=$newpos;
270
+    }
257 271
         $array_selected[$newcode]=$pos;
258 272
         $_SESSION["export_selected_fields"]=$array_selected;
259 273
     }
@@ -282,8 +296,7 @@  discard block
 block discarded – undo
282 296
 	{
283 297
 		setEventMessages($objexport->error, $objexport->errors, 'errors');
284 298
 		$sqlusedforexport=$objexport->sqlusedforexport;
285
-	}
286
-	else
299
+	} else
287 300
 	{
288 301
 		setEventMessages($langs->trans("FileSuccessfullyBuilt"), null, 'mesgs');
289 302
 	    $sqlusedforexport=$objexport->sqlusedforexport;
@@ -296,8 +309,11 @@  discard block
 block discarded – undo
296 309
 	$file = $upload_dir . "/" . GETPOST('file');	// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
297 310
 
298 311
 	$ret=dol_delete_file($file);
299
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
300
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
312
+	if ($ret) {
313
+	    setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
314
+	} else {
315
+	    setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
316
+	}
301 317
 	header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport);
302 318
 	exit;
303 319
 }
@@ -322,7 +338,9 @@  discard block
 block discarded – undo
322 338
 		$hexa='';
323 339
 		foreach($array_selected as $key=>$val)
324 340
 		{
325
-			if ($hexa) $hexa.=',';
341
+			if ($hexa) {
342
+			    $hexa.=',';
343
+			}
326 344
 			$hexa.=$key;
327 345
 		}
328 346
 
@@ -331,7 +349,9 @@  discard block
 block discarded – undo
331 349
 		{
332 350
 			foreach($array_filtervalue as $key=>$val)
333 351
 			{
334
-				if ($hexafiltervalue) $hexafiltervalue.=',';
352
+				if ($hexafiltervalue) {
353
+				    $hexafiltervalue.=',';
354
+				}
335 355
 				$hexafiltervalue.=$key.'='.$val;
336 356
 			}
337 357
 		}
@@ -345,17 +365,16 @@  discard block
 block discarded – undo
345 365
 		if ($result >= 0)
346 366
 		{
347 367
 			setEventMessages($langs->trans("ExportModelSaved",$objexport->model_name), null, 'mesgs');
348
-		}
349
-		else
368
+		} else
350 369
 		{
351 370
 			$langs->load("errors");
352
-			if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS')
353
-				setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors');
354
-			else
355
-				setEventMessages($objexport->error, $objexport->errors, 'errors');
371
+			if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
372
+							setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors');
373
+			} else {
374
+							setEventMessages($objexport->error, $objexport->errors, 'errors');
375
+			}
356 376
 		}
357
-	}
358
-	else
377
+	} else
359 378
 	{
360 379
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportModelName")), null, 'errors');
361 380
 	}
@@ -401,13 +420,18 @@  discard block
 block discarded – undo
401 420
 	if (is_array($objexport->array_export_TypeFields[0]))
402 421
 	{
403 422
 		$_SESSION["export_filtered_fields"]=array();
404
-		foreach($objexport->array_export_TypeFields[0] as $code => $type)	// $code: s.fieldname $value: Text|Boolean|List:ccc
423
+		foreach($objexport->array_export_TypeFields[0] as $code => $type) {
424
+		    // $code: s.fieldname $value: Text|Boolean|List:ccc
405 425
 		{
406 426
 			$newcode=(string) preg_replace('/\./','_',$code);
427
+		}
407 428
 			//print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n<br>";
408 429
 			$filterqualified=1;
409
-			if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') $filterqualified=0;
410
-			elseif (preg_match('/^List/',$type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) $filterqualified=0;
430
+			if (! isset($_POST[$newcode]) || $_POST[$newcode] == '') {
431
+			    $filterqualified=0;
432
+			} elseif (preg_match('/^List/',$type) && (is_numeric($_POST[$newcode]) && $_POST[$newcode] <= 0)) {
433
+			    $filterqualified=0;
434
+			}
411 435
 			if ($filterqualified)
412 436
 			{
413 437
 				//print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n";
@@ -477,15 +501,13 @@  discard block
 block discarded – undo
477 501
             if ($objexport->array_export_perms[$key])
478 502
             {
479 503
             	print '<a href="'.DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$objexport->array_export_code[$key].'">'.img_picto($langs->trans("NewExport"),'filenew').'</a>';
480
-            }
481
-            else
504
+            } else
482 505
             {
483 506
             	print $langs->trans("NotEnoughPermissions");
484 507
             }
485 508
            	print '</td></tr>';
486 509
         }
487
-    }
488
-    else
510
+    } else
489 511
     {
490 512
         print '<tr><td '.$bc[false].' colspan="3">'.$langs->trans("NoExportableData").'</td></tr>';
491 513
     }
@@ -553,8 +575,11 @@  discard block
 block discarded – undo
553 575
     print '<input type="hidden" name="datatoexport" value="'.$datatoexport.'">';
554 576
     print '<table><tr><td colspan="2">';
555 577
     print $langs->trans("SelectExportFields").' ';
556
-    if(empty($conf->global->EXPORTS_SHARE_MODELS))$htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1,$user->id);
557
-	else $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1);
578
+    if(empty($conf->global->EXPORTS_SHARE_MODELS)) {
579
+        $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1,$user->id);
580
+    } else {
581
+	    $htmlother->select_export_model($exportmodelid,'exportmodelid',$datatoexport,1);
582
+	}
558 583
     print ' ';
559 584
     print '<input type="submit" class="button" value="'.$langs->trans("Select").'">';
560 585
     print '</td></tr></table>';
@@ -618,8 +643,7 @@  discard block
 block discarded – undo
618 643
         if (! empty($objexport->array_export_special[0][$code]))
619 644
         {
620 645
             $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
621
-        }
622
-        else
646
+        } else
623 647
         {
624 648
             $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
625 649
         }
@@ -642,8 +666,7 @@  discard block
 block discarded – undo
642 666
             print $form->textwithpicto($text,$htmltext);
643 667
 			//print ' ('.$code.')';
644 668
             print '</td>';
645
-        }
646
-        else
669
+        } else
647 670
         {
648 671
         	// Fields not selected
649 672
             print '<td>';
@@ -672,13 +695,11 @@  discard block
 block discarded – undo
672 695
 		if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0]))
673 696
 		{
674 697
 			print '<a class="butAction" href="export.php?step=3&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
675
-		}
676
-		else
698
+		} else
677 699
 		{
678 700
 			print '<a class="butAction" href="export.php?step=4&datatoexport='.$datatoexport.'">'.$langs->trans("NextStep").'</a>';
679 701
 		}
680
-	}
681
-	else
702
+	} else
682 703
 	{
683 704
 		print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SelectAtLeastOneField")).'">'.$langs->trans("NextStep").'</a>';
684 705
 	}
@@ -688,10 +709,12 @@  discard block
 block discarded – undo
688 709
 
689 710
 if ($step == 3 && $datatoexport)
690 711
 {
691
-    if (count($array_selected) < 1)      // This occurs when going back to page after sessecion expired
712
+    if (count($array_selected) < 1) {
713
+        // This occurs when going back to page after sessecion expired
692 714
     {
693 715
         // Switch to step 2
694 716
         header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
717
+    }
695 718
         exit;
696 719
     }
697 720
 
@@ -809,8 +832,7 @@  discard block
 block discarded – undo
809 832
 			if (! empty($objexport->array_export_special[0][$code]))
810 833
 		{
811 834
 		    $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
812
-		}
813
-		else
835
+		} else
814 836
 		{
815 837
 		    $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
816 838
 		}
@@ -829,15 +851,18 @@  discard block
 block discarded – undo
829 851
 
830 852
 		// Filter value
831 853
 		print '<td>';
832
-		if (! empty($Typefieldsarray[$code]))	// Example: Text, List:c_country:label:rowid, Number, Boolean
854
+		if (! empty($Typefieldsarray[$code])) {
855
+		    // Example: Text, List:c_country:label:rowid, Number, Boolean
833 856
 		{
834 857
 			$szInfoFiltre=$objexport->genDocFilter($Typefieldsarray[$code]);
835
-			if ($szInfoFiltre)	// Is there an info help for this filter ?
858
+		}
859
+			if ($szInfoFiltre) {
860
+			    // Is there an info help for this filter ?
836 861
 			{
837 862
 				$tmp=$objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
838
-				print $form->textwithpicto($tmp, $szInfoFiltre);
839 863
 			}
840
-			else
864
+				print $form->textwithpicto($tmp, $szInfoFiltre);
865
+			} else
841 866
 			{
842 867
 				print $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter);
843 868
 			}
@@ -862,10 +887,12 @@  discard block
 block discarded – undo
862 887
 
863 888
 if ($step == 4 && $datatoexport)
864 889
 {
865
-    if (count($array_selected) < 1)     // This occurs when going back to page after sessecion expired
890
+    if (count($array_selected) < 1) {
891
+        // This occurs when going back to page after sessecion expired
866 892
     {
867 893
         // Switch to step 2
868 894
         header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
895
+    }
869 896
         exit;
870 897
     }
871 898
 
@@ -945,8 +972,11 @@  discard block
 block discarded – undo
945 972
     			if (isset($objexport->array_export_fields[0][$code]))
946 973
     			{
947 974
     				$list.=($list?', ':'');
948
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
949
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
975
+    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) {
976
+    				    $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
977
+    				} else {
978
+    				    $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
979
+    				}
950 980
     			}
951 981
     		}
952 982
     	}
@@ -1001,8 +1031,7 @@  discard block
 block discarded – undo
1001 1031
         if (! empty($objexport->array_export_special[0][$code]))
1002 1032
         {
1003 1033
             $htmltext.='<b>'.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." :</b> ".$objexport->array_export_special[0][$code]."<br>";
1004
-        }
1005
-        else
1034
+        } else
1006 1035
         {
1007 1036
             $htmltext.='<b>'.$langs->trans("Table")." -> ".$langs->trans("Field").":</b> ".$tablename." -> ".preg_replace('/^.*\./','',$code)."<br>";
1008 1037
         }
@@ -1023,8 +1052,12 @@  discard block
 block discarded – undo
1023 1052
         print '<td align="right" width="100">';
1024 1053
         print $value.' ';
1025 1054
         print '</td><td align="center" width="20">';
1026
-        if ($value < count($array_selected)) print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=downfield&field='.$code.'">'.img_down().'</a>';
1027
-        if ($value > 1) print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=upfield&field='.$code.'">'.img_up().'</a>';
1055
+        if ($value < count($array_selected)) {
1056
+            print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=downfield&field='.$code.'">'.img_down().'</a>';
1057
+        }
1058
+        if ($value > 1) {
1059
+            print '<a href="'.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport.'&action=upfield&field='.$code.'">'.img_up().'</a>';
1060
+        }
1028 1061
         print '</td>';
1029 1062
 
1030 1063
         //print '<td>&nbsp;</td>';
@@ -1079,7 +1112,9 @@  discard block
 block discarded – undo
1079 1112
     	$sql = "SELECT rowid, label";
1080 1113
 		$sql.= " FROM ".MAIN_DB_PREFIX."export_model";
1081 1114
 		$sql.= " WHERE type = '".$datatoexport."'";
1082
-		if(empty($conf->global->EXPORTS_SHARE_MODELS))$sql.=" AND fk_user=".$user->id;
1115
+		if(empty($conf->global->EXPORTS_SHARE_MODELS)) {
1116
+		    $sql.=" AND fk_user=".$user->id;
1117
+		}
1083 1118
 		$sql.= " ORDER BY rowid";
1084 1119
 		$resql = $db->query($sql);
1085 1120
 		if ($resql)
@@ -1098,8 +1133,7 @@  discard block
 block discarded – undo
1098 1133
 				print '</tr>';
1099 1134
 				$i++;
1100 1135
 			}
1101
-		}
1102
-		else {
1136
+		} else {
1103 1137
 			dol_print_error($this->db);
1104 1138
 		}
1105 1139
 
@@ -1110,10 +1144,12 @@  discard block
 block discarded – undo
1110 1144
 
1111 1145
 if ($step == 5 && $datatoexport)
1112 1146
 {
1113
-    if (count($array_selected) < 1)      // This occurs when going back to page after sessecion expired
1147
+    if (count($array_selected) < 1) {
1148
+        // This occurs when going back to page after sessecion expired
1114 1149
     {
1115 1150
         // Switch to step 2
1116 1151
         header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport);
1152
+    }
1117 1153
         exit;
1118 1154
     }
1119 1155
 
@@ -1205,8 +1241,11 @@  discard block
 block discarded – undo
1205 1241
     			if (isset($objexport->array_export_fields[0][$code]))
1206 1242
     			{
1207 1243
     				$list.=($list?', ':'');
1208
-    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
1209
-    				else $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
1244
+    				if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/',$array_filtervalue[$code])) {
1245
+    				    $list.=$langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'');
1246
+    				} else {
1247
+    				    $list.=$langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code])?$array_filtervalue[$code]:'')."'";
1248
+    				}
1210 1249
     			}
1211 1250
     		}
1212 1251
     	}
@@ -1266,7 +1305,9 @@  discard block
 block discarded – undo
1266 1305
 
1267 1306
 	print '<div class="fichecenter"><div class="fichehalfleft">';
1268 1307
 
1269
-    if (! is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp);
1308
+    if (! is_dir($conf->export->dir_temp)) {
1309
+        dol_mkdir($conf->export->dir_temp);
1310
+    }
1270 1311
 
1271 1312
     // Affiche liste des documents
1272 1313
     // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste
@@ -1303,6 +1344,7 @@  discard block
 block discarded – undo
1303 1344
 	if (preg_match($regexstring,$newsql,$reg))
1304 1345
 	{
1305 1346
 		return $reg[1];   // The tablename
1347
+	} else {
1348
+	    return '';
1349
+	}
1306 1350
 	}
1307
-	else return '';
1308
-}
Please login to merge, or discard this patch.
dolibarr/htdocs/exports/index.php 3 patches
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -91,15 +91,15 @@  discard block
 block discarded – undo
91 91
 print '<div class="center">';
92 92
 if (count($export->array_export_code))
93 93
 {
94
-	if ($user->rights->export->creer)
95
-	{
96
-		print '<a class="butActionNew" href="'.DOL_URL_ROOT.'/exports/export.php?leftmenu=export">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
97
-	}
98
-	else
99
-	{
100
-		print '<a class="butActionNewRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
101
-	}
102
-	/*
94
+    if ($user->rights->export->creer)
95
+    {
96
+        print '<a class="butActionNew" href="'.DOL_URL_ROOT.'/exports/export.php?leftmenu=export">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
97
+    }
98
+    else
99
+    {
100
+        print '<a class="butActionNewRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
101
+    }
102
+    /*
103 103
 	 print '<form action="'.DOL_URL_ROOT.'/exports/export.php?leftmenu=export"><input type="submit" class="button" value="'.$langs->trans("NewExport").'"';
104 104
 	print ($user->rights->export->creer?'':' disabled');
105 105
 	print '><div class="center"></div></form>';
@@ -127,17 +127,17 @@  discard block
 block discarded – undo
127 127
 {
128 128
     if (preg_match('/__\(Disabled\)__/',$liste[$key]))
129 129
     {
130
-    	$liste[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$liste[$key]);
130
+        $liste[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$liste[$key]);
131 131
     }
132 132
 
133
-	print '<tr class="oddeven">';
134
-	print '<td width="16">'.img_picto_common($model->getDriverLabelForKey($key),$model->getPictoForKey($key)).'</td>';
135
-	$text=$model->getDriverDescForKey($key);
136
-	$label=$liste[$key];
137
-	print '<td>'.$form->textwithpicto($label,$text).'</td>';
138
-	print '<td>'.$model->getLibLabelForKey($key).'</td>';
139
-	print '<td class="nowrap" align="right">'.$model->getLibVersionForKey($key).'</td>';
140
-	print '</tr>';
133
+    print '<tr class="oddeven">';
134
+    print '<td width="16">'.img_picto_common($model->getDriverLabelForKey($key),$model->getPictoForKey($key)).'</td>';
135
+    $text=$model->getDriverDescForKey($key);
136
+    $label=$liste[$key];
137
+    print '<td>'.$form->textwithpicto($label,$text).'</td>';
138
+    print '<td>'.$model->getLibLabelForKey($key).'</td>';
139
+    print '<td class="nowrap" align="right">'.$model->getLibVersionForKey($key).'</td>';
140
+    print '</tr>';
141 141
 }
142 142
 
143 143
 print '</table>';
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -28,18 +28,18 @@  discard block
 block discarded – undo
28 28
 $langs->load("exports");
29 29
 
30 30
 // Security check
31
-$result=restrictedArea($user,'export');
31
+$result = restrictedArea($user, 'export');
32 32
 
33
-$export=new Export($db);
33
+$export = new Export($db);
34 34
 $export->load_arrays($user);
35 35
 
36 36
 /*
37 37
  * View
38 38
  */
39 39
 
40
-$form=new Form($db);
40
+$form = new Form($db);
41 41
 
42
-llxHeader('',$langs->trans("ExportsArea"),'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
42
+llxHeader('', $langs->trans("ExportsArea"), 'EN:Module_Exports_En|FR:Module_Exports|ES:M&oacute;dulo_Exportaciones');
43 43
 
44 44
 print load_fiche_titre($langs->trans("ExportsArea"));
45 45
 
@@ -120,21 +120,21 @@  discard block
 block discarded – undo
120 120
 print '</tr>';
121 121
 
122 122
 include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php';
123
-$model=new ModeleExports($db);
124
-$liste=$model->liste_modeles($db);    // This is not a static method for exports because method load non static properties
123
+$model = new ModeleExports($db);
124
+$liste = $model->liste_modeles($db); // This is not a static method for exports because method load non static properties
125 125
 
126
-foreach($liste as $key => $val)
126
+foreach ($liste as $key => $val)
127 127
 {
128
-    if (preg_match('/__\(Disabled\)__/',$liste[$key]))
128
+    if (preg_match('/__\(Disabled\)__/', $liste[$key]))
129 129
     {
130
-    	$liste[$key]=preg_replace('/__\(Disabled\)__/','('.$langs->transnoentitiesnoconv("Disabled").')',$liste[$key]);
130
+    	$liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]);
131 131
     }
132 132
 
133 133
 	print '<tr class="oddeven">';
134
-	print '<td width="16">'.img_picto_common($model->getDriverLabelForKey($key),$model->getPictoForKey($key)).'</td>';
135
-	$text=$model->getDriverDescForKey($key);
136
-	$label=$liste[$key];
137
-	print '<td>'.$form->textwithpicto($label,$text).'</td>';
134
+	print '<td width="16">'.img_picto_common($model->getDriverLabelForKey($key), $model->getPictoForKey($key)).'</td>';
135
+	$text = $model->getDriverDescForKey($key);
136
+	$label = $liste[$key];
137
+	print '<td>'.$form->textwithpicto($label, $text).'</td>';
138 138
 	print '<td>'.$model->getLibLabelForKey($key).'</td>';
139 139
 	print '<td class="nowrap" align="right">'.$model->getLibVersionForKey($key).'</td>';
140 140
 	print '</tr>';
Please login to merge, or discard this patch.
Braces   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -94,8 +94,7 @@
 block discarded – undo
94 94
 	if ($user->rights->export->creer)
95 95
 	{
96 96
 		print '<a class="butActionNew" href="'.DOL_URL_ROOT.'/exports/export.php?leftmenu=export">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
97
-	}
98
-	else
97
+	} else
99 98
 	{
100 99
 		print '<a class="butActionNewRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("NewExport").'<span class="fa fa-plus-circle valignmiddle"></span></a>';
101 100
 	}
Please login to merge, or discard this patch.
dolibarr/htdocs/margin/productMargins.php 3 patches
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -57,24 +57,24 @@  discard block
 block discarded – undo
57 57
 $pagenext = $page + 1;
58 58
 if (! $sortfield)
59 59
 {
60
-	if ($id > 0)
61
-	{
62
-		$sortfield="f.datef";
63
-		$sortorder="DESC";
64
-	}
65
-	else
66
-	{
67
-	    $sortfield="p.ref";
68
-	    $sortorder="ASC";
69
-	}
60
+    if ($id > 0)
61
+    {
62
+        $sortfield="f.datef";
63
+        $sortorder="DESC";
64
+    }
65
+    else
66
+    {
67
+        $sortfield="p.ref";
68
+        $sortorder="ASC";
69
+    }
70 70
 }
71 71
 
72 72
 $startdate=$enddate='';
73 73
 
74 74
 if (!empty($_POST['startdatemonth']))
75
-  $startdate  = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
75
+    $startdate  = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
76 76
 if (!empty($_POST['enddatemonth']))
77
-  $enddate  = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
77
+    $enddate  = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
78 78
 
79 79
 
80 80
 /*
@@ -104,19 +104,19 @@  discard block
 block discarded – undo
104 104
 
105 105
 if ($id > 0) {
106 106
 
107
-  print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
108
-  print '<td class="maxwidthonsmartpone" colspan="4">';
109
-  print $form->select_produits($id,'id','',20,0,1,2,'',1, array(), 0, 'All');
110
-  print '</td></tr>';
107
+    print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
108
+    print '<td class="maxwidthonsmartpone" colspan="4">';
109
+    print $form->select_produits($id,'id','',20,0,1,2,'',1, array(), 0, 'All');
110
+    print '</td></tr>';
111 111
 
112
-  if (! $sortorder) $sortorder="DESC";
113
-  if (! $sortfield) $sortfield="f.datef";
112
+    if (! $sortorder) $sortorder="DESC";
113
+    if (! $sortfield) $sortfield="f.datef";
114 114
 }
115 115
 else {
116
-	print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
117
-	print '<td class="maxwidthonsmartphone" colspan="4">';
118
-	print $form->select_produits('','id','',20,0,1,2,'',1, array(), 0, 'All');
119
-	print '</td></tr>';
116
+    print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
117
+    print '<td class="maxwidthonsmartphone" colspan="4">';
118
+    print $form->select_produits('','id','',20,0,1,2,'',1, array(), 0, 'All');
119
+    print '</td></tr>';
120 120
 }
121 121
 
122 122
 // Categories
@@ -156,16 +156,16 @@  discard block
 block discarded – undo
156 156
 
157 157
 // Margin Rate
158 158
 if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
159
-	print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
160
-	print '<span id="marginRate"></span>'; // set by jquery (see below)
161
-	print '</td></tr>';
159
+    print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
160
+    print '<span id="marginRate"></span>'; // set by jquery (see below)
161
+    print '</td></tr>';
162 162
 }
163 163
 
164 164
 // Mark Rate
165 165
 if (! empty($conf->global->DISPLAY_MARK_RATES)) {
166
-	print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
167
-	print '<span id="markRate"></span>'; // set by jquery (see below)
168
-	print '</td></tr>';
166
+    print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
167
+    print '<span id="markRate"></span>'; // set by jquery (see below)
168
+    print '</td></tr>';
169 169
 }
170 170
 
171 171
 print "</table>";
@@ -186,24 +186,24 @@  discard block
 block discarded – undo
186 186
 $sql.= ", ".MAIN_DB_PREFIX."facturedet as d";
187 187
 $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product";
188 188
 if (! empty($TSelectedCats)) {
189
-	$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
189
+    $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
190 190
 }
191 191
 $sql.= " WHERE f.fk_soc = s.rowid";
192 192
 $sql.= ' AND f.entity IN ('.getEntity('invoice').')';
193 193
 $sql.= " AND f.fk_statut > 0";
194 194
 $sql.= " AND d.fk_facture = f.rowid";
195 195
 if ($id > 0)
196
-	$sql.= " AND d.fk_product =".$id;
196
+    $sql.= " AND d.fk_product =".$id;
197 197
 if (! empty($TSelectedCats)) {
198
-	$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats) . ')';
198
+    $sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats) . ')';
199 199
 }
200 200
 if (!empty($startdate))
201
-  $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
201
+    $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
202 202
 if (!empty($enddate))
203
-  $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
203
+    $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
204 204
 $sql .= " AND d.buy_price_ht IS NOT NULL";
205 205
 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
206
-	$sql .= " AND d.buy_price_ht <> 0";
206
+    $sql .= " AND d.buy_price_ht <> 0";
207 207
 if ($id > 0) $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
208 208
 else $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
209 209
 $sql.=$db->order($sortfield,$sortorder);
@@ -214,137 +214,137 @@  discard block
 block discarded – undo
214 214
 $result = $db->query($sql);
215 215
 if ($result)
216 216
 {
217
-	$num = $db->num_rows($result);
217
+    $num = $db->num_rows($result);
218 218
 
219
-	print '<br>';
220
-	print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
219
+    print '<br>';
220
+    print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
221 221
 
222
-	//var_dump($conf->global->MARGIN_TYPE);
223
-	if ($conf->global->MARGIN_TYPE == "1")
224
-	    $labelcostprice='BuyingPrice';
225
-	else   // value is 'costprice' or 'pmp'
226
-	    $labelcostprice='CostPrice';
222
+    //var_dump($conf->global->MARGIN_TYPE);
223
+    if ($conf->global->MARGIN_TYPE == "1")
224
+        $labelcostprice='BuyingPrice';
225
+    else   // value is 'costprice' or 'pmp'
226
+        $labelcostprice='CostPrice';
227 227
 
228
-	$moreforfilter='';
228
+    $moreforfilter='';
229 229
 
230
-	$i = 0;
230
+    $i = 0;
231 231
     print '<div class="div-table-responsive">';
232 232
     print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
233 233
 
234
-	print '<tr class="liste_titre">';
235
-	if ($id > 0) {
236
-  		print_liste_field_titre("Invoice",$_SERVER["PHP_SELF"],"f.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
237
-  		print_liste_field_titre("DateInvoice",$_SERVER["PHP_SELF"],"f.datef","","&amp;id=".$id,'align="center"',$sortfield,$sortorder);
238
-  	}
239
-  	else
240
-  	{
241
-  		print_liste_field_titre("ProductService",$_SERVER["PHP_SELF"],"p.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
242
-  	}
243
-	print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
244
-	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
245
-	print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
246
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-		print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
248
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-		print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
250
-	print "</tr>\n";
251
-
252
-	$cumul_achat = 0;
253
-	$cumul_vente = 0;
254
-	$rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
255
-
256
-	if ($num > 0)
257
-	{
258
-		while ($i < $num /*&& $i < $conf->liste_limit*/)
259
-		{
260
-			$objp = $db->fetch_object($result);
261
-			$pa = $objp->buying_price;
262
-			$pv = $objp->selling_price;
263
-			$marge = $objp->marge;
264
-
265
-			if ($marge < 0)
266
-			{
267
-				$marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
268
-				$markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
269
-			}
270
-			else
271
-			{
272
-				$marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
273
-				$markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
274
-			}
275
-
276
-			print '<tr class="oddeven">';
277
-			if ($id > 0) {
278
-				print '<td>';
279
-				$invoicestatic->id=$objp->facid;
280
-				$invoicestatic->ref=$objp->ref;
281
-				print $invoicestatic->getNomUrl(1);
282
-				print "</td>\n";
283
-				print "<td align=\"center\">";
284
-				print dol_print_date($db->jdate($objp->datef),'day')."</td>";
285
-			}
286
-			else {
287
-				print '<td>';
288
-				if ($objp->rowid > 0)
289
-				{
290
-    				$product_static->type=$objp->fk_product_type;
291
-    				$product_static->id=$objp->rowid;
292
-    				$product_static->ref=$objp->ref;
293
-    				$product_static->label=$objp->label;
294
-    				$product_static->entity=$objp->pentity;
295
-    				$text=$product_static->getNomUrl(1);
296
-    				print $text.= ' - '.$objp->label;
297
-				}
298
-				else
299
-				{
300
-				    print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
301
-				}
302
-				print "</td>\n";
303
-				//print "<td>".$product_static->getNomUrl(1)."</td>\n";
304
-			}
305
-			print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
306
-			print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
307
-			print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
308
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
309
-				print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
310
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
311
-				print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
312
-			print "</tr>\n";
313
-
314
-			$i++;
315
-			$cumul_achat += $objp->buying_price;
316
-			$cumul_vente += $objp->selling_price;
317
-		}
318
-	}
319
-
320
-	// affichage totaux marges
321
-
322
-	$totalMargin = $cumul_vente - $cumul_achat;
323
-
324
-	$marginRate = ($cumul_achat != 0)?(100 * $totalMargin / $cumul_achat):'';
325
-	$markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
326
-
327
-	print '<tr class="liste_total">';
328
-	if ($id > 0)
329
-		print '<td colspan=2>';
330
-	else
331
-		print '<td>';
332
-	print $langs->trans('TotalMargin')."</td>";
333
-	print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
334
-	print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
335
-	print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
336
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
337
-		print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
338
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
339
-		print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
340
-	print "</tr>\n";
341
-
342
-	print "</table>";
343
-	print '</div>';
234
+    print '<tr class="liste_titre">';
235
+    if ($id > 0) {
236
+            print_liste_field_titre("Invoice",$_SERVER["PHP_SELF"],"f.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
237
+            print_liste_field_titre("DateInvoice",$_SERVER["PHP_SELF"],"f.datef","","&amp;id=".$id,'align="center"',$sortfield,$sortorder);
238
+        }
239
+        else
240
+        {
241
+            print_liste_field_titre("ProductService",$_SERVER["PHP_SELF"],"p.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
242
+        }
243
+    print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
244
+    print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
245
+    print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
246
+    if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
+        print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
248
+    if (! empty($conf->global->DISPLAY_MARK_RATES))
249
+        print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
250
+    print "</tr>\n";
251
+
252
+    $cumul_achat = 0;
253
+    $cumul_vente = 0;
254
+    $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
255
+
256
+    if ($num > 0)
257
+    {
258
+        while ($i < $num /*&& $i < $conf->liste_limit*/)
259
+        {
260
+            $objp = $db->fetch_object($result);
261
+            $pa = $objp->buying_price;
262
+            $pv = $objp->selling_price;
263
+            $marge = $objp->marge;
264
+
265
+            if ($marge < 0)
266
+            {
267
+                $marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
268
+                $markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
269
+            }
270
+            else
271
+            {
272
+                $marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
273
+                $markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
274
+            }
275
+
276
+            print '<tr class="oddeven">';
277
+            if ($id > 0) {
278
+                print '<td>';
279
+                $invoicestatic->id=$objp->facid;
280
+                $invoicestatic->ref=$objp->ref;
281
+                print $invoicestatic->getNomUrl(1);
282
+                print "</td>\n";
283
+                print "<td align=\"center\">";
284
+                print dol_print_date($db->jdate($objp->datef),'day')."</td>";
285
+            }
286
+            else {
287
+                print '<td>';
288
+                if ($objp->rowid > 0)
289
+                {
290
+                    $product_static->type=$objp->fk_product_type;
291
+                    $product_static->id=$objp->rowid;
292
+                    $product_static->ref=$objp->ref;
293
+                    $product_static->label=$objp->label;
294
+                    $product_static->entity=$objp->pentity;
295
+                    $text=$product_static->getNomUrl(1);
296
+                    print $text.= ' - '.$objp->label;
297
+                }
298
+                else
299
+                {
300
+                    print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
301
+                }
302
+                print "</td>\n";
303
+                //print "<td>".$product_static->getNomUrl(1)."</td>\n";
304
+            }
305
+            print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
306
+            print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
307
+            print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
308
+            if (! empty($conf->global->DISPLAY_MARGIN_RATES))
309
+                print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
310
+            if (! empty($conf->global->DISPLAY_MARK_RATES))
311
+                print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
312
+            print "</tr>\n";
313
+
314
+            $i++;
315
+            $cumul_achat += $objp->buying_price;
316
+            $cumul_vente += $objp->selling_price;
317
+        }
318
+    }
319
+
320
+    // affichage totaux marges
321
+
322
+    $totalMargin = $cumul_vente - $cumul_achat;
323
+
324
+    $marginRate = ($cumul_achat != 0)?(100 * $totalMargin / $cumul_achat):'';
325
+    $markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
326
+
327
+    print '<tr class="liste_total">';
328
+    if ($id > 0)
329
+        print '<td colspan=2>';
330
+    else
331
+        print '<td>';
332
+    print $langs->trans('TotalMargin')."</td>";
333
+    print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
334
+    print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
335
+    print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
336
+    if (! empty($conf->global->DISPLAY_MARGIN_RATES))
337
+        print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
338
+    if (! empty($conf->global->DISPLAY_MARK_RATES))
339
+        print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
340
+    print "</tr>\n";
341
+
342
+    print "</table>";
343
+    print '</div>';
344 344
 }
345 345
 else
346 346
 {
347
-	dol_print_error($db);
347
+    dol_print_error($db);
348 348
 }
349 349
 $db->free($result);
350 350
 
Please login to merge, or discard this patch.
Spacing   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -33,48 +33,48 @@  discard block
 block discarded – undo
33 33
 
34 34
 $id = GETPOST('id', 'int');
35 35
 $ref = GETPOST('ref', 'alpha');
36
-$action=GETPOST('action','alpha');
37
-$confirm=GETPOST('confirm','alpha');
38
-$TSelectedCats=GETPOST('categories', 'array');
36
+$action = GETPOST('action', 'alpha');
37
+$confirm = GETPOST('confirm', 'alpha');
38
+$TSelectedCats = GETPOST('categories', 'array');
39 39
 
40 40
 // Security check
41
-$fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));
42
-$fieldtype = (! empty($ref) ? 'ref' : 'rowid');
43
-if (! empty($user->societe_id)) $socid=$user->societe_id;
44
-$result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype);
45
-$result=restrictedArea($user,'margins');
41
+$fieldvalue = (!empty($id) ? $id : (!empty($ref) ? $ref : ''));
42
+$fieldtype = (!empty($ref) ? 'ref' : 'rowid');
43
+if (!empty($user->societe_id)) $socid = $user->societe_id;
44
+$result = restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
45
+$result = restrictedArea($user, 'margins');
46 46
 
47 47
 $mesg = '';
48 48
 
49 49
 // Load variable for pagination
50
-$limit = GETPOST('limit','int')?GETPOST('limit','int'):$conf->liste_limit;
51
-$sortfield = GETPOST('sortfield','alpha');
52
-$sortorder = GETPOST('sortorder','alpha');
53
-$page = GETPOST('page','int');
50
+$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
51
+$sortfield = GETPOST('sortfield', 'alpha');
52
+$sortorder = GETPOST('sortorder', 'alpha');
53
+$page = GETPOST('page', 'int');
54 54
 if (empty($page) || $page == -1) { $page = 0; }     // If $page is not defined, or '' or -1
55 55
 $offset = $limit * $page;
56 56
 $pageprev = $page - 1;
57 57
 $pagenext = $page + 1;
58
-if (! $sortfield)
58
+if (!$sortfield)
59 59
 {
60 60
 	if ($id > 0)
61 61
 	{
62
-		$sortfield="f.datef";
63
-		$sortorder="DESC";
62
+		$sortfield = "f.datef";
63
+		$sortorder = "DESC";
64 64
 	}
65 65
 	else
66 66
 	{
67
-	    $sortfield="p.ref";
68
-	    $sortorder="ASC";
67
+	    $sortfield = "p.ref";
68
+	    $sortorder = "ASC";
69 69
 	}
70 70
 }
71 71
 
72
-$startdate=$enddate='';
72
+$startdate = $enddate = '';
73 73
 
74 74
 if (!empty($_POST['startdatemonth']))
75
-  $startdate  = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
75
+  $startdate = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
76 76
 if (!empty($_POST['enddatemonth']))
77
-  $enddate  = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
77
+  $enddate = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
78 78
 
79 79
 
80 80
 /*
@@ -82,19 +82,19 @@  discard block
 block discarded – undo
82 82
  */
83 83
 
84 84
 $product_static = new Product($db);
85
-$invoicestatic=new Facture($db);
85
+$invoicestatic = new Facture($db);
86 86
 
87 87
 $form = new Form($db);
88 88
 
89
-llxHeader('',$langs->trans("Margins").' - '.$langs->trans("Products"));
89
+llxHeader('', $langs->trans("Margins").' - '.$langs->trans("Products"));
90 90
 
91
-$text=$langs->trans("Margins");
91
+$text = $langs->trans("Margins");
92 92
 //print load_fiche_titre($text);
93 93
 
94 94
 // Show tabs
95
-$head=marges_prepare_head($user);
96
-$titre=$langs->trans("Margins");
97
-$picto='margin';
95
+$head = marges_prepare_head($user);
96
+$titre = $langs->trans("Margins");
97
+$picto = 'margin';
98 98
 
99 99
 print '<form method="post" name="sel" action="'.$_SERVER['PHP_SELF'].'">';
100 100
 
@@ -106,16 +106,16 @@  discard block
 block discarded – undo
106 106
 
107 107
   print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
108 108
   print '<td class="maxwidthonsmartpone" colspan="4">';
109
-  print $form->select_produits($id,'id','',20,0,1,2,'',1, array(), 0, 'All');
109
+  print $form->select_produits($id, 'id', '', 20, 0, 1, 2, '', 1, array(), 0, 'All');
110 110
   print '</td></tr>';
111 111
 
112
-  if (! $sortorder) $sortorder="DESC";
113
-  if (! $sortfield) $sortfield="f.datef";
112
+  if (!$sortorder) $sortorder = "DESC";
113
+  if (!$sortfield) $sortfield = "f.datef";
114 114
 }
115 115
 else {
116 116
 	print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
117 117
 	print '<td class="maxwidthonsmartphone" colspan="4">';
118
-	print $form->select_produits('','id','',20,0,1,2,'',1, array(), 0, 'All');
118
+	print $form->select_produits('', 'id', '', 20, 0, 1, 2, '', 1, array(), 0, 'All');
119 119
 	print '</td></tr>';
120 120
 }
121 121
 
@@ -155,14 +155,14 @@  discard block
 block discarded – undo
155 155
 print '</td></tr>';
156 156
 
157 157
 // Margin Rate
158
-if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
158
+if (!empty($conf->global->DISPLAY_MARGIN_RATES)) {
159 159
 	print '<tr><td>'.$langs->trans("MarginRate").'</td><td colspan="4">';
160 160
 	print '<span id="marginRate"></span>'; // set by jquery (see below)
161 161
 	print '</td></tr>';
162 162
 }
163 163
 
164 164
 // Mark Rate
165
-if (! empty($conf->global->DISPLAY_MARK_RATES)) {
165
+if (!empty($conf->global->DISPLAY_MARK_RATES)) {
166 166
 	print '<tr><td>'.$langs->trans("MarkRate").'</td><td colspan="4">';
167 167
 	print '<span id="markRate"></span>'; // set by jquery (see below)
168 168
 	print '</td></tr>';
@@ -175,38 +175,38 @@  discard block
 block discarded – undo
175 175
 print '</form>';
176 176
 
177 177
 $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
178
-if ($id > 0) $sql.= " d.fk_product,";
179
-if ($id > 0) $sql.= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
180
-$sql.= " SUM(d.total_ht) as selling_price,";
178
+if ($id > 0) $sql .= " d.fk_product,";
179
+if ($id > 0) $sql .= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
180
+$sql .= " SUM(d.total_ht) as selling_price,";
181 181
 // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
182
-$sql.= " SUM(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
183
-$sql.= " SUM(".$db->ifsql('d.total_ht < 0','-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))','d.total_ht - (d.buy_price_ht * d.qty)').") as marge";
184
-$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
185
-$sql.= ", ".MAIN_DB_PREFIX."facture as f";
186
-$sql.= ", ".MAIN_DB_PREFIX."facturedet as d";
187
-$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product";
188
-if (! empty($TSelectedCats)) {
189
-	$sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
182
+$sql .= " SUM(".$db->ifsql('d.total_ht < 0', 'd.qty * d.buy_price_ht * -1', 'd.qty * d.buy_price_ht').") as buying_price,";
183
+$sql .= " SUM(".$db->ifsql('d.total_ht < 0', '-1 * (abs(d.total_ht) - (d.buy_price_ht * d.qty))', 'd.total_ht - (d.buy_price_ht * d.qty)').") as marge";
184
+$sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
185
+$sql .= ", ".MAIN_DB_PREFIX."facture as f";
186
+$sql .= ", ".MAIN_DB_PREFIX."facturedet as d";
187
+$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product";
188
+if (!empty($TSelectedCats)) {
189
+	$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=p.rowid';
190 190
 }
191
-$sql.= " WHERE f.fk_soc = s.rowid";
192
-$sql.= ' AND f.entity IN ('.getEntity('invoice').')';
193
-$sql.= " AND f.fk_statut > 0";
194
-$sql.= " AND d.fk_facture = f.rowid";
191
+$sql .= " WHERE f.fk_soc = s.rowid";
192
+$sql .= ' AND f.entity IN ('.getEntity('invoice').')';
193
+$sql .= " AND f.fk_statut > 0";
194
+$sql .= " AND d.fk_facture = f.rowid";
195 195
 if ($id > 0)
196
-	$sql.= " AND d.fk_product =".$id;
197
-if (! empty($TSelectedCats)) {
198
-	$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats) . ')';
196
+	$sql .= " AND d.fk_product =".$id;
197
+if (!empty($TSelectedCats)) {
198
+	$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats).')';
199 199
 }
200 200
 if (!empty($startdate))
201
-  $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
201
+  $sql .= " AND f.datef >= '".$db->idate($startdate)."'";
202 202
 if (!empty($enddate))
203
-  $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
203
+  $sql .= " AND f.datef <= '".$db->idate($enddate)."'";
204 204
 $sql .= " AND d.buy_price_ht IS NOT NULL";
205 205
 if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
206 206
 	$sql .= " AND d.buy_price_ht <> 0";
207
-if ($id > 0) $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
208
-else $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
209
-$sql.=$db->order($sortfield,$sortorder);
207
+if ($id > 0) $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
208
+else $sql .= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
209
+$sql .= $db->order($sortfield, $sortorder);
210 210
 // TODO: calculate total to display then restore pagination
211 211
 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
212 212
 
@@ -221,37 +221,37 @@  discard block
 block discarded – undo
221 221
 
222 222
 	//var_dump($conf->global->MARGIN_TYPE);
223 223
 	if ($conf->global->MARGIN_TYPE == "1")
224
-	    $labelcostprice='BuyingPrice';
224
+	    $labelcostprice = 'BuyingPrice';
225 225
 	else   // value is 'costprice' or 'pmp'
226
-	    $labelcostprice='CostPrice';
226
+	    $labelcostprice = 'CostPrice';
227 227
 
228
-	$moreforfilter='';
228
+	$moreforfilter = '';
229 229
 
230 230
 	$i = 0;
231 231
     print '<div class="div-table-responsive">';
232
-    print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
232
+    print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
233 233
 
234 234
 	print '<tr class="liste_titre">';
235 235
 	if ($id > 0) {
236
-  		print_liste_field_titre("Invoice",$_SERVER["PHP_SELF"],"f.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
237
-  		print_liste_field_titre("DateInvoice",$_SERVER["PHP_SELF"],"f.datef","","&amp;id=".$id,'align="center"',$sortfield,$sortorder);
236
+  		print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder);
237
+  		print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&amp;id=".$id, 'align="center"', $sortfield, $sortorder);
238 238
   	}
239 239
   	else
240 240
   	{
241
-  		print_liste_field_titre("ProductService",$_SERVER["PHP_SELF"],"p.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
241
+  		print_liste_field_titre("ProductService", $_SERVER["PHP_SELF"], "p.ref", "", "&amp;id=".$id, '', $sortfield, $sortorder);
242 242
   	}
243
-	print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
244
-	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
245
-	print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
246
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-		print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
248
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-		print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
243
+	print_liste_field_titre("SellingPrice", $_SERVER["PHP_SELF"], "selling_price", "", "&amp;id=".$id, 'align="right"', $sortfield, $sortorder);
244
+	print_liste_field_titre($labelcostprice, $_SERVER["PHP_SELF"], "buying_price", "", "&amp;id=".$id, 'align="right"', $sortfield, $sortorder);
245
+	print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&amp;id=".$id, 'align="right"', $sortfield, $sortorder);
246
+	if (!empty($conf->global->DISPLAY_MARGIN_RATES))
247
+		print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, 'align="right"', $sortfield, $sortorder);
248
+	if (!empty($conf->global->DISPLAY_MARK_RATES))
249
+		print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$id, 'align="right"', $sortfield, $sortorder);
250 250
 	print "</tr>\n";
251 251
 
252 252
 	$cumul_achat = 0;
253 253
 	$cumul_vente = 0;
254
-	$rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT,$conf->global->MAIN_MAX_DECIMALS_TOT);
254
+	$rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT);
255 255
 
256 256
 	if ($num > 0)
257 257
 	{
@@ -264,36 +264,36 @@  discard block
 block discarded – undo
264 264
 
265 265
 			if ($marge < 0)
266 266
 			{
267
-				$marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
268
-				$markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
267
+				$marginRate = ($pa != 0) ?-1 * (100 * $marge / $pa) : '';
268
+				$markRate = ($pv != 0) ?-1 * (100 * $marge / $pv) : '';
269 269
 			}
270 270
 			else
271 271
 			{
272
-				$marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
273
-				$markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
272
+				$marginRate = ($pa != 0) ? (100 * $marge / $pa) : '';
273
+				$markRate = ($pv != 0) ? (100 * $marge / $pv) : '';
274 274
 			}
275 275
 
276 276
 			print '<tr class="oddeven">';
277 277
 			if ($id > 0) {
278 278
 				print '<td>';
279
-				$invoicestatic->id=$objp->facid;
280
-				$invoicestatic->ref=$objp->ref;
279
+				$invoicestatic->id = $objp->facid;
280
+				$invoicestatic->ref = $objp->ref;
281 281
 				print $invoicestatic->getNomUrl(1);
282 282
 				print "</td>\n";
283 283
 				print "<td align=\"center\">";
284
-				print dol_print_date($db->jdate($objp->datef),'day')."</td>";
284
+				print dol_print_date($db->jdate($objp->datef), 'day')."</td>";
285 285
 			}
286 286
 			else {
287 287
 				print '<td>';
288 288
 				if ($objp->rowid > 0)
289 289
 				{
290
-    				$product_static->type=$objp->fk_product_type;
291
-    				$product_static->id=$objp->rowid;
292
-    				$product_static->ref=$objp->ref;
293
-    				$product_static->label=$objp->label;
294
-    				$product_static->entity=$objp->pentity;
295
-    				$text=$product_static->getNomUrl(1);
296
-    				print $text.= ' - '.$objp->label;
290
+    				$product_static->type = $objp->fk_product_type;
291
+    				$product_static->id = $objp->rowid;
292
+    				$product_static->ref = $objp->ref;
293
+    				$product_static->label = $objp->label;
294
+    				$product_static->entity = $objp->pentity;
295
+    				$text = $product_static->getNomUrl(1);
296
+    				print $text .= ' - '.$objp->label;
297 297
 				}
298 298
 				else
299 299
 				{
@@ -305,10 +305,10 @@  discard block
 block discarded – undo
305 305
 			print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
306 306
 			print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
307 307
 			print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
308
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
309
-				print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
310
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
311
-				print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
308
+			if (!empty($conf->global->DISPLAY_MARGIN_RATES))
309
+				print "<td align=\"right\">".(($marginRate === '') ? 'n/a' : price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
310
+			if (!empty($conf->global->DISPLAY_MARK_RATES))
311
+				print "<td align=\"right\">".(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
312 312
 			print "</tr>\n";
313 313
 
314 314
 			$i++;
@@ -321,8 +321,8 @@  discard block
 block discarded – undo
321 321
 
322 322
 	$totalMargin = $cumul_vente - $cumul_achat;
323 323
 
324
-	$marginRate = ($cumul_achat != 0)?(100 * $totalMargin / $cumul_achat):'';
325
-	$markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
324
+	$marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : '';
325
+	$markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : '';
326 326
 
327 327
 	print '<tr class="liste_total">';
328 328
 	if ($id > 0)
@@ -333,10 +333,10 @@  discard block
 block discarded – undo
333 333
 	print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
334 334
 	print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
335 335
 	print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
336
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
337
-		print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
338
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
339
-		print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
336
+	if (!empty($conf->global->DISPLAY_MARGIN_RATES))
337
+		print "<td align=\"right\">".(($marginRate === '') ? 'n/a' : price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
338
+	if (!empty($conf->global->DISPLAY_MARK_RATES))
339
+		print "<td align=\"right\">".(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
340 340
 	print "</tr>\n";
341 341
 
342 342
 	print "</table>";
@@ -358,8 +358,8 @@  discard block
 block discarded – undo
358 358
   });
359 359
 
360 360
   $("#totalMargin").html("'.price($totalMargin, null, null, null, null, $rounding).'");
361
-  $("#marginRate").html("'.(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%").'");
362
-  $("#markRate").html("'.(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%").'");
361
+  $("#marginRate").html("'.(($marginRate === '') ? 'n/a' : price($marginRate, null, null, null, null, $rounding)."%").'");
362
+  $("#markRate").html("'.(($markRate === '') ? 'n/a' : price($markRate, null, null, null, null, $rounding)."%").'");
363 363
 
364 364
 });
365 365
 </script>
Please login to merge, or discard this patch.
Braces   +67 added lines, -46 removed lines patch added patch discarded remove patch
@@ -40,7 +40,9 @@  discard block
 block discarded – undo
40 40
 // Security check
41 41
 $fieldvalue = (! empty($id) ? $id : (! empty($ref) ? $ref : ''));
42 42
 $fieldtype = (! empty($ref) ? 'ref' : 'rowid');
43
-if (! empty($user->societe_id)) $socid=$user->societe_id;
43
+if (! empty($user->societe_id)) {
44
+    $socid=$user->societe_id;
45
+}
44 46
 $result=restrictedArea($user,'produit|service',$fieldvalue,'product&product','','',$fieldtype);
45 47
 $result=restrictedArea($user,'margins');
46 48
 
@@ -61,8 +63,7 @@  discard block
 block discarded – undo
61 63
 	{
62 64
 		$sortfield="f.datef";
63 65
 		$sortorder="DESC";
64
-	}
65
-	else
66
+	} else
66 67
 	{
67 68
 	    $sortfield="p.ref";
68 69
 	    $sortorder="ASC";
@@ -71,10 +72,12 @@  discard block
 block discarded – undo
71 72
 
72 73
 $startdate=$enddate='';
73 74
 
74
-if (!empty($_POST['startdatemonth']))
75
+if (!empty($_POST['startdatemonth'])) {
75 76
   $startdate  = dol_mktime(0, 0, 0, $_POST['startdatemonth'], $_POST['startdateday'], $_POST['startdateyear']);
76
-if (!empty($_POST['enddatemonth']))
77
+}
78
+if (!empty($_POST['enddatemonth'])) {
77 79
   $enddate  = dol_mktime(23, 59, 59, $_POST['enddatemonth'], $_POST['enddateday'], $_POST['enddateyear']);
80
+}
78 81
 
79 82
 
80 83
 /*
@@ -109,10 +112,13 @@  discard block
 block discarded – undo
109 112
   print $form->select_produits($id,'id','',20,0,1,2,'',1, array(), 0, 'All');
110 113
   print '</td></tr>';
111 114
 
112
-  if (! $sortorder) $sortorder="DESC";
113
-  if (! $sortfield) $sortfield="f.datef";
114
-}
115
-else {
115
+  if (! $sortorder) {
116
+      $sortorder="DESC";
117
+  }
118
+  if (! $sortfield) {
119
+      $sortfield="f.datef";
120
+  }
121
+  } else {
116 122
 	print '<tr><td class="titlefield">'.$langs->trans('ChooseProduct/Service').'</td>';
117 123
 	print '<td class="maxwidthonsmartphone" colspan="4">';
118 124
 	print $form->select_produits('','id','',20,0,1,2,'',1, array(), 0, 'All');
@@ -175,8 +181,12 @@  discard block
 block discarded – undo
175 181
 print '</form>';
176 182
 
177 183
 $sql = "SELECT p.label, p.rowid, p.fk_product_type, p.ref, p.entity as pentity,";
178
-if ($id > 0) $sql.= " d.fk_product,";
179
-if ($id > 0) $sql.= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
184
+if ($id > 0) {
185
+    $sql.= " d.fk_product,";
186
+}
187
+if ($id > 0) {
188
+    $sql.= " f.rowid as facid, f.ref, f.total as total_ht, f.datef, f.paye, f.fk_statut as statut,";
189
+}
180 190
 $sql.= " SUM(d.total_ht) as selling_price,";
181 191
 // Note: qty and buy_price_ht is always positive (if not your database may be corrupted, you can update this)
182 192
 $sql.= " SUM(".$db->ifsql('d.total_ht < 0','d.qty * d.buy_price_ht * -1','d.qty * d.buy_price_ht').") as buying_price,";
@@ -192,20 +202,27 @@  discard block
 block discarded – undo
192 202
 $sql.= ' AND f.entity IN ('.getEntity('invoice').')';
193 203
 $sql.= " AND f.fk_statut > 0";
194 204
 $sql.= " AND d.fk_facture = f.rowid";
195
-if ($id > 0)
205
+if ($id > 0) {
196 206
 	$sql.= " AND d.fk_product =".$id;
207
+}
197 208
 if (! empty($TSelectedCats)) {
198 209
 	$sql .= ' AND cp.fk_categorie IN ('.implode(',', $TSelectedCats) . ')';
199 210
 }
200
-if (!empty($startdate))
211
+if (!empty($startdate)) {
201 212
   $sql.= " AND f.datef >= '".$db->idate($startdate)."'";
202
-if (!empty($enddate))
213
+}
214
+if (!empty($enddate)) {
203 215
   $sql.= " AND f.datef <= '".$db->idate($enddate)."'";
216
+}
204 217
 $sql .= " AND d.buy_price_ht IS NOT NULL";
205
-if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)
218
+if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) {
206 219
 	$sql .= " AND d.buy_price_ht <> 0";
207
-if ($id > 0) $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
208
-else $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
220
+}
221
+if ($id > 0) {
222
+    $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity, d.fk_product, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut";
223
+} else {
224
+    $sql.= " GROUP BY p.label, p.rowid, p.fk_product_type, p.ref, p.entity";
225
+}
209 226
 $sql.=$db->order($sortfield,$sortorder);
210 227
 // TODO: calculate total to display then restore pagination
211 228
 //$sql.= $db->plimit($conf->liste_limit +1, $offset);
@@ -220,10 +237,12 @@  discard block
 block discarded – undo
220 237
 	print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&amp;id=".$id, $sortfield, $sortorder, '', $num, $num, '', 0, '', '', 0, 1);
221 238
 
222 239
 	//var_dump($conf->global->MARGIN_TYPE);
223
-	if ($conf->global->MARGIN_TYPE == "1")
224
-	    $labelcostprice='BuyingPrice';
225
-	else   // value is 'costprice' or 'pmp'
240
+	if ($conf->global->MARGIN_TYPE == "1") {
241
+		    $labelcostprice='BuyingPrice';
242
+	} else {
243
+	    // value is 'costprice' or 'pmp'
226 244
 	    $labelcostprice='CostPrice';
245
+	}
227 246
 
228 247
 	$moreforfilter='';
229 248
 
@@ -235,18 +254,19 @@  discard block
 block discarded – undo
235 254
 	if ($id > 0) {
236 255
   		print_liste_field_titre("Invoice",$_SERVER["PHP_SELF"],"f.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
237 256
   		print_liste_field_titre("DateInvoice",$_SERVER["PHP_SELF"],"f.datef","","&amp;id=".$id,'align="center"',$sortfield,$sortorder);
238
-  	}
239
-  	else
257
+  	} else
240 258
   	{
241 259
   		print_liste_field_titre("ProductService",$_SERVER["PHP_SELF"],"p.ref","","&amp;id=".$id,'',$sortfield,$sortorder);
242 260
   	}
243 261
 	print_liste_field_titre("SellingPrice",$_SERVER["PHP_SELF"],"selling_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
244 262
 	print_liste_field_titre($labelcostprice,$_SERVER["PHP_SELF"],"buying_price","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
245 263
 	print_liste_field_titre("Margin",$_SERVER["PHP_SELF"],"marge","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
246
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
247
-		print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
248
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
249
-		print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
264
+	if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
265
+			print_liste_field_titre("MarginRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
266
+	}
267
+	if (! empty($conf->global->DISPLAY_MARK_RATES)) {
268
+			print_liste_field_titre("MarkRate",$_SERVER["PHP_SELF"],"","","&amp;id=".$id,'align="right"',$sortfield,$sortorder);
269
+	}
250 270
 	print "</tr>\n";
251 271
 
252 272
 	$cumul_achat = 0;
@@ -266,8 +286,7 @@  discard block
 block discarded – undo
266 286
 			{
267 287
 				$marginRate = ($pa != 0)?-1*(100 * $marge / $pa):'' ;
268 288
 				$markRate = ($pv != 0)?-1*(100 * $marge / $pv):'' ;
269
-			}
270
-			else
289
+			} else
271 290
 			{
272 291
 				$marginRate = ($pa != 0)?(100 * $marge / $pa):'' ;
273 292
 				$markRate = ($pv != 0)?(100 * $marge / $pv):'' ;
@@ -282,8 +301,7 @@  discard block
 block discarded – undo
282 301
 				print "</td>\n";
283 302
 				print "<td align=\"center\">";
284 303
 				print dol_print_date($db->jdate($objp->datef),'day')."</td>";
285
-			}
286
-			else {
304
+			} else {
287 305
 				print '<td>';
288 306
 				if ($objp->rowid > 0)
289 307
 				{
@@ -294,8 +312,7 @@  discard block
 block discarded – undo
294 312
     				$product_static->entity=$objp->pentity;
295 313
     				$text=$product_static->getNomUrl(1);
296 314
     				print $text.= ' - '.$objp->label;
297
-				}
298
-				else
315
+				} else
299 316
 				{
300 317
 				    print img_object('', 'product').' '.$langs->trans("NotPredefinedProducts");
301 318
 				}
@@ -305,10 +322,12 @@  discard block
 block discarded – undo
305 322
 			print "<td align=\"right\">".price($pv, null, null, null, null, $rounding)."</td>\n";
306 323
 			print "<td align=\"right\">".price($pa, null, null, null, null, $rounding)."</td>\n";
307 324
 			print "<td align=\"right\">".price($marge, null, null, null, null, $rounding)."</td>\n";
308
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
309
-				print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
310
-			if (! empty($conf->global->DISPLAY_MARK_RATES))
311
-				print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
325
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
326
+							print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
327
+			}
328
+			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
329
+							print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
330
+			}
312 331
 			print "</tr>\n";
313 332
 
314 333
 			$i++;
@@ -325,24 +344,26 @@  discard block
 block discarded – undo
325 344
 	$markRate = ($cumul_vente != 0)?(100 * $totalMargin / $cumul_vente):'';
326 345
 
327 346
 	print '<tr class="liste_total">';
328
-	if ($id > 0)
329
-		print '<td colspan=2>';
330
-	else
331
-		print '<td>';
347
+	if ($id > 0) {
348
+			print '<td colspan=2>';
349
+	} else {
350
+			print '<td>';
351
+	}
332 352
 	print $langs->trans('TotalMargin')."</td>";
333 353
 	print "<td align=\"right\">".price($cumul_vente, null, null, null, null, $rounding)."</td>\n";
334 354
 	print "<td align=\"right\">".price($cumul_achat, null, null, null, null, $rounding)."</td>\n";
335 355
 	print "<td align=\"right\">".price($totalMargin, null, null, null, null, $rounding)."</td>\n";
336
-	if (! empty($conf->global->DISPLAY_MARGIN_RATES))
337
-		print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
338
-	if (! empty($conf->global->DISPLAY_MARK_RATES))
339
-		print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
356
+	if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
357
+			print "<td align=\"right\">".(($marginRate === '')?'n/a':price($marginRate, null, null, null, null, $rounding)."%")."</td>\n";
358
+	}
359
+	if (! empty($conf->global->DISPLAY_MARK_RATES)) {
360
+			print "<td align=\"right\">".(($markRate === '')?'n/a':price($markRate, null, null, null, null, $rounding)."%")."</td>\n";
361
+	}
340 362
 	print "</tr>\n";
341 363
 
342 364
 	print "</table>";
343 365
 	print '</div>';
344
-}
345
-else
366
+} else
346 367
 {
347 368
 	dol_print_error($db);
348 369
 }
Please login to merge, or discard this patch.