Passed
Push — master ( 1007d6...492b54 )
by Alxarafe
26:10
created
Base/AlixarController.php 1 patch
Spacing   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -50,13 +50,13 @@  discard block
 block discarded – undo
50 50
         // Note: the function dol_getprefix may have been redefined to return a different key to manage another area to protect.
51 51
         $prefix = DolUtils::dol_getprefix('');
52 52
 
53
-        $sessionname = 'DOLSESSID_' . $prefix;
54
-        $sessiontimeout = 'DOLSESSTIMEOUT_' . $prefix;
53
+        $sessionname = 'DOLSESSID_'.$prefix;
54
+        $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix;
55 55
         if (!empty($_COOKIE[$sessiontimeout])) {
56 56
             ini_set('session.gc_maxlifetime', $_COOKIE[$sessiontimeout]);
57 57
         }
58 58
         session_name($sessionname);
59
-        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.
59
+        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.
60 60
         // This create lock, released when session_write_close() or end of page.
61 61
         // We need this lock as long as we read/write $_SESSION ['vars']. We can remove lock when finished.
62 62
         if (!defined('NOSESSION')) {
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
             Globals::$conf->browser->name = $tmp['browsername'];
81 81
             Globals::$conf->browser->os = $tmp['browseros'];
82 82
             Globals::$conf->browser->version = $tmp['browserversion'];
83
-            Globals::$conf->browser->layout = $tmp['layout'];     // 'classic', 'phone', 'tablet'
83
+            Globals::$conf->browser->layout = $tmp['layout']; // 'classic', 'phone', 'tablet'
84 84
 //var_dump(Globals::$conf->browser);
85 85
 
86 86
             if (Globals::$conf->browser->layout == 'phone') {
@@ -101,18 +101,18 @@  discard block
 block discarded – undo
101 101
                         $newurl = preg_replace('/^http:/i', 'https:', $_SERVER["SCRIPT_URI"]);
102 102
                     }
103 103
                 } else { // Check HTTPS environment variable (Apache/mod_ssl only)
104
-                    $newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT) . $_SERVER["REQUEST_URI"];
104
+                    $newurl = preg_replace('/^http:/i', 'https:', DOL_MAIN_URL_ROOT).$_SERVER["REQUEST_URI"];
105 105
                 }
106 106
             } else {
107 107
 // Check HTTPS environment variable (Apache/mod_ssl only)
108
-                $newurl = Globals::$conf->file->main_force_https . $_SERVER["REQUEST_URI"];
108
+                $newurl = Globals::$conf->file->main_force_https.$_SERVER["REQUEST_URI"];
109 109
             }
110 110
 // Start redirect
111 111
             if ($newurl) {
112
-                DolUtils::dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to " . $newurl);
112
+                DolUtils::dol_syslog("main.inc: dolibarr_main_force_https is on, we make a redirect to ".$newurl);
113 113
                 echo $newurl;
114 114
                 throw Exception('x');
115
-                header("Location: " . $newurl);
115
+                header("Location: ".$newurl);
116 116
                 exit;
117 117
             } else {
118 118
                 DolUtils::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);
@@ -137,29 +137,29 @@  discard block
 block discarded – undo
137 137
 
138 138
 // Loading of additional presentation includes
139 139
         if (!defined('NOREQUIREHTML')) {
140
-            require_once DOL_BASE_PATH . '/core/class/html.form.class.php';     // Need 660ko memory (800ko in 2.2)
140
+            require_once DOL_BASE_PATH.'/core/class/html.form.class.php'; // Need 660ko memory (800ko in 2.2)
141 141
         }
142 142
         if (!defined('NOREQUIREAJAX') && Globals::$conf->use_javascript_ajax) {
143
-            require_once DOL_BASE_PATH . '/core/lib/ajax.lib.php'; // Need 22ko memory
143
+            require_once DOL_BASE_PATH.'/core/lib/ajax.lib.php'; // Need 22ko memory
144 144
         }
145 145
 // If install or upgrade process not done or not completely finished, we call the install page.
146 146
         if (!empty(Globals::$conf->global->MAIN_NOT_INSTALLED) || !empty(Globals::$conf->global->MAIN_NOT_UPGRADED)) {
147 147
             DolUtils::dol_syslog("main.inc: A previous install or upgrade was not complete. Redirect to install page.", LOG_WARNING);
148 148
             throw Exception('x');
149
-            header("Location: " . DOL_BASE_URI . "/install/index.php");
149
+            header("Location: ".DOL_BASE_URI."/install/index.php");
150 150
             exit;
151 151
         }
152 152
 // If an upgrade process is required, we call the install page.
153 153
         if ((!empty(Globals::$conf->global->MAIN_VERSION_LAST_UPGRADE) && (Globals::$conf->global->MAIN_VERSION_LAST_UPGRADE != DOL_VERSION)) || (empty(Globals::$conf->global->MAIN_VERSION_LAST_UPGRADE) && !empty(Globals::$conf->global->MAIN_VERSION_LAST_INSTALL) && (Globals::$conf->global->MAIN_VERSION_LAST_INSTALL != DOL_VERSION))) {
154 154
             $versiontocompare = empty(Globals::$conf->global->MAIN_VERSION_LAST_UPGRADE) ? Globals::$conf->global->MAIN_VERSION_LAST_INSTALL : Globals::$conf->global->MAIN_VERSION_LAST_UPGRADE;
155
-            require_once DOL_BASE_PATH . '/core/lib/admin.lib.php';
155
+            require_once DOL_BASE_PATH.'/core/lib/admin.lib.php';
156 156
             $dolibarrversionlastupgrade = preg_split('/[.-]/', $versiontocompare);
157 157
             $dolibarrversionprogram = preg_split('/[.-]/', DOL_VERSION);
158 158
             $rescomp = versioncompare($dolibarrversionprogram, $dolibarrversionlastupgrade);
159 159
             if ($rescomp > 0) {   // Programs have a version higher than database. We did not add "&& $rescomp < 3" because we want upgrade process for build upgrades
160
-                DolUtils::dol_syslog("main.inc: database version " . $versiontocompare . " is lower than programs version " . DOL_VERSION . ". Redirect to install page.", LOG_WARNING);
160
+                DolUtils::dol_syslog("main.inc: database version ".$versiontocompare." is lower than programs version ".DOL_VERSION.". Redirect to install page.", LOG_WARNING);
161 161
                 throw Exception('x');
162
-                header("Location: " . DOL_BASE_URI . "/install/index.php");
162
+                header("Location: ".DOL_BASE_URI."/install/index.php");
163 163
                 exit;
164 164
             }
165 165
         }
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
             }
184 184
             if ($_SERVER['REQUEST_METHOD'] === 'POST') {  // This test must be after loading $_SESSION['token'].
185 185
                 if (DolUtils::GETPOST('token', 'alpha') != $_SESSION['token']) {
186
-                    DolUtils::dol_syslog("Invalid token in " . $_SERVER['HTTP_REFERER'] . ", action=" . DolUtils::GETPOST('action', 'aZ09') . ", _POST['token']=" . DolUtils::GETPOST('token', 'alpha') . ", _SESSION['token']=" . $_SESSION['token'], LOG_WARNING);
186
+                    DolUtils::dol_syslog("Invalid token in ".$_SERVER['HTTP_REFERER'].", action=".DolUtils::GETPOST('action', 'aZ09').", _POST['token']=".DolUtils::GETPOST('token', 'alpha').", _SESSION['token']=".$_SESSION['token'], LOG_WARNING);
187 187
 //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.
188 188
                     unset($_POST);
189 189
                 }
@@ -261,19 +261,19 @@  discard block
 block discarded – undo
261 261
                 $dol_use_jmobile = DolUtils::GETPOST('dol_use_jmobile', 'int', 3);
262 262
 //dol_syslog("POST key=".join(array_keys($_POST),',').' value='.join($_POST,','));
263 263
 // If in demo mode, we check we go to home page through the public/demo/index.php page
264
-                if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_BASE_URI . '/index.php') {  // We ask index page
264
+                if (!empty($dolibarr_main_demo) && $_SERVER['PHP_SELF'] == DOL_BASE_URI.'/index.php') {  // We ask index page
265 265
                     if (empty($_SERVER['HTTP_REFERER']) || !preg_match('/public/', $_SERVER['HTTP_REFERER'])) {
266
-                        DolUtils::dol_syslog("Call index page from another url than demo page (call is done from page " . $_SERVER['HTTP_REFERER'] . ")");
266
+                        DolUtils::dol_syslog("Call index page from another url than demo page (call is done from page ".$_SERVER['HTTP_REFERER'].")");
267 267
                         $url = '';
268
-                        $url .= ($url ? '&' : '') . ($dol_hide_topmenu ? 'dol_hide_topmenu=' . $dol_hide_topmenu : '');
269
-                        $url .= ($url ? '&' : '') . ($dol_hide_leftmenu ? 'dol_hide_leftmenu=' . $dol_hide_leftmenu : '');
270
-                        $url .= ($url ? '&' : '') . ($dol_optimize_smallscreen ? 'dol_optimize_smallscreen=' . $dol_optimize_smallscreen : '');
271
-                        $url .= ($url ? '&' : '') . ($dol_no_mouse_hover ? 'dol_no_mouse_hover=' . $dol_no_mouse_hover : '');
272
-                        $url .= ($url ? '&' : '') . ($dol_use_jmobile ? 'dol_use_jmobile=' . $dol_use_jmobile : '');
273
-                        $url = DOL_BASE_URI . '/public/demo/index.php' . ($url ? '?' . $url : '');
268
+                        $url .= ($url ? '&' : '').($dol_hide_topmenu ? 'dol_hide_topmenu='.$dol_hide_topmenu : '');
269
+                        $url .= ($url ? '&' : '').($dol_hide_leftmenu ? 'dol_hide_leftmenu='.$dol_hide_leftmenu : '');
270
+                        $url .= ($url ? '&' : '').($dol_optimize_smallscreen ? 'dol_optimize_smallscreen='.$dol_optimize_smallscreen : '');
271
+                        $url .= ($url ? '&' : '').($dol_no_mouse_hover ? 'dol_no_mouse_hover='.$dol_no_mouse_hover : '');
272
+                        $url .= ($url ? '&' : '').($dol_use_jmobile ? 'dol_use_jmobile='.$dol_use_jmobile : '');
273
+                        $url = DOL_BASE_URI.'/public/demo/index.php'.($url ? '?'.$url : '');
274 274
                         echo $url;
275 275
                         throw Exception('x');
276
-                        header("Location: " . $url);
276
+                        header("Location: ".$url);
277 277
                         exit;
278 278
                     }
279 279
                 }
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
                         $test = false;
294 294
 
295 295
 // Call trigger for the "security events" log
296
-                        Globals::$user->trigger_mesg = 'ErrorBadValueForCode - login=' . DolUtils::GETPOST("username", "alpha", 2);
296
+                        Globals::$user->trigger_mesg = 'ErrorBadValueForCode - login='.DolUtils::GETPOST("username", "alpha", 2);
297 297
 // Call of triggers
298 298
                         //include_once DOL_BASE_PATH . '/core/class/interfaces.class.php';
299 299
                         $interface = new Interfaces($db);
@@ -306,7 +306,7 @@  discard block
 block discarded – undo
306 306
                         $action = '';
307 307
                         Globals::$hookManager->initHooks(array('login'));
308 308
                         $parameters = array('dol_authmode' => $this->dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
309
-                        $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action);    // Note that $action and $object may have been modified by some hooks
309
+                        $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action); // Note that $action and $object may have been modified by some hooks
310 310
                         if ($reshook < 0)
311 311
                             $error++;
312 312
 
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
                         }
382 382
 
383 383
                         // Call trigger for the "security events" log
384
-                        Globals::$user->trigger_mesg = Globals::$langs->trans("ErrorBadLoginPassword") . ' - login=' . DolUtils::GETPOST("username", "alpha", 2);
384
+                        Globals::$user->trigger_mesg = Globals::$langs->trans("ErrorBadLoginPassword").' - login='.DolUtils::GETPOST("username", "alpha", 2);
385 385
 
386 386
                         // Call of triggers
387 387
                         //include_once DOL_BASE_PATH . '/core/class/interfaces.class.php';
@@ -395,7 +395,7 @@  discard block
 block discarded – undo
395 395
                         $action = '';
396 396
                         Globals::$hookManager->initHooks(array('login'));
397 397
                         $parameters = array('dol_authmode' => $this->dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
398
-                        $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action);    // Note that $action and $object may have been modified by some hooks
398
+                        $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action); // Note that $action and $object may have been modified by some hooks
399 399
                         if ($reshook < 0) {
400 400
                             $error++;
401 401
                         }
@@ -407,7 +407,7 @@  discard block
 block discarded – undo
407 407
                 // End test login / passwords
408 408
                 if (!$login || (in_array('ldap', $this->authmode) && empty($passwordtotest))) { // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success.
409 409
                 // No data to test login, so we show the login page
410
-                    DolUtils::dol_syslog("--- Access to " . $_SERVER["PHP_SELF"] . " showing the login form and exit");
410
+                    DolUtils::dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." showing the login form and exit");
411 411
                     if (defined('NOREDIRECTBYMAINTOLOGIN')) {
412 412
                         return 'ERROR_NOT_LOGGED';
413 413
                     } else {
@@ -422,8 +422,8 @@  discard block
 block discarded – undo
422 422
                     DolUtils::dol_syslog('User not found, connexion refused');
423 423
                     session_destroy();
424 424
                     session_name($sessionname);
425
-                    session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
426
-                    session_start();    // Fixing the bug of register_globals here is useless since session is empty
425
+                    session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
426
+                    session_start(); // Fixing the bug of register_globals here is useless since session is empty
427 427
 
428 428
                     if ($resultFetchUser == 0) {
429 429
 // Load translation files required by page
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
 
432 432
                         $_SESSION["dol_loginmesg"] = Globals::$langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
433 433
 
434
-                        Globals::$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login=' . $login;
434
+                        Globals::$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
435 435
                     }
436 436
                     if ($resultFetchUser < 0) {
437 437
                         $_SESSION["dol_loginmesg"] = Globals::$user->error;
@@ -451,40 +451,40 @@  discard block
 block discarded – undo
451 451
                     $action = '';
452 452
                     Globals::$hookManager->initHooks(array('login'));
453 453
                     $parameters = array('dol_authmode' => $this->dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
454
-                    $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action);    // Note that $action and $object may have been modified by some hooks
454
+                    $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action); // Note that $action and $object may have been modified by some hooks
455 455
                     if ($reshook < 0) {
456 456
                         $error++;
457 457
                     }
458 458
 
459 459
                     $paramsurl = array();
460 460
                     if (DolUtils::GETPOST('textbrowser', 'int')) {
461
-                        $paramsurl[] = 'textbrowser=' . DolUtils::GETPOST('textbrowser', 'int');
461
+                        $paramsurl[] = 'textbrowser='.DolUtils::GETPOST('textbrowser', 'int');
462 462
                     }
463 463
                     if (DolUtils::GETPOST('nojs', 'int')) {
464
-                        $paramsurl[] = 'nojs=' . DolUtils::GETPOST('nojs', 'int');
464
+                        $paramsurl[] = 'nojs='.DolUtils::GETPOST('nojs', 'int');
465 465
                     }
466 466
                     if (DolUtils::GETPOST('lang', 'aZ09')) {
467
-                        $paramsurl[] = 'lang=' . DolUtils::GETPOST('lang', 'aZ09');
467
+                        $paramsurl[] = 'lang='.DolUtils::GETPOST('lang', 'aZ09');
468 468
                     }
469
-                    echo 'Location: ' . DOL_BASE_URI . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : '');
469
+                    echo 'Location: '.DOL_BASE_URI.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : '');
470 470
                     throw Exception('x');
471
-                    header('Location: ' . DOL_BASE_URI . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : ''));
471
+                    header('Location: '.DOL_BASE_URI.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
472 472
                     exit;
473 473
                 }
474 474
             } else {
475 475
 // We are already into an authenticated session
476 476
                 $login = $_SESSION["dol_login"];
477 477
                 $entity = $_SESSION["dol_entity"];
478
-                DolUtils::dol_syslog("- This is an already logged session. _SESSION['dol_login']=" . $login . " _SESSION['dol_entity']=" . $entity, LOG_DEBUG);
478
+                DolUtils::dol_syslog("- This is an already logged session. _SESSION['dol_login']=".$login." _SESSION['dol_entity']=".$entity, LOG_DEBUG);
479 479
 
480 480
                 $resultFetchUser = Globals::$user->fetch('', $login, '', 1, ($entity > 0 ? $entity : -1));
481 481
                 if ($resultFetchUser <= 0) {
482 482
 // Account has been removed after login
483
-                    DolUtils::dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=" . $login, LOG_WARNING);
483
+                    DolUtils::dol_syslog("Can't load user even if session logged. _SESSION['dol_login']=".$login, LOG_WARNING);
484 484
                     session_destroy();
485 485
                     session_name($sessionname);
486
-                    session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
487
-                    session_start();    // Fixing the bug of register_globals here is useless since session is empty
486
+                    session_set_cookie_params(0, '/', null, false, true); // Add tag httponly on session cookie
487
+                    session_start(); // Fixing the bug of register_globals here is useless since session is empty
488 488
 
489 489
                     if ($resultFetchUser == 0) {
490 490
 // Load translation files required by page
@@ -492,7 +492,7 @@  discard block
 block discarded – undo
492 492
 
493 493
                         $_SESSION["dol_loginmesg"] = Globals::$langs->trans("ErrorCantLoadUserFromDolibarrDatabase", $login);
494 494
 
495
-                        Globals::$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login=' . $login;
495
+                        Globals::$user->trigger_mesg = 'ErrorCantLoadUserFromDolibarrDatabase - login='.$login;
496 496
                     }
497 497
                     if ($resultFetchUser < 0) {
498 498
                         $_SESSION["dol_loginmesg"] = Globals::$user->error;
@@ -512,24 +512,24 @@  discard block
 block discarded – undo
512 512
                     $action = '';
513 513
                     Globals::$hookManager->initHooks(array('login'));
514 514
                     $parameters = array('dol_authmode' => $this->dol_authmode, 'dol_loginmesg' => $_SESSION["dol_loginmesg"]);
515
-                    $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action);    // Note that $action and $object may have been modified by some hooks
515
+                    $reshook = Globals::$hookManager->executeHooks('afterLoginFailed', $parameters, Globals::$user, $action); // Note that $action and $object may have been modified by some hooks
516 516
                     if ($reshook < 0) {
517 517
                         $error++;
518 518
                     }
519 519
 
520 520
                     $paramsurl = array();
521 521
                     if (DolUtils::GETPOST('textbrowser', 'int')) {
522
-                        $paramsurl[] = 'textbrowser=' . DolUtils::GETPOST('textbrowser', 'int');
522
+                        $paramsurl[] = 'textbrowser='.DolUtils::GETPOST('textbrowser', 'int');
523 523
                     }
524 524
                     if (DolUtils::GETPOST('nojs', 'int')) {
525
-                        $paramsurl[] = 'nojs=' . DolUtils::GETPOST('nojs', 'int');
525
+                        $paramsurl[] = 'nojs='.DolUtils::GETPOST('nojs', 'int');
526 526
                     }
527 527
                     if (DolUtils::GETPOST('lang', 'aZ09')) {
528
-                        $paramsurl[] = 'lang=' . DolUtils::GETPOST('lang', 'aZ09');
528
+                        $paramsurl[] = 'lang='.DolUtils::GETPOST('lang', 'aZ09');
529 529
                     }
530
-                    echo 'Location: ' . DOL_BASE_URI . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : '');
530
+                    echo 'Location: '.DOL_BASE_URI.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : '');
531 531
                     throw Exception('x');
532
-                    header('Location: ' . DOL_BASE_URI . '/index.php' . (count($paramsurl) ? '?' . implode('&', $paramsurl) : ''));
532
+                    header('Location: '.DOL_BASE_URI.'/index.php'.(count($paramsurl) ? '?'.implode('&', $paramsurl) : ''));
533 533
                     exit;
534 534
                 } else {
535 535
 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
@@ -538,30 +538,30 @@  discard block
 block discarded – undo
538 538
 // Code for search criteria persistence.
539 539
                     if (!empty($_GET['save_lastsearch_values'])) {    // We must use $_GET here
540 540
                         $relativepathstring = preg_replace('/\?.*$/', '', $_SERVER["HTTP_REFERER"]);
541
-                        $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring);     // Get full path except host server
541
+                        $relativepathstring = preg_replace('/^https?:\/\/[^\/]*/', '', $relativepathstring); // Get full path except host server
542 542
 // Clean $relativepathstring
543 543
                         if (constant('DOL_BASE_URI')) {
544
-                            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
544
+                            $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
545 545
                         }
546 546
                         $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
547 547
                         $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
548 548
 //var_dump($relativepathstring);
549 549
 // 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
550
-                        if (!empty($_SESSION['lastsearch_values_tmp_' . $relativepathstring])) {
551
-                            $_SESSION['lastsearch_values_' . $relativepathstring] = $_SESSION['lastsearch_values_tmp_' . $relativepathstring];
552
-                            unset($_SESSION['lastsearch_values_tmp_' . $relativepathstring]);
550
+                        if (!empty($_SESSION['lastsearch_values_tmp_'.$relativepathstring])) {
551
+                            $_SESSION['lastsearch_values_'.$relativepathstring] = $_SESSION['lastsearch_values_tmp_'.$relativepathstring];
552
+                            unset($_SESSION['lastsearch_values_tmp_'.$relativepathstring]);
553 553
                         }
554
-                        if (!empty($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring])) {
555
-                            $_SESSION['lastsearch_contextpage_' . $relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring];
556
-                            unset($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring]);
554
+                        if (!empty($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring])) {
555
+                            $_SESSION['lastsearch_contextpage_'.$relativepathstring] = $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring];
556
+                            unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
557 557
                         }
558
-                        if (!empty($_SESSION['lastsearch_page_tmp_' . $relativepathstring]) && $_SESSION['lastsearch_page_tmp_' . $relativepathstring] > 1) {
559
-                            $_SESSION['lastsearch_page_' . $relativepathstring] = $_SESSION['lastsearch_page_tmp_' . $relativepathstring];
560
-                            unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
558
+                        if (!empty($_SESSION['lastsearch_page_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_page_tmp_'.$relativepathstring] > 1) {
559
+                            $_SESSION['lastsearch_page_'.$relativepathstring] = $_SESSION['lastsearch_page_tmp_'.$relativepathstring];
560
+                            unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
561 561
                         }
562
-                        if (!empty($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]) && $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] != Globals::$conf->liste_limit) {
563
-                            $_SESSION['lastsearch_limit_' . $relativepathstring] = $_SESSION['lastsearch_limit_tmp_' . $relativepathstring];
564
-                            unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
562
+                        if (!empty($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]) && $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] != Globals::$conf->liste_limit) {
563
+                            $_SESSION['lastsearch_limit_'.$relativepathstring] = $_SESSION['lastsearch_limit_tmp_'.$relativepathstring];
564
+                            unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
565 565
                         }
566 566
                     }
567 567
 
@@ -609,14 +609,14 @@  discard block
 block discarded – undo
609 609
                     $_SESSION['dol_use_jmobile'] = $dol_use_jmobile;
610 610
                 }
611 611
 
612
-                DolUtils::dol_syslog("This is a new started user session. _SESSION['dol_login']=" . $_SESSION["dol_login"] . " Session id=" . session_id());
612
+                DolUtils::dol_syslog("This is a new started user session. _SESSION['dol_login']=".$_SESSION["dol_login"]." Session id=".session_id());
613 613
 
614 614
                 // Config::$dbEngine->begin();
615 615
                 Config::$dbEngine->startTransaction();
616 616
 
617 617
                 Globals::$user->update_last_login_date();
618 618
 
619
-                $loginfo = 'TZ=' . $_SESSION["dol_tz"] . ';TZString=' . $_SESSION["dol_tz_string"] . ';Screen=' . $_SESSION["dol_screenwidth"] . 'x' . $_SESSION["dol_screenheight"];
619
+                $loginfo = 'TZ='.$_SESSION["dol_tz"].';TZString='.$_SESSION["dol_tz_string"].';Screen='.$_SESSION["dol_screenwidth"].'x'.$_SESSION["dol_screenheight"];
620 620
 
621 621
 // Call triggers for the "security events" log
622 622
                 Globals::$user->trigger_mesg = $loginfo;
@@ -632,7 +632,7 @@  discard block
 block discarded – undo
632 632
                 $action = '';
633 633
                 Globals::$hookManager->initHooks(array('login'));
634 634
                 $parameters = array('dol_authmode' => $this->dol_authmode, 'dol_loginfo' => $loginfo);
635
-                $reshook = Globals::$hookManager->executeHooks('afterLogin', $parameters, Globals::$user, $action);    // Note that $action and $object may have been modified by some hooks
635
+                $reshook = Globals::$hookManager->executeHooks('afterLogin', $parameters, Globals::$user, $action); // Note that $action and $object may have been modified by some hooks
636 636
                 if ($reshook < 0) {
637 637
                     $error++;
638 638
                 }
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
                     if ($_SERVER["PHP_SELF"] != $newpath) {   // not already on landing page (avoid infinite loop)
654 654
                         echo $newpath;
655 655
                         throw Exception('x');
656
-                        header('Location: ' . $newpath);
656
+                        header('Location: '.$newpath);
657 657
                         exit;
658 658
                     }
659 659
                 }
@@ -685,7 +685,7 @@  discard block
 block discarded – undo
685 685
             if (empty(Globals::$conf->global->MAIN_FORCETHEME) && !empty(Globals::$user->conf->MAIN_THEME)) {
686 686
                 Globals::$conf->theme = Globals::$user->conf->MAIN_THEME;
687 687
 // Globals::$conf->css = "/theme/" . Globals::$conf->theme . "/style.css.php";
688
-                Globals::$conf->css = '?controller=theme/' . Globals::$conf->theme . '&method=style.css';
688
+                Globals::$conf->css = '?controller=theme/'.Globals::$conf->theme.'&method=style.css';
689 689
             }
690 690
         }
691 691
 
@@ -693,7 +693,7 @@  discard block
 block discarded – undo
693 693
         if (DolUtils::GETPOST('theme', 'alpha')) {
694 694
             Globals::$conf->theme = DolUtils::GETPOST('theme', 'alpha', 1);
695 695
 // Globals::$conf->css = "/theme/" . Globals::$conf->theme . "/style.css.php";
696
-            Globals::$conf->css = '?controller=theme/' . Globals::$conf->theme . '&method=style.css';
696
+            Globals::$conf->css = '?controller=theme/'.Globals::$conf->theme.'&method=style.css';
697 697
         }
698 698
 
699 699
 
@@ -743,7 +743,7 @@  discard block
 block discarded – undo
743 743
         if (!empty(Globals::$conf->dol_use_jmobile) && in_array(Globals::$conf->theme, array('bureau2crea', 'cameleo', 'amarok'))) {
744 744
             Globals::$conf->theme = 'eldy';
745 745
 // Globals::$conf->css = "/theme/" . Globals::$conf->theme . "/style.css.php";
746
-            Globals::$conf->css = '?controller=theme/' . Globals::$conf->theme . '&method=style.css';
746
+            Globals::$conf->css = '?controller=theme/'.Globals::$conf->theme.'&method=style.css';
747 747
         }
748 748
 
749 749
         if (!defined('NOREQUIRETRAN')) {
@@ -780,7 +780,7 @@  discard block
 block discarded – undo
780 780
         }
781 781
 
782 782
 
783
-        DolUtils::dol_syslog("--- Access to " . $_SERVER["PHP_SELF"] . ' - action=' . DolUtils::GETPOST('action', 'az09') . ', massaction=' . DolUtils::GETPOST('massaction', 'az09'));
783
+        DolUtils::dol_syslog("--- Access to ".$_SERVER["PHP_SELF"].' - action='.DolUtils::GETPOST('action', 'az09').', massaction='.DolUtils::GETPOST('massaction', 'az09'));
784 784
 //Another call for easy debugg
785 785
 //dol_syslog("Access to ".$_SERVER["PHP_SELF"].' GET='.join(',',array_keys($_GET)).'->'.join(',',$_GET).' POST:'.join(',',array_keys($_POST)).'->'.join(',',$_POST));
786 786
 // Load main languages files
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 // Define some constants used for style of arrays
793 793
         $bc = array(0 => 'class="impair"', 1 => 'class="pair"');
794 794
         $bcdd = array(0 => 'class="drag drop oddeven"', 1 => 'class="drag drop oddeven"');
795
-        $bcnd = array(0 => 'class="nodrag nodrop nohover"', 1 => 'class="nodrag nodrop nohoverpair"');  // Used for tr to add new lines
795
+        $bcnd = array(0 => 'class="nodrag nodrop nohover"', 1 => 'class="nodrag nodrop nohoverpair"'); // Used for tr to add new lines
796 796
         $bctag = array(0 => 'class="impair tagtr"', 1 => 'class="pair tagtr"');
797 797
 
798 798
 // Define messages variables
@@ -840,7 +840,7 @@  discard block
 block discarded – undo
840 840
 // Load the menu manager (only if not already done)
841 841
             $file_menu = Globals::$conf->standard_menu;
842 842
             if (DolUtils::GETPOST('menu', 'alpha')) {
843
-                $file_menu = DolUtils::GETPOST('menu', 'alpha');     // example: menu=eldy_menu.php
843
+                $file_menu = DolUtils::GETPOST('menu', 'alpha'); // example: menu=eldy_menu.php
844 844
             }
845 845
             if (!class_exists('MenuManager')) {
846 846
                 $menufound = 0;
@@ -852,7 +852,7 @@  discard block
 block discarded – undo
852 852
                     }
853 853
                 }
854 854
                 if (!class_exists('MenuManager')) { // If failed to include, we try with standard eldy_menu.php
855
-                    DolUtils::dol_syslog("You define a menu manager '" . $file_menu . "' that can not be loaded.", LOG_WARNING);
855
+                    DolUtils::dol_syslog("You define a menu manager '".$file_menu."' that can not be loaded.", LOG_WARNING);
856 856
                     $file_menu = 'eldy_menu.php';
857 857
                     // include_once DOL_DOCUMENT_ROOT . "/core/menus/standard/" . $file_menu;
858 858
                 }
@@ -896,7 +896,7 @@  discard block
 block discarded – undo
896 896
 
897 897
         // This is to make Dolibarr working with Plesk
898 898
         if (!empty($_SERVER['DOCUMENT_ROOT']) && substr($_SERVER['DOCUMENT_ROOT'], -6) !== 'htdocs') {
899
-            set_include_path($_SERVER['DOCUMENT_ROOT'] . '/htdocs');
899
+            set_include_path($_SERVER['DOCUMENT_ROOT'].'/htdocs');
900 900
         }
901 901
 
902 902
         // If there is a POST parameter to tell to save automatically some POST parameters into cookies, we do it.
@@ -907,7 +907,7 @@  discard block
 block discarded – undo
907 907
             $tmplist = explode(',', $tmpautoset[1]);
908 908
             $cookiearrayvalue = array();
909 909
             foreach ($tmplist as $tmpkey) {
910
-                $postkey = $tmpautoset[0] . '_' . $tmpkey;
910
+                $postkey = $tmpautoset[0].'_'.$tmpkey;
911 911
 //var_dump('tmpkey='.$tmpkey.' postkey='.$postkey.' value='.$_POST[$postkey]);
912 912
                 if (!empty($_POST[$postkey])) {
913 913
                     $cookiearrayvalue[$tmpkey] = $_POST[$postkey];
@@ -968,8 +968,8 @@  discard block
 block discarded – undo
968 968
             $inj += preg_match('/insert\s+into/i', $val);
969 969
             $inj += preg_match('/select\s+from/i', $val);
970 970
             $inj += preg_match('/into\s+(outfile|dumpfile)/i', $val);
971
-            $inj += preg_match('/user\s*\(/i', $val);      // avoid to use function user() that return current database login
972
-            $inj += preg_match('/information_schema/i', $val);    // avoid to use request that read information_schema database
971
+            $inj += preg_match('/user\s*\(/i', $val); // avoid to use function user() that return current database login
972
+            $inj += preg_match('/information_schema/i', $val); // avoid to use request that read information_schema database
973 973
         }
974 974
         if ($type == 3) {
975 975
             $inj += preg_match('/select|update|delete|replace|group\s+by|concat|count|from/i', $val);
@@ -993,15 +993,15 @@  discard block
 block discarded – undo
993 993
             $inj += preg_match('/<style/i', $val);
994 994
         }
995 995
         $inj += preg_match('/base[\s]+href/si', $val);
996
-        $inj += preg_match('/<.*onmouse/si', $val);       // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
997
-        $inj += preg_match('/onerror\s*=/i', $val);       // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
998
-        $inj += preg_match('/onfocus\s*=/i', $val);       // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
999
-        $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)>
1000
-        $inj += preg_match('/onloadstart\s*=/i', $val);   // onload can be set on audio tag <audio onloadstart=alert(1)>
1001
-        $inj += preg_match('/onclick\s*=/i', $val);       // onclick can be set on img text html tag like <img onclick = alert(1)>
1002
-        $inj += preg_match('/onscroll\s*=/i', $val);      // onscroll can be on textarea
996
+        $inj += preg_match('/<.*onmouse/si', $val); // onmousexxx can be set on img or any html tag like <img title='...' onmouseover=alert(1)>
997
+        $inj += preg_match('/onerror\s*=/i', $val); // onerror can be set on img or any html tag like <img title='...' onerror = alert(1)>
998
+        $inj += preg_match('/onfocus\s*=/i', $val); // onfocus can be set on input text html tag like <input type='text' value='...' onfocus = alert(1)>
999
+        $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)>
1000
+        $inj += preg_match('/onloadstart\s*=/i', $val); // onload can be set on audio tag <audio onloadstart=alert(1)>
1001
+        $inj += preg_match('/onclick\s*=/i', $val); // onclick can be set on img text html tag like <img onclick = alert(1)>
1002
+        $inj += preg_match('/onscroll\s*=/i', $val); // onscroll can be on textarea
1003 1003
 //$inj += preg_match('/on[A-Z][a-z]+\*=/', $val);   // To lock event handlers onAbort(), ...
1004
-        $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val);  // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
1004
+        $inj += preg_match('/&#58;|&#0000058|&#x3A/i', $val); // refused string ':' encoded (no reason to have it encoded) to lock 'javascript:...'
1005 1005
 //if ($type == 1)
1006 1006
 //{
1007 1007
         $inj += preg_match('/javascript:/i', $val);
@@ -1009,10 +1009,10 @@  discard block
 block discarded – undo
1009 1009
 //}
1010 1010
 // For XSS Injection done by adding javascript closing html tags like with onmousemove, etc... (closing a src or href tag with not cleaned param)
1011 1011
         if ($type == 1) {
1012
-            $inj += preg_match('/"/i', $val);  // We refused " in GET parameters value
1012
+            $inj += preg_match('/"/i', $val); // We refused " in GET parameters value
1013 1013
         }
1014 1014
         if ($type == 2) {
1015
-            $inj += preg_match('/[;"]/', $val);  // PHP_SELF is a file system path. It can contains spaces.
1015
+            $inj += preg_match('/[;"]/', $val); // PHP_SELF is a file system path. It can contains spaces.
1016 1016
         }
1017 1017
         return $inj;
1018 1018
     }
@@ -1031,7 +1031,7 @@  discard block
 block discarded – undo
1031 1031
                 if ($this->analyseVarsForSqlAndScriptsInjection($key, $type) && $this->analyseVarsForSqlAndScriptsInjection($value, $type)) {
1032 1032
 //$var[$key] = $value;	// This is useless
1033 1033
                 } else {
1034
-                    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"]) . ')';
1034
+                    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"]).')';
1035 1035
                     exit;
1036 1036
                 }
1037 1037
             }
Please login to merge, or discard this patch.
Base/Langs.php 1 patch
Spacing   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -22,13 +22,13 @@  discard block
 block discarded – undo
22 22
 class Langs
23 23
 {
24 24
 
25
-    public $dir;                          // Directories that contains /langs subdirectory
26
-    public $defaultlang;                  // Current language for current user
27
-    public $charset_output = 'UTF-8';       // Codage used by "trans" method outputs
28
-    public $tab_translate = array();        // Array of all translations key=>value
29
-    private $_tab_loaded = array();         // Array to store result after loading each language file
30
-    public $cache_labels = array();         // Cache for labels return by getLabelFromKey method
31
-    public $cache_currencies = array();     // Cache to store currency symbols
25
+    public $dir; // Directories that contains /langs subdirectory
26
+    public $defaultlang; // Current language for current user
27
+    public $charset_output = 'UTF-8'; // Codage used by "trans" method outputs
28
+    public $tab_translate = array(); // Array of all translations key=>value
29
+    private $_tab_loaded = array(); // Array to store result after loading each language file
30
+    public $cache_labels = array(); // Cache for labels return by getLabelFromKey method
31
+    public $cache_currencies = array(); // Cache to store currency symbols
32 32
     private $cache_currencies_all_loaded = false;
33 33
 
34 34
     /**
@@ -61,13 +61,13 @@  discard block
 block discarded – undo
61 61
             $more = array();
62 62
             $i = 0;
63 63
             foreach (Globals::$conf->file->dol_document_root as $dir) {
64
-                $newdir = $dir . Globals::$conf->global->MAIN_FORCELANGDIR;    // For example Globals::$conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
64
+                $newdir = $dir.Globals::$conf->global->MAIN_FORCELANGDIR; // For example Globals::$conf->global->MAIN_FORCELANGDIR is '/mymodule' meaning we search files into '/mymodule/langs/xx_XX'
65 65
                 if (!in_array($newdir, $this->dir)) {
66
-                    $more['module_' . $i] = $newdir;
67
-                    $i++;   // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
66
+                    $more['module_'.$i] = $newdir;
67
+                    $i++; // We add the forced dir into the array $more. Just after, we add entries into $more to list of lang dir $this->dir.
68 68
                 }
69 69
             }
70
-            $this->dir = array_merge($more, $this->dir);    // Forced dir ($more) are before standard dirs ($this->dir)
70
+            $this->dir = array_merge($more, $this->dir); // Forced dir ($more) are before standard dirs ($this->dir)
71 71
         }
72 72
 
73 73
         $this->origlang = $srclang;
@@ -91,12 +91,12 @@  discard block
 block discarded – undo
91 91
             if (isset($longforshort[strtolower($langpart[0])]) && !in_array($codetouse, $longforshortexcep))
92 92
                 $srclang = $longforshort[strtolower($langpart[0])];
93 93
             else if (!is_numeric($langpart[1])) {  // Second part YY may be a numeric with some Chrome browser
94
-                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[1]);
94
+                $srclang = strtolower($langpart[0])."_".strtoupper($langpart[1]);
95 95
                 $longforlong = array('no_nb' => 'nb_NO');
96 96
                 if (isset($longforlong[strtolower($srclang)]))
97 97
                     $srclang = $longforlong[strtolower($srclang)];
98 98
             } else
99
-                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
99
+                $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
100 100
         }
101 101
         else {      // If it's for a codetouse that is a short code xx
102 102
             // Array to convert short lang code into long code.
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
             if (isset($longforshort[strtolower($langpart[0])]))
105 105
                 $srclang = $longforshort[strtolower($langpart[0])];
106 106
             else if (!empty($langpart[0]))
107
-                $srclang = strtolower($langpart[0]) . "_" . strtoupper($langpart[0]);
107
+                $srclang = strtolower($langpart[0])."_".strtoupper($langpart[0]);
108 108
             else
109 109
                 $srclang = 'en_US';
110 110
         }
@@ -168,11 +168,11 @@  discard block
 block discarded – undo
168 168
         //DolUtils::dol_syslog("Translate::Load Start domain=".$domain." alt=".$alt." forcelangdir=".$forcelangdir." this->defaultlang=".$this->defaultlang);
169 169
         // Check parameters
170 170
         if (empty($domain)) {
171
-            dol_print_error('', get_class($this) . "::Load ErrorWrongParameters");
171
+            dol_print_error('', get_class($this)."::Load ErrorWrongParameters");
172 172
             return -1;
173 173
         }
174 174
         if ($this->defaultlang == 'none_NONE')
175
-            return 0;    // Special language code to not translate keys
175
+            return 0; // Special language code to not translate keys
176 176
 
177 177
 
178 178
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
             
182 182
 // Load $this->tab_translate[] from database
183 183
         if (empty($loadfromfileonly) && count($this->tab_translate) == 0)
184
-            $this->loadFromDatabase($db);      // No translation was never loaded yet, so we load database.
184
+            $this->loadFromDatabase($db); // No translation was never loaded yet, so we load database.
185 185
 
186 186
 
187 187
         $newdomain = $domain;
@@ -210,13 +210,13 @@  discard block
 block discarded – undo
210 210
             $alt = 2;
211 211
 
212 212
         if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
213
-            DolUtils::dol_syslog("Error: " . get_class($this) . "::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
213
+            DolUtils::dol_syslog("Error: ".get_class($this)."::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
214 214
             return -1;
215 215
         }
216 216
 
217 217
         foreach ($this->dir as $keydir => $searchdir) {
218 218
             // Directory of translation files
219
-            $file_lang = $searchdir . ($modulename ? '/' . $modulename : '') . "/langs/" . $langofdir . "/" . $newdomain . ".lang";
219
+            $file_lang = $searchdir.($modulename ? '/'.$modulename : '')."/langs/".$langofdir."/".$newdomain.".lang";
220 220
             $file_lang_osencoded = dol_osencode($file_lang);
221 221
 
222 222
             $filelangexists = is_file($file_lang_osencoded);
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
                 $usecachekey = '';
233 233
                 // Using a memcached server
234 234
                 if (!empty(Globals::$conf->memcached->enabled) && !empty(Globals::$conf->global->MEMCACHED_SERVER)) {
235
-                    $usecachekey = $newdomain . '_' . $langofdir . '_' . md5($file_lang);    // Should not contains special chars
235
+                    $usecachekey = $newdomain.'_'.$langofdir.'_'.md5($file_lang); // Should not contains special chars
236 236
                 }
237 237
                 // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
238 238
                 else if (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) && (Globals::$conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
@@ -243,7 +243,7 @@  discard block
 block discarded – undo
243 243
                     //DolUtils::dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
244 244
                     //global $aaa; $aaa+=1;
245 245
                     //print $aaa." ".$usecachekey."\n";
246
-                    require_once DOL_BASE_PATH . '/core/lib/memory.lib.php';
246
+                    require_once DOL_BASE_PATH.'/core/lib/memory.lib.php';
247 247
                     $tmparray = dol_getcache($usecachekey);
248 248
                     if (is_array($tmparray) && count($tmparray)) {
249 249
                         $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a value already exists into tab_translate, value into tmparaay is not added.
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
                         //var_dump($this->tab_translate);
252 252
                         if ($alt == 2)
253 253
                             $fileread = 1;
254
-                        $found = true;      // Found in dolibarr PHP cache
254
+                        $found = true; // Found in dolibarr PHP cache
255 255
                     }
256 256
                 }
257 257
 
@@ -301,13 +301,13 @@  discard block
 block discarded – undo
301 301
                         if ($usecachekey && count($tabtranslatedomain)) {
302 302
                             $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
303 303
                             if ($ressetcache < 0) {
304
-                                $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
304
+                                $error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
305 305
                                 DolUtils::dol_syslog($error, LOG_ERR);
306 306
                             }
307 307
                         }
308 308
 
309 309
                         if (empty(Globals::$conf->global->MAIN_FORCELANGDIR))
310
-                            break;  // Break loop on each root dir. If a module has forced dir, we do not stop loop.
310
+                            break; // Break loop on each root dir. If a module has forced dir, we do not stop loop.
311 311
                     }
312 312
                 }
313 313
             }
@@ -317,11 +317,11 @@  discard block
 block discarded – undo
317 317
         if ($alt == 0) {
318 318
             // This function MUST NOT contains call to syslog
319 319
             //DolUtils::dol_syslog("Translate::Load loading alternate translation file (to complete ".$this->defaultlang."/".$newdomain.".lang file)", LOG_DEBUG);
320
-            $langofdir = strtolower($langarray[0]) . '_' . strtoupper($langarray[0]);
320
+            $langofdir = strtolower($langarray[0]).'_'.strtoupper($langarray[0]);
321 321
             if ($langofdir == 'el_EL')
322
-                $langofdir = 'el_GR';                     // main parent for el_CY is not 'el_EL' but 'el_GR'
322
+                $langofdir = 'el_GR'; // main parent for el_CY is not 'el_EL' but 'el_GR'
323 323
             if ($langofdir == 'ar_AR')
324
-                $langofdir = 'ar_SA';                     // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
324
+                $langofdir = 'ar_SA'; // main parent for ar_EG is not 'ar_AR' but 'ar_SA'
325 325
             $this->load($domain, $alt + 1, $stopafterdirection, $langofdir);
326 326
         }
327 327
 
@@ -336,7 +336,7 @@  discard block
 block discarded – undo
336 336
         // We are in the pass of the reference file. No more files to scan to complete.
337 337
         if ($alt == 2) {
338 338
             if ($fileread)
339
-                $this->_tab_loaded[$newdomain] = 1;        // Set domain file as found so loaded
339
+                $this->_tab_loaded[$newdomain] = 1; // Set domain file as found so loaded
340 340
 
341 341
             if (empty($this->_tab_loaded[$newdomain]))
342 342
                 $this->_tab_loaded[$newdomain] = 2; // Set this file as not found
@@ -345,7 +345,7 @@  discard block
 block discarded – undo
345 345
         // This part is deprecated and replaced with table llx_overwrite_trans
346 346
         // Kept for backward compatibility.
347 347
         if (empty($loadfromfileonly)) {
348
-            $overwritekey = 'MAIN_OVERWRITE_TRANS_' . $this->defaultlang;
348
+            $overwritekey = 'MAIN_OVERWRITE_TRANS_'.$this->defaultlang;
349 349
             if (!empty(Globals::$conf->global->$overwritekey)) {    // Overwrite translation with key1:newstring1,key2:newstring2
350 350
                 // Overwrite translation with param MAIN_OVERWRITE_TRANS_xx_XX
351 351
                 $tmparray = explode(',', Globals::$conf->global->$overwritekey);
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 
385 385
         // Check parameters
386 386
         if (empty($db))
387
-            return 0;    // Database handler can't be used
387
+            return 0; // Database handler can't be used
388 388
 
389 389
 
390 390
 
@@ -401,13 +401,13 @@  discard block
 block discarded – undo
401 401
             return 0;
402 402
         }
403 403
 
404
-        $this->_tab_loaded[$newdomain] = 1;   // We want to be sure this function is called once only for domain 'database'
404
+        $this->_tab_loaded[$newdomain] = 1; // We want to be sure this function is called once only for domain 'database'
405 405
 
406 406
         $fileread = 0;
407 407
         $langofdir = $this->defaultlang;
408 408
 
409 409
         if (empty($langofdir)) { // This may occurs when load is called without setting the language and without providing a value for forcelangdir
410
-            DolUtils::dol_syslog("Error: " . get_class($this) . "::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
410
+            DolUtils::dol_syslog("Error: ".get_class($this)."::Load was called but language was not set yet with langs->setDefaultLang(). Nothing will be loaded.", LOG_WARNING);
411 411
             return -1;
412 412
         }
413 413
 
@@ -418,7 +418,7 @@  discard block
 block discarded – undo
418 418
         $usecachekey = '';
419 419
         // Using a memcached server
420 420
         if (!empty(Globals::$conf->memcached->enabled) && !empty(Globals::$conf->global->MEMCACHED_SERVER)) {
421
-            $usecachekey = $newdomain . '_' . $langofdir;    // Should not contains special chars
421
+            $usecachekey = $newdomain.'_'.$langofdir; // Should not contains special chars
422 422
         }
423 423
         // Using cache with shmop. Speed gain: 40ms - Memory overusage: 200ko (Size of session cache file)
424 424
         else if (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) && (Globals::$conf->global->MAIN_OPTIMIZE_SPEED & 0x02)) {
@@ -429,20 +429,20 @@  discard block
 block discarded – undo
429 429
             //DolUtils::dol_syslog('Translate::Load we will cache result into usecachekey '.$usecachekey);
430 430
             //global $aaa; $aaa+=1;
431 431
             //print $aaa." ".$usecachekey."\n";
432
-            require_once DOL_BASE_PATH . '/core/lib/memory.lib.php';
432
+            require_once DOL_BASE_PATH.'/core/lib/memory.lib.php';
433 433
             $tmparray = dol_getcache($usecachekey);
434 434
             if (is_array($tmparray) && count($tmparray)) {
435 435
                 $this->tab_translate += $tmparray; // Faster than array_merge($tmparray,$this->tab_translate). Note: If a valuer already exists into tab_translate, value into tmparaay is not added.
436 436
                 //print $newdomain."\n";
437 437
                 //var_dump($this->tab_translate);
438 438
                 $fileread = 1;
439
-                $found = true;      // Found in dolibarr PHP cache
439
+                $found = true; // Found in dolibarr PHP cache
440 440
             }
441 441
         }
442 442
 
443 443
         if (!$found && !empty(Globals::$conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) {
444 444
             // Overwrite translation with database read
445
-            $sql = "SELECT transkey, transvalue FROM " . MAIN_DB_PREFIX . "overwrite_trans where lang='" . $db->escape($this->defaultlang) . "'";
445
+            $sql = "SELECT transkey, transvalue FROM ".MAIN_DB_PREFIX."overwrite_trans where lang='".$db->escape($this->defaultlang)."'";
446 446
             $resql = $db->query($sql);
447 447
 
448 448
             if ($resql) {
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
                     if ($usecachekey && count($tabtranslatedomain)) {
478 478
                         $ressetcache = dol_setcache($usecachekey, $tabtranslatedomain);
479 479
                         if ($ressetcache < 0) {
480
-                            $error = 'Failed to set cache for usecachekey=' . $usecachekey . ' result=' . $ressetcache;
480
+                            $error = 'Failed to set cache for usecachekey='.$usecachekey.' result='.$ressetcache;
481 481
                             DolUtils::dol_syslog($error, LOG_ERR);
482 482
                         }
483 483
                     }
@@ -491,7 +491,7 @@  discard block
 block discarded – undo
491 491
             $this->_tab_loaded[$newdomain] = 1; // Set domain file as loaded
492 492
 
493 493
         if (empty($this->_tab_loaded[$newdomain]))
494
-            $this->_tab_loaded[$newdomain] = 2;           // Marque ce cas comme non trouve (no lines found for language)
494
+            $this->_tab_loaded[$newdomain] = 2; // Marque ce cas comme non trouve (no lines found for language)
495 495
 
496 496
         return 1;
497 497
     }
@@ -561,12 +561,12 @@  discard block
 block discarded – undo
561 561
             $str = $this->tab_translate[$key];
562 562
 
563 563
             // Make some string replacement after translation
564
-            $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
564
+            $replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang;
565 565
             if (!empty(Globals::$conf->global->$replacekey)) {    // Replacement translation variable with string1:newstring1;string2:newstring2
566 566
                 $tmparray = explode(';', Globals::$conf->global->$replacekey);
567 567
                 foreach ($tmparray as $tmp) {
568 568
                     $tmparray2 = explode(':', $tmp);
569
-                    $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
569
+                    $str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str);
570 570
                 }
571 571
             }
572 572
 
@@ -636,12 +636,12 @@  discard block
 block discarded – undo
636 636
             $str = $this->tab_translate[$key];
637 637
 
638 638
             // Make some string replacement after translation
639
-            $replacekey = 'MAIN_REPLACE_TRANS_' . $this->defaultlang;
639
+            $replacekey = 'MAIN_REPLACE_TRANS_'.$this->defaultlang;
640 640
             if (!empty(Globals::$conf->global->$replacekey)) {    // Replacement translation variable with string1:newstring1;string2:newstring2
641 641
                 $tmparray = explode(';', Globals::$conf->global->$replacekey);
642 642
                 foreach ($tmparray as $tmp) {
643 643
                     $tmparray2 = explode(':', $tmp);
644
-                    $str = preg_replace('/' . preg_quote($tmparray2[0]) . '/', $tmparray2[1], $str);
644
+                    $str = preg_replace('/'.preg_quote($tmparray2[0]).'/', $tmparray2[1], $str);
645 645
                 }
646 646
             }
647 647
 
@@ -724,7 +724,7 @@  discard block
 block discarded – undo
724 724
         }
725 725
 
726 726
         // We scan directory langs to detect available languages
727
-        $handle = opendir($langdir . "/langs");
727
+        $handle = opendir($langdir."/langs");
728 728
         $langs_available = array();
729 729
         while ($dir = trim(readdir($handle))) {
730 730
             if (preg_match('/^[a-z]+_[A-Z]+/i', $dir)) {
@@ -734,9 +734,9 @@  discard block
 block discarded – undo
734 734
                     $langs_available[$dir] = $dir;
735 735
                 }
736 736
                 if ($usecode == 1 || !empty(Globals::$conf->global->MAIN_SHOW_LANGUAGE_CODE)) {
737
-                    $langs_available[$dir] = $dir . ': ' . dol_trunc($this->trans('Language_' . $dir), $maxlength);
737
+                    $langs_available[$dir] = $dir.': '.dol_trunc($this->trans('Language_'.$dir), $maxlength);
738 738
                 } else {
739
-                    $langs_available[$dir] = $this->trans('Language_' . $dir);
739
+                    $langs_available[$dir] = $this->trans('Language_'.$dir);
740 740
                 }
741 741
             }
742 742
         }
@@ -756,13 +756,13 @@  discard block
 block discarded – undo
756 756
         // phpcs:enable
757 757
         // Test si fichier dans repertoire de la langue
758 758
         foreach ($this->dir as $searchdir) {
759
-            if (is_readable(dol_osencode($searchdir . "/langs/" . $this->defaultlang . "/" . $filename)))
759
+            if (is_readable(dol_osencode($searchdir."/langs/".$this->defaultlang."/".$filename)))
760 760
                 return true;
761 761
 
762 762
             if ($searchalt) {
763 763
                 // Test si fichier dans repertoire de la langue alternative
764 764
                 if ($this->defaultlang != "en_US")
765
-                    $filenamealt = $searchdir . "/langs/en_US/" . $filename;
765
+                    $filenamealt = $searchdir."/langs/en_US/".$filename;
766 766
                 //else $filenamealt = $searchdir."/langs/fr_FR/".$filename;
767 767
                 if (is_readable(dol_osencode($filenamealt)))
768 768
                     return true;
@@ -799,8 +799,8 @@  discard block
 block discarded – undo
799 799
                 continue; // We must not use dol_is_dir here, function may not be loaded
800 800
 
801 801
             $fonc = 'numberwords';
802
-            if (file_exists($newdir . '/functions_' . $fonc . '.lib.php')) {
803
-                include_once $newdir . '/functions_' . $fonc . '.lib.php';
802
+            if (file_exists($newdir.'/functions_'.$fonc.'.lib.php')) {
803
+                include_once $newdir.'/functions_'.$fonc.'.lib.php';
804 804
                 $newnumber = numberwords_getLabelFromNumber($this, $number, $isamount);
805 805
                 break;
806 806
             }
@@ -834,20 +834,20 @@  discard block
 block discarded – undo
834 834
         // Check if a translation is available (this can call getTradFromKey)
835 835
         $tmp = $this->transnoentitiesnoconv($key);
836 836
         if ($tmp != $key && $tmp != 'ErrorBadValueForParamNotAString') {
837
-            return $tmp;    // Found in language array
837
+            return $tmp; // Found in language array
838 838
         }
839 839
 
840 840
         // Check in cache
841 841
         if (isset($this->cache_labels[$tablename][$key])) { // Can be defined to 0 or ''
842
-            return $this->cache_labels[$tablename][$key];   // Found in cache
842
+            return $this->cache_labels[$tablename][$key]; // Found in cache
843 843
         }
844 844
 
845
-        $sql = "SELECT " . $fieldlabel . " as label";
846
-        $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
847
-        $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($keyforselect ? $keyforselect : $key) . "'";
845
+        $sql = "SELECT ".$fieldlabel." as label";
846
+        $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
847
+        $sql .= " WHERE ".$fieldkey." = '".$db->escape($keyforselect ? $keyforselect : $key)."'";
848 848
         if ($filteronentity)
849
-            $sql .= " AND entity IN (" . getEntity($tablename) . ')';
850
-        DolUtils::dol_syslog(get_class($this) . '::getLabelFromKey', LOG_DEBUG);
849
+            $sql .= " AND entity IN (".getEntity($tablename).')';
850
+        DolUtils::dol_syslog(get_class($this).'::getLabelFromKey', LOG_DEBUG);
851 851
         $resql = $db->query($sql);
852 852
         if ($resql) {
853 853
             $obj = $db->fetch_object($resql);
@@ -879,9 +879,9 @@  discard block
 block discarded – undo
879 879
         $symbol = $this->getCurrencySymbol($currency_code);
880 880
 
881 881
         if (in_array($currency_code, array('USD')))
882
-            return $symbol . $amount;
882
+            return $symbol.$amount;
883 883
         else
884
-            return $amount . $symbol;
884
+            return $amount.$symbol;
885 885
     }
886 886
 
887 887
     /**
@@ -920,18 +920,18 @@  discard block
 block discarded – undo
920 920
         global $db;
921 921
 
922 922
         if ($this->cache_currencies_all_loaded)
923
-            return 0;                                           // Cache already loaded for all
923
+            return 0; // Cache already loaded for all
924 924
         if (!empty($currency_code) && isset($this->cache_currencies[$currency_code]))
925
-            return 0;    // Cache already loaded for the currency
925
+            return 0; // Cache already loaded for the currency
926 926
 
927 927
         $sql = "SELECT code_iso, label, unicode";
928
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_currencies";
928
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies";
929 929
         $sql .= " WHERE active = 1";
930 930
         if (!empty($currency_code))
931
-            $sql .= " AND code_iso = '" . $db->escape($currency_code) . "'";
931
+            $sql .= " AND code_iso = '".$db->escape($currency_code)."'";
932 932
         //$sql.= " ORDER BY code_iso ASC"; // Not required, a sort is done later
933 933
 
934
-        DolUtils::dol_syslog(get_class($this) . '::loadCacheCurrencies', LOG_DEBUG);
934
+        DolUtils::dol_syslog(get_class($this).'::loadCacheCurrencies', LOG_DEBUG);
935 935
         $resql = $db->query($sql);
936 936
         if ($resql) {
937 937
             $this->load("dict");
@@ -946,7 +946,7 @@  discard block
 block discarded – undo
946 946
                 $obj = $db->fetch_object($resql);
947 947
 
948 948
                 // Si traduction existe, on l'utilise, sinon on prend le libelle par defaut
949
-                $this->cache_currencies[$obj->code_iso]['label'] = ($obj->code_iso && $this->trans("Currency" . $obj->code_iso) != "Currency" . $obj->code_iso ? $this->trans("Currency" . $obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
949
+                $this->cache_currencies[$obj->code_iso]['label'] = ($obj->code_iso && $this->trans("Currency".$obj->code_iso) != "Currency".$obj->code_iso ? $this->trans("Currency".$obj->code_iso) : ($obj->label != '-' ? $obj->label : ''));
950 950
                 $this->cache_currencies[$obj->code_iso]['unicode'] = (array) json_decode($obj->unicode, true);
951 951
                 $label[$obj->code_iso] = $this->cache_currencies[$obj->code_iso]['label'];
952 952
                 $i++;
@@ -978,8 +978,8 @@  discard block
 block discarded – undo
978 978
         $substitutionarray = array();
979 979
 
980 980
         foreach ($this->tab_translate as $code => $label) {
981
-            $substitutionarray['lang_' . $code] = $label;
982
-            $substitutionarray['__(' . $code . ')__'] = $label;
981
+            $substitutionarray['lang_'.$code] = $label;
982
+            $substitutionarray['__('.$code.')__'] = $label;
983 983
         }
984 984
 
985 985
         return $substitutionarray;
Please login to merge, or discard this patch.
Base/AlixarView.php 1 patch
Spacing   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 // html header
126 126
         $this->top_htmlhead(/* $this->head, $this->title, $this->disablejs, $this->disablehead, $this->arrayofjs, $this->arrayofcss */);
127 127
 
128
-        print '<body id="mainbody"' . ($this->morecssonbody ? ' class="' . $this->morecssonbody . '"' : '') . '>' . "\n";
128
+        print '<body id="mainbody"'.($this->morecssonbody ? ' class="'.$this->morecssonbody.'"' : '').'>'."\n";
129 129
 
130 130
 // top menu and left menu area
131 131
         if (empty(Globals::$conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) {
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 
135 135
         if (empty(Globals::$conf->dol_hide_leftmenu)) {
136 136
             //$this->left_menu('', $this->help_url, '', '', 1, $this->title, 1);  // $menumanager is retreived with a global $menumanager inside this function
137
-            $this->left_menu('', /* $this->help_url, */ '', '', 1, /* $this->title, */ 1);  // $menumanager is retreived with a global $menumanager inside this function
137
+            $this->left_menu('', /* $this->help_url, */ '', '', 1, /* $this->title, */ 1); // $menumanager is retreived with a global $menumanager inside this function
138 138
         }
139 139
 
140 140
 // main area
@@ -185,13 +185,13 @@  discard block
 block discarded – undo
185 185
          * Top menu
186 186
          */
187 187
         if ((empty(Globals::$conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
188
-            print "\n" . '<!-- Start top horizontal -->' . "\n";
188
+            print "\n".'<!-- Start top horizontal -->'."\n";
189 189
 
190
-            print '<div class="side-nav-vert' . (DolUtils::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.
190
+            print '<div class="side-nav-vert'.(DolUtils::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.
191 191
 // Show menu entries
192
-            print '<div id="tmenu_tooltip' . (empty(Globals::$conf->global->MAIN_MENU_INVERT) ? '' : 'invert') . '" class="tmenu">' . "\n";
192
+            print '<div id="tmenu_tooltip'.(empty(Globals::$conf->global->MAIN_MENU_INVERT) ? '' : 'invert').'" class="tmenu">'."\n";
193 193
             Globals::$menuManager->atarget = $this->target;
194
-            Globals::$menuManager->showmenu('top', array('searchform' => $searchform, 'bookmarks' => $bookmarks));      // This contains a \n
194
+            Globals::$menuManager->showmenu('top', array('searchform' => $searchform, 'bookmarks' => $bookmarks)); // This contains a \n
195 195
             print "</div>\n";
196 196
 
197 197
 // Define link to login card
@@ -199,36 +199,36 @@  discard block
 block discarded – undo
199 199
             if (!empty(Globals::$conf->global->MAIN_APPLICATION_TITLE)) {
200 200
                 $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
201 201
                 if (preg_match('/\d\.\d/', $appli)) {
202
-                    if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli))
203
-                        $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
202
+                    if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli))
203
+                        $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
204 204
                 } else
205
-                    $appli .= " " . DOL_VERSION;
205
+                    $appli .= " ".DOL_VERSION;
206 206
             } else
207
-                $appli .= " " . DOL_VERSION;
207
+                $appli .= " ".DOL_VERSION;
208 208
 
209 209
             if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL))
210
-                $appli .= "<br>" . Globals::$langs->trans("LevelOfFeature") . ': ' . Globals::$conf->global->MAIN_FEATURES_LEVEL;
210
+                $appli .= "<br>".Globals::$langs->trans("LevelOfFeature").': '.Globals::$conf->global->MAIN_FEATURES_LEVEL;
211 211
 
212 212
             $logouttext = '';
213 213
             if (empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
214 214
 //$logouthtmltext=$appli.'<br>';
215 215
                 $logouthtmltext = '';
216 216
                 if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { {
217
-                        $logouthtmltext .= Globals::$langs->trans("Logout") . '<br>';
217
+                        $logouthtmltext .= Globals::$langs->trans("Logout").'<br>';
218 218
                     }
219 219
 
220 220
 //$logouttext .='<a accesskey="l" href="'.DOL_BASE_URI.'/user/logout.php">';
221
-                    $logouttext .= '<a accesskey="l" href="' . BASE_URI . '?controller=user&method=logout">';
221
+                    $logouttext .= '<a accesskey="l" href="'.BASE_URI.'?controller=user&method=logout">';
222 222
 //$logouttext .= img_picto(Globals::$langs->trans('Logout').":".Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
223 223
                     $logouttext .= '<span class="fa fa-sign-out atoplogin"></span>';
224 224
                     $logouttext .= '</a>';
225 225
                 } else {
226 226
                     $logouthtmltext .= Globals::$langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
227
-                    $logouttext .= img_picto(Globals::$langs->trans('Logout') . ":" . Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
227
+                    $logouttext .= img_picto(Globals::$langs->trans('Logout').":".Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
228 228
                 }
229 229
             }
230 230
 
231
-            print '<div class="login_block">' . "\n";
231
+            print '<div class="login_block">'."\n";
232 232
 
233 233
 // Add login user link
234 234
             $toprightmenu .= '<div class="login_block_user">';
@@ -239,18 +239,18 @@  discard block
 block discarded – undo
239 239
             $toprightmenu .= Globals::$user->getNomUrl($mode, '', 1, 0, 11, 0, (Globals::$user->firstname ? 'firstname' : -1), 'atoplogin');
240 240
             $toprightmenu .= '</div></div>';
241 241
 
242
-            $toprightmenu .= '</div>' . "\n";
242
+            $toprightmenu .= '</div>'."\n";
243 243
 
244 244
             $toprightmenu .= '<div class="login_block_other">';
245 245
 
246 246
 // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
247 247
             $parameters = array();
248
-            $result = Globals::$hookManager->executeHooks('printTopRightMenu', $parameters);    // Note that $action and $object may have been modified by some hooks
248
+            $result = Globals::$hookManager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
249 249
             if (is_numeric($result)) {
250 250
                 if ($result == 0)
251
-                    $toprightmenu .= Globals::$hookManager->resPrint;  // add
251
+                    $toprightmenu .= Globals::$hookManager->resPrint; // add
252 252
                 else
253
-                    $toprightmenu = Globals::$hookManager->resPrint;      // replace
253
+                    $toprightmenu = Globals::$hookManager->resPrint; // replace
254 254
             }
255 255
             else {
256 256
                 $toprightmenu .= $result; // For backward compatibility
@@ -259,7 +259,7 @@  discard block
 block discarded – undo
259 259
 // Link to module builder
260 260
             if (!empty(Globals::$conf->modulebuilder->enabled)) {
261 261
 //$text = '<a href="' . DOL_BASE_URI . '/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
262
-                $text = '<a href="' . BASE_URI . '?controller=modulebuilder&method=index&mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
262
+                $text = '<a href="'.BASE_URI.'?controller=modulebuilder&method=index&mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
263 263
 //$text.= img_picto(":".Globals::$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
264 264
                 $text .= '<span class="fa fa-bug atoplogin"></span>';
265 265
                 $text .= '</a>';
@@ -273,12 +273,12 @@  discard block
 block discarded – undo
273 273
                 if (is_array($_POST)) {
274 274
                     foreach ($_POST as $key => $value) {
275 275
                         if ($key !== 'action' && $key !== 'password' && !is_array($value)) {
276
-                            $qs .= '&' . $key . '=' . urlencode($value);
276
+                            $qs .= '&'.$key.'='.urlencode($value);
277 277
                         }
278 278
                     }
279 279
                 }
280
-                $qs .= (($qs && $this->morequerystring) ? '&' : '') . $this->morequerystring;
281
-                $text = '<a href="' . DolUtils::dol_escape_htmltag($_SERVER["PHP_SELF"]) . '?' . $qs . ($qs ? '&' : '') . 'optioncss=print" target="_blank">';
280
+                $qs .= (($qs && $this->morequerystring) ? '&' : '').$this->morequerystring;
281
+                $text = '<a href="'.DolUtils::dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank">';
282 282
 //$text.= img_picto(":".Globals::$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
283 283
                 $text .= '<span class="fa fa-print atoplogin"></span>';
284 284
                 $text .= '</a>';
@@ -307,12 +307,12 @@  discard block
 block discarded – undo
307 307
                     $text = '';
308 308
                     if (!empty(Globals::$conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
309 309
                         Globals::$langs->load('admin');
310
-                        $appli .= '<br>' . Globals::$langs->trans("Database") . ': ' . $db->database_name;
310
+                        $appli .= '<br>'.Globals::$langs->trans("Database").': '.$db->database_name;
311 311
                     }
312
-                    $this->title = $appli . '<br>';
312
+                    $this->title = $appli.'<br>';
313 313
                     $this->title .= Globals::$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage');
314 314
                     if ($mode == 'wiki') {
315
-                        $this->title .= ' - ' . Globals::$langs->trans("PageWiki") . ' &quot;' . DolUtils::dol_escape_htmltag(strtr($helppage, '_', ' ')) . '&quot;';
315
+                        $this->title .= ' - '.Globals::$langs->trans("PageWiki").' &quot;'.DolUtils::dol_escape_htmltag(strtr($helppage, '_', ' ')).'&quot;';
316 316
                     }
317 317
                     $text .= '<a class="help" target="_blank" rel="noopener" href="';
318 318
                     if ($mode == 'wiki') {
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
 
339 339
             print $toprightmenu;
340 340
 
341
-            print "</div>\n";  // end div class="login_block"
341
+            print "</div>\n"; // end div class="login_block"
342 342
 
343 343
             print '</div></div>';
344 344
 
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
         }
348 348
 
349 349
         if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile)) {
350
-            print '<!-- Begin div id-container --><div id="id-container" class="id-container' . (isset($morecss) && $morecss ? ' ' . $morecss : '') . '">';
350
+            print '<!-- Begin div id-container --><div id="id-container" class="id-container'.(isset($morecss) && $morecss ? ' '.$morecss : '').'">';
351 351
         }
352 352
     }
353 353
 
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
             // Instantiate hooks of thirdparty module
381 381
             Globals::$hookManager->initHooks(array('searchform', 'leftblock'));
382 382
 
383
-            print "\n" . '<!-- Begin side-nav id-left -->' . "\n" . '<div class="side-nav"><div id="id-left">' . "\n";
383
+            print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
384 384
 
385 385
             if (Globals::$conf->browser->layout == 'phone') {
386 386
                 Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 // Execute hook printSearchForm
410 410
             $parameters = array('searchform' => $searchform);
411 411
 
412
-            $reshook = Globals::$hookManager->executeHooks('printSearchForm', $parameters);    // Note that $action and $object may have been modified by some hooks
412
+            $reshook = Globals::$hookManager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
413 413
             if (empty($reshook)) {
414 414
                 $searchform .= Globals::$hookManager->resPrint;
415 415
             } else
@@ -417,10 +417,10 @@  discard block
 block discarded – undo
417 417
 
418 418
 // Force special value for $searchform
419 419
             if (!empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty(Globals::$conf->use_javascript_ajax)) {
420
-                $urltosearch = DOL_BASE_URI . '/core/search_page.php?showtitlebefore=1';
421
-                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="' . $urltosearch . '" alt="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")) . '">' . Globals::$langs->trans("Search") . '...</a></div></div>';
420
+                $urltosearch = DOL_BASE_URI.'/core/search_page.php?showtitlebefore=1';
421
+                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.DolUtils::dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")).'">'.Globals::$langs->trans("Search").'...</a></div></div>';
422 422
             } elseif (Globals::$conf->use_javascript_ajax && !empty(Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM)) {
423
-                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")) . '">' . Globals::$langs->trans("Search") . '...</a></div><div id="divsearchforms2" style="display: none">' . $searchform . '</div>';
423
+                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.DolUtils::dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")).'">'.Globals::$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
424 424
                 $searchform .= '<script type="text/javascript">
425 425
             	jQuery(document).ready(function () {
426 426
             		jQuery("#divsearchforms1").click(function(){
@@ -433,16 +433,16 @@  discard block
 block discarded – undo
433 433
 
434 434
 // Define $bookmarks
435 435
             if (!empty(Globals::$conf->bookmark->enabled) && Globals::$user->rights->bookmark->lire) {
436
-                include_once DOL_BASE_PATH . '/bookmarks/bookmarks.lib.php';
436
+                include_once DOL_BASE_PATH.'/bookmarks/bookmarks.lib.php';
437 437
                 Globals::$langs->load("bookmarks");
438 438
 
439 439
                 $bookmarks = printBookmarksList($db, Globals::$langs);
440 440
             }
441 441
 
442 442
 // Left column
443
-            print '<!-- Begin left menu -->' . "\n";
443
+            print '<!-- Begin left menu -->'."\n";
444 444
 
445
-            print '<div class="vmenu"' . (empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"') . '>' . "\n\n";
445
+            print '<div class="vmenu"'.(empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"').'>'."\n\n";
446 446
 
447 447
 // Show left menu with other forms
448 448
             Globals::$menuManager->menu_array = $menu_array_before;
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 // Dolibarr version + help + bug report link
452 452
             print "\n";
453 453
             print "<!-- Begin Help Block-->\n";
454
-            print '<div id="blockvmenuhelp" class="blockvmenuhelp">' . "\n";
454
+            print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
455 455
 
456 456
 // Version
457 457
             if (empty(Globals::$conf->global->MAIN_HIDE_VERSION)) {    // Version is already on help picto and on login page.
@@ -478,18 +478,18 @@  discard block
 block discarded – undo
478 478
                     $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
479 479
                     $doliurl = '';
480 480
                     if (preg_match('/\d\.\d/', $appli)) {
481
-                        if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
482
-                            $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
481
+                        if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) {
482
+                            $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
483 483
                         }
484 484
                     } else {
485
-                        $appli .= " " . DOL_VERSION;
485
+                        $appli .= " ".DOL_VERSION;
486 486
                     }
487 487
                 } else {
488
-                    $appli .= " " . DOL_VERSION;
488
+                    $appli .= " ".DOL_VERSION;
489 489
                 }
490 490
                 print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
491 491
                 if ($doliurl) {
492
-                    print '<a class="help" target="_blank" rel="noopener" href="' . $doliurl . '">';
492
+                    print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
493 493
                 } else {
494 494
                     print '<span class="help">';
495 495
                 }
@@ -499,12 +499,12 @@  discard block
 block discarded – undo
499 499
                 } else {
500 500
                     print '</span>';
501 501
                 }
502
-                print '</div>' . "\n";
502
+                print '</div>'."\n";
503 503
             }
504 504
 
505 505
 // Link to bugtrack
506 506
             if (!empty(Globals::$conf->global->MAIN_BUGTRACK_ENABLELINK)) {
507
-                require_once DOL_BASE_PATH . '/core/lib/functions2.lib.php';
507
+                require_once DOL_BASE_PATH.'/core/lib/functions2.lib.php';
508 508
 
509 509
                 $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
510 510
                 $bugbaseurl .= '?title=';
@@ -513,16 +513,16 @@  discard block
 block discarded – undo
513 513
                 $bugbaseurl .= urlencode("# Bug\n");
514 514
                 $bugbaseurl .= urlencode("\n");
515 515
                 $bugbaseurl .= urlencode("## Environment\n");
516
-                $bugbaseurl .= urlencode("- **Version**: " . DOL_VERSION . "\n");
517
-                $bugbaseurl .= urlencode("- **OS**: " . php_uname('s') . "\n");
518
-                $bugbaseurl .= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
519
-                $bugbaseurl .= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
520
-                $bugbaseurl .= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
521
-                $bugbaseurl .= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
516
+                $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
517
+                $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
518
+                $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
519
+                $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
520
+                $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
521
+                $bugbaseurl .= urlencode("- **URL**: ".$_SERVER["REQUEST_URI"]."\n");
522 522
                 $bugbaseurl .= urlencode("\n");
523 523
                 $bugbaseurl .= urlencode("## Report\n");
524 524
                 print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
525
-                print '<a class="help" target="_blank" rel="noopener" href="' . $bugbaseurl . '">' . Globals::$langs->trans("FindBug") . '</a>';
525
+                print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.Globals::$langs->trans("FindBug").'</a>';
526 526
                 print '</div>';
527 527
             }
528 528
 
@@ -536,14 +536,14 @@  discard block
 block discarded – undo
536 536
 
537 537
 // Execute hook printLeftBlock
538 538
             $parameters = array();
539
-            $reshook = Globals::$hookManager->executeHooks('printLeftBlock', $parameters);    // Note that $action and $object may have been modified by some hooks
539
+            $reshook = Globals::$hookManager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
540 540
             print Globals::$hookManager->resPrint;
541 541
 
542 542
             print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
543 543
         }
544 544
 
545 545
         print "\n";
546
-        print '<!-- Begin right area -->' . "\n";
546
+        print '<!-- Begin right area -->'."\n";
547 547
 
548 548
         if (empty($leftmenuwithoutmainarea)) {
549 549
             main_area($this->title);
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 
567 567
         print "\n";
568 568
 
569
-        print '<!-- Begin div class="fiche" -->' . "\n" . '<div class="fiche">' . "\n";
569
+        print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
570 570
 
571 571
         if (!empty(Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED)) {
572 572
             print info_admin(Globals::$langs->trans("WarningYouAreInMaintenanceMode", Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
@@ -633,18 +633,18 @@  discard block
 block discarded – undo
633 633
 // global Globals::$conf, Globals::$langs, Globals::$user;
634 634
 
635 635
         $ret = '';
636
-        $ret .= '<form action="' . $urlaction . '" method="post" class="searchform">';
637
-        $ret .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
636
+        $ret .= '<form action="'.$urlaction.'" method="post" class="searchform">';
637
+        $ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
638 638
         $ret .= '<input type="hidden" name="mode" value="search">';
639
-        $ret .= '<input type="hidden" name="savelogin" value="' . DolUtils::dol_escape_htmltag(Globals::$user->login) . '">';
639
+        $ret .= '<input type="hidden" name="savelogin" value="'.DolUtils::dol_escape_htmltag(Globals::$user->login).'">';
640 640
         if ($showtitlebefore) {
641
-            $ret .= $this->title . ' ';
641
+            $ret .= $this->title.' ';
642 642
         }
643
-        $ret .= '<input type="text" class="flat ' . $htmlmorecss . '"';
644
-        $ret .= ' style="text-indent: 22px; background-image: url(\'' . $img . '\'); background-repeat: no-repeat; background-position: 3px;"';
645
-        $ret .= ($accesskey ? ' accesskey="' . $accesskey . '"' : '');
646
-        $ret .= ' placeholder="' . strip_tags($this->title) . '"';
647
-        $ret .= ' name="' . $htmlinputname . '" id="' . $prefhtmlinputname . $htmlinputname . '" />';
643
+        $ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
644
+        $ret .= ' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
645
+        $ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
646
+        $ret .= ' placeholder="'.strip_tags($this->title).'"';
647
+        $ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
648 648
         //$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.Globals::$langs->trans("Go").'">';
649 649
         $ret .= '<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
650 650
         $ret .= '<span class="fa fa-search"></span>';
@@ -669,7 +669,7 @@  discard block
 block discarded – undo
669 669
 // global $delayedhtmlcontent;
670 670
 // global $contextpage, $page, $limit;
671 671
 
672
-        $ext = 'layout=' . Globals::$conf->browser->layout . '&version=' . urlencode(DOL_VERSION);
672
+        $ext = 'layout='.Globals::$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
673 673
 
674 674
 // Global html output events ($mesgs, $errors, $warnings)
675 675
         DolUtils::dol_htmloutput_events($disabledoutputofmessages);
@@ -679,7 +679,7 @@  discard block
 block discarded – undo
679 679
         if (is_object(Globals::$user) && !empty(Globals::$user->lastsearch_values_tmp) && is_array(Globals::$user->lastsearch_values_tmp)) {
680 680
 // Clean and save data
681 681
             foreach (Globals::$user->lastsearch_values_tmp as $key => $val) {
682
-                unset($_SESSION['lastsearch_values_tmp_' . $key]);   // Clean array to rebuild it just after
682
+                unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
683 683
                 if (count($val) && empty($_POST['button_removefilter'])) { // If there is search criteria to save and we did not click on 'Clear filter' button
684 684
                     if (empty($val['sortfield'])) {
685 685
                         unset($val['sortfield']);
@@ -687,9 +687,9 @@  discard block
 block discarded – undo
687 687
                     if (empty($val['sortorder'])) {
688 688
                         unset($val['sortorder']);
689 689
                     }
690
-                    dol_syslog('Save lastsearch_values_tmp_' . $key . '=' . json_encode($val, 0) . " (systematic recording of last search criterias)");
691
-                    $_SESSION['lastsearch_values_tmp_' . $key] = json_encode($val);
692
-                    unset($_SESSION['lastsearch_values_' . $key]);
690
+                    dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
691
+                    $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
692
+                    unset($_SESSION['lastsearch_values_'.$key]);
693 693
                 }
694 694
             }
695 695
         }
@@ -698,37 +698,37 @@  discard block
 block discarded – undo
698 698
         $relativepathstring = $_SERVER["PHP_SELF"];
699 699
 // Clean $relativepathstring
700 700
         if (constant('DOL_BASE_URI'))
701
-            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
701
+            $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
702 702
         $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
703 703
         $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
704 704
         if (preg_match('/list\.php$/', $relativepathstring)) {
705
-            unset($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring]);
706
-            unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
707
-            unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
705
+            unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
706
+            unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
707
+            unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
708 708
 
709 709
             if (!empty($contextpage))
710
-                $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring] = $contextpage;
710
+                $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
711 711
             if (!empty($page) && $page > 1)
712
-                $_SESSION['lastsearch_page_tmp_' . $relativepathstring] = $page;
712
+                $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
713 713
             if (!empty($limit) && $limit != Globals::$conf->limit)
714
-                $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] = $limit;
714
+                $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
715 715
 
716
-            unset($_SESSION['lastsearch_contextpage_' . $relativepathstring]);
717
-            unset($_SESSION['lastsearch_page_' . $relativepathstring]);
718
-            unset($_SESSION['lastsearch_limit_' . $relativepathstring]);
716
+            unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
717
+            unset($_SESSION['lastsearch_page_'.$relativepathstring]);
718
+            unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
719 719
         }
720 720
 
721 721
 // Core error message
722 722
         if (!empty(Globals::$conf->global->MAIN_CORE_ERROR)) {
723 723
 // Ajax version
724 724
             if (Globals::$conf->use_javascript_ajax) {
725
-                $this->title = img_warning() . ' ' . Globals::$langs->trans('CoreErrorTitle');
725
+                $this->title = img_warning().' '.Globals::$langs->trans('CoreErrorTitle');
726 726
                 print ajax_dialog($this->title, Globals::$langs->trans('CoreErrorMessage'));
727 727
             }
728 728
 // html version
729 729
             else {
730
-                $msg = img_warning() . ' ' . Globals::$langs->trans('CoreErrorMessage');
731
-                print '<div class="error">' . $msg . '</div>';
730
+                $msg = img_warning().' '.Globals::$langs->trans('CoreErrorMessage');
731
+                print '<div class="error">'.$msg.'</div>';
732 732
             }
733 733
 
734 734
 //define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
@@ -736,17 +736,17 @@  discard block
 block discarded – undo
736 736
 
737 737
         print "\n\n";
738 738
 
739
-        print '</div> <!-- End div class="fiche" -->' . "\n"; // End div fiche
739
+        print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
740 740
 
741 741
         if (empty(Globals::$conf->dol_hide_leftmenu))
742
-            print '</div> <!-- End div id-right -->' . "\n"; // End div id-right
742
+            print '</div> <!-- End div id-right -->'."\n"; // End div id-right
743 743
 
744 744
         if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile))
745
-            print '</div> <!-- End div id-container -->' . "\n"; // End div container
745
+            print '</div> <!-- End div id-container -->'."\n"; // End div container
746 746
 
747 747
         print "\n";
748 748
         if ($comment)
749
-            print '<!-- ' . $comment . ' -->' . "\n";
749
+            print '<!-- '.$comment.' -->'."\n";
750 750
 
751 751
         DolUtils::printCommonFooter($zone);
752 752
 
@@ -754,8 +754,8 @@  discard block
 block discarded – undo
754 754
             print $delayedhtmlcontent;
755 755
 
756 756
         if (!empty(Globals::$conf->use_javascript_ajax)) {
757
-            print "\n" . '<!-- Includes JS Footer of Dolibarr -->' . "\n";
758
-            print '<script type="text/javascript" src="' . BASE_URI . '?controller=core/js/&method=lib_foot.js&lang=' . Globals::$langs->defaultlang . ($ext ? '&' . $ext : '') . '"></script>' . "\n";
757
+            print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
758
+            print '<script type="text/javascript" src="'.BASE_URI.'?controller=core/js/&method=lib_foot.js&lang='.Globals::$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
759 759
         }
760 760
 
761 761
 // Wrapper to add log when clicking on download or preview
@@ -767,7 +767,7 @@  discard block
 block discarded – undo
767 767
                 <script type="text/javascript">
768 768
                     jQuery(document).ready(function () {
769 769
                         $('a.documentpreview').click(function () {
770
-                            $.post('<?php echo DOL_BASE_URI . "/blockedlog/ajax/block-add.php" ?>'
770
+                            $.post('<?php echo DOL_BASE_URI."/blockedlog/ajax/block-add.php" ?>'
771 771
                                     , {
772 772
                                         id:<?php echo $object->id; ?>
773 773
                                         , element: '<?php echo $object->element ?>'
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
                             );
777 777
                         });
778 778
                         $('a.documentdownload').click(function () {
779
-                            $.post('<?php echo DOL_BASE_URI . "/blockedlog/ajax/block-add.php" ?>'
779
+                            $.post('<?php echo DOL_BASE_URI."/blockedlog/ajax/block-add.php" ?>'
780 780
                                     , {
781 781
                                         id:<?php echo $object->id; ?>
782 782
                                         , element: '<?php echo $object->element ?>'
@@ -792,7 +792,7 @@  discard block
 block discarded – undo
792 792
 
793 793
 // A div for the address popup
794 794
         print "\n<!-- A div to allow dialog popup -->\n";
795
-        print '<div id="dialogforpopup" style="display: none;"></div>' . "\n";
795
+        print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
796 796
 
797 797
         print "</body>\n";
798 798
 
Please login to merge, or discard this patch.
Base/CommonObject.php 1 patch
Spacing   +1480 added lines, -1480 removed lines patch added patch discarded remove patch
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 	/**
36 36
 	 * @var string[]	Array of error strings
37 37
 	 */
38
-	public $errors=array();
38
+	public $errors = array();
39 39
 
40 40
 	/**
41 41
 	 * @var string ID to identify managed object
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 	/**
51 51
 	 * @var int    Name of subtable line
52 52
 	 */
53
-	public $table_element_line='';
53
+	public $table_element_line = '';
54 54
 
55 55
 	/**
56 56
 	 * @var string		Key value used to track if data is coming from import wizard
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
 	/**
61 61
 	 * @var mixed		Contains data to manage extrafields
62 62
 	 */
63
-	public $array_options=array();
63
+	public $array_options = array();
64 64
 
65 65
 	/**
66 66
 	 * @var int[][]		Array of linked objects ids. Loaded by ->fetchObjectLinked
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	/**
90 90
 	 * @var array<string,mixed>		Can be used to pass information when only object is provided to method
91 91
 	 */
92
-	public $context=array();
92
+	public $context = array();
93 93
 
94 94
 	/**
95 95
 	 * @var string		Contains canvas name if record is an alternative canvas record
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
 	 * @var mixed		Contains comments
350 350
 	 * @see fetchComments()
351 351
 	 */
352
-	public $comments=array();
352
+	public $comments = array();
353 353
 
354 354
 	/**
355 355
 	 * @var int
@@ -375,9 +375,9 @@  discard block
 block discarded – undo
375 375
 	public $civility_id;
376 376
 
377 377
 	// Dates
378
-	public $date_creation;			// Date creation
379
-	public $date_validation;		// Date validation
380
-	public $date_modification;		// Date last change (tms field)
378
+	public $date_creation; // Date creation
379
+	public $date_validation; // Date validation
380
+	public $date_modification; // Date last change (tms field)
381 381
 
382 382
 
383 383
 
@@ -393,30 +393,30 @@  discard block
 block discarded – undo
393 393
 	 *  @param	string	$ref_ext	Ref ext of object to check
394 394
 	 *  @return int     			<0 if KO, 0 if OK but not found, >0 if OK and exists
395 395
 	 */
396
-	static function isExistingObject($element, $id, $ref='', $ref_ext='')
396
+	static function isExistingObject($element, $id, $ref = '', $ref_ext = '')
397 397
 	{
398
-		global $db,$conf;
398
+		global $db, $conf;
399 399
 
400 400
 		$sql = "SELECT rowid, ref, ref_ext";
401
-		$sql.= " FROM ".MAIN_DB_PREFIX.$element;
402
-		$sql.= " WHERE entity IN (".getEntity($element).")" ;
401
+		$sql .= " FROM ".MAIN_DB_PREFIX.$element;
402
+		$sql .= " WHERE entity IN (".getEntity($element).")";
403 403
 
404
-		if ($id > 0) $sql.= " AND rowid = ".$db->escape($id);
405
-		else if ($ref) $sql.= " AND ref = '".$db->escape($ref)."'";
406
-		else if ($ref_ext) $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'";
404
+		if ($id > 0) $sql .= " AND rowid = ".$db->escape($id);
405
+		else if ($ref) $sql .= " AND ref = '".$db->escape($ref)."'";
406
+		else if ($ref_ext) $sql .= " AND ref_ext = '".$db->escape($ref_ext)."'";
407 407
 		else {
408
-			$error='ErrorWrongParameters';
408
+			$error = 'ErrorWrongParameters';
409 409
 			dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
410 410
 			return -1;
411 411
 		}
412 412
 		if ($ref || $ref_ext)
413
-            $sql .= " AND entity = " . Globals::$conf->entity;
413
+            $sql .= " AND entity = ".Globals::$conf->entity;
414 414
 
415 415
         dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
416 416
 		$resql = $db->query($sql);
417 417
 		if ($resql)
418 418
 		{
419
-			$num=$db->num_rows($resql);
419
+			$num = $db->num_rows($resql);
420 420
 			if ($num > 0) return 1;
421 421
 			else return 0;
422 422
 		}
@@ -430,7 +430,7 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	function errorsToString()
432 432
 	{
433
-		return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
433
+		return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
434 434
 	}
435 435
 
436 436
 	/**
@@ -442,18 +442,18 @@  discard block
 block discarded – undo
442 442
 	 * 	@param	int			$maxlen			Maximum length
443 443
 	 * 	@return	string						String with full name
444 444
 	 */
445
-	function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
445
+	function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
446 446
 	{
447 447
 		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
448
-		$lastname=$this->lastname;
449
-		$firstname=$this->firstname;
450
-		if (empty($lastname))  $lastname=(isset($this->lastname)?$this->lastname:(isset($this->name)?$this->name:(isset($this->nom)?$this->nom:(isset($this->societe)?$this->societe:(isset($this->company)?$this->company:'')))));
448
+		$lastname = $this->lastname;
449
+		$firstname = $this->firstname;
450
+		if (empty($lastname))  $lastname = (isset($this->lastname) ? $this->lastname : (isset($this->name) ? $this->name : (isset($this->nom) ? $this->nom : (isset($this->societe) ? $this->societe : (isset($this->company) ? $this->company : '')))));
451 451
 
452
-		$ret='';
452
+		$ret = '';
453 453
 		if ($option && $this->civility_id)
454 454
 		{
455
-			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
456
-			else $ret.=$this->civility_id.' ';
455
+			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id) != "Civility".$this->civility_id) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
456
+			else $ret .= $this->civility_id.' ';
457 457
 		}
458 458
 
459 459
 		$ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
@@ -469,24 +469,24 @@  discard block
 block discarded – undo
469 469
 	 *  @param		int		    $withregion			1=Add region into address string
470 470
 	 *	@return		string							Full address string
471 471
 	 */
472
-	function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
472
+	function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0)
473 473
 	{
474 474
 		if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
475 475
 		{
476
-			require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
477
-			$tmparray=getCountry($this->country_id,'all');
478
-			$this->country_code=$tmparray['code'];
479
-			$this->country     =$tmparray['label'];
476
+			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
477
+			$tmparray = getCountry($this->country_id, 'all');
478
+			$this->country_code = $tmparray['code'];
479
+			$this->country     = $tmparray['label'];
480 480
 		}
481 481
 
482 482
         if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
483 483
     	{
484
-    		require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
485
-    		$tmparray=getState($this->state_id,'all',0,1);
486
-			$this->state_code   =$tmparray['code'];
487
-			$this->state        =$tmparray['label'];
488
-			$this->region_code  =$tmparray['region_code'];
489
-			$this->region       =$tmparray['region'];
484
+    		require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
485
+    		$tmparray = getState($this->state_id, 'all', 0, 1);
486
+			$this->state_code   = $tmparray['code'];
487
+			$this->state        = $tmparray['label'];
488
+			$this->region_code  = $tmparray['region_code'];
489
+			$this->region       = $tmparray['region'];
490 490
         }
491 491
 
492 492
 		return dol_format_address($this, $withcountry, $sep);
@@ -504,105 +504,105 @@  discard block
 block discarded – undo
504 504
 	{
505 505
 		global $conf, $langs;
506 506
 
507
-		$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
507
+		$countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
508 508
 
509
-		$contactid=0;
510
-		$thirdpartyid=0;
509
+		$contactid = 0;
510
+		$thirdpartyid = 0;
511 511
 		if ($this->element == 'societe')
512 512
 		{
513
-			$thirdpartyid=$this->id;
513
+			$thirdpartyid = $this->id;
514 514
 		}
515 515
 		if ($this->element == 'contact')
516 516
 		{
517
-			$contactid=$this->id;
518
-			$thirdpartyid=$object->fk_soc;
517
+			$contactid = $this->id;
518
+			$thirdpartyid = $object->fk_soc;
519 519
 		}
520 520
 		if ($this->element == 'user')
521 521
 		{
522
-			$contactid=$this->contact_id;
523
-			$thirdpartyid=$object->fk_soc;
522
+			$contactid = $this->contact_id;
523
+			$thirdpartyid = $object->fk_soc;
524 524
 		}
525 525
 
526
-		$out='<!-- BEGIN part to show address block -->';
526
+		$out = '<!-- BEGIN part to show address block -->';
527 527
 
528
-		$outdone=0;
528
+		$outdone = 0;
529 529
 		$coords = $this->getFullAddress(1, ', ', Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
530 530
         if ($coords)
531 531
 		{
532 532
 			if (!empty(Globals::$conf->use_javascript_ajax)) {
533
-				$namecoords = $this->getFullName($langs,1).'<br>'.$coords;
533
+				$namecoords = $this->getFullName($langs, 1).'<br>'.$coords;
534 534
 				// hideonsmatphone because copyToClipboard call jquery dialog that does not work with jmobile
535
-				$out.='<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
536
-				$out.=img_picto($langs->trans("Address"), 'object_address.png');
537
-				$out.='</a> ';
535
+				$out .= '<a href="#" class="hideonsmartphone" onclick="return copyToClipboard(\''.dol_escape_js($namecoords).'\',\''.dol_escape_js($langs->trans("HelpCopyToClipboard")).'\');">';
536
+				$out .= img_picto($langs->trans("Address"), 'object_address.png');
537
+				$out .= '</a> ';
538 538
 			}
539
-			$out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
539
+			$out .= dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
540 540
 			$outdone++;
541 541
 		}
542 542
 
543 543
 		if (!in_array($this->country_code, $countriesusingstate) && empty(Globals::$conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
544 544
             && empty(Globals::$conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
545 545
             if (!empty(Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
546
-                $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
546
+                $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
547 547
             }
548 548
             else {
549
-                $out.=($outdone?' - ':'').$this->state;
549
+                $out .= ($outdone ? ' - ' : '').$this->state;
550 550
             }
551 551
 			$outdone++;
552 552
 		}
553 553
 
554
-		if (! empty($this->phone) || ! empty($this->phone_pro) || ! empty($this->phone_mobile) || ! empty($this->phone_perso) || ! empty($this->fax) || ! empty($this->office_phone) || ! empty($this->user_mobile) || ! empty($this->office_fax)) $out.=($outdone?'<br>':'');
555
-		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
556
-			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
554
+		if (!empty($this->phone) || !empty($this->phone_pro) || !empty($this->phone_mobile) || !empty($this->phone_perso) || !empty($this->fax) || !empty($this->office_phone) || !empty($this->user_mobile) || !empty($this->office_fax)) $out .= ($outdone ? '<br>' : '');
555
+		if (!empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
556
+			$out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
557 557
 		}
558
-		if (! empty($this->phone_pro)) {
559
-			$out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
558
+		if (!empty($this->phone_pro)) {
559
+			$out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
560 560
 		}
561
-		if (! empty($this->phone_mobile)) {
562
-			$out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
561
+		if (!empty($this->phone_mobile)) {
562
+			$out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
563 563
 		}
564
-		if (! empty($this->phone_perso)) {
565
-			$out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
564
+		if (!empty($this->phone_perso)) {
565
+			$out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso")); $outdone++;
566 566
 		}
567
-		if (! empty($this->office_phone)) {
568
-			$out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
567
+		if (!empty($this->office_phone)) {
568
+			$out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
569 569
 		}
570
-		if (! empty($this->user_mobile)) {
571
-			$out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
570
+		if (!empty($this->user_mobile)) {
571
+			$out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
572 572
 		}
573
-		if (! empty($this->fax)) {
574
-			$out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
573
+		if (!empty($this->fax)) {
574
+			$out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
575 575
 		}
576
-		if (! empty($this->office_fax)) {
577
-			$out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
576
+		if (!empty($this->office_fax)) {
577
+			$out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
578 578
 		}
579 579
 
580
-		$out.='<div style="clear: both;"></div>';
581
-		$outdone=0;
582
-		if (! empty($this->email))
580
+		$out .= '<div style="clear: both;"></div>';
581
+		$outdone = 0;
582
+		if (!empty($this->email))
583 583
 		{
584
-			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
584
+			$out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
585 585
 			$outdone++;
586 586
 		}
587
-		if (! empty($this->url))
587
+		if (!empty($this->url))
588 588
 		{
589
-			$out.=dol_print_url($this->url,'_goout',0,1);
589
+			$out .= dol_print_url($this->url, '_goout', 0, 1);
590 590
 			$outdone++;
591 591
 		}
592
-		$out.='<div style="clear: both;">';
592
+		$out .= '<div style="clear: both;">';
593 593
 		if (!empty(Globals::$conf->socialnetworks->enabled)) {
594
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
594
+			if ($this->skype) $out .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
595 595
 			$outdone++;
596
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
596
+			if ($this->jabberid) $out .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
597 597
 			$outdone++;
598
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
598
+			if ($this->twitter) $out .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
599 599
 			$outdone++;
600
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
600
+			if ($this->facebook) $out .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
601 601
 			$outdone++;
602 602
 		}
603
-		$out.='</div>';
603
+		$out .= '</div>';
604 604
 
605
-		$out.='<!-- END Part to show address block -->';
605
+		$out .= '<!-- END Part to show address block -->';
606 606
 
607 607
 		return $out;
608 608
 	}
@@ -615,17 +615,17 @@  discard block
 block discarded – undo
615 615
 	 * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
616 616
 	 * @return	string						Link or empty string if there is no download link
617 617
 	 */
618
-	function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
618
+	function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
619 619
 	{
620 620
 		global $user, $dolibarr_main_url_root;
621 621
 
622 622
 		if (empty($this->last_main_doc))
623 623
 		{
624
-			return '';		// No way to known which document name to use
624
+			return ''; // No way to known which document name to use
625 625
 		}
626 626
 
627 627
 		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
628
-		$ecmfile=new EcmFiles($this->db);
628
+		$ecmfile = new EcmFiles($this->db);
629 629
 		$result = $ecmfile->fetch(0, '', $this->last_main_doc);
630 630
 		if ($result < 0)
631 631
 		{
@@ -673,26 +673,26 @@  discard block
 block discarded – undo
673 673
 		}
674 674
 
675 675
 		// Define $urlwithroot
676
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
677
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
676
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
677
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
678 678
 		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
679 679
 
680
-		$forcedownload=0;
680
+		$forcedownload = 0;
681 681
 
682
-		$paramlink='';
682
+		$paramlink = '';
683 683
 		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
684 684
 		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
685 685
 		//$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
686
-		if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
687
-		if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
686
+		if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
687
+		if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
688 688
 
689 689
 		if ($relativelink)
690 690
 		{
691
-			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
691
+			$linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
692 692
 		}
693 693
 		else
694 694
 		{
695
-			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
695
+			$linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
696 696
 		}
697 697
 
698 698
 		// Here $ecmfile->share is defined
@@ -710,10 +710,10 @@  discard block
 block discarded – undo
710 710
 	 *  @param  int		$notrigger			Disable all triggers
711 711
 	 *  @return int                 		<0 if KO, >0 if OK
712 712
 	 */
713
-	function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
713
+	function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
714 714
 	{
715 715
         // phpcs:enable
716
-		global $user,$langs;
716
+		global $user, $langs;
717 717
 
718 718
 
719 719
 		dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
@@ -722,43 +722,43 @@  discard block
 block discarded – undo
722 722
 		if ($fk_socpeople <= 0)
723 723
 		{
724 724
 			$langs->load("errors");
725
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","1");
726
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
725
+			$this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
726
+			dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
727 727
 			return -1;
728 728
 		}
729
-		if (! $type_contact)
729
+		if (!$type_contact)
730 730
 		{
731 731
 			$langs->load("errors");
732
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","2");
733
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
732
+			$this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
733
+			dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
734 734
 			return -2;
735 735
 		}
736 736
 
737
-		$id_type_contact=0;
737
+		$id_type_contact = 0;
738 738
 		if (is_numeric($type_contact))
739 739
 		{
740
-			$id_type_contact=$type_contact;
740
+			$id_type_contact = $type_contact;
741 741
 		}
742 742
 		else
743 743
 		{
744 744
 			// We look for id type_contact
745 745
 			$sql = "SELECT tc.rowid";
746
-			$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
747
-			$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
748
-			$sql.= " AND tc.source='".$this->db->escape($source)."'";
749
-			$sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
746
+			$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
747
+			$sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
748
+			$sql .= " AND tc.source='".$this->db->escape($source)."'";
749
+			$sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
750 750
 			//print $sql;
751
-			$resql=$this->db->query($sql);
751
+			$resql = $this->db->query($sql);
752 752
 			if ($resql)
753 753
 			{
754 754
 				$obj = $this->db->fetch_object($resql);
755
-				if ($obj) $id_type_contact=$obj->rowid;
755
+				if ($obj) $id_type_contact = $obj->rowid;
756 756
 			}
757 757
 		}
758 758
 
759 759
 		if ($id_type_contact == 0)
760 760
 		{
761
-			$this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
761
+			$this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
762 762
 			dol_syslog("CODE_NOT_VALID_FOR_THIS_ELEMENT: Code type of contact '".$type_contact."' does not exists or is not active for element ".$this->element.", we can ignore it");
763 763
 			return -3;
764 764
 		}
@@ -766,35 +766,35 @@  discard block
 block discarded – undo
766 766
 		$datecreate = dol_now();
767 767
 
768 768
 		// Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
769
-		$TListeContacts=$this->liste_contact(-1, $source);
770
-		$already_added=false;
771
-		if(!empty($TListeContacts)) {
772
-			foreach($TListeContacts as $array_contact) {
773
-				if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
774
-					$already_added=true;
769
+		$TListeContacts = $this->liste_contact(-1, $source);
770
+		$already_added = false;
771
+		if (!empty($TListeContacts)) {
772
+			foreach ($TListeContacts as $array_contact) {
773
+				if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
774
+					$already_added = true;
775 775
 					break;
776 776
 				}
777 777
 			}
778 778
 		}
779 779
 
780
-		if(!$already_added) {
780
+		if (!$already_added) {
781 781
 
782 782
 			$this->db->begin();
783 783
 
784 784
 			// Insert into database
785 785
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
786
-			$sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
787
-			$sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
788
-			$sql.= "'".$this->db->idate($datecreate)."'";
789
-			$sql.= ", 4, ". $id_type_contact;
790
-			$sql.= ")";
786
+			$sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
787
+			$sql .= " VALUES (".$this->id.", ".$fk_socpeople." , ";
788
+			$sql .= "'".$this->db->idate($datecreate)."'";
789
+			$sql .= ", 4, ".$id_type_contact;
790
+			$sql .= ")";
791 791
 
792
-			$resql=$this->db->query($sql);
792
+			$resql = $this->db->query($sql);
793 793
 			if ($resql)
794 794
 			{
795
-				if (! $notrigger)
795
+				if (!$notrigger)
796 796
 				{
797
-					$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
797
+					$result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
798 798
 					if ($result < 0)
799 799
 					{
800 800
 						$this->db->rollback();
@@ -809,14 +809,14 @@  discard block
 block discarded – undo
809 809
 			{
810 810
 				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
811 811
 				{
812
-					$this->error=$this->db->errno();
812
+					$this->error = $this->db->errno();
813 813
 					$this->db->rollback();
814 814
 					echo 'err rollback';
815 815
 					return -2;
816 816
 				}
817 817
 				else
818 818
 				{
819
-					$this->error=$this->db->error();
819
+					$this->error = $this->db->error();
820 820
 					$this->db->rollback();
821 821
 					return -1;
822 822
 				}
@@ -832,15 +832,15 @@  discard block
 block discarded – undo
832 832
 	 *    @param    string          $source     Nature of contact ('internal' or 'external')
833 833
 	 *    @return   int                         >0 if OK, <0 if KO
834 834
 	 */
835
-	function copy_linked_contact($objFrom, $source='internal')
835
+	function copy_linked_contact($objFrom, $source = 'internal')
836 836
 	{
837 837
         // phpcs:enable
838 838
 		$contacts = $objFrom->liste_contact(-1, $source);
839
-		foreach($contacts as $contact)
839
+		foreach ($contacts as $contact)
840 840
 		{
841 841
 			if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
842 842
 			{
843
-				$this->error=$this->db->lasterror();
843
+				$this->error = $this->db->lasterror();
844 844
 				return -1;
845 845
 			}
846 846
 		}
@@ -857,23 +857,23 @@  discard block
 block discarded – undo
857 857
 	 *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
858 858
 	 *      @return int                 		<0 if KO, >= 0 if OK
859 859
 	 */
860
-	function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
860
+	function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
861 861
 	{
862 862
         // phpcs:enable
863 863
 		// Insert into database
864 864
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
865
-		$sql.= " statut = ".$statut;
866
-		if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
867
-		if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
868
-		$sql.= " where rowid = ".$rowid;
869
-		$resql=$this->db->query($sql);
865
+		$sql .= " statut = ".$statut;
866
+		if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'";
867
+		if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'";
868
+		$sql .= " where rowid = ".$rowid;
869
+		$resql = $this->db->query($sql);
870 870
 		if ($resql)
871 871
 		{
872 872
 			return 0;
873 873
 		}
874 874
 		else
875 875
 		{
876
-			$this->error=$this->db->lasterror();
876
+			$this->error = $this->db->lasterror();
877 877
 			return -1;
878 878
 		}
879 879
 	}
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
 	 *    @param	int		$notrigger		Disable all triggers
887 887
 	 *    @return   int						>0 if OK, <0 if KO
888 888
 	 */
889
-	function delete_contact($rowid, $notrigger=0)
889
+	function delete_contact($rowid, $notrigger = 0)
890 890
 	{
891 891
         // phpcs:enable
892 892
 		global $user;
@@ -895,14 +895,14 @@  discard block
 block discarded – undo
895 895
 		$this->db->begin();
896 896
 
897 897
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
898
-		$sql.= " WHERE rowid =".$rowid;
898
+		$sql .= " WHERE rowid =".$rowid;
899 899
 
900 900
 		dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
901 901
 		if ($this->db->query($sql))
902 902
 		{
903
-			if (! $notrigger)
903
+			if (!$notrigger)
904 904
 			{
905
-				$result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
905
+				$result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
906 906
 				if ($result < 0) { $this->db->rollback(); return -1; }
907 907
 			}
908 908
 
@@ -911,7 +911,7 @@  discard block
 block discarded – undo
911 911
 		}
912 912
 		else
913 913
 		{
914
-			$this->error=$this->db->lasterror();
914
+			$this->error = $this->db->lasterror();
915 915
 			$this->db->rollback();
916 916
 			return -1;
917 917
 		}
@@ -925,22 +925,22 @@  discard block
 block discarded – undo
925 925
 	 *	  @param	string	$code		Type of contact (code or id)
926 926
 	 *    @return   int					>0 if OK, <0 if KO
927 927
 	 */
928
-	function delete_linked_contact($source='',$code='')
928
+	function delete_linked_contact($source = '', $code = '')
929 929
 	{
930 930
         // phpcs:enable
931 931
 		$temp = array();
932
-		$typeContact = $this->liste_type_contact($source,'',0,0,$code);
932
+		$typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
933 933
 
934
-		foreach($typeContact as $key => $value)
934
+		foreach ($typeContact as $key => $value)
935 935
 		{
936
-			array_push($temp,$key);
936
+			array_push($temp, $key);
937 937
 		}
938 938
 		$listId = implode(",", $temp);
939 939
 
940 940
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
941
-		$sql.= " WHERE element_id = ".$this->id;
941
+		$sql .= " WHERE element_id = ".$this->id;
942 942
 		if ($listId)
943
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
943
+			$sql .= " AND fk_c_type_contact IN (".$listId.")";
944 944
 
945 945
 		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
946 946
 		if ($this->db->query($sql))
@@ -949,7 +949,7 @@  discard block
 block discarded – undo
949 949
 		}
950 950
 		else
951 951
 		{
952
-			$this->error=$this->db->lasterror();
952
+			$this->error = $this->db->lasterror();
953 953
 			return -1;
954 954
 		}
955 955
 	}
@@ -964,54 +964,54 @@  discard block
 block discarded – undo
964 964
 	 *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
965 965
 	 *    @return	array|int		        Array of contacts, -1 if error
966 966
 	 */
967
-	function liste_contact($statut=-1,$source='external',$list=0,$code='')
967
+	function liste_contact($statut = -1, $source = 'external', $list = 0, $code = '')
968 968
 	{
969 969
         // phpcs:enable
970 970
 		global $langs;
971 971
 
972
-		$tab=array();
973
-
974
-		$sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact";    // This field contains id of llx_socpeople or id of llx_user
975
-		if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
976
-		if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
977
-		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
978
-		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
979
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
980
-		$sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
981
-		if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
982
-		if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
983
-		$sql.= " WHERE ec.element_id =".$this->id;
984
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
985
-		$sql.= " AND tc.element='".$this->db->escape($this->element)."'";
986
-		if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
987
-		if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
988
-		if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
989
-		$sql.= " AND tc.active=1";
990
-		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
991
-		$sql.=" ORDER BY t.lastname ASC";
972
+		$tab = array();
973
+
974
+		$sql = "SELECT ec.rowid, ec.statut as statuslink, ec.fk_socpeople as id, ec.fk_c_type_contact"; // This field contains id of llx_socpeople or id of llx_user
975
+		if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
976
+		if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
977
+		$sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
978
+		$sql .= ", tc.source, tc.element, tc.code, tc.libelle";
979
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
980
+		$sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
981
+		if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
982
+		if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
983
+		$sql .= " WHERE ec.element_id =".$this->id;
984
+		$sql .= " AND ec.fk_c_type_contact=tc.rowid";
985
+		$sql .= " AND tc.element='".$this->db->escape($this->element)."'";
986
+		if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
987
+		if ($source == 'internal') $sql .= " AND tc.source = 'internal'";
988
+		if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'";
989
+		$sql .= " AND tc.active=1";
990
+		if ($statut >= 0) $sql .= " AND ec.statut = '".$statut."'";
991
+		$sql .= " ORDER BY t.lastname ASC";
992 992
 
993 993
 		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
994
-		$resql=$this->db->query($sql);
994
+		$resql = $this->db->query($sql);
995 995
 		if ($resql)
996 996
 		{
997
-			$num=$this->db->num_rows($resql);
998
-			$i=0;
997
+			$num = $this->db->num_rows($resql);
998
+			$i = 0;
999 999
 			while ($i < $num)
1000 1000
 			{
1001 1001
 				$obj = $this->db->fetch_object($resql);
1002 1002
 
1003
-				if (! $list)
1003
+				if (!$list)
1004 1004
 				{
1005
-					$transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1006
-					$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1007
-					$tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
1008
-								   'nom'=>$obj->lastname,      // For backward compatibility
1005
+					$transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1006
+					$libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1007
+					$tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id,
1008
+								   'nom'=>$obj->lastname, // For backward compatibility
1009 1009
 								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1010 1010
 								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1011 1011
 				}
1012 1012
 				else
1013 1013
 				{
1014
-					$tab[$i]=$obj->id;
1014
+					$tab[$i] = $obj->id;
1015 1015
 				}
1016 1016
 
1017 1017
 				$i++;
@@ -1021,7 +1021,7 @@  discard block
 block discarded – undo
1021 1021
 		}
1022 1022
 		else
1023 1023
 		{
1024
-			$this->error=$this->db->lasterror();
1024
+			$this->error = $this->db->lasterror();
1025 1025
 			dol_print_error($this->db);
1026 1026
 			return -1;
1027 1027
 		}
@@ -1037,16 +1037,16 @@  discard block
 block discarded – undo
1037 1037
 	function swapContactStatus($rowid)
1038 1038
 	{
1039 1039
 		$sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1040
-		$sql.= " tc.code, tc.libelle";
1040
+		$sql .= " tc.code, tc.libelle";
1041 1041
 		//$sql.= ", s.fk_soc";
1042
-		$sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1042
+		$sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1043 1043
 		//$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as s ON ec.fk_socpeople=s.rowid";	// Si contact de type external, alors il est lie a une societe
1044
-		$sql.= " WHERE ec.rowid =".$rowid;
1045
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
1046
-		$sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
1044
+		$sql .= " WHERE ec.rowid =".$rowid;
1045
+		$sql .= " AND ec.fk_c_type_contact=tc.rowid";
1046
+		$sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1047 1047
 
1048 1048
 		dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1049
-		$resql=$this->db->query($sql);
1049
+		$resql = $this->db->query($sql);
1050 1050
 		if ($resql)
1051 1051
 		{
1052 1052
 			$obj = $this->db->fetch_object($resql);
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
 		}
1058 1058
 		else
1059 1059
 		{
1060
-			$this->error=$this->db->error();
1060
+			$this->error = $this->db->error();
1061 1061
 			dol_print_error($this->db);
1062 1062
 			return -1;
1063 1063
 		}
@@ -1074,44 +1074,44 @@  discard block
 block discarded – undo
1074 1074
 	 *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1075 1075
 	 *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1076 1076
 	 */
1077
-	function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1077
+	function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1078 1078
 	{
1079 1079
         // phpcs:enable
1080 1080
 		global $langs;
1081 1081
 
1082
-		if (empty($order)) $order='position';
1083
-		if ($order == 'position') $order.=',code';
1082
+		if (empty($order)) $order = 'position';
1083
+		if ($order == 'position') $order .= ',code';
1084 1084
 
1085 1085
 		$tab = array();
1086 1086
 		$sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1087
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1088
-		$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
1089
-		if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
1090
-		if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
1091
-		if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
1092
-		$sql.= $this->db->order($order,'ASC');
1087
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1088
+		$sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1089
+		if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types
1090
+		if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'";
1091
+		if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'";
1092
+		$sql .= $this->db->order($order, 'ASC');
1093 1093
 
1094 1094
 		//print "sql=".$sql;
1095
-		$resql=$this->db->query($sql);
1095
+		$resql = $this->db->query($sql);
1096 1096
 		if ($resql)
1097 1097
 		{
1098
-			$num=$this->db->num_rows($resql);
1099
-			$i=0;
1098
+			$num = $this->db->num_rows($resql);
1099
+			$i = 0;
1100 1100
 			while ($i < $num)
1101 1101
 			{
1102 1102
 				$obj = $this->db->fetch_object($resql);
1103 1103
 
1104
-				$transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1105
-				$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1106
-				if (empty($option)) $tab[$obj->rowid]=$libelle_type;
1107
-				else $tab[$obj->code]=$libelle_type;
1104
+				$transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1105
+				$libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1106
+				if (empty($option)) $tab[$obj->rowid] = $libelle_type;
1107
+				else $tab[$obj->code] = $libelle_type;
1108 1108
 				$i++;
1109 1109
 			}
1110 1110
 			return $tab;
1111 1111
 		}
1112 1112
 		else
1113 1113
 		{
1114
-			$this->error=$this->db->lasterror();
1114
+			$this->error = $this->db->lasterror();
1115 1115
 			//dol_print_error($this->db);
1116 1116
 			return null;
1117 1117
 		}
@@ -1128,53 +1128,53 @@  discard block
 block discarded – undo
1128 1128
 	 *		@param	int		$status		limited to a certain status
1129 1129
 	 *      @return array       		List of id for such contacts
1130 1130
 	 */
1131
-	function getIdContact($source,$code,$status=0)
1131
+	function getIdContact($source, $code, $status = 0)
1132 1132
 	{
1133 1133
 		global $conf;
1134 1134
 
1135
-		$result=array();
1136
-		$i=0;
1135
+		$result = array();
1136
+		$i = 0;
1137 1137
 		//cas particulier pour les expeditions
1138
-		if($this->element=='shipping' && $this->origin_id != 0) {
1139
-			$id=$this->origin_id;
1140
-			$element='commande';
1141
-        } else if($this->element=='reception' && $this->origin_id != 0) {
1142
-            $id=$this->origin_id;
1143
-            $element='order_supplier';
1138
+		if ($this->element == 'shipping' && $this->origin_id != 0) {
1139
+			$id = $this->origin_id;
1140
+			$element = 'commande';
1141
+        } else if ($this->element == 'reception' && $this->origin_id != 0) {
1142
+            $id = $this->origin_id;
1143
+            $element = 'order_supplier';
1144 1144
 		} else {
1145
-			$id=$this->id;
1146
-			$element=$this->element;
1145
+			$id = $this->id;
1146
+			$element = $this->element;
1147 1147
 		}
1148 1148
 
1149 1149
 		$sql = "SELECT ec.fk_socpeople";
1150
-		$sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1151
-		if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
1152
-		if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1153
-		$sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1154
-		$sql.= " WHERE ec.element_id = ".$id;
1155
-		$sql.= " AND ec.fk_socpeople = c.rowid";
1156
-		if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
1157
-		if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
1158
-		$sql.= " AND ec.fk_c_type_contact = tc.rowid";
1159
-		$sql.= " AND tc.element = '".$element."'";
1160
-		$sql.= " AND tc.source = '".$source."'";
1161
-		$sql.= " AND tc.code = '".$code."'";
1162
-		$sql.= " AND tc.active = 1";
1163
-		if ($status) $sql.= " AND ec.statut = ".$status;
1150
+		$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1151
+		if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,";
1152
+		if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
1153
+		$sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1154
+		$sql .= " WHERE ec.element_id = ".$id;
1155
+		$sql .= " AND ec.fk_socpeople = c.rowid";
1156
+		if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")";
1157
+		if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")";
1158
+		$sql .= " AND ec.fk_c_type_contact = tc.rowid";
1159
+		$sql .= " AND tc.element = '".$element."'";
1160
+		$sql .= " AND tc.source = '".$source."'";
1161
+		$sql .= " AND tc.code = '".$code."'";
1162
+		$sql .= " AND tc.active = 1";
1163
+		if ($status) $sql .= " AND ec.statut = ".$status;
1164 1164
 
1165 1165
 		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1166
-		$resql=$this->db->query($sql);
1166
+		$resql = $this->db->query($sql);
1167 1167
 		if ($resql)
1168 1168
 		{
1169 1169
 			while ($obj = $this->db->fetch_object($resql))
1170 1170
 			{
1171
-				$result[$i]=$obj->fk_socpeople;
1171
+				$result[$i] = $obj->fk_socpeople;
1172 1172
 				$i++;
1173 1173
 			}
1174 1174
 		}
1175 1175
 		else
1176 1176
 		{
1177
-			$this->error=$this->db->error();
1177
+			$this->error = $this->db->error();
1178 1178
 			return null;
1179 1179
 		}
1180 1180
 
@@ -1188,16 +1188,16 @@  discard block
 block discarded – undo
1188 1188
 	 *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1189 1189
 	 *		@return	int						<0 if KO, >0 if OK
1190 1190
 	 */
1191
-	function fetch_contact($contactid=null)
1191
+	function fetch_contact($contactid = null)
1192 1192
 	{
1193 1193
         // phpcs:enable
1194
-		if (empty($contactid)) $contactid=$this->contactid;
1194
+		if (empty($contactid)) $contactid = $this->contactid;
1195 1195
 
1196 1196
 		if (empty($contactid)) return 0;
1197 1197
 
1198 1198
 		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1199 1199
 		$contact = new Contact($this->db);
1200
-		$result=$contact->fetch($contactid);
1200
+		$result = $contact->fetch($contactid);
1201 1201
 		$this->contact = $contact;
1202 1202
 		return $result;
1203 1203
 	}
@@ -1209,7 +1209,7 @@  discard block
 block discarded – undo
1209 1209
 	 *		@param		int		$force_thirdparty_id	Force thirdparty id
1210 1210
 	 *		@return		int								<0 if KO, >0 if OK
1211 1211
 	 */
1212
-	function fetch_thirdparty($force_thirdparty_id=0)
1212
+	function fetch_thirdparty($force_thirdparty_id = 0)
1213 1213
 	{
1214 1214
         // phpcs:enable
1215 1215
 		global $conf;
@@ -1217,7 +1217,7 @@  discard block
 block discarded – undo
1217 1217
 		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1218 1218
 			return 0;
1219 1219
 
1220
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1220
+		require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1221 1221
 
1222 1222
 		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1223 1223
 		if ($force_thirdparty_id)
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
 
1281 1281
 		dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1282 1282
 
1283
-		$idtype=$this->barcode_type;
1283
+		$idtype = $this->barcode_type;
1284 1284
 		if (empty($idtype) && $idtype != '0')	// If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
1285 1285
 		{
1286 1286
 			if ($this->element == 'product')
@@ -1295,8 +1295,8 @@  discard block
 block discarded – undo
1295 1295
 			if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder))    // If data not already loaded
1296 1296
 			{
1297 1297
 				$sql = "SELECT rowid, code, libelle as label, coder";
1298
-				$sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299
-				$sql.= " WHERE rowid = ".$idtype;
1298
+				$sql .= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299
+				$sql .= " WHERE rowid = ".$idtype;
1300 1300
 				dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1301 1301
 				$resql = $this->db->query($sql);
1302 1302
 				if ($resql)
@@ -1329,13 +1329,13 @@  discard block
 block discarded – undo
1329 1329
         // phpcs:enable
1330 1330
 		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1331 1331
 
1332
-		if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet;	// For backward compatibility
1332
+		if (empty($this->fk_project) && !empty($this->fk_projet)) $this->fk_project = $this->fk_projet; // For backward compatibility
1333 1333
 		if (empty($this->fk_project)) return 0;
1334 1334
 
1335 1335
 		$project = new Project($this->db);
1336 1336
 		$result = $project->fetch($this->fk_project);
1337 1337
 
1338
-		$this->projet = $project;	// deprecated
1338
+		$this->projet = $project; // deprecated
1339 1339
 		$this->project = $project;
1340 1340
 		return $result;
1341 1341
 	}
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
 	{
1372 1372
         // phpcs:enable
1373 1373
 		$user = new User($this->db);
1374
-		$result=$user->fetch($userid);
1374
+		$result = $user->fetch($userid);
1375 1375
 		$this->user = $user;
1376 1376
 		return $result;
1377 1377
 	}
@@ -1409,14 +1409,14 @@  discard block
 block discarded – undo
1409 1409
 	{
1410 1410
 		global $conf;
1411 1411
 
1412
-		$result=false;
1412
+		$result = false;
1413 1413
 
1414 1414
 		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX.$table;
1415
-		$sql.= " WHERE ".$field." = '".$key."'";
1416
-		if (! empty($element)) {
1417
-			$sql.= " AND entity IN (".getEntity($element).")";
1415
+		$sql .= " WHERE ".$field." = '".$key."'";
1416
+		if (!empty($element)) {
1417
+			$sql .= " AND entity IN (".getEntity($element).")";
1418 1418
 		} else {
1419
-			$sql .= " AND entity = " . Globals::$conf->entity;
1419
+			$sql .= " AND entity = ".Globals::$conf->entity;
1420 1420
         }
1421 1421
 
1422 1422
 		dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
@@ -1443,10 +1443,10 @@  discard block
 block discarded – undo
1443 1443
 	 */
1444 1444
 	function getValueFrom($table, $id, $field)
1445 1445
 	{
1446
-		$result=false;
1446
+		$result = false;
1447 1447
 		if (!empty($id) && !empty($field) && !empty($table)) {
1448 1448
 			$sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
1449
-			$sql.= " WHERE rowid = ".$id;
1449
+			$sql .= " WHERE rowid = ".$id;
1450 1450
 
1451 1451
 			dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1452 1452
 			$resql = $this->db->query($sql);
@@ -1475,36 +1475,36 @@  discard block
 block discarded – undo
1475 1475
 	 *	@return	int							<0 if KO, >0 if OK
1476 1476
 	 *  @see updateExtraField
1477 1477
 	 */
1478
-	function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
1478
+	function setValueFrom($field, $value, $table = '', $id = null, $format = '', $id_field = '', $fuser = null, $trigkey = '', $fk_user_field = 'fk_user_modif')
1479 1479
 	{
1480
-		global $user,$langs,$conf;
1480
+		global $user, $langs, $conf;
1481 1481
 
1482
-		if (empty($table)) 	  $table=$this->table_element;
1483
-		if (empty($id))    	  $id=$this->id;
1484
-		if (empty($format))   $format='text';
1485
-		if (empty($id_field)) $id_field='rowid';
1482
+		if (empty($table)) 	  $table = $this->table_element;
1483
+		if (empty($id))    	  $id = $this->id;
1484
+		if (empty($format))   $format = 'text';
1485
+		if (empty($id_field)) $id_field = 'rowid';
1486 1486
 
1487
-		$error=0;
1487
+		$error = 0;
1488 1488
 
1489 1489
 		$this->db->begin();
1490 1490
 
1491 1491
 		// Special case
1492
-		if ($table == 'product' && $field == 'note_private') $field='note';
1492
+		if ($table == 'product' && $field == 'note_private') $field = 'note';
1493 1493
 		if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
1494 1494
 
1495 1495
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
1496 1496
 
1497
-		if ($format == 'text') $sql.= $field." = '".$this->db->escape($value)."'";
1498
-		else if ($format == 'int') $sql.= $field." = ".$this->db->escape($value);
1499
-		else if ($format == 'date') $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
1497
+		if ($format == 'text') $sql .= $field." = '".$this->db->escape($value)."'";
1498
+		else if ($format == 'int') $sql .= $field." = ".$this->db->escape($value);
1499
+		else if ($format == 'date') $sql .= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
1500 1500
 
1501 1501
 		if ($fk_user_field)
1502 1502
 		{
1503
-			if (! empty($fuser) && is_object($fuser)) $sql.=", ".$fk_user_field." = ".$fuser->id;
1504
-			elseif (empty($fuser) || $fuser != 'none') $sql.=", ".$fk_user_field." = ".$user->id;
1503
+			if (!empty($fuser) && is_object($fuser)) $sql .= ", ".$fk_user_field." = ".$fuser->id;
1504
+			elseif (empty($fuser) || $fuser != 'none') $sql .= ", ".$fk_user_field." = ".$user->id;
1505 1505
 		}
1506 1506
 
1507
-		$sql.= " WHERE ".$id_field." = ".$id;
1507
+		$sql .= " WHERE ".$id_field." = ".$id;
1508 1508
 
1509 1509
 		dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
1510 1510
 		$resql = $this->db->query($sql);
@@ -1521,11 +1521,11 @@  discard block
 block discarded – undo
1521 1521
 				{
1522 1522
 					$result = $this->fetchCommon($id);
1523 1523
 				}
1524
-				if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);   // This may set this->errors
1524
+				if ($result >= 0) $result = $this->call_trigger($trigkey, (!empty($fuser) && is_object($fuser)) ? $fuser : $user); // This may set this->errors
1525 1525
 				if ($result < 0) $error++;
1526 1526
 			}
1527 1527
 
1528
-			if (! $error)
1528
+			if (!$error)
1529 1529
 			{
1530 1530
 				if (property_exists($this, $field)) $this->$field = $value;
1531 1531
 				$this->db->commit();
@@ -1539,7 +1539,7 @@  discard block
 block discarded – undo
1539 1539
 		}
1540 1540
 		else
1541 1541
 		{
1542
-			$this->error=$this->db->lasterror();
1542
+			$this->error = $this->db->lasterror();
1543 1543
 			$this->db->rollback();
1544 1544
 			return -1;
1545 1545
 		}
@@ -1554,14 +1554,14 @@  discard block
 block discarded – undo
1554 1554
 	 *		@param	int		$nodbprefix	Do not include DB prefix to forge table name
1555 1555
 	 *      @return int         		<0 if KO, >0 if OK
1556 1556
 	 */
1557
-	function load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
1557
+	function load_previous_next_ref($filter, $fieldid, $nodbprefix = 0)
1558 1558
 	{
1559 1559
         // phpcs:enable
1560 1560
 		global $conf, $user;
1561 1561
 
1562
-		if (! $this->table_element)
1562
+		if (!$this->table_element)
1563 1563
 		{
1564
-			dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1564
+			dol_print_error('', get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1565 1565
 			return -1;
1566 1566
 		}
1567 1567
 		if ($fieldid == 'none') return 1;
@@ -1576,45 +1576,45 @@  discard block
 block discarded – undo
1576 1576
 		if ($this->element == 'societe') $alias = 'te';
1577 1577
 
1578 1578
 		$sql = "SELECT MAX(te.".$fieldid.")";
1579
-		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
1579
+		$sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
1580 1580
 		if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1581
-            $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1582
-		}
1583
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to entity
1584
-		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to socid
1585
-		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";	// If we need to link to societe to limit select to socid
1586
-		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid)  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1587
-		$sql.= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'";  // ->ref must always be defined (set to id if field does not exists)
1588
-		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id;
1589
-		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1590
-		if (! empty($filter))
1591
-		{
1592
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1593
-			$sql.=$filter;
1594
-		}
1595
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to entity
1596
-		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to socid
1581
+            $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1582
+		}
1583
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
1584
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
1585
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
1586
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid)  $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1587
+		$sql .= " WHERE te.".$fieldid." < '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
1588
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
1589
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
1590
+		if (!empty($filter))
1591
+		{
1592
+			if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
1593
+			$sql .= $filter;
1594
+		}
1595
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
1596
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
1597 1597
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598 1598
 			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599 1599
                 if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1600
-                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1600
+                    $sql .= " AND te.entity IS NOT NULL"; // Show all users
1601 1601
 				} else {
1602
-					$sql.= " AND ug.fk_user = te.rowid";
1603
-					$sql.= " AND ug.entity IN (".getEntity($this->element).")";
1602
+					$sql .= " AND ug.fk_user = te.rowid";
1603
+					$sql .= " AND ug.entity IN (".getEntity($this->element).")";
1604 1604
 				}
1605 1605
 			} else {
1606
-				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1606
+				$sql .= ' AND te.entity IN ('.getEntity($this->element).')';
1607 1607
 			}
1608 1608
 		}
1609
-		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid;
1610
-		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1611
-		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid;
1609
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
1610
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
1611
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
1612 1612
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1613 1613
 
1614 1614
 		$result = $this->db->query($sql);
1615
-		if (! $result)
1615
+		if (!$result)
1616 1616
 		{
1617
-			$this->error=$this->db->lasterror();
1617
+			$this->error = $this->db->lasterror();
1618 1618
 			return -1;
1619 1619
 		}
1620 1620
 		$row = $this->db->fetch_row($result);
@@ -1622,46 +1622,46 @@  discard block
 block discarded – undo
1622 1622
 
1623 1623
 
1624 1624
 		$sql = "SELECT MIN(te.".$fieldid.")";
1625
-		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
1625
+		$sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
1626 1626
 		if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1627
-            $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1628
-		}
1629
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to entity
1630
-		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ", ".MAIN_DB_PREFIX."societe as s";	// If we need to link to societe to limit select to socid
1631
-		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";	// If we need to link to societe to limit select to socid
1632
-		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1633
-		$sql.= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'";  // ->ref must always be defined (set to id if field does not exists)
1634
-		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND sc.fk_user = " .$user->id;
1635
-		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1636
-		if (! empty($filter))
1637
-		{
1638
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1639
-			$sql.=$filter;
1640
-		}
1641
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to entity
1642
-		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql.= ' AND te.fk_soc = s.rowid';			// If we need to link to societe to limit select to socid
1627
+            $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1628
+		}
1629
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to entity
1630
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s"; // If we need to link to societe to limit select to socid
1631
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid"; // If we need to link to societe to limit select to socid
1632
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1633
+		$sql .= " WHERE te.".$fieldid." > '".$this->db->escape($this->ref)."'"; // ->ref must always be defined (set to id if field does not exists)
1634
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id;
1635
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) $sql .= " AND (sc.fk_user = ".$user->id.' OR te.fk_soc IS NULL)';
1636
+		if (!empty($filter))
1637
+		{
1638
+			if (!preg_match('/^\s*AND/i', $filter)) $sql .= " AND "; // For backward compatibility
1639
+			$sql .= $filter;
1640
+		}
1641
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to entity
1642
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) $sql .= ' AND te.fk_soc = s.rowid'; // If we need to link to societe to limit select to socid
1643 1643
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644 1644
 			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645 1645
                 if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1646
-                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1646
+                    $sql .= " AND te.entity IS NOT NULL"; // Show all users
1647 1647
 				} else {
1648
-					$sql.= " AND ug.fk_user = te.rowid";
1649
-					$sql.= " AND ug.entity IN (".getEntity($this->element).")";
1648
+					$sql .= " AND ug.fk_user = te.rowid";
1649
+					$sql .= " AND ug.entity IN (".getEntity($this->element).")";
1650 1650
 				}
1651 1651
 			} else {
1652
-				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1652
+				$sql .= ' AND te.entity IN ('.getEntity($this->element).')';
1653 1653
 			}
1654 1654
 		}
1655
-		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql.= ' AND te.fk_soc = ' . $socid;
1656
-		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1657
-		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql.= ' AND te.rowid = ' . $socid;
1655
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') $sql .= ' AND te.fk_soc = '.$socid;
1656
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') $sql .= ' AND (te.fk_soc = '.$socid.' OR te.fk_soc IS NULL)';
1657
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') $sql .= ' AND te.rowid = '.$socid;
1658 1658
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1659 1659
 		// Rem: Bug in some mysql version: SELECT MIN(rowid) FROM llx_socpeople WHERE rowid > 1 when one row in database with rowid=1, returns 1 instead of null
1660 1660
 
1661 1661
 		$result = $this->db->query($sql);
1662
-		if (! $result)
1662
+		if (!$result)
1663 1663
 		{
1664
-			$this->error=$this->db->lasterror();
1664
+			$this->error = $this->db->lasterror();
1665 1665
 			return -2;
1666 1666
 		}
1667 1667
 		$row = $this->db->fetch_row($result);
@@ -1678,11 +1678,11 @@  discard block
 block discarded – undo
1678 1678
 	 *      @return array				Array of id of contacts (if source=external or internal)
1679 1679
 	 * 									Array of id of third parties with at least one contact on object (if source=thirdparty)
1680 1680
 	 */
1681
-	function getListContactId($source='external')
1681
+	function getListContactId($source = 'external')
1682 1682
 	{
1683 1683
 		$contactAlreadySelected = array();
1684
-		$tab = $this->liste_contact(-1,$source);
1685
-		$num=count($tab);
1684
+		$tab = $this->liste_contact(-1, $source);
1685
+		$num = count($tab);
1686 1686
 		$i = 0;
1687 1687
 		while ($i < $num)
1688 1688
 		{
@@ -1702,24 +1702,24 @@  discard block
 block discarded – undo
1702 1702
 	 */
1703 1703
 	function setProject($projectid)
1704 1704
 	{
1705
-		if (! $this->table_element)
1705
+		if (!$this->table_element)
1706 1706
 		{
1707
-			dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
1707
+			dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined", LOG_ERR);
1708 1708
 			return -1;
1709 1709
 		}
1710 1710
 
1711 1711
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1712 1712
 		if ($this->table_element == 'actioncomm')
1713 1713
 		{
1714
-			if ($projectid) $sql.= ' SET fk_project = '.$projectid;
1715
-			else $sql.= ' SET fk_project = NULL';
1716
-			$sql.= ' WHERE id = '.$this->id;
1714
+			if ($projectid) $sql .= ' SET fk_project = '.$projectid;
1715
+			else $sql .= ' SET fk_project = NULL';
1716
+			$sql .= ' WHERE id = '.$this->id;
1717 1717
 		}
1718 1718
 		else
1719 1719
 		{
1720
-			if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
1721
-			else $sql.= ' SET fk_projet = NULL';
1722
-			$sql.= ' WHERE rowid = '.$this->id;
1720
+			if ($projectid) $sql .= ' SET fk_projet = '.$projectid;
1721
+			else $sql .= ' SET fk_projet = NULL';
1722
+			$sql .= ' WHERE rowid = '.$this->id;
1723 1723
 		}
1724 1724
 
1725 1725
 		dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
@@ -1765,14 +1765,14 @@  discard block
 block discarded – undo
1765 1765
 			else
1766 1766
 			{
1767 1767
 				dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
1768
-				$this->error=$this->db->error();
1768
+				$this->error = $this->db->error();
1769 1769
 				return -1;
1770 1770
 			}
1771 1771
 		}
1772 1772
 		else
1773 1773
 		{
1774 1774
 			dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
1775
-			$this->error='Status of the object is incompatible '.$this->statut;
1775
+			$this->error = 'Status of the object is incompatible '.$this->statut;
1776 1776
 			return -2;
1777 1777
 		}
1778 1778
 	}
@@ -1799,21 +1799,21 @@  discard block
 block discarded – undo
1799 1799
 				$this->multicurrency_code = $code;
1800 1800
 
1801 1801
 				list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
-				if ($rate) $this->setMulticurrencyRate($rate,2);
1802
+				if ($rate) $this->setMulticurrencyRate($rate, 2);
1803 1803
 
1804 1804
 				return 1;
1805 1805
 			}
1806 1806
 			else
1807 1807
 			{
1808 1808
 				dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
1809
-				$this->error=$this->db->error();
1809
+				$this->error = $this->db->error();
1810 1810
 				return -1;
1811 1811
 			}
1812 1812
 		}
1813 1813
 		else
1814 1814
 		{
1815 1815
 			dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
1816
-			$this->error='Status of the object is incompatible '.$this->statut;
1816
+			$this->error = 'Status of the object is incompatible '.$this->statut;
1817 1817
 			return -2;
1818 1818
 		}
1819 1819
 	}
@@ -1825,7 +1825,7 @@  discard block
 block discarded – undo
1825 1825
 	 *  @param		int		$mode	mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency
1826 1826
 	 *  @return		int				>0 if OK, <0 if KO
1827 1827
 	 */
1828
-	function setMulticurrencyRate($rate, $mode=1)
1828
+	function setMulticurrencyRate($rate, $mode = 1)
1829 1829
 	{
1830 1830
 		dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
1831 1831
 		if ($this->statut >= 0 || $this->element == 'societe')
@@ -1845,7 +1845,7 @@  discard block
 block discarded – undo
1845 1845
 				{
1846 1846
 					foreach ($this->lines as &$line)
1847 1847
 					{
1848
-						if($mode == 1) {
1848
+						if ($mode == 1) {
1849 1849
 							$line->subprice = 0;
1850 1850
 						}
1851 1851
 
@@ -1853,14 +1853,14 @@  discard block
 block discarded – undo
1853 1853
 							case 'propal':
1854 1854
 								$this->updateline(
1855 1855
 									$line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
1856
-									($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
1856
+									($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
1857 1857
 									$line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
1858 1858
 									$line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1859 1859
 								);
1860 1860
 								break;
1861 1861
 							case 'commande':
1862 1862
 								$this->updateline(
1863
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1863
+									$line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
1864 1864
 									$line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
1865 1865
 									$line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1866 1866
 									$line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
@@ -1868,7 +1868,7 @@  discard block
 block discarded – undo
1868 1868
 								break;
1869 1869
 							case 'facture':
1870 1870
 								$this->updateline(
1871
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1871
+									$line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
1872 1872
 									$line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
1873 1873
 									$line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1874 1874
 									$line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
@@ -1877,21 +1877,21 @@  discard block
 block discarded – undo
1877 1877
 							case 'supplier_proposal':
1878 1878
 								$this->updateline(
1879 1879
 									$line->id, $line->subprice, $line->qty, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx,
1880
-									($line->description?$line->description:$line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
1880
+									($line->description ? $line->description : $line->desc), 'HT', $line->info_bits, $line->special_code, $line->fk_parent_line,
1881 1881
 									$line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
1882 1882
 									$line->ref_fourn, $line->multicurrency_subprice
1883 1883
 								);
1884 1884
 								break;
1885 1885
 							case 'order_supplier':
1886 1886
 								$this->updateline(
1887
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1887
+									$line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->qty, $line->remise_percent,
1888 1888
 									$line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
1889 1889
 									$line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1890 1890
 								);
1891 1891
 								break;
1892 1892
 							case 'invoice_supplier':
1893 1893
 								$this->updateline(
1894
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
1894
+									$line->id, ($line->description ? $line->description : $line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
1895 1895
 									$line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
1896 1896
 									$line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1897 1897
 								);
@@ -1908,14 +1908,14 @@  discard block
 block discarded – undo
1908 1908
 			else
1909 1909
 			{
1910 1910
 				dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
1911
-				$this->error=$this->db->error();
1911
+				$this->error = $this->db->error();
1912 1912
 				return -1;
1913 1913
 			}
1914 1914
 		}
1915 1915
 		else
1916 1916
 		{
1917 1917
 			dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
1918
-			$this->error='Status of the object is incompatible '.$this->statut;
1918
+			$this->error = 'Status of the object is incompatible '.$this->statut;
1919 1919
 			return -2;
1920 1920
 		}
1921 1921
 	}
@@ -1945,20 +1945,20 @@  discard block
 block discarded – undo
1945 1945
 				$this->cond_reglement_id = $id;
1946 1946
 				// for supplier
1947 1947
 				if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
1948
-				$this->cond_reglement = $id;	// for compatibility
1948
+				$this->cond_reglement = $id; // for compatibility
1949 1949
 				return 1;
1950 1950
 			}
1951 1951
 			else
1952 1952
 			{
1953 1953
 				dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
1954
-				$this->error=$this->db->error();
1954
+				$this->error = $this->db->error();
1955 1955
 				return -1;
1956 1956
 			}
1957 1957
 		}
1958 1958
 		else
1959 1959
 		{
1960 1960
 			dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
1961
-			$this->error='Status of the object is incompatible '.$this->statut;
1961
+			$this->error = 'Status of the object is incompatible '.$this->statut;
1962 1962
 			return -2;
1963 1963
 		}
1964 1964
 	}
@@ -1976,7 +1976,7 @@  discard block
 block discarded – undo
1976 1976
 		if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
1977 1977
 
1978 1978
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
1979
-		$sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
1979
+		$sql .= " WHERE rowid = ".$this->id." AND fk_statut = 0";
1980 1980
 
1981 1981
 		if ($this->db->query($sql))
1982 1982
 		{
@@ -1985,7 +1985,7 @@  discard block
 block discarded – undo
1985 1985
 		}
1986 1986
 		else
1987 1987
 		{
1988
-			$this->error=$this->db->error();
1988
+			$this->error = $this->db->error();
1989 1989
 			dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
1990 1990
 			return -1;
1991 1991
 		}
@@ -2001,29 +2001,29 @@  discard block
 block discarded – undo
2001 2001
 	 *
2002 2002
 	 *  @return     int              1 if OK, 0 if KO
2003 2003
 	 */
2004
-	function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
2004
+	function setShippingMethod($shipping_method_id, $notrigger = false, $userused = null)
2005 2005
 	{
2006 2006
         global $user;
2007 2007
 
2008
-        if (empty($userused)) $userused=$user;
2008
+        if (empty($userused)) $userused = $user;
2009 2009
 
2010 2010
         $error = 0;
2011 2011
 
2012
-		if (! $this->table_element) {
2013
-			dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined",LOG_ERR);
2012
+		if (!$this->table_element) {
2013
+			dol_syslog(get_class($this)."::setShippingMethod was called on objet with property table_element not defined", LOG_ERR);
2014 2014
 			return -1;
2015 2015
 		}
2016 2016
 
2017 2017
         $this->db->begin();
2018 2018
 
2019
-		if ($shipping_method_id<0) $shipping_method_id='NULL';
2019
+		if ($shipping_method_id < 0) $shipping_method_id = 'NULL';
2020 2020
 		dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2021 2021
 
2022 2022
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2023
-		$sql.= " SET fk_shipping_method = ".$shipping_method_id;
2024
-		$sql.= " WHERE rowid=".$this->id;
2023
+		$sql .= " SET fk_shipping_method = ".$shipping_method_id;
2024
+		$sql .= " WHERE rowid=".$this->id;
2025 2025
         $resql = $this->db->query($sql);
2026
-		if (! $resql) {
2026
+		if (!$resql) {
2027 2027
 			dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2028 2028
 			$this->error = $this->db->lasterror();
2029 2029
 			$error++;
@@ -2031,8 +2031,8 @@  discard block
 block discarded – undo
2031 2031
             if (!$notrigger)
2032 2032
             {
2033 2033
                 // Call trigger
2034
-                $this->context=array('shippingmethodupdate'=>1);
2035
-                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2034
+                $this->context = array('shippingmethodupdate'=>1);
2035
+                $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2036 2036
                 if ($result < 0) $error++;
2037 2037
                 // End call trigger
2038 2038
             }
@@ -2042,7 +2042,7 @@  discard block
 block discarded – undo
2042 2042
             $this->db->rollback();
2043 2043
             return -1;
2044 2044
         } else {
2045
-            $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
2045
+            $this->shipping_method_id = ($shipping_method_id == 'NULL') ?null:$shipping_method_id;
2046 2046
             $this->db->commit();
2047 2047
             return 1;
2048 2048
         }
@@ -2057,23 +2057,23 @@  discard block
 block discarded – undo
2057 2057
 	 */
2058 2058
 	function setWarehouse($warehouse_id)
2059 2059
 	{
2060
-		if (! $this->table_element) {
2061
-			dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
2060
+		if (!$this->table_element) {
2061
+			dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined", LOG_ERR);
2062 2062
 			return -1;
2063 2063
 		}
2064
-		if ($warehouse_id<0) $warehouse_id='NULL';
2064
+		if ($warehouse_id < 0) $warehouse_id = 'NULL';
2065 2065
 		dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2066 2066
 
2067 2067
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2068
-		$sql.= " SET fk_warehouse = ".$warehouse_id;
2069
-		$sql.= " WHERE rowid=".$this->id;
2068
+		$sql .= " SET fk_warehouse = ".$warehouse_id;
2069
+		$sql .= " WHERE rowid=".$this->id;
2070 2070
 
2071 2071
 		if ($this->db->query($sql)) {
2072
-			$this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
2072
+			$this->warehouse_id = ($warehouse_id == 'NULL') ?null:$warehouse_id;
2073 2073
 			return 1;
2074 2074
 		} else {
2075 2075
 			dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2076
-			$this->error=$this->db->error();
2076
+			$this->error = $this->db->error();
2077 2077
 			return 0;
2078 2078
 		}
2079 2079
 	}
@@ -2088,25 +2088,25 @@  discard block
 block discarded – undo
2088 2088
 	 */
2089 2089
 	function setDocModel($user, $modelpdf)
2090 2090
 	{
2091
-		if (! $this->table_element)
2091
+		if (!$this->table_element)
2092 2092
 		{
2093
-			dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
2093
+			dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined", LOG_ERR);
2094 2094
 			return -1;
2095 2095
 		}
2096 2096
 
2097
-		$newmodelpdf=dol_trunc($modelpdf,255);
2097
+		$newmodelpdf = dol_trunc($modelpdf, 255);
2098 2098
 
2099 2099
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2100
-		$sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2101
-		$sql.= " WHERE rowid = ".$this->id;
2100
+		$sql .= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2101
+		$sql .= " WHERE rowid = ".$this->id;
2102 2102
 		// if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
2103 2103
 		// if ($this->element == 'propal')  $sql.= " AND fk_statut = 0";
2104 2104
 
2105 2105
 		dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2106
-		$resql=$this->db->query($sql);
2106
+		$resql = $this->db->query($sql);
2107 2107
 		if ($resql)
2108 2108
 		{
2109
-			$this->modelpdf=$modelpdf;
2109
+			$this->modelpdf = $modelpdf;
2110 2110
 			return 1;
2111 2111
 		}
2112 2112
 		else
@@ -2125,29 +2125,29 @@  discard block
 block discarded – undo
2125 2125
 	 *  @param      User	$userused		Object user
2126 2126
 	 *  @return		int				1 if OK, 0 if KO
2127 2127
 	 */
2128
-	function setBankAccount($fk_account, $notrigger=false, $userused=null)
2128
+	function setBankAccount($fk_account, $notrigger = false, $userused = null)
2129 2129
 	{
2130 2130
         global $user;
2131 2131
 
2132
-        if (empty($userused)) $userused=$user;
2132
+        if (empty($userused)) $userused = $user;
2133 2133
 
2134 2134
         $error = 0;
2135 2135
 
2136
-		if (! $this->table_element) {
2137
-			dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined",LOG_ERR);
2136
+		if (!$this->table_element) {
2137
+			dol_syslog(get_class($this)."::setBankAccount was called on objet with property table_element not defined", LOG_ERR);
2138 2138
 			return -1;
2139 2139
 		}
2140 2140
         $this->db->begin();
2141 2141
 
2142
-		if ($fk_account<0) $fk_account='NULL';
2142
+		if ($fk_account < 0) $fk_account = 'NULL';
2143 2143
 		dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2144 2144
 
2145 2145
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2146
-		$sql.= " SET fk_account = ".$fk_account;
2147
-		$sql.= " WHERE rowid=".$this->id;
2146
+		$sql .= " SET fk_account = ".$fk_account;
2147
+		$sql .= " WHERE rowid=".$this->id;
2148 2148
 
2149 2149
         $resql = $this->db->query($sql);
2150
-        if (! $resql)
2150
+        if (!$resql)
2151 2151
         {
2152 2152
             dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153 2153
             $this->error = $this->db->lasterror();
@@ -2158,8 +2158,8 @@  discard block
 block discarded – undo
2158 2158
             if (!$notrigger)
2159 2159
             {
2160 2160
                 // Call trigger
2161
-                $this->context=array('bankaccountupdate'=>1);
2162
-                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2161
+                $this->context = array('bankaccountupdate'=>1);
2162
+                $result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $userused);
2163 2163
                 if ($result < 0) $error++;
2164 2164
                 // End call trigger
2165 2165
             }
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
         }
2172 2172
         else
2173 2173
         {
2174
-            $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2174
+            $this->fk_account = ($fk_account == 'NULL') ?null:$fk_account;
2175 2175
             $this->db->commit();
2176 2176
             return 1;
2177 2177
         }
@@ -2190,26 +2190,26 @@  discard block
 block discarded – undo
2190 2190
 	 * 	@param		boolean		$fk_parent_line    Table with fk_parent_line field or not
2191 2191
 	 * 	@return		int                            <0 if KO, >0 if OK
2192 2192
 	 */
2193
-	function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
2193
+	function line_order($renum = false, $rowidorder = 'ASC', $fk_parent_line = true)
2194 2194
 	{
2195 2195
         // phpcs:enable
2196
-		if (! $this->table_element_line)
2196
+		if (!$this->table_element_line)
2197 2197
 		{
2198
-			dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
2198
+			dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined", LOG_ERR);
2199 2199
 			return -1;
2200 2200
 		}
2201
-		if (! $this->fk_element)
2201
+		if (!$this->fk_element)
2202 2202
 		{
2203
-			dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
2203
+			dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined", LOG_ERR);
2204 2204
 			return -1;
2205 2205
 		}
2206 2206
 
2207 2207
 		// Count number of lines to reorder (according to choice $renum)
2208
-		$nl=0;
2208
+		$nl = 0;
2209 2209
 		$sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2210
-		$sql.= ' WHERE '.$this->fk_element.'='.$this->id;
2211
-		if (! $renum) $sql.= ' AND rang = 0';
2212
-		if ($renum) $sql.= ' AND rang <> 0';
2210
+		$sql .= ' WHERE '.$this->fk_element.'='.$this->id;
2211
+		if (!$renum) $sql .= ' AND rang = 0';
2212
+		if ($renum) $sql .= ' AND rang <> 0';
2213 2213
 
2214 2214
 		dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
2215 2215
 		$resql = $this->db->query($sql);
@@ -2223,28 +2223,28 @@  discard block
 block discarded – undo
2223 2223
 		{
2224 2224
 			// The goal of this part is to reorder all lines, with all children lines sharing the same
2225 2225
 			// counter that parents.
2226
-			$rows=array();
2226
+			$rows = array();
2227 2227
 
2228 2228
 			// We first search all lines that are parent lines (for multilevel details lines)
2229 2229
 			$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2230
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2231
-			if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
2232
-			$sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
2230
+			$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2231
+			if ($fk_parent_line) $sql .= ' AND fk_parent_line IS NULL';
2232
+			$sql .= ' ORDER BY rang ASC, rowid '.$rowidorder;
2233 2233
 
2234 2234
 			dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
2235 2235
 			$resql = $this->db->query($sql);
2236 2236
 			if ($resql)
2237 2237
 			{
2238
-				$i=0;
2238
+				$i = 0;
2239 2239
 				$num = $this->db->num_rows($resql);
2240 2240
 				while ($i < $num)
2241 2241
 				{
2242 2242
 					$row = $this->db->fetch_row($resql);
2243
-					$rows[] = $row[0];	// Add parent line into array rows
2243
+					$rows[] = $row[0]; // Add parent line into array rows
2244 2244
 					$childrens = $this->getChildrenOfLine($row[0]);
2245
-					if (! empty($childrens))
2245
+					if (!empty($childrens))
2246 2246
 					{
2247
-						foreach($childrens as $child)
2247
+						foreach ($childrens as $child)
2248 2248
 						{
2249 2249
 							array_push($rows, $child);
2250 2250
 						}
@@ -2253,11 +2253,11 @@  discard block
 block discarded – undo
2253 2253
 				}
2254 2254
 
2255 2255
 				// Now we set a new number for each lines (parent and children with children included into parent tree)
2256
-				if (! empty($rows))
2256
+				if (!empty($rows))
2257 2257
 				{
2258
-					foreach($rows as $key => $row)
2258
+					foreach ($rows as $key => $row)
2259 2259
 					{
2260
-						$this->updateRangOfLine($row, ($key+1));
2260
+						$this->updateRangOfLine($row, ($key + 1));
2261 2261
 					}
2262 2262
 				}
2263 2263
 			}
@@ -2277,18 +2277,18 @@  discard block
 block discarded – undo
2277 2277
 	 */
2278 2278
 	function getChildrenOfLine($id)
2279 2279
 	{
2280
-		$rows=array();
2280
+		$rows = array();
2281 2281
 
2282 2282
 		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2283
-		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2284
-		$sql.= ' AND fk_parent_line = '.$id;
2285
-		$sql.= ' ORDER BY rang ASC';
2283
+		$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2284
+		$sql .= ' AND fk_parent_line = '.$id;
2285
+		$sql .= ' ORDER BY rang ASC';
2286 2286
 
2287 2287
 		dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
2288 2288
 		$resql = $this->db->query($sql);
2289 2289
 		if ($resql)
2290 2290
 		{
2291
-			$i=0;
2291
+			$i = 0;
2292 2292
 			$num = $this->db->num_rows($resql);
2293 2293
 			while ($i < $num)
2294 2294
 			{
@@ -2309,7 +2309,7 @@  discard block
 block discarded – undo
2309 2309
 	 * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2310 2310
 	 * 	@return	void
2311 2311
 	 */
2312
-	function line_up($rowid, $fk_parent_line=true)
2312
+	function line_up($rowid, $fk_parent_line = true)
2313 2313
 	{
2314 2314
         // phpcs:enable
2315 2315
 		$this->line_order(false, 'ASC', $fk_parent_line);
@@ -2329,7 +2329,7 @@  discard block
 block discarded – undo
2329 2329
 	 * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2330 2330
 	 * 	@return	void
2331 2331
 	 */
2332
-	function line_down($rowid, $fk_parent_line=true)
2332
+	function line_down($rowid, $fk_parent_line = true)
2333 2333
 	{
2334 2334
         // phpcs:enable
2335 2335
 		$this->line_order(false, 'ASC', $fk_parent_line);
@@ -2351,16 +2351,16 @@  discard block
 block discarded – undo
2351 2351
 	 * 	@param	int		$rang		Position
2352 2352
 	 * 	@return	void
2353 2353
 	 */
2354
-	function updateRangOfLine($rowid,$rang)
2354
+	function updateRangOfLine($rowid, $rang)
2355 2355
 	{
2356 2356
 		$fieldposition = 'rang';
2357 2357
 		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2358 2358
 
2359 2359
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2360
-		$sql.= ' WHERE rowid = '.$rowid;
2360
+		$sql .= ' WHERE rowid = '.$rowid;
2361 2361
 
2362 2362
 		dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
2363
-		if (! $this->db->query($sql))
2363
+		if (!$this->db->query($sql))
2364 2364
 		{
2365 2365
 			dol_print_error($this->db);
2366 2366
 		}
@@ -2377,9 +2377,9 @@  discard block
 block discarded – undo
2377 2377
 	{
2378 2378
         // phpcs:enable
2379 2379
 		$num = count($rows);
2380
-		for ($i = 0 ; $i < $num ; $i++)
2380
+		for ($i = 0; $i < $num; $i++)
2381 2381
 		{
2382
-			$this->updateRangOfLine($rows[$i], ($i+1));
2382
+			$this->updateRangOfLine($rows[$i], ($i + 1));
2383 2383
 		}
2384 2384
 	}
2385 2385
 
@@ -2390,21 +2390,21 @@  discard block
 block discarded – undo
2390 2390
 	 * 	@param	int		$rang		Position
2391 2391
 	 * 	@return	void
2392 2392
 	 */
2393
-	function updateLineUp($rowid,$rang)
2393
+	function updateLineUp($rowid, $rang)
2394 2394
 	{
2395 2395
 		if ($rang > 1)
2396 2396
 		{
2397 2397
 			$fieldposition = 'rang';
2398 2398
 			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2399 2399
 
2400
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang ;
2401
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2402
-			$sql.= ' AND rang = '.($rang - 1);
2403
-			if ($this->db->query($sql) )
2400
+			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2401
+			$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2402
+			$sql .= ' AND rang = '.($rang - 1);
2403
+			if ($this->db->query($sql))
2404 2404
 			{
2405 2405
 				$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang - 1);
2406
-				$sql.= ' WHERE rowid = '.$rowid;
2407
-				if (! $this->db->query($sql) )
2406
+				$sql .= ' WHERE rowid = '.$rowid;
2407
+				if (!$this->db->query($sql))
2408 2408
 				{
2409 2409
 					dol_print_error($this->db);
2410 2410
 				}
@@ -2424,7 +2424,7 @@  discard block
 block discarded – undo
2424 2424
 	 * 	@param	int		$max		Max
2425 2425
 	 * 	@return	void
2426 2426
 	 */
2427
-	function updateLineDown($rowid,$rang,$max)
2427
+	function updateLineDown($rowid, $rang, $max)
2428 2428
 	{
2429 2429
 		if ($rang < $max)
2430 2430
 		{
@@ -2432,13 +2432,13 @@  discard block
 block discarded – undo
2432 2432
 			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2433 2433
 
2434 2434
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2435
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2436
-			$sql.= ' AND rang = '.($rang+1);
2437
-			if ($this->db->query($sql) )
2435
+			$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2436
+			$sql .= ' AND rang = '.($rang + 1);
2437
+			if ($this->db->query($sql))
2438 2438
 			{
2439
-				$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang+1);
2440
-				$sql.= ' WHERE rowid = '.$rowid;
2441
-				if (! $this->db->query($sql) )
2439
+				$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.($rang + 1);
2440
+				$sql .= ' WHERE rowid = '.$rowid;
2441
+				if (!$this->db->query($sql))
2442 2442
 				{
2443 2443
 					dol_print_error($this->db);
2444 2444
 				}
@@ -2459,7 +2459,7 @@  discard block
 block discarded – undo
2459 2459
 	function getRangOfLine($rowid)
2460 2460
 	{
2461 2461
 		$sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2462
-		$sql.= ' WHERE rowid ='.$rowid;
2462
+		$sql .= ' WHERE rowid ='.$rowid;
2463 2463
 
2464 2464
 		dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
2465 2465
 		$resql = $this->db->query($sql);
@@ -2479,8 +2479,8 @@  discard block
 block discarded – undo
2479 2479
 	function getIdOfLine($rang)
2480 2480
 	{
2481 2481
 		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2482
-		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2483
-		$sql.= ' AND rang = '.$rang;
2482
+		$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2483
+		$sql .= ' AND rang = '.$rang;
2484 2484
 		$resql = $this->db->query($sql);
2485 2485
 		if ($resql)
2486 2486
 		{
@@ -2496,22 +2496,22 @@  discard block
 block discarded – undo
2496 2496
 	 * 	@param		int		$fk_parent_line		Parent line id
2497 2497
 	 *  @return     int  			   			Max value of rang in table of lines
2498 2498
 	 */
2499
-	function line_max($fk_parent_line=0)
2499
+	function line_max($fk_parent_line = 0)
2500 2500
 	{
2501 2501
         // phpcs:enable
2502 2502
 		// Search the last rang with fk_parent_line
2503 2503
 		if ($fk_parent_line)
2504 2504
 		{
2505 2505
 			$sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2506
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2507
-			$sql.= ' AND fk_parent_line = '.$fk_parent_line;
2506
+			$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2507
+			$sql .= ' AND fk_parent_line = '.$fk_parent_line;
2508 2508
 
2509 2509
 			dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2510 2510
 			$resql = $this->db->query($sql);
2511 2511
 			if ($resql)
2512 2512
 			{
2513 2513
 				$row = $this->db->fetch_row($resql);
2514
-				if (! empty($row[0]))
2514
+				if (!empty($row[0]))
2515 2515
 				{
2516 2516
 					return $row[0];
2517 2517
 				}
@@ -2525,7 +2525,7 @@  discard block
 block discarded – undo
2525 2525
 		else
2526 2526
 		{
2527 2527
 			$sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2528
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2528
+			$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2529 2529
 
2530 2530
 			dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2531 2531
 			$resql = $this->db->query($sql);
@@ -2547,15 +2547,15 @@  discard block
 block discarded – undo
2547 2547
 	function update_ref_ext($ref_ext)
2548 2548
 	{
2549 2549
         // phpcs:enable
2550
-		if (! $this->table_element)
2550
+		if (!$this->table_element)
2551 2551
 		{
2552 2552
 			dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
2553 2553
 			return -1;
2554 2554
 		}
2555 2555
 
2556 2556
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2557
-		$sql.= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
2558
-		$sql.= " WHERE ".(isset($this->table_rowid)?$this->table_rowid:'rowid')." = ". $this->id;
2557
+		$sql .= " SET ref_ext = '".$this->db->escape($ref_ext)."'";
2558
+		$sql .= " WHERE ".(isset($this->table_rowid) ? $this->table_rowid : 'rowid')." = ".$this->id;
2559 2559
 
2560 2560
 		dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
2561 2561
 		if ($this->db->query($sql))
@@ -2565,7 +2565,7 @@  discard block
 block discarded – undo
2565 2565
 		}
2566 2566
 		else
2567 2567
 		{
2568
-			$this->error=$this->db->error();
2568
+			$this->error = $this->db->error();
2569 2569
 			return -1;
2570 2570
 		}
2571 2571
 	}
@@ -2578,31 +2578,31 @@  discard block
 block discarded – undo
2578 2578
 	 *  @param		string		$suffix		'', '_public' or '_private'
2579 2579
 	 *  @return     int      		   		<0 if KO, >0 if OK
2580 2580
 	 */
2581
-	function update_note($note, $suffix='')
2581
+	function update_note($note, $suffix = '')
2582 2582
 	{
2583 2583
         // phpcs:enable
2584 2584
 		global $user;
2585 2585
 
2586
-		if (! $this->table_element)
2586
+		if (!$this->table_element)
2587 2587
 		{
2588
-			$this->error='update_note was called on objet with property table_element not defined';
2588
+			$this->error = 'update_note was called on objet with property table_element not defined';
2589 2589
 			dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
2590 2590
 			return -1;
2591 2591
 		}
2592
-		if (! in_array($suffix,array('','_public','_private')))
2592
+		if (!in_array($suffix, array('', '_public', '_private')))
2593 2593
 		{
2594
-			$this->error='update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
2594
+			$this->error = 'update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
2595 2595
 			dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
2596 2596
 			return -2;
2597 2597
 		}
2598 2598
 		// Special cas
2599 2599
 		//var_dump($this->table_element);exit;
2600
-		if ($this->table_element == 'product') $suffix='';
2600
+		if ($this->table_element == 'product') $suffix = '';
2601 2601
 
2602 2602
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2603
-		$sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
2604
-		$sql.= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))?"fk_user_mod":"fk_user_modif")." = ".$user->id;
2605
-		$sql.= " WHERE rowid =". $this->id;
2603
+		$sql .= " SET note".$suffix." = ".(!empty($note) ? ("'".$this->db->escape($note)."'") : "NULL");
2604
+		$sql .= " ,".(in_array($this->table_element, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment')) ? "fk_user_mod" : "fk_user_modif")." = ".$user->id;
2605
+		$sql .= " WHERE rowid =".$this->id;
2606 2606
 
2607 2607
 		dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
2608 2608
 		if ($this->db->query($sql))
@@ -2611,14 +2611,14 @@  discard block
 block discarded – undo
2611 2611
 			else if ($suffix == '_private') $this->note_private = $note;
2612 2612
 			else
2613 2613
 			{
2614
-				$this->note = $note;      // deprecated
2614
+				$this->note = $note; // deprecated
2615 2615
 				$this->note_private = $note;
2616 2616
 			}
2617 2617
 			return 1;
2618 2618
 		}
2619 2619
 		else
2620 2620
 		{
2621
-			$this->error=$this->db->lasterror();
2621
+			$this->error = $this->db->lasterror();
2622 2622
 			return -1;
2623 2623
 		}
2624 2624
 	}
@@ -2635,7 +2635,7 @@  discard block
 block discarded – undo
2635 2635
 	function update_note_public($note)
2636 2636
 	{
2637 2637
         // phpcs:enable
2638
-		return $this->update_note($note,'_public');
2638
+		return $this->update_note($note, '_public');
2639 2639
 	}
2640 2640
 
2641 2641
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -2649,7 +2649,7 @@  discard block
 block discarded – undo
2649 2649
 	 *  @param	Societe	$seller				If roundingadjust is '0' or '1' or maybe 'auto', it means we recalculate total for lines before calculating total for object and for this, we need seller object.
2650 2650
 	 *	@return	int    			           	<0 if KO, >0 if OK
2651 2651
 	 */
2652
-	function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
2652
+	function update_price($exclspec = 0, $roundingadjust = 'none', $nodatabaseupdate = 0, $seller = null)
2653 2653
 	{
2654 2654
         // phpcs:enable
2655 2655
 		global $conf, $hookmanager, $action;
@@ -2669,7 +2669,7 @@  discard block
 block discarded – undo
2669 2669
 		elseif ($this->element == 'supplier_proposal')
2670 2670
 			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2671 2671
 
2672
-		if (! empty($MODULE)) {
2672
+		if (!empty($MODULE)) {
2673 2673
 			if (!empty(Globals::$conf->global->$MODULE)) {
2674 2674
                 $modsactivated = explode(',', Globals::$conf->global->$MODULE);
2675 2675
                 foreach ($modsactivated as $mod) {
@@ -2681,45 +2681,45 @@  discard block
 block discarded – undo
2681 2681
 
2682 2682
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2683 2683
 
2684
-		if ($roundingadjust == '-1') $roundingadjust='auto';	// For backward compatibility
2684
+		if ($roundingadjust == '-1') $roundingadjust = 'auto'; // For backward compatibility
2685 2685
 
2686
-		$forcedroundingmode=$roundingadjust;
2686
+		$forcedroundingmode = $roundingadjust;
2687 2687
 		if ($forcedroundingmode == 'auto' && isset(Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND))
2688 2688
             $forcedroundingmode = Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2689
-        elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2689
+        elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0';
2690 2690
 
2691
-		$error=0;
2691
+		$error = 0;
2692 2692
 
2693 2693
 		$multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2694 2694
 
2695 2695
 		// Define constants to find lines to sum
2696
-		$fieldtva='total_tva';
2697
-		$fieldlocaltax1='total_localtax1';
2698
-		$fieldlocaltax2='total_localtax2';
2699
-		$fieldup='subprice';
2696
+		$fieldtva = 'total_tva';
2697
+		$fieldlocaltax1 = 'total_localtax1';
2698
+		$fieldlocaltax2 = 'total_localtax2';
2699
+		$fieldup = 'subprice';
2700 2700
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2701 2701
 		{
2702
-			$fieldtva='tva';
2703
-			$fieldup='pu_ht';
2702
+			$fieldtva = 'tva';
2703
+			$fieldup = 'pu_ht';
2704 2704
 		}
2705 2705
 		if ($this->element == 'expensereport')
2706 2706
 		{
2707
-			$fieldup='value_unit';
2707
+			$fieldup = 'value_unit';
2708 2708
 		}
2709 2709
 
2710 2710
 		$sql = 'SELECT rowid, qty, '.$fieldup.' as up, remise_percent, total_ht, '.$fieldtva.' as total_tva, total_ttc, '.$fieldlocaltax1.' as total_localtax1, '.$fieldlocaltax2.' as total_localtax2,';
2711
-		$sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2712
-			if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
2713
-			$sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2714
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2715
-		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2711
+		$sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2712
+			if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent';
2713
+			$sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2714
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2715
+		$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2716 2716
 		if ($exclspec)
2717 2717
 		{
2718
-			$product_field='product_type';
2719
-			if ($this->table_element_line == 'contratdet') $product_field='';    // contratdet table has no product_type field
2720
-			if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
2718
+			$product_field = 'product_type';
2719
+			if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field
2720
+			if ($product_field) $sql .= ' AND '.$product_field.' <> 9';
2721 2721
 		}
2722
-		$sql.= ' ORDER by rowid';	// We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
2722
+		$sql .= ' ORDER by rowid'; // We want to be sure to always use same order of line to not change lines differently when option MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND is used
2723 2723
 
2724 2724
 		dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2725 2725
 		$resql = $this->db->query($sql);
@@ -2733,7 +2733,7 @@  discard block
 block discarded – undo
2733 2733
 			$total_ht_by_vats  = array();
2734 2734
 			$total_tva_by_vats = array();
2735 2735
 			$total_ttc_by_vats = array();
2736
-			$this->multicurrency_total_ht	= 0;
2736
+			$this->multicurrency_total_ht = 0;
2737 2737
 			$this->multicurrency_total_tva	= 0;
2738 2738
 			$this->multicurrency_total_ttc	= 0;
2739 2739
 
@@ -2744,54 +2744,54 @@  discard block
 block discarded – undo
2744 2744
 				$obj = $this->db->fetch_object($resql);
2745 2745
 
2746 2746
 				// Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2747
-				$parameters=array('fk_element' => $obj->rowid);
2747
+				$parameters = array('fk_element' => $obj->rowid);
2748 2748
 				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2749 2749
 
2750 2750
 				if (empty($reshook) && $forcedroundingmode == '0')	// Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
2751 2751
 				{
2752
-					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2753
-					$tmpcal=calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
2754
-					$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2752
+					$localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
2753
+					$tmpcal = calcul_price_total($obj->qty, $obj->up, $obj->remise_percent, $obj->vatrate, $obj->localtax1_tx, $obj->localtax2_tx, 0, 'HT', $obj->info_bits, $obj->product_type, $seller, $localtax_array, (isset($obj->situation_percent) ? $obj->situation_percent : 100), $multicurrency_tx);
2754
+					$diff = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2755 2755
 					if ($diff)
2756 2756
 					{
2757
-						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2757
+						$sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2758 2758
 						dol_syslog('We found unconsistent data into detailed line (difference of '.$diff.') for line rowid = '.$obj->rowid." (total vat of line calculated=".$tmpcal[1].", database=".$obj->total_tva."). We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
2759
-								$resqlfix=$this->db->query($sqlfix);
2760
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2759
+								$resqlfix = $this->db->query($sqlfix);
2760
+								if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
2761 2761
 								$obj->total_tva = $tmpcal[1];
2762 2762
 								$obj->total_ttc = $tmpcal[2];
2763 2763
 						//
2764 2764
 					}
2765 2765
 				}
2766 2766
 
2767
-				$this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2767
+				$this->total_ht        += $obj->total_ht; // The field visible at end of line detail
2768 2768
 				$this->total_tva       += $obj->total_tva;
2769 2769
 				$this->total_localtax1 += $obj->total_localtax1;
2770 2770
 				$this->total_localtax2 += $obj->total_localtax2;
2771 2771
 				$this->total_ttc       += $obj->total_ttc;
2772
-				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2772
+				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht; // The field visible at end of line detail
2773 2773
 				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2774 2774
 				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2775 2775
 
2776
-				if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
2777
-				if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
2778
-				if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
2776
+				if (!isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate] = 0;
2777
+				if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0;
2778
+				if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0;
2779 2779
 				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2780 2780
 				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2781 2781
 				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2782 2782
 
2783 2783
 				if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2784 2784
 				{
2785
-					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2786
-					$diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2785
+					$tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2786
+					$diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
2787 2787
 					//print 'Line '.$i.' rowid='.$obj->rowid.' vat_rate='.$obj->vatrate.' total_ht='.$obj->total_ht.' total_tva='.$obj->total_tva.' total_ttc='.$obj->total_ttc.' total_ht_by_vats='.$total_ht_by_vats[$obj->vatrate].' total_tva_by_vats='.$total_tva_by_vats[$obj->vatrate].' (new calculation = '.$tmpvat.') total_ttc_by_vats='.$total_ttc_by_vats[$obj->vatrate].($diff?" => DIFF":"")."<br>\n";
2788 2788
 					if ($diff)
2789 2789
 					{
2790 2790
 						if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
2791
-						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
2791
+						$sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".($obj->total_tva - $diff).", total_ttc = ".($obj->total_ttc - $diff)." WHERE rowid = ".$obj->rowid;
2792 2792
 						dol_syslog('We found a difference of '.$diff.' for line rowid = '.$obj->rowid.". We fix the total_vat and total_ttc of line by running sqlfix = ".$sqlfix);
2793
-								$resqlfix=$this->db->query($sqlfix);
2794
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2793
+								$resqlfix = $this->db->query($sqlfix);
2794
+								if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
2795 2795
 								$this->total_tva -= $diff;
2796 2796
 								$this->total_ttc -= $diff;
2797 2797
 								$total_tva_by_vats[$obj->vatrate] -= $diff;
@@ -2803,11 +2803,11 @@  discard block
 block discarded – undo
2803 2803
 			}
2804 2804
 
2805 2805
 			// Add revenue stamp to total
2806
-			$this->total_ttc       			+= isset($this->revenuestamp)?$this->revenuestamp:0;
2807
-			$this->multicurrency_total_ttc  += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0;
2806
+			$this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
2807
+			$this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
2808 2808
 
2809 2809
 			// Situations totals
2810
-			if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE )
2810
+			if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE)
2811 2811
 			{
2812 2812
 				$prev_sits = $this->get_prev_sits();
2813 2813
 
@@ -2826,17 +2826,17 @@  discard block
 block discarded – undo
2826 2826
 			$this->db->free($resql);
2827 2827
 
2828 2828
 			// Now update global field total_ht, total_ttc and tva
2829
-			$fieldht='total_ht';
2830
-			$fieldtva='tva';
2831
-			$fieldlocaltax1='localtax1';
2832
-			$fieldlocaltax2='localtax2';
2833
-			$fieldttc='total_ttc';
2829
+			$fieldht = 'total_ht';
2830
+			$fieldtva = 'tva';
2831
+			$fieldlocaltax1 = 'localtax1';
2832
+			$fieldlocaltax2 = 'localtax2';
2833
+			$fieldttc = 'total_ttc';
2834 2834
 			// Specific code for backward compatibility with old field names
2835
-			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht='total';
2836
-			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
2837
-			if ($this->element == 'propal')                                                $fieldttc='total';
2838
-			if ($this->element == 'expensereport')                                         $fieldtva='total_tva';
2839
-			if ($this->element == 'supplier_proposal')                                     $fieldttc='total';
2835
+			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht = 'total';
2836
+			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva';
2837
+			if ($this->element == 'propal')                                                $fieldttc = 'total';
2838
+			if ($this->element == 'expensereport')                                         $fieldtva = 'total_tva';
2839
+			if ($this->element == 'supplier_proposal')                                     $fieldttc = 'total';
2840 2840
 
2841 2841
 			if (empty($nodatabaseupdate))
2842 2842
 			{
@@ -2853,16 +2853,16 @@  discard block
 block discarded – undo
2853 2853
 
2854 2854
 
2855 2855
 				dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2856
-				$resql=$this->db->query($sql);
2857
-				if (! $resql)
2856
+				$resql = $this->db->query($sql);
2857
+				if (!$resql)
2858 2858
 				{
2859 2859
 					$error++;
2860
-					$this->error=$this->db->lasterror();
2861
-					$this->errors[]=$this->db->lasterror();
2860
+					$this->error = $this->db->lasterror();
2861
+					$this->errors[] = $this->db->lasterror();
2862 2862
 				}
2863 2863
 			}
2864 2864
 
2865
-			if (! $error)
2865
+			if (!$error)
2866 2866
 			{
2867 2867
 				return 1;
2868 2868
 			}
@@ -2873,7 +2873,7 @@  discard block
 block discarded – undo
2873 2873
 		}
2874 2874
 		else
2875 2875
 		{
2876
-			dol_print_error($this->db,'Bad request in update_price');
2876
+			dol_print_error($this->db, 'Bad request in update_price');
2877 2877
 			return -1;
2878 2878
 		}
2879 2879
 	}
@@ -2887,30 +2887,30 @@  discard block
 block discarded – undo
2887 2887
 	 *	@return		int					<=0 if KO, >0 if OK
2888 2888
 	 *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2889 2889
 	 */
2890
-	function add_object_linked($origin=null, $origin_id=null)
2890
+	function add_object_linked($origin = null, $origin_id = null)
2891 2891
 	{
2892 2892
         // phpcs:enable
2893
-		$origin = (! empty($origin) ? $origin : $this->origin);
2894
-		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2893
+		$origin = (!empty($origin) ? $origin : $this->origin);
2894
+		$origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
2895 2895
 
2896 2896
 		// Special case
2897
-		if ($origin == 'order') $origin='commande';
2898
-		if ($origin == 'invoice') $origin='facture';
2899
-		if ($origin == 'invoice_template') $origin='facturerec';
2900
-    	if ($origin == 'supplierorder') $origin='order_supplier';
2897
+		if ($origin == 'order') $origin = 'commande';
2898
+		if ($origin == 'invoice') $origin = 'facture';
2899
+		if ($origin == 'invoice_template') $origin = 'facturerec';
2900
+    	if ($origin == 'supplierorder') $origin = 'order_supplier';
2901 2901
 		$this->db->begin();
2902 2902
 
2903 2903
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2904
-		$sql.= "fk_source";
2905
-		$sql.= ", sourcetype";
2906
-		$sql.= ", fk_target";
2907
-		$sql.= ", targettype";
2908
-		$sql.= ") VALUES (";
2909
-		$sql.= $origin_id;
2910
-		$sql.= ", '".$this->db->escape($origin)."'";
2911
-		$sql.= ", ".$this->id;
2912
-		$sql.= ", '".$this->db->escape($this->element)."'";
2913
-		$sql.= ")";
2904
+		$sql .= "fk_source";
2905
+		$sql .= ", sourcetype";
2906
+		$sql .= ", fk_target";
2907
+		$sql .= ", targettype";
2908
+		$sql .= ") VALUES (";
2909
+		$sql .= $origin_id;
2910
+		$sql .= ", '".$this->db->escape($origin)."'";
2911
+		$sql .= ", ".$this->id;
2912
+		$sql .= ", '".$this->db->escape($this->element)."'";
2913
+		$sql .= ")";
2914 2914
 
2915 2915
 		dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2916 2916
 		if ($this->db->query($sql))
@@ -2920,7 +2920,7 @@  discard block
 block discarded – undo
2920 2920
 	  	}
2921 2921
 	  	else
2922 2922
 	  	{
2923
-	  		$this->error=$this->db->lasterror();
2923
+	  		$this->error = $this->db->lasterror();
2924 2924
 	  		$this->db->rollback();
2925 2925
 	  		return 0;
2926 2926
 	  	}
@@ -2948,33 +2948,33 @@  discard block
 block discarded – undo
2948 2948
 	 *	@return int							<0 if KO, >0 if OK
2949 2949
 	 *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2950 2950
 	 */
2951
-	function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2951
+	function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
2952 2952
 	{
2953 2953
 		global $conf;
2954 2954
 
2955
-		$this->linkedObjectsIds=array();
2956
-		$this->linkedObjects=array();
2955
+		$this->linkedObjectsIds = array();
2956
+		$this->linkedObjects = array();
2957 2957
 
2958
-		$justsource=false;
2959
-		$justtarget=false;
2960
-		$withtargettype=false;
2961
-		$withsourcetype=false;
2958
+		$justsource = false;
2959
+		$justtarget = false;
2960
+		$withtargettype = false;
2961
+		$withsourcetype = false;
2962 2962
 
2963
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2963
+		if (!empty($sourceid) && !empty($sourcetype) && empty($targetid))
2964 2964
 		{
2965
-			$justsource=true;  // the source (id and type) is a search criteria
2966
-			if (! empty($targettype)) $withtargettype=true;
2965
+			$justsource = true; // the source (id and type) is a search criteria
2966
+			if (!empty($targettype)) $withtargettype = true;
2967 2967
 		}
2968
-		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2968
+		if (!empty($targetid) && !empty($targettype) && empty($sourceid))
2969 2969
 		{
2970
-			$justtarget=true;  // the target (id and type) is a search criteria
2971
-			if (! empty($sourcetype)) $withsourcetype=true;
2970
+			$justtarget = true; // the target (id and type) is a search criteria
2971
+			if (!empty($sourcetype)) $withsourcetype = true;
2972 2972
 		}
2973 2973
 
2974
-		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
2975
-		$targetid = (! empty($targetid) ? $targetid : $this->id);
2976
-		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
2977
-		$targettype = (! empty($targettype) ? $targettype : $this->element);
2974
+		$sourceid = (!empty($sourceid) ? $sourceid : $this->id);
2975
+		$targetid = (!empty($targetid) ? $targetid : $this->id);
2976
+		$sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
2977
+		$targettype = (!empty($targettype) ? $targettype : $this->element);
2978 2978
 
2979 2979
 		/*if (empty($sourceid) && empty($targetid))
2980 2980
 		 {
@@ -2984,25 +2984,25 @@  discard block
 block discarded – undo
2984 2984
 
2985 2985
 		// Links between objects are stored in table element_element
2986 2986
 		$sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2987
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2988
-		$sql.= " WHERE ";
2987
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
2988
+		$sql .= " WHERE ";
2989 2989
 		if ($justsource || $justtarget)
2990 2990
 		{
2991 2991
 			if ($justsource)
2992 2992
 			{
2993
-				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2994
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2993
+				$sql .= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2994
+				if ($withtargettype) $sql .= " AND targettype = '".$targettype."'";
2995 2995
 			}
2996 2996
 			else if ($justtarget)
2997 2997
 			{
2998
-				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2999
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
2998
+				$sql .= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2999
+				if ($withsourcetype) $sql .= " AND sourcetype = '".$sourcetype."'";
3000 3000
 			}
3001 3001
 		}
3002 3002
 		else
3003 3003
 		{
3004
-			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3005
-			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3004
+			$sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3005
+			$sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3006 3006
 		}
3007 3007
 		$sql .= ' ORDER BY '.$orderby;
3008 3008
 
@@ -3019,36 +3019,36 @@  discard block
 block discarded – undo
3019 3019
 				{
3020 3020
 					if ($justsource)
3021 3021
 					{
3022
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3022
+						$this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3023 3023
 					}
3024 3024
 					else if ($justtarget)
3025 3025
 					{
3026
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3026
+						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3027 3027
 					}
3028 3028
 				}
3029 3029
 				else
3030 3030
 				{
3031 3031
 					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3032 3032
 					{
3033
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3033
+						$this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3034 3034
 					}
3035 3035
 					if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3036 3036
 					{
3037
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3037
+						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3038 3038
 					}
3039 3039
 				}
3040 3040
 				$i++;
3041 3041
 			}
3042 3042
 
3043
-			if (! empty($this->linkedObjectsIds))
3043
+			if (!empty($this->linkedObjectsIds))
3044 3044
 			{
3045 3045
 				$tmparray = $this->linkedObjectsIds;
3046
-				foreach($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3046
+				foreach ($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3047 3047
 				{
3048 3048
 					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3049 3049
 					$module = $element = $subelement = $objecttype;
3050 3050
 					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3051
-						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3051
+						&& preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
3052 3052
 					{
3053 3053
 						$module = $element = $regs[1];
3054 3054
 						$subelement = $regs[2];
@@ -3056,31 +3056,31 @@  discard block
 block discarded – undo
3056 3056
 
3057 3057
 					$classpath = $element.'/class';
3058 3058
 					// To work with non standard classpath or module name
3059
-					if ($objecttype == 'facture')			{
3059
+					if ($objecttype == 'facture') {
3060 3060
 						$classpath = 'compta/facture/class';
3061 3061
 					}
3062
-					else if ($objecttype == 'facturerec')			{
3062
+					else if ($objecttype == 'facturerec') {
3063 3063
 						$classpath = 'compta/facture/class'; $module = 'facture';
3064 3064
 					}
3065
-					else if ($objecttype == 'propal')			{
3065
+					else if ($objecttype == 'propal') {
3066 3066
 						$classpath = 'comm/propal/class';
3067 3067
 					}
3068
-					else if ($objecttype == 'supplier_proposal')			{
3068
+					else if ($objecttype == 'supplier_proposal') {
3069 3069
 						$classpath = 'supplier_proposal/class';
3070 3070
 					}
3071
-					else if ($objecttype == 'shipping')			{
3071
+					else if ($objecttype == 'shipping') {
3072 3072
 						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3073 3073
 					}
3074
-					else if ($objecttype == 'delivery')			{
3074
+					else if ($objecttype == 'delivery') {
3075 3075
 						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3076 3076
 					}
3077
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3077
+					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
3078 3078
 						$classpath = 'fourn/class'; $module = 'fournisseur';
3079 3079
 					}
3080
-					else if ($objecttype == 'fichinter')			{
3080
+					else if ($objecttype == 'fichinter') {
3081 3081
 						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3082 3082
 					}
3083
-					else if ($objecttype == 'subscription')			{
3083
+					else if ($objecttype == 'subscription') {
3084 3084
 						$classpath = 'adherents/class'; $module = 'adherent';
3085 3085
 					}
3086 3086
 
@@ -3093,16 +3093,16 @@  discard block
 block discarded – undo
3093 3093
 					else if ($objecttype == 'invoice_supplier') {
3094 3094
 						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3095 3095
 					}
3096
-					else if ($objecttype == 'order_supplier')   {
3096
+					else if ($objecttype == 'order_supplier') {
3097 3097
 						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3098 3098
 					}
3099
-					else if ($objecttype == 'supplier_proposal')   {
3099
+					else if ($objecttype == 'supplier_proposal') {
3100 3100
 						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3101 3101
 					}
3102
-					else if ($objecttype == 'facturerec')   {
3102
+					else if ($objecttype == 'facturerec') {
3103 3103
 						$classfile = 'facture-rec'; $classname = 'FactureRec';
3104 3104
 					}
3105
-					else if ($objecttype == 'subscription')   {
3105
+					else if ($objecttype == 'subscription') {
3106 3106
 						$classfile = 'subscription'; $classname = 'Subscription';
3107 3107
 					}
3108 3108
 
@@ -3114,7 +3114,7 @@  discard block
 block discarded – undo
3114 3114
 							//print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
3115 3115
 							if (class_exists($classname))
3116 3116
 							{
3117
-								foreach($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3117
+								foreach ($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3118 3118
 								{
3119 3119
 									$object = new $classname($this->db);
3120 3120
 									$ret = $object->fetch($objectid);
@@ -3151,28 +3151,28 @@  discard block
 block discarded – undo
3151 3151
 	 *	@return							int	>0 if OK, <0 if KO
3152 3152
 	 *	@see	add_object_linked, fetObjectLinked, deleteObjectLinked
3153 3153
 	 */
3154
-	function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
3154
+	function updateObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '')
3155 3155
 	{
3156
-		$updatesource=false;
3157
-		$updatetarget=false;
3156
+		$updatesource = false;
3157
+		$updatetarget = false;
3158 3158
 
3159
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource=true;
3160
-		else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $updatetarget=true;
3159
+		if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $updatesource = true;
3160
+		else if (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $updatetarget = true;
3161 3161
 
3162 3162
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
3163 3163
 		if ($updatesource)
3164 3164
 		{
3165
-			$sql.= "fk_source = ".$sourceid;
3166
-			$sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'";
3167
-			$sql.= " WHERE fk_target = ".$this->id;
3168
-			$sql.= " AND targettype = '".$this->db->escape($this->element)."'";
3165
+			$sql .= "fk_source = ".$sourceid;
3166
+			$sql .= ", sourcetype = '".$this->db->escape($sourcetype)."'";
3167
+			$sql .= " WHERE fk_target = ".$this->id;
3168
+			$sql .= " AND targettype = '".$this->db->escape($this->element)."'";
3169 3169
 		}
3170 3170
 		else if ($updatetarget)
3171 3171
 		{
3172
-			$sql.= "fk_target = ".$targetid;
3173
-			$sql.= ", targettype = '".$this->db->escape($targettype)."'";
3174
-			$sql.= " WHERE fk_source = ".$this->id;
3175
-			$sql.= " AND sourcetype = '".$this->db->escape($this->element)."'";
3172
+			$sql .= "fk_target = ".$targetid;
3173
+			$sql .= ", targettype = '".$this->db->escape($targettype)."'";
3174
+			$sql .= " WHERE fk_source = ".$this->id;
3175
+			$sql .= " AND sourcetype = '".$this->db->escape($this->element)."'";
3176 3176
 		}
3177 3177
 
3178 3178
 		dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
@@ -3182,7 +3182,7 @@  discard block
 block discarded – undo
3182 3182
 		}
3183 3183
 		else
3184 3184
 		{
3185
-			$this->error=$this->db->lasterror();
3185
+			$this->error = $this->db->lasterror();
3186 3186
 			return -1;
3187 3187
 		}
3188 3188
 	}
@@ -3198,42 +3198,42 @@  discard block
 block discarded – undo
3198 3198
 	 *	@return     					int	>0 if OK, <0 if KO
3199 3199
 	 *	@see	add_object_linked, updateObjectLinked, fetchObjectLinked
3200 3200
 	 */
3201
-	function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
3201
+	function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '')
3202 3202
 	{
3203
-		$deletesource=false;
3204
-		$deletetarget=false;
3203
+		$deletesource = false;
3204
+		$deletetarget = false;
3205 3205
 
3206
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource=true;
3207
-		else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) $deletetarget=true;
3206
+		if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) $deletesource = true;
3207
+		else if (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) $deletetarget = true;
3208 3208
 
3209
-		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
3210
-		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
3211
-		$targetid = (! empty($targetid) ? $targetid : $this->id);
3212
-		$targettype = (! empty($targettype) ? $targettype : $this->element);
3209
+		$sourceid = (!empty($sourceid) ? $sourceid : $this->id);
3210
+		$sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
3211
+		$targetid = (!empty($targetid) ? $targetid : $this->id);
3212
+		$targettype = (!empty($targettype) ? $targettype : $this->element);
3213 3213
 
3214 3214
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
3215
-		$sql.= " WHERE";
3215
+		$sql .= " WHERE";
3216 3216
 		if ($rowid > 0)
3217 3217
 		{
3218
-			$sql.=" rowid = ".$rowid;
3218
+			$sql .= " rowid = ".$rowid;
3219 3219
 		}
3220 3220
 		else
3221 3221
 		{
3222 3222
 			if ($deletesource)
3223 3223
 			{
3224
-				$sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3225
-				$sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
3224
+				$sql .= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3225
+				$sql .= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
3226 3226
 			}
3227 3227
 			else if ($deletetarget)
3228 3228
 			{
3229
-				$sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
3230
-				$sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
3229
+				$sql .= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
3230
+				$sql .= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
3231 3231
 			}
3232 3232
 			else
3233 3233
 			{
3234
-				$sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
3235
-				$sql.= " OR";
3236
-				$sql.= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
3234
+				$sql .= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
3235
+				$sql .= " OR";
3236
+				$sql .= " (fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."')";
3237 3237
 			}
3238 3238
 		}
3239 3239
 
@@ -3244,8 +3244,8 @@  discard block
 block discarded – undo
3244 3244
 		}
3245 3245
 		else
3246 3246
 		{
3247
-			$this->error=$this->db->lasterror();
3248
-			$this->errors[]=$this->error;
3247
+			$this->error = $this->db->lasterror();
3248
+			$this->errors[] = $this->error;
3249 3249
 			return -1;
3250 3250
 		}
3251 3251
 	}
@@ -3259,30 +3259,30 @@  discard block
 block discarded – undo
3259 3259
 	 *      @param	string	$trigkey		Trigger key to use for trigger
3260 3260
 	 *      @return int						<0 if KO, >0 if OK
3261 3261
 	 */
3262
-	function setStatut($status, $elementId=null, $elementType='', $trigkey='')
3262
+	function setStatut($status, $elementId = null, $elementType = '', $trigkey = '')
3263 3263
 	{
3264
-		global $user,$langs,$conf;
3264
+		global $user, $langs, $conf;
3265 3265
 
3266
-		$savElementId=$elementId;  // To be used later to know if we were using the method using the id of this or not.
3266
+		$savElementId = $elementId; // To be used later to know if we were using the method using the id of this or not.
3267 3267
 
3268
-		$elementId = (!empty($elementId)?$elementId:$this->id);
3269
-		$elementTable = (!empty($elementType)?$elementType:$this->table_element);
3268
+		$elementId = (!empty($elementId) ? $elementId : $this->id);
3269
+		$elementTable = (!empty($elementType) ? $elementType : $this->table_element);
3270 3270
 
3271 3271
 		$this->db->begin();
3272 3272
 
3273
-		$fieldstatus="fk_statut";
3274
-		if ($elementTable == 'facture_rec') $fieldstatus="suspended";
3275
-		if ($elementTable == 'mailing') $fieldstatus="statut";
3276
-		if ($elementTable == 'cronjob') $fieldstatus="status";
3277
-		if ($elementTable == 'user') $fieldstatus="statut";
3278
-		if ($elementTable == 'expensereport') $fieldstatus="fk_statut";
3279
-		if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus="status";
3273
+		$fieldstatus = "fk_statut";
3274
+		if ($elementTable == 'facture_rec') $fieldstatus = "suspended";
3275
+		if ($elementTable == 'mailing') $fieldstatus = "statut";
3276
+		if ($elementTable == 'cronjob') $fieldstatus = "status";
3277
+		if ($elementTable == 'user') $fieldstatus = "statut";
3278
+		if ($elementTable == 'expensereport') $fieldstatus = "fk_statut";
3279
+		if ($elementTable == 'commande_fournisseur_dispatch') $fieldstatus = "status";
3280 3280
 
3281 3281
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
3282
-		$sql.= " SET ".$fieldstatus." = ".$status;
3282
+		$sql .= " SET ".$fieldstatus." = ".$status;
3283 3283
 		// If status = 1 = validated, update also fk_user_valid
3284
-		if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
3285
-		$sql.= " WHERE rowid=".$elementId;
3284
+		if ($status == 1 && $elementTable == 'expensereport') $sql .= ", fk_user_valid = ".$user->id;
3285
+		$sql .= " WHERE rowid=".$elementId;
3286 3286
 
3287 3287
 		dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
3288 3288
 		if ($this->db->query($sql))
@@ -3292,27 +3292,27 @@  discard block
 block discarded – undo
3292 3292
 			// Try autoset of trigkey
3293 3293
 			if (empty($trigkey))
3294 3294
 			{
3295
-				if ($this->element == 'supplier_proposal' && $status == 2) $trigkey='SUPPLIER_PROPOSAL_SIGN';   // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
3296
-				if ($this->element == 'supplier_proposal' && $status == 3) $trigkey='SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
3297
-				if ($this->element == 'supplier_proposal' && $status == 4) $trigkey='SUPPLIER_PROPOSAL_CLOSE';  // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
3298
-				if ($this->element == 'fichinter' && $status == 3) $trigkey='FICHINTER_CLASSIFY_DONE';
3299
-				if ($this->element == 'fichinter' && $status == 2) $trigkey='FICHINTER_CLASSIFY_BILLED';
3300
-				if ($this->element == 'fichinter' && $status == 1) $trigkey='FICHINTER_CLASSIFY_UNBILLED';
3295
+				if ($this->element == 'supplier_proposal' && $status == 2) $trigkey = 'SUPPLIER_PROPOSAL_SIGN'; // 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
3296
+				if ($this->element == 'supplier_proposal' && $status == 3) $trigkey = 'SUPPLIER_PROPOSAL_REFUSE'; // 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
3297
+				if ($this->element == 'supplier_proposal' && $status == 4) $trigkey = 'SUPPLIER_PROPOSAL_CLOSE'; // 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
3298
+				if ($this->element == 'fichinter' && $status == 3) $trigkey = 'FICHINTER_CLASSIFY_DONE';
3299
+				if ($this->element == 'fichinter' && $status == 2) $trigkey = 'FICHINTER_CLASSIFY_BILLED';
3300
+				if ($this->element == 'fichinter' && $status == 1) $trigkey = 'FICHINTER_CLASSIFY_UNBILLED';
3301 3301
 			}
3302 3302
 
3303 3303
 			if ($trigkey)
3304 3304
 			{
3305 3305
 				// Appel des triggers
3306
-				include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
3307
-				$interface=new Interfaces($this->db);
3308
-				$result=$interface->run_triggers($trigkey,$this,$user,$langs,$conf);
3306
+				include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
3307
+				$interface = new Interfaces($this->db);
3308
+				$result = $interface->run_triggers($trigkey, $this, $user, $langs, $conf);
3309 3309
 				if ($result < 0) {
3310
-					$error++; $this->errors=$interface->errors;
3310
+					$error++; $this->errors = $interface->errors;
3311 3311
 				}
3312 3312
 				// Fin appel triggers
3313 3313
 			}
3314 3314
 
3315
-			if (! $error)
3315
+			if (!$error)
3316 3316
 			{
3317 3317
 				$this->db->commit();
3318 3318
 
@@ -3327,13 +3327,13 @@  discard block
 block discarded – undo
3327 3327
 			else
3328 3328
 			{
3329 3329
 				$this->db->rollback();
3330
-				dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
3330
+				dol_syslog(get_class($this)."::setStatus ".$this->error, LOG_ERR);
3331 3331
 				return -1;
3332 3332
 			}
3333 3333
 		}
3334 3334
 		else
3335 3335
 		{
3336
-			$this->error=$this->db->lasterror();
3336
+			$this->error = $this->db->lasterror();
3337 3337
 			$this->db->rollback();
3338 3338
 			return -1;
3339 3339
 		}
@@ -3347,22 +3347,22 @@  discard block
 block discarded – undo
3347 3347
 	 *  @param      string	$ref    Record ref
3348 3348
 	 *  @return		int				<0 if KO, 0 if nothing done, >0 if OK
3349 3349
 	 */
3350
-	function getCanvas($id=0,$ref='')
3350
+	function getCanvas($id = 0, $ref = '')
3351 3351
 	{
3352 3352
 		global $conf;
3353 3353
 
3354 3354
 		if (empty($id) && empty($ref)) return 0;
3355 3355
 		if (!empty(Globals::$conf->global->MAIN_DISABLE_CANVAS))
3356
-            return 0;    // To increase speed. Not enabled by default.
3356
+            return 0; // To increase speed. Not enabled by default.
3357 3357
 
3358 3358
             // Clean parameters
3359 3359
 		$ref = trim($ref);
3360 3360
 
3361 3361
 		$sql = "SELECT rowid, canvas";
3362
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3363
-		$sql.= " WHERE entity IN (".getEntity($this->element).")";
3364
-		if (! empty($id))  $sql.= " AND rowid = ".$id;
3365
-		if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
3362
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3363
+		$sql .= " WHERE entity IN (".getEntity($this->element).")";
3364
+		if (!empty($id))  $sql .= " AND rowid = ".$id;
3365
+		if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'";
3366 3366
 
3367 3367
 		$resql = $this->db->query($sql);
3368 3368
 		if ($resql)
@@ -3370,7 +3370,7 @@  discard block
 block discarded – undo
3370 3370
 			$obj = $this->db->fetch_object($resql);
3371 3371
 			if ($obj)
3372 3372
 			{
3373
-				$this->canvas   = $obj->canvas;
3373
+				$this->canvas = $obj->canvas;
3374 3374
 				return 1;
3375 3375
 			}
3376 3376
 			else return 0;
@@ -3392,7 +3392,7 @@  discard block
 block discarded – undo
3392 3392
 	function getSpecialCode($lineid)
3393 3393
 	{
3394 3394
 		$sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3395
-		$sql.= ' WHERE rowid = '.$lineid;
3395
+		$sql .= ' WHERE rowid = '.$lineid;
3396 3396
 		$resql = $this->db->query($sql);
3397 3397
 		if ($resql)
3398 3398
 		{
@@ -3408,14 +3408,14 @@  discard block
 block discarded – undo
3408 3408
 	 *  @param	int		$id			Force id of object
3409 3409
 	 *  @return	int					<0 if KO, 0 if not used, >0 if already used
3410 3410
 	 */
3411
-	function isObjectUsed($id=0)
3411
+	function isObjectUsed($id = 0)
3412 3412
 	{
3413 3413
 		global $langs;
3414 3414
 
3415
-		if (empty($id)) $id=$this->id;
3415
+		if (empty($id)) $id = $this->id;
3416 3416
 
3417 3417
 		// Check parameters
3418
-		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3418
+		if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0)
3419 3419
 		{
3420 3420
 			dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3421 3421
 			return -1;
@@ -3423,24 +3423,24 @@  discard block
 block discarded – undo
3423 3423
 
3424 3424
 		$arraytoscan = $this->childtables;
3425 3425
 		// For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3426
-		$tmparray=array_keys($this->childtables);
3426
+		$tmparray = array_keys($this->childtables);
3427 3427
 		if (is_numeric($tmparray[0]))
3428 3428
 		{
3429 3429
 			$arraytoscan = array_flip($this->childtables);
3430 3430
 		}
3431 3431
 
3432 3432
 		// Test if child exists
3433
-		$haschild=0;
3434
-		foreach($arraytoscan as $table => $elementname)
3433
+		$haschild = 0;
3434
+		foreach ($arraytoscan as $table => $elementname)
3435 3435
 		{
3436 3436
 			//print $id.'-'.$table.'-'.$elementname.'<br>';
3437 3437
 			// Check if third party can be deleted
3438 3438
 			$sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3439
-			$sql.= " WHERE ".$this->fk_element." = ".$id;
3440
-			$resql=$this->db->query($sql);
3439
+			$sql .= " WHERE ".$this->fk_element." = ".$id;
3440
+			$resql = $this->db->query($sql);
3441 3441
 			if ($resql)
3442 3442
 			{
3443
-				$obj=$this->db->fetch_object($resql);
3443
+				$obj = $this->db->fetch_object($resql);
3444 3444
 				if ($obj->nb > 0)
3445 3445
 				{
3446 3446
 					$langs->load("errors");
@@ -3448,24 +3448,24 @@  discard block
 block discarded – undo
3448 3448
 					$haschild += $obj->nb;
3449 3449
 					if (is_numeric($elementname))	// old usage
3450 3450
 					{
3451
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3451
+						$this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3452 3452
 					}
3453 3453
 					else	// new usage: $elementname=Translation key
3454 3454
 					{
3455
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3455
+						$this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3456 3456
 					}
3457
-					break;    // We found at least one, we stop here
3457
+					break; // We found at least one, we stop here
3458 3458
 				}
3459 3459
 			}
3460 3460
 			else
3461 3461
 			{
3462
-				$this->errors[]=$this->db->lasterror();
3462
+				$this->errors[] = $this->db->lasterror();
3463 3463
 				return -1;
3464 3464
 			}
3465 3465
 		}
3466 3466
 		if ($haschild > 0)
3467 3467
 		{
3468
-			$this->errors[]="ErrorRecordHasChildren";
3468
+			$this->errors[] = "ErrorRecordHasChildren";
3469 3469
 			return $haschild;
3470 3470
 		}
3471 3471
 		else return 0;
@@ -3477,18 +3477,18 @@  discard block
 block discarded – undo
3477 3477
 	 *	@param	int		$predefined		-1=All, 0=Count free product/service only, 1=Count predefined product/service only, 2=Count predefined product, 3=Count predefined service
3478 3478
 	 *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3479 3479
 	 */
3480
-	function hasProductsOrServices($predefined=-1)
3480
+	function hasProductsOrServices($predefined = -1)
3481 3481
 	{
3482
-		$nb=0;
3482
+		$nb = 0;
3483 3483
 
3484
-		foreach($this->lines as $key => $val)
3484
+		foreach ($this->lines as $key => $val)
3485 3485
 		{
3486
-			$qualified=0;
3487
-			if ($predefined == -1) $qualified=1;
3488
-			if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
3489
-			if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
3490
-			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
3491
-			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
3486
+			$qualified = 0;
3487
+			if ($predefined == -1) $qualified = 1;
3488
+			if ($predefined == 1 && $val->fk_product > 0) $qualified = 1;
3489
+			if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1;
3490
+			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1;
3491
+			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1;
3492 3492
 			if ($qualified) $nb++;
3493 3493
 		}
3494 3494
 		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
@@ -3502,24 +3502,24 @@  discard block
 block discarded – undo
3502 3502
 	 */
3503 3503
 	function getTotalDiscount()
3504 3504
 	{
3505
-		$total_discount=0.00;
3505
+		$total_discount = 0.00;
3506 3506
 
3507 3507
 		$sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
3508
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3509
-		$sql.= " WHERE ".$this->fk_element." = ".$this->id;
3508
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3509
+		$sql .= " WHERE ".$this->fk_element." = ".$this->id;
3510 3510
 
3511 3511
 		dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3512 3512
 		$resql = $this->db->query($sql);
3513 3513
 		if ($resql)
3514 3514
 		{
3515
-			$num=$this->db->num_rows($resql);
3516
-			$i=0;
3515
+			$num = $this->db->num_rows($resql);
3516
+			$i = 0;
3517 3517
 			while ($i < $num)
3518 3518
 			{
3519 3519
 				$obj = $this->db->fetch_object($resql);
3520 3520
 
3521 3521
 				$pu_ht = $obj->pu_ht;
3522
-				$qty= $obj->qty;
3522
+				$qty = $obj->qty;
3523 3523
 				$total_ht = $obj->total_ht;
3524 3524
 
3525 3525
 				$total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
@@ -3553,17 +3553,17 @@  discard block
 block discarded – undo
3553 3553
 		{
3554 3554
 			if (isset($line->qty_asked))
3555 3555
 			{
3556
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3557
-				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3556
+				if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
3557
+				$totalOrdered += $line->qty_asked; // defined for shipment only
3558 3558
 			}
3559 3559
 			if (isset($line->qty_shipped))
3560 3560
 			{
3561
-				if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3562
-				$totalToShip+=$line->qty_shipped;   // defined for shipment only
3563
-            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3561
+				if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is ''
3562
+				$totalToShip += $line->qty_shipped; // defined for shipment only
3563
+            } else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3564 3564
             {
3565
-                if (empty($totalToShip)) $totalToShip=0;
3566
-                $totalToShip+=$line->qty;   // defined for reception only
3565
+                if (empty($totalToShip)) $totalToShip = 0;
3566
+                $totalToShip += $line->qty; // defined for reception only
3567 3567
 			}
3568 3568
 
3569 3569
 			// Define qty, weight, volume, weight_units, volume_units
@@ -3576,27 +3576,27 @@  discard block
 block discarded – undo
3576 3576
 			}
3577 3577
 
3578 3578
 			$weight = $line->weight ? $line->weight : 0;
3579
-            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3579
+            ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
3580 3580
 			$volume = $line->volume ? $line->volume : 0;
3581
-			($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
3581
+			($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
3582 3582
 
3583
-			$weight_units=$line->weight_units;
3584
-			($weight_units==0 && !empty($line->product->weight_units))? $weight_units=$line->product->weight_units: 0;
3585
-			$volume_units=$line->volume_units;
3586
-			($volume_units==0 && !empty($line->product->volume_units))? $volume_units=$line->product->volume_units: 0;
3583
+			$weight_units = $line->weight_units;
3584
+			($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
3585
+			$volume_units = $line->volume_units;
3586
+			($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
3587 3587
 
3588
-			$weightUnit=0;
3589
-			$volumeUnit=0;
3590
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3591
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
3588
+			$weightUnit = 0;
3589
+			$volumeUnit = 0;
3590
+			if (!empty($weight_units)) $weightUnit = $weight_units;
3591
+			if (!empty($volume_units)) $volumeUnit = $volume_units;
3592 3592
 
3593
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3594
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3593
+			if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is ''
3594
+			if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is ''
3595 3595
 
3596 3596
 			//var_dump($line->volume_units);
3597 3597
 			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3598 3598
 			{
3599
-				$trueWeightUnit=pow(10, $weightUnit);
3599
+				$trueWeightUnit = pow(10, $weightUnit);
3600 3600
 				$totalWeight += $weight * $qty * $trueWeightUnit;
3601 3601
 			}
3602 3602
 			else {
@@ -3610,18 +3610,18 @@  discard block
 block discarded – undo
3610 3610
 			$totalWeight += $weight * $qty * $trueWeightUnit;
3611 3611
 		}
3612 3612
 		else
3613
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3613
+					$totalWeight += $weight * $qty; // This may be wrong if we mix different units
3614 3614
 			}
3615 3615
 			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3616 3616
 			{
3617 3617
 				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3618
-				$trueVolumeUnit=pow(10, $volumeUnit);
3618
+				$trueVolumeUnit = pow(10, $volumeUnit);
3619 3619
 				//print $line->volume;
3620 3620
 				$totalVolume += $volume * $qty * $trueVolumeUnit;
3621 3621
 			}
3622 3622
 			else
3623 3623
 			{
3624
-				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3624
+				$totalVolume += $volume * $qty; // This may be wrong if we mix different units
3625 3625
 			}
3626 3626
 		}
3627 3627
 
@@ -3638,17 +3638,17 @@  discard block
 block discarded – undo
3638 3638
 	{
3639 3639
 		$this->db->begin();
3640 3640
 
3641
-		$extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3641
+		$extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
3642 3642
 
3643 3643
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3644
-		$sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3645
-		$sql.= " WHERE rowid = ".$this->id;
3644
+		$sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3645
+		$sql .= " WHERE rowid = ".$this->id;
3646 3646
 
3647 3647
 		dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3648 3648
 		$resql = $this->db->query($sql);
3649
-		if (! $resql)
3649
+		if (!$resql)
3650 3650
 		{
3651
-			$this->error=$this->db->lasterror();
3651
+			$this->error = $this->db->lasterror();
3652 3652
 			$this->db->rollback();
3653 3653
 			return -1;
3654 3654
 		}
@@ -3683,7 +3683,7 @@  discard block
 block discarded – undo
3683 3683
 			}
3684 3684
 		}
3685 3685
 
3686
-		$out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3686
+		$out .= (($res->code && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms;
3687 3687
 
3688 3688
 		return $out;
3689 3689
 	}
@@ -3729,11 +3729,11 @@  discard block
 block discarded – undo
3729 3729
 		if ($this->id && $this->table_element)
3730 3730
 		{
3731 3731
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3732
-			$sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3733
-			$sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3734
-			$sql.= " WHERE rowid = " . $this->id;
3732
+			$sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3733
+			$sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3734
+			$sql .= " WHERE rowid = ".$this->id;
3735 3735
 			dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3736
-			$resql=$this->db->query($sql);
3736
+			$resql = $this->db->query($sql);
3737 3737
 			if ($resql)
3738 3738
 			{
3739 3739
 				$this->fk_incoterms = $id_incoterm;
@@ -3774,24 +3774,24 @@  discard block
 block discarded – undo
3774 3774
 	 */
3775 3775
 	function formAddObjectLine($dateSelector, $seller, $buyer)
3776 3776
 	{
3777
-		global $conf,$user,$langs,$object,$hookmanager;
3778
-		global $form,$bcnd,$var;
3777
+		global $conf, $user, $langs, $object, $hookmanager;
3778
+		global $form, $bcnd, $var;
3779 3779
 
3780 3780
 		// Line extrafield
3781 3781
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3782 3782
 		$extrafieldsline = new ExtraFields($this->db);
3783
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3783
+		$extralabelslines = $extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3784 3784
 
3785 3785
 		// Output template part (modules that overwrite templates must declare this into descriptor)
3786 3786
 		// Use global variables + $dateSelector + $seller and $buyer
3787 3787
 		$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
3788
-        foreach($dirtpls as $reldir)
3788
+        foreach ($dirtpls as $reldir)
3789 3789
 		{
3790 3790
 			$tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3791 3791
 			if (empty(Globals::$conf->file->strict_mode)) {
3792
-                $res=@include $tpl;
3792
+                $res = @include $tpl;
3793 3793
 			} else {
3794
-				$res=include $tpl; // for debug
3794
+				$res = include $tpl; // for debug
3795 3795
 			}
3796 3796
 			if ($res) break;
3797 3797
 		}
@@ -3815,14 +3815,14 @@  discard block
 block discarded – undo
3815 3815
 	 *	@param  int	    	$dateSelector      	1=Show also date range input fields
3816 3816
 	 *	@return	void
3817 3817
 	 */
3818
-	function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3818
+	function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0)
3819 3819
 	{
3820 3820
 		global $conf, $hookmanager, $langs, $user;
3821 3821
 		// TODO We should not use global var for this !
3822 3822
 		global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3823 3823
 
3824 3824
 		// Define usemargins
3825
-		$usemargins=0;
3825
+		$usemargins = 0;
3826 3826
 		if (!empty(Globals::$conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande')))
3827 3827
             $usemargins = 1;
3828 3828
 
@@ -3831,9 +3831,9 @@  discard block
 block discarded – undo
3831 3831
 		// Line extrafield
3832 3832
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3833 3833
 		$extrafieldsline = new ExtraFields($this->db);
3834
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3834
+		$extralabelslines = $extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3835 3835
 
3836
-		$parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3836
+		$parameters = array('num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3837 3837
 		$reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3838 3838
 		if (empty($reshook))
3839 3839
 		{
@@ -3862,7 +3862,7 @@  discard block
 block discarded – undo
3862 3862
 
3863 3863
 			// Multicurrency
3864 3864
 			if (!empty(Globals::$conf->multicurrency->enabled) && $this->multicurrency_code != Globals::$conf->currency)
3865
-                print '<td class="linecoluht_currency" align="right" width="80">' . $langs->trans('PriceUHTCurrency', $this->multicurrency_code) . '</td>';
3865
+                print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
3866 3866
 
3867 3867
             if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
3868 3868
 
@@ -3877,7 +3877,7 @@  discard block
 block discarded – undo
3877 3877
 			print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
3878 3878
 
3879 3879
 			if ($this->situation_cycle_ref) {
3880
-				print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3880
+				print '<td class="linecolcycleref" align="right">'.$langs->trans('Progress').'</td>';
3881 3881
 			}
3882 3882
 
3883 3883
 			if ($usemargins && !empty(Globals::$conf->margin->enabled) && empty($user->societe_id)) {
@@ -3900,17 +3900,17 @@  discard block
 block discarded – undo
3900 3900
 
3901 3901
 			// Multicurrency
3902 3902
 			if (!empty(Globals::$conf->multicurrency->enabled) && $this->multicurrency_code != Globals::$conf->currency)
3903
-                print '<td class="linecoltotalht_currency" align="right">' . $langs->trans('TotalHTShortCurrency', $this->multicurrency_code) . '</td>';
3903
+                print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
3904 3904
 
3905 3905
             if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
3906 3906
 
3907
-			print '<td class="linecoledit"></td>';  // No width to allow autodim
3907
+			print '<td class="linecoledit"></td>'; // No width to allow autodim
3908 3908
 
3909 3909
 			print '<td class="linecoldelete" width="10"></td>';
3910 3910
 
3911 3911
 			print '<td class="linecolmove" width="10"></td>';
3912 3912
 
3913
-			if($action == 'selectlines')
3913
+			if ($action == 'selectlines')
3914 3914
 			{
3915 3915
 			    print '<td class="linecolcheckall" align="center">';
3916 3916
 			    print '<input type="checkbox" class="linecheckboxtoggle" />';
@@ -3923,7 +3923,7 @@  discard block
 block discarded – undo
3923 3923
 		}
3924 3924
 
3925 3925
 		$var = true;
3926
-		$i	 = 0;
3926
+		$i = 0;
3927 3927
 
3928 3928
 		print "<tbody>\n";
3929 3929
 		foreach ($this->lines as $line)
@@ -3936,18 +3936,18 @@  discard block
 block discarded – undo
3936 3936
 			{
3937 3937
 				if (empty($line->fk_parent_line))
3938 3938
 				{
3939
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3940
-					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3939
+					$parameters = array('line'=>$line, 'var'=>$var, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3940
+					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3941 3941
 				}
3942 3942
 				else
3943 3943
 				{
3944
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline, 'fk_parent_line'=>$line->fk_parent_line);
3945
-					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3944
+					$parameters = array('line'=>$line, 'var'=>$var, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline, 'fk_parent_line'=>$line->fk_parent_line);
3945
+					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3946 3946
 				}
3947 3947
 			}
3948 3948
 			if (empty($reshook))
3949 3949
 			{
3950
-				$this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3950
+				$this->printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafieldsline);
3951 3951
 			}
3952 3952
 
3953 3953
 			$i++;
@@ -3971,23 +3971,23 @@  discard block
 block discarded – undo
3971 3971
 	 *  @param  int			$extrafieldsline	Object of extrafield line attribute
3972 3972
 	 *	@return	void
3973 3973
 	 */
3974
-	function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
3974
+	function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafieldsline = 0)
3975 3975
 	{
3976
-		global $conf,$langs,$user,$object,$hookmanager;
3977
-		global $form,$bc,$bcdd;
3978
-		global $object_rights, $disableedit, $disablemove, $disableremove;   // TODO We should not use global var for this !
3976
+		global $conf, $langs, $user, $object, $hookmanager;
3977
+		global $form, $bc, $bcdd;
3978
+		global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
3979 3979
 
3980 3980
 		$object_rights = $this->getRights();
3981 3981
 
3982
-		$element=$this->element;
3982
+		$element = $this->element;
3983 3983
 
3984
-		$text=''; $description=''; $type=0;
3984
+		$text = ''; $description = ''; $type = 0;
3985 3985
 
3986 3986
 		// Show product and description
3987
-		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3987
+		$type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type);
3988 3988
 		// Try to enhance type detection using date_start and date_end for free lines where type was not saved.
3989
-		if (! empty($line->date_start)) $type=1; // deprecated
3990
-		if (! empty($line->date_end)) $type=1; // deprecated
3989
+		if (!empty($line->date_start)) $type = 1; // deprecated
3990
+		if (!empty($line->date_end)) $type = 1; // deprecated
3991 3991
 
3992 3992
 		// Ligne en mode visu
3993 3993
 		if ($action != 'editline' || $selected != $line->id)
@@ -4000,13 +4000,13 @@  discard block
 block discarded – undo
4000 4000
 
4001 4001
 				$product_static->ref = $line->ref; //can change ref in hook
4002 4002
 				$product_static->label = $line->label; //can change label in hook
4003
-				$text=$product_static->getNomUrl(1);
4003
+				$text = $product_static->getNomUrl(1);
4004 4004
 
4005 4005
 				// Define output language and label
4006 4006
 				if (!empty(Globals::$conf->global->MAIN_MULTILANGS)) {
4007
-					if (! is_object($this->thirdparty))
4007
+					if (!is_object($this->thirdparty))
4008 4008
 					{
4009
-						dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4009
+						dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4010 4010
 						return;
4011 4011
 					}
4012 4012
 
@@ -4014,39 +4014,39 @@  discard block
 block discarded – undo
4014 4014
 					$prod->fetch($line->fk_product);
4015 4015
 
4016 4016
 					$outputlangs = $langs;
4017
-					$newlang='';
4018
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
4017
+					$newlang = '';
4018
+					if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
4019 4019
 					if (!empty(Globals::$conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang))
4020
-                        $newlang = $this->thirdparty->default_lang;  // For language to language of customer
4021
-                    if (! empty($newlang))
4020
+                        $newlang = $this->thirdparty->default_lang; // For language to language of customer
4021
+                    if (!empty($newlang))
4022 4022
 					{
4023
-						$outputlangs = new Translate("",$conf);
4023
+						$outputlangs = new Translate("", $conf);
4024 4024
 						$outputlangs->setDefaultLang($newlang);
4025 4025
 					}
4026 4026
 
4027
-					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4027
+					$label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4028 4028
 				}
4029 4029
 				else
4030 4030
 				{
4031 4031
 					$label = $line->product_label;
4032 4032
 				}
4033 4033
 
4034
-				$text.= ' - '.(! empty($line->label)?$line->label:$label);
4034
+				$text .= ' - '.(!empty($line->label) ? $line->label : $label);
4035 4035
 				$description .= (!empty(Globals::$conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
4036 4036
             }
4037 4037
 
4038
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4038
+			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
4039 4039
 
4040 4040
 			// Output template part (modules that overwrite templates must declare this into descriptor)
4041 4041
 			// Use global variables + $dateSelector + $seller and $buyer
4042 4042
 			$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4043
-            foreach($dirtpls as $reldir)
4043
+            foreach ($dirtpls as $reldir)
4044 4044
 			{
4045 4045
 				$tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4046 4046
 				if (empty(Globals::$conf->file->strict_mode)) {
4047
-                    $res=@include $tpl;
4047
+                    $res = @include $tpl;
4048 4048
 				} else {
4049
-					$res=include $tpl; // for debug
4049
+					$res = include $tpl; // for debug
4050 4050
 				}
4051 4051
 				if ($res) break;
4052 4052
 			}
@@ -4055,21 +4055,21 @@  discard block
 block discarded – undo
4055 4055
 		// Ligne en mode update
4056 4056
 		if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4057 4057
 		{
4058
-			$label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4059
-			$placeholder=' placeholder="'.$langs->trans("Label").'"';
4058
+			$label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4059
+			$placeholder = ' placeholder="'.$langs->trans("Label").'"';
4060 4060
 
4061
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4061
+			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
4062 4062
 
4063 4063
 			// Output template part (modules that overwrite templates must declare this into descriptor)
4064 4064
 			// Use global variables + $dateSelector + $seller and $buyer
4065 4065
 			$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4066
-            foreach($dirtpls as $reldir)
4066
+            foreach ($dirtpls as $reldir)
4067 4067
 			{
4068 4068
 				$tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4069 4069
 				if (empty(Globals::$conf->file->strict_mode)) {
4070
-                    $res=@include $tpl;
4070
+                    $res = @include $tpl;
4071 4071
 				} else {
4072
-					$res=include $tpl; // for debug
4072
+					$res = include $tpl; // for debug
4073 4073
 				}
4074 4074
 				if ($res) break;
4075 4075
 			}
@@ -4089,7 +4089,7 @@  discard block
 block discarded – undo
4089 4089
 	 *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4090 4090
 	 *  @return	void
4091 4091
 	 */
4092
-	function printOriginLinesList($restrictlist='')
4092
+	function printOriginLinesList($restrictlist = '')
4093 4093
 	{
4094 4094
 		global $langs, $hookmanager, $conf;
4095 4095
 
@@ -4099,7 +4099,7 @@  discard block
 block discarded – undo
4099 4099
 		print '<td align="right">'.$langs->trans('VATRate').'</td>';
4100 4100
 		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4101 4101
 		if (!empty(Globals::$conf->multicurrency->enabled))
4102
-            print '<td align="right">' . $langs->trans('PriceUHTCurrency') . '</td>';
4102
+            print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4103 4103
         print '<td align="right">'.$langs->trans('Qty').'</td>';
4104 4104
 		if (Globals::$conf->global->PRODUCT_USE_UNITS) {
4105 4105
 			print '<td align="left">'.$langs->trans('Unit').'</td>';
@@ -4107,19 +4107,19 @@  discard block
 block discarded – undo
4107 4107
 		print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
4108 4108
 
4109 4109
 		$var = true;
4110
-		$i	 = 0;
4110
+		$i = 0;
4111 4111
 
4112
-		if (! empty($this->lines))
4112
+		if (!empty($this->lines))
4113 4113
 		{
4114 4114
 			foreach ($this->lines as $line)
4115 4115
 			{
4116
-				if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4116
+				if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4117 4117
 				{
4118 4118
 					if (empty($line->fk_parent_line))
4119 4119
 					{
4120
-						$parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
4121
-						$action='';
4122
-						$hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4120
+						$parameters = array('line'=>$line, 'var'=>$var, 'i'=>$i);
4121
+						$action = '';
4122
+						$hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4123 4123
 					}
4124 4124
 				}
4125 4125
 				else
@@ -4143,103 +4143,103 @@  discard block
 block discarded – undo
4143 4143
 	 *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4144 4144
 	 * 	@return	void
4145 4145
 	 */
4146
-	function printOriginLine($line, $var, $restrictlist='')
4146
+	function printOriginLine($line, $var, $restrictlist = '')
4147 4147
 	{
4148 4148
 		global $langs, $conf;
4149 4149
 
4150 4150
 		//var_dump($line);
4151 4151
 		if (!empty($line->date_start))
4152 4152
 		{
4153
-			$date_start=$line->date_start;
4153
+			$date_start = $line->date_start;
4154 4154
 		}
4155 4155
 		else
4156 4156
 		{
4157
-			$date_start=$line->date_debut_prevue;
4158
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4157
+			$date_start = $line->date_debut_prevue;
4158
+			if ($line->date_debut_reel) $date_start = $line->date_debut_reel;
4159 4159
 		}
4160 4160
 		if (!empty($line->date_end))
4161 4161
 		{
4162
-			$date_end=$line->date_end;
4162
+			$date_end = $line->date_end;
4163 4163
 		}
4164 4164
 		else
4165 4165
 		{
4166
-			$date_end=$line->date_fin_prevue;
4167
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4166
+			$date_end = $line->date_fin_prevue;
4167
+			if ($line->date_fin_reel) $date_end = $line->date_fin_reel;
4168 4168
 		}
4169 4169
 
4170 4170
 		$this->tpl['label'] = '';
4171
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4171
+		if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow');
4172 4172
 
4173 4173
 		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4174 4174
 		{
4175
-			$discount=new DiscountAbsolute($this->db);
4175
+			$discount = new DiscountAbsolute($this->db);
4176 4176
 			$discount->fk_soc = $this->socid;
4177
-			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4177
+			$this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
4178 4178
 		}
4179
-		else if (! empty($line->fk_product))
4179
+		else if (!empty($line->fk_product))
4180 4180
 		{
4181 4181
 			$productstatic = new Product($this->db);
4182 4182
 			$productstatic->id = $line->fk_product;
4183 4183
 			$productstatic->ref = $line->ref;
4184 4184
 			$productstatic->type = $line->fk_product_type;
4185
-            if(empty($productstatic->ref)){
4185
+            if (empty($productstatic->ref)) {
4186 4186
 				$line->fetch_product();
4187 4187
 				$productstatic = $line->product;
4188 4188
 			}
4189 4189
 			
4190
-			$this->tpl['label'].= $productstatic->getNomUrl(1);
4191
-			$this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4190
+			$this->tpl['label'] .= $productstatic->getNomUrl(1);
4191
+			$this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
4192 4192
 			// Dates
4193 4193
 			if ($line->product_type == 1 && ($date_start || $date_end))
4194 4194
 			{
4195
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4195
+				$this->tpl['label'] .= get_date_range($date_start, $date_end);
4196 4196
 			}
4197 4197
 		}
4198 4198
 		else
4199 4199
 		{
4200
-			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4200
+			$this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
4201 4201
 			if (!empty($line->desc)) {
4202
-				$this->tpl['label'].=$line->desc;
4203
-			}else {
4204
-				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4202
+				$this->tpl['label'] .= $line->desc;
4203
+			} else {
4204
+				$this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
4205 4205
 			}
4206 4206
 			
4207 4207
 			// Dates
4208 4208
 			if ($line->product_type == 1 && ($date_start || $date_end))
4209 4209
 			{
4210
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4210
+				$this->tpl['label'] .= get_date_range($date_start, $date_end);
4211 4211
 			}
4212 4212
 		}
4213 4213
 
4214
-		if (! empty($line->desc))
4214
+		if (!empty($line->desc))
4215 4215
 		{
4216 4216
 			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4217 4217
 			{
4218
-				$discount=new DiscountAbsolute($this->db);
4218
+				$discount = new DiscountAbsolute($this->db);
4219 4219
 				$discount->fetch($line->fk_remise_except);
4220
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4220
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
4221 4221
 			}
4222 4222
 			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4223 4223
 			{
4224
-				$discount=new DiscountAbsolute($this->db);
4224
+				$discount = new DiscountAbsolute($this->db);
4225 4225
 				$discount->fetch($line->fk_remise_except);
4226
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4226
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
4227 4227
 			}
4228 4228
 			elseif ($line->desc == '(EXCESS RECEIVED)')
4229 4229
 			{
4230
-				$discount=new DiscountAbsolute($this->db);
4230
+				$discount = new DiscountAbsolute($this->db);
4231 4231
 				$discount->fetch($line->fk_remise_except);
4232
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4232
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
4233 4233
 			}
4234 4234
 			elseif ($line->desc == '(EXCESS PAID)')
4235 4235
 			{
4236
-				$discount=new DiscountAbsolute($this->db);
4236
+				$discount = new DiscountAbsolute($this->db);
4237 4237
 				$discount->fetch($line->fk_remise_except);
4238
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4238
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
4239 4239
 			}
4240 4240
 			else
4241 4241
 			{
4242
-				$this->tpl['description'] = dol_trunc($line->desc,60);
4242
+				$this->tpl['description'] = dol_trunc($line->desc, 60);
4243 4243
 			}
4244 4244
 		}
4245 4245
 		else
@@ -4250,7 +4250,7 @@  discard block
 block discarded – undo
4250 4250
         // VAT Rate
4251 4251
         $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4252 4252
         $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
4253
-        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4253
+        if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
4254 4254
 
4255 4255
 		$this->tpl['price'] = price($line->subprice);
4256 4256
 		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
@@ -4260,19 +4260,19 @@  discard block
 block discarded – undo
4260 4260
         $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4261 4261
 
4262 4262
 		// Is the line strike or not
4263
-		$this->tpl['strike']=0;
4264
-		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4263
+		$this->tpl['strike'] = 0;
4264
+		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1;
4265 4265
 
4266 4266
 		// Output template part (modules that overwrite templates must declare this into descriptor)
4267 4267
 		// Use global variables + $dateSelector + $seller and $buyer
4268 4268
 		$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4269
-        foreach($dirtpls as $reldir)
4269
+        foreach ($dirtpls as $reldir)
4270 4270
 		{
4271 4271
 			$tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4272 4272
 			if (empty(Globals::$conf->file->strict_mode)) {
4273
-                $res=@include $tpl;
4273
+                $res = @include $tpl;
4274 4274
 			} else {
4275
-				$res=include $tpl; // for debug
4275
+				$res = include $tpl; // for debug
4276 4276
 			}
4277 4277
 			if ($res) break;
4278 4278
 		}
@@ -4290,26 +4290,26 @@  discard block
 block discarded – undo
4290 4290
 	 *	@param		int		$mandatory			Mandatory or not
4291 4291
 	 *	@return		int							<=0 if KO, >0 if OK
4292 4292
 	 */
4293
-	function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4293
+	function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
4294 4294
 	{
4295 4295
         // phpcs:enable
4296 4296
 		$this->db->begin();
4297 4297
 
4298 4298
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
4299
-		$sql.= "resource_id";
4300
-		$sql.= ", resource_type";
4301
-		$sql.= ", element_id";
4302
-		$sql.= ", element_type";
4303
-		$sql.= ", busy";
4304
-		$sql.= ", mandatory";
4305
-		$sql.= ") VALUES (";
4306
-		$sql.= $resource_id;
4307
-		$sql.= ", '".$this->db->escape($resource_type)."'";
4308
-		$sql.= ", '".$this->db->escape($this->id)."'";
4309
-		$sql.= ", '".$this->db->escape($this->element)."'";
4310
-		$sql.= ", '".$this->db->escape($busy)."'";
4311
-		$sql.= ", '".$this->db->escape($mandatory)."'";
4312
-		$sql.= ")";
4299
+		$sql .= "resource_id";
4300
+		$sql .= ", resource_type";
4301
+		$sql .= ", element_id";
4302
+		$sql .= ", element_type";
4303
+		$sql .= ", busy";
4304
+		$sql .= ", mandatory";
4305
+		$sql .= ") VALUES (";
4306
+		$sql .= $resource_id;
4307
+		$sql .= ", '".$this->db->escape($resource_type)."'";
4308
+		$sql .= ", '".$this->db->escape($this->id)."'";
4309
+		$sql .= ", '".$this->db->escape($this->element)."'";
4310
+		$sql .= ", '".$this->db->escape($busy)."'";
4311
+		$sql .= ", '".$this->db->escape($mandatory)."'";
4312
+		$sql .= ")";
4313 4313
 
4314 4314
 		dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4315 4315
 		if ($this->db->query($sql))
@@ -4319,7 +4319,7 @@  discard block
 block discarded – undo
4319 4319
 		}
4320 4320
 		else
4321 4321
 		{
4322
-			$this->error=$this->db->lasterror();
4322
+			$this->error = $this->db->lasterror();
4323 4323
 			$this->db->rollback();
4324 4324
 			return  0;
4325 4325
 		}
@@ -4334,7 +4334,7 @@  discard block
 block discarded – undo
4334 4334
 	 *    @param	int		$notrigger		Disable all triggers
4335 4335
 	 *    @return   int						>0 if OK, <0 if KO
4336 4336
 	 */
4337
-	function delete_resource($rowid, $element, $notrigger=0)
4337
+	function delete_resource($rowid, $element, $notrigger = 0)
4338 4338
 	{
4339 4339
         // phpcs:enable
4340 4340
 		global $user;
@@ -4342,22 +4342,22 @@  discard block
 block discarded – undo
4342 4342
 		$this->db->begin();
4343 4343
 
4344 4344
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4345
-		$sql.= " WHERE rowid=".$rowid;
4345
+		$sql .= " WHERE rowid=".$rowid;
4346 4346
 
4347 4347
 		dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
4348 4348
 
4349
-		$resql=$this->db->query($sql);
4350
-		if (! $resql)
4349
+		$resql = $this->db->query($sql);
4350
+		if (!$resql)
4351 4351
 		{
4352
-			$this->error=$this->db->lasterror();
4352
+			$this->error = $this->db->lasterror();
4353 4353
 			$this->db->rollback();
4354 4354
 			return -1;
4355 4355
 		}
4356 4356
 		else
4357 4357
 		{
4358
-			if (! $notrigger)
4358
+			if (!$notrigger)
4359 4359
 			{
4360
-				$result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4360
+				$result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4361 4361
 				if ($result < 0) { $this->db->rollback(); return -1; }
4362 4362
 			}
4363 4363
 			$this->db->commit();
@@ -4376,8 +4376,8 @@  discard block
 block discarded – undo
4376 4376
 		// Force a copy of this->lines, otherwise it will point to same object.
4377 4377
 		if (isset($this->lines) && is_array($this->lines))
4378 4378
 		{
4379
-			$nboflines=count($this->lines);
4380
-			for($i=0; $i < $nboflines; $i++)
4379
+			$nboflines = count($this->lines);
4380
+			for ($i = 0; $i < $nboflines; $i++)
4381 4381
 			{
4382 4382
 				$this->lines[$i] = clone $this->lines[$i];
4383 4383
 			}
@@ -4397,44 +4397,44 @@  discard block
 block discarded – undo
4397 4397
 	 * @return 	int 						>0 if OK, <0 if KO
4398 4398
 	 * @see	addFileIntoDatabaseIndex
4399 4399
 	 */
4400
-	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4400
+	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
4401 4401
 	{
4402 4402
 		global $conf, $langs, $user;
4403 4403
 
4404
-		$srctemplatepath='';
4404
+		$srctemplatepath = '';
4405 4405
 
4406 4406
 		// Increase limit for PDF build
4407
-		$err=error_reporting();
4407
+		$err = error_reporting();
4408 4408
 		error_reporting(0);
4409 4409
 		@set_time_limit(120);
4410 4410
 		error_reporting($err);
4411 4411
 
4412 4412
 		// If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4413
-		$tmp=explode(':',$modele,2);
4414
-		if (! empty($tmp[1]))
4413
+		$tmp = explode(':', $modele, 2);
4414
+		if (!empty($tmp[1]))
4415 4415
 		{
4416
-			$modele=$tmp[0];
4417
-			$srctemplatepath=$tmp[1];
4416
+			$modele = $tmp[0];
4417
+			$srctemplatepath = $tmp[1];
4418 4418
 		}
4419 4419
 
4420 4420
 		// Search template files
4421
-		$file=''; $classname=''; $filefound=0;
4422
-		$dirmodels=array('/');
4421
+		$file = ''; $classname = ''; $filefound = 0;
4422
+		$dirmodels = array('/');
4423 4423
 		if (is_array(Globals::$conf->modules_parts['models']))
4424 4424
             $dirmodels = array_merge($dirmodels, Globals::$conf->modules_parts['models']);
4425
-        foreach($dirmodels as $reldir)
4425
+        foreach ($dirmodels as $reldir)
4426 4426
 		{
4427
-			foreach(array('doc','pdf') as $prefix)
4427
+			foreach (array('doc', 'pdf') as $prefix)
4428 4428
 			{
4429
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4429
+				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php
4430 4430
 				else $file = $prefix."_".$modele.".modules.php";
4431 4431
 
4432 4432
 				// On verifie l'emplacement du modele
4433
-				$file=dol_buildpath($reldir.$modelspath.$file,0);
4433
+				$file = dol_buildpath($reldir.$modelspath.$file, 0);
4434 4434
 				if (file_exists($file))
4435 4435
 				{
4436
-					$filefound=1;
4437
-					$classname=$prefix.'_'.$modele;
4436
+					$filefound = 1;
4437
+					$classname = $prefix.'_'.$modele;
4438 4438
 					break;
4439 4439
 				}
4440 4440
 			}
@@ -4444,7 +4444,7 @@  discard block
 block discarded – undo
4444 4444
 		// If generator was found
4445 4445
 		if ($filefound)
4446 4446
 		{
4447
-			global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4447
+			global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4448 4448
 
4449 4449
 			require_once $file;
4450 4450
 
@@ -4453,31 +4453,31 @@  discard block
 block discarded – undo
4453 4453
 			// If generator is ODT, we must have srctemplatepath defined, if not we set it.
4454 4454
 			if ($obj->type == 'odt' && empty($srctemplatepath))
4455 4455
 			{
4456
-				$varfortemplatedir=$obj->scandir;
4456
+				$varfortemplatedir = $obj->scandir;
4457 4457
 				if ($varfortemplatedir && !empty(Globals::$conf->global->$varfortemplatedir)) {
4458 4458
 					$dirtoscan = Globals::$conf->global->$varfortemplatedir;
4459 4459
 
4460
-                    $listoffiles=array();
4460
+                    $listoffiles = array();
4461 4461
 
4462 4462
 					// Now we add first model found in directories scanned
4463
-					$listofdir=explode(',',$dirtoscan);
4464
-					foreach($listofdir as $key => $tmpdir)
4463
+					$listofdir = explode(',', $dirtoscan);
4464
+					foreach ($listofdir as $key => $tmpdir)
4465 4465
 					{
4466
-						$tmpdir=trim($tmpdir);
4467
-						$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4468
-						if (! $tmpdir) { unset($listofdir[$key]); continue; }
4466
+						$tmpdir = trim($tmpdir);
4467
+						$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
4468
+						if (!$tmpdir) { unset($listofdir[$key]); continue; }
4469 4469
 						if (is_dir($tmpdir))
4470 4470
 						{
4471
-							$tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4472
-							if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4471
+							$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
4472
+							if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
4473 4473
 						}
4474 4474
 					}
4475 4475
 
4476 4476
 					if (count($listoffiles))
4477 4477
 					{
4478
-						foreach($listoffiles as $record)
4478
+						foreach ($listoffiles as $record)
4479 4479
 						{
4480
-							$srctemplatepath=$record['fullname'];
4480
+							$srctemplatepath = $record['fullname'];
4481 4481
 							break;
4482 4482
 						}
4483 4483
 					}
@@ -4485,27 +4485,27 @@  discard block
 block discarded – undo
4485 4485
 
4486 4486
 				if (empty($srctemplatepath))
4487 4487
 				{
4488
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4488
+					$this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4489 4489
 					return -1;
4490 4490
 				}
4491 4491
 			}
4492 4492
 
4493
-			if ($obj->type == 'odt' && ! empty($srctemplatepath))
4493
+			if ($obj->type == 'odt' && !empty($srctemplatepath))
4494 4494
 			{
4495
-				if (! dol_is_file($srctemplatepath))
4495
+				if (!dol_is_file($srctemplatepath))
4496 4496
 				{
4497
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4497
+					$this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4498 4498
 					return -1;
4499 4499
 				}
4500 4500
 			}
4501 4501
 
4502 4502
 			// We save charset_output to restore it because write_file can change it if needed for
4503 4503
 			// output format that does not support UTF8.
4504
-			$sav_charset_output=$outputlangs->charset_output;
4504
+			$sav_charset_output = $outputlangs->charset_output;
4505 4505
 
4506 4506
 			if (in_array(get_class($this), array('Adherent')))
4507 4507
 			{
4508
-				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4508
+				$arrayofrecords = array(); // The write_file of templates of adherent class need this var
4509 4509
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4510 4510
 			}
4511 4511
 			else
@@ -4516,36 +4516,36 @@  discard block
 block discarded – undo
4516 4516
 
4517 4517
 			if ($resultwritefile > 0)
4518 4518
 			{
4519
-				$outputlangs->charset_output=$sav_charset_output;
4519
+				$outputlangs->charset_output = $sav_charset_output;
4520 4520
 
4521 4521
 				// We delete old preview
4522 4522
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4523 4523
 				dol_delete_preview($this);
4524 4524
 
4525 4525
 				// Index file in database
4526
-				if (! empty($obj->result['fullpath']))
4526
+				if (!empty($obj->result['fullpath']))
4527 4527
 				{
4528 4528
 					$destfull = $obj->result['fullpath'];
4529 4529
 					$upload_dir = dirname($destfull);
4530 4530
 					$destfile = basename($destfull);
4531
-					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4531
+					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
4532 4532
 
4533
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4533
+					if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4534 4534
 					{
4535 4535
 						$filename = basename($destfile);
4536 4536
 						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4537 4537
 						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4538 4538
 
4539 4539
 						include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
4540
-						$ecmfile=new EcmFiles($this->db);
4541
-						$result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename);
4540
+						$ecmfile = new EcmFiles($this->db);
4541
+						$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
4542 4542
 
4543 4543
 						// Set the public "share" key
4544 4544
 						$setsharekey = false;
4545 4545
 						if ($this->element == 'propal')
4546 4546
 						{
4547 4547
 							$useonlinesignature = Globals::$conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
4548
-                            if ($useonlinesignature) $setsharekey=true;
4548
+                            if ($useonlinesignature) $setsharekey = true;
4549 4549
 							if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD))
4550 4550
                                 $setsharekey = true;
4551 4551
                         }
@@ -4567,11 +4567,11 @@  discard block
 block discarded – undo
4567 4567
 
4568 4568
 						if ($result > 0)
4569 4569
 						{
4570
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4570
+							$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
4571 4571
 							$ecmfile->fullpath_orig = '';
4572 4572
 							$ecmfile->gen_or_uploaded = 'generated';
4573
-							$ecmfile->description = '';    // indexed content
4574
-							$ecmfile->keyword = '';        // keyword content
4573
+							$ecmfile->description = ''; // indexed content
4574
+							$ecmfile->keyword = ''; // keyword content
4575 4575
 							$result = $ecmfile->update($user);
4576 4576
 							if ($result < 0)
4577 4577
 							{
@@ -4583,11 +4583,11 @@  discard block
 block discarded – undo
4583 4583
 							$ecmfile->entity = Globals::$conf->entity;
4584 4584
                             $ecmfile->filepath = $rel_dir;
4585 4585
 							$ecmfile->filename = $filename;
4586
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4586
+							$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
4587 4587
 							$ecmfile->fullpath_orig = '';
4588 4588
 							$ecmfile->gen_or_uploaded = 'generated';
4589
-							$ecmfile->description = '';    // indexed content
4590
-							$ecmfile->keyword = '';        // keyword content
4589
+							$ecmfile->description = ''; // indexed content
4590
+							$ecmfile->keyword = ''; // keyword content
4591 4591
 							$ecmfile->src_object_type = $this->table_element;
4592 4592
 							$ecmfile->src_object_id   = $this->id;
4593 4593
 
@@ -4604,14 +4604,14 @@  discard block
 block discarded – undo
4604 4604
 						//var_dump($obj->update_main_doc_field);exit;
4605 4605
 
4606 4606
 						// Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4607
-						$update_main_doc_field=0;
4608
-						if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4609
-						if ($update_main_doc_field && ! empty($this->table_element))
4607
+						$update_main_doc_field = 0;
4608
+						if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1;
4609
+						if ($update_main_doc_field && !empty($this->table_element))
4610 4610
 						{
4611 4611
 							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4612
-							$sql.= ' WHERE rowid = '.$this->id;
4612
+							$sql .= ' WHERE rowid = '.$this->id;
4613 4613
 							$resql = $this->db->query($sql);
4614
-							if (! $resql) dol_print_error($this->db);
4614
+							if (!$resql) dol_print_error($this->db);
4615 4615
 						}
4616 4616
 					}
4617 4617
 				}
@@ -4627,15 +4627,15 @@  discard block
 block discarded – undo
4627 4627
 			}
4628 4628
 			else
4629 4629
 			{
4630
-				$outputlangs->charset_output=$sav_charset_output;
4630
+				$outputlangs->charset_output = $sav_charset_output;
4631 4631
 				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4632 4632
 				return -1;
4633 4633
 			}
4634 4634
 		}
4635 4635
 		else
4636 4636
 		{
4637
-			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4638
-			dol_print_error('',$this->error);
4637
+			$this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $file);
4638
+			dol_print_error('', $this->error);
4639 4639
 			return -1;
4640 4640
 		}
4641 4641
 	}
@@ -4651,9 +4651,9 @@  discard block
 block discarded – undo
4651 4651
 	{
4652 4652
 		global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4653 4653
 
4654
-		require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4654
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
4655 4655
 
4656
-		$file_osencoded=dol_osencode($file);
4656
+		$file_osencoded = dol_osencode($file);
4657 4657
 		if (file_exists($file_osencoded))
4658 4658
 		{
4659 4659
 			// Create small thumbs for company (Ratio is near 16/9)
@@ -4683,7 +4683,7 @@  discard block
 block discarded – undo
4683 4683
 	 * @param   string              $alternatevalue     Alternate value to use
4684 4684
 	 * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4685 4685
 	 **/
4686
-	function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4686
+	function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
4687 4687
 	{
4688 4688
 		global $conf, $_POST;
4689 4689
 
@@ -4692,16 +4692,16 @@  discard block
 block discarded – undo
4692 4692
 
4693 4693
 		if (isset($alternatevalue)) return $alternatevalue;
4694 4694
 
4695
-		$newelement=$this->element;
4696
-		if ($newelement == 'facture') $newelement='invoice';
4697
-		if ($newelement == 'commande') $newelement='order';
4695
+		$newelement = $this->element;
4696
+		if ($newelement == 'facture') $newelement = 'invoice';
4697
+		if ($newelement == 'commande') $newelement = 'order';
4698 4698
 		if (empty($newelement))
4699 4699
 		{
4700 4700
 			dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
4701 4701
 			return '';
4702 4702
 		}
4703 4703
 
4704
-		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4704
+		$keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
4705 4705
 		//var_dump($keyforfieldname);
4706 4706
 		if (isset(Globals::$conf->global->$keyforfieldname))
4707 4707
             return Globals::$conf->global->$keyforfieldname;
@@ -4727,21 +4727,21 @@  discard block
 block discarded – undo
4727 4727
 	function call_trigger($trigger_name, $user)
4728 4728
 	{
4729 4729
         // phpcs:enable
4730
-		global $langs,$conf;
4730
+		global $langs, $conf;
4731 4731
 
4732
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
4733
-		$interface=new Interfaces($this->db);
4734
-		$result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
4732
+		include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
4733
+		$interface = new Interfaces($this->db);
4734
+		$result = $interface->run_triggers($trigger_name, $this, $user, $langs, $conf);
4735 4735
 
4736 4736
 		if ($result < 0)
4737 4737
 		{
4738 4738
 			if (!empty($this->errors))
4739 4739
 			{
4740
-				$this->errors=array_unique(array_merge($this->errors,$interface->errors));   // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
4740
+				$this->errors = array_unique(array_merge($this->errors, $interface->errors)); // We use array_unique because when a trigger call another trigger on same object, this->errors is added twice.
4741 4741
 			}
4742 4742
 			else
4743 4743
 			{
4744
-				$this->errors=$interface->errors;
4744
+				$this->errors = $interface->errors;
4745 4745
 			}
4746 4746
 		}
4747 4747
 		return $result;
@@ -4760,19 +4760,19 @@  discard block
 block discarded – undo
4760 4760
 	 *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
4761 4761
 	 *  @return	int						<0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
4762 4762
 	 */
4763
-	function fetch_optionals($rowid=null, $optionsArray=null)
4763
+	function fetch_optionals($rowid = null, $optionsArray = null)
4764 4764
 	{
4765 4765
         // phpcs:enable
4766
-		if (empty($rowid)) $rowid=$this->id;
4766
+		if (empty($rowid)) $rowid = $this->id;
4767 4767
 
4768 4768
 		// To avoid SQL errors. Probably not the better solution though
4769 4769
 		if (!$this->table_element) {
4770 4770
 			return 0;
4771 4771
 		}
4772 4772
 
4773
-		$this->array_options=array();
4773
+		$this->array_options = array();
4774 4774
 
4775
-		if (! is_array($optionsArray))
4775
+		if (!is_array($optionsArray))
4776 4776
 		{
4777 4777
 			// If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4778 4778
 			// TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
@@ -4788,7 +4788,7 @@  discard block
 block discarded – undo
4788 4788
 			{
4789 4789
 				$extrafields->fetch_name_optionals_label($this->table_element);
4790 4790
 			}
4791
-			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4791
+			$optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
4792 4792
 		}
4793 4793
 		else
4794 4794
 		{
@@ -4807,18 +4807,18 @@  discard block
 block discarded – undo
4807 4807
 			{
4808 4808
 				if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4809 4809
 				{
4810
-					$sql.= ", ".$name;
4810
+					$sql .= ", ".$name;
4811 4811
 				}
4812 4812
 			}
4813
-			$sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4814
-			$sql.= " WHERE fk_object = ".$rowid;
4813
+			$sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4814
+			$sql .= " WHERE fk_object = ".$rowid;
4815 4815
 
4816 4816
 			//dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4817
-			$resql=$this->db->query($sql);
4817
+			$resql = $this->db->query($sql);
4818 4818
 			if ($resql)
4819 4819
 			{
4820 4820
 				$this->array_options = array();
4821
-				$numrows=$this->db->num_rows($resql);
4821
+				$numrows = $this->db->num_rows($resql);
4822 4822
 				if ($numrows)
4823 4823
 				{
4824 4824
 					$tab = $this->db->fetch_array($resql);
@@ -4826,17 +4826,17 @@  discard block
 block discarded – undo
4826 4826
 					foreach ($tab as $key => $value)
4827 4827
 					{
4828 4828
 						// Test fetch_array ! is_int($key) because fetch_array result is a mix table with Key as alpha and Key as int (depend db engine)
4829
-						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4829
+						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
4830 4830
 						{
4831 4831
 							// we can add this attribute to object
4832
-							if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4832
+							if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
4833 4833
 							{
4834 4834
 								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4835
-								$this->array_options["options_".$key]=$this->db->jdate($value);
4835
+								$this->array_options["options_".$key] = $this->db->jdate($value);
4836 4836
 							}
4837 4837
 							else
4838 4838
 							{
4839
-								$this->array_options["options_".$key]=$value;
4839
+								$this->array_options["options_".$key] = $value;
4840 4840
 							}
4841 4841
 
4842 4842
 							//var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
@@ -4872,10 +4872,10 @@  discard block
 block discarded – undo
4872 4872
 
4873 4873
 		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4874 4874
 		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4875
-		$resql=$this->db->query($sql_del);
4876
-		if (! $resql)
4875
+		$resql = $this->db->query($sql_del);
4876
+		if (!$resql)
4877 4877
 		{
4878
-			$this->error=$this->db->lasterror();
4878
+			$this->error = $this->db->lasterror();
4879 4879
 			$this->db->rollback();
4880 4880
 			return -1;
4881 4881
 		}
@@ -4896,37 +4896,37 @@  discard block
 block discarded – undo
4896 4896
 	 *  @return int 						-1=error, O=did nothing, 1=OK
4897 4897
 	 *  @see updateExtraField, setValueFrom
4898 4898
 	 */
4899
-	function insertExtraFields($trigger='', $userused=null)
4899
+	function insertExtraFields($trigger = '', $userused = null)
4900 4900
 	{
4901
-		global $conf,$langs,$user;
4901
+		global $conf, $langs, $user;
4902 4902
 
4903
-		if (empty($userused)) $userused=$user;
4903
+		if (empty($userused)) $userused = $user;
4904 4904
 
4905
-		$error=0;
4905
+		$error = 0;
4906 4906
 
4907 4907
 		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
4908 4908
             return 0; // For avoid conflicts if trigger used
4909 4909
 
4910
-        if (! empty($this->array_options))
4910
+        if (!empty($this->array_options))
4911 4911
 		{
4912 4912
 			// Check parameters
4913 4913
 			$langs->load('admin');
4914 4914
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4915 4915
 			$extrafields = new ExtraFields($this->db);
4916
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4916
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
4917 4917
 
4918 4918
 			//Eliminate copied source object extra_fields that do not exist in target object
4919
-			$new_array_options=array();
4919
+			$new_array_options = array();
4920 4920
 			foreach ($this->array_options as $key => $value) {
4921
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4921
+				if (in_array(substr($key, 8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4922 4922
 					$new_array_options[$key] = $value;
4923 4923
 				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4924 4924
 					$new_array_options['options_'.$key] = $value;
4925 4925
 			}
4926 4926
 
4927
-			foreach($new_array_options as $key => $value)
4927
+			foreach ($new_array_options as $key => $value)
4928 4928
 			{
4929
-			   	$attributeKey      = substr($key,8);   // Remove 'options_' prefix
4929
+			   	$attributeKey      = substr($key, 8); // Remove 'options_' prefix
4930 4930
 			   	$attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4931 4931
 			   	$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4932 4932
 			   	$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
@@ -4934,13 +4934,13 @@  discard block
 block discarded – undo
4934 4934
 
4935 4935
 			   	if ($attributeRequired)
4936 4936
 			   	{
4937
-			   		$mandatorypb=false;
4938
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4939
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
4937
+			   		$mandatorypb = false;
4938
+			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
4939
+			   		if ($this->array_options[$key] === '') $mandatorypb = true;
4940 4940
 			   		if ($mandatorypb)
4941 4941
 			   		{
4942 4942
 			   			dol_syslog($this->error);
4943
-			   			$this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4943
+			   			$this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
4944 4944
 			   			return -1;
4945 4945
 			   		}
4946 4946
 			   	}
@@ -4951,25 +4951,25 @@  discard block
 block discarded – undo
4951 4951
 			   	switch ($attributeType)
4952 4952
 			   	{
4953 4953
 			   		case 'int':
4954
-			  			if (!is_numeric($value) && $value!='')
4954
+			  			if (!is_numeric($value) && $value != '')
4955 4955
 			   			{
4956
-			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4956
+			   				$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4957 4957
 			   				return -1;
4958 4958
 			  			}
4959
-			   			elseif ($value=='')
4959
+			   			elseif ($value == '')
4960 4960
 			   			{
4961 4961
 			   				$new_array_options[$key] = null;
4962 4962
 			   			}
4963 4963
 			 			break;
4964 4964
 					case 'double':
4965 4965
 						$value = price2num($value);
4966
-						if (!is_numeric($value) && $value!='')
4966
+						if (!is_numeric($value) && $value != '')
4967 4967
 						{
4968 4968
 							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4969
-							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4969
+							$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4970 4970
 							return -1;
4971 4971
 						}
4972
-						elseif ($value=='')
4972
+						elseif ($value == '')
4973 4973
 						{
4974 4974
 							$new_array_options[$key] = null;
4975 4975
 						}
@@ -4983,12 +4983,12 @@  discard block
 block discarded – undo
4983 4983
              			}
4984 4984
              			break;*/
4985 4985
 			   		case 'password':
4986
-			   			$algo='';
4986
+			   			$algo = '';
4987 4987
 			   			if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4988 4988
 			   			{
4989 4989
 			   				// If there is an encryption choice, we use it to crypt data before insert
4990 4990
 			   				$tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4991
-			   				$algo=reset($tmparrays);
4991
+			   				$algo = reset($tmparrays);
4992 4992
 			   				if ($algo != '')
4993 4993
 			   				{
4994 4994
 			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
@@ -4999,7 +4999,7 @@  discard block
 block discarded – undo
4999 4999
 			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
5000 5000
 				   					if ($this->array_options[$key] == $this->oldcopy->array_options[$key])	// If old value crypted in database is same than submited new value, it means we don't change it, so we don't update.
5001 5001
 				   					{
5002
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5002
+				   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
5003 5003
 				   					}
5004 5004
 									else
5005 5005
 									{
@@ -5010,7 +5010,7 @@  discard block
 block discarded – undo
5010 5010
 			   					}
5011 5011
 			   					else
5012 5012
 			   					{
5013
-			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5013
+			   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
5014 5014
 			   					}
5015 5015
 			   				}
5016 5016
 			   			}
@@ -5027,13 +5027,13 @@  discard block
 block discarded – undo
5027 5027
 						break;
5028 5028
 					case 'datetime':
5029 5029
 						// If data is a string instead of a timestamp, we convert it
5030
-						if (! is_int($this->array_options[$key])) {
5030
+						if (!is_int($this->array_options[$key])) {
5031 5031
 							$this->array_options[$key] = strtotime($this->array_options[$key]);
5032 5032
 						}
5033 5033
 						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5034 5034
 						break;
5035 5035
 		   			case 'link':
5036
-						$param_list=array_keys($attributeParam['options']);
5036
+						$param_list = array_keys($attributeParam['options']);
5037 5037
 						// 0 : ObjectName
5038 5038
 						// 1 : classPath
5039 5039
 						$InfoFieldList = explode(":", $param_list[0]);
@@ -5042,18 +5042,18 @@  discard block
 block discarded – undo
5042 5042
 						{
5043 5043
 							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5044 5044
 							{
5045
-								$new_array_options[$key]='';
5045
+								$new_array_options[$key] = '';
5046 5046
 							}
5047 5047
 							elseif ($value)
5048 5048
 							{
5049 5049
 								$object = new $InfoFieldList[0]($this->db);
5050
-								if (is_numeric($value)) $res=$object->fetch($value);
5051
-								else $res=$object->fetch('',$value);
5050
+								if (is_numeric($value)) $res = $object->fetch($value);
5051
+								else $res = $object->fetch('', $value);
5052 5052
 
5053
-								if ($res > 0) $new_array_options[$key]=$object->id;
5053
+								if ($res > 0) $new_array_options[$key] = $object->id;
5054 5054
 								else
5055 5055
 								{
5056
-									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5056
+									$this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
5057 5057
 									$this->db->rollback();
5058 5058
 									return -1;
5059 5059
 								}
@@ -5077,46 +5077,46 @@  discard block
 block discarded – undo
5077 5077
 			$this->db->query($sql_del);
5078 5078
 
5079 5079
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5080
-			foreach($new_array_options as $key => $value)
5080
+			foreach ($new_array_options as $key => $value)
5081 5081
 			{
5082
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5082
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5083 5083
 				// Add field of attribut
5084 5084
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5085
-					$sql.=",".$attributeKey;
5085
+					$sql .= ",".$attributeKey;
5086 5086
 			}
5087 5087
 			$sql .= ") VALUES (".$this->id;
5088 5088
 
5089
-			foreach($new_array_options as $key => $value)
5089
+			foreach ($new_array_options as $key => $value)
5090 5090
 			{
5091
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5091
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5092 5092
 				// Add field of attribute
5093 5093
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5094 5094
 				{
5095 5095
 					if ($new_array_options[$key] != '')
5096 5096
 					{
5097
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5097
+						$sql .= ",'".$this->db->escape($new_array_options[$key])."'";
5098 5098
 					}
5099 5099
 					else
5100 5100
 					{
5101
-						$sql.=",null";
5101
+						$sql .= ",null";
5102 5102
 					}
5103 5103
 				}
5104 5104
 			}
5105
-			$sql.=")";
5105
+			$sql .= ")";
5106 5106
 
5107 5107
 			dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5108 5108
 			$resql = $this->db->query($sql);
5109
-			if (! $resql)
5109
+			if (!$resql)
5110 5110
 			{
5111
-				$this->error=$this->db->lasterror();
5111
+				$this->error = $this->db->lasterror();
5112 5112
 				$error++;
5113 5113
 			}
5114 5114
 
5115
-			if (! $error && $trigger)
5115
+			if (!$error && $trigger)
5116 5116
 			{
5117 5117
 				// Call trigger
5118
-				$this->context=array('extrafieldaddupdate'=>1);
5119
-				$result=$this->call_trigger($trigger, $userused);
5118
+				$this->context = array('extrafieldaddupdate'=>1);
5119
+				$result = $this->call_trigger($trigger, $userused);
5120 5120
 				if ($result < 0) $error++;
5121 5121
 				// End call trigger
5122 5122
 			}
@@ -5145,26 +5145,26 @@  discard block
 block discarded – undo
5145 5145
 	 *  @return int                 		-1=error, O=did nothing, 1=OK
5146 5146
 	 *  @see setValueFrom, insertExtraFields
5147 5147
 	 */
5148
-	function updateExtraField($key, $trigger=null, $userused=null)
5148
+	function updateExtraField($key, $trigger = null, $userused = null)
5149 5149
 	{
5150
-		global $conf,$langs,$user;
5150
+		global $conf, $langs, $user;
5151 5151
 
5152
-		if (empty($userused)) $userused=$user;
5152
+		if (empty($userused)) $userused = $user;
5153 5153
 
5154
-		$error=0;
5154
+		$error = 0;
5155 5155
 
5156 5156
 		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
5157 5157
             return 0; // For avoid conflicts if trigger used
5158 5158
 
5159
-        if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5159
+        if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
5160 5160
 		{
5161 5161
 			// Check parameters
5162 5162
 			$langs->load('admin');
5163 5163
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5164 5164
 			$extrafields = new ExtraFields($this->db);
5165
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5165
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
5166 5166
 
5167
-			$value=$this->array_options["options_".$key];
5167
+			$value = $this->array_options["options_".$key];
5168 5168
 
5169 5169
 			$attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5170 5170
 			$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
@@ -5177,25 +5177,25 @@  discard block
 block discarded – undo
5177 5177
 			switch ($attributeType)
5178 5178
 			{
5179 5179
 				case 'int':
5180
-					if (!is_numeric($value) && $value!='')
5180
+					if (!is_numeric($value) && $value != '')
5181 5181
 					{
5182
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5182
+						$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5183 5183
 						return -1;
5184 5184
 					}
5185
-					elseif ($value=='')
5185
+					elseif ($value == '')
5186 5186
 					{
5187 5187
 						$this->array_options["options_".$key] = null;
5188 5188
 					}
5189 5189
 					break;
5190 5190
 				case 'double':
5191 5191
 					$value = price2num($value);
5192
-					if (!is_numeric($value) && $value!='')
5192
+					if (!is_numeric($value) && $value != '')
5193 5193
 					{
5194 5194
 						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5195
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5195
+						$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5196 5196
 						return -1;
5197 5197
 					}
5198
-					elseif ($value=='')
5198
+					elseif ($value == '')
5199 5199
 					{
5200 5200
 						$this->array_options["options_".$key] = null;
5201 5201
 					}
@@ -5212,13 +5212,13 @@  discard block
 block discarded – undo
5212 5212
 					$this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5213 5213
 					break;
5214 5214
 				case 'date':
5215
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5215
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5216 5216
 					break;
5217 5217
 				case 'datetime':
5218
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5218
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5219 5219
 					break;
5220 5220
 				case 'link':
5221
-					$param_list=array_keys($attributeParam['options']);
5221
+					$param_list = array_keys($attributeParam['options']);
5222 5222
 					// 0 : ObjectName
5223 5223
 					// 1 : classPath
5224 5224
 					$InfoFieldList = explode(":", $param_list[0]);
@@ -5226,8 +5226,8 @@  discard block
 block discarded – undo
5226 5226
 					if ($value)
5227 5227
 					{
5228 5228
 						$object = new $InfoFieldList[0]($this->db);
5229
-						$object->fetch(0,$value);
5230
-						$this->array_options["options_".$key]=$object->id;
5229
+						$object->fetch(0, $value);
5230
+						$this->array_options["options_".$key] = $object->id;
5231 5231
 					}
5232 5232
 					break;
5233 5233
 			}
@@ -5236,24 +5236,24 @@  discard block
 block discarded – undo
5236 5236
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5237 5237
 			$sql .= " WHERE fk_object = ".$this->id;
5238 5238
 			$resql = $this->db->query($sql);
5239
-			if (! $resql)
5239
+			if (!$resql)
5240 5240
 			{
5241 5241
 				$error++;
5242
-				$this->error=$this->db->lasterror();
5242
+				$this->error = $this->db->lasterror();
5243 5243
 			}
5244 5244
 
5245
-			if (! $error && $trigger)
5245
+			if (!$error && $trigger)
5246 5246
 			{
5247 5247
 				// Call trigger
5248
-				$this->context=array('extrafieldupdate'=>1);
5249
-				$result=$this->call_trigger($trigger, $userused);
5248
+				$this->context = array('extrafieldupdate'=>1);
5249
+				$result = $this->call_trigger($trigger, $userused);
5250 5250
 				if ($result < 0) $error++;
5251 5251
 				// End call trigger
5252 5252
 			}
5253 5253
 
5254 5254
 			if ($error)
5255 5255
 			{
5256
-				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5256
+				dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
5257 5257
 				$this->db->rollback();
5258 5258
 				return -1;
5259 5259
 			}
@@ -5280,71 +5280,71 @@  discard block
 block discarded – undo
5280 5280
 	 * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5281 5281
 	 * @return string
5282 5282
 	 */
5283
-	function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5283
+	function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0)
5284 5284
 	{
5285
-		global $conf,$langs,$form;
5285
+		global $conf, $langs, $form;
5286 5286
 
5287
-		if (! is_object($form))
5287
+		if (!is_object($form))
5288 5288
 		{
5289 5289
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5290
-			$form=new Form($this->db);
5290
+			$form = new Form($this->db);
5291 5291
 		}
5292 5292
 
5293
-		$val=$this->fields[$key];
5293
+		$val = $this->fields[$key];
5294 5294
 
5295
-		$out='';
5296
-        $type='';
5295
+		$out = '';
5296
+        $type = '';
5297 5297
         $param = array();
5298
-        $param['options']=array();
5299
-        $size =$this->fields[$key]['size'];
5298
+        $param['options'] = array();
5299
+        $size = $this->fields[$key]['size'];
5300 5300
         // Because we work on extrafields
5301
-        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5302
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5303
-            $type ='link';
5304
-        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5305
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5306
-            $type ='link';
5307
-        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5308
-            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5309
-            $type ='sellist';
5310
-        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5311
-            $param['options']=array();
5312
-            $type ='varchar';
5313
-            $size=$reg[1];
5314
-        } elseif(preg_match('/varchar/', $val['type'])) {
5315
-            $param['options']=array();
5316
-            $type ='varchar';
5317
-        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5318
-            $param['options']=$this->fields[$key]['arrayofkeyval'];
5319
-            $type ='select';
5301
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
5302
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5303
+            $type = 'link';
5304
+        } elseif (preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5305
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5306
+            $type = 'link';
5307
+        } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5308
+            $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5309
+            $type = 'sellist';
5310
+        } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
5311
+            $param['options'] = array();
5312
+            $type = 'varchar';
5313
+            $size = $reg[1];
5314
+        } elseif (preg_match('/varchar/', $val['type'])) {
5315
+            $param['options'] = array();
5316
+            $type = 'varchar';
5317
+        } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
5318
+            $param['options'] = $this->fields[$key]['arrayofkeyval'];
5319
+            $type = 'select';
5320 5320
         } else {
5321
-            $param['options']=array();
5322
-            $type =$this->fields[$key]['type'];
5321
+            $param['options'] = array();
5322
+            $type = $this->fields[$key]['type'];
5323 5323
         }
5324 5324
 
5325
-		$label=$this->fields[$key]['label'];
5325
+		$label = $this->fields[$key]['label'];
5326 5326
 		//$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5327
-		$default=$this->fields[$key]['default'];
5328
-		$computed=$this->fields[$key]['computed'];
5329
-		$unique=$this->fields[$key]['unique'];
5330
-		$required=$this->fields[$key]['required'];
5327
+		$default = $this->fields[$key]['default'];
5328
+		$computed = $this->fields[$key]['computed'];
5329
+		$unique = $this->fields[$key]['unique'];
5330
+		$required = $this->fields[$key]['required'];
5331 5331
 
5332
-		$langfile=$this->fields[$key]['langfile'];
5333
-		$list=$this->fields[$key]['list'];
5334
-		$hidden=abs($this->fields[$key]['visible'])!=1?1:0;
5332
+		$langfile = $this->fields[$key]['langfile'];
5333
+		$list = $this->fields[$key]['list'];
5334
+		$hidden = abs($this->fields[$key]['visible']) != 1 ? 1 : 0;
5335 5335
 
5336 5336
 		$objectid = $this->id;
5337 5337
 
5338 5338
 
5339 5339
 		if ($computed)
5340 5340
 		{
5341
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5341
+			if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5342 5342
 			else return '';
5343 5343
 		}
5344 5344
 
5345 5345
 
5346 5346
 		// Use in priority showsize from parameters, then $val['css'] then autodefine
5347
-		if (empty($morecss) && ! empty($val['css']))
5347
+		if (empty($morecss) && !empty($val['css']))
5348 5348
 		{
5349 5349
 			$showsize = $val['css'];
5350 5350
 		}
@@ -5358,16 +5358,16 @@  discard block
 block discarded – undo
5358 5358
 			{
5359 5359
 				$morecss = 'minwidth200imp';
5360 5360
 			}
5361
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5361
+			elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5362 5362
 			{
5363 5363
 				$morecss = 'maxwidth75';
5364 5364
                         }elseif ($type == 'url')
5365 5365
 			{
5366
-				$morecss='minwidth400';
5366
+				$morecss = 'minwidth400';
5367 5367
 			}
5368 5368
 			elseif ($type == 'boolean')
5369 5369
 			{
5370
-				$morecss='';
5370
+				$morecss = '';
5371 5371
 			}
5372 5372
 			else
5373 5373
 			{
@@ -5386,12 +5386,12 @@  discard block
 block discarded – undo
5386 5386
 			}
5387 5387
 		}
5388 5388
 
5389
-		if (in_array($type,array('date','datetime')))
5389
+		if (in_array($type, array('date', 'datetime')))
5390 5390
 		{
5391
-			$tmp=explode(',',$size);
5392
-			$newsize=$tmp[0];
5391
+			$tmp = explode(',', $size);
5392
+			$newsize = $tmp[0];
5393 5393
 
5394
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5394
+			$showtime = in_array($type, array('datetime')) ? 1 : 0;
5395 5395
 
5396 5396
 			// Do not show current date when field not required (see selectDate() method)
5397 5397
 			if (!$required && $value == '') $value = '-1';
@@ -5399,235 +5399,235 @@  discard block
 block discarded – undo
5399 5399
 			// TODO Must also support $moreparam
5400 5400
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5401 5401
 		}
5402
-		elseif (in_array($type,array('int','integer')))
5402
+		elseif (in_array($type, array('int', 'integer')))
5403 5403
 		{
5404
-			$tmp=explode(',',$size);
5405
-			$newsize=$tmp[0];
5406
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
5404
+			$tmp = explode(',', $size);
5405
+			$newsize = $tmp[0];
5406
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$newsize.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
5407 5407
 		}
5408 5408
 		elseif (preg_match('/varchar/', $type))
5409 5409
 		{
5410
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam?$moreparam:'').'>';
5410
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" maxlength="'.$size.'" value="'.dol_escape_htmltag($value).'"'.($moreparam ? $moreparam : '').'>';
5411 5411
 		}
5412 5412
 		elseif (in_array($type, array('mail', 'phone', 'url')))
5413 5413
 		{
5414
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5414
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5415 5415
 		}
5416 5416
 		elseif ($type == 'text')
5417 5417
 		{
5418
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5418
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5419 5419
 			{
5420 5420
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5421
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5422
-				$out=$doleditor->Create(1);
5421
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
5422
+				$out = $doleditor->Create(1);
5423 5423
 			}
5424 5424
 			else
5425 5425
 			{
5426
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5426
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5427 5427
 			}
5428 5428
 		}
5429 5429
 		elseif ($type == 'html')
5430 5430
 		{
5431
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5431
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5432 5432
 			{
5433 5433
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5434
-				$doleditor = new DolEditor($keyprefix . $key . $keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty(Globals::$conf->fckeditor->enabled) && Globals::$conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
5435
-                $out=$doleditor->Create(1);
5434
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty(Globals::$conf->fckeditor->enabled) && Globals::$conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
5435
+                $out = $doleditor->Create(1);
5436 5436
 			}
5437 5437
 			else
5438 5438
 			{
5439
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5439
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5440 5440
 			}
5441 5441
 		}
5442 5442
 		elseif ($type == 'boolean')
5443 5443
 		{
5444
-			$checked='';
5444
+			$checked = '';
5445 5445
 			if (!empty($value)) {
5446
-				$checked=' checked value="1" ';
5446
+				$checked = ' checked value="1" ';
5447 5447
 			} else {
5448
-				$checked=' value="1" ';
5448
+				$checked = ' value="1" ';
5449 5449
 			}
5450
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5450
+			$out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
5451 5451
 		}
5452 5452
 		elseif ($type == 'price')
5453 5453
 		{
5454 5454
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5455
-				$value=price($value);
5455
+				$value = price($value);
5456 5456
 			}
5457
-			$out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '> ' . $langs->getCurrencySymbol(Globals::$conf->currency);
5457
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol(Globals::$conf->currency);
5458 5458
         }
5459
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5459
+		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5460 5460
 		{
5461 5461
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5462
-				$value=price($value);
5462
+				$value = price($value);
5463 5463
 			}
5464
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5464
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
5465 5465
 		}
5466 5466
 		elseif ($type == 'select')
5467 5467
 		{
5468 5468
 			$out = '';
5469 5469
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5470
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5471
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5470
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5471
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5472 5472
 			}
5473 5473
 
5474
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5475
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5474
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5475
+                if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
5476 5476
 			foreach ($param['options'] as $key => $val)
5477 5477
 			{
5478 5478
 				if ((string) $key == '') continue;
5479 5479
 				list($val, $parent) = explode('|', $val);
5480
-				$out.='<option value="'.$key.'"';
5481
-				$out.= (((string) $value == (string) $key)?' selected':'');
5482
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5483
-				$out.='>'.$val.'</option>';
5480
+				$out .= '<option value="'.$key.'"';
5481
+				$out .= (((string) $value == (string) $key) ? ' selected' : '');
5482
+				$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5483
+				$out .= '>'.$val.'</option>';
5484 5484
 			}
5485
-			$out.='</select>';
5485
+			$out .= '</select>';
5486 5486
 		}
5487 5487
 		elseif ($type == 'sellist')
5488 5488
 		{
5489 5489
 			$out = '';
5490 5490
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5491
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5492
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5491
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5492
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5493 5493
 			}
5494 5494
 
5495
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5495
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5496 5496
 			if (is_array($param['options']))
5497 5497
 			{
5498
-				$param_list=array_keys($param['options']);
5498
+				$param_list = array_keys($param['options']);
5499 5499
 				$InfoFieldList = explode(":", $param_list[0]);
5500
-				$parentName='';
5501
-				$parentField='';
5500
+				$parentName = '';
5501
+				$parentField = '';
5502 5502
 				// 0 : tableName
5503 5503
 				// 1 : label field name
5504 5504
 				// 2 : key fields name (if differ of rowid)
5505 5505
 				// 3 : key field parent (for dependent lists)
5506 5506
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5507
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5507
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5508 5508
 
5509 5509
 
5510
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5510
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
5511 5511
 				{
5512 5512
 					if (strpos($InfoFieldList[4], 'extra.') !== false)
5513 5513
 					{
5514
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
5514
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5515 5515
 					} else {
5516
-						$keyList=$InfoFieldList[2].' as rowid';
5516
+						$keyList = $InfoFieldList[2].' as rowid';
5517 5517
 					}
5518 5518
 				}
5519
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5519
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
5520 5520
 				{
5521 5521
 					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5522
-					$keyList.= ', '.$parentField;
5522
+					$keyList .= ', '.$parentField;
5523 5523
 				}
5524 5524
 
5525
-				$fields_label = explode('|',$InfoFieldList[1]);
5525
+				$fields_label = explode('|', $InfoFieldList[1]);
5526 5526
 				if (is_array($fields_label))
5527 5527
 				{
5528
-					$keyList .=', ';
5528
+					$keyList .= ', ';
5529 5529
 					$keyList .= implode(', ', $fields_label);
5530 5530
 				}
5531 5531
 
5532
-				$sqlwhere='';
5532
+				$sqlwhere = '';
5533 5533
 				$sql = 'SELECT '.$keyList;
5534
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5534
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5535 5535
 				if (!empty($InfoFieldList[4]))
5536 5536
 				{
5537 5537
 					// can use SELECT request
5538
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5539
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5538
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5539
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5540 5540
 					}
5541 5541
 
5542 5542
 					// current object id can be use into filter
5543
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5544
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5543
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5544
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5545 5545
 					} else {
5546
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5546
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5547 5547
 					}
5548 5548
 					//We have to join on extrafield table
5549
-					if (strpos($InfoFieldList[4], 'extra')!==false)
5549
+					if (strpos($InfoFieldList[4], 'extra') !== false)
5550 5550
 					{
5551
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5552
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5551
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5552
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5553 5553
 					}
5554 5554
 					else
5555 5555
 					{
5556
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5556
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5557 5557
 					}
5558 5558
 				}
5559 5559
 				else
5560 5560
 				{
5561
-					$sqlwhere.= ' WHERE 1=1';
5561
+					$sqlwhere .= ' WHERE 1=1';
5562 5562
 				}
5563 5563
 				// Some tables may have field, some other not. For the moment we disable it.
5564
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
5564
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5565 5565
 				{
5566
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5566
+					$sqlwhere .= ' AND entity = '.Globals::$conf->entity;
5567 5567
                 }
5568
-				$sql.=$sqlwhere;
5568
+				$sql .= $sqlwhere;
5569 5569
 				//print $sql;
5570 5570
 
5571
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
5571
+				$sql .= ' ORDER BY '.implode(', ', $fields_label);
5572 5572
 
5573 5573
 				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5574 5574
 				$resql = $this->db->query($sql);
5575 5575
 				if ($resql)
5576 5576
 				{
5577
-					$out.='<option value="0">&nbsp;</option>';
5577
+					$out .= '<option value="0">&nbsp;</option>';
5578 5578
 					$num = $this->db->num_rows($resql);
5579 5579
 					$i = 0;
5580 5580
 					while ($i < $num)
5581 5581
 					{
5582
-						$labeltoshow='';
5582
+						$labeltoshow = '';
5583 5583
 						$obj = $this->db->fetch_object($resql);
5584 5584
 
5585 5585
 						// Several field into label (eq table:code|libelle:rowid)
5586 5586
 						$notrans = false;
5587
-						$fields_label = explode('|',$InfoFieldList[1]);
5587
+						$fields_label = explode('|', $InfoFieldList[1]);
5588 5588
 						if (is_array($fields_label))
5589 5589
 						{
5590 5590
 							$notrans = true;
5591 5591
 							foreach ($fields_label as $field_toshow)
5592 5592
 							{
5593
-								$labeltoshow.= $obj->$field_toshow.' ';
5593
+								$labeltoshow .= $obj->$field_toshow.' ';
5594 5594
 							}
5595 5595
 						}
5596 5596
 						else
5597 5597
 						{
5598
-							$labeltoshow=$obj->{$InfoFieldList[1]};
5598
+							$labeltoshow = $obj->{$InfoFieldList[1]};
5599 5599
 						}
5600
-						$labeltoshow=dol_trunc($labeltoshow,45);
5600
+						$labeltoshow = dol_trunc($labeltoshow, 45);
5601 5601
 
5602 5602
 						if ($value == $obj->rowid)
5603 5603
 						{
5604 5604
 							foreach ($fields_label as $field_toshow)
5605 5605
 							{
5606
-								$translabel=$langs->trans($obj->$field_toshow);
5607
-								if ($translabel!=$obj->$field_toshow) {
5608
-									$labeltoshow=dol_trunc($translabel,18).' ';
5609
-								}else {
5610
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5606
+								$translabel = $langs->trans($obj->$field_toshow);
5607
+								if ($translabel != $obj->$field_toshow) {
5608
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5609
+								} else {
5610
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5611 5611
 								}
5612 5612
 							}
5613
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5613
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5614 5614
 						}
5615 5615
 						else
5616 5616
 						{
5617
-							if (! $notrans)
5617
+							if (!$notrans)
5618 5618
 							{
5619
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5620
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5621
-									$labeltoshow=dol_trunc($translabel,18);
5619
+								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5620
+								if ($translabel != $obj->{$InfoFieldList[1]}) {
5621
+									$labeltoshow = dol_trunc($translabel, 18);
5622 5622
 								}
5623 5623
 								else {
5624
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5624
+									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]},18);
5625 5625
 								}
5626 5626
 							}
5627
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
5628
-							if ($value==$obj->rowid)
5627
+							if (empty($labeltoshow)) $labeltoshow = '(not defined)';
5628
+							if ($value == $obj->rowid)
5629 5629
 							{
5630
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5630
+								$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5631 5631
 							}
5632 5632
 
5633 5633
 							if (!empty($InfoFieldList[3]) && $parentField)
@@ -5635,10 +5635,10 @@  discard block
 block discarded – undo
5635 5635
 								$parent = $parentName.':'.$obj->{$parentField};
5636 5636
 							}
5637 5637
 
5638
-							$out.='<option value="'.$obj->rowid.'"';
5639
-							$out.= ($value==$obj->rowid?' selected':'');
5640
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5641
-							$out.='>'.$labeltoshow.'</option>';
5638
+							$out .= '<option value="'.$obj->rowid.'"';
5639
+							$out .= ($value == $obj->rowid ? ' selected' : '');
5640
+							$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5641
+							$out .= '>'.$labeltoshow.'</option>';
5642 5642
 						}
5643 5643
 
5644 5644
 						$i++;
@@ -5649,23 +5649,23 @@  discard block
 block discarded – undo
5649 5649
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5650 5650
 				}
5651 5651
 			}
5652
-			$out.='</select>';
5652
+			$out .= '</select>';
5653 5653
 		}
5654 5654
 		elseif ($type == 'checkbox')
5655 5655
 		{
5656
-			$value_arr=explode(',',$value);
5657
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5656
+			$value_arr = explode(',', $value);
5657
+			$out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5658 5658
 		}
5659 5659
 		elseif ($type == 'radio')
5660 5660
 		{
5661
-			$out='';
5661
+			$out = '';
5662 5662
 			foreach ($param['options'] as $keyopt => $val)
5663 5663
 			{
5664
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5665
-				$out.=' value="'.$keyopt.'"';
5666
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5667
-				$out.= ($value==$keyopt?'checked':'');
5668
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5664
+				$out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
5665
+				$out .= ' value="'.$keyopt.'"';
5666
+				$out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5667
+				$out .= ($value == $keyopt ? 'checked' : '');
5668
+				$out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5669 5669
 			}
5670 5670
 		}
5671 5671
 		elseif ($type == 'chkbxlst')
@@ -5680,24 +5680,24 @@  discard block
 block discarded – undo
5680 5680
 			if (is_array($param['options'])) {
5681 5681
 				$param_list = array_keys($param['options']);
5682 5682
 				$InfoFieldList = explode(":", $param_list[0]);
5683
-				$parentName='';
5684
-				$parentField='';
5683
+				$parentName = '';
5684
+				$parentField = '';
5685 5685
 				// 0 : tableName
5686 5686
 				// 1 : label field name
5687 5687
 				// 2 : key fields name (if differ of rowid)
5688 5688
 				// 3 : key field parent (for dependent lists)
5689 5689
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5690
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5690
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5691 5691
 
5692
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5693
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5694
-					$keyList .= ', ' . $parentField;
5692
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
5693
+					list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5694
+					$keyList .= ', '.$parentField;
5695 5695
 				}
5696
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5696
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
5697 5697
 					if (strpos($InfoFieldList[4], 'extra.') !== false) {
5698
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5698
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5699 5699
 					} else {
5700
-						$keyList = $InfoFieldList[2] . ' as rowid';
5700
+						$keyList = $InfoFieldList[2].' as rowid';
5701 5701
 					}
5702 5702
 				}
5703 5703
 
@@ -5708,50 +5708,50 @@  discard block
 block discarded – undo
5708 5708
 				}
5709 5709
 
5710 5710
 				$sqlwhere = '';
5711
-				$sql = 'SELECT ' . $keyList;
5712
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5713
-				if (! empty($InfoFieldList[4])) {
5711
+				$sql = 'SELECT '.$keyList;
5712
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5713
+				if (!empty($InfoFieldList[4])) {
5714 5714
 
5715 5715
 					// can use SELECT request
5716
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5717
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5716
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5717
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5718 5718
 					}
5719 5719
 
5720 5720
 					// current object id can be use into filter
5721
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5722
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5721
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5722
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5723 5723
 					} else {
5724
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5724
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5725 5725
 					}
5726 5726
 
5727 5727
 					// We have to join on extrafield table
5728 5728
 					if (strpos($InfoFieldList[4], 'extra') !== false) {
5729
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5730
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5729
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5730
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5731 5731
 					} else {
5732
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5732
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5733 5733
 					}
5734 5734
 				} else {
5735 5735
 					$sqlwhere .= ' WHERE 1=1';
5736 5736
 				}
5737 5737
 				// Some tables may have field, some other not. For the moment we disable it.
5738
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
5738
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5739 5739
 				{
5740
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5740
+					$sqlwhere .= ' AND entity = '.Globals::$conf->entity;
5741 5741
                 }
5742 5742
 				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
5743 5743
 				// print $sql;
5744 5744
 
5745 5745
 				$sql .= $sqlwhere;
5746
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5746
+				dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
5747 5747
 				$resql = $this->db->query($sql);
5748 5748
 				if ($resql) {
5749 5749
 					$num = $this->db->num_rows($resql);
5750 5750
 					$i = 0;
5751 5751
 
5752
-					$data=array();
5752
+					$data = array();
5753 5753
 
5754
-					while ( $i < $num ) {
5754
+					while ($i < $num) {
5755 5755
 						$labeltoshow = '';
5756 5756
 						$obj = $this->db->fetch_object($resql);
5757 5757
 
@@ -5760,8 +5760,8 @@  discard block
 block discarded – undo
5760 5760
 						$fields_label = explode('|', $InfoFieldList[1]);
5761 5761
 						if (is_array($fields_label)) {
5762 5762
 							$notrans = true;
5763
-							foreach ( $fields_label as $field_toshow ) {
5764
-								$labeltoshow .= $obj->$field_toshow . ' ';
5763
+							foreach ($fields_label as $field_toshow) {
5764
+								$labeltoshow .= $obj->$field_toshow.' ';
5765 5765
 							}
5766 5766
 						} else {
5767 5767
 							$labeltoshow = $obj->{$InfoFieldList[1]};
@@ -5769,18 +5769,18 @@  discard block
 block discarded – undo
5769 5769
 						$labeltoshow = dol_trunc($labeltoshow, 45);
5770 5770
 
5771 5771
 						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5772
-							foreach ( $fields_label as $field_toshow ) {
5772
+							foreach ($fields_label as $field_toshow) {
5773 5773
 								$translabel = $langs->trans($obj->$field_toshow);
5774 5774
 								if ($translabel != $obj->$field_toshow) {
5775
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
5775
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5776 5776
 								} else {
5777
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5777
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5778 5778
 								}
5779 5779
 							}
5780 5780
 
5781
-							$data[$obj->rowid]=$labeltoshow;
5781
+							$data[$obj->rowid] = $labeltoshow;
5782 5782
 						} else {
5783
-							if (! $notrans) {
5783
+							if (!$notrans) {
5784 5784
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5785 5785
 								if ($translabel != $obj->{$InfoFieldList[1]}) {
5786 5786
 									$labeltoshow = dol_trunc($translabel, 18);
@@ -5792,66 +5792,66 @@  discard block
 block discarded – undo
5792 5792
 								$labeltoshow = '(not defined)';
5793 5793
 
5794 5794
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5795
-									$data[$obj->rowid]=$labeltoshow;
5795
+									$data[$obj->rowid] = $labeltoshow;
5796 5796
 								}
5797 5797
 
5798
-								if (! empty($InfoFieldList[3]) && $parentField) {
5799
-									$parent = $parentName . ':' . $obj->{$parentField};
5798
+								if (!empty($InfoFieldList[3]) && $parentField) {
5799
+									$parent = $parentName.':'.$obj->{$parentField};
5800 5800
 								}
5801 5801
 
5802
-								$data[$obj->rowid]=$labeltoshow;
5802
+								$data[$obj->rowid] = $labeltoshow;
5803 5803
 						}
5804 5804
 
5805
-						$i ++;
5805
+						$i++;
5806 5806
 					}
5807 5807
 					$this->db->free($resql);
5808 5808
 
5809
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5809
+					$out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5810 5810
 				} else {
5811
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5811
+					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5812 5812
 				}
5813 5813
 			}
5814 5814
 		}
5815 5815
 		elseif ($type == 'link')
5816 5816
 		{
5817
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5818
-			$showempty=(($required && $default != '')?0:1);
5819
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5817
+			$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
5818
+			$showempty = (($required && $default != '') ? 0 : 1);
5819
+			$out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5820 5820
 			if (Globals::$conf->global->MAIN_FEATURES_LEVEL >= 2) {
5821
-            			list($class,$classfile)=explode(':',$param_list[0]);
5822
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5823
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5824
-            			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5821
+            			list($class, $classfile) = explode(':', $param_list[0]);
5822
+            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
5823
+            			else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php', 1);
5824
+            			$out .= '<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5825 5825
             			// TODO Add Javascript code to add input fields contents to new elements urls
5826 5826
 			}
5827 5827
 		}
5828 5828
 		elseif ($type == 'password')
5829 5829
 		{
5830 5830
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
5831
-			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5831
+			$out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
5832 5832
 		}
5833 5833
 		elseif ($type == 'array')
5834 5834
 		{
5835 5835
 			$newval = $val;
5836 5836
 			$newval['type'] = 'varchar(256)';
5837 5837
 
5838
-			$out='';
5838
+			$out = '';
5839 5839
 
5840 5840
 			$inputs = array();
5841
-			if(! empty($value)) {
5842
-				foreach($value as $option) {
5843
-					$out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5844
-					$out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5841
+			if (!empty($value)) {
5842
+				foreach ($value as $option) {
5843
+					$out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5844
+					$out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5845 5845
 				}
5846 5846
 			}
5847 5847
 
5848
-			$out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5848
+			$out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5849 5849
 
5850 5850
 			$newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5851
-			$newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5851
+			$newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5852 5852
 
5853 5853
 			if (!empty(Globals::$conf->use_javascript_ajax)) {
5854
-                $out.= '
5854
+                $out .= '
5855 5855
 					<script type="text/javascript">
5856 5856
 					$(document).ready(function() {
5857 5857
 						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
@@ -5866,7 +5866,7 @@  discard block
 block discarded – undo
5866 5866
 			}
5867 5867
 		}
5868 5868
 		if (!empty($hidden)) {
5869
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5869
+			$out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5870 5870
 		}
5871 5871
 		/* Add comments
5872 5872
 		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
@@ -5888,14 +5888,14 @@  discard block
 block discarded – undo
5888 5888
 	 * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5889 5889
 	 * @return string
5890 5890
 	 */
5891
-	function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5891
+	function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $showsize = 0)
5892 5892
 	{
5893
-		global $conf,$langs,$form;
5893
+		global $conf, $langs, $form;
5894 5894
 
5895
-		if (! is_object($form))
5895
+		if (!is_object($form))
5896 5896
 		{
5897 5897
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5898
-			$form=new Form($this->db);
5898
+			$form = new Form($this->db);
5899 5899
 		}
5900 5900
 
5901 5901
 		$objectid = $this->id;
@@ -5906,28 +5906,28 @@  discard block
 block discarded – undo
5906 5906
 		// Convert var to be able to share same code than showOutputField of extrafields
5907 5907
 		if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5908 5908
 		{
5909
-			$type = 'varchar';		// convert varchar(xx) int varchar
5909
+			$type = 'varchar'; // convert varchar(xx) int varchar
5910 5910
 			$size = $reg[1];
5911 5911
 		}
5912
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5913
-		if (is_array($val['arrayofkeyval'])) $type='select';
5914
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5912
+		elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
5913
+		if (is_array($val['arrayofkeyval'])) $type = 'select';
5914
+		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
5915 5915
 
5916
-		$default=$val['default'];
5917
-		$computed=$val['computed'];
5918
-		$unique=$val['unique'];
5919
-		$required=$val['required'];
5920
-		$param=$val['param'];
5916
+		$default = $val['default'];
5917
+		$computed = $val['computed'];
5918
+		$unique = $val['unique'];
5919
+		$required = $val['required'];
5920
+		$param = $val['param'];
5921 5921
 		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5922 5922
 		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5923 5923
 		{
5924
-			$type='link';
5925
-			$param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5924
+			$type = 'link';
5925
+			$param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5926 5926
 		}
5927
-		$langfile=$val['langfile'];
5928
-		$list=$val['list'];
5929
-		$help=$val['help'];
5930
-		$hidden=(($val['visible'] == 0) ? 1 : 0);			// If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
5927
+		$langfile = $val['langfile'];
5928
+		$list = $val['list'];
5929
+		$help = $val['help'];
5930
+		$hidden = (($val['visible'] == 0) ? 1 : 0); // If zero, we are sure it is hidden, otherwise we show. If it depends on mode (view/create/edit form or list, this must be filtered by caller)
5931 5931
 
5932 5932
 		if ($hidden) return '';
5933 5933
 
@@ -5951,18 +5951,18 @@  discard block
 block discarded – undo
5951 5951
 				//$showsize=19;
5952 5952
 				$showsize = 'minwidth200imp';
5953 5953
 			}
5954
-			elseif (in_array($type,array('int','double','price')))
5954
+			elseif (in_array($type, array('int', 'double', 'price')))
5955 5955
 			{
5956 5956
 				//$showsize=10;
5957 5957
 				$showsize = 'maxwidth75';
5958 5958
 			}
5959 5959
 			elseif ($type == 'url')
5960 5960
 			{
5961
-				$showsize='minwidth400';
5961
+				$showsize = 'minwidth400';
5962 5962
 			}
5963 5963
 			elseif ($type == 'boolean')
5964 5964
 			{
5965
-				$showsize='';
5965
+				$showsize = '';
5966 5966
 			}
5967 5967
 			else
5968 5968
 			{
@@ -5983,49 +5983,49 @@  discard block
 block discarded – undo
5983 5983
 		}
5984 5984
 
5985 5985
 		// Format output value differently according to properties of field
5986
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5987
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5986
+		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
5987
+		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
5988 5988
 		elseif ($type == 'date')
5989 5989
 		{
5990
-			if(! empty($value)) {
5991
-				$value=dol_print_date($value,'day');
5990
+			if (!empty($value)) {
5991
+				$value = dol_print_date($value, 'day');
5992 5992
 			} else {
5993
-				$value='';
5993
+				$value = '';
5994 5994
 			}
5995 5995
 		}
5996 5996
 		elseif ($type == 'datetime')
5997 5997
 		{
5998
-			if(! empty($value)) {
5999
-				$value=dol_print_date($value,'dayhour');
5998
+			if (!empty($value)) {
5999
+				$value = dol_print_date($value, 'dayhour');
6000 6000
 			} else {
6001
-				$value='';
6001
+				$value = '';
6002 6002
 			}
6003 6003
 		}
6004 6004
 		elseif ($type == 'double')
6005 6005
 		{
6006 6006
 			if (!empty($value)) {
6007
-				$value=price($value);
6007
+				$value = price($value);
6008 6008
 			}
6009 6009
 		}
6010 6010
 		elseif ($type == 'boolean')
6011 6011
 		{
6012
-			$checked='';
6012
+			$checked = '';
6013 6013
 			if (!empty($value)) {
6014
-				$checked=' checked ';
6014
+				$checked = ' checked ';
6015 6015
 			}
6016
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6016
+			$value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
6017 6017
 		}
6018 6018
 		elseif ($type == 'mail')
6019 6019
 		{
6020
-			$value=dol_print_email($value,0,0,0,64,1,1);
6020
+			$value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
6021 6021
 		}
6022 6022
 		elseif ($type == 'url')
6023 6023
 		{
6024
-			$value=dol_print_url($value,'_blank',32,1);
6024
+			$value = dol_print_url($value, '_blank', 32, 1);
6025 6025
 		}
6026 6026
 		elseif ($type == 'phone')
6027 6027
 		{
6028
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6028
+			$value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6029 6029
 		}
6030 6030
 		elseif ($type == 'price')
6031 6031
 		{
@@ -6033,40 +6033,40 @@  discard block
 block discarded – undo
6033 6033
         }
6034 6034
 		elseif ($type == 'select')
6035 6035
 		{
6036
-			$value=$param['options'][$value];
6036
+			$value = $param['options'][$value];
6037 6037
 		}
6038 6038
 		elseif ($type == 'sellist')
6039 6039
 		{
6040
-			$param_list=array_keys($param['options']);
6040
+			$param_list = array_keys($param['options']);
6041 6041
 			$InfoFieldList = explode(":", $param_list[0]);
6042 6042
 
6043
-			$selectkey="rowid";
6044
-			$keyList='rowid';
6043
+			$selectkey = "rowid";
6044
+			$keyList = 'rowid';
6045 6045
 
6046
-			if (count($InfoFieldList)>=3)
6046
+			if (count($InfoFieldList) >= 3)
6047 6047
 			{
6048 6048
 				$selectkey = $InfoFieldList[2];
6049
-				$keyList=$InfoFieldList[2].' as rowid';
6049
+				$keyList = $InfoFieldList[2].' as rowid';
6050 6050
 			}
6051 6051
 
6052
-			$fields_label = explode('|',$InfoFieldList[1]);
6053
-			if(is_array($fields_label)) {
6054
-				$keyList .=', ';
6052
+			$fields_label = explode('|', $InfoFieldList[1]);
6053
+			if (is_array($fields_label)) {
6054
+				$keyList .= ', ';
6055 6055
 				$keyList .= implode(', ', $fields_label);
6056 6056
 			}
6057 6057
 
6058 6058
 			$sql = 'SELECT '.$keyList;
6059
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6060
-			if (strpos($InfoFieldList[4], 'extra')!==false)
6059
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6060
+			if (strpos($InfoFieldList[4], 'extra') !== false)
6061 6061
 			{
6062
-				$sql.= ' as main';
6062
+				$sql .= ' as main';
6063 6063
 			}
6064
-			if ($selectkey=='rowid' && empty($value)) {
6065
-				$sql.= " WHERE ".$selectkey."=0";
6066
-			} elseif ($selectkey=='rowid') {
6067
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6068
-			}else {
6069
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6064
+			if ($selectkey == 'rowid' && empty($value)) {
6065
+				$sql .= " WHERE ".$selectkey."=0";
6066
+			} elseif ($selectkey == 'rowid') {
6067
+				$sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
6068
+			} else {
6069
+				$sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6070 6070
 			}
6071 6071
 
6072 6072
 			//$sql.= ' AND entity = '.Globals::$conf->entity;
@@ -6075,38 +6075,38 @@  discard block
 block discarded – undo
6075 6075
 			$resql = $this->db->query($sql);
6076 6076
 			if ($resql)
6077 6077
 			{
6078
-				$value='';	// value was used, so now we reste it to use it to build final output
6078
+				$value = ''; // value was used, so now we reste it to use it to build final output
6079 6079
 
6080 6080
 				$obj = $this->db->fetch_object($resql);
6081 6081
 
6082 6082
 				// Several field into label (eq table:code|libelle:rowid)
6083
-				$fields_label = explode('|',$InfoFieldList[1]);
6083
+				$fields_label = explode('|', $InfoFieldList[1]);
6084 6084
 
6085
-				if(is_array($fields_label) && count($fields_label)>1)
6085
+				if (is_array($fields_label) && count($fields_label) > 1)
6086 6086
 				{
6087 6087
 					foreach ($fields_label as $field_toshow)
6088 6088
 					{
6089
-						$translabel='';
6089
+						$translabel = '';
6090 6090
 						if (!empty($obj->$field_toshow)) {
6091
-							$translabel=$langs->trans($obj->$field_toshow);
6091
+							$translabel = $langs->trans($obj->$field_toshow);
6092 6092
 						}
6093
-						if ($translabel!=$field_toshow) {
6094
-							$value.=dol_trunc($translabel,18).' ';
6095
-						}else {
6096
-							$value.=$obj->$field_toshow.' ';
6093
+						if ($translabel != $field_toshow) {
6094
+							$value .= dol_trunc($translabel, 18).' ';
6095
+						} else {
6096
+							$value .= $obj->$field_toshow.' ';
6097 6097
 						}
6098 6098
 					}
6099 6099
 				}
6100 6100
 				else
6101 6101
 				{
6102
-					$translabel='';
6102
+					$translabel = '';
6103 6103
 					if (!empty($obj->{$InfoFieldList[1]})) {
6104
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
6104
+						$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6105 6105
 					}
6106
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6107
-						$value=dol_trunc($translabel,18);
6108
-					}else {
6109
-						$value=$obj->{$InfoFieldList[1]};
6106
+					if ($translabel != $obj->{$InfoFieldList[1]}) {
6107
+						$value = dol_trunc($translabel, 18);
6108
+					} else {
6109
+						$value = $obj->{$InfoFieldList[1]};
6110 6110
 					}
6111 6111
 				}
6112 6112
 			}
@@ -6114,18 +6114,18 @@  discard block
 block discarded – undo
6114 6114
 		}
6115 6115
 		elseif ($type == 'radio')
6116 6116
 		{
6117
-			$value=$param['options'][$value];
6117
+			$value = $param['options'][$value];
6118 6118
 		}
6119 6119
 		elseif ($type == 'checkbox')
6120 6120
 		{
6121
-			$value_arr=explode(',',$value);
6122
-			$value='';
6123
-			if (is_array($value_arr) && count($value_arr)>0)
6121
+			$value_arr = explode(',', $value);
6122
+			$value = '';
6123
+			if (is_array($value_arr) && count($value_arr) > 0)
6124 6124
 			{
6125 6125
 				foreach ($value_arr as $keyval=>$valueval) {
6126
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6126
+					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6127 6127
 				}
6128
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6128
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6129 6129
 			}
6130 6130
 		}
6131 6131
 		elseif ($type == 'chkbxlst')
@@ -6140,7 +6140,7 @@  discard block
 block discarded – undo
6140 6140
 
6141 6141
 			if (count($InfoFieldList) >= 3) {
6142 6142
 				$selectkey = $InfoFieldList[2];
6143
-				$keyList = $InfoFieldList[2] . ' as rowid';
6143
+				$keyList = $InfoFieldList[2].' as rowid';
6144 6144
 			}
6145 6145
 
6146 6146
 			$fields_label = explode('|', $InfoFieldList[1]);
@@ -6149,75 +6149,75 @@  discard block
 block discarded – undo
6149 6149
 				$keyList .= implode(', ', $fields_label);
6150 6150
 			}
6151 6151
 
6152
-			$sql = 'SELECT ' . $keyList;
6153
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6152
+			$sql = 'SELECT '.$keyList;
6153
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6154 6154
 			if (strpos($InfoFieldList[4], 'extra') !== false) {
6155 6155
 				$sql .= ' as main';
6156 6156
 			}
6157 6157
 			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6158 6158
 			// $sql.= ' AND entity = '.Globals::$conf->entity;
6159 6159
 
6160
-            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6160
+            dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
6161 6161
 			$resql = $this->db->query($sql);
6162 6162
 			if ($resql) {
6163 6163
 				$value = ''; // value was used, so now we reste it to use it to build final output
6164
-				$toprint=array();
6165
-				while ( $obj = $this->db->fetch_object($resql) ) {
6164
+				$toprint = array();
6165
+				while ($obj = $this->db->fetch_object($resql)) {
6166 6166
 
6167 6167
 					// Several field into label (eq table:code|libelle:rowid)
6168 6168
 					$fields_label = explode('|', $InfoFieldList[1]);
6169 6169
 					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6170 6170
 						if (is_array($fields_label) && count($fields_label) > 1) {
6171
-							foreach ( $fields_label as $field_toshow ) {
6171
+							foreach ($fields_label as $field_toshow) {
6172 6172
 								$translabel = '';
6173
-								if (! empty($obj->$field_toshow)) {
6173
+								if (!empty($obj->$field_toshow)) {
6174 6174
 									$translabel = $langs->trans($obj->$field_toshow);
6175 6175
 								}
6176 6176
 								if ($translabel != $field_toshow) {
6177
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6177
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6178 6178
 								} else {
6179
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6179
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6180 6180
 								}
6181 6181
 							}
6182 6182
 						} else {
6183 6183
 							$translabel = '';
6184
-							if (! empty($obj->{$InfoFieldList[1]})) {
6184
+							if (!empty($obj->{$InfoFieldList[1]})) {
6185 6185
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6186 6186
 							}
6187 6187
 							if ($translabel != $obj->{$InfoFieldList[1]}) {
6188
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6188
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6189 6189
 							} else {
6190
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6190
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6191 6191
 							}
6192 6192
 						}
6193 6193
 					}
6194 6194
 				}
6195
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6195
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6196 6196
 			} else {
6197
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6197
+				dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6198 6198
 			}
6199 6199
 		}
6200 6200
 		elseif ($type == 'link')
6201 6201
 		{
6202
-			$out='';
6202
+			$out = '';
6203 6203
 
6204 6204
 			// only if something to display (perf)
6205 6205
 			if ($value)
6206 6206
 			{
6207
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6207
+				$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
6208 6208
 
6209 6209
 				$InfoFieldList = explode(":", $param_list[0]);
6210
-				$classname=$InfoFieldList[0];
6211
-				$classpath=$InfoFieldList[1];
6212
-				$getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6213
-				if (! empty($classpath))
6210
+				$classname = $InfoFieldList[0];
6211
+				$classpath = $InfoFieldList[1];
6212
+				$getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6213
+				if (!empty($classpath))
6214 6214
 				{
6215 6215
 					dol_include_once($InfoFieldList[1]);
6216 6216
 					if ($classname && class_exists($classname))
6217 6217
 					{
6218 6218
 						$object = new $classname($this->db);
6219 6219
 						$object->fetch($value);
6220
-						$value=$object->getNomUrl($getnomurlparam);
6220
+						$value = $object->getNomUrl($getnomurlparam);
6221 6221
 					}
6222 6222
 				}
6223 6223
 				else
@@ -6226,15 +6226,15 @@  discard block
 block discarded – undo
6226 6226
 					return 'Error bad setup of extrafield';
6227 6227
 				}
6228 6228
 			}
6229
-			else $value='';
6229
+			else $value = '';
6230 6230
 		}
6231 6231
 		elseif ($type == 'text' || $type == 'html')
6232 6232
 		{
6233
-			$value=dol_htmlentitiesbr($value);
6233
+			$value = dol_htmlentitiesbr($value);
6234 6234
 		}
6235 6235
 		elseif ($type == 'password')
6236 6236
 		{
6237
-			$value=preg_replace('/./i','*',$value);
6237
+			$value = preg_replace('/./i', '*', $value);
6238 6238
 		}
6239 6239
 		elseif ($type == 'array')
6240 6240
 		{
@@ -6242,7 +6242,7 @@  discard block
 block discarded – undo
6242 6242
 		}
6243 6243
 
6244 6244
 		//print $type.'-'.$size;
6245
-		$out=$value;
6245
+		$out = $value;
6246 6246
 
6247 6247
 		return $out;
6248 6248
 	}
@@ -6259,11 +6259,11 @@  discard block
 block discarded – undo
6259 6259
 	 * @param	string		$onetrtd		All fields in same tr td
6260 6260
 	 * @return 	string
6261 6261
 	 */
6262
-	function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6262
+	function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
6263 6263
 	{
6264 6264
 		global $db, $conf, $langs, $action, $form;
6265 6265
 
6266
-		if (! is_object($form)) $form=new Form($db);
6266
+		if (!is_object($form)) $form = new Form($db);
6267 6267
 
6268 6268
 		$out = '';
6269 6269
 
@@ -6274,10 +6274,10 @@  discard block
 block discarded – undo
6274 6274
 			$out .= "\n";
6275 6275
 
6276 6276
 			$e = 0;
6277
-			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6277
+			foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6278 6278
 			{
6279 6279
 				// Show only the key field in params
6280
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6280
+				if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
6281 6281
 
6282 6282
 				$enabled = 1;
6283 6283
 				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
@@ -6291,25 +6291,25 @@  discard block
 block discarded – undo
6291 6291
 					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6292 6292
 				}
6293 6293
 
6294
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6294
+				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6295 6295
 				if (empty($perms)) continue;
6296 6296
 
6297 6297
 				// Load language if required
6298
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6298
+				if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6299 6299
 
6300
-				$colspan='3';
6301
-				if (is_array($params) && count($params)>0) {
6302
-					if (array_key_exists('colspan',$params)) {
6303
-						$colspan=$params['colspan'];
6300
+				$colspan = '3';
6301
+				if (is_array($params) && count($params) > 0) {
6302
+					if (array_key_exists('colspan', $params)) {
6303
+						$colspan = $params['colspan'];
6304 6304
 					}
6305 6305
 				}
6306 6306
 
6307
-				switch($mode) {
6307
+				switch ($mode) {
6308 6308
 					case "view":
6309
-						$value=$this->array_options["options_".$key.$keysuffix];
6309
+						$value = $this->array_options["options_".$key.$keysuffix];
6310 6310
 						break;
6311 6311
 					case "edit":
6312
-						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6312
+						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values.
6313 6313
 						// GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6314 6314
 						if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6315 6315
 						{
@@ -6320,7 +6320,7 @@  discard block
 block discarded – undo
6320 6320
 								$value = $getposttemp;
6321 6321
 							}
6322 6322
 						} else {
6323
-							$value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6323
+							$value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
6324 6324
 						}
6325 6325
 						//var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6326 6326
 						break;
@@ -6332,11 +6332,11 @@  discard block
 block discarded – undo
6332 6332
 				}
6333 6333
 				else
6334 6334
 				{
6335
-					$csstyle='';
6336
-					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6337
-					if (is_array($params) && count($params)>0) {
6338
-						if (array_key_exists('style',$params)) {
6339
-							$csstyle=$params['style'];
6335
+					$csstyle = '';
6336
+					$class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6337
+					if (is_array($params) && count($params) > 0) {
6338
+						if (array_key_exists('style', $params)) {
6339
+							$csstyle = $params['style'];
6340 6340
 						}
6341 6341
 					}
6342 6342
 
@@ -6358,35 +6358,35 @@  discard block
 block discarded – undo
6358 6358
 					if ($action == 'selectlines') { $colspan++; }
6359 6359
 
6360 6360
 					// Convert date into timestamp format (value in memory must be a timestamp)
6361
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6361
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
6362 6362
 					{
6363
-						$datenotinstring = $this->array_options['options_' . $key];
6364
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6363
+						$datenotinstring = $this->array_options['options_'.$key];
6364
+						if (!is_numeric($this->array_options['options_'.$key]))	// For backward compatibility
6365 6365
 						{
6366 6366
 							$datenotinstring = $this->db->jdate($datenotinstring);
6367 6367
 						}
6368
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min",'int',3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day",'int',3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year",'int',3)):$datenotinstring;
6368
+						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?dol_mktime(GETPOST($keyprefix.'options_'.$key.$keysuffix."hour", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."min", 'int', 3), 0, GETPOST($keyprefix.'options_'.$key.$keysuffix."month", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."day", 'int', 3), GETPOST($keyprefix.'options_'.$key.$keysuffix."year", 'int', 3)) : $datenotinstring;
6369 6369
 					}
6370 6370
 					// Convert float submited string into real php numeric (value in memory must be a php numeric)
6371
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6371
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
6372 6372
 					{
6373
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6373
+						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)) : $this->array_options['options_'.$key];
6374 6374
 					}
6375 6375
 
6376 6376
 					$labeltoshow = $langs->trans($label);
6377 6377
 
6378 6378
 					$out .= '<td class="titlefield';
6379
-					if (GETPOST('action','none') == 'create') $out.='create';
6380
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6379
+					if (GETPOST('action', 'none') == 'create') $out .= 'create';
6380
+					if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6381 6381
 					$out .= '">';
6382
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6382
+					if (!empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6383 6383
 					else $out .= $labeltoshow;
6384 6384
 					$out .= '</td>';
6385 6385
 
6386 6386
 					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6387
-					$out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6387
+					$out .= '<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
6388 6388
 
6389
-					switch($mode) {
6389
+					switch ($mode) {
6390 6390
 						case "view":
6391 6391
 							$out .= $extrafields->showOutputField($key, $value);
6392 6392
 							break;
@@ -6451,7 +6451,7 @@  discard block
 block discarded – undo
6451 6451
 		global $user;
6452 6452
 
6453 6453
 		$element = $this->element;
6454
-		if ($element == 'facturerec') $element='facture';
6454
+		if ($element == 'facturerec') $element = 'facture';
6455 6455
 
6456 6456
 		return $user->rights->{$element};
6457 6457
 	}
@@ -6468,15 +6468,15 @@  discard block
 block discarded – undo
6468 6468
 	 * @param  int         $ignoreerrors  Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one)
6469 6469
 	 * @return bool						  True if success, False if error
6470 6470
 	 */
6471
-	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6471
+	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
6472 6472
 	{
6473 6473
 		foreach ($tables as $table)
6474 6474
 		{
6475 6475
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6476 6476
 
6477
-			if (! $db->query($sql))
6477
+			if (!$db->query($sql))
6478 6478
 			{
6479
-				if ($ignoreerrors) return true;		// TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
6479
+				if ($ignoreerrors) return true; // TODO Not enough. If there is A-B on kept thirdarty and B-C on old one, we must get A-B-C after merge. Not A-B.
6480 6480
 				//$this->errors = $db->lasterror();
6481 6481
 				return false;
6482 6482
 			}
@@ -6509,7 +6509,7 @@  discard block
 block discarded – undo
6509 6509
 		else
6510 6510
 		{
6511 6511
 			// Get cost price for margin calculation
6512
-			if (! empty($fk_product))
6512
+			if (!empty($fk_product))
6513 6513
 			{
6514 6514
 				if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'costprice') {
6515 6515
 					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
@@ -6580,18 +6580,18 @@  discard block
 block discarded – undo
6580 6580
 	 *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6581 6581
 	 *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6582 6582
 	 */
6583
-	function show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $notitle=0, $usesharelink=0)
6583
+	function show_photos($modulepart, $sdir, $size = 0, $nbmax = 0, $nbbyrow = 5, $showfilename = 0, $showaction = 0, $maxHeight = 120, $maxWidth = 160, $nolink = 0, $notitle = 0, $usesharelink = 0)
6584 6584
 	{
6585 6585
         // phpcs:enable
6586
-		global $conf,$user,$langs;
6586
+		global $conf, $user, $langs;
6587 6587
 
6588
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6589
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6588
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6589
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6590 6590
 
6591
-		$sortfield='position_name';
6592
-		$sortorder='asc';
6591
+		$sortfield = 'position_name';
6592
+		$sortorder = 'asc';
6593 6593
 
6594
-		$dir = $sdir . '/';
6594
+		$dir = $sdir.'/';
6595 6595
 		$pdir = '/';
6596 6596
 		if ($modulepart == 'ticket')
6597 6597
 		{
@@ -6606,26 +6606,26 @@  discard block
 block discarded – undo
6606 6606
 
6607 6607
 		// For backward compatibility
6608 6608
 		if ($modulepart == 'product' && !empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
6609
-			$dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6610
-			$pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6609
+			$dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6610
+			$pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6611 6611
 		}
6612 6612
 
6613 6613
 		// Defined relative dir to DOL_DATA_ROOT
6614 6614
 		$relativedir = '';
6615 6615
 		if ($dir)
6616 6616
 		{
6617
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6618
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
6619
-			$relativedir = preg_replace('/[\\/]$/','',$relativedir);
6617
+			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
6618
+			$relativedir = preg_replace('/^[\\/]/', '', $relativedir);
6619
+			$relativedir = preg_replace('/[\\/]$/', '', $relativedir);
6620 6620
 		}
6621 6621
 
6622 6622
 		$dirthumb = $dir.'thumbs/';
6623 6623
 		$pdirthumb = $pdir.'thumbs/';
6624 6624
 
6625
-		$return ='<!-- Photo -->'."\n";
6626
-		$nbphoto=0;
6625
+		$return = '<!-- Photo -->'."\n";
6626
+		$nbphoto = 0;
6627 6627
 
6628
-		$filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6628
+		$filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
6629 6629
 
6630 6630
 		/* if (! empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6631 6631
           {
@@ -6639,12 +6639,12 @@  discard block
 block discarded – undo
6639 6639
 		{
6640 6640
 			if ($sortfield && $sortorder)
6641 6641
 			{
6642
-				$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6642
+				$filearray = dol_sort_array($filearray, $sortfield, $sortorder);
6643 6643
 			}
6644 6644
 
6645
-			foreach($filearray as $key => $val)
6645
+			foreach ($filearray as $key => $val)
6646 6646
 			{
6647
-				$photo='';
6647
+				$photo = '';
6648 6648
 				$file = $val['name'];
6649 6649
 
6650 6650
 				//if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
@@ -6659,36 +6659,36 @@  discard block
 block discarded – undo
6659 6659
 					if ($size == 1 || $size == 'small') {   // Format vignette
6660 6660
 
6661 6661
 						// Find name of thumb file
6662
-						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6663
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
6662
+						$photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
6663
+						if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
6664 6664
 
6665 6665
 						// Get filesize of original file
6666
-						$imgarray=dol_getImageSize($dir.$photo);
6666
+						$imgarray = dol_getImageSize($dir.$photo);
6667 6667
 
6668 6668
 						if ($nbbyrow > 0)
6669 6669
 						{
6670
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6670
+							if ($nbphoto == 1) $return .= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6671 6671
 
6672
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6673
-							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6672
+							if ($nbphoto % $nbbyrow == 1) $return .= '<tr align=center valign=middle border=1>';
6673
+							$return .= '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
6674 6674
 						}
6675 6675
 						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
6676 6676
 
6677
-						$return.= "\n";
6677
+						$return .= "\n";
6678 6678
 
6679
-						$relativefile=preg_replace('/^\//', '', $pdir.$photo);
6679
+						$relativefile = preg_replace('/^\//', '', $pdir.$photo);
6680 6680
 						if (empty($nolink))
6681 6681
 						{
6682
-							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6683
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6684
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6682
+							$urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6683
+							if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
6684
+							else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6685 6685
 						}
6686 6686
 
6687 6687
 						// Show image (width height=$maxHeight)
6688 6688
 						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6689
-						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6690
-						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6691
-						if ($notitle) $alt='';
6689
+						$alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
6690
+						$alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6691
+						if ($notitle) $alt = '';
6692 6692
 
6693 6693
 						if ($usesharelink)
6694 6694
 						{
@@ -6696,81 +6696,81 @@  discard block
 block discarded – undo
6696 6696
 							{
6697 6697
 								if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6698 6698
 								{
6699
-									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6700
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6699
+									$return .= '<!-- Show original file (thumb not yet available with shared links) -->';
6700
+									$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6701 6701
 								}
6702 6702
 								else {
6703
-									$return.= '<!-- Show original file -->';
6704
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6703
+									$return .= '<!-- Show original file -->';
6704
+									$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6705 6705
 								}
6706 6706
 							}
6707 6707
 							else
6708 6708
 							{
6709
-								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6710
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6709
+								$return .= '<!-- Show nophoto file (because file is not shared) -->';
6710
+								$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6711 6711
 							}
6712 6712
 						}
6713 6713
 						else
6714 6714
 						{
6715 6715
 							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6716 6716
 							{
6717
-								$return.= '<!-- Show thumb -->';
6718
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
6717
+								$return .= '<!-- Show thumb -->';
6718
+								$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdirthumb.$photo_vignette).'" title="'.dol_escape_htmltag($alt).'">';
6719 6719
 							}
6720 6720
 							else {
6721
-								$return.= '<!-- Show original file -->';
6722
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
6721
+								$return .= '<!-- Show original file -->';
6722
+								$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" title="'.dol_escape_htmltag($alt).'">';
6723 6723
 							}
6724 6724
 						}
6725 6725
 
6726
-						if (empty($nolink)) $return.= '</a>';
6727
-						$return.="\n";
6726
+						if (empty($nolink)) $return .= '</a>';
6727
+						$return .= "\n";
6728 6728
 
6729
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6729
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6730 6730
 						if ($showaction)
6731 6731
 						{
6732
-							$return.= '<br>';
6732
+							$return .= '<br>';
6733 6733
 							// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6734 6734
 							if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6735 6735
 							{
6736
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'),'refresh').'&nbsp;&nbsp;</a>';
6736
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=addthumb&amp;file='.urlencode($pdir.$viewfilename).'">'.img_picto($langs->trans('GenerateThumb'), 'refresh').'&nbsp;&nbsp;</a>';
6737 6737
 							}
6738 6738
 							// Special cas for product
6739 6739
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6740 6740
 							{
6741 6741
 								// Link to resize
6742
-								$return.= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
6742
+								$return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
6743 6743
 
6744 6744
 								// Link to delete
6745
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6746
-								$return.= img_delete().'</a>';
6745
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6746
+								$return .= img_delete().'</a>';
6747 6747
 							}
6748 6748
 						}
6749
-						$return.= "\n";
6749
+						$return .= "\n";
6750 6750
 
6751 6751
 						if ($nbbyrow > 0)
6752 6752
 						{
6753
-							$return.= '</td>';
6754
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6753
+							$return .= '</td>';
6754
+							if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
6755 6755
 						}
6756
-						else if ($nbbyrow < 0) $return.='</div>';
6756
+						else if ($nbbyrow < 0) $return .= '</div>';
6757 6757
 					}
6758 6758
 
6759 6759
 					if (empty($size)) {     // Format origine
6760
-						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6760
+						$return .= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6761 6761
 
6762
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6762
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6763 6763
 						if ($showaction)
6764 6764
 						{
6765 6765
 							// Special case for product
6766 6766
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6767 6767
 							{
6768 6768
 								// Link to resize
6769
-								$return.= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
6769
+								$return .= '<a href="'.DOL_URL_ROOT.'/core/photos_resize.php?modulepart='.urlencode('produit|service').'&id='.$this->id.'&amp;file='.urlencode($pdir.$viewfilename).'" title="'.dol_escape_htmltag($langs->trans("Resize")).'">'.img_picto($langs->trans("Resize"), 'resize', '').'</a> &nbsp; ';
6770 6770
 
6771 6771
 								// Link to delete
6772
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6773
-								$return.= img_delete().'</a>';
6772
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6773
+								$return .= img_delete().'</a>';
6774 6774
 							}
6775 6775
 						}
6776 6776
 					}
@@ -6780,18 +6780,18 @@  discard block
 block discarded – undo
6780 6780
 				}
6781 6781
 			}
6782 6782
 
6783
-			if ($size==1 || $size=='small')
6783
+			if ($size == 1 || $size == 'small')
6784 6784
 			{
6785 6785
 				if ($nbbyrow > 0)
6786 6786
 				{
6787 6787
 					// Ferme tableau
6788 6788
 					while ($nbphoto % $nbbyrow)
6789 6789
 					{
6790
-						$return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6790
+						$return .= '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
6791 6791
 						$nbphoto++;
6792 6792
 					}
6793 6793
 
6794
-					if ($nbphoto) $return.= '</table>';
6794
+					if ($nbphoto) $return .= '</table>';
6795 6795
 				}
6796 6796
 			}
6797 6797
 		}
@@ -6810,9 +6810,9 @@  discard block
 block discarded – undo
6810 6810
 	 */
6811 6811
 	protected function isArray($info)
6812 6812
 	{
6813
-		if(is_array($info))
6813
+		if (is_array($info))
6814 6814
 		{
6815
-			if(isset($info['type']) && $info['type']=='array') return true;
6815
+			if (isset($info['type']) && $info['type'] == 'array') return true;
6816 6816
 			else return false;
6817 6817
 		}
6818 6818
 		else return false;
@@ -6826,9 +6826,9 @@  discard block
 block discarded – undo
6826 6826
 	 */
6827 6827
 	protected function isNull($info)
6828 6828
 	{
6829
-		if(is_array($info))
6829
+		if (is_array($info))
6830 6830
 		{
6831
-			if(isset($info['type']) && $info['type']=='null') return true;
6831
+			if (isset($info['type']) && $info['type'] == 'null') return true;
6832 6832
 			else return false;
6833 6833
 		}
6834 6834
 		else return false;
@@ -6842,7 +6842,7 @@  discard block
 block discarded – undo
6842 6842
 	 */
6843 6843
 	public function isDate($info)
6844 6844
 	{
6845
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6845
+		if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
6846 6846
 		else return false;
6847 6847
 	}
6848 6848
 
@@ -6854,9 +6854,9 @@  discard block
 block discarded – undo
6854 6854
 	 */
6855 6855
 	public function isInt($info)
6856 6856
 	{
6857
-		if(is_array($info))
6857
+		if (is_array($info))
6858 6858
 		{
6859
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6859
+			if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
6860 6860
 			else return false;
6861 6861
 		}
6862 6862
 		else return false;
@@ -6870,7 +6870,7 @@  discard block
 block discarded – undo
6870 6870
 	 */
6871 6871
 	public function isFloat($info)
6872 6872
 	{
6873
-		if(is_array($info))
6873
+		if (is_array($info))
6874 6874
 		{
6875 6875
 			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6876 6876
 			else return false;
@@ -6886,9 +6886,9 @@  discard block
 block discarded – undo
6886 6886
 	 */
6887 6887
 	public function isText($info)
6888 6888
 	{
6889
-		if(is_array($info))
6889
+		if (is_array($info))
6890 6890
 		{
6891
-			if(isset($info['type']) && $info['type']=='text') return true;
6891
+			if (isset($info['type']) && $info['type'] == 'text') return true;
6892 6892
 			else return false;
6893 6893
 		}
6894 6894
 		else return false;
@@ -6902,9 +6902,9 @@  discard block
 block discarded – undo
6902 6902
 	 */
6903 6903
 	protected function isIndex($info)
6904 6904
 	{
6905
-		if(is_array($info))
6905
+		if (is_array($info))
6906 6906
 		{
6907
-			if(isset($info['index']) && $info['index']==true) return true;
6907
+			if (isset($info['index']) && $info['index'] == true) return true;
6908 6908
 			else return false;
6909 6909
 		}
6910 6910
 		else return false;
@@ -6920,13 +6920,13 @@  discard block
 block discarded – undo
6920 6920
 	{
6921 6921
 		global $conf;
6922 6922
 
6923
-		$queryarray=array();
6923
+		$queryarray = array();
6924 6924
 		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6925 6925
 		{
6926 6926
 			// Depending on field type ('datetime', ...)
6927
-			if($this->isDate($info))
6927
+			if ($this->isDate($info))
6928 6928
 			{
6929
-				if(empty($this->{$field}))
6929
+				if (empty($this->{$field}))
6930 6930
 				{
6931 6931
 					$queryarray[$field] = null;
6932 6932
 				}
@@ -6935,10 +6935,10 @@  discard block
 block discarded – undo
6935 6935
 					$queryarray[$field] = $this->db->idate($this->{$field});
6936 6936
 				}
6937 6937
 			}
6938
-			else if($this->isArray($info))
6938
+			else if ($this->isArray($info))
6939 6939
 			{
6940
-				if(! empty($this->{$field})) {
6941
-					if(! is_array($this->{$field})) {
6940
+				if (!empty($this->{$field})) {
6941
+					if (!is_array($this->{$field})) {
6942 6942
 						$this->{$field} = array($this->{$field});
6943 6943
 					}
6944 6944
 					$queryarray[$field] = serialize($this->{$field});
@@ -6946,20 +6946,20 @@  discard block
 block discarded – undo
6946 6946
 					$queryarray[$field] = null;
6947 6947
 				}
6948 6948
 			}
6949
-			else if($this->isInt($info))
6949
+			else if ($this->isInt($info))
6950 6950
 			{
6951 6951
 				if ($field == 'entity' && is_null($this->{$field}))
6952 6952
                     $queryarray[$field] = Globals::$conf->entity;
6953 6953
                 else
6954 6954
 				{
6955 6955
 					$queryarray[$field] = (int) price2num($this->{$field});
6956
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6956
+					if (empty($queryarray[$field])) $queryarray[$field] = 0; // May be reset to null later if property 'notnull' is -1 for this field.
6957 6957
 				}
6958 6958
 			}
6959
-			else if($this->isFloat($info))
6959
+			else if ($this->isFloat($info))
6960 6960
 			{
6961 6961
 				$queryarray[$field] = (double) price2num($this->{$field});
6962
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6962
+				if (empty($queryarray[$field])) $queryarray[$field] = 0;
6963 6963
 			}
6964 6964
 			else
6965 6965
 			{
@@ -6967,7 +6967,7 @@  discard block
 block discarded – undo
6967 6967
 			}
6968 6968
 
6969 6969
 			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6970
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6970
+			if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6971 6971
 		}
6972 6972
 
6973 6973
 		return $queryarray;
@@ -6983,35 +6983,35 @@  discard block
 block discarded – undo
6983 6983
 	{
6984 6984
 		foreach ($this->fields as $field => $info)
6985 6985
 		{
6986
-			if($this->isDate($info))
6986
+			if ($this->isDate($info))
6987 6987
 			{
6988
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6988
+				if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6989 6989
 				else $this->{$field} = strtotime($obj->{$field});
6990 6990
 			}
6991
-			elseif($this->isArray($info))
6991
+			elseif ($this->isArray($info))
6992 6992
 			{
6993
-				if(! empty($obj->{$field})) {
6993
+				if (!empty($obj->{$field})) {
6994 6994
 					$this->{$field} = @unserialize($obj->{$field});
6995 6995
 					// Hack for data not in UTF8
6996
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6996
+					if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6997 6997
 				} else {
6998 6998
 					$this->{$field} = array();
6999 6999
 				}
7000 7000
 			}
7001
-			elseif($this->isInt($info))
7001
+			elseif ($this->isInt($info))
7002 7002
 			{
7003 7003
 				if ($field == 'rowid') $this->id = (int) $obj->{$field};
7004 7004
 				else $this->{$field} = (int) $obj->{$field};
7005 7005
 			}
7006
-			elseif($this->isFloat($info))
7006
+			elseif ($this->isFloat($info))
7007 7007
 			{
7008 7008
 				$this->{$field} = (double) $obj->{$field};
7009 7009
 			}
7010
-			elseif($this->isNull($info))
7010
+			elseif ($this->isNull($info))
7011 7011
 			{
7012 7012
 				$val = $obj->{$field};
7013 7013
 				// zero is not null
7014
-				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7014
+				$this->{$field} = (is_null($val) || (empty($val) && $val !== 0 && $val !== '0') ? null : $val);
7015 7015
 			}
7016 7016
 			else
7017 7017
 			{
@@ -7020,7 +7020,7 @@  discard block
 block discarded – undo
7020 7020
 		}
7021 7021
 
7022 7022
 		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7023
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7023
+		if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7024 7024
 	}
7025 7025
 
7026 7026
 	/**
@@ -7062,14 +7062,14 @@  discard block
 block discarded – undo
7062 7062
 
7063 7063
 		$error = 0;
7064 7064
 
7065
-		$now=dol_now();
7065
+		$now = dol_now();
7066 7066
 
7067 7067
 		$fieldvalues = $this->setSaveQuery();
7068
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7069
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7070
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7068
+		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
7069
+		if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
7070
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7071 7071
 
7072
-		$keys=array();
7072
+		$keys = array();
7073 7073
 		$values = array();
7074 7074
 		foreach ($fieldvalues as $k => $v) {
7075 7075
 			$keys[$k] = $k;
@@ -7078,58 +7078,58 @@  discard block
 block discarded – undo
7078 7078
 		}
7079 7079
 
7080 7080
 		// Clean and check mandatory
7081
-		foreach($keys as $key)
7081
+		foreach ($keys as $key)
7082 7082
 		{
7083 7083
 			// If field is an implicit foreign key field
7084
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7085
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7084
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
7085
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
7086 7086
 
7087 7087
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7088
-			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7088
+			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && !isset($values[$key]) && is_null($val['default']))
7089 7089
 			{
7090 7090
 				$error++;
7091
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7091
+				$this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7092 7092
 			}
7093 7093
 
7094 7094
 			// If field is an implicit foreign key field
7095
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7096
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7095
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key] = 'null';
7096
+			if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
7097 7097
 		}
7098 7098
 
7099 7099
 		if ($error) return -1;
7100 7100
 
7101 7101
 		$this->db->begin();
7102 7102
 
7103
-		if (! $error)
7103
+		if (!$error)
7104 7104
 		{
7105 7105
 			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7106
-			$sql.= ' ('.implode( ", ", $keys ).')';
7107
-			$sql.= ' VALUES ('.implode( ", ", $values ).')';
7106
+			$sql .= ' ('.implode(", ", $keys).')';
7107
+			$sql .= ' VALUES ('.implode(", ", $values).')';
7108 7108
 
7109 7109
 			$res = $this->db->query($sql);
7110
-			if ($res===false) {
7110
+			if ($res === false) {
7111 7111
 				$error++;
7112 7112
 				$this->errors[] = $this->db->lasterror();
7113 7113
 			}
7114 7114
 		}
7115 7115
 
7116
-		if (! $error)
7116
+		if (!$error)
7117 7117
 		{
7118
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7118
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
7119 7119
 		}
7120 7120
 
7121 7121
 		// Create extrafields
7122
-		if (! $error)
7122
+		if (!$error)
7123 7123
 		{
7124
-			$result=$this->insertExtraFields();
7124
+			$result = $this->insertExtraFields();
7125 7125
 			if ($result < 0) $error++;
7126 7126
 		}
7127 7127
 
7128 7128
 		// Triggers
7129
-		if (! $error && ! $notrigger)
7129
+		if (!$error && !$notrigger)
7130 7130
 		{
7131 7131
 			// Call triggers
7132
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7132
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
7133 7133
 			if ($result < 0) { $error++; }
7134 7134
 			// End call triggers
7135 7135
 		}
@@ -7158,13 +7158,13 @@  discard block
 block discarded – undo
7158 7158
 		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7159 7159
 
7160 7160
 		$sql = 'SELECT '.$this->getFieldList();
7161
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7161
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7162 7162
 
7163
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7164
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7165
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7166
-		if ($morewhere)   $sql.= $morewhere;
7167
-		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7163
+		if (!empty($id))  $sql .= ' WHERE rowid = '.$id;
7164
+		elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7165
+		else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
7166
+		if ($morewhere)   $sql .= $morewhere;
7167
+		$sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
7168 7168
 
7169 7169
 		$res = $this->db->query($sql);
7170 7170
 		if ($res)
@@ -7201,14 +7201,14 @@  discard block
 block discarded – undo
7201 7201
 
7202 7202
 		$error = 0;
7203 7203
 
7204
-		$now=dol_now();
7204
+		$now = dol_now();
7205 7205
 
7206 7206
 		$fieldvalues = $this->setSaveQuery();
7207
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7208
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7209
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7207
+		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
7208
+		if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
7209
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7210 7210
 
7211
-		$keys=array();
7211
+		$keys = array();
7212 7212
 		$values = array();
7213 7213
 		foreach ($fieldvalues as $k => $v) {
7214 7214
 			$keys[$k] = $k;
@@ -7218,10 +7218,10 @@  discard block
 block discarded – undo
7218 7218
 		}
7219 7219
 
7220 7220
 		// Clean and check mandatory
7221
-		foreach($keys as $key)
7221
+		foreach ($keys as $key)
7222 7222
 		{
7223
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7224
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7223
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
7224
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
7225 7225
 
7226 7226
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7227 7227
 			/*
@@ -7232,13 +7232,13 @@  discard block
 block discarded – undo
7232 7232
 			}*/
7233 7233
 		}
7234 7234
 
7235
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
7235
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(',', $tmp).' WHERE rowid='.$this->id;
7236 7236
 
7237 7237
 		$this->db->begin();
7238
-		if (! $error)
7238
+		if (!$error)
7239 7239
 		{
7240 7240
 			$res = $this->db->query($sql);
7241
-			if ($res===false)
7241
+			if ($res === false)
7242 7242
 			{
7243 7243
 				$error++;
7244 7244
 				$this->errors[] = $this->db->lasterror();
@@ -7247,7 +7247,7 @@  discard block
 block discarded – undo
7247 7247
 
7248 7248
 		// Update extrafield
7249 7249
 		if (!$error && empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) {
7250
-			$result=$this->insertExtraFields();
7250
+			$result = $this->insertExtraFields();
7251 7251
 			if ($result < 0)
7252 7252
 			{
7253 7253
 				$error++;
@@ -7255,10 +7255,10 @@  discard block
 block discarded – undo
7255 7255
 		}
7256 7256
 
7257 7257
 		// Triggers
7258
-		if (! $error && ! $notrigger)
7258
+		if (!$error && !$notrigger)
7259 7259
 		{
7260 7260
 			// Call triggers
7261
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7261
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
7262 7262
 			if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7263 7263
 			// End call triggers
7264 7264
 		}
@@ -7281,68 +7281,68 @@  discard block
 block discarded – undo
7281 7281
 	 * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7282 7282
 	 * @return 	int             				<=0 if KO, >0 if OK
7283 7283
 	 */
7284
-	public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7284
+	public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
7285 7285
 	{
7286
-		$error=0;
7286
+		$error = 0;
7287 7287
 
7288 7288
 		$this->db->begin();
7289 7289
 
7290 7290
 		if ($forcechilddeletion)
7291 7291
 		{
7292
-			foreach($this->childtables as $table)
7292
+			foreach ($this->childtables as $table)
7293 7293
 			{
7294 7294
 				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7295 7295
 				$resql = $this->db->query($sql);
7296
-				if (! $resql)
7296
+				if (!$resql)
7297 7297
 				{
7298
-					$this->error=$this->db->lasterror();
7299
-					$this->errors[]=$this->error;
7298
+					$this->error = $this->db->lasterror();
7299
+					$this->errors[] = $this->error;
7300 7300
 					$this->db->rollback();
7301 7301
 					return -1;
7302 7302
 				}
7303 7303
 			}
7304 7304
 		}
7305
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7305
+		elseif (!empty($this->fk_element) && !empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7306 7306
 		{
7307 7307
 			$objectisused = $this->isObjectUsed($this->id);
7308
-			if (! empty($objectisused))
7308
+			if (!empty($objectisused))
7309 7309
 			{
7310 7310
 				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7311
-				$this->error='ErrorRecordHasChildren';
7312
-				$this->errors[]=$this->error;
7311
+				$this->error = 'ErrorRecordHasChildren';
7312
+				$this->errors[] = $this->error;
7313 7313
 				$this->db->rollback();
7314 7314
 				return 0;
7315 7315
 			}
7316 7316
 		}
7317 7317
 
7318
-		if (! $error) {
7319
-			if (! $notrigger) {
7318
+		if (!$error) {
7319
+			if (!$notrigger) {
7320 7320
 				// Call triggers
7321
-				$result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7321
+				$result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7322 7322
 				if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7323 7323
 				// End call triggers
7324 7324
 			}
7325 7325
 		}
7326 7326
 
7327
-		if (! $error && ! empty($this->isextrafieldmanaged))
7327
+		if (!$error && !empty($this->isextrafieldmanaged))
7328 7328
 		{
7329
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7330
-			$sql.= " WHERE fk_object=" . $this->id;
7329
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields";
7330
+			$sql .= " WHERE fk_object=".$this->id;
7331 7331
 
7332 7332
 			$resql = $this->db->query($sql);
7333
-			if (! $resql)
7333
+			if (!$resql)
7334 7334
 			{
7335 7335
 				$this->errors[] = $this->db->lasterror();
7336 7336
 				$error++;
7337 7337
 			}
7338 7338
 		}
7339 7339
 
7340
-		if (! $error)
7340
+		if (!$error)
7341 7341
 		{
7342 7342
 			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7343 7343
 
7344 7344
 			$res = $this->db->query($sql);
7345
-			if($res===false) {
7345
+			if ($res === false) {
7346 7346
 				$error++;
7347 7347
 				$this->errors[] = $this->db->lasterror();
7348 7348
 			}
@@ -7383,9 +7383,9 @@  discard block
 block discarded – undo
7383 7383
 		require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7384 7384
 
7385 7385
 		$comment = new Comment($this->db);
7386
-		$result=$comment->fetchAllFor($this->element, $this->id);
7387
-		if ($result<0) {
7388
-			$this->errors=array_merge($this->errors, $comment->errors);
7386
+		$result = $comment->fetchAllFor($this->element, $this->id);
7387
+		if ($result < 0) {
7388
+			$this->errors = array_merge($this->errors, $comment->errors);
7389 7389
 			return -1;
7390 7390
 		} else {
7391 7391
 			$this->comments = $comment->comments;
Please login to merge, or discard this patch.
Base/Conf.php 1 patch
Spacing   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
     //! Used to store current currency (ISO code like 'USD', 'EUR', ...)
37 37
     public $currency;
38 38
     //! Used to store current css (from theme)
39
-    public $theme;        // Contains current theme ("eldy", "auguria", ...)
40
-    public $css;          // Contains full path of css page ("/theme/eldy/style.css.php", ...)
39
+    public $theme; // Contains current theme ("eldy", "auguria", ...)
40
+    public $css; // Contains full path of css page ("/theme/eldy/style.css.php", ...)
41 41
     //! Used to store current menu handler
42 42
     public $standard_menu;
43 43
     public $modules = array(); // List of activated modules
@@ -54,11 +54,11 @@  discard block
 block discarded – undo
54 54
     public $entity = 1;
55 55
     //! Used to store list of entities to use for each element
56 56
     public $entities = array();
57
-    public $dol_hide_topmenu;   // Set if we force param dol_hide_topmenu into login url
58
-    public $dol_hide_leftmenu;   // Set if we force param dol_hide_leftmenu into login url
57
+    public $dol_hide_topmenu; // Set if we force param dol_hide_topmenu into login url
58
+    public $dol_hide_leftmenu; // Set if we force param dol_hide_leftmenu into login url
59 59
     public $dol_optimize_smallscreen; // Set if we force param dol_optimize_smallscreen into login url or if browser is smartphone
60
-    public $dol_no_mouse_hover;   // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone
61
-    public $dol_use_jmobile;   // Set if we force param dol_use_jmobile into login url
60
+    public $dol_no_mouse_hover; // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone
61
+    public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url
62 62
     public $user;
63 63
 
64 64
     /**
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
         $this->multicompany = new \stdClass();
80 80
 
81 81
         //! Charset for HTML output and for storing data in memory
82
-        $this->file->character_set_client = 'UTF-8';   // UTF-8, ISO-8859-1
82
+        $this->file->character_set_client = 'UTF-8'; // UTF-8, ISO-8859-1
83 83
         // First level object
84 84
         // TODO Remove this part.
85 85
         $this->expedition_bon = new \stdClass();
@@ -116,13 +116,13 @@  discard block
 block discarded – undo
116 116
         var_dump($this);
117 117
         die('en setValues');
118 118
 
119
-        dol_syslog(get_class($this) . "::setValues");
119
+        dol_syslog(get_class($this)."::setValues");
120 120
 
121 121
         //Define all global constants into Conf::$global->key=value
122
-        $sql = "SELECT " . $db->decrypt('name') . " as name,";
123
-        $sql .= " " . $db->decrypt('value') . " as value, entity";
124
-        $sql .= " FROM " . MAIN_DB_PREFIX . "const";
125
-        $sql .= " WHERE entity IN (0," . $this->entity . ")";
122
+        $sql = "SELECT ".$db->decrypt('name')." as name,";
123
+        $sql .= " ".$db->decrypt('value')." as value, entity";
124
+        $sql .= " FROM ".MAIN_DB_PREFIX."const";
125
+        $sql .= " WHERE entity IN (0,".$this->entity.")";
126 126
         $sql .= " ORDER BY entity"; // This is to have entity 0 first, then entity 1 that overwrite.
127 127
 
128 128
         $resql = $db->query($sql);
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
                             if (is_array($arrValue) && !empty($arrValue))
163 163
                                 $value = $arrValue;
164 164
                             else if (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl')))
165
-                                $value = '/' . $modulename . '/core/' . $partname . '/';
165
+                                $value = '/'.$modulename.'/core/'.$partname.'/';
166 166
                             else if (in_array($partname, array('models', 'theme')))
167
-                                $value = '/' . $modulename . '/';
167
+                                $value = '/'.$modulename.'/';
168 168
                             else if (in_array($partname, array('sms')))
169
-                                $value = '/' . $modulename . '/';
169
+                                $value = '/'.$modulename.'/';
170 170
                             else if ($value == 1)
171
-                                $value = '/' . $modulename . '/core/modules/' . $partname . '/'; // ex: partname = societe
171
+                                $value = '/'.$modulename.'/core/modules/'.$partname.'/'; // ex: partname = societe
172 172
                             $this->modules_parts[$partname] = array_merge($this->modules_parts[$partname], array($modulename => $value)); // $value may be a string or an array
173 173
                         }
174 174
                         // If this is a module constant (must be at end)
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
                             if (!isset($this->$modulename) || !is_object($this->$modulename))
182 182
                                 $this->$modulename = new \stdClass();
183 183
                             $this->$modulename->enabled = true;
184
-                            $this->modules[] = $modulename;              // Add this module in list of enabled modules
184
+                            $this->modules[] = $modulename; // Add this module in list of enabled modules
185 185
                         }
186 186
                     }
187 187
                 }
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
             $filesList = explode(":", Conf::$global->LOCAL_CONSTS_FILES);
197 197
             foreach ($filesList as $file) {
198 198
                 $file = dol_sanitizeFileName($file);
199
-                include_once DOL_DOCUMENT_ROOT . "/" . $file . "/" . $file . "_consts.php";
199
+                include_once DOL_DOCUMENT_ROOT."/".$file."/".$file."_consts.php";
200 200
                 foreach ($file2bddconsts as $key => $value) {
201 201
                     Conf::$global->$key = $value;
202 202
                 }
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
             try {
213 213
                 date_default_timezone_set(Globals::$conf->$global->MAIN_SERVER_TZ);
214 214
             } catch (Exception $e) {
215
-                dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=" . Conf::$global->MAIN_SERVER_TZ, LOG_ERR);
215
+                dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=".Conf::$global->MAIN_SERVER_TZ, LOG_ERR);
216 216
             }
217 217
         }
218 218
 
@@ -273,18 +273,18 @@  discard block
 block discarded – undo
273 273
         $rootforuser = DOL_DATA_ROOT;
274 274
         // If multicompany module is enabled, we redefine the root of data
275 275
         if (!empty($this->multicompany->enabled) && !empty($this->entity) && $this->entity > 1) {
276
-            $rootfordata .= '/' . $this->entity;
276
+            $rootfordata .= '/'.$this->entity;
277 277
         }
278 278
 
279 279
         // Define default dir_output and dir_temp for directories of modules
280 280
         foreach ($this->modules as $module) {
281 281
             //var_dump($module);
282 282
             // For multicompany sharings
283
-            $this->$module->multidir_output = array($this->entity => $rootfordata . "/" . $module);
284
-            $this->$module->multidir_temp = array($this->entity => $rootfordata . "/" . $module . "/temp");
283
+            $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module);
284
+            $this->$module->multidir_temp = array($this->entity => $rootfordata."/".$module."/temp");
285 285
             // For backward compatibility
286
-            $this->$module->dir_output = $rootfordata . "/" . $module;
287
-            $this->$module->dir_temp = $rootfordata . "/" . $module . "/temp";
286
+            $this->$module->dir_output = $rootfordata."/".$module;
287
+            $this->$module->dir_temp = $rootfordata."/".$module."/temp";
288 288
         }
289 289
 
290 290
         // External modules storage
@@ -294,45 +294,45 @@  discard block
 block discarded – undo
294 294
                     foreach ($dirs as $type => $name) {
295 295
                         $subdir = ($type == 'temp' ? '/temp' : '');
296 296
                         // For multicompany sharings
297
-                        $varname = 'multidir_' . $type;
298
-                        $this->$module->$varname = array($this->entity => $rootfordata . "/" . $name . $subdir);
297
+                        $varname = 'multidir_'.$type;
298
+                        $this->$module->$varname = array($this->entity => $rootfordata."/".$name.$subdir);
299 299
                         // For backward compatibility
300
-                        $varname = 'dir_' . $type;
301
-                        $this->$module->$varname = $rootfordata . "/" . $name . $subdir;
300
+                        $varname = 'dir_'.$type;
301
+                        $this->$module->$varname = $rootfordata."/".$name.$subdir;
302 302
                     }
303 303
                 }
304 304
             }
305 305
         }
306 306
 
307 307
         // For mycompany storage
308
-        $this->mycompany->dir_output = $rootfordata . "/mycompany";
309
-        $this->mycompany->dir_temp = $rootfordata . "/mycompany/temp";
308
+        $this->mycompany->dir_output = $rootfordata."/mycompany";
309
+        $this->mycompany->dir_temp = $rootfordata."/mycompany/temp";
310 310
 
311 311
         // For admin storage
312
-        $this->admin->dir_output = $rootfordata . '/admin';
313
-        $this->admin->dir_temp = $rootfordata . '/admin/temp';
312
+        $this->admin->dir_output = $rootfordata.'/admin';
313
+        $this->admin->dir_temp = $rootfordata.'/admin/temp';
314 314
 
315 315
         // For user storage
316
-        $this->user->multidir_output = array($this->entity => $rootfordata . "/users");
317
-        $this->user->multidir_temp = array($this->entity => $rootfordata . "/users/temp");
316
+        $this->user->multidir_output = array($this->entity => $rootfordata."/users");
317
+        $this->user->multidir_temp = array($this->entity => $rootfordata."/users/temp");
318 318
         // For backward compatibility
319
-        $this->user->dir_output = $rootforuser . "/users";
320
-        $this->user->dir_temp = $rootforuser . "/users/temp";
319
+        $this->user->dir_output = $rootforuser."/users";
320
+        $this->user->dir_temp = $rootforuser."/users/temp";
321 321
 
322 322
         // For usergroup storage
323
-        $this->usergroup->dir_output = $rootforuser . "/usergroups";
324
-        $this->usergroup->dir_temp = $rootforuser . "/usergroups/temp";
323
+        $this->usergroup->dir_output = $rootforuser."/usergroups";
324
+        $this->usergroup->dir_temp = $rootforuser."/usergroups/temp";
325 325
 
326 326
         // For proposal storage
327
-        $this->propal->multidir_output = array($this->entity => $rootfordata . "/propale");
328
-        $this->propal->multidir_temp = array($this->entity => $rootfordata . "/propale/temp");
327
+        $this->propal->multidir_output = array($this->entity => $rootfordata."/propale");
328
+        $this->propal->multidir_temp = array($this->entity => $rootfordata."/propale/temp");
329 329
         // For backward compatibility
330
-        $this->propal->dir_output = $rootfordata . "/propale";
331
-        $this->propal->dir_temp = $rootfordata . "/propale/temp";
330
+        $this->propal->dir_output = $rootfordata."/propale";
331
+        $this->propal->dir_temp = $rootfordata."/propale/temp";
332 332
 
333 333
         // For medias storage
334
-        $this->medias->multidir_output = array($this->entity => $rootfordata . "/medias");
335
-        $this->medias->multidir_temp = array($this->entity => $rootfordata . "/medias/temp");
334
+        $this->medias->multidir_output = array($this->entity => $rootfordata."/medias");
335
+        $this->medias->multidir_temp = array($this->entity => $rootfordata."/medias/temp");
336 336
 
337 337
         // Exception: Some dir are not the name of module. So we keep exception here for backward compatibility.
338 338
         // Sous module bons d'expedition
@@ -343,72 +343,72 @@  discard block
 block discarded – undo
343 343
         // Module fournisseur
344 344
         if (!empty($this->fournisseur)) {
345 345
             $this->fournisseur->commande = new \stdClass();
346
-            $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata . "/fournisseur/commande");
347
-            $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/commande/temp");
348
-            $this->fournisseur->commande->dir_output = $rootfordata . "/fournisseur/commande";  // For backward compatibility
349
-            $this->fournisseur->commande->dir_temp = $rootfordata . "/fournisseur/commande/temp"; // For backward compatibility
346
+            $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande");
347
+            $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfordata."/fournisseur/commande/temp");
348
+            $this->fournisseur->commande->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility
349
+            $this->fournisseur->commande->dir_temp = $rootfordata."/fournisseur/commande/temp"; // For backward compatibility
350 350
             $this->fournisseur->facture = new \stdClass();
351
-            $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata . "/fournisseur/facture");
352
-            $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/facture/temp");
353
-            $this->fournisseur->facture->dir_output = $rootfordata . "/fournisseur/facture";  // For backward compatibility
354
-            $this->fournisseur->facture->dir_temp = $rootfordata . "/fournisseur/facture/temp"; // For backward compatibility
351
+            $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture");
352
+            $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfordata."/fournisseur/facture/temp");
353
+            $this->fournisseur->facture->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility
354
+            $this->fournisseur->facture->dir_temp = $rootfordata."/fournisseur/facture/temp"; // For backward compatibility
355 355
             $this->supplierproposal = new \stdClass();
356
-            $this->supplierproposal->multidir_output = array($this->entity => $rootfordata . "/supplier_proposal");
357
-            $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata . "/supplier_proposal/temp");
358
-            $this->supplierproposal->dir_output = $rootfordata . "/supplier_proposal";    // For backward compatibility
359
-            $this->supplierproposal->dir_temp = $rootfordata . "/supplier_proposal/temp";   // For backward compatibility
356
+            $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal");
357
+            $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata."/supplier_proposal/temp");
358
+            $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility
359
+            $this->supplierproposal->dir_temp = $rootfordata."/supplier_proposal/temp"; // For backward compatibility
360 360
             $this->fournisseur->payment = new \stdClass();
361
-            $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata . "/fournisseur/payment");
362
-            $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/payment/temp");
363
-            $this->fournisseur->payment->dir_output = $rootfordata . "/fournisseur/payment";  // For backward compatibility
364
-            $this->fournisseur->payment->dir_temp = $rootfordata . "/fournisseur/payment/temp"; // For backward compatibility
361
+            $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata."/fournisseur/payment");
362
+            $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfordata."/fournisseur/payment/temp");
363
+            $this->fournisseur->payment->dir_output = $rootfordata."/fournisseur/payment"; // For backward compatibility
364
+            $this->fournisseur->payment->dir_temp = $rootfordata."/fournisseur/payment/temp"; // For backward compatibility
365 365
             // To prepare split of module fournisseur into fournisseur + supplier_order + supplier_invoice
366 366
             if (!empty($this->fournisseur->enabled) && empty(Globals::$conf->$global->MAIN_USE_NEW_SUPPLIERMOD)) {  // By default, if module supplier is on, we set new properties
367 367
                 $this->supplier_order = new \stdClass();
368 368
                 $this->supplier_order->enabled = 1;
369
-                $this->supplier_order->multidir_output = array($this->entity => $rootfordata . "/fournisseur/commande");
370
-                $this->supplier_order->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/commande/temp");
371
-                $this->supplier_order->dir_output = $rootfordata . "/fournisseur/commande";   // For backward compatibility
372
-                $this->supplier_order->dir_temp = $rootfordata . "/fournisseur/commande/temp";  // For backward compatibility
369
+                $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande");
370
+                $this->supplier_order->multidir_temp = array($this->entity => $rootfordata."/fournisseur/commande/temp");
371
+                $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility
372
+                $this->supplier_order->dir_temp = $rootfordata."/fournisseur/commande/temp"; // For backward compatibility
373 373
                 $this->supplier_invoice = new \stdClass();
374 374
                 $this->supplier_invoice->enabled = 1;
375
-                $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata . "/fournisseur/facture");
376
-                $this->supplier_invoice->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/facture/temp");
377
-                $this->supplier_invoice->dir_output = $rootfordata . "/fournisseur/facture";  // For backward compatibility
378
-                $this->supplier_invoice->dir_temp = $rootfordata . "/fournisseur/facture/temp";  // For backward compatibility
375
+                $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture");
376
+                $this->supplier_invoice->multidir_temp = array($this->entity => $rootfordata."/fournisseur/facture/temp");
377
+                $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility
378
+                $this->supplier_invoice->dir_temp = $rootfordata."/fournisseur/facture/temp"; // For backward compatibility
379 379
                 $this->supplierproposal = new \stdClass();
380
-                $this->supplierproposal->multidir_output = array($this->entity => $rootfordata . "/supplier_proposal");
381
-                $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata . "/supplier_proposal/temp");
382
-                $this->supplierproposal->dir_output = $rootfordata . "/supplier_proposal";   // For backward compatibility
383
-                $this->supplierproposal->dir_temp = $rootfordata . "/supplier_proposal/temp";  // For backward compatibility
380
+                $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal");
381
+                $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata."/supplier_proposal/temp");
382
+                $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility
383
+                $this->supplierproposal->dir_temp = $rootfordata."/supplier_proposal/temp"; // For backward compatibility
384 384
             }
385 385
         }
386 386
 
387 387
         // Module product/service
388
-        $this->product->multidir_output = array($this->entity => $rootfordata . "/produit");
389
-        $this->product->multidir_temp = array($this->entity => $rootfordata . "/produit/temp");
390
-        $this->service->multidir_output = array($this->entity => $rootfordata . "/produit");
391
-        $this->service->multidir_temp = array($this->entity => $rootfordata . "/produit/temp");
388
+        $this->product->multidir_output = array($this->entity => $rootfordata."/produit");
389
+        $this->product->multidir_temp = array($this->entity => $rootfordata."/produit/temp");
390
+        $this->service->multidir_output = array($this->entity => $rootfordata."/produit");
391
+        $this->service->multidir_temp = array($this->entity => $rootfordata."/produit/temp");
392 392
         // For backward compatibility
393
-        $this->product->dir_output = $rootfordata . "/produit";
394
-        $this->product->dir_temp = $rootfordata . "/produit/temp";
395
-        $this->service->dir_output = $rootfordata . "/produit";
396
-        $this->service->dir_temp = $rootfordata . "/produit/temp";
393
+        $this->product->dir_output = $rootfordata."/produit";
394
+        $this->product->dir_temp = $rootfordata."/produit/temp";
395
+        $this->service->dir_output = $rootfordata."/produit";
396
+        $this->service->dir_temp = $rootfordata."/produit/temp";
397 397
 
398 398
         // Module productbatch
399
-        $this->productbatch->multidir_output = array($this->entity => $rootfordata . "/produitlot");
400
-        $this->productbatch->multidir_temp = array($this->entity => $rootfordata . "/produitlot/temp");
399
+        $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot");
400
+        $this->productbatch->multidir_temp = array($this->entity => $rootfordata."/produitlot/temp");
401 401
 
402 402
         // Module contrat
403
-        $this->contrat->multidir_output = array($this->entity => $rootfordata . "/contract");
404
-        $this->contrat->multidir_temp = array($this->entity => $rootfordata . "/contract/temp");
403
+        $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract");
404
+        $this->contrat->multidir_temp = array($this->entity => $rootfordata."/contract/temp");
405 405
         // For backward compatibility
406
-        $this->contrat->dir_output = $rootfordata . "/contract";
407
-        $this->contrat->dir_temp = $rootfordata . "/contract/temp";
406
+        $this->contrat->dir_output = $rootfordata."/contract";
407
+        $this->contrat->dir_temp = $rootfordata."/contract/temp";
408 408
 
409 409
         // Module bank
410
-        $this->bank->dir_output = $rootfordata . "/bank";
411
-        $this->bank->dir_temp = $rootfordata . "/bank/temp";
410
+        $this->bank->dir_output = $rootfordata."/bank";
411
+        $this->bank->dir_temp = $rootfordata."/bank/temp";
412 412
 
413 413
 
414 414
         // Set some default values
@@ -431,7 +431,7 @@  discard block
 block discarded – undo
431 431
         if (empty(Globals::$conf->$global->USER_PASSWORD_GENERATED))
432 432
             Conf::$global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator
433 433
         if (empty(Globals::$conf->$global->MAIN_UMASK))
434
-            Conf::$global->MAIN_UMASK = '0664';         // Default mask
434
+            Conf::$global->MAIN_UMASK = '0664'; // Default mask
435 435
 
436 436
 
437 437
 
@@ -472,7 +472,7 @@  discard block
 block discarded – undo
472 472
         $this->currency = Conf::$global->MAIN_MONNAIE;
473 473
 
474 474
         if (empty(Globals::$conf->$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY))
475
-            Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30;   // Less than 1 minutes to be sure
475
+            Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30; // Less than 1 minutes to be sure
476 476
 
477 477
 
478 478
 
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 
483 483
 // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...)
484 484
         if (empty(Globals::$conf->$global->ACCOUNTING_MODE))
485
-            Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES';  // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
485
+            Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
486 486
 
487 487
 
488 488
 
@@ -514,7 +514,7 @@  discard block
 block discarded – undo
514 514
             Conf::$global->MAIN_THEME = Conf::$global->MAIN_FORCETHEME;
515 515
         $this->theme = Conf::$global->MAIN_THEME;
516 516
         //$this->css  = "/theme/".$this->theme."/style.css.php";
517
-        $this->css = '?controller=theme/' . $this->theme . '&method=style.css';
517
+        $this->css = '?controller=theme/'.$this->theme.'&method=style.css';
518 518
 
519 519
         // conf->email_from = email pour envoi par dolibarr des mails automatiques
520 520
         $this->email_from = "[email protected]";
@@ -534,8 +534,8 @@  discard block
 block discarded – undo
534 534
             Conf::$global->MAIN_EMAIL_ADD_TRACK_ID = 1;
535 535
 
536 536
         // Format for date (used by default when not found or not searched in lang)
537
-        $this->format_date_short = "%d/%m/%Y";            // Format of day with PHP/C tags (strftime functions)
538
-        $this->format_date_short_java = "dd/MM/yyyy";     // Format of day with Java tags
537
+        $this->format_date_short = "%d/%m/%Y"; // Format of day with PHP/C tags (strftime functions)
538
+        $this->format_date_short_java = "dd/MM/yyyy"; // Format of day with Java tags
539 539
         $this->format_hour_short = "%H:%M";
540 540
         $this->format_hour_short_duration = "%H:%M";
541 541
         $this->format_date_text_short = "%d %b %Y";
@@ -559,9 +559,9 @@  discard block
 block discarded – undo
559 559
 
560 560
         // Default pdf option
561 561
         if (!isset(Globals::$conf->$global->MAIN_PDF_DASH_BETWEEN_LINES))
562
-            Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1;    // use dash between lines
562
+            Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1; // use dash between lines
563 563
         if (!isset(Globals::$conf->$global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
564
-            Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1;  // allow html content into free footer text
564
+            Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1; // allow html content into free footer text
565 565
 
566 566
 
567 567
 
@@ -578,7 +578,7 @@  discard block
 block discarded – undo
578 578
 
579 579
         // By default, we propagate contacts
580 580
         if (!isset(Globals::$conf->$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
581
-            Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*';  // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
581
+            Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*'; // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
582 582
 
583 583
 
584 584
 
@@ -603,7 +603,7 @@  discard block
 block discarded – undo
603 603
             Conf::$global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later.
604 604
         if (!empty($this->modules_parts['moduleforexternal'])) {  // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list
605 605
             foreach ($this->modules_parts['moduleforexternal'] as $key => $value)
606
-                Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= "," . $key;
606
+                Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= ",".$key;
607 607
         }
608 608
 
609 609
         // Enable select2
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 
697 697
         // Save inconsistent option
698 698
         if (empty(Globals::$conf->$global->AGENDA_USE_EVENT_TYPE) && (!isset(Globals::$conf->$global->AGENDA_DEFAULT_FILTER_TYPE) || Conf::$global->AGENDA_DEFAULT_FILTER_TYPE == 'AC_NON_AUTO')) {
699
-            Conf::$global->AGENDA_DEFAULT_FILTER_TYPE = '0';    // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on.
699
+            Conf::$global->AGENDA_DEFAULT_FILTER_TYPE = '0'; // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on.
700 700
         }
701 701
 
702 702
         if (!isset(Globals::$conf->$global->MAIN_EXTRAFIELDS_IN_ONE_TD))
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
                 $dir = dol_buildpath($reldir, 0);
739 739
                 $newdir = dol_osencode($dir);
740 740
                 if (is_dir($newdir)) {
741
-                    $file = $newdir . $handler . '.php';
741
+                    $file = $newdir.$handler.'.php';
742 742
                     if (file_exists($file)) {
743 743
                         $handler_files[] = $file;
744 744
                     }
@@ -746,7 +746,7 @@  discard block
 block discarded – undo
746 746
             }
747 747
 
748 748
             if (empty($handler_files)) {
749
-                throw new Exception('Missing log handler file ' . $handler . '.php');
749
+                throw new Exception('Missing log handler file '.$handler.'.php');
750 750
             }
751 751
 
752 752
             require_once $handler_files[0];
Please login to merge, or discard this patch.
Base/Categorie.php 1 patch
Spacing   +292 added lines, -292 removed lines patch added patch discarded remove patch
@@ -108,7 +108,7 @@  discard block
 block discarded – undo
108 108
 		'member'   => 'member',
109 109
 		'contact'  => 'socpeople',
110 110
 		'user'     => 'user',
111
-        'account'  => 'account',		// old for bank_account
111
+        'account'  => 'account', // old for bank_account
112 112
         'bank_account' => 'account',
113 113
         'project'  => 'project',
114 114
 	);
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 		'member'   => 'member',
126 126
 		'contact'  => 'contact',
127 127
 		'user'     => 'user',
128
-        'account'  => 'account',		// old for bank_account
128
+        'account'  => 'account', // old for bank_account
129 129
         'bank_account'=> 'account',
130 130
         'project'  => 'project',
131 131
 	);
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 		'member'   => 'Adherent',
143 143
 		'contact'  => 'Contact',
144 144
 		'user'     => 'User',
145
-		'account'  => 'Account',		// old for bank account
145
+		'account'  => 'Account', // old for bank account
146 146
 		'bank_account'  => 'Account',
147 147
         'project'  => 'Project',
148 148
 	);
@@ -166,12 +166,12 @@  discard block
 block discarded – undo
166 166
 	/**
167 167
 	 * @var string ID to identify managed object
168 168
 	 */
169
-	public $element='category';
169
+	public $element = 'category';
170 170
 
171 171
 	/**
172 172
 	 * @var string Name of table without prefix where object is stored
173 173
 	 */
174
-	public $table_element='categorie';
174
+	public $table_element = 'categorie';
175 175
 
176 176
 	/**
177 177
      * @var int ID
@@ -238,24 +238,24 @@  discard block
 block discarded – undo
238 238
 	 *  @param		string	$type	Type of category ('product', '...') or (0, 1, ...)
239 239
 	 * 	@return		int				<0 if KO, >0 if OK
240 240
 	 */
241
-	function fetch($id, $label='', $type=null)
241
+	function fetch($id, $label = '', $type = null)
242 242
 	{
243 243
 		global $conf;
244 244
 
245 245
 		// Check parameters
246 246
 		if (empty($id) && empty($label)) return -1;
247
-		if (! is_numeric($type)) $type=$this->MAP_ID[$type];
247
+		if (!is_numeric($type)) $type = $this->MAP_ID[$type];
248 248
 
249 249
 		$sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type";
250
-		$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
250
+		$sql .= " FROM ".MAIN_DB_PREFIX."categorie";
251 251
 		if ($id > 0)
252 252
 		{
253
-			$sql.= " WHERE rowid = ".$id;
253
+			$sql .= " WHERE rowid = ".$id;
254 254
 		}
255 255
 		else
256 256
 		{
257
-			$sql.= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
258
-			if (! is_null($type)) $sql.= " AND type = ".$this->db->escape($type);
257
+			$sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")";
258
+			if (!is_null($type)) $sql .= " AND type = ".$this->db->escape($type);
259 259
 		}
260 260
 
261 261
 		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
@@ -266,16 +266,16 @@  discard block
 block discarded – undo
266 266
 			{
267 267
 				$res = $this->db->fetch_array($resql);
268 268
 
269
-				$this->id			= $res['rowid'];
269
+				$this->id = $res['rowid'];
270 270
 				//$this->ref			= $res['rowid'];
271 271
 				$this->fk_parent	= $res['fk_parent'];
272 272
 				$this->label		= $res['label'];
273
-				$this->description	= $res['description'];
273
+				$this->description = $res['description'];
274 274
 				$this->color    	= $res['color'];
275 275
 				$this->socid		= $res['fk_soc'];
276
-				$this->visible		= $res['visible'];
276
+				$this->visible = $res['visible'];
277 277
 				$this->type			= $res['type'];
278
-				$this->entity		= $res['entity'];
278
+				$this->entity = $res['entity'];
279 279
 
280 280
 				// Retreive all extrafield
281 281
 				// fetch optionals attributes and labels
@@ -312,14 +312,14 @@  discard block
 block discarded – undo
312 312
 	 */
313 313
 	function create($user)
314 314
 	{
315
-		global $conf,$langs,$hookmanager;
315
+		global $conf, $langs, $hookmanager;
316 316
 		$langs->load('categories');
317 317
 
318
-		$type=$this->type;
318
+		$type = $this->type;
319 319
 
320
-		if (! is_numeric($type)) $type=$this->MAP_ID[$type];
320
+		if (!is_numeric($type)) $type = $this->MAP_ID[$type];
321 321
 
322
-		$error=0;
322
+		$error = 0;
323 323
 
324 324
 		dol_syslog(get_class($this).'::create', LOG_DEBUG);
325 325
 
@@ -328,13 +328,13 @@  discard block
 block discarded – undo
328 328
 		$this->description = trim($this->description);
329 329
 		$this->color = trim($this->color);
330 330
 		$this->import_key = trim($this->import_key);
331
-		if (empty($this->visible)) $this->visible=0;
331
+		if (empty($this->visible)) $this->visible = 0;
332 332
 		$this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
333 333
 
334 334
 		if ($this->already_exists())
335 335
 		{
336
-			$this->error=$langs->trans("ImpossibleAddCat", $this->label);
337
-			$this->error.=" : ".$langs->trans("CategoryExistsAtSameLevel");
336
+			$this->error = $langs->trans("ImpossibleAddCat", $this->label);
337
+			$this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
338 338
 			dol_syslog($this->error, LOG_WARNING);
339 339
 			return -4;
340 340
 		}
@@ -342,30 +342,30 @@  discard block
 block discarded – undo
342 342
 		$this->db->begin();
343 343
 
344 344
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (";
345
-		$sql.= "fk_parent,";
346
-		$sql.= " label,";
347
-		$sql.= " description,";
348
-		$sql.= " color,";
345
+		$sql .= "fk_parent,";
346
+		$sql .= " label,";
347
+		$sql .= " description,";
348
+		$sql .= " color,";
349 349
 		if (!empty(Globals::$conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) {
350
-			$sql.= "fk_soc,";
350
+			$sql .= "fk_soc,";
351 351
 		}
352
-		$sql.= " visible,";
353
-		$sql.= " type,";
354
-		$sql.= " import_key,";
355
-		$sql.= " entity";
356
-		$sql.= ") VALUES (";
357
-		$sql.= $this->db->escape($this->fk_parent).",";
358
-		$sql.= "'".$this->db->escape($this->label)."',";
359
-		$sql.= "'".$this->db->escape($this->description)."',";
360
-		$sql.= "'".$this->db->escape($this->color)."',";
352
+		$sql .= " visible,";
353
+		$sql .= " type,";
354
+		$sql .= " import_key,";
355
+		$sql .= " entity";
356
+		$sql .= ") VALUES (";
357
+		$sql .= $this->db->escape($this->fk_parent).",";
358
+		$sql .= "'".$this->db->escape($this->label)."',";
359
+		$sql .= "'".$this->db->escape($this->description)."',";
360
+		$sql .= "'".$this->db->escape($this->color)."',";
361 361
 		if (!empty(Globals::$conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) {
362
-			$sql.= ($this->socid != -1 ? $this->socid : 'null').",";
362
+			$sql .= ($this->socid != -1 ? $this->socid : 'null').",";
363 363
 		}
364
-		$sql.= "'".$this->db->escape($this->visible)."',";
365
-		$sql.= $this->db->escape($type).",";
366
-		$sql.= (! empty($this->import_key)?"'".$this->db->escape($this->import_key)."'":'null').",";
364
+		$sql .= "'".$this->db->escape($this->visible)."',";
365
+		$sql .= $this->db->escape($type).",";
366
+		$sql .= (!empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : 'null').",";
367 367
 		$sql .= $this->db->escape(Globals::$conf->entity);
368
-        $sql.= ")";
368
+        $sql .= ")";
369 369
 
370 370
 		$res = $this->db->query($sql);
371 371
 		if ($res)
@@ -376,26 +376,26 @@  discard block
 block discarded – undo
376 376
 			{
377 377
 				$this->id = $id;
378 378
 
379
-				$action='create';
379
+				$action = 'create';
380 380
 
381 381
 				// Actions on extra fields
382 382
 				if (empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used{
383
-					$result=$this->insertExtraFields();
383
+					$result = $this->insertExtraFields();
384 384
 					if ($result < 0)
385 385
 					{
386 386
 						$error++;
387 387
 					}
388 388
 				}
389 389
 
390
-				if (! $error)
390
+				if (!$error)
391 391
 				{
392 392
 	                // Call trigger
393
-    	            $result=$this->call_trigger('CATEGORY_CREATE',$user);
393
+    	            $result = $this->call_trigger('CATEGORY_CREATE', $user);
394 394
         	        if ($result < 0) { $error++; }
395 395
             	    // End call triggers
396 396
 				}
397 397
 
398
-                if ( ! $error )
398
+                if (!$error)
399 399
                 {
400 400
     				$this->db->commit();
401 401
     				return $id;
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
 		}
415 415
 		else
416 416
 		{
417
-			$this->error=$this->db->error();
417
+			$this->error = $this->db->error();
418 418
 			$this->db->rollback();
419 419
 			return -1;
420 420
 		}
@@ -430,29 +430,29 @@  discard block
 block discarded – undo
430 430
 	 */
431 431
 	function update(User $user)
432 432
 	{
433
-		global $conf, $langs,$hookmanager;
433
+		global $conf, $langs, $hookmanager;
434 434
 
435
-		$error=0;
435
+		$error = 0;
436 436
 
437 437
 		// Clean parameters
438
-		$this->label=trim($this->label);
439
-		$this->description=trim($this->description);
438
+		$this->label = trim($this->label);
439
+		$this->description = trim($this->description);
440 440
 		$this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
441 441
 		$this->visible = ($this->visible != "" ? intval($this->visible) : 0);
442 442
 
443 443
 		if ($this->already_exists())
444 444
 		{
445
-			$this->error=$langs->trans("ImpossibleUpdateCat");
446
-			$this->error.=" : ".$langs->trans("CategoryExistsAtSameLevel");
445
+			$this->error = $langs->trans("ImpossibleUpdateCat");
446
+			$this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
447 447
 			return -1;
448 448
 		}
449 449
 
450 450
 		$this->db->begin();
451 451
 
452 452
 		$sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
453
-		$sql.= " SET label = '".$this->db->escape($this->label)."',";
454
-		$sql.= " description = '".$this->db->escape($this->description)."',";
455
-		$sql.= " color = '".$this->db->escape($this->color)."'";
453
+		$sql .= " SET label = '".$this->db->escape($this->label)."',";
454
+		$sql .= " description = '".$this->db->escape($this->description)."',";
455
+		$sql .= " color = '".$this->db->escape($this->color)."'";
456 456
 		if (!empty(Globals::$conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) {
457 457
 			$sql .= ", fk_soc = ".($this->socid != -1 ? $this->socid : 'null');
458 458
 		}
@@ -463,21 +463,21 @@  discard block
 block discarded – undo
463 463
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
464 464
 		if ($this->db->query($sql))
465 465
 		{
466
-			$action='update';
466
+			$action = 'update';
467 467
 
468 468
 			// Actions on extra fields
469 469
 			if (empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used{
470
-				$result=$this->insertExtraFields();
470
+				$result = $this->insertExtraFields();
471 471
 				if ($result < 0)
472 472
 				{
473 473
 					$error++;
474 474
 				}
475 475
 			}
476 476
 
477
-			if (! $error)
477
+			if (!$error)
478 478
 			{
479 479
 	            // Call trigger
480
-    	        $result=$this->call_trigger('CATEGORY_MODIFY',$user);
480
+    	        $result = $this->call_trigger('CATEGORY_MODIFY', $user);
481 481
         	    if ($result < 0) { $error++; $this->db->rollback(); return -1; }
482 482
             	// End call triggers
483 483
 			}
@@ -501,11 +501,11 @@  discard block
 block discarded – undo
501 501
      *	@param	int		$notrigger	1=Does not execute triggers, 0= execute triggers
502 502
 	 *	@return	int                 <0 KO >0 OK
503 503
 	 */
504
-	function delete($user, $notrigger=0)
504
+	function delete($user, $notrigger = 0)
505 505
 	{
506
-		global $conf,$langs;
506
+		global $conf, $langs;
507 507
 
508
-		$error=0;
508
+		$error = 0;
509 509
 
510 510
         // Clean parameters
511 511
 		$this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
@@ -514,24 +514,24 @@  discard block
 block discarded – undo
514 514
 
515 515
 		$this->db->begin();
516 516
 
517
-		if (! $error && ! $notrigger)
517
+		if (!$error && !$notrigger)
518 518
 		{
519 519
 		    // Call trigger
520
-		    $result=$this->call_trigger('CATEGORY_DELETE',$user);
520
+		    $result = $this->call_trigger('CATEGORY_DELETE', $user);
521 521
 		    if ($result < 0) $error++;
522 522
 		    // End call triggers
523 523
 		}
524 524
 
525 525
 		/* FIX #1317 : Check for child category and move up 1 level*/
526
-		if (! $error)
526
+		if (!$error)
527 527
 		{
528 528
 			$sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
529
-			$sql.= " SET fk_parent = ".$this->fk_parent;
530
-			$sql.= " WHERE fk_parent = ".$this->id;
529
+			$sql .= " SET fk_parent = ".$this->fk_parent;
530
+			$sql .= " WHERE fk_parent = ".$this->id;
531 531
 
532 532
 			if (!$this->db->query($sql))
533 533
 			{
534
-				$this->error=$this->db->lasterror();
534
+				$this->error = $this->db->lasterror();
535 535
 				$error++;
536 536
 			}
537 537
 		}
@@ -548,7 +548,7 @@  discard block
 block discarded – undo
548 548
             'categorie' => 'rowid',
549 549
         );
550 550
         foreach ($arraydelete as $key => $value) {
551
-            $sql  = "DELETE FROM " . MAIN_DB_PREFIX . $key;
551
+            $sql  = "DELETE FROM ".MAIN_DB_PREFIX.$key;
552 552
             $sql .= " WHERE ".$value." = ".$this->id;
553 553
             if (!$this->db->query($sql)) {
554 554
                 $this->errors[] = $this->db->lasterror();
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
 
560 560
 		// Removed extrafields
561 561
 		if (!$error && empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED)) { // For avoid conflicts if trigger used{
562
-			$result=$this->deleteExtraFields();
562
+			$result = $this->deleteExtraFields();
563 563
 			if ($result < 0)
564 564
 			{
565 565
 				$error++;
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 			}
568 568
 		}
569 569
 
570
-		if (! $error)
570
+		if (!$error)
571 571
 		{
572 572
 			$this->db->commit();
573 573
 			return 1;
@@ -590,27 +590,27 @@  discard block
 block discarded – undo
590 590
 	function add_type($obj, $type)
591 591
 	{
592 592
         // phpcs:enable
593
-		global $user,$langs,$conf;
593
+		global $user, $langs, $conf;
594 594
 
595
-		$error=0;
595
+		$error = 0;
596 596
 
597 597
 		if ($this->id == -1) return -2;
598 598
 
599 599
         $this->db->begin();
600 600
 
601
-		$sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
602
-		$sql .= " (fk_categorie, fk_" . $this->MAP_CAT_FK[$type] . ")";
603
-		$sql .= " VALUES (" . $this->id . ", " . $obj->id . ")";
601
+		$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
602
+		$sql .= " (fk_categorie, fk_".$this->MAP_CAT_FK[$type].")";
603
+		$sql .= " VALUES (".$this->id.", ".$obj->id.")";
604 604
 
605 605
 		dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
606 606
 		if ($this->db->query($sql))
607 607
 		{
608 608
 			if (!empty(Globals::$conf->global->CATEGORIE_RECURSIV_ADD)) {
609 609
 				$sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
610
-				$sql.= " WHERE rowid = ".$this->id;
610
+				$sql .= " WHERE rowid = ".$this->id;
611 611
 
612 612
 				dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
613
-				$resql=$this->db->query($sql);
613
+				$resql = $this->db->query($sql);
614 614
 				if ($resql)
615 615
 				{
616 616
 					if ($this->db->num_rows($resql) > 0)
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 				else
636 636
 				{
637 637
 					$error++;
638
-					$this->error=$this->db->lasterror();
638
+					$this->error = $this->db->lasterror();
639 639
 				}
640 640
 
641 641
 				if ($error)
@@ -648,12 +648,12 @@  discard block
 block discarded – undo
648 648
 
649 649
 
650 650
             // Call trigger
651
-			$this->context=array('linkto'=>$obj);	// Save object we want to link category to into category instance to provide information to trigger
652
-			$result=$this->call_trigger('CATEGORY_LINK',$user);
651
+			$this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
652
+			$result = $this->call_trigger('CATEGORY_LINK', $user);
653 653
             if ($result < 0) { $error++; }
654 654
             // End call triggers
655 655
 
656
-			if (! $error)
656
+			if (!$error)
657 657
 			{
658 658
 			    $this->db->commit();
659 659
 			    return 1;
@@ -669,12 +669,12 @@  discard block
 block discarded – undo
669 669
 		    $this->db->rollback();
670 670
 			if ($this->db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
671 671
 			{
672
-				$this->error=$this->db->lasterrno();
672
+				$this->error = $this->db->lasterrno();
673 673
 				return -3;
674 674
 			}
675 675
 			else
676 676
 			{
677
-				$this->error=$this->db->lasterror();
677
+				$this->error = $this->db->lasterror();
678 678
 			}
679 679
 			return -1;
680 680
 		}
@@ -689,38 +689,38 @@  discard block
 block discarded – undo
689 689
 	 *
690 690
 	 * @return  int          1 if OK, -1 if KO
691 691
 	 */
692
-	function del_type($obj,$type)
692
+	function del_type($obj, $type)
693 693
 	{
694 694
         // phpcs:enable
695
-		global $user,$langs,$conf;
695
+		global $user, $langs, $conf;
696 696
 
697
-		$error=0;
697
+		$error = 0;
698 698
 
699 699
 		// For backward compatibility
700 700
 		if ($type == 'societe') {
701 701
 			$type = 'customer';
702
-			dol_syslog( get_class( $this ) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
702
+			dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
703 703
 		} elseif ($type == 'fournisseur') {
704 704
 			$type = 'supplier';
705
-			dol_syslog( get_class( $this ) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
705
+			dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
706 706
 		}
707 707
 
708 708
         $this->db->begin();
709 709
 
710
-		$sql = "DELETE FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
711
-		$sql .= " WHERE fk_categorie = " . $this->id;
712
-		$sql .= " AND   fk_" . $this->MAP_CAT_FK[$type] . "  = " . $obj->id;
710
+		$sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
711
+		$sql .= " WHERE fk_categorie = ".$this->id;
712
+		$sql .= " AND   fk_".$this->MAP_CAT_FK[$type]."  = ".$obj->id;
713 713
 
714 714
 		dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
715 715
 		if ($this->db->query($sql))
716 716
 		{
717 717
             // Call trigger
718
-			$this->context=array('unlinkoff'=>$obj);	// Save object we want to link category to into category instance to provide information to trigger
719
-			$result=$this->call_trigger('CATEGORY_UNLINK',$user);
718
+			$this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger
719
+			$result = $this->call_trigger('CATEGORY_UNLINK', $user);
720 720
             if ($result < 0) { $error++; }
721 721
             // End call triggers
722 722
 
723
-			if (! $error)
723
+			if (!$error)
724 724
 			{
725 725
 			    $this->db->commit();
726 726
 			    return 1;
@@ -734,7 +734,7 @@  discard block
 block discarded – undo
734 734
 		else
735 735
 		{
736 736
 		    $this->db->rollback();
737
-			$this->error=$this->db->lasterror();
737
+			$this->error = $this->db->lasterror();
738 738
 			return -1;
739 739
 		}
740 740
 	}
@@ -747,18 +747,18 @@  discard block
 block discarded – undo
747 747
 	 * @return  array|int              -1 if KO, array of instance of object if OK
748 748
 	 * @see containsObject
749 749
 	 */
750
-	function getObjectsInCateg($type, $onlyids=0)
750
+	function getObjectsInCateg($type, $onlyids = 0)
751 751
 	{
752 752
 		$objs = array();
753 753
 
754
-		$obj = new $this->MAP_OBJ_CLASS[$type]( $this->db );
754
+		$obj = new $this->MAP_OBJ_CLASS[$type]($this->db);
755 755
 
756
-		$sql = "SELECT c.fk_" . $this->MAP_CAT_FK[$type];
757
-		$sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as c";
758
-		$sql .= ", " . MAIN_DB_PREFIX . $this->MAP_OBJ_TABLE[$type] . " as o";
759
-		$sql .= " WHERE o.entity IN (" . getEntity( $obj->element).")";
760
-		$sql.= " AND c.fk_categorie = ".$this->id;
761
-		$sql .= " AND c.fk_" . $this->MAP_CAT_FK[$type] . " = o.rowid";
756
+		$sql = "SELECT c.fk_".$this->MAP_CAT_FK[$type];
757
+		$sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as c";
758
+		$sql .= ", ".MAIN_DB_PREFIX.$this->MAP_OBJ_TABLE[$type]." as o";
759
+		$sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
760
+		$sql .= " AND c.fk_categorie = ".$this->id;
761
+		$sql .= " AND c.fk_".$this->MAP_CAT_FK[$type]." = o.rowid";
762 762
 
763 763
 		dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
764 764
 		$resql = $this->db->query($sql);
@@ -768,12 +768,12 @@  discard block
 block discarded – undo
768 768
 			{
769 769
 			    if ($onlyids)
770 770
 			    {
771
-			        $objs[] = $rec['fk_' . $this->MAP_CAT_FK[$type]];
771
+			        $objs[] = $rec['fk_'.$this->MAP_CAT_FK[$type]];
772 772
 			    }
773 773
 			    else
774 774
 			    {
775
-				    $obj = new $this->MAP_OBJ_CLASS[$type]( $this->db );
776
-				    $obj->fetch( $rec['fk_' . $this->MAP_CAT_FK[$type]]);
775
+				    $obj = new $this->MAP_OBJ_CLASS[$type]($this->db);
776
+				    $obj->fetch($rec['fk_'.$this->MAP_CAT_FK[$type]]);
777 777
 				    $objs[] = $obj;
778 778
 			    }
779 779
 			}
@@ -781,7 +781,7 @@  discard block
 block discarded – undo
781 781
 		}
782 782
 		else
783 783
 		{
784
-			$this->error=$this->db->error().' sql='.$sql;
784
+			$this->error = $this->db->error().' sql='.$sql;
785 785
 			return -1;
786 786
 		}
787 787
 	}
@@ -796,14 +796,14 @@  discard block
 block discarded – undo
796 796
 	 */
797 797
 	function containsObject($type, $object_id)
798 798
 	{
799
-		$sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
800
-		$sql .= " WHERE fk_categorie = " . $this->id . " AND fk_" . $this->MAP_CAT_FK[$type] . " = " . $object_id;
799
+		$sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
800
+		$sql .= " WHERE fk_categorie = ".$this->id." AND fk_".$this->MAP_CAT_FK[$type]." = ".$object_id;
801 801
 		dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
802 802
 		$resql = $this->db->query($sql);
803 803
 		if ($resql) {
804 804
 			return $this->db->fetch_object($resql)->nb;
805 805
 		} else {
806
-			$this->error=$this->db->error().' sql='.$sql;
806
+			$this->error = $this->db->error().' sql='.$sql;
807 807
 			return -1;
808 808
 		}
809 809
 	}
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
 	 * @param	int		$page		Page number
820 820
 	 * @return	array|int			Array of categories, 0 if no cat, -1 on error
821 821
 	 */
822
-	function getListForItem($id, $type='customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
822
+	function getListForItem($id, $type = 'customer', $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
823 823
 	{
824 824
 		global $conf;
825 825
 
@@ -827,26 +827,26 @@  discard block
 block discarded – undo
827 827
 
828 828
 		$sub_type = $type;
829 829
 		$subcol_name = "fk_".$type;
830
-		if ($type=="customer") {
831
-			$sub_type="societe";
832
-			$subcol_name="fk_soc";
830
+		if ($type == "customer") {
831
+			$sub_type = "societe";
832
+			$subcol_name = "fk_soc";
833 833
 		}
834
-		if ($type=="supplier") {
835
-			$sub_type="fournisseur";
836
-			$subcol_name="fk_soc";
834
+		if ($type == "supplier") {
835
+			$sub_type = "fournisseur";
836
+			$subcol_name = "fk_soc";
837 837
 		}
838
-		if ($type=="contact") {
839
-			$subcol_name="fk_socpeople";
838
+		if ($type == "contact") {
839
+			$subcol_name = "fk_socpeople";
840 840
 		}
841 841
 		$sql = "SELECT s.rowid";
842
-		$sql.= " FROM ".MAIN_DB_PREFIX."categorie as s";
843
-		$sql.= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub ";
844
-		$sql.= ' WHERE s.entity IN ('.getEntity('category').')';
845
-		$sql.= ' AND s.type='.array_search($type, self::$MAP_ID_TO_CODE);
846
-		$sql.= ' AND s.rowid = sub.fk_categorie';
847
-		$sql.= ' AND sub.'.$subcol_name.' = '.$id;
842
+		$sql .= " FROM ".MAIN_DB_PREFIX."categorie as s";
843
+		$sql .= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub ";
844
+		$sql .= ' WHERE s.entity IN ('.getEntity('category').')';
845
+		$sql .= ' AND s.type='.array_search($type, self::$MAP_ID_TO_CODE);
846
+		$sql .= ' AND s.rowid = sub.fk_categorie';
847
+		$sql .= ' AND sub.'.$subcol_name.' = '.$id;
848 848
 
849
-		$sql.= $this->db->order($sortfield, $sortorder);
849
+		$sql .= $this->db->order($sortfield, $sortorder);
850 850
 
851 851
 		$offset = 0;
852 852
 		$nbtotalofrecords = '';
@@ -860,12 +860,12 @@  discard block
 block discarded – undo
860 860
 			}
861 861
 		}
862 862
 
863
-		$sql.= $this->db->plimit($limit + 1, $offset);
863
+		$sql .= $this->db->plimit($limit + 1, $offset);
864 864
 
865 865
 		$result = $this->db->query($sql);
866 866
 		if ($result)
867 867
 		{
868
-			$i=0;
868
+			$i = 0;
869 869
 			$num = $this->db->num_rows($result);
870 870
 			$min = min($num, ($limit <= 0 ? $num : $limit));
871 871
 			while ($i < $min)
@@ -874,20 +874,20 @@  discard block
 block discarded – undo
874 874
 				$category_static = new Categorie($this->db);
875 875
 				if ($category_static->fetch($obj->rowid))
876 876
 				{
877
-					$categories[$i]['id'] 				= $category_static->id;
877
+					$categories[$i]['id'] = $category_static->id;
878 878
 					$categories[$i]['fk_parent']		= $category_static->fk_parent;
879 879
 					$categories[$i]['label']			= $category_static->label;
880
-					$categories[$i]['description']		= $category_static->description;
880
+					$categories[$i]['description'] = $category_static->description;
881 881
 					$categories[$i]['color']    		= $category_static->color;
882 882
 					$categories[$i]['socid']			= $category_static->socid;
883
-					$categories[$i]['visible']			= $category_static->visible;
884
-					$categories[$i]['type']			= $category_static->type;
885
-					$categories[$i]['entity']			= $category_static->entity;
886
-					$categories[$i]['array_options']	= $category_static->array_options;
883
+					$categories[$i]['visible'] = $category_static->visible;
884
+					$categories[$i]['type'] = $category_static->type;
885
+					$categories[$i]['entity'] = $category_static->entity;
886
+					$categories[$i]['array_options'] = $category_static->array_options;
887 887
 
888 888
 					// multilangs
889 889
 					if (!empty(Globals::$conf->global->MAIN_MULTILANGS)) {
890
-                        $categories[$i]['multilangs']	= $category_static->multilangs;
890
+                        $categories[$i]['multilangs'] = $category_static->multilangs;
891 891
 					}
892 892
 				}
893 893
 				$i++;
@@ -897,7 +897,7 @@  discard block
 block discarded – undo
897 897
 			$this->error = $this->db->lasterror();
898 898
 			return -1;
899 899
 		}
900
-		if ( ! count($categories)) {
900
+		if (!count($categories)) {
901 901
 			return 0;
902 902
 		}
903 903
 
@@ -914,12 +914,12 @@  discard block
 block discarded – undo
914 914
 	{
915 915
         // phpcs:enable
916 916
 		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
917
-		$sql.= " WHERE fk_parent = ".$this->id;
917
+		$sql .= " WHERE fk_parent = ".$this->id;
918 918
 
919
-		$res  = $this->db->query($sql);
919
+		$res = $this->db->query($sql);
920 920
 		if ($res)
921 921
 		{
922
-			$cats = array ();
922
+			$cats = array();
923 923
 			while ($rec = $this->db->fetch_array($res))
924 924
 			{
925 925
 				$cat = new Categorie($this->db);
@@ -946,21 +946,21 @@  discard block
 block discarded – undo
946 946
         // phpcs:enable
947 947
 		global $conf;
948 948
 
949
-		$this->motherof=array();
949
+		$this->motherof = array();
950 950
 
951 951
 		// Load array[child]=parent
952 952
 		$sql = "SELECT fk_parent as id_parent, rowid as id_son";
953
-		$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
954
-		$sql.= " WHERE fk_parent != 0";
955
-		$sql.= " AND entity IN (".getEntity('category').")";
953
+		$sql .= " FROM ".MAIN_DB_PREFIX."categorie";
954
+		$sql .= " WHERE fk_parent != 0";
955
+		$sql .= " AND entity IN (".getEntity('category').")";
956 956
 
957 957
 		dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
958 958
 		$resql = $this->db->query($sql);
959 959
 		if ($resql)
960 960
 		{
961
-			while ($obj= $this->db->fetch_object($resql))
961
+			while ($obj = $this->db->fetch_object($resql))
962 962
 			{
963
-				$this->motherof[$obj->id_son]=$obj->id_parent;
963
+				$this->motherof[$obj->id_son] = $obj->id_parent;
964 964
 			}
965 965
 			return 1;
966 966
 		}
@@ -987,12 +987,12 @@  discard block
 block discarded – undo
987 987
 	 *
988 988
 	 * @return  array|int               Array of categories. this->cats and this->motherof are set, -1 on error
989 989
 	 */
990
-	function get_full_arbo($type, $markafterid=0)
990
+	function get_full_arbo($type, $markafterid = 0)
991 991
 	{
992 992
         // phpcs:enable
993 993
 	    global $conf, $langs;
994 994
 
995
-		if (! is_numeric($type)) $type = $this->MAP_ID[$type];
995
+		if (!is_numeric($type)) $type = $this->MAP_ID[$type];
996 996
 
997 997
 		$this->cats = array();
998 998
 
@@ -1001,27 +1001,27 @@  discard block
 block discarded – undo
1001 1001
 		$current_lang = $langs->getDefaultLang();
1002 1002
 
1003 1003
 		// Init $this->cats array
1004
-		$sql = "SELECT DISTINCT c.rowid, c.label, c.description, c.color, c.fk_parent, c.visible";	// Distinct reduce pb with old tables with duplicates
1004
+		$sql = "SELECT DISTINCT c.rowid, c.label, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates
1005 1005
 		if (!empty(Globals::$conf->global->MAIN_MULTILANGS))
1006 1006
             $sql .= ", t.label as label_trans, t.description as description_trans";
1007
-        $sql.= " FROM ".MAIN_DB_PREFIX."categorie as c";
1007
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
1008 1008
 		if (!empty(Globals::$conf->global->MAIN_MULTILANGS))
1009
-            $sql .= " LEFT  JOIN " . MAIN_DB_PREFIX . "categorie_lang as t ON t.fk_category=c.rowid AND t.lang='" . $current_lang . "'";
1010
-        $sql .= " WHERE c.entity IN (" . getEntity( 'category') . ")";
1011
-		$sql .= " AND c.type = " . $type;
1009
+            $sql .= " LEFT  JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$current_lang."'";
1010
+        $sql .= " WHERE c.entity IN (".getEntity('category').")";
1011
+		$sql .= " AND c.type = ".$type;
1012 1012
 
1013 1013
 		dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
1014 1014
 		$resql = $this->db->query($sql);
1015 1015
 		if ($resql)
1016 1016
 		{
1017
-			$i=0;
1017
+			$i = 0;
1018 1018
 			while ($obj = $this->db->fetch_object($resql))
1019 1019
 			{
1020 1020
 				$this->cats[$obj->rowid]['rowid'] = $obj->rowid;
1021 1021
 				$this->cats[$obj->rowid]['id'] = $obj->rowid;
1022 1022
 				$this->cats[$obj->rowid]['fk_parent'] = $obj->fk_parent;
1023
-				$this->cats[$obj->rowid]['label'] = ! empty($obj->label_trans) ? $obj->label_trans : $obj->label;
1024
-				$this->cats[$obj->rowid]['description'] = ! empty($obj->description_trans) ? $obj->description_trans : $obj->description;
1023
+				$this->cats[$obj->rowid]['label'] = !empty($obj->label_trans) ? $obj->label_trans : $obj->label;
1024
+				$this->cats[$obj->rowid]['description'] = !empty($obj->description_trans) ? $obj->description_trans : $obj->description;
1025 1025
 				$this->cats[$obj->rowid]['color'] = $obj->color;
1026 1026
 				$this->cats[$obj->rowid]['visible'] = $obj->visible;
1027 1027
 				$i++;
@@ -1035,24 +1035,24 @@  discard block
 block discarded – undo
1035 1035
 
1036 1036
 		// We add the fullpath property to each elements of first level (no parent exists)
1037 1037
 		dol_syslog(get_class($this)."::get_full_arbo call to build_path_from_id_categ", LOG_DEBUG);
1038
-		foreach($this->cats as $key => $val)
1038
+		foreach ($this->cats as $key => $val)
1039 1039
 		{
1040 1040
 			//print 'key='.$key.'<br>'."\n";
1041
-			$this->build_path_from_id_categ($key,0);	// Process a branch from the root category key (this category has no parent)
1041
+			$this->build_path_from_id_categ($key, 0); // Process a branch from the root category key (this category has no parent)
1042 1042
 		}
1043 1043
 
1044 1044
         // Exclude leaf including $markafterid from tree
1045 1045
         if ($markafterid)
1046 1046
         {
1047 1047
             //print "Look to discard category ".$markafterid."\n";
1048
-            $keyfilter1='^'.$markafterid.'$';
1049
-            $keyfilter2='_'.$markafterid.'$';
1050
-            $keyfilter3='^'.$markafterid.'_';
1051
-            $keyfilter4='_'.$markafterid.'_';
1052
-            foreach($this->cats as $key => $val)
1048
+            $keyfilter1 = '^'.$markafterid.'$';
1049
+            $keyfilter2 = '_'.$markafterid.'$';
1050
+            $keyfilter3 = '^'.$markafterid.'_';
1051
+            $keyfilter4 = '_'.$markafterid.'_';
1052
+            foreach ($this->cats as $key => $val)
1053 1053
             {
1054
-                if (preg_match('/'.$keyfilter1.'/',$val['fullpath']) || preg_match('/'.$keyfilter2.'/',$val['fullpath'])
1055
-                || preg_match('/'.$keyfilter3.'/',$val['fullpath']) || preg_match('/'.$keyfilter4.'/',$val['fullpath']))
1054
+                if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath'])
1055
+                || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath']))
1056 1056
                 {
1057 1057
                     unset($this->cats[$key]);
1058 1058
                 }
@@ -1060,7 +1060,7 @@  discard block
 block discarded – undo
1060 1060
         }
1061 1061
 
1062 1062
 		dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
1063
-		$this->cats=dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
1063
+		$this->cats = dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
1064 1064
 
1065 1065
 		//$this->debug_cats();
1066 1066
 
@@ -1075,12 +1075,12 @@  discard block
 block discarded – undo
1075 1075
 	 * 	@param		int		$protection		Deep counter to avoid infinite loop
1076 1076
 	 *	@return		void
1077 1077
 	 */
1078
-	function build_path_from_id_categ($id_categ,$protection=1000)
1078
+	function build_path_from_id_categ($id_categ, $protection = 1000)
1079 1079
 	{
1080 1080
         // phpcs:enable
1081 1081
 		dol_syslog(get_class($this)."::build_path_from_id_categ id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
1082 1082
 
1083
-		if (! empty($this->cats[$id_categ]['fullpath']))
1083
+		if (!empty($this->cats[$id_categ]['fullpath']))
1084 1084
 		{
1085 1085
 			// Already defined
1086 1086
 			dol_syslog(get_class($this)."::build_path_from_id_categ fullpath and fulllabel already defined", LOG_WARNING);
@@ -1093,20 +1093,20 @@  discard block
 block discarded – undo
1093 1093
 		// Define fullpath and fulllabel
1094 1094
 		$this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
1095 1095
 		$this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
1096
-		$i=0; $cursor_categ=$id_categ;
1096
+		$i = 0; $cursor_categ = $id_categ;
1097 1097
 		//print 'Work for id_categ='.$id_categ.'<br>'."\n";
1098
-		while ((empty($protection) || $i < $protection) && ! empty($this->motherof[$cursor_categ]))
1098
+		while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ]))
1099 1099
 		{
1100 1100
 			//print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
1101 1101
 			$this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
1102 1102
 			$this->cats[$id_categ]['fulllabel'] = $this->cats[$this->motherof[$cursor_categ]]['label'].' >> '.$this->cats[$id_categ]['fulllabel'];
1103 1103
 			//print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
1104
-			$i++; $cursor_categ=$this->motherof[$cursor_categ];
1104
+			$i++; $cursor_categ = $this->motherof[$cursor_categ];
1105 1105
 		}
1106 1106
 		//print 'Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].'<br>'."\n";
1107 1107
 
1108 1108
 		// We count number of _ to have level
1109
-		$this->cats[$id_categ]['level']=dol_strlen(preg_replace('/[^_]/i','',$this->cats[$id_categ]['fullpath']));
1109
+		$this->cats[$id_categ]['level'] = dol_strlen(preg_replace('/[^_]/i', '', $this->cats[$id_categ]['fullpath']));
1110 1110
 
1111 1111
 		return;
1112 1112
 	}
@@ -1121,7 +1121,7 @@  discard block
 block discarded – undo
1121 1121
 	{
1122 1122
         // phpcs:enable
1123 1123
 		// Display $this->cats
1124
-		foreach($this->cats as $key => $val)
1124
+		foreach ($this->cats as $key => $val)
1125 1125
 		{
1126 1126
 			print 'id: '.$this->cats[$key]['id'];
1127 1127
 			print ' label: '.$this->cats[$key]['label'];
@@ -1142,22 +1142,22 @@  discard block
 block discarded – undo
1142 1142
 	 *	@param	boolean		$parent		Just parent categories if true
1143 1143
 	 *	@return	array|int				Table of Object Category, -1 on error
1144 1144
 	 */
1145
-	function get_all_categories($type=null, $parent=false)
1145
+	function get_all_categories($type = null, $parent = false)
1146 1146
 	{
1147 1147
         // phpcs:enable
1148
-		if (! is_numeric($type)) $type = $this->MAP_ID[$type];
1148
+		if (!is_numeric($type)) $type = $this->MAP_ID[$type];
1149 1149
 
1150 1150
 		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1151
-		$sql.= " WHERE entity IN (".getEntity('category').")";
1152
-		if (! is_null($type))
1153
-			$sql.= " AND type = ".$type;
1151
+		$sql .= " WHERE entity IN (".getEntity('category').")";
1152
+		if (!is_null($type))
1153
+			$sql .= " AND type = ".$type;
1154 1154
 		if ($parent)
1155
-			$sql.= " AND fk_parent = 0";
1155
+			$sql .= " AND fk_parent = 0";
1156 1156
 
1157 1157
 		$res = $this->db->query($sql);
1158 1158
 		if ($res)
1159 1159
 		{
1160
-			$cats = array ();
1160
+			$cats = array();
1161 1161
 			while ($rec = $this->db->fetch_array($res))
1162 1162
 			{
1163 1163
 				$cat = new Categorie($this->db);
@@ -1182,19 +1182,19 @@  discard block
 block discarded – undo
1182 1182
 	function already_exists()
1183 1183
 	{
1184 1184
         // phpcs:enable
1185
-		$type=$this->type;
1185
+		$type = $this->type;
1186 1186
 
1187
-		if (! is_numeric($type)) $type=$this->MAP_ID[$type];
1187
+		if (!is_numeric($type)) $type = $this->MAP_ID[$type];
1188 1188
 
1189 1189
 		/* We have to select any rowid from llx_categorie which category's mother and label
1190 1190
 		 * are equals to those of the calling category
1191 1191
 		 */
1192 1192
 		$sql = "SELECT c.rowid";
1193
-		$sql.= " FROM ".MAIN_DB_PREFIX."categorie as c ";
1194
-		$sql.= " WHERE c.entity IN (".getEntity('category').")";
1195
-		$sql.= " AND c.type = ".$type;
1196
-		$sql.= " AND c.fk_parent = ".$this->fk_parent;
1197
-		$sql.= " AND c.label = '".$this->db->escape($this->label)."'";
1193
+		$sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
1194
+		$sql .= " WHERE c.entity IN (".getEntity('category').")";
1195
+		$sql .= " AND c.type = ".$type;
1196
+		$sql .= " AND c.fk_parent = ".$this->fk_parent;
1197
+		$sql .= " AND c.label = '".$this->db->escape($this->label)."'";
1198 1198
 
1199 1199
 		dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
1200 1200
 		$resql = $this->db->query($sql);
@@ -1208,7 +1208,7 @@  discard block
 block discarded – undo
1208 1208
 				 * So if the result have the same id, update is not for label, and if result have an other one,
1209 1209
 				 * update may be for label.
1210 1210
 				 */
1211
-				if($obj[0] > 0 && $obj[0] != $this->id)
1211
+				if ($obj[0] > 0 && $obj[0] != $this->id)
1212 1212
 				{
1213 1213
 					dol_syslog(get_class($this)."::already_exists category with name=".$this->label." and parent ".$this->fk_parent." exists: rowid=".$obj[0]." current_id=".$this->id, LOG_DEBUG);
1214 1214
 					return 1;
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
 		}
1220 1220
 		else
1221 1221
 		{
1222
-			$this->error=$this->db->error();
1222
+			$this->error = $this->db->error();
1223 1223
 			return -1;
1224 1224
 		}
1225 1225
 	}
@@ -1231,7 +1231,7 @@  discard block
 block discarded – undo
1231 1231
 	 *	@param		int		$type		Type of category (0, 1, ...)
1232 1232
 	 *	@return		array
1233 1233
 	 */
1234
-	function get_main_categories($type=null)
1234
+	function get_main_categories($type = null)
1235 1235
 	{
1236 1236
         // phpcs:enable
1237 1237
 		return $this->get_all_categories($type, true);
@@ -1247,7 +1247,7 @@  discard block
 block discarded – undo
1247 1247
 	 * @param   int     $nocolor     0
1248 1248
 	 * @return	array
1249 1249
 	 */
1250
-	function print_all_ways($sep = " &gt;&gt; ", $url='', $nocolor=0)
1250
+	function print_all_ways($sep = " &gt;&gt; ", $url = '', $nocolor = 0)
1251 1251
 	{
1252 1252
         // phpcs:enable
1253 1253
 		$ways = array();
@@ -1257,29 +1257,29 @@  discard block
 block discarded – undo
1257 1257
 		{
1258 1258
 			$w = array();
1259 1259
 			$i = 0;
1260
-			$forced_color='';
1260
+			$forced_color = '';
1261 1261
 			foreach ($way as $cat)
1262 1262
 			{
1263 1263
 			    $i++;
1264 1264
 
1265 1265
 			    if (empty($nocolor))
1266 1266
 			    {
1267
-    			    $forced_color='toreplace';
1267
+    			    $forced_color = 'toreplace';
1268 1268
     			    if ($i == count($way))
1269 1269
     			    {
1270 1270
     			        // Check contrast with background and correct text color
1271
-    			        $forced_color='categtextwhite';
1271
+    			        $forced_color = 'categtextwhite';
1272 1272
     			        if ($cat->color)
1273 1273
     			        {
1274
-    			            if (colorIsLight($cat->color)) $forced_color='categtextblack';
1274
+    			            if (colorIsLight($cat->color)) $forced_color = 'categtextblack';
1275 1275
     			        }
1276 1276
     			    }
1277 1277
 			    }
1278 1278
 
1279 1279
 				if ($url == '')
1280 1280
 				{
1281
-			        $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color .'">';
1282
-			        $linkend='</a>';
1281
+			        $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color.'">';
1282
+			        $linkend = '</a>';
1283 1283
 				    $w[] = $link.$cat->label.$linkend;
1284 1284
 				}
1285 1285
 				else
@@ -1308,9 +1308,9 @@  discard block
 block discarded – undo
1308 1308
 		$parents = array();
1309 1309
 
1310 1310
 		$sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
1311
-		$sql.= " WHERE rowid = ".$this->id;
1311
+		$sql .= " WHERE rowid = ".$this->id;
1312 1312
 
1313
-		$res  = $this->db->query($sql);
1313
+		$res = $this->db->query($sql);
1314 1314
 
1315 1315
 		if ($res)
1316 1316
 		{
@@ -1344,17 +1344,17 @@  discard block
 block discarded – undo
1344 1344
         // phpcs:enable
1345 1345
 		$ways = array();
1346 1346
 
1347
-		$parents=$this->get_meres();
1348
-		if (! empty($parents))
1347
+		$parents = $this->get_meres();
1348
+		if (!empty($parents))
1349 1349
 		{
1350 1350
 			foreach ($parents as $parent)
1351 1351
 			{
1352
-				$allways=$parent->get_all_ways();
1352
+				$allways = $parent->get_all_ways();
1353 1353
 				foreach ($allways as $way)
1354 1354
 				{
1355
-					$w		= $way;
1356
-					$w[]	= $this;
1357
-					$ways[]	= $w;
1355
+					$w = $way;
1356
+					$w[] = $this;
1357
+					$ways[] = $w;
1358 1358
 				}
1359 1359
 			}
1360 1360
 		}
@@ -1375,7 +1375,7 @@  discard block
 block discarded – undo
1375 1375
 	 *                      	    labels, 'id'= Get array of category IDs
1376 1376
 	 * @return  array|int           Array of category objects or < 0 if KO
1377 1377
 	 */
1378
-	function containing($id, $type, $mode='object')
1378
+	function containing($id, $type, $mode = 'object')
1379 1379
 	{
1380 1380
 		$cats = array();
1381 1381
 
@@ -1385,9 +1385,9 @@  discard block
 block discarded – undo
1385 1385
 		{
1386 1386
 		    // Load bank groups
1387 1387
 		    $sql = "SELECT c.label, c.rowid";
1388
-		    $sql.= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
1389
-		    $sql.= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid";
1390
-		    $sql.= " ORDER BY c.label";
1388
+		    $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
1389
+		    $sql .= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid";
1390
+		    $sql .= " ORDER BY c.label";
1391 1391
 
1392 1392
 		    $res = $this->db->query($sql);
1393 1393
 		    if ($res)
@@ -1415,9 +1415,9 @@  discard block
 block discarded – undo
1415 1415
         else
1416 1416
         {
1417 1417
     		$sql = "SELECT ct.fk_categorie, c.label, c.rowid";
1418
-    		$sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as ct, " . MAIN_DB_PREFIX . "categorie as c";
1419
-    		$sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_" . $this->MAP_CAT_FK[$type] . " = " . (int) $id . " AND c.type = " . $this->MAP_ID[$type];
1420
-    		$sql .= " AND c.entity IN (" . getEntity( 'category') . ")";
1418
+    		$sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as ct, ".MAIN_DB_PREFIX."categorie as c";
1419
+    		$sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".$this->MAP_CAT_FK[$type]." = ".(int) $id." AND c.type = ".$this->MAP_ID[$type];
1420
+    		$sql .= " AND c.entity IN (".getEntity('category').")";
1421 1421
 
1422 1422
     		$res = $this->db->query($sql);
1423 1423
     		if ($res)
@@ -1461,7 +1461,7 @@  discard block
 block discarded – undo
1461 1461
 	{
1462 1462
 		// Deprecation warning
1463 1463
 		if (is_numeric($type)) {
1464
-			dol_syslog(__METHOD__ . ': using numeric types is deprecated.', LOG_WARNING);
1464
+			dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
1465 1465
 		}
1466 1466
 
1467 1467
 		$cats = array();
@@ -1469,28 +1469,28 @@  discard block
 block discarded – undo
1469 1469
 		// For backward compatibility
1470 1470
 		if (is_numeric($type)) {
1471 1471
 			// We want to reverse lookup
1472
-			$map_type = array_flip( $this->MAP_ID );
1472
+			$map_type = array_flip($this->MAP_ID);
1473 1473
 			$type = $map_type[$type];
1474
-			dol_syslog( get_class( $this ) . "::rechercher(): numeric types are deprecated, please use string instead",
1475
-				LOG_WARNING );
1474
+			dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead",
1475
+				LOG_WARNING);
1476 1476
 		}
1477 1477
 
1478 1478
 		// Generation requete recherche
1479
-		$sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie";
1480
-		$sql .= " WHERE type = " . $this->MAP_ID[$type];
1481
-		$sql .= " AND entity IN (" . getEntity( 'category') . ")";
1479
+		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1480
+		$sql .= " WHERE type = ".$this->MAP_ID[$type];
1481
+		$sql .= " AND entity IN (".getEntity('category').")";
1482 1482
 		if ($nom)
1483 1483
 		{
1484
-			if (! $exact)
1484
+			if (!$exact)
1485 1485
 				$nom = '%'.str_replace('*', '%', $nom).'%';
1486
-			if (! $case)
1487
-				$sql.= " AND label LIKE '".$this->db->escape($nom)."'";
1486
+			if (!$case)
1487
+				$sql .= " AND label LIKE '".$this->db->escape($nom)."'";
1488 1488
 			else
1489
-				$sql.= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
1489
+				$sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'";
1490 1490
 		}
1491 1491
 		if ($id)
1492 1492
 		{
1493
-			$sql.=" AND rowid = '".$id."'";
1493
+			$sql .= " AND rowid = '".$id."'";
1494 1494
 		}
1495 1495
 
1496 1496
 		$res  = $this->db->query($sql);
@@ -1507,7 +1507,7 @@  discard block
 block discarded – undo
1507 1507
 		}
1508 1508
 		else
1509 1509
 		{
1510
-			$this->error=$this->db->error().' sql='.$sql;
1510
+			$this->error = $this->db->error().' sql='.$sql;
1511 1511
 			return -1;
1512 1512
 		}
1513 1513
 	}
@@ -1521,29 +1521,29 @@  discard block
 block discarded – undo
1521 1521
 	 * 	@param		int		$maxlength		Max length of text
1522 1522
 	 *	@return		string					Chaine avec URL
1523 1523
 	 */
1524
-	function getNomUrl($withpicto=0,$option='',$maxlength=0)
1524
+	function getNomUrl($withpicto = 0, $option = '', $maxlength = 0)
1525 1525
 	{
1526 1526
 		global $langs;
1527 1527
 
1528
-		$result='';
1529
-		$label=$langs->trans("ShowCategory").': '. ($this->ref?$this->ref:$this->label);
1528
+		$result = '';
1529
+		$label = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
1530 1530
 
1531 1531
 		// Check contrast with background and correct text color
1532
-		$forced_color='categtextwhite';
1532
+		$forced_color = 'categtextwhite';
1533 1533
 		if ($this->color)
1534 1534
 		{
1535
-			if (colorIsLight($this->color)) $forced_color='categtextblack';
1535
+			if (colorIsLight($this->color)) $forced_color = 'categtextblack';
1536 1536
 		}
1537 1537
 
1538
-		$link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.'&backtopage='.urlencode($_SERVER['PHP_SELF']).'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip '.$forced_color .'">';
1539
-		$linkend='</a>';
1538
+		$link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$this->id.'&type='.$this->type.'&backtopage='.urlencode($_SERVER['PHP_SELF']).'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip '.$forced_color.'">';
1539
+		$linkend = '</a>';
1540 1540
 
1541
-		$picto='category';
1541
+		$picto = 'category';
1542 1542
 
1543 1543
 
1544
-        if ($withpicto) $result.=($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
1545
-		if ($withpicto && $withpicto != 2) $result.=' ';
1546
-		if ($withpicto != 2) $result.=$link.dol_trunc(($this->ref?$this->ref:$this->label),$maxlength).$linkend;
1544
+        if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
1545
+		if ($withpicto && $withpicto != 2) $result .= ' ';
1546
+		if ($withpicto != 2) $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
1547 1547
 		return $result;
1548 1548
 	}
1549 1549
 
@@ -1561,10 +1561,10 @@  discard block
 block discarded – undo
1561 1561
         // phpcs:enable
1562 1562
 		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1563 1563
 
1564
-		$dir = $sdir .'/'. get_exdir($this->id,2,0,0,$this,'category') . $this->id ."/";
1564
+		$dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
1565 1565
 		$dir .= "photos/";
1566 1566
 
1567
-		if (! file_exists($dir))
1567
+		if (!file_exists($dir))
1568 1568
 		{
1569 1569
 			dol_mkdir($dir);
1570 1570
 		}
@@ -1573,9 +1573,9 @@  discard block
 block discarded – undo
1573 1573
 			if (is_array($file['name']) && count($file['name']) > 0)
1574 1574
 			{
1575 1575
 				$nbfile = count($file['name']);
1576
-				for ($i = 0; $i <= $nbfile; $i ++) {
1576
+				for ($i = 0; $i <= $nbfile; $i++) {
1577 1577
 
1578
-					$originImage = $dir . $file['name'][$i];
1578
+					$originImage = $dir.$file['name'][$i];
1579 1579
 
1580 1580
 					// Cree fichier en taille origine
1581 1581
 					dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
@@ -1586,7 +1586,7 @@  discard block
 block discarded – undo
1586 1586
 					}
1587 1587
 				}
1588 1588
 			} else {
1589
-				$originImage = $dir . $file['name'];
1589
+				$originImage = $dir.$file['name'];
1590 1590
 
1591 1591
 				// Cree fichier en taille origine
1592 1592
 				dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
@@ -1607,42 +1607,42 @@  discard block
 block discarded – undo
1607 1607
 	 *    @param      int		$nbmax      Nombre maximum de photos (0=pas de max)
1608 1608
 	 *    @return     array       			Tableau de photos
1609 1609
 	 */
1610
-	function liste_photos($dir,$nbmax=0)
1610
+	function liste_photos($dir, $nbmax = 0)
1611 1611
 	{
1612 1612
         // phpcs:enable
1613
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
1613
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1614 1614
 
1615
-		$nbphoto=0;
1616
-		$tabobj=array();
1615
+		$nbphoto = 0;
1616
+		$tabobj = array();
1617 1617
 
1618 1618
 		$dirthumb = $dir.'thumbs/';
1619 1619
 
1620 1620
 		if (file_exists($dir))
1621 1621
 		{
1622
-			$handle=opendir($dir);
1622
+			$handle = opendir($dir);
1623 1623
             if (is_resource($handle))
1624 1624
             {
1625 1625
     			while (($file = readdir($handle)) !== false)
1626 1626
     			{
1627
-    				if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i',$dir.$file))
1627
+    				if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file))
1628 1628
     				{
1629 1629
     					$nbphoto++;
1630 1630
     					$photo = $file;
1631 1631
 
1632 1632
     					// On determine nom du fichier vignette
1633
-    					$photo_vignette='';
1634
-    					if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i',$photo,$regs))
1633
+    					$photo_vignette = '';
1634
+    					if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs))
1635 1635
     					{
1636
-    						$photo_vignette=preg_replace('/'.$regs[0].'/i','',$photo).'_small'.$regs[0];
1636
+    						$photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
1637 1637
     					}
1638 1638
 
1639 1639
     					// Objet
1640
-    					$obj=array();
1641
-    					$obj['photo']=$photo;
1642
-    					if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette']='thumbs/' . $photo_vignette;
1643
-    					else $obj['photo_vignette']="";
1640
+    					$obj = array();
1641
+    					$obj['photo'] = $photo;
1642
+    					if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
1643
+    					else $obj['photo_vignette'] = "";
1644 1644
 
1645
-    					$tabobj[$nbphoto-1]=$obj;
1645
+    					$tabobj[$nbphoto - 1] = $obj;
1646 1646
 
1647 1647
     					// On continue ou on arrete de boucler
1648 1648
     					if ($nbmax && $nbphoto >= $nbmax) break;
@@ -1670,18 +1670,18 @@  discard block
 block discarded – undo
1670 1670
 
1671 1671
 	    $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
1672 1672
 		$dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
1673
-		$filename = preg_replace('/'.preg_quote($dir,'/').'/i','',$file); // Nom du fichier
1673
+		$filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
1674 1674
 
1675 1675
 		// On efface l'image d'origine
1676
-		dol_delete_file($file,1);
1676
+		dol_delete_file($file, 1);
1677 1677
 
1678 1678
 		// Si elle existe, on efface la vignette
1679
-		if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i',$filename,$regs))
1679
+		if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs))
1680 1680
 		{
1681
-			$photo_vignette=preg_replace('/'.$regs[0].'/i','',$filename).'_small'.$regs[0];
1681
+			$photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
1682 1682
 			if (file_exists($dirthumb.$photo_vignette))
1683 1683
 			{
1684
-				dol_delete_file($dirthumb.$photo_vignette,1);
1684
+				dol_delete_file($dirthumb.$photo_vignette, 1);
1685 1685
 			}
1686 1686
 		}
1687 1687
 	}
@@ -1718,9 +1718,9 @@  discard block
 block discarded – undo
1718 1718
 	    foreach ($langs_available as $key => $value)
1719 1719
 	    {
1720 1720
 	        $sql = "SELECT rowid";
1721
-	        $sql.= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1722
-	        $sql.= " WHERE fk_category=".$this->id;
1723
-	        $sql.= " AND lang='".$key."'";
1721
+	        $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1722
+	        $sql .= " WHERE fk_category=".$this->id;
1723
+	        $sql .= " AND lang='".$key."'";
1724 1724
 
1725 1725
 	        $result = $this->db->query($sql);
1726 1726
 
@@ -1729,20 +1729,20 @@  discard block
 block discarded – undo
1729 1729
 	            if ($this->db->num_rows($result)) // si aucune ligne dans la base
1730 1730
 	            {
1731 1731
 	                $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
1732
-	                $sql2.= " SET label='".$this->db->escape($this->label)."',";
1733
-	                $sql2.= " description='".$this->db->escape($this->description)."'";
1734
-	                $sql2.= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'";
1732
+	                $sql2 .= " SET label='".$this->db->escape($this->label)."',";
1733
+	                $sql2 .= " description='".$this->db->escape($this->description)."'";
1734
+	                $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'";
1735 1735
 	            }
1736 1736
 	            else
1737 1737
 	            {
1738 1738
 	                $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
1739
-	                $sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->label);
1740
-	                $sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"])."')";
1739
+	                $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->label);
1740
+	                $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')";
1741 1741
 	            }
1742 1742
 	            dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
1743
-	            if (! $this->db->query($sql2))
1743
+	            if (!$this->db->query($sql2))
1744 1744
 	            {
1745
-	                $this->error=$this->db->lasterror();
1745
+	                $this->error = $this->db->lasterror();
1746 1746
 	                return -1;
1747 1747
 	            }
1748 1748
 	        }
@@ -1751,30 +1751,30 @@  discard block
 block discarded – undo
1751 1751
 	            if ($this->db->num_rows($result)) // si aucune ligne dans la base
1752 1752
 	            {
1753 1753
 	                $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
1754
-	                $sql2.= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
1755
-	                $sql2.= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'";
1756
-	                $sql2.= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'";
1754
+	                $sql2 .= " SET label='".$this->db->escape($this->multilangs["$key"]["label"])."',";
1755
+	                $sql2 .= " description='".$this->db->escape($this->multilangs["$key"]["description"])."'";
1756
+	                $sql2 .= " WHERE fk_category=".$this->id." AND lang='".$this->db->escape($key)."'";
1757 1757
 	            }
1758 1758
 	            else
1759 1759
 	            {
1760 1760
 	                $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
1761
-	                $sql2.= " VALUES(".$this->id.",'".$key."','". $this->db->escape($this->multilangs["$key"]["label"]);
1762
-	                $sql2.= "','".$this->db->escape($this->multilangs["$key"]["description"])."')";
1761
+	                $sql2 .= " VALUES(".$this->id.",'".$key."','".$this->db->escape($this->multilangs["$key"]["label"]);
1762
+	                $sql2 .= "','".$this->db->escape($this->multilangs["$key"]["description"])."')";
1763 1763
 	            }
1764 1764
 
1765 1765
 	            // on ne sauvegarde pas des champs vides
1766
-	            if ( $this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"] )
1766
+	            if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"])
1767 1767
 	                dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
1768
-	            if (! $this->db->query($sql2))
1768
+	            if (!$this->db->query($sql2))
1769 1769
 	            {
1770
-	                $this->error=$this->db->lasterror();
1770
+	                $this->error = $this->db->lasterror();
1771 1771
 	                return -1;
1772 1772
 	            }
1773 1773
 	        }
1774 1774
 	    }
1775 1775
 
1776 1776
 			// Call trigger
1777
-			$result = $this->call_trigger('CATEGORY_SET_MULTILANGS',$user);
1777
+			$result = $this->call_trigger('CATEGORY_SET_MULTILANGS', $user);
1778 1778
 			if ($result < 0) {
1779 1779
 				$this->error = $this->db->lasterror();
1780 1780
 				return -1;
@@ -1796,28 +1796,28 @@  discard block
 block discarded – undo
1796 1796
 	    $current_lang = $langs->getDefaultLang();
1797 1797
 
1798 1798
 	    $sql = "SELECT lang, label, description";
1799
-	    $sql.= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1800
-	    $sql.= " WHERE fk_category=".$this->id;
1799
+	    $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1800
+	    $sql .= " WHERE fk_category=".$this->id;
1801 1801
 
1802 1802
 	    $result = $this->db->query($sql);
1803 1803
 	    if ($result)
1804 1804
 	    {
1805
-	        while ( $obj = $this->db->fetch_object($result) )
1805
+	        while ($obj = $this->db->fetch_object($result))
1806 1806
 	        {
1807 1807
 	            //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
1808
-	            if( $obj->lang == $current_lang ) // si on a les traduct. dans la langue courante on les charge en infos principales.
1808
+	            if ($obj->lang == $current_lang) // si on a les traduct. dans la langue courante on les charge en infos principales.
1809 1809
 	            {
1810
-	                $this->label		= $obj->label;
1811
-	                $this->description	= $obj->description;
1810
+	                $this->label = $obj->label;
1811
+	                $this->description = $obj->description;
1812 1812
 	            }
1813
-	            $this->multilangs["$obj->lang"]["label"]		= $obj->label;
1814
-	            $this->multilangs["$obj->lang"]["description"]	= $obj->description;
1813
+	            $this->multilangs["$obj->lang"]["label"] = $obj->label;
1814
+	            $this->multilangs["$obj->lang"]["description"] = $obj->description;
1815 1815
 	        }
1816 1816
 	        return 1;
1817 1817
 	    }
1818 1818
 	    else
1819 1819
 	    {
1820
-	        $this->error=$langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1820
+	        $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
1821 1821
 	        return -1;
1822 1822
 	    }
1823 1823
 	}
@@ -1846,10 +1846,10 @@  discard block
 block discarded – undo
1846 1846
         dol_syslog(get_class($this)."::initAsSpecimen");
1847 1847
 
1848 1848
         // Initialise parametres
1849
-        $this->id=0;
1850
-        $this->fk_parent=0;
1849
+        $this->id = 0;
1850
+        $this->fk_parent = 0;
1851 1851
         $this->label = 'SPECIMEN';
1852
-        $this->specimen=1;
1852
+        $this->specimen = 1;
1853 1853
         $this->description = 'This is a description';
1854 1854
         $this->socid = 1;
1855 1855
         $this->type = self::TYPE_PRODUCT;
Please login to merge, or discard this patch.
Base/FormOther.php 1 patch
Spacing   +218 added lines, -218 removed lines patch added patch discarded remove patch
@@ -68,14 +68,14 @@  discard block
 block discarded – undo
68 68
      *    @param    int		$fk_user          Utilisateur créant le modèle
69 69
      *    @return	void
70 70
      */
71
-    function select_export_model($selected='', $htmlname='exportmodelid', $type='', $useempty=0, $fk_user=null)
71
+    function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null)
72 72
     {
73 73
         // phpcs:enable
74 74
         $sql = "SELECT rowid, label";
75
-        $sql.= " FROM ".MAIN_DB_PREFIX."export_model";
76
-        $sql.= " WHERE type = '".$type."'";
77
-		if (!empty($fk_user)) $sql.=" AND fk_user=".$fk_user;
78
-        $sql.= " ORDER BY rowid";
75
+        $sql .= " FROM ".MAIN_DB_PREFIX."export_model";
76
+        $sql .= " WHERE type = '".$type."'";
77
+		if (!empty($fk_user)) $sql .= " AND fk_user=".$fk_user;
78
+        $sql .= " ORDER BY rowid";
79 79
         $result = $this->db->query($sql);
80 80
         if ($result)
81 81
         {
@@ -120,13 +120,13 @@  discard block
 block discarded – undo
120 120
      *    @param    int		$useempty          Affiche valeur vide dans liste
121 121
      *    @return	void
122 122
      */
123
-    function select_import_model($selected='', $htmlname='importmodelid', $type='', $useempty=0)
123
+    function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0)
124 124
     {
125 125
         // phpcs:enable
126 126
         $sql = "SELECT rowid, label";
127
-        $sql.= " FROM ".MAIN_DB_PREFIX."import_model";
128
-        $sql.= " WHERE type = '".$type."'";
129
-        $sql.= " ORDER BY rowid";
127
+        $sql .= " FROM ".MAIN_DB_PREFIX."import_model";
128
+        $sql .= " WHERE type = '".$type."'";
129
+        $sql .= " ORDER BY rowid";
130 130
         $result = $this->db->query($sql);
131 131
         if ($result)
132 132
         {
@@ -169,19 +169,19 @@  discard block
 block discarded – undo
169 169
      *    @param    string	$htmlname	Name of combo list
170 170
      *    @return	integer
171 171
      */
172
-    function select_ecotaxes($selected='', $htmlname='ecotaxe_id')
172
+    function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id')
173 173
     {
174 174
         // phpcs:enable
175 175
         global $langs;
176 176
 
177 177
         $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,";
178
-        $sql.= " c.label as country";
179
-        $sql.= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c";
180
-        $sql.= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
181
-        $sql.= " ORDER BY country, e.organization ASC, e.code ASC";
178
+        $sql .= " c.label as country";
179
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c";
180
+        $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid";
181
+        $sql .= " ORDER BY country, e.organization ASC, e.code ASC";
182 182
 
183 183
     	dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG);
184
-        $resql=$this->db->query($sql);
184
+        $resql = $this->db->query($sql);
185 185
         if ($resql)
186 186
         {
187 187
             print '<select class="flat" name="'.$htmlname.'">';
@@ -228,26 +228,26 @@  discard block
 block discarded – undo
228 228
      *    @param    string	$country_code   Country Code
229 229
      *    @return	string					HTML select list
230 230
      */
231
-    function select_revenue_stamp($selected='', $htmlname='revenuestamp', $country_code='')
231
+    function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '')
232 232
     {
233 233
         // phpcs:enable
234 234
     	global $langs;
235 235
 
236
-    	$out='';
236
+    	$out = '';
237 237
 
238 238
     	$sql = "SELECT r.taux, r.revenuestamp_type";
239
-    	$sql.= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
240
-    	$sql.= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
241
-    	$sql.= " AND c.code = '".$country_code."'";
239
+    	$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c";
240
+    	$sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid";
241
+    	$sql .= " AND c.code = '".$country_code."'";
242 242
 
243 243
     	dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG);
244
-    	$resql=$this->db->query($sql);
244
+    	$resql = $this->db->query($sql);
245 245
     	if ($resql)
246 246
     	{
247
-    		$out.='<select class="flat" name="'.$htmlname.'">';
247
+    		$out .= '<select class="flat" name="'.$htmlname.'">';
248 248
     		$num = $this->db->num_rows($resql);
249 249
     		$i = 0;
250
-    		$out.='<option value="0">&nbsp;</option>'."\n";
250
+    		$out .= '<option value="0">&nbsp;</option>'."\n";
251 251
     		if ($num)
252 252
     		{
253 253
     			while ($i < $num)
@@ -255,19 +255,19 @@  discard block
 block discarded – undo
255 255
     				$obj = $this->db->fetch_object($resql);
256 256
     				if (($selected && $selected == $obj->taux) || $num == 1)
257 257
     				{
258
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
258
+    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').' selected>';
259 259
     				}
260 260
     				else
261 261
     				{
262
-    					$out.='<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
262
+    					$out .= '<option value="'.$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '').'"'.($obj->revenuestamp_type == 'percent' ? ' data-type="percent"' : '').'>';
263 263
     					//print '<option onmouseover="showtip(\''.$obj->libelle.'\')" onMouseout="hidetip()" value="'.$obj->rowid.'">';
264 264
     				}
265
-    				$out.=$obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
266
-    				$out.='</option>';
265
+    				$out .= $obj->taux.($obj->revenuestamp_type == 'percent' ? '%' : '');
266
+    				$out .= '</option>';
267 267
     				$i++;
268 268
     			}
269 269
     		}
270
-    		$out.='</select>';
270
+    		$out .= '</select>';
271 271
     		return $out;
272 272
     	}
273 273
     	else
@@ -291,27 +291,27 @@  discard block
 block discarded – undo
291 291
      *    @param    int     $showempty      Add also an empty line
292 292
      *    @return   string					HTML select string
293 293
      */
294
-    function select_percent($selected=0,$htmlname='percent',$disabled=0,$increment=5,$start=0,$end=100,$showempty=0)
294
+    function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0)
295 295
     {
296 296
         // phpcs:enable
297
-        $return = '<select class="flat" name="'.$htmlname.'" '.($disabled?'disabled':'').'>';
298
-        if ($showempty) $return.='<option value="-1"'.(($selected == -1 || $selected == '')?' selected':'').'>&nbsp;</option>';
297
+        $return = '<select class="flat" name="'.$htmlname.'" '.($disabled ? 'disabled' : '').'>';
298
+        if ($showempty) $return .= '<option value="-1"'.(($selected == -1 || $selected == '') ? ' selected' : '').'>&nbsp;</option>';
299 299
 
300
-        for ($i = $start ; $i <= $end ; $i += $increment)
300
+        for ($i = $start; $i <= $end; $i += $increment)
301 301
         {
302 302
             if ($selected != '' && (int) $selected == $i)
303 303
             {
304
-                $return.= '<option value="'.$i.'" selected>';
304
+                $return .= '<option value="'.$i.'" selected>';
305 305
             }
306 306
             else
307 307
             {
308
-                $return.= '<option value="'.$i.'">';
308
+                $return .= '<option value="'.$i.'">';
309 309
             }
310
-            $return.= $i.' % ';
311
-            $return.= '</option>';
310
+            $return .= $i.' % ';
311
+            $return .= '</option>';
312 312
         }
313 313
 
314
-        $return.= '</select>';
314
+        $return .= '</select>';
315 315
 
316 316
         return $return;
317 317
     }
@@ -329,7 +329,7 @@  discard block
 block discarded – undo
329 329
      * @return  string		        	Html combo list code
330 330
      * @see	select_all_categories
331 331
      */
332
-    function select_categories($type, $selected=0, $htmlname='search_categ', $nocateg=0, $showempty=1, $morecss='')
332
+    function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '')
333 333
     {
334 334
         // phpcs:enable
335 335
         global $conf, $langs;
@@ -338,7 +338,7 @@  discard block
 block discarded – undo
338 338
         // For backward compatibility
339 339
         if (is_numeric($type))
340 340
         {
341
-            dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
341
+            dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
342 342
         }
343 343
 
344 344
         // Load list of "categories"
@@ -348,30 +348,30 @@  discard block
 block discarded – undo
348 348
         $moreforfilter = '';
349 349
         // Enhance with select2
350 350
         if (Globals::$conf->use_javascript_ajax) {
351
-            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
351
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
352 352
             $comboenhancement = ajax_combobox('select_categ_'.$htmlname);
353
-            $moreforfilter.=$comboenhancement;
353
+            $moreforfilter .= $comboenhancement;
354 354
         }
355 355
 
356 356
         // Print a select with each of them
357
-        $moreforfilter.='<select class="flat minwidth100'.($morecss?' '.$morecss:'').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
358
-        if ($showempty) $moreforfilter.='<option value="0">&nbsp;</option>';	// Should use -1 to say nothing
357
+        $moreforfilter .= '<select class="flat minwidth100'.($morecss ? ' '.$morecss : '').'" id="select_categ_'.$htmlname.'" name="'.$htmlname.'">';
358
+        if ($showempty) $moreforfilter .= '<option value="0">&nbsp;</option>'; // Should use -1 to say nothing
359 359
 
360 360
         if (is_array($tab_categs))
361 361
         {
362 362
             foreach ($tab_categs as $categ)
363 363
             {
364
-                $moreforfilter.='<option value="'.$categ['id'].'"';
365
-                if ($categ['id'] == $selected) $moreforfilter.=' selected';
366
-                $moreforfilter.='>'.dol_trunc($categ['fulllabel'],50,'middle').'</option>';
364
+                $moreforfilter .= '<option value="'.$categ['id'].'"';
365
+                if ($categ['id'] == $selected) $moreforfilter .= ' selected';
366
+                $moreforfilter .= '>'.dol_trunc($categ['fulllabel'], 50, 'middle').'</option>';
367 367
             }
368 368
         }
369 369
         if ($nocateg)
370 370
         {
371 371
         	$langs->load("categories");
372
-        	$moreforfilter.='<option value="-2"'.($selected == -2 ? ' selected':'').'>- '.$langs->trans("NotCategorized").' -</option>';
372
+        	$moreforfilter .= '<option value="-2"'.($selected == -2 ? ' selected' : '').'>- '.$langs->trans("NotCategorized").' -</option>';
373 373
         }
374
-        $moreforfilter.='</select>';
374
+        $moreforfilter .= '</select>';
375 375
 
376 376
         return $moreforfilter;
377 377
     }
@@ -389,43 +389,43 @@  discard block
 block discarded – undo
389 389
      *  @param	string	$morecss		More CSS
390 390
      *  @return string					Html combo list code
391 391
      */
392
-    function select_salesrepresentatives($selected,$htmlname,$user,$showstatus=0,$showempty=1,$morecss='')
392
+    function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '')
393 393
     {
394 394
         // phpcs:enable
395
-        global $conf,$langs;
395
+        global $conf, $langs;
396 396
         $langs->load('users');
397 397
 
398 398
         $out = '';
399 399
         // Enhance with select2
400 400
         if (Globals::$conf->use_javascript_ajax) {
401
-            include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
401
+            include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
402 402
 
403 403
             $comboenhancement = ajax_combobox($htmlname);
404 404
             if ($comboenhancement)
405 405
             {
406
-            	$out.=$comboenhancement;
406
+            	$out .= $comboenhancement;
407 407
             }
408 408
         }
409 409
         // Select each sales and print them in a select input
410
-        $out.='<select class="flat'.($morecss?' '.$morecss:'').'" id="'.$htmlname.'" name="'.$htmlname.'">';
411
-        if ($showempty) $out.='<option value="0">&nbsp;</option>';
410
+        $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'">';
411
+        if ($showempty) $out .= '<option value="0">&nbsp;</option>';
412 412
 
413 413
         // Get list of users allowed to be viewed
414 414
         $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login";
415
-        $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u";
416
-        $sql_usr .= " WHERE u.entity IN (0," . Globals::$conf->entity . ")";
417
-        if (empty($user->rights->user->user->lire)) $sql_usr.=" AND u.rowid = ".$user->id;
418
-        if (! empty($user->societe_id)) $sql_usr.=" AND u.fk_soc = ".$user->societe_id;
415
+        $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u";
416
+        $sql_usr .= " WHERE u.entity IN (0,".Globals::$conf->entity.")";
417
+        if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id;
418
+        if (!empty($user->societe_id)) $sql_usr .= " AND u.fk_soc = ".$user->societe_id;
419 419
         // Add existing sales representatives of thirdparty of external user
420 420
         if (empty($user->rights->user->user->lire) && $user->societe_id)
421 421
         {
422
-            $sql_usr.=" UNION ";
423
-            $sql_usr.= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login";
424
-            $sql_usr.= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc";
425
-            $sql_usr .= " WHERE u2.entity IN (0," . Globals::$conf->entity . ")";
426
-            $sql_usr.= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id;
422
+            $sql_usr .= " UNION ";
423
+            $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login";
424
+            $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc";
425
+            $sql_usr .= " WHERE u2.entity IN (0,".Globals::$conf->entity.")";
426
+            $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->societe_id;
427 427
         }
428
-	    $sql_usr.= " ORDER BY statut DESC, lastname ASC";  // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
428
+	    $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION.
429 429
         //print $sql_usr;exit;
430 430
 
431 431
         $resql_usr = $this->db->query($sql_usr);
@@ -434,33 +434,33 @@  discard block
 block discarded – undo
434 434
             while ($obj_usr = $this->db->fetch_object($resql_usr))
435 435
             {
436 436
 
437
-                $out.='<option value="'.$obj_usr->rowid.'"';
437
+                $out .= '<option value="'.$obj_usr->rowid.'"';
438 438
 
439
-                if ($obj_usr->rowid == $selected) $out.=' selected';
439
+                if ($obj_usr->rowid == $selected) $out .= ' selected';
440 440
 
441
-                $out.='>';
442
-                $out.=dolGetFirstLastname($obj_usr->firstname,$obj_usr->lastname);
441
+                $out .= '>';
442
+                $out .= dolGetFirstLastname($obj_usr->firstname, $obj_usr->lastname);
443 443
                 // Complete name with more info
444
-                $moreinfo=0;
444
+                $moreinfo = 0;
445 445
                 if (!empty(Globals::$conf->global->MAIN_SHOW_LOGIN)) {
446
-                    $out.=($moreinfo?' - ':' (').$obj_usr->login;
446
+                    $out .= ($moreinfo ? ' - ' : ' (').$obj_usr->login;
447 447
                     $moreinfo++;
448 448
                 }
449 449
                 if ($showstatus >= 0)
450 450
                 {
451 451
 					if ($obj_usr->statut == 1 && $showstatus == 1)
452 452
 					{
453
-						$out.=($moreinfo?' - ':' (').$langs->trans('Enabled');
453
+						$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Enabled');
454 454
 	                	$moreinfo++;
455 455
 					}
456 456
 					if ($obj_usr->statut == 0)
457 457
 					{
458
-						$out.=($moreinfo?' - ':' (').$langs->trans('Disabled');
458
+						$out .= ($moreinfo ? ' - ' : ' (').$langs->trans('Disabled');
459 459
                 		$moreinfo++;
460 460
 					}
461 461
 				}
462
-				$out.=($moreinfo?')':'');
463
-                $out.='</option>';
462
+				$out .= ($moreinfo ? ')' : '');
463
+                $out .= '</option>';
464 464
             }
465 465
             $this->db->free($resql_usr);
466 466
         }
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
         {
469 469
             dol_print_error($this->db);
470 470
         }
471
-        $out.='</select>';
471
+        $out .= '</select>';
472 472
 
473 473
         return $out;
474 474
     }
@@ -488,21 +488,21 @@  discard block
 block discarded – undo
488 488
      *  @param	string	$morecss				More css
489 489
      *  @return	void
490 490
      */
491
-    function selectProjectTasks($selectedtask='', $projectid=0, $htmlname='task_parent', $modeproject=0, $modetask=0, $mode=0, $useempty=0, $disablechildoftaskid=0, $filteronprojstatus='', $morecss='')
491
+    function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '')
492 492
     {
493 493
         global $user, $langs;
494 494
 
495 495
         require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
496 496
 
497 497
         //print $modeproject.'-'.$modetask;
498
-        $task=new Task($this->db);
499
-        $tasksarray=$task->getTasksArray($modetask?$user:0, $modeproject?$user:0, $projectid, 0, $mode, '', $filteronprojstatus);
498
+        $task = new Task($this->db);
499
+        $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus);
500 500
         if ($tasksarray)
501 501
         {
502
-        	print '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
502
+        	print '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
503 503
             if ($useempty) print '<option value="0">&nbsp;</option>';
504
-            $j=0;
505
-            $level=0;
504
+            $j = 0;
505
+            $level = 0;
506 506
             $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid);
507 507
             print '</select>';
508 508
 
@@ -526,14 +526,14 @@  discard block
 block discarded – undo
526 526
      * @param	int		$disablechildoftaskid	1=Disable task that are child of the provided task id
527 527
      * @return	void
528 528
      */
529
-    private function _pLineSelect(&$inc, $parent, $lines, $level=0, $selectedtask=0, $selectedproject=0, $disablechildoftaskid=0)
529
+    private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0)
530 530
     {
531 531
         global $langs, $user, $conf;
532 532
 
533
-        $lastprojectid=0;
533
+        $lastprojectid = 0;
534 534
 
535
-        $numlines=count($lines);
536
-        for ($i = 0 ; $i < $numlines ; $i++)
535
+        $numlines = count($lines);
536
+        for ($i = 0; $i < $numlines; $i++)
537 537
         {
538 538
         	if ($lines[$i]->fk_parent == $parent)
539 539
             {
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
                         if ($i > 0) print '<option value="0" disabled>----------</option>';
550 550
                         print '<option value="'.$lines[$i]->fk_project.'_0"';
551 551
                         if ($selectedproject == $lines[$i]->fk_project) print ' selected';
552
-                        print '>';	// Project -> Task
552
+                        print '>'; // Project -> Task
553 553
                         print $langs->trans("Project").' '.$lines[$i]->projectref;
554 554
                         if (empty($lines[$i]->public))
555 555
                         {
@@ -562,22 +562,22 @@  discard block
 block discarded – undo
562 562
                         //print '-'.$parent.'-'.$lines[$i]->fk_project.'-'.$lastprojectid;
563 563
                         print "</option>\n";
564 564
 
565
-                        $lastprojectid=$lines[$i]->fk_project;
565
+                        $lastprojectid = $lines[$i]->fk_project;
566 566
                         $inc++;
567 567
                     }
568 568
                 }
569 569
 
570
-                $newdisablechildoftaskid=$disablechildoftaskid;
570
+                $newdisablechildoftaskid = $disablechildoftaskid;
571 571
 
572 572
                 // Print task
573 573
                 if (isset($lines[$i]->id))		// We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0
574 574
                 {
575 575
                 	// Check if we must disable entry
576
-                	$disabled=0;
576
+                	$disabled = 0;
577 577
                 	if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid)))
578 578
                 	{
579 579
                			$disabled++;
580
-               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid=$lines[$i]->id;	// If task is child of a disabled parent, we will propagate id to disable next child too
580
+               			if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too
581 581
                 	}
582 582
 
583 583
                     print '<option value="'.$lines[$i]->fk_project.'_'.$lines[$i]->id.'"';
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
                         print ' ('.$langs->trans("Visibility").': '.$langs->trans("SharedProject").')';
596 596
                     }
597 597
                     if ($lines[$i]->id) print ' > ';
598
-                    for ($k = 0 ; $k < $level ; $k++)
598
+                    for ($k = 0; $k < $level; $k++)
599 599
                     {
600 600
                         print "&nbsp;&nbsp;&nbsp;";
601 601
                     }
@@ -619,13 +619,13 @@  discard block
 block discarded – undo
619 619
      * 		@return	string							HTML code for color thumb
620 620
      *		@see selectColor
621 621
      */
622
-    static function showColor($color, $textifnotdefined='')
622
+    static function showColor($color, $textifnotdefined = '')
623 623
     {
624
-    	$textcolor='FFF';
624
+    	$textcolor = 'FFF';
625 625
     	include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
626
-    	if(colorIsLight($color)) $textcolor='000';
626
+    	if (colorIsLight($color)) $textcolor = '000';
627 627
 
628
-    	$color = colorArrayToHex(colorStringToArray($color,array()),'');
628
+    	$color = colorArrayToHex(colorStringToArray($color, array()), '');
629 629
 
630 630
 		if ($color) print '<input type="text" class="colorthumb" disabled style="padding: 1px; margin-top: 0; margin-bottom: 0; color: #'.$textcolor.'; background-color: #'.$color.'" value="'.$color.'">';
631 631
 		else print $textifnotdefined;
@@ -644,7 +644,7 @@  discard block
 block discarded – undo
644 644
      * 		@deprecated Use instead selectColor
645 645
      *      @see selectColor()
646 646
      */
647
-    function select_color($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='')
647
+    function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '')
648 648
     {
649 649
         // phpcs:enable
650 650
     	print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors);
@@ -662,24 +662,24 @@  discard block
 block discarded – undo
662 662
      * 		@return	string
663 663
      *		@see showColor
664 664
      */
665
-    static function selectColor($set_color='', $prefix='f_color', $form_name='', $showcolorbox=1, $arrayofcolors='', $morecss='')
665
+    static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '')
666 666
     {
667 667
 	    // Deprecation warning
668 668
 	    if ($form_name) {
669
-		    dol_syslog(__METHOD__ . ": form_name parameter is deprecated", LOG_WARNING);
669
+		    dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING);
670 670
 	    }
671 671
 
672
-        global $langs,$conf;
672
+        global $langs, $conf;
673 673
 
674
-        $out='';
674
+        $out = '';
675 675
 
676
-        if (! is_array($arrayofcolors) || count($arrayofcolors) < 1)
676
+        if (!is_array($arrayofcolors) || count($arrayofcolors) < 1)
677 677
         {
678 678
             $langs->load("other");
679 679
             if (empty(Globals::$conf->dol_use_jmobile)) {
680
-	            $out.= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
681
-	            $out.= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
682
-	            $out.= '<script type="text/javascript">
680
+	            $out .= '<link rel="stylesheet" media="screen" type="text/css" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/css/jPicker-1.1.6.css" />';
681
+	            $out .= '<script type="text/javascript" src="'.DOL_URL_ROOT.'/includes/jquery/plugins/jpicker/jpicker-1.1.6.js"></script>';
682
+	            $out .= '<script type="text/javascript">
683 683
 	             jQuery(document).ready(function(){
684 684
 	                $(\'#colorpicker'.$prefix.'\').jPicker( {
685 685
 	                window: {
@@ -717,14 +717,14 @@  discard block
 block discarded – undo
717 717
 			        } ); });
718 718
 	             </script>';
719 719
             }
720
-            $out.= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss?' '.$morecss:'').'" type="text" value="'.$set_color.'" />';
720
+            $out .= '<input id="colorpicker'.$prefix.'" name="'.$prefix.'" size="6" maxlength="7" class="flat'.($morecss ? ' '.$morecss : '').'" type="text" value="'.$set_color.'" />';
721 721
         }
722 722
         else  // In most cases, this is not used. We used instead function with no specific list of colors
723 723
         {
724 724
             if (empty(Globals::$conf->dol_use_jmobile)) {
725
-	        	$out.= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
726
-	            $out.= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
727
-	            $out.= '<script type="text/javascript">
725
+	        	$out .= '<link rel="stylesheet" href="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.css" type="text/css" media="screen" />';
726
+	            $out .= '<script src="'.DOL_URL_ROOT.'/includes/jquery/plugins/colorpicker/jquery.colorpicker.js" type="text/javascript"></script>';
727
+	            $out .= '<script type="text/javascript">
728 728
 	             jQuery(document).ready(function(){
729 729
 	                 jQuery(\'#colorpicker'.$prefix.'\').colorpicker({
730 730
 	                     size: 14,
@@ -734,15 +734,15 @@  discard block
 block discarded – undo
734 734
 	             });
735 735
 	             </script>';
736 736
             }
737
-            $out.= '<select id="colorpicker'.$prefix.'" class="flat'.($morecss?' '.$morecss:'').'" name="'.$prefix.'">';
737
+            $out .= '<select id="colorpicker'.$prefix.'" class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$prefix.'">';
738 738
             //print '<option value="-1">&nbsp;</option>';
739 739
             foreach ($arrayofcolors as $val)
740 740
             {
741
-                $out.= '<option value="'.$val.'"';
742
-                if ($set_color == $val) $out.= ' selected';
743
-                $out.= '>'.$val.'</option>';
741
+                $out .= '<option value="'.$val.'"';
742
+                if ($set_color == $val) $out .= ' selected';
743
+                $out .= '>'.$val.'</option>';
744 744
             }
745
-            $out.= '</select>';
745
+            $out .= '</select>';
746 746
         }
747 747
 
748 748
         return $out;
@@ -759,12 +759,12 @@  discard block
 block discarded – undo
759 759
      *	@param	int		$y      	Hauteur de l'image en pixels
760 760
      *	@return	void
761 761
      */
762
-    function CreateColorIcon($color,$module,$name,$x='12',$y='12')
762
+    function CreateColorIcon($color, $module, $name, $x = '12', $y = '12')
763 763
     {
764 764
         // phpcs:enable
765 765
         global $conf;
766 766
 
767
-        $file = Globals::$conf->$module->dir_temp . '/' . $name . '.png';
767
+        $file = Globals::$conf->$module->dir_temp.'/'.$name.'.png';
768 768
 
769 769
         // On cree le repertoire contenant les icones
770 770
         if (!file_exists(Globals::$conf->$module->dir_temp)) {
@@ -772,19 +772,19 @@  discard block
 block discarded – undo
772 772
         }
773 773
 
774 774
         // On cree l'image en vraies couleurs
775
-        $image = imagecreatetruecolor($x,$y);
775
+        $image = imagecreatetruecolor($x, $y);
776 776
 
777
-        $color = substr($color,1,6);
777
+        $color = substr($color, 1, 6);
778 778
 
779
-        $rouge = hexdec(substr($color,0,2)); //conversion du canal rouge
780
-        $vert  = hexdec(substr($color,2,2)); //conversion du canal vert
781
-        $bleu  = hexdec(substr($color,4,2)); //conversion du canal bleu
779
+        $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge
780
+        $vert  = hexdec(substr($color, 2, 2)); //conversion du canal vert
781
+        $bleu  = hexdec(substr($color, 4, 2)); //conversion du canal bleu
782 782
 
783
-        $couleur = imagecolorallocate($image,$rouge,$vert,$bleu);
783
+        $couleur = imagecolorallocate($image, $rouge, $vert, $bleu);
784 784
         //print $rouge.$vert.$bleu;
785
-        imagefill($image,0,0,$couleur); //on remplit l'image
785
+        imagefill($image, 0, 0, $couleur); //on remplit l'image
786 786
         // On cree la couleur et on l'attribue a une variable pour ne pas la perdre
787
-        ImagePng($image,$file); //renvoie une image sous format png
787
+        ImagePng($image, $file); //renvoie une image sous format png
788 788
         ImageDestroy($image);
789 789
     }
790 790
 
@@ -797,7 +797,7 @@  discard block
 block discarded – undo
797 797
      *    	@param  int			$useempty          Affiche valeur vide dans liste
798 798
      *    	@return	string
799 799
      */
800
-    function select_dayofweek($selected='',$htmlname='weekid',$useempty=0)
800
+    function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0)
801 801
     {
802 802
         // phpcs:enable
803 803
         global $langs;
@@ -845,17 +845,17 @@  discard block
 block discarded – undo
845 845
      *      @param	string		$morecss			More Css
846 846
      *      @return string
847 847
      */
848
-    function select_month($selected='', $htmlname='monthid', $useempty=0, $longlabel=0, $morecss='')
848
+    function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = '')
849 849
     {
850 850
         // phpcs:enable
851 851
         global $langs;
852 852
 
853 853
         require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
854 854
 
855
-        if ($longlabel) $montharray = monthArray($langs, 0);	// Get array
855
+        if ($longlabel) $montharray = monthArray($langs, 0); // Get array
856 856
         else $montharray = monthArray($langs, 1);
857 857
 
858
-        $select_month = '<select class="flat'.($morecss?' '.$morecss:'').'" name="'.$htmlname.'" id="'.$htmlname.'">';
858
+        $select_month = '<select class="flat'.($morecss ? ' '.$morecss : '').'" name="'.$htmlname.'" id="'.$htmlname.'">';
859 859
         if ($useempty)
860 860
         {
861 861
             $select_month .= '<option value="0">&nbsp;</option>';
@@ -892,10 +892,10 @@  discard block
 block discarded – undo
892 892
      *  @param	string		$morecss		More CSS
893 893
      *  @return	string
894 894
      */
895
-    function select_year($selected='',$htmlname='yearid',$useempty=0, $min_year=10, $max_year=5, $offset=0, $invert=0, $option='', $morecss='valignmiddle widthauto')
895
+    function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle widthauto')
896 896
     {
897 897
         // phpcs:enable
898
-        print $this->selectyear($selected,$htmlname,$useempty,$min_year,$max_year,$offset,$invert,$option,$morecss);
898
+        print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss);
899 899
     }
900 900
 
901 901
     /**
@@ -912,41 +912,41 @@  discard block
 block discarded – undo
912 912
      *  @param	string	$morecss		More css
913 913
      *  @return	string
914 914
      */
915
-    function selectyear($selected='',$htmlname='yearid',$useempty=0, $min_year=10, $max_year=5, $offset=0, $invert=0, $option='', $morecss='valignmiddle widthauto')
915
+    function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle widthauto')
916 916
     {
917
-        $out='';
917
+        $out = '';
918 918
 
919
-        $currentyear = date("Y")+$offset;
920
-        $max_year = $currentyear+$max_year;
921
-        $min_year = $currentyear-$min_year;
922
-        if(empty($selected) && empty($useempty)) $selected = $currentyear;
919
+        $currentyear = date("Y") + $offset;
920
+        $max_year = $currentyear + $max_year;
921
+        $min_year = $currentyear - $min_year;
922
+        if (empty($selected) && empty($useempty)) $selected = $currentyear;
923 923
 
924
-        $out.= '<select class="flat'.($morecss?' '.$morecss:'').'" id="' . $htmlname . '" name="' . $htmlname . '"'.$option.' >';
925
-        if($useempty)
924
+        $out .= '<select class="flat'.($morecss ? ' '.$morecss : '').'" id="'.$htmlname.'" name="'.$htmlname.'"'.$option.' >';
925
+        if ($useempty)
926 926
         {
927
-        	$selected_html='';
927
+        	$selected_html = '';
928 928
             if ($selected == '') $selected_html = ' selected';
929
-            $out.= '<option value=""' . $selected_html . '>&nbsp;</option>';
929
+            $out .= '<option value=""'.$selected_html.'>&nbsp;</option>';
930 930
         }
931
-        if (! $invert)
931
+        if (!$invert)
932 932
         {
933 933
             for ($y = $max_year; $y >= $min_year; $y--)
934 934
             {
935
-                $selected_html='';
935
+                $selected_html = '';
936 936
                 if ($selected > 0 && $y == $selected) $selected_html = ' selected';
937
-                $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
937
+                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
938 938
             }
939 939
         }
940 940
         else
941 941
         {
942 942
             for ($y = $min_year; $y <= $max_year; $y++)
943 943
             {
944
-                $selected_html='';
944
+                $selected_html = '';
945 945
                 if ($selected > 0 && $y == $selected) $selected_html = ' selected';
946
-                $out.= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
946
+                $out .= '<option value="'.$y.'"'.$selected_html.' >'.$y.'</option>';
947 947
             }
948 948
         }
949
-        $out.= "</select>\n";
949
+        $out .= "</select>\n";
950 950
 
951 951
         return $out;
952 952
     }
@@ -963,10 +963,10 @@  discard block
 block discarded – undo
963 963
      * @param  	int		$originid      	Id de l'origine
964 964
      * @return	void
965 965
      */
966
-    function form_address($page, $selected, $socid, $htmlname='address_id', $origin='', $originid='')
966
+    function form_address($page, $selected, $socid, $htmlname = 'address_id', $origin = '', $originid = '')
967 967
     {
968 968
         // phpcs:enable
969
-        global $langs,$conf;
969
+        global $langs, $conf;
970 970
         global $form;
971 971
 
972 972
         if ($htmlname != "none")
@@ -984,9 +984,9 @@  discard block
 block discarded – undo
984 984
         {
985 985
             if ($selected)
986 986
             {
987
-                require_once DOL_DOCUMENT_ROOT .'/societe/class/address.class.php';
988
-                $address=new Address($this->db);
989
-                $result=$address->fetch_address($selected);
987
+                require_once DOL_DOCUMENT_ROOT.'/societe/class/address.class.php';
988
+                $address = new Address($this->db);
989
+                $result = $address->fetch_address($selected);
990 990
                 print '<a href='.DOL_URL_ROOT.'/comm/address.php?socid='.$address->socid.'&id='.$address->id.'&action=edit&origin='.$origin.'&originid='.$originid.'>'.$address->label.'</a>';
991 991
             }
992 992
             else
@@ -1006,70 +1006,70 @@  discard block
 block discarded – undo
1006 1006
      * 	@param	   String       $areacode    Code of area for pages ('0'=value for Home page)
1007 1007
      * 	@return    array                     array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>)
1008 1008
      */
1009
-    static function getBoxesArea($user,$areacode)
1009
+    static function getBoxesArea($user, $areacode)
1010 1010
     {
1011
-        global $conf,$langs,$db;
1011
+        global $conf, $langs, $db;
1012 1012
 
1013 1013
         include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
1014 1014
 
1015
-        $confuserzone='MAIN_BOXES_'.$areacode;
1015
+        $confuserzone = 'MAIN_BOXES_'.$areacode;
1016 1016
 
1017 1017
         // $boxactivated will be array of boxes enabled into global setup
1018 1018
         // $boxidactivatedforuser will be array of boxes choosed by user
1019 1019
 
1020
-        $selectboxlist='';
1021
-        $boxactivated=InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone)?null:$user), array(), 0);	// Search boxes of common+user (or common only if user has no specific setup)
1020
+        $selectboxlist = '';
1021
+        $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup)
1022 1022
 
1023
-        $boxidactivatedforuser=array();
1024
-        foreach($boxactivated as $box)
1023
+        $boxidactivatedforuser = array();
1024
+        foreach ($boxactivated as $box)
1025 1025
         {
1026
-        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id]=$box->id;	// We keep only boxes to show for user
1026
+        	if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user
1027 1027
         }
1028 1028
 
1029 1029
         // Define selectboxlist
1030
-        $arrayboxtoactivatelabel=array();
1031
-        if (! empty($user->conf->$confuserzone))
1030
+        $arrayboxtoactivatelabel = array();
1031
+        if (!empty($user->conf->$confuserzone))
1032 1032
         {
1033
-        	$boxorder='';
1034
-        	$langs->load("boxes");	// Load label of boxes
1035
-        	foreach($boxactivated as $box)
1033
+        	$boxorder = '';
1034
+        	$langs->load("boxes"); // Load label of boxes
1035
+        	foreach ($boxactivated as $box)
1036 1036
         	{
1037
-        		if (! empty($boxidactivatedforuser[$box->id])) continue;	// Already visible for user
1038
-        		$label=$langs->transnoentitiesnoconv($box->boxlabel);
1037
+        		if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user
1038
+        		$label = $langs->transnoentitiesnoconv($box->boxlabel);
1039 1039
         		//if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')';
1040 1040
         		if (preg_match('/graph/', $box->class) && Globals::$conf->browser->layout != 'phone') {
1041
-        			$label=$label.' <span class="fa fa-bar-chart"></span>';
1041
+        			$label = $label.' <span class="fa fa-bar-chart"></span>';
1042 1042
         		}
1043
-        		$arrayboxtoactivatelabel[$box->id]=$label;			// We keep only boxes not shown for user, to show into combo list
1043
+        		$arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list
1044 1044
         	}
1045
-            foreach($boxidactivatedforuser as $boxid)
1045
+            foreach ($boxidactivatedforuser as $boxid)
1046 1046
         	{
1047
-       			if (empty($boxorder)) $boxorder.='A:';
1048
-  				$boxorder.=$boxid.',';
1047
+       			if (empty($boxorder)) $boxorder .= 'A:';
1048
+  				$boxorder .= $boxid.',';
1049 1049
         	}
1050 1050
 
1051 1051
         	//var_dump($boxidactivatedforuser);
1052 1052
 
1053 1053
         	// Class Form must have been already loaded
1054
-        	$selectboxlist.='<!-- Form with select box list -->'."\n";
1055
-			$selectboxlist.='<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1056
-			$selectboxlist.='<input type="hidden" name="addbox" value="addbox">';
1057
-			$selectboxlist.='<input type="hidden" name="userid" value="'.$user->id.'">';
1058
-			$selectboxlist.='<input type="hidden" name="areacode" value="'.$areacode.'">';
1059
-			$selectboxlist.='<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1060
-			$selectboxlist.=Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1054
+        	$selectboxlist .= '<!-- Form with select box list -->'."\n";
1055
+			$selectboxlist .= '<form id="addbox" name="addbox" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
1056
+			$selectboxlist .= '<input type="hidden" name="addbox" value="addbox">';
1057
+			$selectboxlist .= '<input type="hidden" name="userid" value="'.$user->id.'">';
1058
+			$selectboxlist .= '<input type="hidden" name="areacode" value="'.$areacode.'">';
1059
+			$selectboxlist .= '<input type="hidden" name="boxorder" value="'.$boxorder.'">';
1060
+			$selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1);
1061 1061
             if (empty(Globals::$conf->use_javascript_ajax))
1062
-                $selectboxlist .= ' <input type="submit" class="button" value="' . $langs->trans("AddBox") . '">';
1063
-            $selectboxlist.='</form>';
1062
+                $selectboxlist .= ' <input type="submit" class="button" value="'.$langs->trans("AddBox").'">';
1063
+            $selectboxlist .= '</form>';
1064 1064
             if (!empty(Globals::$conf->use_javascript_ajax)) {
1065
-            	include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
1066
-            	$selectboxlist.=ajax_combobox("boxcombo");
1065
+            	include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
1066
+            	$selectboxlist .= ajax_combobox("boxcombo");
1067 1067
             }
1068 1068
         }
1069 1069
 
1070 1070
         // Javascript code for dynamic actions
1071 1071
         if (!empty(Globals::$conf->use_javascript_ajax)) {
1072
-	        $selectboxlist.='<script type="text/javascript" language="javascript">
1072
+	        $selectboxlist .= '<script type="text/javascript" language="javascript">
1073 1073
 
1074 1074
 	        // To update list of activated boxes
1075 1075
 	        function updateBoxOrder(closing) {
@@ -1083,7 +1083,7 @@  discard block
 block discarded – undo
1083 1083
 	        			async: false
1084 1084
 	        		});
1085 1085
 	        		// We force reload to be sure to get all boxes into list
1086
-	        		window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=delbox\';
1086
+	        		window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=delbox\';
1087 1087
 	        	}
1088 1088
 	        	else
1089 1089
 	        	{
@@ -1105,11 +1105,11 @@  discard block
 block discarded – undo
1105 1105
 	    					url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&boxid=\'+boxid+\'&zone='.$areacode.'&userid='.$user->id.'\',
1106 1106
 	    			        async: false
1107 1107
 	    		        });
1108
-	        			window.location.search=\'mainmenu='.GETPOST("mainmenu","aZ09").'&leftmenu='.GETPOST('leftmenu',"aZ09").'&action=addbox&boxid=\'+boxid;
1108
+	        			window.location.search=\'mainmenu='.GETPOST("mainmenu", "aZ09").'&leftmenu='.GETPOST('leftmenu', "aZ09").'&action=addbox&boxid=\'+boxid;
1109 1109
 	                }
1110 1110
 	        	});';
1111
-	        	if (! count($arrayboxtoactivatelabel)) $selectboxlist.='jQuery("#boxcombo").hide();';
1112
-	        	$selectboxlist.='
1111
+	        	if (!count($arrayboxtoactivatelabel)) $selectboxlist .= 'jQuery("#boxcombo").hide();';
1112
+	        	$selectboxlist .= '
1113 1113
 
1114 1114
 	        	jQuery("#boxhalfleft, #boxhalfright").sortable({
1115 1115
 	    	    	handle: \'.boxhandle\',
@@ -1134,79 +1134,79 @@  discard block
 block discarded – undo
1134 1134
 
1135 1135
         	});'."\n";
1136 1136
 
1137
-	        $selectboxlist.='</script>'."\n";
1137
+	        $selectboxlist .= '</script>'."\n";
1138 1138
         }
1139 1139
 
1140 1140
         // Define boxlista and boxlistb
1141
-        $nbboxactivated=count($boxidactivatedforuser);
1141
+        $nbboxactivated = count($boxidactivatedforuser);
1142 1142
 
1143 1143
         if ($nbboxactivated)
1144 1144
         {
1145 1145
         	// Load translation files required by the page
1146
-            $langs->loadLangs(array("boxes","projects"));
1146
+            $langs->loadLangs(array("boxes", "projects"));
1147 1147
 
1148
-        	$emptybox=new ModeleBoxes($db);
1148
+        	$emptybox = new ModeleBoxes($db);
1149 1149
 
1150
-            $boxlista.="\n<!-- Box left container -->\n";
1150
+            $boxlista .= "\n<!-- Box left container -->\n";
1151 1151
 
1152 1152
             // Define $box_max_lines
1153
-            $box_max_lines=5;
1153
+            $box_max_lines = 5;
1154 1154
             if (!empty(Globals::$conf->global->MAIN_BOXES_MAXLINES))
1155 1155
                 $box_max_lines = Globals::$conf->global->MAIN_BOXES_MAXLINES;
1156 1156
 
1157
-            $ii=0;
1157
+            $ii = 0;
1158 1158
             foreach ($boxactivated as $key => $box)
1159 1159
             {
1160
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1161
-				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='A'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1162
-            	if (preg_match('/^A/i',$box->box_order)) // column A
1160
+            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1161
+				if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1162
+            	if (preg_match('/^A/i', $box->box_order)) // column A
1163 1163
                 {
1164 1164
                     $ii++;
1165 1165
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1166 1166
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1167 1167
                     // Show box
1168 1168
                     $box->loadBox($box_max_lines);
1169
-                    $boxlista.= $box->outputBox();
1169
+                    $boxlista .= $box->outputBox();
1170 1170
                 }
1171 1171
             }
1172 1172
 
1173 1173
             if (Globals::$conf->browser->layout != 'phone') {
1174
-            	$emptybox->box_id='A';
1175
-            	$emptybox->info_box_head=array();
1176
-            	$emptybox->info_box_contents=array();
1177
-            	$boxlista.= $emptybox->outputBox(array(),array());
1174
+            	$emptybox->box_id = 'A';
1175
+            	$emptybox->info_box_head = array();
1176
+            	$emptybox->info_box_contents = array();
1177
+            	$boxlista .= $emptybox->outputBox(array(), array());
1178 1178
             }
1179
-            $boxlista.= "<!-- End box left container -->\n";
1179
+            $boxlista .= "<!-- End box left container -->\n";
1180 1180
 
1181
-            $boxlistb.= "\n<!-- Box right container -->\n";
1181
+            $boxlistb .= "\n<!-- Box right container -->\n";
1182 1182
 
1183
-            $ii=0;
1183
+            $ii = 0;
1184 1184
             foreach ($boxactivated as $key => $box)
1185 1185
             {
1186
-            	if ((! empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1187
-            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order='B'.sprintf("%02d",($ii+1));	// When box_order was not yet set to Axx or Bxx and is still 0
1188
-            	if (preg_match('/^B/i',$box->box_order)) // colonne B
1186
+            	if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue;
1187
+            	if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0
1188
+            	if (preg_match('/^B/i', $box->box_order)) // colonne B
1189 1189
                 {
1190 1190
                     $ii++;
1191 1191
                     //print 'box_id '.$boxactivated[$ii]->box_id.' ';
1192 1192
                     //print 'box_order '.$boxactivated[$ii]->box_order.'<br>';
1193 1193
                     // Show box
1194 1194
                     $box->loadBox($box_max_lines);
1195
-                    $boxlistb.= $box->outputBox();
1195
+                    $boxlistb .= $box->outputBox();
1196 1196
                 }
1197 1197
             }
1198 1198
 
1199 1199
             if (Globals::$conf->browser->layout != 'phone') {
1200
-            	$emptybox->box_id='B';
1201
-            	$emptybox->info_box_head=array();
1202
-            	$emptybox->info_box_contents=array();
1203
-            	$boxlistb.= $emptybox->outputBox(array(),array());
1200
+            	$emptybox->box_id = 'B';
1201
+            	$emptybox->info_box_head = array();
1202
+            	$emptybox->info_box_contents = array();
1203
+            	$boxlistb .= $emptybox->outputBox(array(), array());
1204 1204
             }
1205 1205
 
1206
-            $boxlistb.= "<!-- End box right container -->\n";
1206
+            $boxlistb .= "<!-- End box right container -->\n";
1207 1207
         }
1208 1208
 
1209
-        return array('selectboxlist'=>count($boxactivated)?$selectboxlist:'', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb);
1209
+        return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb);
1210 1210
     }
1211 1211
 
1212 1212
 
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
      *  @param  string  $moreattrib         More attributes on HTML select tag
1224 1224
      * 	@return	void
1225 1225
      */
1226
-    function select_dictionary($htmlname,$dictionarytable,$keyfield='code',$labelfield='label',$selected='',$useempty=0,$moreattrib='')
1226
+    function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '')
1227 1227
     {
1228 1228
         // phpcs:enable
1229 1229
         global $langs, $conf;
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
         $langs->load("admin");
1232 1232
 
1233 1233
         $sql = "SELECT rowid, ".$keyfield.", ".$labelfield;
1234
-        $sql.= " FROM ".MAIN_DB_PREFIX.$dictionarytable;
1235
-        $sql.= " ORDER BY ".$labelfield;
1234
+        $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable;
1235
+        $sql .= " ORDER BY ".$labelfield;
1236 1236
 
1237 1237
         dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG);
1238 1238
         $result = $this->db->query($sql);
@@ -1242,7 +1242,7 @@  discard block
 block discarded – undo
1242 1242
             $i = 0;
1243 1243
             if ($num)
1244 1244
             {
1245
-                print '<select id="select'.$htmlname.'" class="flat selectdictionary" name="'.$htmlname.'"'.($moreattrib?' '.$moreattrib:'').'>';
1245
+                print '<select id="select'.$htmlname.'" class="flat selectdictionary" name="'.$htmlname.'"'.($moreattrib ? ' '.$moreattrib : '').'>';
1246 1246
                 if ($useempty == 1 || ($useempty == 2 && $num > 1))
1247 1247
                 {
1248 1248
                     print '<option value="-1">&nbsp;</option>';
Please login to merge, or discard this patch.
Helpers/DolUtils2.php 1 patch
Spacing   +536 added lines, -536 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
                 $pos++;
57 57
                 $unicodeHexVal = substr($source, $pos, 4);
58 58
                 $unicode = hexdec($unicodeHexVal);
59
-                $entity = "&#". $unicode . ';';
59
+                $entity = "&#".$unicode.';';
60 60
                 $decodedStr .= utf8_encode($entity);
61 61
                 $pos += 4;
62 62
             }
@@ -82,31 +82,31 @@  discard block
 block discarded – undo
82 82
  * @param	string	$subdir		Sub directory (Example: '/mailings')
83 83
  * @return	array				Array of directories that can contains module descriptors
84 84
  */
85
-function dolGetModulesDirs($subdir='')
85
+function dolGetModulesDirs($subdir = '')
86 86
 {
87 87
     global $conf;
88 88
 
89
-    $modulesdir=array();
89
+    $modulesdir = array();
90 90
 
91 91
     foreach (Globals::$conf->file->dol_document_root as $type => $dirroot) {
92 92
         // Default core/modules dir
93 93
         if ($type === 'main') {
94
-            $modulesdir[$dirroot . '/core/modules' . $subdir . '/'] = $dirroot . '/core/modules' . $subdir . '/';
94
+            $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
95 95
         }
96 96
 
97 97
         // Scan dir from external modules
98
-        $handle=@opendir($dirroot);
98
+        $handle = @opendir($dirroot);
99 99
         if (is_resource($handle))
100 100
         {
101
-            while (($file = readdir($handle))!==false)
101
+            while (($file = readdir($handle)) !== false)
102 102
             {
103
-                if (preg_match('/disabled/',$file)) continue;   // We discard module if it contains disabled into name.
103
+                if (preg_match('/disabled/', $file)) continue; // We discard module if it contains disabled into name.
104 104
 
105 105
                 if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
106 106
                 {
107
-                    if (is_dir($dirroot . '/' . $file . '/core/modules'.$subdir.'/'))
107
+                    if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/'))
108 108
                     {
109
-                        $modulesdir[$dirroot . '/' . $file . '/core/modules'.$subdir.'/'] = $dirroot . '/' . $file . '/core/modules'.$subdir.'/';
109
+                        $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
110 110
                     }
111 111
                 }
112 112
             }
@@ -127,13 +127,13 @@  discard block
 block discarded – undo
127 127
 {
128 128
     global $langs;
129 129
 
130
-    $selected='EUA4';
130
+    $selected = 'EUA4';
131 131
     if (!$outputlangs) {
132
-    	$outputlangs=$langs;
132
+    	$outputlangs = $langs;
133 133
     }
134 134
 
135
-    if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
136
-    if ($outputlangs->defaultlang == 'en_US') $selected='USLetter';    // US
135
+    if ($outputlangs->defaultlang == 'ca_CA') $selected = 'CAP4'; // Canada
136
+    if ($outputlangs->defaultlang == 'en_US') $selected = 'USLetter'; // US
137 137
     return $selected;
138 138
 }
139 139
 
@@ -145,19 +145,19 @@  discard block
 block discarded – undo
145 145
  *  @param  int			$searchalt      1=Search also in alternative languages
146 146
  *	@return	boolean						true if OK, false if KO
147 147
  */
148
-function dol_print_file($langs,$filename,$searchalt=0)
148
+function dol_print_file($langs, $filename, $searchalt = 0)
149 149
 {
150 150
     global $conf;
151 151
 
152 152
     // Test if file is in lang directory
153
-    foreach($langs->dir as $searchdir)
153
+    foreach ($langs->dir as $searchdir)
154 154
     {
155
-        $formfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
155
+        $formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename);
156 156
         dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
157 157
         if (is_readable($formfile))
158 158
         {
159
-            $content=file_get_contents($formfile);
160
-            $isutf8=utf8_check($content);
159
+            $content = file_get_contents($formfile);
160
+            $isutf8 = utf8_check($content);
161 161
             if (!$isutf8 && Globals::$conf->file->character_set_client == 'UTF-8')
162 162
                     print utf8_encode($content);
163 163
                 elseif ($isutf8 && Globals::$conf->file->character_set_client == 'ISO-8859-1')
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
             //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
176 176
             if (is_readable($formfilealt))
177 177
             {
178
-                $content=file_get_contents($formfilealt);
179
-                $isutf8=utf8_check($content);
178
+                $content = file_get_contents($formfilealt);
179
+                $isutf8 = utf8_check($content);
180 180
                 if (!$isutf8 && Globals::$conf->file->character_set_client == 'UTF-8')
181 181
                         print utf8_encode($content);
182 182
                     elseif ($isutf8 && Globals::$conf->file->character_set_client == 'ISO-8859-1')
@@ -199,7 +199,7 @@  discard block
 block discarded – undo
199 199
  *  @param  int     $usetable       Output into a table
200 200
  *	@return	void
201 201
  */
202
-function dol_print_object_info($object, $usetable=0)
202
+function dol_print_object_info($object, $usetable = 0)
203 203
 {
204 204
     global $langs, $db;
205 205
 
@@ -208,16 +208,16 @@  discard block
 block discarded – undo
208 208
 
209 209
     include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
210 210
 
211
-    $deltadateforserver=getServerTimeZoneInt('now');
212
-    $deltadateforclient=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
211
+    $deltadateforserver = getServerTimeZoneInt('now');
212
+    $deltadateforclient = ((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
213 213
     //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
214
-    $deltadateforuser=round($deltadateforclient-$deltadateforserver);
214
+    $deltadateforuser = round($deltadateforclient - $deltadateforserver);
215 215
     //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
216 216
 
217 217
     if ($usetable) print '<table class="border centpercent">';
218 218
 
219 219
     // Import key
220
-    if (! empty($object->import_key))
220
+    if (!empty($object->import_key))
221 221
     {
222 222
         if ($usetable) print '<tr><td class="titlefield">';
223 223
         print $langs->trans("ImportedWithSet");
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
     }
230 230
 
231 231
     // User creation (old method using already loaded object and not id is kept for backward compatibility)
232
-    if (! empty($object->user_creation) || ! empty($object->user_creation_id))
232
+    if (!empty($object->user_creation) || !empty($object->user_creation_id))
233 233
     {
234 234
         if ($usetable) print '<tr><td class="titlefield">';
235 235
         print $langs->trans("CreatedBy");
@@ -242,7 +242,7 @@  discard block
 block discarded – undo
242 242
         }
243 243
         else
244 244
         {
245
-            $userstatic=new User($db);
245
+            $userstatic = new User($db);
246 246
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
247 247
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
248 248
         	else print $langs->trans("Unknown");
@@ -252,20 +252,20 @@  discard block
 block discarded – undo
252 252
     }
253 253
 
254 254
     // Date creation
255
-    if (! empty($object->date_creation))
255
+    if (!empty($object->date_creation))
256 256
     {
257 257
         if ($usetable) print '<tr><td class="titlefield">';
258 258
         print $langs->trans("DateCreation");
259 259
         if ($usetable) print '</td><td>';
260 260
         else print ': ';
261 261
         print dol_print_date($object->date_creation, 'dayhour');
262
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
262
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
263 263
         if ($usetable) print '</td></tr>';
264 264
         else print '<br>';
265 265
     }
266 266
 
267 267
     // User change (old method using already loaded object and not id is kept for backward compatibility)
268
-    if (! empty($object->user_modification) || ! empty($object->user_modification_id))
268
+    if (!empty($object->user_modification) || !empty($object->user_modification_id))
269 269
     {
270 270
         if ($usetable) print '<tr><td class="titlefield">';
271 271
         print $langs->trans("ModifiedBy");
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
         }
279 279
         else
280 280
         {
281
-            $userstatic=new User($db);
281
+            $userstatic = new User($db);
282 282
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
283 283
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
284 284
         	else print $langs->trans("Unknown");
@@ -288,20 +288,20 @@  discard block
 block discarded – undo
288 288
     }
289 289
 
290 290
     // Date change
291
-    if (! empty($object->date_modification))
291
+    if (!empty($object->date_modification))
292 292
     {
293 293
         if ($usetable) print '<tr><td class="titlefield">';
294 294
         print $langs->trans("DateLastModification");
295 295
         if ($usetable) print '</td><td>';
296 296
         else print ': ';
297 297
         print dol_print_date($object->date_modification, 'dayhour');
298
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
298
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
299 299
         if ($usetable) print '</td></tr>';
300 300
         else print '<br>';
301 301
     }
302 302
 
303 303
     // User validation (old method using already loaded object and not id is kept for backward compatibility)
304
-    if (! empty($object->user_validation) || ! empty($object->user_validation_id))
304
+    if (!empty($object->user_validation) || !empty($object->user_validation_id))
305 305
     {
306 306
         if ($usetable) print '<tr><td class="titlefield">';
307 307
         print $langs->trans("ValidatedBy");
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
         }
315 315
         else
316 316
         {
317
-            $userstatic=new User($db);
317
+            $userstatic = new User($db);
318 318
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
319 319
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
320 320
         	else print $langs->trans("Unknown");
@@ -324,20 +324,20 @@  discard block
 block discarded – undo
324 324
     }
325 325
 
326 326
     // Date validation
327
-    if (! empty($object->date_validation))
327
+    if (!empty($object->date_validation))
328 328
     {
329 329
         if ($usetable) print '<tr><td class="titlefield">';
330 330
         print $langs->trans("DateValidation");
331 331
         if ($usetable) print '</td><td>';
332 332
         else print ': ';
333 333
         print dol_print_date($object->date_validation, 'dayhour');
334
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
334
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
335 335
         if ($usetable) print '</td></tr>';
336 336
         else print '<br>';
337 337
     }
338 338
 
339 339
     // User approve (old method using already loaded object and not id is kept for backward compatibility)
340
-    if (! empty($object->user_approve) || ! empty($object->user_approve_id))
340
+    if (!empty($object->user_approve) || !empty($object->user_approve_id))
341 341
     {
342 342
         if ($usetable) print '<tr><td class="titlefield">';
343 343
         print $langs->trans("ApprovedBy");
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
         }
351 351
         else
352 352
         {
353
-            $userstatic=new User($db);
353
+            $userstatic = new User($db);
354 354
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
355 355
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
356 356
         	else print $langs->trans("Unknown");
@@ -360,26 +360,26 @@  discard block
 block discarded – undo
360 360
     }
361 361
 
362 362
     // Date approve
363
-    if (! empty($object->date_approve))
363
+    if (!empty($object->date_approve))
364 364
     {
365 365
         if ($usetable) print '<tr><td class="titlefield">';
366 366
         print $langs->trans("DateApprove");
367 367
         if ($usetable) print '</td><td>';
368 368
         else print ': ';
369 369
         print dol_print_date($object->date_approve, 'dayhour');
370
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
370
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
371 371
         if ($usetable) print '</td></tr>';
372 372
         else print '<br>';
373 373
     }
374 374
 
375 375
     // User approve
376
-    if (! empty($object->user_approve_id2))
376
+    if (!empty($object->user_approve_id2))
377 377
     {
378 378
         if ($usetable) print '<tr><td class="titlefield">';
379 379
         print $langs->trans("ApprovedBy");
380 380
         if ($usetable) print '</td><td>';
381 381
         else print ': ';
382
-        $userstatic=new User($db);
382
+        $userstatic = new User($db);
383 383
         $userstatic->fetch($object->user_approve_id2);
384 384
         if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
385 385
         else print $langs->trans("Unknown");
@@ -388,20 +388,20 @@  discard block
 block discarded – undo
388 388
     }
389 389
 
390 390
     // Date approve
391
-    if (! empty($object->date_approve2))
391
+    if (!empty($object->date_approve2))
392 392
     {
393 393
         if ($usetable) print '<tr><td class="titlefield">';
394 394
         print $langs->trans("DateApprove2");
395 395
         if ($usetable) print '</td><td>';
396 396
         else print ': ';
397 397
         print dol_print_date($object->date_approve2, 'dayhour');
398
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
398
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2 + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
399 399
         if ($usetable) print '</td></tr>';
400 400
         else print '<br>';
401 401
     }
402 402
 
403 403
     // User close
404
-    if (! empty($object->user_cloture))
404
+    if (!empty($object->user_cloture))
405 405
     {
406 406
         if ($usetable) print '<tr><td class="titlefield">';
407 407
         print $langs->trans("ClosedBy");
@@ -414,7 +414,7 @@  discard block
 block discarded – undo
414 414
         }
415 415
         else
416 416
         {
417
-            $userstatic=new User($db);
417
+            $userstatic = new User($db);
418 418
             $userstatic->fetch($object->user_cloture);
419 419
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
420 420
         	else print $langs->trans("Unknown");
@@ -424,20 +424,20 @@  discard block
 block discarded – undo
424 424
     }
425 425
 
426 426
     // Date close
427
-    if (! empty($object->date_cloture))
427
+    if (!empty($object->date_cloture))
428 428
     {
429 429
         if ($usetable) print '<tr><td class="titlefield">';
430 430
         print $langs->trans("DateClosing");
431 431
         if ($usetable) print '</td><td>';
432 432
         else print ': ';
433 433
         print dol_print_date($object->date_cloture, 'dayhour');
434
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
434
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
435 435
         if ($usetable) print '</td></tr>';
436 436
         else print '<br>';
437 437
     }
438 438
 
439 439
     // User conciliate
440
-    if (! empty($object->user_rappro))
440
+    if (!empty($object->user_rappro))
441 441
     {
442 442
         if ($usetable) print '<tr><td class="titlefield">';
443 443
         print $langs->trans("ConciliatedBy");
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
         }
451 451
         else
452 452
         {
453
-            $userstatic=new User($db);
453
+            $userstatic = new User($db);
454 454
             $userstatic->fetch($object->user_rappro);
455 455
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
456 456
         	else print $langs->trans("Unknown");
@@ -460,27 +460,27 @@  discard block
 block discarded – undo
460 460
     }
461 461
 
462 462
     // Date conciliate
463
-    if (! empty($object->date_rappro))
463
+    if (!empty($object->date_rappro))
464 464
     {
465 465
         if ($usetable) print '<tr><td class="titlefield">';
466 466
         print $langs->trans("DateConciliating");
467 467
         if ($usetable) print '</td><td>';
468 468
         else print ': ';
469 469
         print dol_print_date($object->date_rappro, 'dayhour');
470
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
470
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
471 471
         if ($usetable) print '</td></tr>';
472 472
         else print '<br>';
473 473
     }
474 474
 
475 475
     // Date send
476
-    if (! empty($object->date_envoi))
476
+    if (!empty($object->date_envoi))
477 477
     {
478 478
         if ($usetable) print '<tr><td class="titlefield">';
479 479
         print $langs->trans("DateLastSend");
480 480
         if ($usetable) print '</td><td>';
481 481
         else print ': ';
482 482
         print dol_print_date($object->date_envoi, 'dayhour');
483
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
483
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
484 484
         if ($usetable) print '</td></tr>';
485 485
         else print '<br>';
486 486
     }
@@ -499,8 +499,8 @@  discard block
 block discarded – undo
499 499
  */
500 500
 function dolAddEmailTrackId($email, $trackingid)
501 501
 {
502
-	$tmp=explode('@',$email);
503
-	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
502
+	$tmp = explode('@', $email);
503
+	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
504 504
 }
505 505
 
506 506
 /**
@@ -535,7 +535,7 @@  discard block
 block discarded – undo
535 535
  *  @param  int		$anchor		1: verify anchor is provided, 0: not verify anchor
536 536
  *	@return int					1=Check is OK, 0=Check is KO
537 537
  */
538
-function isValidUrl($url,$http=0,$pass=0,$port=0,$path=0,$query=0,$anchor=0)
538
+function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
539 539
 {
540 540
     $ValidUrl = 0;
541 541
     $urlregex = '';
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
     // HOSTNAME OR IP
550 550
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // x allowed (ex. http://localhost, http://routerlogin)
551 551
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+";  // x.x
552
-    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*";  // x ou x.xx (2 x ou plus)
552
+    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
553 553
     //use only one of the above
554 554
 
555 555
     // PORT
@@ -578,33 +578,33 @@  discard block
 block discarded – undo
578 578
  *	@param  integer	$http		1 = keep both http:// and https://, 0: remove http:// but not https://
579 579
  *	@return string				Cleaned url
580 580
  */
581
-function clean_url($url,$http=1)
581
+function clean_url($url, $http = 1)
582 582
 {
583 583
     // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
584 584
     // To include the minus sign in a char class, we must not escape it but put it at the end of the class
585 585
     // Also, there's no need of escape a dot sign in a class
586
-    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i',$url,$regs))
586
+    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs))
587 587
     {
588
-        $proto=$regs[1];
589
-        $domain=$regs[2];
590
-        $port=isset($regs[3])?$regs[3]:'';
588
+        $proto = $regs[1];
589
+        $domain = $regs[2];
590
+        $port = isset($regs[3]) ? $regs[3] : '';
591 591
         //print $url." -> ".$proto." - ".$domain." - ".$port;
592 592
         //$url = dol_string_nospecial(trim($url));
593 593
         $url = trim($url);
594 594
 
595 595
         // Si http: defini on supprime le http (Si https on ne supprime pas)
596
-        $newproto=$proto;
597
-        if ($http==0)
596
+        $newproto = $proto;
597
+        if ($http == 0)
598 598
         {
599
-            if (preg_match('/^http:[\\/]+/i',$url))
599
+            if (preg_match('/^http:[\\/]+/i', $url))
600 600
             {
601
-                $url = preg_replace('/^http:[\\/]+/i','',$url);
601
+                $url = preg_replace('/^http:[\\/]+/i', '', $url);
602 602
                 $newproto = '';
603 603
             }
604 604
         }
605 605
 
606 606
         // On passe le nom de domaine en minuscule
607
-        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
607
+        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
608 608
 
609 609
         return $CleanUrl;
610 610
     }
@@ -624,35 +624,35 @@  discard block
 block discarded – undo
624 624
  * 	@param 		bool		$displaytld			Display tld (default: true)
625 625
  * 	@return		string							Return email with hidden parts or '';
626 626
  */
627
-function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
627
+function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
628 628
 {
629
-	if(!isValidEmail($mail))return '';
629
+	if (!isValidEmail($mail))return '';
630 630
 	$tab = explode('@', $mail);
631
-	$tab2 = explode('.',$tab[1]);
631
+	$tab2 = explode('.', $tab[1]);
632 632
 	$string_replace = '';
633 633
 	$mail_name = $tab[0];
634 634
 	$mail_domaine = $tab2[0];
635 635
 	$mail_tld = '';
636 636
 
637 637
 	$nbofelem = count($tab2);
638
-	for($i=1; $i < $nbofelem && $displaytld; $i++)
638
+	for ($i = 1; $i < $nbofelem && $displaytld; $i++)
639 639
 	{
640 640
 		$mail_tld .= '.'.$tab2[$i];
641 641
 	}
642 642
 
643
-	for($i=0; $i < $nbreplace; $i++){
643
+	for ($i = 0; $i < $nbreplace; $i++) {
644 644
 		$string_replace .= $replace;
645 645
 	}
646 646
 
647
-	if(strlen($mail_name) > $nbdisplaymail){
647
+	if (strlen($mail_name) > $nbdisplaymail) {
648 648
 		$mail_name = substr($mail_name, 0, $nbdisplaymail);
649 649
 	}
650 650
 
651
-	if(strlen($mail_domaine) > $nbdisplaydomain){
652
-		$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
651
+	if (strlen($mail_domaine) > $nbdisplaydomain) {
652
+		$mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
653 653
 	}
654 654
 
655
-	return $mail_name . $string_replace . $mail_domaine . $mail_tld;
655
+	return $mail_name.$string_replace.$mail_domaine.$mail_tld;
656 656
 }
657 657
 
658 658
 
@@ -665,14 +665,14 @@  discard block
 block discarded – undo
665 665
  * 	@param	string	$tdoptions	Options for td
666 666
  * 	@return	string
667 667
  */
668
-function array2tr($data,$troptions='',$tdoptions='')
668
+function array2tr($data, $troptions = '', $tdoptions = '')
669 669
 {
670
-    $text = '<tr '.$troptions.'>' ;
671
-    foreach($data as $key => $item){
672
-        $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
670
+    $text = '<tr '.$troptions.'>';
671
+    foreach ($data as $key => $item) {
672
+        $text .= '<td '.$tdoptions.'>'.$item.'</td>';
673 673
     }
674
-    $text.= '</tr>' ;
675
-    return $text ;
674
+    $text .= '</tr>';
675
+    return $text;
676 676
 }
677 677
 
678 678
 /**
@@ -685,22 +685,22 @@  discard block
 block discarded – undo
685 685
  * 	@param	string	$tdoptions		Options for td
686 686
  * 	@return	string
687 687
  */
688
-function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
688
+function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
689 689
 {
690
-    $text='' ;
691
-    if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
692
-    foreach($data as $key => $item){
693
-        if(is_array($item)){
694
-            $text.=array2tr($item,$troptions,$tdoptions);
690
+    $text = '';
691
+    if ($tableMarkup) $text = '<table '.$tableoptions.'>';
692
+    foreach ($data as $key => $item) {
693
+        if (is_array($item)) {
694
+            $text .= array2tr($item, $troptions, $tdoptions);
695 695
         } else {
696
-            $text.= '<tr '.$troptions.'>' ;
697
-            $text.= '<td '.$tdoptions.'>'.$key.'</td>' ;
698
-            $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
699
-            $text.= '</tr>' ;
696
+            $text .= '<tr '.$troptions.'>';
697
+            $text .= '<td '.$tdoptions.'>'.$key.'</td>';
698
+            $text .= '<td '.$tdoptions.'>'.$item.'</td>';
699
+            $text .= '</tr>';
700 700
         }
701 701
     }
702
-    if($tableMarkup) $text.= '</table>' ;
703
-    return $text ;
702
+    if ($tableMarkup) $text .= '</table>';
703
+    return $text;
704 704
 }
705 705
 
706 706
 /**
@@ -719,19 +719,19 @@  discard block
 block discarded – undo
719 719
  * @param	int			$forceentity	Entity id to force
720 720
  * @return 	string						New value (numeric) or error message
721 721
  */
722
-function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true, $objuser=null, $forceentity=null)
722
+function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
723 723
 {
724
-    global $conf,$user;
724
+    global $conf, $user;
725 725
 
726
-    if (! is_object($objsoc)) $valueforccc=$objsoc;
727
-    else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
728
-    else $valueforccc=$objsoc->code_client;
726
+    if (!is_object($objsoc)) $valueforccc = $objsoc;
727
+    else if ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = $objsoc->code_fournisseur;
728
+    else $valueforccc = $objsoc->code_client;
729 729
 
730 730
     $sharetable = $table;
731 731
     if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
732 732
 
733 733
     // Clean parameters
734
-    if ($date == '') $date=dol_now();	// We use local year and month of PHP server to search numbers
734
+    if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers
735 735
     // but we should use local year and month of user
736 736
 
737 737
     // For debugging
@@ -741,132 +741,132 @@  discard block
 block discarded – undo
741 741
     //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
742 742
     //$date=dol_stringtotime('20130101');
743 743
 
744
-    $hasglobalcounter=false;
744
+    $hasglobalcounter = false;
745 745
     // Extract value for mask counter, mask raz and mask offset
746
-    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
746
+    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg))
747 747
     {
748
-        $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
749
-        $maskcounter=$reg[1];
750
-        $hasglobalcounter=true;
748
+        $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
749
+        $maskcounter = $reg[1];
750
+        $hasglobalcounter = true;
751 751
     }
752 752
     else
753 753
     {
754 754
         // setting some defaults so the rest of the code won't fail if there is a third party counter
755
-        $masktri='00000';
756
-        $maskcounter='00000';
755
+        $masktri = '00000';
756
+        $maskcounter = '00000';
757 757
     }
758 758
 
759
-    $maskraz=-1;
760
-    $maskoffset=0;
761
-    $resetEveryMonth=false;
759
+    $maskraz = -1;
760
+    $maskoffset = 0;
761
+    $resetEveryMonth = false;
762 762
     if (dol_strlen($maskcounter) < 3 && empty(Globals::$conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS))
763 763
             return 'ErrorCounterMustHaveMoreThan3Digits';
764 764
 
765 765
         // Extract value for third party mask counter
766
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
766
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
767 767
     {
768
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
769
-        $maskrefclient_maskclientcode=$regClientRef[1];
770
-        $maskrefclient_maskcounter=$regClientRef[2];
771
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
772
-        $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
773
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
774
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
768
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
769
+        $maskrefclient_maskclientcode = $regClientRef[1];
770
+        $maskrefclient_maskcounter = $regClientRef[2];
771
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
772
+        $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
773
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
774
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
775 775
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
776 776
     }
777
-    else $maskrefclient='';
777
+    else $maskrefclient = '';
778 778
 
779 779
     // fail if there is neither a global nor a third party counter
780
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
780
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
781 781
     {
782 782
         return 'ErrorBadMask';
783 783
     }
784 784
 
785 785
     // Extract value for third party type
786
-    if (preg_match('/\{(t+)\}/i',$mask,$regType))
786
+    if (preg_match('/\{(t+)\}/i', $mask, $regType))
787 787
     {
788
-        $masktype=$regType[1];
789
-        $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
790
-        $masktype_value=str_pad($masktype_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
788
+        $masktype = $regType[1];
789
+        $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask)
790
+        $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
791 791
     }
792 792
     else
793 793
     {
794
-    	$masktype='';
795
-    	$masktype_value='';
794
+    	$masktype = '';
795
+    	$masktype_value = '';
796 796
     }
797 797
 
798 798
     // Extract value for user
799
-    if (preg_match('/\{(u+)\}/i',$mask,$regType))
799
+    if (preg_match('/\{(u+)\}/i', $mask, $regType))
800 800
     {
801 801
     	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
802 802
     	if (is_object($objuser)) $lastname = $objuser->lastname;
803 803
 
804
-    	$maskuser=$regType[1];
805
-    	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
806
-    	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
804
+    	$maskuser = $regType[1];
805
+    	$maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
806
+    	$maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
807 807
     }
808 808
     else
809 809
     {
810
-    	$maskuser='';
811
-    	$maskuser_value='';
810
+    	$maskuser = '';
811
+    	$maskuser_value = '';
812 812
     }
813 813
 
814 814
     // Personalized field {XXX-1} à {XXX-9}
815
-    $maskperso=array();
816
-    $maskpersonew=array();
817
-    $tmpmask=$mask;
818
-    while (preg_match('/\{([A-Z]+)\-([1-9])\}/',$tmpmask,$regKey))
815
+    $maskperso = array();
816
+    $maskpersonew = array();
817
+    $tmpmask = $mask;
818
+    while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey))
819 819
     {
820
-        $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}';
821
-        $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
822
-        $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
820
+        $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
821
+        $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
822
+        $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
823 823
     }
824 824
 
825
-    if (strstr($mask,'user_extra_'))
825
+    if (strstr($mask, 'user_extra_'))
826 826
     {
827 827
 			$start = "{user_extra_";
828 828
 			$end = "\}";
829
-			$extra= get_string_between($mask, "user_extra_", "}");
830
-			if(!empty($user->array_options['options_'.$extra])){
831
-				$mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
829
+			$extra = get_string_between($mask, "user_extra_", "}");
830
+			if (!empty($user->array_options['options_'.$extra])) {
831
+				$mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
832 832
 			}
833 833
     }
834
-    $maskwithonlyymcode=$mask;
835
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
836
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
837
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
838
-    $maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
839
-    $maskwithonlyymcode=preg_replace('/\{(u+)\}/i',$maskuser_value,$maskwithonlyymcode);
840
-    foreach($maskperso as $key => $val)
834
+    $maskwithonlyymcode = $mask;
835
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
836
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
837
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
838
+    $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
839
+    $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
840
+    foreach ($maskperso as $key => $val)
841 841
     {
842
-        $maskwithonlyymcode=preg_replace('/'.preg_quote($val,'/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
842
+        $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
843 843
     }
844
-    $maskwithnocode=$maskwithonlyymcode;
845
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
846
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
847
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
848
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
844
+    $maskwithnocode = $maskwithonlyymcode;
845
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
846
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
847
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
848
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
849 849
     // Now maskwithnocode = 0000ddmmyyyyccc for example
850 850
     // and maskcounter    = 0000 for example
851 851
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
852 852
     //var_dump($reg);
853 853
 
854 854
     // If an offset is asked
855
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
856
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
855
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
856
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
857 857
 
858 858
     // Define $sqlwhere
859
-    $sqlwhere='';
860
-    $yearoffset=0;	// Use year of current $date by default
861
-    $yearoffsettype=false;		// false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
859
+    $sqlwhere = '';
860
+    $yearoffset = 0; // Use year of current $date by default
861
+    $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
862 862
 
863 863
     // If a restore to zero after a month is asked we check if there is already a value for this year.
864
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))	$yearoffsettype = preg_replace('/^@/','',$reg[2]);
865
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))	$yearoffsettype = preg_replace('/^@/','',$reg[3]);
864
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))	$yearoffsettype = preg_replace('/^@/', '', $reg[2]);
865
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))	$yearoffsettype = preg_replace('/^@/', '', $reg[3]);
866 866
 
867 867
     //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
868 868
     if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
869
-        $maskraz=$yearoffsettype; // For backward compatibility
869
+        $maskraz = $yearoffsettype; // For backward compatibility
870 870
     else if ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && Globals::$conf->global->SOCIETE_FISCAL_MONTH_START > 1))
871 871
             $maskraz = Globals::$conf->global->SOCIETE_FISCAL_MONTH_START;
872 872
         //print "maskraz=".$maskraz;	// -1=no reset
@@ -881,79 +881,79 @@  discard block
 block discarded – undo
881 881
         // Define posy, posm and reg
882 882
         if ($maskraz > 1)	// if reset is not first month, we need month and year into mask
883 883
         {
884
-            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
885
-            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
884
+            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
885
+            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
886 886
             else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
887 887
 
888 888
             if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
889 889
         }
890 890
         else // if reset is for a specific month in year, we need year
891 891
         {
892
-            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
893
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
894
-            else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
892
+            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
893
+        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
894
+            else if (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; }
895 895
             else return 'ErrorCantUseRazIfNoYearInMask';
896 896
         }
897 897
         // Define length
898
-        $yearlen = $posy?dol_strlen($reg[$posy]):0;
899
-        $monthlen = $posm?dol_strlen($reg[$posm]):0;
898
+        $yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
899
+        $monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
900 900
         // Define pos
901
-       	$yearpos = (dol_strlen($reg[1])+1);
902
-        $monthpos = ($yearpos+$yearlen);
901
+       	$yearpos = (dol_strlen($reg[1]) + 1);
902
+        $monthpos = ($yearpos + $yearlen);
903 903
         if ($posy == 3 && $posm == 2) {		// if month is before year
904
-          	$monthpos = (dol_strlen($reg[1])+1);
905
-           	$yearpos = ($monthpos+$monthlen);
904
+          	$monthpos = (dol_strlen($reg[1]) + 1);
905
+           	$yearpos = ($monthpos + $monthlen);
906 906
         }
907 907
         //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
908 908
 
909 909
         // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
910
-        $monthcomp=$maskraz;
911
-        $yearcomp=0;
910
+        $monthcomp = $maskraz;
911
+        $yearcomp = 0;
912 912
 
913
-        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
913
+        if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
914 914
         {
915
-        	$currentyear=date("Y", $date);
916
-        	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
917
-        	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
918
-        	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
915
+        	$currentyear = date("Y", $date);
916
+        	$fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
917
+        	$newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
918
+        	$nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1);
919 919
         	//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
920 920
 
921 921
         	// If after or equal of current fiscal date
922 922
         	if ($date >= $fiscaldate)
923 923
         	{
924 924
         		// If before of next new year date
925
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
925
+        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1;
926 926
         	}
927 927
         	// If after or equal of current new year date
928
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
928
+        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1;
929 929
         }
930 930
         // For backward compatibility
931
-        else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
931
+        else if (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; }	// If current month lower that month of return to zero, year is previous year
932 932
 
933
-        if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
934
-        elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
935
-        elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
933
+        if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
934
+        elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
935
+        elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
936 936
         if ($monthcomp > 1 && empty($resetEveryMonth))	// Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
937 937
         {
938
-            if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
939
-            elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
940
-
941
-            $sqlwhere.="(";
942
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
943
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
944
-            $sqlwhere.=" OR";
945
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
946
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
947
-            $sqlwhere.=')';
938
+            if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
939
+            elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
940
+
941
+            $sqlwhere .= "(";
942
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
943
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
944
+            $sqlwhere .= " OR";
945
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
946
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
947
+            $sqlwhere .= ')';
948 948
         }
949 949
 		else if ($resetEveryMonth)
950 950
 		{
951
-			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
952
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
951
+			$sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
952
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
953 953
 		}
954 954
         else   // reset is done on january
955 955
         {
956
-            $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
956
+            $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
957 957
         }
958 958
     }
959 959
     //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n";	// sqlwhere and yearcomp defined only if we ask a reset
@@ -962,49 +962,49 @@  discard block
 block discarded – undo
962 962
     // Define $sqlstring
963 963
     if (function_exists('mb_strrpos'))
964 964
     	{
965
-    	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
965
+    	$posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8');
966 966
 	}
967 967
 	else
968 968
 	{
969
-    	$posnumstart=strrpos($maskwithnocode,$maskcounter);
969
+    	$posnumstart = strrpos($maskwithnocode, $maskcounter);
970 970
 	}	// Pos of counter in final string (from 0 to ...)
971 971
     if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
972
-    $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
972
+    $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')';
973 973
 
974 974
     // Define $maskLike
975 975
     $maskLike = dol_string_nospecial($mask);
976
-    $maskLike = str_replace("%","_",$maskLike);
976
+    $maskLike = str_replace("%", "_", $maskLike);
977 977
     // Replace protected special codes with matching number of _ as wild card caracter
978
-    $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
979
-    $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
980
-    $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
981
-    $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
982
-    $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
983
-    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
984
-    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
985
-    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
986
-    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
987
-    foreach($maskperso as $key => $val)
978
+    $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
979
+    $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
980
+    $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
981
+    $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
982
+    $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
983
+    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
984
+    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
985
+    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
986
+    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
987
+    foreach ($maskperso as $key => $val)
988 988
     {
989
-    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
989
+    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
990 990
     }
991 991
 
992 992
     // Get counter in database
993
-    $counter=0;
993
+    $counter = 0;
994 994
     $sql = "SELECT MAX(".$sqlstring.") as val";
995
-    $sql.= " FROM ".MAIN_DB_PREFIX.$table;
996
-    $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
997
-	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
995
+    $sql .= " FROM ".MAIN_DB_PREFIX.$table;
996
+    $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
997
+	$sql .= " AND ".$field." NOT LIKE '(PROV%)'";
998 998
     if ($bentityon) // only if entity enable
999
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
1000
-    else if (! empty($forceentity))
1001
-    	$sql.= " AND entity IN (".$forceentity.")";
1002
-    if ($where) $sql.=$where;
1003
-    if ($sqlwhere) $sql.=' AND '.$sqlwhere;
999
+    	$sql .= " AND entity IN (".getEntity($sharetable).")";
1000
+    else if (!empty($forceentity))
1001
+    	$sql .= " AND entity IN (".$forceentity.")";
1002
+    if ($where) $sql .= $where;
1003
+    if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
1004 1004
 
1005 1005
     //print $sql.'<br>';
1006 1006
     dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1007
-    $resql=$db->query($sql);
1007
+    $resql = $db->query($sql);
1008 1008
     if ($resql)
1009 1009
     {
1010 1010
         $obj = $db->fetch_object($resql);
@@ -1013,10 +1013,10 @@  discard block
 block discarded – undo
1013 1013
     else dol_print_error($db);
1014 1014
 
1015 1015
     // Check if we must force counter to maskoffset
1016
-    if (empty($counter)) $counter=$maskoffset;
1017
-    else if (preg_match('/[^0-9]/i',$counter))
1016
+    if (empty($counter)) $counter = $maskoffset;
1017
+    else if (preg_match('/[^0-9]/i', $counter))
1018 1018
     {
1019
-    	$counter=0;
1019
+    	$counter = 0;
1020 1020
     	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1021 1021
     }
1022 1022
     else if ($counter < $maskoffset && empty(Globals::$conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST))
@@ -1024,36 +1024,36 @@  discard block
 block discarded – undo
1024 1024
 
1025 1025
         if ($mode == 'last')	// We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1026 1026
     {
1027
-        $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1027
+        $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1028 1028
 
1029 1029
         // Define $maskLike
1030 1030
         $maskLike = dol_string_nospecial($mask);
1031
-        $maskLike = str_replace("%","_",$maskLike);
1031
+        $maskLike = str_replace("%", "_", $maskLike);
1032 1032
         // Replace protected special codes with matching number of _ as wild card caracter
1033
-        $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
1034
-        $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
1035
-        $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
1036
-        $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
1037
-        $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
1038
-        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
1039
-        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1040
-        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1041
-        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1042
-
1043
-        $ref='';
1033
+        $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1034
+        $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1035
+        $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1036
+        $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1037
+        $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1038
+        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
1039
+        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1040
+        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1041
+        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1042
+
1043
+        $ref = '';
1044 1044
         $sql = "SELECT ".$field." as ref";
1045
-        $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1046
-        $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1047
-    	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1045
+        $sql .= " FROM ".MAIN_DB_PREFIX.$table;
1046
+        $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
1047
+    	$sql .= " AND ".$field." NOT LIKE '%PROV%'";
1048 1048
     	if ($bentityon) // only if entity enable
1049
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1050
-        else if (! empty($forceentity))
1051
-        	$sql.= " AND entity IN (".$forceentity.")";
1052
-        if ($where) $sql.=$where;
1053
-        if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1049
+        	$sql .= " AND entity IN (".getEntity($sharetable).")";
1050
+        else if (!empty($forceentity))
1051
+        	$sql .= " AND entity IN (".$forceentity.")";
1052
+        if ($where) $sql .= $where;
1053
+        if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
1054 1054
 
1055 1055
         dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1056
-        $resql=$db->query($sql);
1056
+        $resql = $db->query($sql);
1057 1057
         if ($resql)
1058 1058
         {
1059 1059
             $obj = $db->fetch_object($resql);
@@ -1061,7 +1061,7 @@  discard block
 block discarded – undo
1061 1061
         }
1062 1062
         else dol_print_error($db);
1063 1063
 
1064
-        $numFinal=$ref;
1064
+        $numFinal = $ref;
1065 1065
     }
1066 1066
     else if ($mode == 'next')
1067 1067
     {
@@ -1070,47 +1070,47 @@  discard block
 block discarded – undo
1070 1070
         // If value for $counter has a length higher than $maskcounter chars
1071 1071
         if ($counter >= pow(10, dol_strlen($maskcounter)))
1072 1072
         {
1073
-        	$counter='ErrorMaxNumberReachForThisMask';
1073
+        	$counter = 'ErrorMaxNumberReachForThisMask';
1074 1074
         }
1075 1075
 
1076
-        if (! empty($maskrefclient_maskcounter))
1076
+        if (!empty($maskrefclient_maskcounter))
1077 1077
         {
1078 1078
             //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
1079 1079
 
1080 1080
             // Define $sqlstring
1081
-            $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient));	// Pos of counter in final string (from 0 to ...)
1081
+            $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
1082 1082
             if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
1083
-            $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
1083
+            $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
1084 1084
             //print "x".$sqlstring;
1085 1085
 
1086 1086
             // Define $maskrefclient_maskLike
1087 1087
             $maskrefclient_maskLike = dol_string_nospecial($mask);
1088
-            $maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
1088
+            $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
1089 1089
             // Replace protected special codes with matching number of _ as wild card caracter
1090
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
1091
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
1092
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
1093
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
1094
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
1095
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
1096
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
1090
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
1091
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
1092
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
1093
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
1094
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
1095
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
1096
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
1097 1097
 
1098 1098
             // Get counter in database
1099
-            $maskrefclient_counter=0;
1099
+            $maskrefclient_counter = 0;
1100 1100
             $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
1101
-            $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
1101
+            $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
1102 1102
             //$sql.= " WHERE ".$field." not like '(%'";
1103
-            $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1103
+            $maskrefclient_sql .= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1104 1104
             if ($bentityon) // only if entity enable
1105
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1106
-            else if (! empty($forceentity))
1107
-            	$sql.= " AND entity IN (".$forceentity.")";
1108
-            if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1109
-            if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1110
-            $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1105
+            	$maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
1106
+            else if (!empty($forceentity))
1107
+            	$sql .= " AND entity IN (".$forceentity.")";
1108
+            if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask
1109
+            if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
1110
+            $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1111 1111
 
1112 1112
             dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
1113
-            $maskrefclient_resql=$db->query($maskrefclient_sql);
1113
+            $maskrefclient_resql = $db->query($maskrefclient_sql);
1114 1114
             if ($maskrefclient_resql)
1115 1115
             {
1116 1116
                 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
             }
1119 1119
             else dol_print_error($db);
1120 1120
 
1121
-            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1121
+            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset;
1122 1122
 			$maskrefclient_counter++;
1123 1123
         }
1124 1124
 
@@ -1126,54 +1126,54 @@  discard block
 block discarded – undo
1126 1126
         $numFinal = $mask;
1127 1127
 
1128 1128
         // We replace special codes except refclient
1129
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1129
+		if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1130 1130
 		{
1131
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1132
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1133
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1131
+	        $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
1132
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
1133
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
1134 1134
 		}
1135 1135
 		else	// we want yyyy to be current year
1136 1136
 		{
1137
-        	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1138
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1139
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1137
+        	$numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
1138
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
1139
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
1140 1140
 		}
1141
-        $numFinal = preg_replace('/\{mm\}/i',  date("m",$date), $numFinal);
1142
-        $numFinal = preg_replace('/\{dd\}/i',  date("d",$date), $numFinal);
1141
+        $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
1142
+        $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
1143 1143
 
1144 1144
         // Now we replace the counter
1145
-        $maskbefore='{'.$masktri.'}';
1146
-        $maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1145
+        $maskbefore = '{'.$masktri.'}';
1146
+        $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1147 1147
         //print 'x'.$maskbefore.'-'.$maskafter.'y';
1148
-        $numFinal = str_replace($maskbefore,$maskafter,$numFinal);
1148
+        $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
1149 1149
 
1150 1150
         // Now we replace the refclient
1151 1151
         if ($maskrefclient)
1152 1152
         {
1153 1153
             //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1154
-            $maskrefclient_maskbefore='{'.$maskrefclient.'}';
1155
-            $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
1156
-            $numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
1154
+            $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
1155
+            $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
1156
+            $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal);
1157 1157
         }
1158 1158
 
1159 1159
         // Now we replace the type
1160 1160
         if ($masktype)
1161 1161
         {
1162
-            $masktype_maskbefore='{'.$masktype.'}';
1163
-            $masktype_maskafter=$masktype_value;
1164
-            $numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
1162
+            $masktype_maskbefore = '{'.$masktype.'}';
1163
+            $masktype_maskafter = $masktype_value;
1164
+            $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
1165 1165
         }
1166 1166
 
1167 1167
         // Now we replace the user
1168 1168
         if ($maskuser)
1169 1169
         {
1170
-        	$maskuser_maskbefore='{'.$maskuser.'}';
1171
-        	$maskuser_maskafter=$maskuser_value;
1172
-        	$numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1170
+        	$maskuser_maskbefore = '{'.$maskuser.'}';
1171
+        	$maskuser_maskafter = $maskuser_value;
1172
+        	$numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
1173 1173
         }
1174 1174
     }
1175 1175
 
1176
-    dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
1176
+    dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
1177 1177
     return $numFinal;
1178 1178
 }
1179 1179
 
@@ -1188,11 +1188,11 @@  discard block
 block discarded – undo
1188 1188
 function get_string_between($string, $start, $end)
1189 1189
 {
1190 1190
     $string = " ".$string;
1191
-     $ini = strpos($string,$start);
1191
+     $ini = strpos($string, $start);
1192 1192
      if ($ini == 0) return "";
1193 1193
      $ini += strlen($start);
1194
-     $len = strpos($string,$end,$ini) - $ini;
1195
-     return substr($string,$ini,$len);
1194
+     $len = strpos($string, $end, $ini) - $ini;
1195
+     return substr($string, $ini, $len);
1196 1196
 }
1197 1197
 
1198 1198
 /**
@@ -1202,78 +1202,78 @@  discard block
 block discarded – undo
1202 1202
  * @param 	string	$value		Value
1203 1203
  * @return	int|string		    <0 or error string if KO, 0 if OK
1204 1204
  */
1205
-function check_value($mask,$value)
1205
+function check_value($mask, $value)
1206 1206
 {
1207
-    $result=0;
1207
+    $result = 0;
1208 1208
 
1209
-    $hasglobalcounter=false;
1209
+    $hasglobalcounter = false;
1210 1210
     // Extract value for mask counter, mask raz and mask offset
1211
-    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$mask,$reg))
1211
+    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg))
1212 1212
     {
1213
-        $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
1214
-        $maskcounter=$reg[1];
1215
-        $hasglobalcounter=true;
1213
+        $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
1214
+        $maskcounter = $reg[1];
1215
+        $hasglobalcounter = true;
1216 1216
     }
1217 1217
     else
1218 1218
     {
1219 1219
         // setting some defaults so the rest of the code won't fail if there is a third party counter
1220
-        $masktri='00000';
1221
-        $maskcounter='00000';
1220
+        $masktri = '00000';
1221
+        $maskcounter = '00000';
1222 1222
     }
1223 1223
 
1224
-    $maskraz=-1;
1225
-    $maskoffset=0;
1224
+    $maskraz = -1;
1225
+    $maskoffset = 0;
1226 1226
     if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1227 1227
 
1228 1228
     // Extract value for third party mask counter
1229
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
1229
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
1230 1230
     {
1231
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
1232
-        $maskrefclient_maskclientcode=$regClientRef[1];
1233
-        $maskrefclient_maskcounter=$regClientRef[2];
1234
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
1235
-        $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
1236
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1237
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
1231
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
1232
+        $maskrefclient_maskclientcode = $regClientRef[1];
1233
+        $maskrefclient_maskcounter = $regClientRef[2];
1234
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
1235
+        $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
1236
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1237
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
1238 1238
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1239 1239
     }
1240
-    else $maskrefclient='';
1240
+    else $maskrefclient = '';
1241 1241
 
1242 1242
     // fail if there is neither a global nor a third party counter
1243
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
1243
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
1244 1244
     {
1245 1245
         return 'ErrorBadMask';
1246 1246
     }
1247 1247
 
1248
-    $maskwithonlyymcode=$mask;
1249
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$maskcounter,$maskwithonlyymcode);
1250
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
1251
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
1252
-    $maskwithnocode=$maskwithonlyymcode;
1253
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
1254
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
1255
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
1256
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
1248
+    $maskwithonlyymcode = $mask;
1249
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1250
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1251
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1252
+    $maskwithnocode = $maskwithonlyymcode;
1253
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1254
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1255
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1256
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1257 1257
     // Now maskwithnocode = 0000ddmmyyyyccc for example
1258 1258
     // and maskcounter    = 0000 for example
1259 1259
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1260 1260
 
1261 1261
     // If an offset is asked
1262
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
1263
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1262
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1263
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1264 1264
 
1265 1265
     // Define $sqlwhere
1266 1266
 
1267 1267
     // If a restore to zero after a month is asked we check if there is already a value for this year.
1268
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))  $maskraz=preg_replace('/^@/','',$reg[2]);
1269
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))  $maskraz=preg_replace('/^@/','',$reg[3]);
1268
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))  $maskraz = preg_replace('/^@/', '', $reg[2]);
1269
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))  $maskraz = preg_replace('/^@/', '', $reg[3]);
1270 1270
     if ($maskraz >= 0)
1271 1271
     {
1272 1272
         if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1273 1273
 
1274 1274
         // Define reg
1275
-        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1276
-        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
1275
+        if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1276
+        if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask';
1277 1277
         //print "x".$maskwithonlyymcode." ".$maskraz;
1278 1278
     }
1279 1279
     //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
@@ -1282,8 +1282,8 @@  discard block
 block discarded – undo
1282 1282
     //
1283 1283
 
1284 1284
     // Check length
1285
-    $len=dol_strlen($maskwithnocode);
1286
-    if (dol_strlen($value) != $len) $result=-1;
1285
+    $len = dol_strlen($maskwithnocode);
1286
+    if (dol_strlen($value) != $len) $result = -1;
1287 1287
 
1288 1288
     // Define $maskLike
1289 1289
     /* seems not used
@@ -1299,7 +1299,7 @@  discard block
 block discarded – undo
1299 1299
     if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
1300 1300
 	*/
1301 1301
 
1302
-    dol_syslog("functions2::check_value result=".$result,LOG_DEBUG);
1302
+    dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
1303 1303
     return $result;
1304 1304
 }
1305 1305
 
@@ -1311,13 +1311,13 @@  discard block
 block discarded – undo
1311 1311
  *	@param   boolean	$upper		Convert to tupper
1312 1312
  *	@return  string					x
1313 1313
  */
1314
-function binhex($bin, $pad=false, $upper=false)
1314
+function binhex($bin, $pad = false, $upper = false)
1315 1315
 {
1316
-    $last = dol_strlen($bin)-1;
1317
-    for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
1316
+    $last = dol_strlen($bin) - 1;
1317
+    for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); }
1318 1318
     $x = dechex($x);
1319
-    if($pad){ while(dol_strlen($x) < intval(dol_strlen($bin))/4){ $x = "0$x"; } }
1320
-    if($upper){ $x = strtoupper($x); }
1319
+    if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } }
1320
+    if ($upper) { $x = strtoupper($x); }
1321 1321
     return $x;
1322 1322
 }
1323 1323
 
@@ -1329,11 +1329,11 @@  discard block
 block discarded – undo
1329 1329
  */
1330 1330
 function hexbin($hexa)
1331 1331
 {
1332
-    $bin='';
1332
+    $bin = '';
1333 1333
     $strLength = dol_strlen($hexa);
1334
-    for($i=0;$i<$strLength;$i++)
1334
+    for ($i = 0; $i < $strLength; $i++)
1335 1335
     {
1336
-        $bin.=str_pad(decbin(hexdec($hexa{$i})),4,'0',STR_PAD_LEFT);
1336
+        $bin .= str_pad(decbin(hexdec($hexa{$i})), 4, '0', STR_PAD_LEFT);
1337 1337
     }
1338 1338
     return $bin;
1339 1339
 }
@@ -1346,9 +1346,9 @@  discard block
 block discarded – undo
1346 1346
  */
1347 1347
 function numero_semaine($time)
1348 1348
 {
1349
-    $stime = strftime('%Y-%m-%d',$time);
1349
+    $stime = strftime('%Y-%m-%d', $time);
1350 1350
 
1351
-    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i',$stime,$reg))
1351
+    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg))
1352 1352
     {
1353 1353
         // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
1354 1354
         $annee = $reg[1];
@@ -1364,47 +1364,47 @@  discard block
 block discarded – undo
1364 1364
      */
1365 1365
 
1366 1366
     // Definition du Jeudi de la semaine
1367
-    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
1368
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1369
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
1370
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1371
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
1372
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1367
+    if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche
1368
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
1369
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi
1370
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
1371
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi
1372
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
1373 1373
     else // Jeudi
1374
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1374
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
1375 1375
 
1376 1376
     // Definition du premier Jeudi de l'annee
1377
-    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
1377
+    if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche
1378 1378
     {
1379
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1379
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
1380 1380
     }
1381
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
1381
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi
1382 1382
     {
1383
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1383
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
1384 1384
     }
1385
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
1385
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi
1386 1386
     {
1387
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1387
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
1388 1388
     }
1389 1389
     else // Jeudi
1390 1390
     {
1391
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
1391
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine));
1392 1392
     }
1393 1393
 
1394 1394
     // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
1395
-    $numeroSemaine =     (
1395
+    $numeroSemaine = (
1396 1396
     (
1397
-    date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine)))
1397
+    date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine)))
1398 1398
     -
1399
-    date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee)))
1399
+    date("z", mktime(12, 0, 0, date("m", $premierJeudiAnnee), date("d", $premierJeudiAnnee), date("Y", $premierJeudiAnnee)))
1400 1400
     ) / 7
1401 1401
     ) + 1;
1402 1402
 
1403 1403
     // Cas particulier de la semaine 53
1404
-    if ($numeroSemaine==53)
1404
+    if ($numeroSemaine == 53)
1405 1405
     {
1406 1406
         // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
1407
-        if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365))
1407
+        if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365))
1408 1408
         {
1409 1409
             $numeroSemaine = 53;
1410 1410
         }
@@ -1416,7 +1416,7 @@  discard block
 block discarded – undo
1416 1416
 
1417 1417
     //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
1418 1418
 
1419
-    return sprintf("%02d",$numeroSemaine);
1419
+    return sprintf("%02d", $numeroSemaine);
1420 1420
 }
1421 1421
 
1422 1422
 /**
@@ -1427,26 +1427,26 @@  discard block
 block discarded – undo
1427 1427
  *	@param  int		$to_unit   		Nouvelle unite  en puissance de 10
1428 1428
  *	@return float	        		Masse convertie
1429 1429
  */
1430
-function weight_convert($weight,&$from_unit,$to_unit)
1430
+function weight_convert($weight, &$from_unit, $to_unit)
1431 1431
 {
1432 1432
     /* Pour convertire 320 gr en Kg appeler
1433 1433
      *  $f = -3
1434 1434
      *  weigh_convert(320, $f, 0) retournera 0.32
1435 1435
      *
1436 1436
      */
1437
-    while ($from_unit  <> $to_unit)
1437
+    while ($from_unit <> $to_unit)
1438 1438
     {
1439 1439
         if ($from_unit > $to_unit)
1440 1440
         {
1441 1441
             $weight = $weight * 10;
1442 1442
             $from_unit = $from_unit - 1;
1443
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1443
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1444 1444
         }
1445 1445
         if ($from_unit < $to_unit)
1446 1446
         {
1447 1447
             $weight = $weight / 10;
1448 1448
             $from_unit = $from_unit + 1;
1449
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1449
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1450 1450
         }
1451 1451
     }
1452 1452
 
@@ -1473,21 +1473,21 @@  discard block
 block discarded – undo
1473 1473
 
1474 1474
     // We remove old parameters for all keys in $tab
1475 1475
     $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
1476
-    $sql.= " WHERE fk_user = ".$user->id;
1477
-    $sql .= " AND entity = " . Globals::$conf->entity;
1478
-        $sql.= " AND param in (";
1479
-    $i=0;
1476
+    $sql .= " WHERE fk_user = ".$user->id;
1477
+    $sql .= " AND entity = ".Globals::$conf->entity;
1478
+        $sql .= " AND param in (";
1479
+    $i = 0;
1480 1480
     foreach ($tab as $key => $value)
1481 1481
     {
1482
-        if ($i > 0) $sql.=',';
1483
-        $sql.="'".$db->escape($key)."'";
1482
+        if ($i > 0) $sql .= ',';
1483
+        $sql .= "'".$db->escape($key)."'";
1484 1484
         $i++;
1485 1485
     }
1486
-    $sql.= ")";
1486
+    $sql .= ")";
1487 1487
     dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1488 1488
 
1489
-    $resql=$db->query($sql);
1490
-    if (! $resql)
1489
+    $resql = $db->query($sql);
1490
+    if (!$resql)
1491 1491
     {
1492 1492
         dol_print_error($db);
1493 1493
         $db->rollback();
@@ -1500,12 +1500,12 @@  discard block
 block discarded – undo
1500 1500
         if ($value)
1501 1501
         {
1502 1502
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
1503
-            $sql .= " VALUES (" . $user->id . "," . Globals::$conf->entity . ",";
1504
-                $sql.= " '".$db->escape($key)."','".$db->escape($value)."')";
1503
+            $sql .= " VALUES (".$user->id.",".Globals::$conf->entity.",";
1504
+                $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
1505 1505
 
1506 1506
             dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1507
-            $result=$db->query($sql);
1508
-            if (! $result)
1507
+            $result = $db->query($sql);
1508
+            if (!$result)
1509 1509
             {
1510 1510
                 dol_print_error($db);
1511 1511
                 $db->rollback();
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
  *	@param	Translate	$langs			Output language
1532 1532
  *	@return	string						Formated reduction
1533 1533
  */
1534
-function dol_print_reduction($reduction,$langs)
1534
+function dol_print_reduction($reduction, $langs)
1535 1535
 {
1536 1536
     $string = '';
1537 1537
     if ($reduction == 100)
@@ -1540,7 +1540,7 @@  discard block
 block discarded – undo
1540 1540
     }
1541 1541
     else
1542 1542
     {
1543
-    	$string = vatrate($reduction,true);
1543
+    	$string = vatrate($reduction, true);
1544 1544
     }
1545 1545
 
1546 1546
     return $string;
@@ -1554,7 +1554,7 @@  discard block
 block discarded – undo
1554 1554
  */
1555 1555
 function version_os()
1556 1556
 {
1557
-    $osversion=php_uname();
1557
+    $osversion = php_uname();
1558 1558
     return $osversion;
1559 1559
 }
1560 1560
 
@@ -1598,18 +1598,18 @@  discard block
 block discarded – undo
1598 1598
  *  @param  int		    $maxfilenamelength  Max length of value to show
1599 1599
  * 	@return	mixed			    			0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
1600 1600
  */
1601
-function getListOfModels($db,$type,$maxfilenamelength=0)
1601
+function getListOfModels($db, $type, $maxfilenamelength = 0)
1602 1602
 {
1603
-    global $conf,$langs;
1604
-    $liste=array();
1605
-    $found=0;
1606
-    $dirtoscan='';
1603
+    global $conf, $langs;
1604
+    $liste = array();
1605
+    $found = 0;
1606
+    $dirtoscan = '';
1607 1607
 
1608 1608
     $sql = "SELECT nom as id, nom as lib, libelle as label, description as description";
1609
-    $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
1610
-    $sql.= " WHERE type = '".$type."'";
1611
-    $sql .= " AND entity IN (0," . Globals::$conf->entity . ")";
1612
-        $sql.= " ORDER BY description DESC";
1609
+    $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
1610
+    $sql .= " WHERE type = '".$type."'";
1611
+    $sql .= " AND entity IN (0,".Globals::$conf->entity.")";
1612
+        $sql .= " ORDER BY description DESC";
1613 1613
 
1614 1614
     dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
1615 1615
     $resql = $db->query($sql);
@@ -1619,48 +1619,48 @@  discard block
 block discarded – undo
1619 1619
         $i = 0;
1620 1620
         while ($i < $num)
1621 1621
         {
1622
-            $found=1;
1622
+            $found = 1;
1623 1623
 
1624 1624
             $obj = $db->fetch_object($resql);
1625 1625
 
1626 1626
             // If this generation module needs to scan a directory, then description field is filled
1627 1627
             // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1628
-            if (! empty($obj->description))	// A list of directories to scan is defined
1628
+            if (!empty($obj->description))	// A list of directories to scan is defined
1629 1629
             {
1630 1630
                 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1631 1631
 
1632
-                $const=$obj->description;
1632
+                $const = $obj->description;
1633 1633
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim(Globals::$conf->global->$const));
1634 1634
                     $dirtoscan = preg_replace('/[\r\n]+/', ',', trim(Globals::$conf->global->$const));
1635 1635
 
1636
-                    $listoffiles=array();
1636
+                    $listoffiles = array();
1637 1637
 
1638 1638
                 // Now we add models found in directories scanned
1639
-                $listofdir=explode(',',$dirtoscan);
1640
-                foreach($listofdir as $key=>$tmpdir)
1639
+                $listofdir = explode(',', $dirtoscan);
1640
+                foreach ($listofdir as $key=>$tmpdir)
1641 1641
                 {
1642
-                    $tmpdir=trim($tmpdir);
1643
-                    $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
1644
-                    if (! $tmpdir) { unset($listofdir[$key]); continue; }
1642
+                    $tmpdir = trim($tmpdir);
1643
+                    $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
1644
+                    if (!$tmpdir) { unset($listofdir[$key]); continue; }
1645 1645
                     if (is_dir($tmpdir))
1646 1646
                     {
1647 1647
 			// all type of template is allowed
1648
-			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1649
-                        if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1648
+			$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1649
+                        if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
1650 1650
                     }
1651 1651
                 }
1652 1652
 
1653 1653
                 if (count($listoffiles))
1654 1654
                 {
1655
-                    foreach($listoffiles as $record)
1655
+                    foreach ($listoffiles as $record)
1656 1656
                     {
1657
-                        $max=($maxfilenamelength?$maxfilenamelength:28);
1658
-                        $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
1657
+                        $max = ($maxfilenamelength ? $maxfilenamelength : 28);
1658
+                        $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
1659 1659
                     }
1660 1660
                 }
1661 1661
                 else
1662 1662
                 {
1663
-                    $liste[0]=$obj->label.': '.$langs->trans("None");
1663
+                    $liste[0] = $obj->label.': '.$langs->trans("None");
1664 1664
                 }
1665 1665
             }
1666 1666
             else
@@ -1669,14 +1669,14 @@  discard block
 block discarded – undo
1669 1669
                 {
1670 1670
                     global $_Avery_Labels;
1671 1671
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1672
-                    foreach($_Avery_Labels as $key => $val)
1672
+                    foreach ($_Avery_Labels as $key => $val)
1673 1673
                     {
1674
-                        $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
1674
+                        $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->lib).' '.$val['name'];
1675 1675
                     }
1676 1676
                 }
1677 1677
                 else    // Common usage
1678 1678
                 {
1679
-                    $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
1679
+                    $liste[$obj->id] = $obj->label ? $obj->label : $obj->lib;
1680 1680
                 }
1681 1681
             }
1682 1682
             $i++;
@@ -1705,10 +1705,10 @@  discard block
 block discarded – undo
1705 1705
 	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1706 1706
 
1707 1707
 		// Then we test if it is a private range
1708
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1708
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1709 1709
 
1710 1710
 		// Then we test if it is a reserved range
1711
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1711
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1712 1712
 
1713 1713
 		return 1;
1714 1714
 	}
@@ -1723,12 +1723,12 @@  discard block
 block discarded – undo
1723 1723
  *  @param  string		$firstname		Firstname
1724 1724
  *	@return	string						Login
1725 1725
  */
1726
-function dol_buildlogin($lastname,$firstname)
1726
+function dol_buildlogin($lastname, $firstname)
1727 1727
 {
1728
-    $login=strtolower(dol_string_unaccent($firstname));
1729
-    $login.=($login?'.':'');
1730
-    $login.=strtolower(dol_string_unaccent($lastname));
1731
-    $login=dol_string_nospecial($login,''); // For special names
1728
+    $login = strtolower(dol_string_unaccent($firstname));
1729
+    $login .= ($login ? '.' : '');
1730
+    $login .= strtolower(dol_string_unaccent($lastname));
1731
+    $login = dol_string_nospecial($login, ''); // For special names
1732 1732
     return $login;
1733 1733
 }
1734 1734
 
@@ -1741,18 +1741,18 @@  discard block
 block discarded – undo
1741 1741
 {
1742 1742
     global $conf;
1743 1743
 
1744
-    $params=array();
1744
+    $params = array();
1745 1745
     $proxyuse = (empty(Globals::$conf->global->MAIN_PROXY_USE) ? false : true);
1746 1746
         $proxyhost = (empty(Globals::$conf->global->MAIN_PROXY_USE) ? false : Globals::$conf->global->MAIN_PROXY_HOST);
1747 1747
         $proxyport = (empty(Globals::$conf->global->MAIN_PROXY_USE) ? false : Globals::$conf->global->MAIN_PROXY_PORT);
1748 1748
         $proxyuser = (empty(Globals::$conf->global->MAIN_PROXY_USE) ? false : Globals::$conf->global->MAIN_PROXY_USER);
1749 1749
         $proxypass = (empty(Globals::$conf->global->MAIN_PROXY_USE) ? false : Globals::$conf->global->MAIN_PROXY_PASS);
1750
-        $timeout = (empty(Globals::$conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : Globals::$conf->global->MAIN_USE_CONNECT_TIMEOUT);               // Connection timeout
1751
-        $response_timeout = (empty(Globals::$conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : Globals::$conf->global->MAIN_USE_RESPONSE_TIMEOUT);    // Response timeout
1750
+        $timeout = (empty(Globals::$conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : Globals::$conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
1751
+        $response_timeout = (empty(Globals::$conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : Globals::$conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
1752 1752
         //print extension_loaded('soap');
1753 1753
     if ($proxyuse)
1754 1754
     {
1755
-        $params=array('connection_timeout'=>$timeout,
1755
+        $params = array('connection_timeout'=>$timeout,
1756 1756
                       'response_timeout'=>$response_timeout,
1757 1757
                       'proxy_use'      => 1,
1758 1758
                       'proxy_host'     => $proxyhost,
@@ -1764,7 +1764,7 @@  discard block
 block discarded – undo
1764 1764
     }
1765 1765
     else
1766 1766
     {
1767
-        $params=array('connection_timeout'=>$timeout,
1767
+        $params = array('connection_timeout'=>$timeout,
1768 1768
                       'response_timeout'=>$response_timeout,
1769 1769
                       'proxy_use'      => 0,
1770 1770
                       'proxy_host'     => false,
@@ -1787,15 +1787,15 @@  discard block
 block discarded – undo
1787 1787
  * @param 	string	$option			More options
1788 1788
  * @return	string					URL of link to object id/type
1789 1789
  */
1790
-function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
1790
+function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
1791 1791
 {
1792 1792
 	global $db, $conf, $langs;
1793 1793
 
1794
-	$ret='';
1794
+	$ret = '';
1795 1795
 
1796 1796
 	// Parse element/subelement (ex: project_task)
1797 1797
 	$module = $element = $subelement = $objecttype;
1798
-	if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1798
+	if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
1799 1799
 	{
1800 1800
 		$module = $element = $regs[1];
1801 1801
 		$subelement = $regs[2];
@@ -1806,18 +1806,18 @@  discard block
 block discarded – undo
1806 1806
 	// To work with non standard path
1807 1807
 	if ($objecttype == 'facture' || $objecttype == 'invoice') {
1808 1808
 		$classpath = 'compta/facture/class';
1809
-		$module='facture';
1810
-		$subelement='facture';
1809
+		$module = 'facture';
1810
+		$subelement = 'facture';
1811 1811
 	}
1812 1812
 	if ($objecttype == 'commande' || $objecttype == 'order') {
1813 1813
 		$classpath = 'commande/class';
1814
-		$module='commande';
1815
-		$subelement='commande';
1814
+		$module = 'commande';
1815
+		$subelement = 'commande';
1816 1816
 	}
1817
-	if ($objecttype == 'propal')  {
1817
+	if ($objecttype == 'propal') {
1818 1818
 		$classpath = 'comm/propal/class';
1819 1819
 	}
1820
-	if ($objecttype == 'supplier_proposal')  {
1820
+	if ($objecttype == 'supplier_proposal') {
1821 1821
 		$classpath = 'supplier_proposal/class';
1822 1822
 	}
1823 1823
 	if ($objecttype == 'shipping') {
@@ -1832,33 +1832,33 @@  discard block
 block discarded – undo
1832 1832
 	}
1833 1833
 	if ($objecttype == 'contract') {
1834 1834
 		$classpath = 'contrat/class';
1835
-		$module='contrat';
1836
-		$subelement='contrat';
1835
+		$module = 'contrat';
1836
+		$subelement = 'contrat';
1837 1837
 	}
1838 1838
 	if ($objecttype == 'member') {
1839 1839
 		$classpath = 'adherents/class';
1840
-		$module='adherent';
1841
-		$subelement='adherent';
1840
+		$module = 'adherent';
1841
+		$subelement = 'adherent';
1842 1842
 	}
1843 1843
 	if ($objecttype == 'cabinetmed_cons') {
1844 1844
 		$classpath = 'cabinetmed/class';
1845
-		$module='cabinetmed';
1846
-		$subelement='cabinetmedcons';
1845
+		$module = 'cabinetmed';
1846
+		$subelement = 'cabinetmedcons';
1847 1847
 	}
1848 1848
 	if ($objecttype == 'fichinter') {
1849 1849
 		$classpath = 'fichinter/class';
1850
-		$module='ficheinter';
1851
-		$subelement='fichinter';
1850
+		$module = 'ficheinter';
1851
+		$subelement = 'fichinter';
1852 1852
 	}
1853 1853
 	if ($objecttype == 'task') {
1854 1854
 		$classpath = 'projet/class';
1855
-		$module='projet';
1856
-		$subelement='task';
1855
+		$module = 'projet';
1856
+		$subelement = 'task';
1857 1857
 	}
1858 1858
 	if ($objecttype == 'stock') {
1859 1859
 		$classpath = 'product/stock/class';
1860
-		$module='stock';
1861
-		$subelement='stock';
1860
+		$module = 'stock';
1861
+		$subelement = 'stock';
1862 1862
 	}
1863 1863
 
1864 1864
 	//print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
@@ -1866,33 +1866,33 @@  discard block
 block discarded – undo
1866 1866
 	$classfile = strtolower($subelement); $classname = ucfirst($subelement);
1867 1867
 	if ($objecttype == 'invoice_supplier') {
1868 1868
 		$classfile = 'fournisseur.facture';
1869
-		$classname='FactureFournisseur';
1869
+		$classname = 'FactureFournisseur';
1870 1870
 		$classpath = 'fourn/class';
1871
-		$module='fournisseur';
1871
+		$module = 'fournisseur';
1872 1872
 	}
1873
-	elseif ($objecttype == 'order_supplier')   {
1873
+	elseif ($objecttype == 'order_supplier') {
1874 1874
 		$classfile = 'fournisseur.commande';
1875
-		$classname='CommandeFournisseur';
1875
+		$classname = 'CommandeFournisseur';
1876 1876
 		$classpath = 'fourn/class';
1877
-		$module='fournisseur';
1877
+		$module = 'fournisseur';
1878 1878
 	}
1879
-	elseif ($objecttype == 'stock')   {
1879
+	elseif ($objecttype == 'stock') {
1880 1880
 		$classpath = 'product/stock/class';
1881
-		$classfile='entrepot';
1882
-		$classname='Entrepot';
1881
+		$classfile = 'entrepot';
1882
+		$classname = 'Entrepot';
1883 1883
 	}
1884 1884
 	if (!empty(Globals::$conf->$module->enabled)) {
1885
-		$res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1885
+		$res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1886 1886
 		if ($res)
1887 1887
 		{
1888 1888
 			if (class_exists($classname))
1889 1889
 			{
1890 1890
 				$object = new $classname($db);
1891
-				$res=$object->fetch($objectid);
1891
+				$res = $object->fetch($objectid);
1892 1892
 				if ($res > 0) {
1893
-					$ret=$object->getNomUrl($withpicto,$option);
1894
-				} elseif($res==0) {
1895
-					$ret=$langs->trans('Deleted');
1893
+					$ret = $object->getNomUrl($withpicto, $option);
1894
+				} elseif ($res == 0) {
1895
+					$ret = $langs->trans('Deleted');
1896 1896
 				}
1897 1897
 				unset($object);
1898 1898
 			}
@@ -1913,12 +1913,12 @@  discard block
 block discarded – undo
1913 1913
  */
1914 1914
 function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
1915 1915
 {
1916
-	$totalnb=0;
1917
-	$listofid=array();
1918
-	$listofparentid=array();
1916
+	$totalnb = 0;
1917
+	$listofid = array();
1918
+	$listofparentid = array();
1919 1919
 
1920 1920
 	// Get list of all id in array listofid and all parents in array listofparentid
1921
-	$sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1921
+	$sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1922 1922
 	$resql = $db->query($sql);
1923 1923
 	if ($resql)
1924 1924
 	{
@@ -1927,8 +1927,8 @@  discard block
 block discarded – undo
1927 1927
 		while ($i < $num)
1928 1928
 		{
1929 1929
 			$obj = $db->fetch_object($resql);
1930
-			$listofid[]=$obj->rowid;
1931
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1930
+			$listofid[] = $obj->rowid;
1931
+			if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id;
1932 1932
 			$i++;
1933 1933
 		}
1934 1934
 	}
@@ -1942,78 +1942,78 @@  discard block
 block discarded – undo
1942 1942
 		print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1943 1943
 
1944 1944
 		// Check loops on each other
1945
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1945
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
1946 1946
 		$resql = $db->query($sql);
1947 1947
 		if ($resql)
1948 1948
 		{
1949
-			$nb=$db->affected_rows($sql);
1949
+			$nb = $db->affected_rows($sql);
1950 1950
 			if ($nb > 0)
1951 1951
 			{
1952 1952
 				print '<br>Some record that were parent of themself were cleaned.';
1953 1953
 			}
1954 1954
 
1955
-			$totalnb+=$nb;
1955
+			$totalnb += $nb;
1956 1956
 		}
1957 1957
 		//else dol_print_error($db);
1958 1958
 
1959 1959
 		// Check other loops
1960
-		$listofidtoclean=array();
1961
-		foreach($listofparentid as $id => $pid)
1960
+		$listofidtoclean = array();
1961
+		foreach ($listofparentid as $id => $pid)
1962 1962
 		{
1963 1963
 			// Check depth
1964 1964
 			//print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1965 1965
 
1966
-			$cursor=$id; $arrayidparsed=array();	// We start from child $id
1966
+			$cursor = $id; $arrayidparsed = array(); // We start from child $id
1967 1967
 			while ($cursor > 0)
1968 1968
 			{
1969
-				$arrayidparsed[$cursor]=1;
1969
+				$arrayidparsed[$cursor] = 1;
1970 1970
 				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1971 1971
 				{
1972 1972
 					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1973 1973
 					unset($arrayidparsed);
1974
-					$listofidtoclean[$cursor]=$id;
1974
+					$listofidtoclean[$cursor] = $id;
1975 1975
 					break;
1976 1976
 				}
1977
-				$cursor=$listofparentid[$cursor];
1977
+				$cursor = $listofparentid[$cursor];
1978 1978
 			}
1979 1979
 
1980 1980
 			if (count($listofidtoclean)) break;
1981 1981
 		}
1982 1982
 
1983 1983
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1984
-		$sql.= " SET ".$fieldfkparent." = 0";
1985
-		$sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1984
+		$sql .= " SET ".$fieldfkparent." = 0";
1985
+		$sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong
1986 1986
 		$resql = $db->query($sql);
1987 1987
 		if ($resql)
1988 1988
 		{
1989
-			$nb=$db->affected_rows($sql);
1989
+			$nb = $db->affected_rows($sql);
1990 1990
 			if ($nb > 0)
1991 1991
 			{
1992 1992
 				// Removed orphelins records
1993 1993
 				print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1994
-				print join(',',$listofidtoclean);
1994
+				print join(',', $listofidtoclean);
1995 1995
 			}
1996 1996
 
1997
-			$totalnb+=$nb;
1997
+			$totalnb += $nb;
1998 1998
 		}
1999 1999
 		//else dol_print_error($db);
2000 2000
 
2001 2001
 		// Check and clean orphelins
2002 2002
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
2003
-		$sql.= " SET ".$fieldfkparent." = 0";
2004
-		$sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
2003
+		$sql .= " SET ".$fieldfkparent." = 0";
2004
+		$sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent
2005 2005
 		$resql = $db->query($sql);
2006 2006
 		if ($resql)
2007 2007
 		{
2008
-			$nb=$db->affected_rows($sql);
2008
+			$nb = $db->affected_rows($sql);
2009 2009
 			if ($nb > 0)
2010 2010
 			{
2011 2011
 				// Removed orphelins records
2012 2012
 				print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2013
-				print join(',',$listofid);
2013
+				print join(',', $listofid);
2014 2014
 			}
2015 2015
 
2016
-			$totalnb+=$nb;
2016
+			$totalnb += $nb;
2017 2017
 		}
2018 2018
 		//else dol_print_error($db);
2019 2019
 
@@ -2034,21 +2034,21 @@  discard block
 block discarded – undo
2034 2034
     $module = $element = $subelement = $element_type;
2035 2035
 
2036 2036
     // If we ask an resource form external module (instead of default path)
2037
-    if (preg_match('/^([^@]+)@([^@]+)$/i',$element_type,$regs))
2037
+    if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs))
2038 2038
     {
2039 2039
         $element = $subelement = $regs[1];
2040 2040
         $module 	= $regs[2];
2041 2041
     }
2042 2042
 
2043 2043
     //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
2044
-    if ( preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
2044
+    if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs))
2045 2045
     {
2046 2046
         $module = $element = $regs[1];
2047 2047
         $subelement = $regs[2];
2048 2048
     }
2049 2049
 
2050 2050
     // For compat
2051
-    if($element_type == "action") {
2051
+    if ($element_type == "action") {
2052 2052
         $classpath = 'comm/action/class';
2053 2053
         $subelement = 'Actioncomm';
2054 2054
         $module = 'agenda';
@@ -2057,18 +2057,18 @@  discard block
 block discarded – undo
2057 2057
     // To work with non standard path
2058 2058
     if ($element_type == 'facture' || $element_type == 'invoice') {
2059 2059
         $classpath = 'compta/facture/class';
2060
-        $module='facture';
2061
-        $subelement='facture';
2060
+        $module = 'facture';
2061
+        $subelement = 'facture';
2062 2062
     }
2063 2063
     if ($element_type == 'commande' || $element_type == 'order') {
2064 2064
         $classpath = 'commande/class';
2065
-        $module='commande';
2066
-        $subelement='commande';
2065
+        $module = 'commande';
2066
+        $subelement = 'commande';
2067 2067
     }
2068
-    if ($element_type == 'propal')  {
2068
+    if ($element_type == 'propal') {
2069 2069
         $classpath = 'comm/propal/class';
2070 2070
     }
2071
-    if ($element_type == 'supplier_proposal')  {
2071
+    if ($element_type == 'supplier_proposal') {
2072 2072
         $classpath = 'supplier_proposal/class';
2073 2073
     }
2074 2074
     if ($element_type == 'shipping') {
@@ -2083,45 +2083,45 @@  discard block
 block discarded – undo
2083 2083
     }
2084 2084
     if ($element_type == 'contract') {
2085 2085
         $classpath = 'contrat/class';
2086
-        $module='contrat';
2087
-        $subelement='contrat';
2086
+        $module = 'contrat';
2087
+        $subelement = 'contrat';
2088 2088
     }
2089 2089
     if ($element_type == 'member') {
2090 2090
         $classpath = 'adherents/class';
2091
-        $module='adherent';
2092
-        $subelement='adherent';
2091
+        $module = 'adherent';
2092
+        $subelement = 'adherent';
2093 2093
     }
2094 2094
     if ($element_type == 'cabinetmed_cons') {
2095 2095
         $classpath = 'cabinetmed/class';
2096
-        $module='cabinetmed';
2097
-        $subelement='cabinetmedcons';
2096
+        $module = 'cabinetmed';
2097
+        $subelement = 'cabinetmedcons';
2098 2098
     }
2099 2099
     if ($element_type == 'fichinter') {
2100 2100
         $classpath = 'fichinter/class';
2101
-        $module='ficheinter';
2102
-        $subelement='fichinter';
2101
+        $module = 'ficheinter';
2102
+        $subelement = 'fichinter';
2103 2103
     }
2104 2104
     if ($element_type == 'dolresource' || $element_type == 'resource') {
2105 2105
         $classpath = 'resource/class';
2106
-        $module='resource';
2107
-        $subelement='dolresource';
2106
+        $module = 'resource';
2107
+        $subelement = 'dolresource';
2108 2108
     }
2109 2109
     if ($element_type == 'propaldet') {
2110 2110
         $classpath = 'comm/propal/class';
2111
-        $module='propal';
2112
-        $subelement='propaleligne';
2111
+        $module = 'propal';
2112
+        $subelement = 'propaleligne';
2113 2113
     }
2114
-    if ($element_type == 'order_supplier')  {
2114
+    if ($element_type == 'order_supplier') {
2115 2115
         $classpath = 'fourn/class';
2116
-        $module='fournisseur';
2117
-        $subelement='commandefournisseur';
2118
-        $classfile='fournisseur.commande';
2116
+        $module = 'fournisseur';
2117
+        $subelement = 'commandefournisseur';
2118
+        $classfile = 'fournisseur.commande';
2119 2119
     }
2120
-    if ($element_type == 'invoice_supplier')  {
2120
+    if ($element_type == 'invoice_supplier') {
2121 2121
         $classpath = 'fourn/class';
2122
-        $module='fournisseur';
2123
-        $subelement='facturefournisseur';
2124
-        $classfile='fournisseur.facture';
2122
+        $module = 'fournisseur';
2123
+        $subelement = 'facturefournisseur';
2124
+        $classfile = 'fournisseur.facture';
2125 2125
     }
2126 2126
 
2127 2127
     if (!isset($classfile)) $classfile = strtolower($subelement);
@@ -2148,10 +2148,10 @@  discard block
 block discarded – undo
2148 2148
  * @param	ref     	$element_ref 	Element ref (Use this if element_id but not both)
2149 2149
  * @return 	int|object 					object || 0 || -1 if error
2150 2150
  */
2151
-function fetchObjectByElement($element_id, $element_type, $element_ref='')
2151
+function fetchObjectByElement($element_id, $element_type, $element_ref = '')
2152 2152
 {
2153 2153
     global $conf;
2154
-	global $db,$conf;
2154
+	global $db, $conf;
2155 2155
 
2156 2156
     $element_prop = getElementProperties($element_type);
2157 2157
     if (is_array($element_prop) && Globals::$conf->{$element_prop['module']}->enabled) {
@@ -2177,11 +2177,11 @@  discard block
 block discarded – undo
2177 2177
  *  @return	string						RGB hex value (without # before). For example: 'FF00FF', '01FF02'
2178 2178
  *  @see	colorStringToArray
2179 2179
  */
2180
-function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2180
+function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
2181 2181
 {
2182
-	if (! is_array($arraycolor)) return $colorifnotfound;
2182
+	if (!is_array($arraycolor)) return $colorifnotfound;
2183 2183
 	if (empty($arraycolor)) return $colorifnotfound;
2184
-	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2184
+	return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
2185 2185
 }
2186 2186
 
2187 2187
 /**
@@ -2196,15 +2196,15 @@  discard block
 block discarded – undo
2196 2196
  */
2197 2197
 static function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2198 2198
     {
2199
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2200
-	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2201
-	if (! $tmp)
2199
+	if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
2200
+	$tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
2201
+	if (!$tmp)
2202 2202
 	{
2203
-		$tmp=explode(',',$stringcolor);
2203
+		$tmp = explode(',', $stringcolor);
2204 2204
 		if (count($tmp) < 3) return $colorifnotfound;
2205 2205
 		return $tmp;
2206 2206
 	}
2207
-	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2207
+	return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
2208 2208
 }
2209 2209
 
2210 2210
 /**
@@ -2224,8 +2224,8 @@  discard block
 block discarded – undo
2224 2224
     foreach ($input as $key => $values) {
2225 2225
         $append = array();
2226 2226
 
2227
-        foreach($result as $product) {
2228
-            foreach($values as $item) {
2227
+        foreach ($result as $product) {
2228
+            foreach ($values as $item) {
2229 2229
                 $product[$key] = $item;
2230 2230
                 $append[] = $product;
2231 2231
             }
@@ -2246,8 +2246,8 @@  discard block
 block discarded – undo
2246 2246
  */
2247 2247
 function getModuleDirForApiClass($module)
2248 2248
 {
2249
-    $moduledirforclass=$module;
2250
-    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2249
+    $moduledirforclass = $module;
2250
+    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
2251 2251
 
2252 2252
     if ($module == 'contracts') {
2253 2253
     	$moduledirforclass = 'contrat';
@@ -2323,9 +2323,9 @@  discard block
 block discarded – undo
2323 2323
  * @param	$max	int	Between 0 and 255
2324 2324
  * @return String
2325 2325
  */
2326
-function random_color_part($min=0,$max=255)
2326
+function random_color_part($min = 0, $max = 255)
2327 2327
 {
2328
-    return str_pad( dechex( mt_rand( $min, $max) ), 2, '0', STR_PAD_LEFT);
2328
+    return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
2329 2329
 }
2330 2330
 
2331 2331
 /*
@@ -2335,8 +2335,8 @@  discard block
 block discarded – undo
2335 2335
  * @param	$max	int	Between 0 and 255
2336 2336
  * @return String
2337 2337
  */
2338
-function random_color($min=0, $max=255)
2338
+function random_color($min = 0, $max = 255)
2339 2339
 {
2340
-    return random_color_part($min, $max) . random_color_part($min, $max) . random_color_part($min, $max);
2340
+    return random_color_part($min, $max).random_color_part($min, $max).random_color_part($min, $max);
2341 2341
 }
2342 2342
 }
Please login to merge, or discard this patch.
Helpers/Security.php 1 patch
Spacing   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -105,12 +105,12 @@  discard block
 block discarded – undo
105 105
     static function dol_hash($chain, $type = '0')
106 106
     {
107 107
         // No need to add salt for password_hash
108
-        if (($type == '0' || $type == 'auto') &&!empty(Globals::$conf->global->MAIN_SECURITY_HASH_ALGO) && Globals::$conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) {
108
+        if (($type == '0' || $type == 'auto') && !empty(Globals::$conf->global->MAIN_SECURITY_HASH_ALGO) && Globals::$conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) {
109 109
             return password_hash($chain, PASSWORD_DEFAULT);
110 110
         }
111 111
         // Salt value
112 112
         if (!empty(Globals::$conf->global->MAIN_SECURITY_SALT)) {
113
-            $chain = Globals::$conf->global->MAIN_SECURITY_SALT . $chain;
113
+            $chain = Globals::$conf->global->MAIN_SECURITY_SALT.$chain;
114 114
         }
115 115
         if ($type == '1' || $type == 'sha1') {
116 116
             return sha1($chain);
@@ -122,7 +122,7 @@  discard block
 block discarded – undo
122 122
             return md5($chain);
123 123
         }
124 124
         if ($type == '4' || $type == 'md5openldap') {
125
-            return '{md5}' . base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
125
+            return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base)
126 126
         }
127 127
         if ($type == '5') {
128 128
             return hash('sha256', $chain);
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
             return false;
203 203
 
204 204
         if ($dbt_select != 'rowid' && $dbt_select != 'id')
205
-            $objectid = "'" . $objectid . "'";
205
+            $objectid = "'".$objectid."'";
206 206
 
207 207
         // Features/modules to check
208 208
         $featuresarray = array($features);
@@ -402,7 +402,7 @@  discard block
 block discarded – undo
402 402
                 else if ($feature == 'ftp') {
403 403
                     if (!$user->rights->ftp->write)
404 404
                         $deleteok = 0;
405
-                }else if ($feature == 'salaries') {
405
+                } else if ($feature == 'salaries') {
406 406
                     if (!$user->rights->salaries->delete)
407 407
                         $deleteok = 0;
408 408
                 }
@@ -480,8 +480,8 @@  discard block
 block discarded – undo
480 480
                 $feature = 'projet_task';
481 481
 
482 482
             $check = array('adherent', 'banque', 'don', 'user', 'usergroup', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource'); // Test on entity only (Objects with no link to company)
483
-            $checksoc = array('societe');  // Test for societe object
484
-            $checkother = array('contact', 'agenda');  // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
483
+            $checksoc = array('societe'); // Test for societe object
484
+            $checkother = array('contact', 'agenda'); // Test on entity and link to third party. Allowed if link is empty (Ex: contacts...).
485 485
             $checkproject = array('projet', 'project'); // Test for project object
486 486
             $checktask = array('projet_task');
487 487
             $nocheck = array('barcode', 'stock'); // No test
@@ -489,32 +489,32 @@  discard block
 block discarded – undo
489 489
             // If dbtablename not defined, we use same name for table than module name
490 490
             if (empty($dbtablename)) {
491 491
                 $dbtablename = $feature;
492
-                $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename);  // We change dbtablename, so we set sharedelement too.
492
+                $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too.
493 493
             }
494 494
 
495 495
             // Check permission for object with entity
496 496
             if (in_array($feature, $check)) {
497
-                $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
498
-                $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
497
+                $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
498
+                $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
499 499
                 if (($feature == 'user' || $feature == 'usergroup') && !empty(Globals::$conf->multicompany->enabled)) {
500 500
                     if (!empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
501 501
                         if (Globals::$conf->entity == 1 && $user->admin && !$user->entity) {
502
-                            $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
502
+                            $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
503 503
                             $sql .= " AND dbt.entity IS NOT NULL";
504 504
                         } else {
505
-                            $sql .= "," . MAIN_DB_PREFIX . "usergroup_user as ug";
506
-                            $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
505
+                            $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug";
506
+                            $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
507 507
                             $sql .= " AND (ug.fk_user = dbt.rowid";
508
-                            $sql .= " AND ug.entity IN (" . getEntity('user') . "))";
508
+                            $sql .= " AND ug.entity IN (".getEntity('user')."))";
509 509
                             $sql .= " OR dbt.entity = 0"; // Show always superadmin
510 510
                         }
511 511
                     } else {
512
-                        $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
513
-                        $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
512
+                        $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
513
+                        $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
514 514
                     }
515 515
                 } else {
516
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
517
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
516
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
517
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
518 518
                 }
519 519
             } else if (in_array($feature, $checksoc)) { // We check feature = checksoc
520 520
                 // If external user: Check permission for external users
@@ -525,47 +525,47 @@  discard block
 block discarded – undo
525 525
                 // If internal user: Check permission for internal users that are restricted on their objects
526 526
                 else if (!empty(Globals::$conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) {
527 527
                     $sql = "SELECT COUNT(sc.fk_soc) as nb";
528
-                    $sql .= " FROM (" . MAIN_DB_PREFIX . "societe_commerciaux as sc";
529
-                    $sql .= ", " . MAIN_DB_PREFIX . "societe as s)";
530
-                    $sql .= " WHERE sc.fk_soc IN (" . $objectid . ")";
531
-                    $sql .= " AND sc.fk_user = " . $user->id;
528
+                    $sql .= " FROM (".MAIN_DB_PREFIX."societe_commerciaux as sc";
529
+                    $sql .= ", ".MAIN_DB_PREFIX."societe as s)";
530
+                    $sql .= " WHERE sc.fk_soc IN (".$objectid.")";
531
+                    $sql .= " AND sc.fk_user = ".$user->id;
532 532
                     $sql .= " AND sc.fk_soc = s.rowid";
533
-                    $sql .= " AND s.entity IN (" . getEntity($sharedelement, 1) . ")";
533
+                    $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
534 534
                 }
535 535
                 // If multicompany and internal users with all permissions, check user is in correct entity
536 536
                 else if (!empty(Globals::$conf->multicompany->enabled)) {
537 537
                     $sql = "SELECT COUNT(s.rowid) as nb";
538
-                    $sql .= " FROM " . MAIN_DB_PREFIX . "societe as s";
539
-                    $sql .= " WHERE s.rowid IN (" . $objectid . ")";
540
-                    $sql .= " AND s.entity IN (" . getEntity($sharedelement, 1) . ")";
538
+                    $sql .= " FROM ".MAIN_DB_PREFIX."societe as s";
539
+                    $sql .= " WHERE s.rowid IN (".$objectid.")";
540
+                    $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")";
541 541
                 }
542 542
             } else if (in_array($feature, $checkother)) { // Test on entity and link to societe. Allowed if link is empty (Ex: contacts...).
543 543
                 // If external user: Check permission for external users
544 544
                 if ($user->socid > 0) {
545
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
546
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
547
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
548
-                    $sql .= " AND dbt.fk_soc = " . $user->socid;
545
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
546
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
547
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
548
+                    $sql .= " AND dbt.fk_soc = ".$user->socid;
549 549
                 }
550 550
                 // If internal user: Check permission for internal users that are restricted on their objects
551 551
                 else if (!empty(Globals::$conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) {
552
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
553
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
554
-                    $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '" . $user->id . "'";
555
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
552
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
553
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
554
+                    $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = '".$user->id."'";
555
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
556 556
                     $sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user
557
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
557
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
558 558
                 }
559 559
                 // If multicompany and internal users with all permissions, check user is in correct entity
560 560
                 else if (!empty(Globals::$conf->multicompany->enabled)) {
561
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
562
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
563
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
564
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
561
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
562
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
563
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
564
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
565 565
                 }
566 566
             } else if (in_array($feature, $checkproject)) {
567 567
                 if (!empty(Globals::$conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
568
-                    include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
568
+                    include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
569 569
                     $projectstatic = new Project($db);
570 570
                     $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
571 571
                     $tmparray = explode(',', $tmps);
@@ -573,17 +573,17 @@  discard block
 block discarded – undo
573 573
                         return false;
574 574
                 }
575 575
                 else {
576
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
577
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
578
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
579
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
576
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
577
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
578
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
579
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
580 580
                 }
581 581
             } else if (in_array($feature, $checktask)) {
582 582
                 if (!empty(Globals::$conf->projet->enabled) && empty($user->rights->projet->all->lire)) {
583 583
                     $task = new Task($db);
584 584
                     $task->fetch($objectid);
585 585
 
586
-                    include_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
586
+                    include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
587 587
                     $projectstatic = new Project($db);
588 588
                     $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0);
589 589
                     $tmparray = explode(',', $tmps);
@@ -591,41 +591,41 @@  discard block
 block discarded – undo
591 591
                         return false;
592 592
                 }
593 593
                 else {
594
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
595
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
596
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
597
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
594
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
595
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
596
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
597
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
598 598
                 }
599 599
             } else if (!in_array($feature, $nocheck)) {  // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield
600 600
                 // If external user: Check permission for external users
601 601
                 if ($user->socid > 0) {
602 602
                     if (empty($dbt_keyfield))
603 603
                         dol_print_error('', 'Param dbt_keyfield is required but not defined');
604
-                    $sql = "SELECT COUNT(dbt." . $dbt_keyfield . ") as nb";
605
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
606
-                    $sql .= " WHERE dbt.rowid IN (" . $objectid . ")";
607
-                    $sql .= " AND dbt." . $dbt_keyfield . " = " . $user->socid;
604
+                    $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb";
605
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
606
+                    $sql .= " WHERE dbt.rowid IN (".$objectid.")";
607
+                    $sql .= " AND dbt.".$dbt_keyfield." = ".$user->socid;
608 608
                 }
609 609
                 // If internal user: Check permission for internal users that are restricted on their objects
610 610
                 else if (!empty(Globals::$conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) {
611 611
                     if (empty($dbt_keyfield))
612 612
                         dol_print_error('', 'Param dbt_keyfield is required but not defined');
613 613
                     $sql = "SELECT COUNT(sc.fk_soc) as nb";
614
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
615
-                    $sql .= ", " . MAIN_DB_PREFIX . "societe as s";
616
-                    $sql .= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc";
617
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
618
-                    $sql .= " AND sc.fk_soc = dbt." . $dbt_keyfield;
619
-                    $sql .= " AND dbt." . $dbt_keyfield . " = s.rowid";
620
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
621
-                    $sql .= " AND sc.fk_user = " . $user->id;
614
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
615
+                    $sql .= ", ".MAIN_DB_PREFIX."societe as s";
616
+                    $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
617
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
618
+                    $sql .= " AND sc.fk_soc = dbt.".$dbt_keyfield;
619
+                    $sql .= " AND dbt.".$dbt_keyfield." = s.rowid";
620
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
621
+                    $sql .= " AND sc.fk_user = ".$user->id;
622 622
                 }
623 623
                 // If multicompany and internal users with all permissions, check user is in correct entity
624 624
                 else if (!empty(Globals::$conf->multicompany->enabled)) {
625
-                    $sql = "SELECT COUNT(dbt." . $dbt_select . ") as nb";
626
-                    $sql .= " FROM " . MAIN_DB_PREFIX . $dbtablename . " as dbt";
627
-                    $sql .= " WHERE dbt." . $dbt_select . " IN (" . $objectid . ")";
628
-                    $sql .= " AND dbt.entity IN (" . getEntity($sharedelement, 1) . ")";
625
+                    $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb";
626
+                    $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt";
627
+                    $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")";
628
+                    $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")";
629 629
                 }
630 630
             }
631 631
 
@@ -658,7 +658,7 @@  discard block
 block discarded – undo
658 658
     {
659 659
         global $conf, $db, $user, $langs;
660 660
         if (!is_object($langs)) {
661
-            include_once DOL_DOCUMENT_ROOT . '/core/class/translate.class.php';
661
+            include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
662 662
             $langs = new Translate('', $conf);
663 663
             $langs->setDefaultLang();
664 664
         }
@@ -680,7 +680,7 @@  discard block
 block discarded – undo
680 680
         print '<br>';
681 681
         if (empty($showonlymessage)) {
682 682
             if ($user->login) {
683
-                print $langs->trans("CurrentLogin") . ': <font class="error">' . $user->login . '</font><br>';
683
+                print $langs->trans("CurrentLogin").': <font class="error">'.$user->login.'</font><br>';
684 684
                 print $langs->trans("ErrorForbidden2", $langs->trans("Home"), $langs->trans("Users"));
685 685
             } else {
686 686
                 print $langs->trans("ErrorForbidden3");
Please login to merge, or discard this patch.