Passed
Push — master ( 492b54...49af33 )
by Alxarafe
25:44
created
Views/CategoriesIndexView.php 1 patch
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 
110 110
         $this->llxHeader('', $this->title, '', '', 0, 0, $arrayofjs, $arrayofcss);
111 111
 
112
-        $newcardbutton = '<a class="butActionNew" href="' . BASE_URI . '/categories/card.php?action=create&type=' . $this->type . '&backtopage=' . urlencode($_SERVER["PHP_SELF"] . '?type=' . $this->type) . '"><span class="valignmiddle">' . Globals::$langs->trans("NewCategory") . '</span>';
112
+        $newcardbutton = '<a class="butActionNew" href="'.BASE_URI.'/categories/card.php?action=create&type='.$this->type.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?type='.$this->type).'"><span class="valignmiddle">'.Globals::$langs->trans("NewCategory").'</span>';
113 113
         $newcardbutton .= '<span class="fa fa-plus-circle valignmiddle"></span>';
114 114
         $newcardbutton .= '</a>';
115 115
 
@@ -123,17 +123,17 @@  discard block
 block discarded – undo
123 123
         /*
124 124
          * Zone recherche produit/service
125 125
          */
126
-        print '<form method="post" action="index.php?type=' . $this->type . '">';
127
-        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
128
-        print '<input type="hidden" name="type" value="' . $this->type . '">';
126
+        print '<form method="post" action="index.php?type='.$this->type.'">';
127
+        print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
128
+        print '<input type="hidden" name="type" value="'.$this->type.'">';
129 129
 
130 130
 
131 131
         print '<table class="noborder nohover" width="100%">';
132 132
         print '<tr class="liste_titre">';
133
-        print '<td colspan="3">' . Globals::$langs->trans("Search") . '</td>';
133
+        print '<td colspan="3">'.Globals::$langs->trans("Search").'</td>';
134 134
         print '</tr>';
135 135
         print '<tr class="oddeven"><td>';
136
-        print Globals::$langs->trans("Name") . ':</td><td><input class="flat inputsearch" type="text" name="catname" value="' . $catname . '"/></td><td><input type="submit" class="button" value="' . Globals::$langs->trans("Search") . '"></td></tr>';
136
+        print Globals::$langs->trans("Name").':</td><td><input class="flat inputsearch" type="text" name="catname" value="'.$catname.'"/></td><td><input type="submit" class="button" value="'.Globals::$langs->trans("Search").'"></td></tr>';
137 137
         /*
138 138
           // faire une rech dans une sous categorie uniquement
139 139
           print '<tr '.$bc[0].'><td>';
@@ -158,17 +158,17 @@  discard block
 block discarded – undo
158 158
             $cats = $categstatic->rechercher($id, $catname, $this->typetext);
159 159
 
160 160
             print '<table class="noborder" width="100%">';
161
-            print '<tr class="liste_titre"><td colspan="2">' . Globals::$langs->trans("FoundCats") . '</td></tr>';
161
+            print '<tr class="liste_titre"><td colspan="2">'.Globals::$langs->trans("FoundCats").'</td></tr>';
162 162
 
163 163
             foreach ($cats as $cat) {
164
-                print "\t" . '<tr class="oddeven">' . "\n";
164
+                print "\t".'<tr class="oddeven">'."\n";
165 165
                 print "\t\t<td>";
166 166
                 $categstatic->id = $cat->id;
167 167
                 $categstatic->ref = $cat->label;
168 168
                 $categstatic->label = $cat->label;
169 169
                 $categstatic->type = $cat->type;
170 170
                 $categstatic->color = $cat->color;
171
-                print '<span class="noborderoncategories" ' . ($categstatic->color ? ' style="background: #' . $categstatic->color . ';"' : ' style="background: #aaa"') . '>';
171
+                print '<span class="noborderoncategories" '.($categstatic->color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>';
172 172
                 print $categstatic->getNomUrl(1, '');
173 173
                 print '</span>';
174 174
                 print "</td>\n";
@@ -208,9 +208,9 @@  discard block
 block discarded – undo
208 208
             $data[] = array(
209 209
                 'rowid' => $val['rowid'],
210 210
                 'fk_menu' => $val['fk_parent'],
211
-                'entry' => '<table class="nobordernopadding centpercent"><tr><td><span class="noborderoncategories" ' . ($categstatic->color ? ' style="background: #' . $categstatic->color . ';"' : ' style="background: #aaa"') . '>' . $li . '</span></td>' .
211
+                'entry' => '<table class="nobordernopadding centpercent"><tr><td><span class="noborderoncategories" '.($categstatic->color ? ' style="background: #'.$categstatic->color.';"' : ' style="background: #aaa"').'>'.$li.'</span></td>'.
212 212
                 //'<td width="50%">'.dolGetFirstLineOfText($desc).'</td>'.
213
-                '<td align="right" width="20px;"><a href="' . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $val['id'] . '&type=' . $this->type . '">' . img_view() . '</a></td>' .
213
+                '<td align="right" width="20px;"><a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$val['id'].'&type='.$this->type.'">'.img_view().'</a></td>'.
214 214
                 '</tr></table>'
215 215
             );
216 216
         }
@@ -219,9 +219,9 @@  discard block
 block discarded – undo
219 219
 //print_barre_liste('', 0, $_SERVER["PHP_SELF"], '', '', '', '', 0, 0, '', 0, $newcardbutton, '', 0, 1, 1);
220 220
 
221 221
         print '<table class="liste nohover" width="100%">';
222
-        print '<tr class="liste_titre"><td>' . Globals::$langs->trans("Categories") . '</td><td></td><td align="right">';
222
+        print '<tr class="liste_titre"><td>'.Globals::$langs->trans("Categories").'</td><td></td><td align="right">';
223 223
         if (!empty($conf->use_javascript_ajax)) {
224
-            print '<div id="iddivjstreecontrol"><a class="notasortlink" href="#">' . img_picto('', 'object_category') . ' ' . Globals::$langs->trans("UndoExpandAll") . '</a> | <a class="notasortlink" href="#">' . img_picto('', 'object_category-expanded') . ' ' . Globals::$langs->trans("ExpandAll") . '</a></div>';
224
+            print '<div id="iddivjstreecontrol"><a class="notasortlink" href="#">'.img_picto('', 'object_category').' '.Globals::$langs->trans("UndoExpandAll").'</a> | <a class="notasortlink" href="#">'.img_picto('', 'object_category-expanded').' '.Globals::$langs->trans("ExpandAll").'</a></div>';
225 225
         }
226 226
         print '</td></tr>';
227 227
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
             print '</td></tr>';
234 234
         } else {
235 235
             print '<tr class="pair">';
236
-            print '<td colspan="3"><table class="nobordernopadding"><tr class="nobordernopadding"><td>' . DolUtils::img_picto_common('', 'treemenu/branchbottom.gif') . '</td>';
236
+            print '<td colspan="3"><table class="nobordernopadding"><tr class="nobordernopadding"><td>'.DolUtils::img_picto_common('', 'treemenu/branchbottom.gif').'</td>';
237 237
             print '<td valign="middle">';
238 238
             print Globals::$langs->trans("NoCategoryYet");
239 239
             print '</td>';
Please login to merge, or discard this patch.
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->beginTransaction();
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/CommonObject.php 3 patches
Indentation   +7071 added lines, -7071 removed lines patch added patch discarded remove patch
@@ -21,7389 +21,7389 @@
 block discarded – undo
21 21
 
22 22
 abstract class CommonObject
23 23
 {
24
-	/**
24
+    /**
25 25
      * @var int The object identifier
26 26
      */
27
-	public $id;
28
-
29
-	/**
30
-	 * @var string 		Error string
31
-	 * @see             errors
32
-	 */
33
-	public $error;
34
-
35
-	/**
36
-	 * @var string[]	Array of error strings
37
-	 */
38
-	public $errors=array();
39
-
40
-	/**
41
-	 * @var string ID to identify managed object
42
-	 */
43
-	public $element;
44
-
45
-	/**
46
-	 * @var string Name of table without prefix where object is stored
47
-	 */
48
-	public $table_element;
49
-
50
-	/**
51
-	 * @var int    Name of subtable line
52
-	 */
53
-	public $table_element_line='';
54
-
55
-	/**
56
-	 * @var string		Key value used to track if data is coming from import wizard
57
-	 */
58
-	public $import_key;
59
-
60
-	/**
61
-	 * @var mixed		Contains data to manage extrafields
62
-	 */
63
-	public $array_options=array();
64
-
65
-	/**
66
-	 * @var int[][]		Array of linked objects ids. Loaded by ->fetchObjectLinked
67
-	 */
68
-	public $linkedObjectsIds;
69
-
70
-	/**
71
-	 * @var mixed		Array of linked objects. Loaded by ->fetchObjectLinked
72
-	 */
73
-	public $linkedObjects;
74
-
75
-	/**
76
-	 * @var Object      To store a cloned copy of object before to edit it and keep track of old properties
77
-	 */
78
-	public $oldcopy;
79
-
80
-	/**
81
-	 * @var string		Column name of the ref field.
82
-	 */
83
-	protected $table_ref_field = '';
84
-
85
-
86
-
87
-	// Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
88
-
89
-	/**
90
-	 * @var array<string,mixed>		Can be used to pass information when only object is provided to method
91
-	 */
92
-	public $context=array();
93
-
94
-	/**
95
-	 * @var string		Contains canvas name if record is an alternative canvas record
96
-	 */
97
-	public $canvas;
98
-
99
-	/**
100
-	 * @var Project The related project
101
-	 * @see fetch_projet()
102
-	 */
103
-	public $project;
104
-
105
-	/**
106
-	 * @var int The related project ID
107
-	 * @see setProject(), project
108
-	 */
109
-	public $fk_project;
110
-
111
-	/**
112
-	 * @deprecated
113
-	 * @see project
114
-	 */
115
-	public $projet;
116
-
117
-	/**
118
-	 * @var Contact a related contact
119
-	 * @see fetch_contact()
120
-	 */
121
-	public $contact;
122
-
123
-	/**
124
-	 * @var int The related contact ID
125
-	 * @see fetch_contact()
126
-	 */
127
-	public $contact_id;
128
-
129
-	/**
130
-	 * @var Societe A related thirdparty
131
-	 * @see fetch_thirdparty()
132
-	 */
133
-	public $thirdparty;
134
-
135
-	/**
136
-	 * @var User A related user
137
-	 * @see fetch_user()
138
-	 */
139
-	public $user;
140
-
141
-	/**
142
-	 * @var string 	The type of originating object ('commande', 'facture', ...)
143
-	 * @see fetch_origin()
144
-	 */
145
-	public $origin;
146
-
147
-	/**
148
-	 * @var int 	The id of originating object
149
-	 * @see fetch_origin()
150
-	 */
151
-	public $origin_id;
152
-
153
-	/**
154
-	 * @var string The object's reference
155
-	 */
156
-	public $ref;
157
-
158
-	/**
159
-	 * @var string The object's previous reference
160
-	 */
161
-	public $ref_previous;
162
-
163
-	/**
164
-	 * @var string The object's next reference
165
-	 */
166
-	public $ref_next;
167
-
168
-	/**
169
-	 * @var string An external reference for the object
170
-	 */
171
-	public $ref_ext;
172
-
173
-	/**
174
-	 * @var int The object's status
175
-	 * @see setStatut()
176
-	 */
177
-	public $statut;
178
-
179
-	/**
180
-	 * @var string
181
-	 * @see getFullAddress()
182
-	 */
183
-	public $country;
184
-
185
-	/**
186
-	 * @var int
187
-	 * @see getFullAddress(), country
188
-	 */
189
-	public $country_id;
190
-
191
-	/**
192
-	 * @var string
193
-	 * @see getFullAddress(), isInEEC(), country
194
-	 */
195
-    public $country_code;
27
+    public $id;
196 28
 
197 29
     /**
198
-	 * @var string
199
-	 * @see getFullAddress()
200
-	 */
201
-	public $state;
202
-
203
-	/**
204
-	 * @var int
205
-	 * @see getFullAddress(), state
206
-	 */
207
-	public $state_id;
30
+     * @var string 		Error string
31
+     * @see             errors
32
+     */
33
+    public $error;
208 34
 
209
-	/**
210
-	 * @var string
211
-	 * @see getFullAddress(), state
212
-	 */
213
-    public $state_code;
35
+    /**
36
+     * @var string[]	Array of error strings
37
+     */
38
+    public $errors=array();
214 39
 
215 40
     /**
216
-	 * @var string
217
-	 * @see getFullAddress(), region
218
-	 */
219
-	public $region;
41
+     * @var string ID to identify managed object
42
+     */
43
+    public $element;
220 44
 
221
-	/**
222
-	 * @var string
223
-	 * @see getFullAddress(), region
224
-	 */
225
-    public $region_code;
45
+    /**
46
+     * @var string Name of table without prefix where object is stored
47
+     */
48
+    public $table_element;
226 49
 
227
-	/**
228
-	 * @var int
229
-	 * @see fetch_barcode()
230
-	 */
231
-	public $barcode_type;
232
-
233
-	/**
234
-	 * @var string
235
-	 * @see fetch_barcode(), barcode_type
236
-	 */
237
-	public $barcode_type_code;
238
-
239
-	/**
240
-	 * @var string
241
-	 * @see fetch_barcode(), barcode_type
242
-	 */
243
-	public $barcode_type_label;
244
-
245
-	/**
246
-	 * @var string
247
-	 * @see fetch_barcode(), barcode_type
248
-	 */
249
-	public $barcode_type_coder;
250
-
251
-	/**
252
-	 * @var int Payment method ID (cheque, cash, ...)
253
-	 * @see setPaymentMethods()
254
-	 */
255
-	public $mode_reglement_id;
256
-
257
-	/**
258
-	 * @var int Payment terms ID
259
-	 * @see setPaymentTerms()
260
-	 */
261
-	public $cond_reglement_id;
262
-
263
-	/**
264
-	 * @var int Payment terms ID
265
-	 * @deprecated Kept for compatibility
266
-	 * @see cond_reglement_id;
267
-	 */
268
-	public $cond_reglement;
269
-
270
-	/**
271
-	 * @var int Delivery address ID
272
-	 * @deprecated
273
-	 * @see setDeliveryAddress()
274
-	 */
275
-	public $fk_delivery_address;
276
-
277
-	/**
278
-	 * @var int Shipping method ID
279
-	 * @see setShippingMethod()
280
-	 */
281
-	public $shipping_method_id;
282
-
283
-	/**
284
-	 * @var string
285
-	 * @see SetDocModel()
286
-	 */
287
-	public $modelpdf;
288
-
289
-	/**
290
-	 * @var int Bank account ID
291
-	 * @see SetBankAccount()
292
-	 */
293
-	public $fk_account;
294
-
295
-	/**
296
-	 * @var string Public note
297
-	 * @see update_note()
298
-	 */
299
-	public $note_public;
300
-
301
-	/**
302
-	 * @var string Private note
303
-	 * @see update_note()
304
-	 */
305
-	public $note_private;
306
-
307
-	/**
308
-	 * @deprecated
309
-	 * @see note_public
310
-	 */
311
-	public $note;
312
-
313
-	/**
314
-	 * @var float Total amount before taxes
315
-	 * @see update_price()
316
-	 */
317
-	public $total_ht;
318
-
319
-	/**
320
-	 * @var float Total VAT amount
321
-	 * @see update_price()
322
-	 */
323
-	public $total_tva;
324
-
325
-	/**
326
-	 * @var float Total local tax 1 amount
327
-	 * @see update_price()
328
-	 */
329
-	public $total_localtax1;
330
-
331
-	/**
332
-	 * @var float Total local tax 2 amount
333
-	 * @see update_price()
334
-	 */
335
-	public $total_localtax2;
336
-
337
-	/**
338
-	 * @var float Total amount with taxes
339
-	 * @see update_price()
340
-	 */
341
-	public $total_ttc;
342
-
343
-	/**
344
-	 * @var CommonObjectLine[]
345
-	 */
346
-	public $lines;
347
-
348
-	/**
349
-	 * @var mixed		Contains comments
350
-	 * @see fetchComments()
351
-	 */
352
-	public $comments=array();
353
-
354
-	/**
355
-	 * @var int
356
-	 * @see setIncoterms()
357
-	 */
358
-	public $fk_incoterms;
359
-
360
-	/**
361
-	 * @var string
362
-	 * @see SetIncoterms()
363
-	 */
364
-	public $libelle_incoterms;
365
-
366
-	/**
367
-	 * @var string
368
-	 * @see display_incoterms()
369
-	 */
370
-	public $location_incoterms;
371
-
372
-	public $name;
373
-	public $lastname;
374
-	public $firstname;
375
-	public $civility_id;
376
-
377
-	// Dates
378
-	public $date_creation;			// Date creation
379
-	public $date_validation;		// Date validation
380
-	public $date_modification;		// Date last change (tms field)
381
-
382
-
383
-
384
-	// No constructor as it is an abstract class
385
-
386
-	/**
387
-	 * Check an object id/ref exists
388
-	 * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
389
-	 *
390
-	 *  @param	string	$element   	String of element ('product', 'facture', ...)
391
-	 *  @param	int		$id      	Id of object
392
-	 *  @param  string	$ref     	Ref of object to check
393
-	 *  @param	string	$ref_ext	Ref ext of object to check
394
-	 *  @return int     			<0 if KO, 0 if OK but not found, >0 if OK and exists
395
-	 */
396
-	static function isExistingObject($element, $id, $ref='', $ref_ext='')
397
-	{
398
-		global $db,$conf;
399
-
400
-		$sql = "SELECT rowid, ref, ref_ext";
401
-		$sql.= " FROM ".MAIN_DB_PREFIX.$element;
402
-		$sql.= " WHERE entity IN (".getEntity($element).")" ;
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)."'";
407
-		else {
408
-			$error='ErrorWrongParameters';
409
-			dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
410
-			return -1;
411
-		}
412
-		if ($ref || $ref_ext)
413
-            $sql .= " AND entity = " . Globals::$conf->entity;
50
+    /**
51
+     * @var int    Name of subtable line
52
+     */
53
+    public $table_element_line='';
414 54
 
415
-        dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
416
-		$resql = $db->query($sql);
417
-		if ($resql)
418
-		{
419
-			$num=$db->num_rows($resql);
420
-			if ($num > 0) return 1;
421
-			else return 0;
422
-		}
423
-		return -1;
424
-	}
425
-
426
-	/**
427
-	 * Method to output saved errors
428
-	 *
429
-	 * @return	string		String with errors
430
-	 */
431
-	function errorsToString()
432
-	{
433
-		return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
434
-	}
435
-
436
-	/**
437
-	 *	Return full name (civility+' '+name+' '+lastname)
438
-	 *
439
-	 *	@param	Translate	$langs			Language object for translation of civility (used only if option is 1)
440
-	 *	@param	int			$option			0=No option, 1=Add civility
441
-	 * 	@param	int			$nameorder		-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
442
-	 * 	@param	int			$maxlen			Maximum length
443
-	 * 	@return	string						String with full name
444
-	 */
445
-	function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
446
-	{
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:'')))));
451
-
452
-		$ret='';
453
-		if ($option && $this->civility_id)
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.' ';
457
-		}
458
-
459
-		$ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
55
+    /**
56
+     * @var string		Key value used to track if data is coming from import wizard
57
+     */
58
+    public $import_key;
460 59
 
461
-        return DolUtils::dol_trunc($ret, $maxlen);
462
-    }
60
+    /**
61
+     * @var mixed		Contains data to manage extrafields
62
+     */
63
+    public $array_options=array();
463 64
 
464
-	/**
465
-	 * 	Return full address of contact
466
-	 *
467
-	 * 	@param		int			$withcountry		1=Add country into address string
468
-	 *  @param		string		$sep				Separator to use to build string
469
-	 *  @param		int		    $withregion			1=Add region into address string
470
-	 *	@return		string							Full address string
471
-	 */
472
-	function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
473
-	{
474
-		if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
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'];
480
-		}
65
+    /**
66
+     * @var int[][]		Array of linked objects ids. Loaded by ->fetchObjectLinked
67
+     */
68
+    public $linkedObjectsIds;
481 69
 
482
-        if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
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'];
490
-        }
491
-
492
-		return dol_format_address($this, $withcountry, $sep);
493
-	}
494
-
495
-
496
-	/**
497
-	 * 	Return full address for banner
498
-	 *
499
-	 * 	@param		string		$htmlkey            HTML id to make banner content unique
500
-	 *  @param      Object      $object				Object (thirdparty, thirdparty of contact for contact, null for a member)
501
-	 *	@return		string							Full address string
502
-	 */
503
-	function getBannerAddress($htmlkey, $object)
504
-	{
505
-		global $conf, $langs;
506
-
507
-		$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
508
-
509
-		$contactid=0;
510
-		$thirdpartyid=0;
511
-		if ($this->element == 'societe')
512
-		{
513
-			$thirdpartyid=$this->id;
514
-		}
515
-		if ($this->element == 'contact')
516
-		{
517
-			$contactid=$this->id;
518
-			$thirdpartyid=$object->fk_soc;
519
-		}
520
-		if ($this->element == 'user')
521
-		{
522
-			$contactid=$this->contact_id;
523
-			$thirdpartyid=$object->fk_soc;
524
-		}
525
-
526
-		$out='<!-- BEGIN part to show address block -->';
527
-
528
-		$outdone=0;
529
-		$coords = $this->getFullAddress(1, ', ', Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
530
-        if ($coords)
531
-		{
532
-			if (!empty(Globals::$conf->use_javascript_ajax)) {
533
-				$namecoords = $this->getFullName($langs,1).'<br>'.$coords;
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> ';
538
-			}
539
-			$out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
540
-			$outdone++;
541
-		}
542
-
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
-            && empty(Globals::$conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
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;
547
-            }
548
-            else {
549
-                $out.=($outdone?' - ':'').$this->state;
550
-            }
551
-			$outdone++;
552
-		}
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++;
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++;
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++;
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++;
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++;
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++;
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++;
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++;
578
-		}
579
-
580
-		$out.='<div style="clear: both;"></div>';
581
-		$outdone=0;
582
-		if (! empty($this->email))
583
-		{
584
-			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
585
-			$outdone++;
586
-		}
587
-		if (! empty($this->url))
588
-		{
589
-			$out.=dol_print_url($this->url,'_goout',0,1);
590
-			$outdone++;
591
-		}
592
-		$out.='<div style="clear: both;">';
593
-		if (!empty(Globals::$conf->socialnetworks->enabled)) {
594
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
595
-			$outdone++;
596
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
597
-			$outdone++;
598
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
599
-			$outdone++;
600
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
601
-			$outdone++;
602
-		}
603
-		$out.='</div>';
604
-
605
-		$out.='<!-- END Part to show address block -->';
606
-
607
-		return $out;
608
-	}
609
-
610
-	/**
611
-	 * Return the link of last main doc file for direct public download.
612
-	 *
613
-	 * @param	string	$modulepart			Module related to document
614
-	 * @param	int		$initsharekey		Init the share key if it was not yet defined
615
-	 * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
616
-	 * @return	string						Link or empty string if there is no download link
617
-	 */
618
-	function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
619
-	{
620
-		global $user, $dolibarr_main_url_root;
621
-
622
-		if (empty($this->last_main_doc))
623
-		{
624
-			return '';		// No way to known which document name to use
625
-		}
626
-
627
-		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
628
-		$ecmfile=new EcmFiles($this->db);
629
-		$result = $ecmfile->fetch(0, '', $this->last_main_doc);
630
-		if ($result < 0)
631
-		{
632
-			$this->error = $ecmfile->error;
633
-			$this->errors = $ecmfile->errors;
634
-			return -1;
635
-		}
636
-
637
-		if (empty($ecmfile->id))
638
-		{
639
-			// Add entry into index
640
-			if ($initsharekey)
641
-			{
642
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
643
-				// TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
644
-				/*
645
-				$ecmfile->filepath = $rel_dir;
646
-				$ecmfile->filename = $filename;
647
-				$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
648
-				$ecmfile->fullpath_orig = '';
649
-				$ecmfile->gen_or_uploaded = 'generated';
650
-				$ecmfile->description = '';    // indexed content
651
-				$ecmfile->keyword = '';        // keyword content
652
-				$ecmfile->share = getRandomPassword(true);
653
-				$result = $ecmfile->create($user);
654
-				if ($result < 0)
655
-				{
656
-					$this->error = $ecmfile->error;
657
-					$this->errors = $ecmfile->errors;
658
-				}
659
-				*/
660
-			}
661
-			else return '';
662
-		}
663
-		elseif (empty($ecmfile->share))
664
-		{
665
-			// Add entry into index
666
-			if ($initsharekey)
667
-			{
668
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
669
-				$ecmfile->share = getRandomPassword(true);
670
-				$ecmfile->update($user);
671
-			}
672
-			else return '';
673
-		}
674
-
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
678
-		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
679
-
680
-		$forcedownload=0;
681
-
682
-		$paramlink='';
683
-		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
684
-		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
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';
688
-
689
-		if ($relativelink)
690
-		{
691
-			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
692
-		}
693
-		else
694
-		{
695
-			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
696
-		}
697
-
698
-		// Here $ecmfile->share is defined
699
-		return $linktoreturn;
700
-	}
70
+    /**
71
+     * @var mixed		Array of linked objects. Loaded by ->fetchObjectLinked
72
+     */
73
+    public $linkedObjects;
701 74
 
75
+    /**
76
+     * @var Object      To store a cloned copy of object before to edit it and keep track of old properties
77
+     */
78
+    public $oldcopy;
702 79
 
703
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
704
-	/**
705
-	 *  Add a link between element $this->element and a contact
706
-	 *
707
-	 *  @param	int		$fk_socpeople       Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
708
-	 *  @param 	int		$type_contact 		Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
709
-	 *  @param  string	$source             external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
710
-	 *  @param  int		$notrigger			Disable all triggers
711
-	 *  @return int                 		<0 if KO, >0 if OK
712
-	 */
713
-	function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
714
-	{
715
-        // phpcs:enable
716
-		global $user,$langs;
717
-
718
-
719
-		dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
720
-
721
-		// Check parameters
722
-		if ($fk_socpeople <= 0)
723
-		{
724
-			$langs->load("errors");
725
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","1");
726
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
727
-			return -1;
728
-		}
729
-		if (! $type_contact)
730
-		{
731
-			$langs->load("errors");
732
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","2");
733
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
734
-			return -2;
735
-		}
736
-
737
-		$id_type_contact=0;
738
-		if (is_numeric($type_contact))
739
-		{
740
-			$id_type_contact=$type_contact;
741
-		}
742
-		else
743
-		{
744
-			// We look for id type_contact
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";
750
-			//print $sql;
751
-			$resql=$this->db->query($sql);
752
-			if ($resql)
753
-			{
754
-				$obj = $this->db->fetch_object($resql);
755
-				if ($obj) $id_type_contact=$obj->rowid;
756
-			}
757
-		}
758
-
759
-		if ($id_type_contact == 0)
760
-		{
761
-			$this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
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
-			return -3;
764
-		}
765
-
766
-		$datecreate = dol_now();
767
-
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;
775
-					break;
776
-				}
777
-			}
778
-		}
80
+    /**
81
+     * @var string		Column name of the ref field.
82
+     */
83
+    protected $table_ref_field = '';
779 84
 
780
-		if(!$already_added) {
781 85
 
782
-			$this->db->begin();
783 86
 
784
-			// Insert into database
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.= ")";
87
+    // Following vars are used by some objects only. We keep this property here in CommonObject to be able to provide common method using them.
791 88
 
792
-			$resql=$this->db->query($sql);
793
-			if ($resql)
794
-			{
795
-				if (! $notrigger)
796
-				{
797
-					$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
798
-					if ($result < 0)
799
-					{
800
-						$this->db->rollback();
801
-						return -1;
802
-					}
803
-				}
89
+    /**
90
+     * @var array<string,mixed>		Can be used to pass information when only object is provided to method
91
+     */
92
+    public $context=array();
804 93
 
805
-				$this->db->commit();
806
-				return 1;
807
-			}
808
-			else
809
-			{
810
-				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
811
-				{
812
-					$this->error=$this->db->errno();
813
-					$this->db->rollback();
814
-					echo 'err rollback';
815
-					return -2;
816
-				}
817
-				else
818
-				{
819
-					$this->error=$this->db->error();
820
-					$this->db->rollback();
821
-					return -1;
822
-				}
823
-			}
824
-		} else return 0;
825
-	}
94
+    /**
95
+     * @var string		Contains canvas name if record is an alternative canvas record
96
+     */
97
+    public $canvas;
826 98
 
827
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
828
-	/**
829
-	 *    Copy contact from one element to current
830
-	 *
831
-	 *    @param    CommonObject    $objFrom    Source element
832
-	 *    @param    string          $source     Nature of contact ('internal' or 'external')
833
-	 *    @return   int                         >0 if OK, <0 if KO
834
-	 */
835
-	function copy_linked_contact($objFrom, $source='internal')
836
-	{
837
-        // phpcs:enable
838
-		$contacts = $objFrom->liste_contact(-1, $source);
839
-		foreach($contacts as $contact)
840
-		{
841
-			if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
842
-			{
843
-				$this->error=$this->db->lasterror();
844
-				return -1;
845
-			}
846
-		}
847
-		return 1;
848
-	}
99
+    /**
100
+     * @var Project The related project
101
+     * @see fetch_projet()
102
+     */
103
+    public $project;
849 104
 
850
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
851
-	/**
852
-	 *      Update a link to contact line
853
-	 *
854
-	 *      @param	int		$rowid              Id of line contact-element
855
-	 * 		@param	int		$statut	            New status of link
856
-	 *      @param  int		$type_contact_id    Id of contact type (not modified if 0)
857
-	 *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
858
-	 *      @return int                 		<0 if KO, >= 0 if OK
859
-	 */
860
-	function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
861
-	{
862
-        // phpcs:enable
863
-		// Insert into database
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);
870
-		if ($resql)
871
-		{
872
-			return 0;
873
-		}
874
-		else
875
-		{
876
-			$this->error=$this->db->lasterror();
877
-			return -1;
878
-		}
879
-	}
105
+    /**
106
+     * @var int The related project ID
107
+     * @see setProject(), project
108
+     */
109
+    public $fk_project;
880 110
 
881
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
882
-	/**
883
-	 *    Delete a link to contact line
884
-	 *
885
-	 *    @param	int		$rowid			Id of contact link line to delete
886
-	 *    @param	int		$notrigger		Disable all triggers
887
-	 *    @return   int						>0 if OK, <0 if KO
888
-	 */
889
-	function delete_contact($rowid, $notrigger=0)
890
-	{
891
-        // phpcs:enable
892
-		global $user;
111
+    /**
112
+     * @deprecated
113
+     * @see project
114
+     */
115
+    public $projet;
893 116
 
117
+    /**
118
+     * @var Contact a related contact
119
+     * @see fetch_contact()
120
+     */
121
+    public $contact;
894 122
 
895
-		$this->db->begin();
123
+    /**
124
+     * @var int The related contact ID
125
+     * @see fetch_contact()
126
+     */
127
+    public $contact_id;
896 128
 
897
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
898
-		$sql.= " WHERE rowid =".$rowid;
129
+    /**
130
+     * @var Societe A related thirdparty
131
+     * @see fetch_thirdparty()
132
+     */
133
+    public $thirdparty;
899 134
 
900
-		dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
901
-		if ($this->db->query($sql))
902
-		{
903
-			if (! $notrigger)
904
-			{
905
-				$result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
906
-				if ($result < 0) { $this->db->rollback(); return -1; }
907
-			}
908
-
909
-			$this->db->commit();
910
-			return 1;
911
-		}
912
-		else
913
-		{
914
-			$this->error=$this->db->lasterror();
915
-			$this->db->rollback();
916
-			return -1;
917
-		}
918
-	}
135
+    /**
136
+     * @var User A related user
137
+     * @see fetch_user()
138
+     */
139
+    public $user;
919 140
 
920
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
921
-	/**
922
-	 *    Delete all links between an object $this and all its contacts
923
-	 *
924
-	 *	  @param	string	$source		'' or 'internal' or 'external'
925
-	 *	  @param	string	$code		Type of contact (code or id)
926
-	 *    @return   int					>0 if OK, <0 if KO
927
-	 */
928
-	function delete_linked_contact($source='',$code='')
929
-	{
930
-        // phpcs:enable
931
-		$temp = array();
932
-		$typeContact = $this->liste_type_contact($source,'',0,0,$code);
933
-
934
-		foreach($typeContact as $key => $value)
935
-		{
936
-			array_push($temp,$key);
937
-		}
938
-		$listId = implode(",", $temp);
939
-
940
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
941
-		$sql.= " WHERE element_id = ".$this->id;
942
-		if ($listId)
943
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
944
-
945
-		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
946
-		if ($this->db->query($sql))
947
-		{
948
-			return 1;
949
-		}
950
-		else
951
-		{
952
-			$this->error=$this->db->lasterror();
953
-			return -1;
954
-		}
955
-	}
141
+    /**
142
+     * @var string 	The type of originating object ('commande', 'facture', ...)
143
+     * @see fetch_origin()
144
+     */
145
+    public $origin;
956 146
 
957
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
958
-	/**
959
-	 *    Get array of all contacts for an object
960
-	 *
961
-	 *    @param	int			$statut		Status of links to get (-1=all)
962
-	 *    @param	string		$source		Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
963
-	 *    @param	int         $list       0:Return array contains all properties, 1:Return array contains just id
964
-	 *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
965
-	 *    @return	array|int		        Array of contacts, -1 if error
966
-	 */
967
-	function liste_contact($statut=-1,$source='external',$list=0,$code='')
968
-	{
969
-        // phpcs:enable
970
-		global $langs;
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";
992
-
993
-		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
994
-		$resql=$this->db->query($sql);
995
-		if ($resql)
996
-		{
997
-			$num=$this->db->num_rows($resql);
998
-			$i=0;
999
-			while ($i < $num)
1000
-			{
1001
-				$obj = $this->db->fetch_object($resql);
147
+    /**
148
+     * @var int 	The id of originating object
149
+     * @see fetch_origin()
150
+     */
151
+    public $origin_id;
1002 152
 
1003
-				if (! $list)
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
1009
-								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1010
-								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1011
-				}
1012
-				else
1013
-				{
1014
-					$tab[$i]=$obj->id;
1015
-				}
153
+    /**
154
+     * @var string The object's reference
155
+     */
156
+    public $ref;
1016 157
 
1017
-				$i++;
1018
-			}
1019
-
1020
-			return $tab;
1021
-		}
1022
-		else
1023
-		{
1024
-			$this->error=$this->db->lasterror();
1025
-			dol_print_error($this->db);
1026
-			return -1;
1027
-		}
1028
-	}
1029
-
1030
-
1031
-	/**
1032
-	 * 		Update status of a contact linked to object
1033
-	 *
1034
-	 * 		@param	int		$rowid		Id of link between object and contact
1035
-	 * 		@return	int					<0 if KO, >=0 if OK
1036
-	 */
1037
-	function swapContactStatus($rowid)
1038
-	{
1039
-		$sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1040
-		$sql.= " tc.code, tc.libelle";
1041
-		//$sql.= ", s.fk_soc";
1042
-		$sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
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)."'";
1047
-
1048
-		dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1049
-		$resql=$this->db->query($sql);
1050
-		if ($resql)
1051
-		{
1052
-			$obj = $this->db->fetch_object($resql);
1053
-			$newstatut = ($obj->statut == 4) ? 5 : 4;
1054
-			$result = $this->update_contact($rowid, $newstatut);
1055
-			$this->db->free($resql);
1056
-			return $result;
1057
-		}
1058
-		else
1059
-		{
1060
-			$this->error=$this->db->error();
1061
-			dol_print_error($this->db);
1062
-			return -1;
1063
-		}
1064
-	}
158
+    /**
159
+     * @var string The object's previous reference
160
+     */
161
+    public $ref_previous;
1065 162
 
1066
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1067
-	/**
1068
-	 *      Return array with list of possible values for type of contacts
1069
-	 *
1070
-	 *      @param	string	$source     'internal', 'external' or 'all'
1071
-	 *      @param	string	$order		Sort order by : 'position', 'code', 'rowid'...
1072
-	 *      @param  int		$option     0=Return array id->label, 1=Return array code->label
1073
-	 *      @param  int		$activeonly 0=all status of contact, 1=only the active
1074
-	 *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1075
-	 *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1076
-	 */
1077
-	function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1078
-	{
1079
-        // phpcs:enable
1080
-		global $langs;
1081
-
1082
-		if (empty($order)) $order='position';
1083
-		if ($order == 'position') $order.=',code';
1084
-
1085
-		$tab = array();
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');
1093
-
1094
-		//print "sql=".$sql;
1095
-		$resql=$this->db->query($sql);
1096
-		if ($resql)
1097
-		{
1098
-			$num=$this->db->num_rows($resql);
1099
-			$i=0;
1100
-			while ($i < $num)
1101
-			{
1102
-				$obj = $this->db->fetch_object($resql);
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;
1108
-				$i++;
1109
-			}
1110
-			return $tab;
1111
-		}
1112
-		else
1113
-		{
1114
-			$this->error=$this->db->lasterror();
1115
-			//dol_print_error($this->db);
1116
-			return null;
1117
-		}
1118
-	}
1119
-
1120
-	/**
1121
-	 *      Return id of contacts for a source and a contact code.
1122
-	 *      Example: contact client de facturation ('external', 'BILLING')
1123
-	 *      Example: contact client de livraison ('external', 'SHIPPING')
1124
-	 *      Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
1125
-	 *
1126
-	 *		@param	string	$source		'external' or 'internal'
1127
-	 *		@param	string	$code		'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
1128
-	 *		@param	int		$status		limited to a certain status
1129
-	 *      @return array       		List of id for such contacts
1130
-	 */
1131
-	function getIdContact($source,$code,$status=0)
1132
-	{
1133
-		global $conf;
1134
-
1135
-		$result=array();
1136
-		$i=0;
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';
1144
-		} else {
1145
-			$id=$this->id;
1146
-			$element=$this->element;
1147
-		}
1148
-
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;
1164
-
1165
-		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1166
-		$resql=$this->db->query($sql);
1167
-		if ($resql)
1168
-		{
1169
-			while ($obj = $this->db->fetch_object($resql))
1170
-			{
1171
-				$result[$i]=$obj->fk_socpeople;
1172
-				$i++;
1173
-			}
1174
-		}
1175
-		else
1176
-		{
1177
-			$this->error=$this->db->error();
1178
-			return null;
1179
-		}
1180
-
1181
-		return $result;
1182
-	}
163
+    /**
164
+     * @var string The object's next reference
165
+     */
166
+    public $ref_next;
1183 167
 
1184
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1185
-	/**
1186
-	 *		Load object contact with id=$this->contactid into $this->contact
1187
-	 *
1188
-	 *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1189
-	 *		@return	int						<0 if KO, >0 if OK
1190
-	 */
1191
-	function fetch_contact($contactid=null)
1192
-	{
1193
-        // phpcs:enable
1194
-		if (empty($contactid)) $contactid=$this->contactid;
168
+    /**
169
+     * @var string An external reference for the object
170
+     */
171
+    public $ref_ext;
1195 172
 
1196
-		if (empty($contactid)) return 0;
173
+    /**
174
+     * @var int The object's status
175
+     * @see setStatut()
176
+     */
177
+    public $statut;
1197 178
 
1198
-		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1199
-		$contact = new Contact($this->db);
1200
-		$result=$contact->fetch($contactid);
1201
-		$this->contact = $contact;
1202
-		return $result;
1203
-	}
179
+    /**
180
+     * @var string
181
+     * @see getFullAddress()
182
+     */
183
+    public $country;
1204 184
 
1205
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1206
-	/**
1207
-	 *    	Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
1208
-	 *
1209
-	 *		@param		int		$force_thirdparty_id	Force thirdparty id
1210
-	 *		@return		int								<0 if KO, >0 if OK
1211
-	 */
1212
-	function fetch_thirdparty($force_thirdparty_id=0)
1213
-	{
1214
-        // phpcs:enable
1215
-		global $conf;
185
+    /**
186
+     * @var int
187
+     * @see getFullAddress(), country
188
+     */
189
+    public $country_id;
1216 190
 
1217
-		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1218
-			return 0;
191
+    /**
192
+     * @var string
193
+     * @see getFullAddress(), isInEEC(), country
194
+     */
195
+    public $country_code;
1219 196
 
1220
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
197
+    /**
198
+     * @var string
199
+     * @see getFullAddress()
200
+     */
201
+    public $state;
1221 202
 
1222
-		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1223
-		if ($force_thirdparty_id)
1224
-			$idtofetch = $force_thirdparty_id;
203
+    /**
204
+     * @var int
205
+     * @see getFullAddress(), state
206
+     */
207
+    public $state_id;
1225 208
 
1226
-		if ($idtofetch) {
1227
-			$thirdparty = new Societe($this->db);
1228
-			$result = $thirdparty->fetch($idtofetch);
1229
-			$this->thirdparty = $thirdparty;
209
+    /**
210
+     * @var string
211
+     * @see getFullAddress(), state
212
+     */
213
+    public $state_code;
1230 214
 
1231
-			// Use first price level if level not defined for third party
1232
-			if (!empty(Globals::$conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1233
-                $this->thirdparty->price_level = 1;
1234
-			}
215
+    /**
216
+     * @var string
217
+     * @see getFullAddress(), region
218
+     */
219
+    public $region;
1235 220
 
1236
-			return $result;
1237
-		} else
1238
-			return -1;
1239
-	}
221
+    /**
222
+     * @var string
223
+     * @see getFullAddress(), region
224
+     */
225
+    public $region_code;
1240 226
 
227
+    /**
228
+     * @var int
229
+     * @see fetch_barcode()
230
+     */
231
+    public $barcode_type;
1241 232
 
1242
-	/**
1243
-	 * Looks for an object with ref matching the wildcard provided
1244
-	 * It does only work when $this->table_ref_field is set
1245
-	 *
1246
-	 * @param string $ref Wildcard
1247
-	 * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
1248
-	 */
1249
-	public function fetchOneLike($ref)
1250
-	{
1251
-		if (!$this->table_ref_field) {
1252
-			return 0;
1253
-		}
233
+    /**
234
+     * @var string
235
+     * @see fetch_barcode(), barcode_type
236
+     */
237
+    public $barcode_type_code;
1254 238
 
1255
-		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
239
+    /**
240
+     * @var string
241
+     * @see fetch_barcode(), barcode_type
242
+     */
243
+    public $barcode_type_label;
1256 244
 
1257
-		$query = $this->db->query($sql);
245
+    /**
246
+     * @var string
247
+     * @see fetch_barcode(), barcode_type
248
+     */
249
+    public $barcode_type_coder;
1258 250
 
1259
-		if (!$this->db->num_rows($query)) {
1260
-			return 0;
1261
-		}
251
+    /**
252
+     * @var int Payment method ID (cheque, cash, ...)
253
+     * @see setPaymentMethods()
254
+     */
255
+    public $mode_reglement_id;
1262 256
 
1263
-		$result = $this->db->fetch_object($query);
257
+    /**
258
+     * @var int Payment terms ID
259
+     * @see setPaymentTerms()
260
+     */
261
+    public $cond_reglement_id;
1264 262
 
1265
-		return $this->fetch($result->rowid);
1266
-	}
263
+    /**
264
+     * @var int Payment terms ID
265
+     * @deprecated Kept for compatibility
266
+     * @see cond_reglement_id;
267
+     */
268
+    public $cond_reglement;
1267 269
 
1268
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1269
-	/**
1270
-	 *	Load data for barcode into properties ->barcode_type*
1271
-	 *	Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
1272
-	 *  if it is not defined, ->element must be defined to know default barcode type.
1273
-	 *
1274
-	 *	@return		int			<0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
1275
-	 */
1276
-	function fetch_barcode()
1277
-	{
1278
-        // phpcs:enable
1279
-		global $conf;
270
+    /**
271
+     * @var int Delivery address ID
272
+     * @deprecated
273
+     * @see setDeliveryAddress()
274
+     */
275
+    public $fk_delivery_address;
1280 276
 
1281
-		dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
277
+    /**
278
+     * @var int Shipping method ID
279
+     * @see setShippingMethod()
280
+     */
281
+    public $shipping_method_id;
1282 282
 
1283
-		$idtype=$this->barcode_type;
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
-		{
1286
-			if ($this->element == 'product')
1287
-                $idtype = Globals::$conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1288
-            else if ($this->element == 'societe')
1289
-                $idtype = Globals::$conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1290
-            else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1291
-		}
283
+    /**
284
+     * @var string
285
+     * @see SetDocModel()
286
+     */
287
+    public $modelpdf;
1292 288
 
1293
-		if ($idtype > 0)
1294
-		{
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
-			{
1297
-				$sql = "SELECT rowid, code, libelle as label, coder";
1298
-				$sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299
-				$sql.= " WHERE rowid = ".$idtype;
1300
-				dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1301
-				$resql = $this->db->query($sql);
1302
-				if ($resql)
1303
-				{
1304
-					$obj = $this->db->fetch_object($resql);
1305
-					$this->barcode_type       = $obj->rowid;
1306
-					$this->barcode_type_code  = $obj->code;
1307
-					$this->barcode_type_label = $obj->label;
1308
-					$this->barcode_type_coder = $obj->coder;
1309
-					return 1;
1310
-				}
1311
-				else
1312
-				{
1313
-					dol_print_error($this->db);
1314
-					return -1;
1315
-				}
1316
-			}
1317
-		}
1318
-		return 0;
1319
-	}
289
+    /**
290
+     * @var int Bank account ID
291
+     * @see SetBankAccount()
292
+     */
293
+    public $fk_account;
1320 294
 
1321
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1322
-	/**
1323
-	 *		Load the project with id $this->fk_project into this->project
1324
-	 *
1325
-	 *		@return		int			<0 if KO, >=0 if OK
1326
-	 */
1327
-	function fetch_projet()
1328
-	{
1329
-        // phpcs:enable
1330
-		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
295
+    /**
296
+     * @var string Public note
297
+     * @see update_note()
298
+     */
299
+    public $note_public;
1331 300
 
1332
-		if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet;	// For backward compatibility
1333
-		if (empty($this->fk_project)) return 0;
301
+    /**
302
+     * @var string Private note
303
+     * @see update_note()
304
+     */
305
+    public $note_private;
1334 306
 
1335
-		$project = new Project($this->db);
1336
-		$result = $project->fetch($this->fk_project);
307
+    /**
308
+     * @deprecated
309
+     * @see note_public
310
+     */
311
+    public $note;
1337 312
 
1338
-		$this->projet = $project;	// deprecated
1339
-		$this->project = $project;
1340
-		return $result;
1341
-	}
313
+    /**
314
+     * @var float Total amount before taxes
315
+     * @see update_price()
316
+     */
317
+    public $total_ht;
1342 318
 
1343
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1344
-	/**
1345
-	 *		Load the product with id $this->fk_product into this->product
1346
-	 *
1347
-	 *		@return		int			<0 if KO, >=0 if OK
1348
-	 */
1349
-	function fetch_product()
1350
-	{
1351
-        // phpcs:enable
1352
-		include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
319
+    /**
320
+     * @var float Total VAT amount
321
+     * @see update_price()
322
+     */
323
+    public $total_tva;
1353 324
 
1354
-		if (empty($this->fk_product)) return 0;
325
+    /**
326
+     * @var float Total local tax 1 amount
327
+     * @see update_price()
328
+     */
329
+    public $total_localtax1;
1355 330
 
1356
-		$product = new Product($this->db);
1357
-		$result = $product->fetch($this->fk_product);
331
+    /**
332
+     * @var float Total local tax 2 amount
333
+     * @see update_price()
334
+     */
335
+    public $total_localtax2;
1358 336
 
1359
-		$this->product = $product;
1360
-		return $result;
1361
-	}
337
+    /**
338
+     * @var float Total amount with taxes
339
+     * @see update_price()
340
+     */
341
+    public $total_ttc;
1362 342
 
1363
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1364
-	/**
1365
-	 *		Load the user with id $userid into this->user
1366
-	 *
1367
-	 *		@param	int		$userid 		Id du contact
1368
-	 *		@return	int						<0 if KO, >0 if OK
1369
-	 */
1370
-	function fetch_user($userid)
1371
-	{
1372
-        // phpcs:enable
1373
-		$user = new User($this->db);
1374
-		$result=$user->fetch($userid);
1375
-		$this->user = $user;
1376
-		return $result;
1377
-	}
343
+    /**
344
+     * @var CommonObjectLine[]
345
+     */
346
+    public $lines;
1378 347
 
1379
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1380
-	/**
1381
-	 *	Read linked origin object
1382
-	 *
1383
-	 *	@return		void
1384
-	 */
1385
-	function fetch_origin()
1386
-	{
1387
-        // phpcs:enable
1388
-		if ($this->origin == 'shipping') $this->origin = 'expedition';
1389
-		if ($this->origin == 'delivery') $this->origin = 'livraison';
1390
-        if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
348
+    /**
349
+     * @var mixed		Contains comments
350
+     * @see fetchComments()
351
+     */
352
+    public $comments=array();
1391 353
 
1392
-		$origin = $this->origin;
354
+    /**
355
+     * @var int
356
+     * @see setIncoterms()
357
+     */
358
+    public $fk_incoterms;
1393 359
 
1394
-		$classname = ucfirst($origin);
1395
-		$this->$origin = new $classname($this->db);
1396
-		$this->$origin->fetch($this->origin_id);
1397
-	}
360
+    /**
361
+     * @var string
362
+     * @see SetIncoterms()
363
+     */
364
+    public $libelle_incoterms;
1398 365
 
1399
-	/**
1400
-     *  Load object from specific field
1401
-     *
1402
-     *  @param	string	$table		Table element or element line
1403
-     *  @param	string	$field		Field selected
1404
-     *  @param	string	$key		Import key
1405
-     *  @param	string	$element	Element name
1406
-     *	@return	int					<0 if KO, >0 if OK
366
+    /**
367
+     * @var string
368
+     * @see display_incoterms()
1407 369
      */
1408
-	function fetchObjectFrom($table, $field, $key, $element = null)
1409
-	{
1410
-		global $conf;
1411
-
1412
-		$result=false;
1413
-
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).")";
1418
-		} else {
1419
-			$sql .= " AND entity = " . Globals::$conf->entity;
1420
-        }
1421
-
1422
-		dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1423
-		$resql = $this->db->query($sql);
1424
-		if ($resql)
1425
-		{
1426
-			$row = $this->db->fetch_row($resql);
1427
-			// Test for avoid error -1
1428
-			if ($row[0] > 0) {
1429
-				$result = $this->fetch($row[0]);
1430
-			}
1431
-		}
1432
-
1433
-		return $result;
1434
-	}
1435
-
1436
-	/**
1437
-	 *	Getter generic. Load value from a specific field
1438
-	 *
1439
-	 *	@param	string	$table		Table of element or element line
1440
-	 *	@param	int		$id			Element id
1441
-	 *	@param	string	$field		Field selected
1442
-	 *	@return	int					<0 if KO, >0 if OK
1443
-	 */
1444
-	function getValueFrom($table, $id, $field)
1445
-	{
1446
-		$result=false;
1447
-		if (!empty($id) && !empty($field) && !empty($table)) {
1448
-			$sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
1449
-			$sql.= " WHERE rowid = ".$id;
1450
-
1451
-			dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1452
-			$resql = $this->db->query($sql);
1453
-			if ($resql)
1454
-			{
1455
-				$row = $this->db->fetch_row($resql);
1456
-				$result = $row[0];
1457
-			}
1458
-		}
1459
-		return $result;
1460
-	}
1461
-
1462
-	/**
1463
-	 *	Setter generic. Update a specific field into database.
1464
-	 *  Warning: Trigger is run only if param trigkey is provided.
1465
-	 *
1466
-	 *	@param	string		$field			Field to update
1467
-	 *	@param	mixed		$value			New value
1468
-	 *	@param	string		$table			To force other table element or element line (should not be used)
1469
-	 *	@param	int			$id				To force other object id (should not be used)
1470
-	 *	@param	string		$format			Data format ('text', 'date'). 'text' is used if not defined
1471
-	 *	@param	string		$id_field		To force rowid field name. 'rowid' is used if not defined
1472
-	 *	@param	User|string	$fuser			Update the user of last update field with this user. If not provided, current user is used except if value is 'none'
1473
-	 *  @param  string      $trigkey    	Trigger key to run (in most cases something like 'XXX_MODIFY')
1474
-	 *  @param	string		$fk_user_field	Name of field to save user id making change
1475
-	 *	@return	int							<0 if KO, >0 if OK
1476
-	 *  @see updateExtraField
1477
-	 */
1478
-	function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
1479
-	{
1480
-		global $user,$langs,$conf;
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';
1486
-
1487
-		$error=0;
1488
-
1489
-		$this->db->begin();
1490
-
1491
-		// Special case
1492
-		if ($table == 'product' && $field == 'note_private') $field='note';
1493
-		if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
1494
-
1495
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
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");
1500
-
1501
-		if ($fk_user_field)
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;
1505
-		}
1506
-
1507
-		$sql.= " WHERE ".$id_field." = ".$id;
1508
-
1509
-		dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
1510
-		$resql = $this->db->query($sql);
1511
-		if ($resql)
1512
-		{
1513
-			if ($trigkey)
1514
-			{
1515
-				// call trigger with updated object values
1516
-				if (empty($this->fields) && method_exists($this, 'fetch'))
1517
-				{
1518
-					$result = $this->fetch($id);
1519
-				}
1520
-				else
1521
-				{
1522
-					$result = $this->fetchCommon($id);
1523
-				}
1524
-				if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);   // This may set this->errors
1525
-				if ($result < 0) $error++;
1526
-			}
370
+    public $location_incoterms;
1527 371
 
1528
-			if (! $error)
1529
-			{
1530
-				if (property_exists($this, $field)) $this->$field = $value;
1531
-				$this->db->commit();
1532
-				return 1;
1533
-			}
1534
-			else
1535
-			{
1536
-				$this->db->rollback();
1537
-				return -2;
1538
-			}
1539
-		}
1540
-		else
1541
-		{
1542
-			$this->error=$this->db->lasterror();
1543
-			$this->db->rollback();
1544
-			return -1;
1545
-		}
1546
-	}
372
+    public $name;
373
+    public $lastname;
374
+    public $firstname;
375
+    public $civility_id;
1547 376
 
1548
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1549
-	/**
1550
-	 *      Load properties id_previous and id_next by comparing $fieldid with $this->ref
1551
-	 *
1552
-	 *      @param	string	$filter		Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
1553
-	 *	 	@param  string	$fieldid   	Name of field to use for the select MAX and MIN
1554
-	 *		@param	int		$nodbprefix	Do not include DB prefix to forge table name
1555
-	 *      @return int         		<0 if KO, >0 if OK
1556
-	 */
1557
-	function load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
1558
-	{
1559
-        // phpcs:enable
1560
-		global $conf, $user;
1561
-
1562
-		if (! $this->table_element)
1563
-		{
1564
-			dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1565
-			return -1;
1566
-		}
1567
-		if ($fieldid == 'none') return 1;
1568
-
1569
-		// Security on socid
1570
-		$socid = 0;
1571
-		if ($user->societe_id > 0) $socid = $user->societe_id;
1572
-
1573
-		// this->ismultientitymanaged contains
1574
-		// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
1575
-		$alias = 's';
1576
-		if ($this->element == 'societe') $alias = 'te';
1577
-
1578
-		$sql = "SELECT MAX(te.".$fieldid.")";
1579
-		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
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
1597
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598
-			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
-                if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1600
-                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1601
-				} else {
1602
-					$sql.= " AND ug.fk_user = te.rowid";
1603
-					$sql.= " AND ug.entity IN (".getEntity($this->element).")";
1604
-				}
1605
-			} else {
1606
-				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1607
-			}
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;
1612
-		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1613
-
1614
-		$result = $this->db->query($sql);
1615
-		if (! $result)
1616
-		{
1617
-			$this->error=$this->db->lasterror();
1618
-			return -1;
1619
-		}
1620
-		$row = $this->db->fetch_row($result);
1621
-		$this->ref_previous = $row[0];
1622
-
1623
-
1624
-		$sql = "SELECT MIN(te.".$fieldid.")";
1625
-		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
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
1643
-		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644
-			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
-                if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1646
-                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1647
-				} else {
1648
-					$sql.= " AND ug.fk_user = te.rowid";
1649
-					$sql.= " AND ug.entity IN (".getEntity($this->element).")";
1650
-				}
1651
-			} else {
1652
-				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1653
-			}
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;
1658
-		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
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
-
1661
-		$result = $this->db->query($sql);
1662
-		if (! $result)
1663
-		{
1664
-			$this->error=$this->db->lasterror();
1665
-			return -2;
1666
-		}
1667
-		$row = $this->db->fetch_row($result);
1668
-		$this->ref_next = $row[0];
1669
-
1670
-		return 1;
1671
-	}
1672
-
1673
-
1674
-	/**
1675
-	 *      Return list of id of contacts of object
1676
-	 *
1677
-	 *      @param	string	$source     Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
1678
-	 *      @return array				Array of id of contacts (if source=external or internal)
1679
-	 * 									Array of id of third parties with at least one contact on object (if source=thirdparty)
1680
-	 */
1681
-	function getListContactId($source='external')
1682
-	{
1683
-		$contactAlreadySelected = array();
1684
-		$tab = $this->liste_contact(-1,$source);
1685
-		$num=count($tab);
1686
-		$i = 0;
1687
-		while ($i < $num)
1688
-		{
1689
-			if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
1690
-			else  $contactAlreadySelected[$i] = $tab[$i]['id'];
1691
-			$i++;
1692
-		}
1693
-		return $contactAlreadySelected;
1694
-	}
1695
-
1696
-
1697
-	/**
1698
-	 *	Link element with a project
1699
-	 *
1700
-	 *	@param     	int		$projectid		Project id to link element to
1701
-	 *	@return		int						<0 if KO, >0 if OK
1702
-	 */
1703
-	function setProject($projectid)
1704
-	{
1705
-		if (! $this->table_element)
1706
-		{
1707
-			dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
1708
-			return -1;
1709
-		}
1710
-
1711
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1712
-		if ($this->table_element == 'actioncomm')
1713
-		{
1714
-			if ($projectid) $sql.= ' SET fk_project = '.$projectid;
1715
-			else $sql.= ' SET fk_project = NULL';
1716
-			$sql.= ' WHERE id = '.$this->id;
1717
-		}
1718
-		else
1719
-		{
1720
-			if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
1721
-			else $sql.= ' SET fk_projet = NULL';
1722
-			$sql.= ' WHERE rowid = '.$this->id;
1723
-		}
1724
-
1725
-		dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
1726
-		if ($this->db->query($sql))
1727
-		{
1728
-			$this->fk_project = $projectid;
1729
-			return 1;
1730
-		}
1731
-		else
1732
-		{
1733
-			dol_print_error($this->db);
1734
-			return -1;
1735
-		}
1736
-	}
1737
-
1738
-	/**
1739
-	 *  Change the payments methods
1740
-	 *
1741
-	 *  @param		int		$id		Id of new payment method
1742
-	 *  @return		int				>0 if OK, <0 if KO
1743
-	 */
1744
-	function setPaymentMethods($id)
1745
-	{
1746
-		dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
1747
-		if ($this->statut >= 0 || $this->element == 'societe')
1748
-		{
1749
-			// TODO uniformize field name
1750
-			$fieldname = 'fk_mode_reglement';
1751
-			if ($this->element == 'societe') $fieldname = 'mode_reglement';
1752
-			if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
1753
-
1754
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1755
-			$sql .= ' SET '.$fieldname.' = '.$id;
1756
-			$sql .= ' WHERE rowid='.$this->id;
1757
-
1758
-			if ($this->db->query($sql))
1759
-			{
1760
-				$this->mode_reglement_id = $id;
1761
-				// for supplier
1762
-				if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
1763
-				return 1;
1764
-			}
1765
-			else
1766
-			{
1767
-				dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
1768
-				$this->error=$this->db->error();
1769
-				return -1;
1770
-			}
1771
-		}
1772
-		else
1773
-		{
1774
-			dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
1775
-			$this->error='Status of the object is incompatible '.$this->statut;
1776
-			return -2;
1777
-		}
1778
-	}
1779
-
1780
-	/**
1781
-	 *  Change the multicurrency code
1782
-	 *
1783
-	 *  @param		string	$code	multicurrency code
1784
-	 *  @return		int				>0 if OK, <0 if KO
1785
-	 */
1786
-	function setMulticurrencyCode($code)
1787
-	{
1788
-		dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')');
1789
-		if ($this->statut >= 0 || $this->element == 'societe')
1790
-		{
1791
-			$fieldname = 'multicurrency_code';
1792
-
1793
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1794
-			$sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
1795
-			$sql .= ' WHERE rowid='.$this->id;
1796
-
1797
-			if ($this->db->query($sql))
1798
-			{
1799
-				$this->multicurrency_code = $code;
377
+    // Dates
378
+    public $date_creation;			// Date creation
379
+    public $date_validation;		// Date validation
380
+    public $date_modification;		// Date last change (tms field)
1800 381
 
1801
-				list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
-				if ($rate) $this->setMulticurrencyRate($rate,2);
1803 382
 
1804
-				return 1;
1805
-			}
1806
-			else
1807
-			{
1808
-				dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
1809
-				$this->error=$this->db->error();
1810
-				return -1;
1811
-			}
1812
-		}
1813
-		else
1814
-		{
1815
-			dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
1816
-			$this->error='Status of the object is incompatible '.$this->statut;
1817
-			return -2;
1818
-		}
1819
-	}
1820
-
1821
-	/**
1822
-	 *  Change the multicurrency rate
1823
-	 *
1824
-	 *  @param		double	$rate	multicurrency rate
1825
-	 *  @param		int		$mode	mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency
1826
-	 *  @return		int				>0 if OK, <0 if KO
1827
-	 */
1828
-	function setMulticurrencyRate($rate, $mode=1)
1829
-	{
1830
-		dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
1831
-		if ($this->statut >= 0 || $this->element == 'societe')
1832
-		{
1833
-			$fieldname = 'multicurrency_tx';
1834
-
1835
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1836
-			$sql .= ' SET '.$fieldname.' = '.$rate;
1837
-			$sql .= ' WHERE rowid='.$this->id;
1838
-
1839
-			if ($this->db->query($sql))
1840
-			{
1841
-				$this->multicurrency_tx = $rate;
1842 383
 
1843
-				// Update line price
1844
-				if (!empty($this->lines))
1845
-				{
1846
-					foreach ($this->lines as &$line)
1847
-					{
1848
-						if($mode == 1) {
1849
-							$line->subprice = 0;
1850
-						}
384
+    // No constructor as it is an abstract class
1851 385
 
1852
-						switch ($this->element) {
1853
-							case 'propal':
1854
-								$this->updateline(
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,
1857
-									$line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
1858
-									$line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1859
-								);
1860
-								break;
1861
-							case 'commande':
1862
-								$this->updateline(
1863
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1864
-									$line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
1865
-									$line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1866
-									$line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1867
-								);
1868
-								break;
1869
-							case 'facture':
1870
-								$this->updateline(
1871
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1872
-									$line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
1873
-									$line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1874
-									$line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
1875
-								);
1876
-								break;
1877
-							case 'supplier_proposal':
1878
-								$this->updateline(
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,
1881
-									$line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
1882
-									$line->ref_fourn, $line->multicurrency_subprice
1883
-								);
1884
-								break;
1885
-							case 'order_supplier':
1886
-								$this->updateline(
1887
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1888
-									$line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
1889
-									$line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1890
-								);
1891
-								break;
1892
-							case 'invoice_supplier':
1893
-								$this->updateline(
1894
-									$line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
1895
-									$line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
1896
-									$line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1897
-								);
1898
-								break;
1899
-							default:
1900
-								dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
1901
-								break;
1902
-						}
1903
-					}
1904
-				}
386
+    /**
387
+     * Check an object id/ref exists
388
+     * If you don't need/want to instantiate object and just need to know if object exists, use this method instead of fetch
389
+     *
390
+     *  @param	string	$element   	String of element ('product', 'facture', ...)
391
+     *  @param	int		$id      	Id of object
392
+     *  @param  string	$ref     	Ref of object to check
393
+     *  @param	string	$ref_ext	Ref ext of object to check
394
+     *  @return int     			<0 if KO, 0 if OK but not found, >0 if OK and exists
395
+     */
396
+    static function isExistingObject($element, $id, $ref='', $ref_ext='')
397
+    {
398
+        global $db,$conf;
399
+
400
+        $sql = "SELECT rowid, ref, ref_ext";
401
+        $sql.= " FROM ".MAIN_DB_PREFIX.$element;
402
+        $sql.= " WHERE entity IN (".getEntity($element).")" ;
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)."'";
407
+        else {
408
+            $error='ErrorWrongParameters';
409
+            dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
410
+            return -1;
411
+        }
412
+        if ($ref || $ref_ext)
413
+            $sql .= " AND entity = " . Globals::$conf->entity;
1905 414
 
1906
-				return 1;
1907
-			}
1908
-			else
1909
-			{
1910
-				dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
1911
-				$this->error=$this->db->error();
1912
-				return -1;
1913
-			}
1914
-		}
1915
-		else
1916
-		{
1917
-			dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
1918
-			$this->error='Status of the object is incompatible '.$this->statut;
1919
-			return -2;
1920
-		}
1921
-	}
1922
-
1923
-	/**
1924
-	 *  Change the payments terms
1925
-	 *
1926
-	 *  @param		int		$id		Id of new payment terms
1927
-	 *  @return		int				>0 if OK, <0 if KO
1928
-	 */
1929
-	function setPaymentTerms($id)
1930
-	{
1931
-		dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
1932
-		if ($this->statut >= 0 || $this->element == 'societe')
1933
-		{
1934
-			// TODO uniformize field name
1935
-			$fieldname = 'fk_cond_reglement';
1936
-			if ($this->element == 'societe') $fieldname = 'cond_reglement';
1937
-			if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
1938
-
1939
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1940
-			$sql .= ' SET '.$fieldname.' = '.$id;
1941
-			$sql .= ' WHERE rowid='.$this->id;
1942
-
1943
-			if ($this->db->query($sql))
1944
-			{
1945
-				$this->cond_reglement_id = $id;
1946
-				// for supplier
1947
-				if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
1948
-				$this->cond_reglement = $id;	// for compatibility
1949
-				return 1;
1950
-			}
1951
-			else
1952
-			{
1953
-				dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
1954
-				$this->error=$this->db->error();
1955
-				return -1;
1956
-			}
1957
-		}
1958
-		else
1959
-		{
1960
-			dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
1961
-			$this->error='Status of the object is incompatible '.$this->statut;
1962
-			return -2;
1963
-		}
1964
-	}
1965
-
1966
-	/**
1967
-	 *	Define delivery address
1968
-	 *  @deprecated
1969
-	 *
1970
-	 *	@param      int		$id		Address id
1971
-	 *	@return     int				<0 si ko, >0 si ok
1972
-	 */
1973
-	function setDeliveryAddress($id)
1974
-	{
1975
-		$fieldname = 'fk_delivery_address';
1976
-		if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
1977
-
1978
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
1979
-		$sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
1980
-
1981
-		if ($this->db->query($sql))
1982
-		{
1983
-			$this->fk_delivery_address = $id;
1984
-			return 1;
1985
-		}
1986
-		else
1987
-		{
1988
-			$this->error=$this->db->error();
1989
-			dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
1990
-			return -1;
1991
-		}
1992
-	}
1993
-
1994
-
1995
-	/**
1996
-	 *  Change the shipping method
1997
-	 *
1998
-	 *  @param      int     $shipping_method_id     Id of shipping method
1999
-     *  @param      bool    $notrigger              false=launch triggers after, true=disable triggers
2000
-     *  @param      User	$userused               Object user
2001
-	 *
2002
-	 *  @return     int              1 if OK, 0 if KO
2003
-	 */
2004
-	function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
2005
-	{
2006
-        global $user;
415
+        dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
416
+        $resql = $db->query($sql);
417
+        if ($resql)
418
+        {
419
+            $num=$db->num_rows($resql);
420
+            if ($num > 0) return 1;
421
+            else return 0;
422
+        }
423
+        return -1;
424
+    }
2007 425
 
2008
-        if (empty($userused)) $userused=$user;
426
+    /**
427
+     * Method to output saved errors
428
+     *
429
+     * @return	string		String with errors
430
+     */
431
+    function errorsToString()
432
+    {
433
+        return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
434
+    }
2009 435
 
2010
-        $error = 0;
436
+    /**
437
+     *	Return full name (civility+' '+name+' '+lastname)
438
+     *
439
+     *	@param	Translate	$langs			Language object for translation of civility (used only if option is 1)
440
+     *	@param	int			$option			0=No option, 1=Add civility
441
+     * 	@param	int			$nameorder		-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
442
+     * 	@param	int			$maxlen			Maximum length
443
+     * 	@return	string						String with full name
444
+     */
445
+    function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
446
+    {
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:'')))));
2011 451
 
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
-			return -1;
2015
-		}
452
+        $ret='';
453
+        if ($option && $this->civility_id)
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.' ';
457
+        }
2016 458
 
2017
-        $this->db->begin();
459
+        $ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
2018 460
 
2019
-		if ($shipping_method_id<0) $shipping_method_id='NULL';
2020
-		dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
461
+        return DolUtils::dol_trunc($ret, $maxlen);
462
+    }
2021 463
 
2022
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2023
-		$sql.= " SET fk_shipping_method = ".$shipping_method_id;
2024
-		$sql.= " WHERE rowid=".$this->id;
2025
-        $resql = $this->db->query($sql);
2026
-		if (! $resql) {
2027
-			dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2028
-			$this->error = $this->db->lasterror();
2029
-			$error++;
2030
-        } else {
2031
-            if (!$notrigger)
2032
-            {
2033
-                // Call trigger
2034
-                $this->context=array('shippingmethodupdate'=>1);
2035
-                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2036
-                if ($result < 0) $error++;
2037
-                // End call trigger
2038
-            }
2039
-        }
2040
-        if ($error)
464
+    /**
465
+     * 	Return full address of contact
466
+     *
467
+     * 	@param		int			$withcountry		1=Add country into address string
468
+     *  @param		string		$sep				Separator to use to build string
469
+     *  @param		int		    $withregion			1=Add region into address string
470
+     *	@return		string							Full address string
471
+     */
472
+    function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
473
+    {
474
+        if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
2041 475
         {
2042
-            $this->db->rollback();
2043
-            return -1;
2044
-        } else {
2045
-            $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
2046
-            $this->db->commit();
2047
-            return 1;
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'];
2048 480
         }
2049
-	}
2050
-
2051
-
2052
-	/**
2053
-	 *  Change the warehouse
2054
-	 *
2055
-	 *  @param      int     $warehouse_id     Id of warehouse
2056
-	 *  @return     int              1 if OK, 0 if KO
2057
-	 */
2058
-	function setWarehouse($warehouse_id)
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);
2062
-			return -1;
2063
-		}
2064
-		if ($warehouse_id<0) $warehouse_id='NULL';
2065
-		dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2066
-
2067
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2068
-		$sql.= " SET fk_warehouse = ".$warehouse_id;
2069
-		$sql.= " WHERE rowid=".$this->id;
2070
-
2071
-		if ($this->db->query($sql)) {
2072
-			$this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
2073
-			return 1;
2074
-		} else {
2075
-			dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2076
-			$this->error=$this->db->error();
2077
-			return 0;
2078
-		}
2079
-	}
2080
-
2081
-
2082
-	/**
2083
-	 *		Set last model used by doc generator
2084
-	 *
2085
-	 *		@param		User	$user		User object that make change
2086
-	 *		@param		string	$modelpdf	Modele name
2087
-	 *		@return		int					<0 if KO, >0 if OK
2088
-	 */
2089
-	function setDocModel($user, $modelpdf)
2090
-	{
2091
-		if (! $this->table_element)
2092
-		{
2093
-			dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
2094
-			return -1;
2095
-		}
2096
-
2097
-		$newmodelpdf=dol_trunc($modelpdf,255);
2098
-
2099
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2100
-		$sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2101
-		$sql.= " WHERE rowid = ".$this->id;
2102
-		// if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
2103
-		// if ($this->element == 'propal')  $sql.= " AND fk_statut = 0";
2104
-
2105
-		dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2106
-		$resql=$this->db->query($sql);
2107
-		if ($resql)
2108
-		{
2109
-			$this->modelpdf=$modelpdf;
2110
-			return 1;
2111
-		}
2112
-		else
2113
-		{
2114
-			dol_print_error($this->db);
2115
-			return 0;
2116
-		}
2117
-	}
2118
-
2119
-
2120
-	/**
2121
-	 *  Change the bank account
2122
-	 *
2123
-	 *  @param		int		$fk_account		Id of bank account
2124
-	 *  @param      bool    $notrigger      false=launch triggers after, true=disable triggers
2125
-	 *  @param      User	$userused		Object user
2126
-	 *  @return		int				1 if OK, 0 if KO
2127
-	 */
2128
-	function setBankAccount($fk_account, $notrigger=false, $userused=null)
2129
-	{
2130
-        global $user;
2131 481
 
2132
-        if (empty($userused)) $userused=$user;
482
+        if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
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'];
490
+        }
2133 491
 
2134
-        $error = 0;
492
+        return dol_format_address($this, $withcountry, $sep);
493
+    }
2135 494
 
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
-			return -1;
2139
-		}
2140
-        $this->db->begin();
2141 495
 
2142
-		if ($fk_account<0) $fk_account='NULL';
2143
-		dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
496
+    /**
497
+     * 	Return full address for banner
498
+     *
499
+     * 	@param		string		$htmlkey            HTML id to make banner content unique
500
+     *  @param      Object      $object				Object (thirdparty, thirdparty of contact for contact, null for a member)
501
+     *	@return		string							Full address string
502
+     */
503
+    function getBannerAddress($htmlkey, $object)
504
+    {
505
+        global $conf, $langs;
2144 506
 
2145
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2146
-		$sql.= " SET fk_account = ".$fk_account;
2147
-		$sql.= " WHERE rowid=".$this->id;
507
+        $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
2148 508
 
2149
-        $resql = $this->db->query($sql);
2150
-        if (! $resql)
509
+        $contactid=0;
510
+        $thirdpartyid=0;
511
+        if ($this->element == 'societe')
2151 512
         {
2152
-            dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153
-            $this->error = $this->db->lasterror();
2154
-            $error++;
513
+            $thirdpartyid=$this->id;
2155 514
         }
2156
-        else
515
+        if ($this->element == 'contact')
2157 516
         {
2158
-            if (!$notrigger)
2159
-            {
2160
-                // Call trigger
2161
-                $this->context=array('bankaccountupdate'=>1);
2162
-                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2163
-                if ($result < 0) $error++;
2164
-                // End call trigger
2165
-            }
517
+            $contactid=$this->id;
518
+            $thirdpartyid=$object->fk_soc;
2166 519
         }
2167
-        if ($error)
520
+        if ($this->element == 'user')
2168 521
         {
2169
-            $this->db->rollback();
2170
-            return -1;
522
+            $contactid=$this->contact_id;
523
+            $thirdpartyid=$object->fk_soc;
2171 524
         }
2172
-        else
525
+
526
+        $out='<!-- BEGIN part to show address block -->';
527
+
528
+        $outdone=0;
529
+        $coords = $this->getFullAddress(1, ', ', Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
530
+        if ($coords)
2173 531
         {
2174
-            $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2175
-            $this->db->commit();
2176
-            return 1;
532
+            if (!empty(Globals::$conf->use_javascript_ajax)) {
533
+                $namecoords = $this->getFullName($langs,1).'<br>'.$coords;
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> ';
538
+            }
539
+            $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
540
+            $outdone++;
2177 541
         }
2178
-    }
2179 542
 
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
+            && empty(Globals::$conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
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;
547
+            }
548
+            else {
549
+                $out.=($outdone?' - ':'').$this->state;
550
+            }
551
+            $outdone++;
552
+        }
2180 553
 
2181
-	// TODO: Move line related operations to CommonObjectLine?
2182
-
2183
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2184
-	/**
2185
-	 *  Save a new position (field rang) for details lines.
2186
-	 *  You can choose to set position for lines with already a position or lines without any position defined.
2187
-	 *
2188
-	 * 	@param		boolean		$renum			   True to renum all already ordered lines, false to renum only not already ordered lines.
2189
-	 * 	@param		string		$rowidorder		   ASC or DESC
2190
-	 * 	@param		boolean		$fk_parent_line    Table with fk_parent_line field or not
2191
-	 * 	@return		int                            <0 if KO, >0 if OK
2192
-	 */
2193
-	function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
2194
-	{
2195
-        // phpcs:enable
2196
-		if (! $this->table_element_line)
2197
-		{
2198
-			dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
2199
-			return -1;
2200
-		}
2201
-		if (! $this->fk_element)
2202
-		{
2203
-			dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
2204
-			return -1;
2205
-		}
2206
-
2207
-		// Count number of lines to reorder (according to choice $renum)
2208
-		$nl=0;
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';
2213
-
2214
-		dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
2215
-		$resql = $this->db->query($sql);
2216
-		if ($resql)
2217
-		{
2218
-			$row = $this->db->fetch_row($resql);
2219
-			$nl = $row[0];
2220
-		}
2221
-		else dol_print_error($this->db);
2222
-		if ($nl > 0)
2223
-		{
2224
-			// The goal of this part is to reorder all lines, with all children lines sharing the same
2225
-			// counter that parents.
2226
-			$rows=array();
2227
-
2228
-			// We first search all lines that are parent lines (for multilevel details lines)
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;
2233
-
2234
-			dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
2235
-			$resql = $this->db->query($sql);
2236
-			if ($resql)
2237
-			{
2238
-				$i=0;
2239
-				$num = $this->db->num_rows($resql);
2240
-				while ($i < $num)
2241
-				{
2242
-					$row = $this->db->fetch_row($resql);
2243
-					$rows[] = $row[0];	// Add parent line into array rows
2244
-					$childrens = $this->getChildrenOfLine($row[0]);
2245
-					if (! empty($childrens))
2246
-					{
2247
-						foreach($childrens as $child)
2248
-						{
2249
-							array_push($rows, $child);
2250
-						}
2251
-					}
2252
-					$i++;
2253
-				}
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
+        }
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
+        }
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
+        }
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
+        }
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
+        }
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
+        }
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
+        }
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
+        }
2254 579
 
2255
-				// Now we set a new number for each lines (parent and children with children included into parent tree)
2256
-				if (! empty($rows))
2257
-				{
2258
-					foreach($rows as $key => $row)
2259
-					{
2260
-						$this->updateRangOfLine($row, ($key+1));
2261
-					}
2262
-				}
2263
-			}
2264
-			else
2265
-			{
2266
-				dol_print_error($this->db);
2267
-			}
2268
-		}
2269
-		return 1;
2270
-	}
2271
-
2272
-	/**
2273
-	 * 	Get children of line
2274
-	 *
2275
-	 * 	@param	int		$id		Id of parent line
2276
-	 * 	@return	array			Array with list of children lines id
2277
-	 */
2278
-	function getChildrenOfLine($id)
2279
-	{
2280
-		$rows=array();
2281
-
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';
2286
-
2287
-		dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
2288
-		$resql = $this->db->query($sql);
2289
-		if ($resql)
2290
-		{
2291
-			$i=0;
2292
-			$num = $this->db->num_rows($resql);
2293
-			while ($i < $num)
2294
-			{
2295
-				$row = $this->db->fetch_row($resql);
2296
-				$rows[$i] = $row[0];
2297
-				$i++;
2298
-			}
2299
-		}
580
+        $out.='<div style="clear: both;"></div>';
581
+        $outdone=0;
582
+        if (! empty($this->email))
583
+        {
584
+            $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
585
+            $outdone++;
586
+        }
587
+        if (! empty($this->url))
588
+        {
589
+            $out.=dol_print_url($this->url,'_goout',0,1);
590
+            $outdone++;
591
+        }
592
+        $out.='<div style="clear: both;">';
593
+        if (!empty(Globals::$conf->socialnetworks->enabled)) {
594
+            if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
595
+            $outdone++;
596
+            if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
597
+            $outdone++;
598
+            if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
599
+            $outdone++;
600
+            if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
601
+            $outdone++;
602
+        }
603
+        $out.='</div>';
2300 604
 
2301
-		return $rows;
2302
-	}
605
+        $out.='<!-- END Part to show address block -->';
2303 606
 
2304
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2305
-	/**
2306
-	 * 	Update a line to have a lower rank
2307
-	 *
2308
-	 * 	@param 	int			$rowid				Id of line
2309
-	 * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2310
-	 * 	@return	void
2311
-	 */
2312
-	function line_up($rowid, $fk_parent_line=true)
2313
-	{
2314
-        // phpcs:enable
2315
-		$this->line_order(false, 'ASC', $fk_parent_line);
607
+        return $out;
608
+    }
2316 609
 
2317
-		// Get rang of line
2318
-		$rang = $this->getRangOfLine($rowid);
610
+    /**
611
+     * Return the link of last main doc file for direct public download.
612
+     *
613
+     * @param	string	$modulepart			Module related to document
614
+     * @param	int		$initsharekey		Init the share key if it was not yet defined
615
+     * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
616
+     * @return	string						Link or empty string if there is no download link
617
+     */
618
+    function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
619
+    {
620
+        global $user, $dolibarr_main_url_root;
2319 621
 
2320
-		// Update position of line
2321
-		$this->updateLineUp($rowid, $rang);
2322
-	}
622
+        if (empty($this->last_main_doc))
623
+        {
624
+            return '';		// No way to known which document name to use
625
+        }
2323 626
 
2324
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2325
-	/**
2326
-	 * 	Update a line to have a higher rank
2327
-	 *
2328
-	 * 	@param	int			$rowid				Id of line
2329
-	 * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2330
-	 * 	@return	void
2331
-	 */
2332
-	function line_down($rowid, $fk_parent_line=true)
2333
-	{
2334
-        // phpcs:enable
2335
-		$this->line_order(false, 'ASC', $fk_parent_line);
2336
-
2337
-		// Get rang of line
2338
-		$rang = $this->getRangOfLine($rowid);
2339
-
2340
-		// Get max value for rang
2341
-		$max = $this->line_max();
2342
-
2343
-		// Update position of line
2344
-		$this->updateLineDown($rowid, $rang, $max);
2345
-	}
2346
-
2347
-	/**
2348
-	 * 	Update position of line (rang)
2349
-	 *
2350
-	 * 	@param	int		$rowid		Id of line
2351
-	 * 	@param	int		$rang		Position
2352
-	 * 	@return	void
2353
-	 */
2354
-	function updateRangOfLine($rowid,$rang)
2355
-	{
2356
-		$fieldposition = 'rang';
2357
-		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2358
-
2359
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2360
-		$sql.= ' WHERE rowid = '.$rowid;
2361
-
2362
-		dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
2363
-		if (! $this->db->query($sql))
2364
-		{
2365
-			dol_print_error($this->db);
2366
-		}
2367
-	}
627
+        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
628
+        $ecmfile=new EcmFiles($this->db);
629
+        $result = $ecmfile->fetch(0, '', $this->last_main_doc);
630
+        if ($result < 0)
631
+        {
632
+            $this->error = $ecmfile->error;
633
+            $this->errors = $ecmfile->errors;
634
+            return -1;
635
+        }
2368 636
 
2369
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2370
-	/**
2371
-	 * 	Update position of line with ajax (rang)
2372
-	 *
2373
-	 * 	@param	array	$rows	Array of rows
2374
-	 * 	@return	void
2375
-	 */
2376
-	function line_ajaxorder($rows)
2377
-	{
2378
-        // phpcs:enable
2379
-		$num = count($rows);
2380
-		for ($i = 0 ; $i < $num ; $i++)
2381
-		{
2382
-			$this->updateRangOfLine($rows[$i], ($i+1));
2383
-		}
2384
-	}
2385
-
2386
-	/**
2387
-	 * 	Update position of line up (rang)
2388
-	 *
2389
-	 * 	@param	int		$rowid		Id of line
2390
-	 * 	@param	int		$rang		Position
2391
-	 * 	@return	void
2392
-	 */
2393
-	function updateLineUp($rowid,$rang)
2394
-	{
2395
-		if ($rang > 1)
2396
-		{
2397
-			$fieldposition = 'rang';
2398
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
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) )
2404
-			{
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) )
2408
-				{
2409
-					dol_print_error($this->db);
2410
-				}
2411
-			}
2412
-			else
2413
-			{
2414
-				dol_print_error($this->db);
2415
-			}
2416
-		}
2417
-	}
2418
-
2419
-	/**
2420
-	 * 	Update position of line down (rang)
2421
-	 *
2422
-	 * 	@param	int		$rowid		Id of line
2423
-	 * 	@param	int		$rang		Position
2424
-	 * 	@param	int		$max		Max
2425
-	 * 	@return	void
2426
-	 */
2427
-	function updateLineDown($rowid,$rang,$max)
2428
-	{
2429
-		if ($rang < $max)
2430
-		{
2431
-			$fieldposition = 'rang';
2432
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2433
-
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) )
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) )
637
+        if (empty($ecmfile->id))
638
+        {
639
+            // Add entry into index
640
+            if ($initsharekey)
641
+            {
642
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
643
+                // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
644
+                /*
645
+				$ecmfile->filepath = $rel_dir;
646
+				$ecmfile->filename = $filename;
647
+				$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
648
+				$ecmfile->fullpath_orig = '';
649
+				$ecmfile->gen_or_uploaded = 'generated';
650
+				$ecmfile->description = '';    // indexed content
651
+				$ecmfile->keyword = '';        // keyword content
652
+				$ecmfile->share = getRandomPassword(true);
653
+				$result = $ecmfile->create($user);
654
+				if ($result < 0)
2442 655
 				{
2443
-					dol_print_error($this->db);
656
+					$this->error = $ecmfile->error;
657
+					$this->errors = $ecmfile->errors;
2444 658
 				}
2445
-			}
2446
-			else
2447
-			{
2448
-				dol_print_error($this->db);
2449
-			}
2450
-		}
2451
-	}
2452
-
2453
-	/**
2454
-	 * 	Get position of line (rang)
2455
-	 *
2456
-	 * 	@param		int		$rowid		Id of line
2457
-	 *  @return		int     			Value of rang in table of lines
2458
-	 */
2459
-	function getRangOfLine($rowid)
2460
-	{
2461
-		$sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2462
-		$sql.= ' WHERE rowid ='.$rowid;
2463
-
2464
-		dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
2465
-		$resql = $this->db->query($sql);
2466
-		if ($resql)
2467
-		{
2468
-			$row = $this->db->fetch_row($resql);
2469
-			return $row[0];
2470
-		}
2471
-	}
2472
-
2473
-	/**
2474
-	 * 	Get rowid of the line relative to its position
2475
-	 *
2476
-	 * 	@param		int		$rang		Rang value
2477
-	 *  @return     int     			Rowid of the line
2478
-	 */
2479
-	function getIdOfLine($rang)
2480
-	{
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;
2484
-		$resql = $this->db->query($sql);
2485
-		if ($resql)
2486
-		{
2487
-			$row = $this->db->fetch_row($resql);
2488
-			return $row[0];
2489
-		}
2490
-	}
659
+				*/
660
+            }
661
+            else return '';
662
+        }
663
+        elseif (empty($ecmfile->share))
664
+        {
665
+            // Add entry into index
666
+            if ($initsharekey)
667
+            {
668
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
669
+                $ecmfile->share = getRandomPassword(true);
670
+                $ecmfile->update($user);
671
+            }
672
+            else return '';
673
+        }
2491 674
 
2492
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2493
-	/**
2494
-	 * 	Get max value used for position of line (rang)
2495
-	 *
2496
-	 * 	@param		int		$fk_parent_line		Parent line id
2497
-	 *  @return     int  			   			Max value of rang in table of lines
2498
-	 */
2499
-	function line_max($fk_parent_line=0)
2500
-	{
2501
-        // phpcs:enable
2502
-		// Search the last rang with fk_parent_line
2503
-		if ($fk_parent_line)
2504
-		{
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;
2508
-
2509
-			dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2510
-			$resql = $this->db->query($sql);
2511
-			if ($resql)
2512
-			{
2513
-				$row = $this->db->fetch_row($resql);
2514
-				if (! empty($row[0]))
2515
-				{
2516
-					return $row[0];
2517
-				}
2518
-				else
2519
-				{
2520
-					return $this->getRangOfLine($fk_parent_line);
2521
-				}
2522
-			}
2523
-		}
2524
-		// If not, search the last rang of element
2525
-		else
2526
-		{
2527
-			$sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2528
-			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2529
-
2530
-			dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2531
-			$resql = $this->db->query($sql);
2532
-			if ($resql)
2533
-			{
2534
-				$row = $this->db->fetch_row($resql);
2535
-				return $row[0];
2536
-			}
2537
-		}
2538
-	}
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
678
+        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
2539 679
 
2540
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2541
-	/**
2542
-	 *  Update external ref of element
2543
-	 *
2544
-	 *  @param      string		$ref_ext	Update field ref_ext
2545
-	 *  @return     int      		   		<0 if KO, >0 if OK
2546
-	 */
2547
-	function update_ref_ext($ref_ext)
2548
-	{
2549
-        // phpcs:enable
2550
-		if (! $this->table_element)
2551
-		{
2552
-			dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
2553
-			return -1;
2554
-		}
2555
-
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;
2559
-
2560
-		dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
2561
-		if ($this->db->query($sql))
2562
-		{
2563
-			$this->ref_ext = $ref_ext;
2564
-			return 1;
2565
-		}
2566
-		else
2567
-		{
2568
-			$this->error=$this->db->error();
2569
-			return -1;
2570
-		}
2571
-	}
680
+        $forcedownload=0;
2572 681
 
2573
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2574
-	/**
2575
-	 *  Update note of element
2576
-	 *
2577
-	 *  @param      string		$note		New value for note
2578
-	 *  @param		string		$suffix		'', '_public' or '_private'
2579
-	 *  @return     int      		   		<0 if KO, >0 if OK
2580
-	 */
2581
-	function update_note($note, $suffix='')
2582
-	{
2583
-        // phpcs:enable
2584
-		global $user;
2585
-
2586
-		if (! $this->table_element)
2587
-		{
2588
-			$this->error='update_note was called on objet with property table_element not defined';
2589
-			dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
2590
-			return -1;
2591
-		}
2592
-		if (! in_array($suffix,array('','_public','_private')))
2593
-		{
2594
-			$this->error='update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
2595
-			dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
2596
-			return -2;
2597
-		}
2598
-		// Special cas
2599
-		//var_dump($this->table_element);exit;
2600
-		if ($this->table_element == 'product') $suffix='';
2601
-
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;
2606
-
2607
-		dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
2608
-		if ($this->db->query($sql))
2609
-		{
2610
-			if ($suffix == '_public') $this->note_public = $note;
2611
-			else if ($suffix == '_private') $this->note_private = $note;
2612
-			else
2613
-			{
2614
-				$this->note = $note;      // deprecated
2615
-				$this->note_private = $note;
2616
-			}
2617
-			return 1;
2618
-		}
2619
-		else
2620
-		{
2621
-			$this->error=$this->db->lasterror();
2622
-			return -1;
2623
-		}
2624
-	}
682
+        $paramlink='';
683
+        //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
684
+        //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
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';
688
+
689
+        if ($relativelink)
690
+        {
691
+            $linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
692
+        }
693
+        else
694
+        {
695
+            $linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
696
+        }
697
+
698
+        // Here $ecmfile->share is defined
699
+        return $linktoreturn;
700
+    }
2625 701
 
2626
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2627
-	/**
2628
-	 * 	Update public note (kept for backward compatibility)
2629
-	 *
2630
-	 * @param      string		$note		New value for note
2631
-	 * @return     int      		   		<0 if KO, >0 if OK
2632
-	 * @deprecated
2633
-	 * @see update_note()
2634
-	 */
2635
-	function update_note_public($note)
2636
-	{
2637
-        // phpcs:enable
2638
-		return $this->update_note($note,'_public');
2639
-	}
2640 702
 
2641 703
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2642
-	/**
2643
-	 *	Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
2644
-	 *  Must be called at end of methods addline or updateline.
2645
-	 *
2646
-	 *	@param	int		$exclspec          	>0 = Exclude special product (product_type=9)
2647
-	 *  @param  string	$roundingadjust    	'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total
2648
-	 *  @param	int		$nodatabaseupdate	1=Do not update database. Update only properties of object.
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
-	 *	@return	int    			           	<0 if KO, >0 if OK
2651
-	 */
2652
-	function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
2653
-	{
704
+    /**
705
+     *  Add a link between element $this->element and a contact
706
+     *
707
+     *  @param	int		$fk_socpeople       Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
708
+     *  @param 	int		$type_contact 		Type of contact (code or id). Must be id or code found into table llx_c_type_contact. For example: SALESREPFOLL
709
+     *  @param  string	$source             external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
710
+     *  @param  int		$notrigger			Disable all triggers
711
+     *  @return int                 		<0 if KO, >0 if OK
712
+     */
713
+    function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
714
+    {
2654 715
         // phpcs:enable
2655
-		global $conf, $hookmanager, $action;
2656
-
2657
-		// Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
2658
-		$MODULE = "";
2659
-		if ($this->element == 'propal')
2660
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
2661
-		elseif ($this->element == 'order')
2662
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
2663
-		elseif ($this->element == 'facture')
2664
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
2665
-		elseif ($this->element == 'facture_fourn')
2666
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
2667
-		elseif ($this->element == 'order_supplier')
2668
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
2669
-		elseif ($this->element == 'supplier_proposal')
2670
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2671
-
2672
-		if (! empty($MODULE)) {
2673
-			if (!empty(Globals::$conf->global->$MODULE)) {
2674
-                $modsactivated = explode(',', Globals::$conf->global->$MODULE);
2675
-                foreach ($modsactivated as $mod) {
2676
-					if (Globals::$conf->$mod->enabled)
2677
-                        return 1; // update was disabled by specific setup
2678
-				}
2679
-			}
2680
-		}
716
+        global $user,$langs;
2681 717
 
2682
-		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2683 718
 
2684
-		if ($roundingadjust == '-1') $roundingadjust='auto';	// For backward compatibility
719
+        dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
2685 720
 
2686
-		$forcedroundingmode=$roundingadjust;
2687
-		if ($forcedroundingmode == 'auto' && isset(Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND))
2688
-            $forcedroundingmode = Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2689
-        elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
721
+        // Check parameters
722
+        if ($fk_socpeople <= 0)
723
+        {
724
+            $langs->load("errors");
725
+            $this->error=$langs->trans("ErrorWrongValueForParameterX","1");
726
+            dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
727
+            return -1;
728
+        }
729
+        if (! $type_contact)
730
+        {
731
+            $langs->load("errors");
732
+            $this->error=$langs->trans("ErrorWrongValueForParameterX","2");
733
+            dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
734
+            return -2;
735
+        }
2690 736
 
2691
-		$error=0;
2692
-
2693
-		$multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2694
-
2695
-		// Define constants to find lines to sum
2696
-		$fieldtva='total_tva';
2697
-		$fieldlocaltax1='total_localtax1';
2698
-		$fieldlocaltax2='total_localtax2';
2699
-		$fieldup='subprice';
2700
-		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2701
-		{
2702
-			$fieldtva='tva';
2703
-			$fieldup='pu_ht';
2704
-		}
2705
-		if ($this->element == 'expensereport')
2706
-		{
2707
-			$fieldup='value_unit';
2708
-		}
2709
-
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;
2716
-		if ($exclspec)
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';
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
2723
-
2724
-		dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2725
-		$resql = $this->db->query($sql);
2726
-		if ($resql)
2727
-		{
2728
-			$this->total_ht  = 0;
2729
-			$this->total_tva = 0;
2730
-			$this->total_localtax1 = 0;
2731
-			$this->total_localtax2 = 0;
2732
-			$this->total_ttc = 0;
2733
-			$total_ht_by_vats  = array();
2734
-			$total_tva_by_vats = array();
2735
-			$total_ttc_by_vats = array();
2736
-			$this->multicurrency_total_ht	= 0;
2737
-			$this->multicurrency_total_tva	= 0;
2738
-			$this->multicurrency_total_ttc	= 0;
2739
-
2740
-			$num = $this->db->num_rows($resql);
2741
-			$i = 0;
2742
-			while ($i < $num)
2743
-			{
2744
-				$obj = $this->db->fetch_object($resql);
737
+        $id_type_contact=0;
738
+        if (is_numeric($type_contact))
739
+        {
740
+            $id_type_contact=$type_contact;
741
+        }
742
+        else
743
+        {
744
+            // We look for id type_contact
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";
750
+            //print $sql;
751
+            $resql=$this->db->query($sql);
752
+            if ($resql)
753
+            {
754
+                $obj = $this->db->fetch_object($resql);
755
+                if ($obj) $id_type_contact=$obj->rowid;
756
+            }
757
+        }
2745 758
 
2746
-				// Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2747
-				$parameters=array('fk_element' => $obj->rowid);
2748
-				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
759
+        if ($id_type_contact == 0)
760
+        {
761
+            $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
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
+            return -3;
764
+        }
2749 765
 
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
-				{
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
-					if ($diff)
2756
-					{
2757
-						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
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');
2761
-								$obj->total_tva = $tmpcal[1];
2762
-								$obj->total_ttc = $tmpcal[2];
2763
-						//
2764
-					}
2765
-				}
766
+        $datecreate = dol_now();
2766 767
 
2767
-				$this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2768
-				$this->total_tva       += $obj->total_tva;
2769
-				$this->total_localtax1 += $obj->total_localtax1;
2770
-				$this->total_localtax2 += $obj->total_localtax2;
2771
-				$this->total_ttc       += $obj->total_ttc;
2772
-				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2773
-				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2774
-				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
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;
2779
-				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2780
-				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2781
-				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2782
-
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
-				{
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
-					//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
-					if ($diff)
2789
-					{
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;
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');
2795
-								$this->total_tva -= $diff;
2796
-								$this->total_ttc -= $diff;
2797
-								$total_tva_by_vats[$obj->vatrate] -= $diff;
2798
-								$total_ttc_by_vats[$obj->vatrate] -= $diff;
2799
-					}
2800
-				}
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;
775
+                    break;
776
+                }
777
+            }
778
+        }
2801 779
 
2802
-				$i++;
2803
-			}
780
+        if(!$already_added) {
2804 781
 
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;
782
+            $this->db->begin();
2808 783
 
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 )
2811
-			{
2812
-				$prev_sits = $this->get_prev_sits();
2813
-
2814
-				foreach ($prev_sits as $sit) {				// $sit is an object Facture loaded with a fetch.
2815
-					$this->total_ht -= $sit->total_ht;
2816
-					$this->total_tva -= $sit->total_tva;
2817
-					$this->total_localtax1 -= $sit->total_localtax1;
2818
-					$this->total_localtax2 -= $sit->total_localtax2;
2819
-					$this->total_ttc -= $sit->total_ttc;
2820
-					$this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
2821
-					$this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
2822
-					$this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
2823
-				}
2824
-			}
2825
-
2826
-			$this->db->free($resql);
2827
-
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';
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';
2840
-
2841
-			if (empty($nodatabaseupdate))
2842
-			{
2843
-				$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
2844
-				$sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
2845
-				$sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
2846
-				$sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
2847
-				$sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
2848
-				$sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
2849
-						$sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
2850
-						$sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
2851
-						$sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
2852
-				$sql .= ' WHERE rowid = '.$this->id;
2853
-
2854
-
2855
-				dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2856
-				$resql=$this->db->query($sql);
2857
-				if (! $resql)
2858
-				{
2859
-					$error++;
2860
-					$this->error=$this->db->lasterror();
2861
-					$this->errors[]=$this->db->lasterror();
2862
-				}
2863
-			}
784
+            // Insert into database
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.= ")";
2864 791
 
2865
-			if (! $error)
2866
-			{
2867
-				return 1;
2868
-			}
2869
-			else
2870
-			{
2871
-				return -1;
2872
-			}
2873
-		}
2874
-		else
2875
-		{
2876
-			dol_print_error($this->db,'Bad request in update_price');
2877
-			return -1;
2878
-		}
2879
-	}
792
+            $resql=$this->db->query($sql);
793
+            if ($resql)
794
+            {
795
+                if (! $notrigger)
796
+                {
797
+                    $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
798
+                    if ($result < 0)
799
+                    {
800
+                        $this->db->rollback();
801
+                        return -1;
802
+                    }
803
+                }
804
+
805
+                $this->db->commit();
806
+                return 1;
807
+            }
808
+            else
809
+            {
810
+                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
811
+                {
812
+                    $this->error=$this->db->errno();
813
+                    $this->db->rollback();
814
+                    echo 'err rollback';
815
+                    return -2;
816
+                }
817
+                else
818
+                {
819
+                    $this->error=$this->db->error();
820
+                    $this->db->rollback();
821
+                    return -1;
822
+                }
823
+            }
824
+        } else return 0;
825
+    }
2880 826
 
2881 827
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2882
-	/**
2883
-	 *	Add objects linked in llx_element_element.
2884
-	 *
2885
-	 *	@param		string	$origin		Linked element type
2886
-	 *	@param		int		$origin_id	Linked element id
2887
-	 *	@return		int					<=0 if KO, >0 if OK
2888
-	 *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2889
-	 */
2890
-	function add_object_linked($origin=null, $origin_id=null)
2891
-	{
828
+    /**
829
+     *    Copy contact from one element to current
830
+     *
831
+     *    @param    CommonObject    $objFrom    Source element
832
+     *    @param    string          $source     Nature of contact ('internal' or 'external')
833
+     *    @return   int                         >0 if OK, <0 if KO
834
+     */
835
+    function copy_linked_contact($objFrom, $source='internal')
836
+    {
2892 837
         // phpcs:enable
2893
-		$origin = (! empty($origin) ? $origin : $this->origin);
2894
-		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2895
-
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';
2901
-		$this->db->begin();
2902
-
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.= ")";
2914
-
2915
-		dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2916
-		if ($this->db->query($sql))
2917
-	  	{
2918
-	  		$this->db->commit();
2919
-	  		return 1;
2920
-	  	}
2921
-	  	else
2922
-	  	{
2923
-	  		$this->error=$this->db->lasterror();
2924
-	  		$this->db->rollback();
2925
-	  		return 0;
2926
-	  	}
2927
-	}
2928
-
2929
-	/**
2930
-	 *	Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
2931
-	 *		this->linkedObjectsIds array and
2932
-	 *		this->linkedObjects array if $loadalsoobjects = 1
2933
-	 *  Possible usage for parameters:
2934
-	 *  - all parameters empty -> we look all link to current object (current object can be source or target)
2935
-	 *  - source id+type -> will get target list linked to source
2936
-	 *  - target id+type -> will get source list linked to target
2937
-	 *  - source id+type + target type -> will get target list of the type
2938
-	 *  - target id+type + target source -> will get source list of the type
2939
-	 *
2940
-	 *	@param	int		$sourceid			Object source id (if not defined, id of object)
2941
-	 *	@param  string	$sourcetype			Object source type (if not defined, element name of object)
2942
-	 *	@param  int		$targetid			Object target id (if not defined, id of object)
2943
-	 *	@param  string	$targettype			Object target type (if not defined, elemennt name of object)
2944
-	 *	@param  string	$clause				'OR' or 'AND' clause used when both source id and target id are provided
2945
-	 *  @param  int		$alsosametype		0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
2946
-	 *  @param  string	$orderby			SQL 'ORDER BY' clause
2947
-	 *  @param	int		$loadalsoobjects	Load also array this->linkedObjects (Use 0 to increase performances)
2948
-	 *	@return int							<0 if KO, >0 if OK
2949
-	 *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2950
-	 */
2951
-	function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2952
-	{
2953
-		global $conf;
2954
-
2955
-		$this->linkedObjectsIds=array();
2956
-		$this->linkedObjects=array();
2957
-
2958
-		$justsource=false;
2959
-		$justtarget=false;
2960
-		$withtargettype=false;
2961
-		$withsourcetype=false;
2962
-
2963
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2964
-		{
2965
-			$justsource=true;  // the source (id and type) is a search criteria
2966
-			if (! empty($targettype)) $withtargettype=true;
2967
-		}
2968
-		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2969
-		{
2970
-			$justtarget=true;  // the target (id and type) is a search criteria
2971
-			if (! empty($sourcetype)) $withsourcetype=true;
2972
-		}
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);
2978
-
2979
-		/*if (empty($sourceid) && empty($targetid))
2980
-		 {
2981
-		 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
2982
-		 return -1;
2983
-		 }*/
2984
-
2985
-		// Links between objects are stored in table element_element
2986
-		$sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2987
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2988
-		$sql.= " WHERE ";
2989
-		if ($justsource || $justtarget)
2990
-		{
2991
-			if ($justsource)
2992
-			{
2993
-				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2994
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2995
-			}
2996
-			else if ($justtarget)
2997
-			{
2998
-				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2999
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
3000
-			}
3001
-		}
3002
-		else
3003
-		{
3004
-			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3005
-			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3006
-		}
3007
-		$sql .= ' ORDER BY '.$orderby;
3008
-
3009
-		dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3010
-		$resql = $this->db->query($sql);
3011
-		if ($resql)
3012
-		{
3013
-			$num = $this->db->num_rows($resql);
3014
-			$i = 0;
3015
-			while ($i < $num)
3016
-			{
3017
-				$obj = $this->db->fetch_object($resql);
3018
-				if ($justsource || $justtarget)
3019
-				{
3020
-					if ($justsource)
3021
-					{
3022
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3023
-					}
3024
-					else if ($justtarget)
3025
-					{
3026
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3027
-					}
3028
-				}
3029
-				else
3030
-				{
3031
-					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3032
-					{
3033
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3034
-					}
3035
-					if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3036
-					{
3037
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3038
-					}
3039
-				}
3040
-				$i++;
3041
-			}
838
+        $contacts = $objFrom->liste_contact(-1, $source);
839
+        foreach($contacts as $contact)
840
+        {
841
+            if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
842
+            {
843
+                $this->error=$this->db->lasterror();
844
+                return -1;
845
+            }
846
+        }
847
+        return 1;
848
+    }
3042 849
 
3043
-			if (! empty($this->linkedObjectsIds))
3044
-			{
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', ...)
3047
-				{
3048
-					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3049
-					$module = $element = $subelement = $objecttype;
3050
-					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3051
-						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3052
-					{
3053
-						$module = $element = $regs[1];
3054
-						$subelement = $regs[2];
3055
-					}
3056
-
3057
-					$classpath = $element.'/class';
3058
-					// To work with non standard classpath or module name
3059
-					if ($objecttype == 'facture')			{
3060
-						$classpath = 'compta/facture/class';
3061
-					}
3062
-					else if ($objecttype == 'facturerec')			{
3063
-						$classpath = 'compta/facture/class'; $module = 'facture';
3064
-					}
3065
-					else if ($objecttype == 'propal')			{
3066
-						$classpath = 'comm/propal/class';
3067
-					}
3068
-					else if ($objecttype == 'supplier_proposal')			{
3069
-						$classpath = 'supplier_proposal/class';
3070
-					}
3071
-					else if ($objecttype == 'shipping')			{
3072
-						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3073
-					}
3074
-					else if ($objecttype == 'delivery')			{
3075
-						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3076
-					}
3077
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3078
-						$classpath = 'fourn/class'; $module = 'fournisseur';
3079
-					}
3080
-					else if ($objecttype == 'fichinter')			{
3081
-						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3082
-					}
3083
-					else if ($objecttype == 'subscription')			{
3084
-						$classpath = 'adherents/class'; $module = 'adherent';
3085
-					}
3086
-
3087
-					// Set classfile
3088
-					$classfile = strtolower($subelement); $classname = ucfirst($subelement);
3089
-
3090
-					if ($objecttype == 'order') {
3091
-						$classfile = 'commande'; $classname = 'Commande';
3092
-					}
3093
-					else if ($objecttype == 'invoice_supplier') {
3094
-						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3095
-					}
3096
-					else if ($objecttype == 'order_supplier')   {
3097
-						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3098
-					}
3099
-					else if ($objecttype == 'supplier_proposal')   {
3100
-						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3101
-					}
3102
-					else if ($objecttype == 'facturerec')   {
3103
-						$classfile = 'facture-rec'; $classname = 'FactureRec';
3104
-					}
3105
-					else if ($objecttype == 'subscription')   {
3106
-						$classfile = 'subscription'; $classname = 'Subscription';
3107
-					}
3108
-
3109
-					// Here $module, $classfile and $classname are set
3110
-					if (Globals::$conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
3111
-						if ($loadalsoobjects)
3112
-						{
3113
-							dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
3114
-							//print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
3115
-							if (class_exists($classname))
3116
-							{
3117
-								foreach($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3118
-								{
3119
-									$object = new $classname($this->db);
3120
-									$ret = $object->fetch($objectid);
3121
-									if ($ret >= 0)
3122
-									{
3123
-										$this->linkedObjects[$objecttype][$i] = $object;
3124
-									}
3125
-								}
3126
-							}
3127
-						}
3128
-					}
3129
-					else
3130
-					{
3131
-						unset($this->linkedObjectsIds[$objecttype]);
3132
-					}
3133
-				}
3134
-			}
3135
-			return 1;
3136
-		}
3137
-		else
3138
-		{
3139
-			dol_print_error($this->db);
3140
-			return -1;
3141
-		}
3142
-	}
3143
-
3144
-	/**
3145
-	 *	Update object linked of a current object
3146
-	 *
3147
-	 *	@param	int		$sourceid		Object source id
3148
-	 *	@param  string	$sourcetype		Object source type
3149
-	 *	@param  int		$targetid		Object target id
3150
-	 *	@param  string	$targettype		Object target type
3151
-	 *	@return							int	>0 if OK, <0 if KO
3152
-	 *	@see	add_object_linked, fetObjectLinked, deleteObjectLinked
3153
-	 */
3154
-	function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
3155
-	{
3156
-		$updatesource=false;
3157
-		$updatetarget=false;
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;
3161
-
3162
-		$sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
3163
-		if ($updatesource)
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)."'";
3169
-		}
3170
-		else if ($updatetarget)
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)."'";
3176
-		}
3177
-
3178
-		dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
3179
-		if ($this->db->query($sql))
3180
-		{
3181
-			return 1;
3182
-		}
3183
-		else
3184
-		{
3185
-			$this->error=$this->db->lasterror();
3186
-			return -1;
3187
-		}
3188
-	}
3189
-
3190
-	/**
3191
-	 *	Delete all links between an object $this
3192
-	 *
3193
-	 *	@param	int		$sourceid		Object source id
3194
-	 *	@param  string	$sourcetype		Object source type
3195
-	 *	@param  int		$targetid		Object target id
3196
-	 *	@param  string	$targettype		Object target type
3197
-	 *  @param	int		$rowid			Row id of line to delete. If defined, other parameters are not used.
3198
-	 *	@return     					int	>0 if OK, <0 if KO
3199
-	 *	@see	add_object_linked, updateObjectLinked, fetchObjectLinked
3200
-	 */
3201
-	function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
3202
-	{
3203
-		$deletesource=false;
3204
-		$deletetarget=false;
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;
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);
3213
-
3214
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
3215
-		$sql.= " WHERE";
3216
-		if ($rowid > 0)
3217
-		{
3218
-			$sql.=" rowid = ".$rowid;
3219
-		}
3220
-		else
3221
-		{
3222
-			if ($deletesource)
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)."'";
3226
-			}
3227
-			else if ($deletetarget)
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)."'";
3231
-			}
3232
-			else
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)."')";
3237
-			}
3238
-		}
3239
-
3240
-		dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
3241
-		if ($this->db->query($sql))
3242
-		{
3243
-			return 1;
3244
-		}
3245
-		else
3246
-		{
3247
-			$this->error=$this->db->lasterror();
3248
-			$this->errors[]=$this->error;
3249
-			return -1;
3250
-		}
3251
-	}
3252
-
3253
-	/**
3254
-	 *      Set status of an object
3255
-	 *
3256
-	 *      @param	int		$status			Status to set
3257
-	 *      @param	int		$elementId		Id of element to force (use this->id by default)
3258
-	 *      @param	string	$elementType	Type of element to force (use this->table_element by default)
3259
-	 *      @param	string	$trigkey		Trigger key to use for trigger
3260
-	 *      @return int						<0 if KO, >0 if OK
3261
-	 */
3262
-	function setStatut($status, $elementId=null, $elementType='', $trigkey='')
3263
-	{
3264
-		global $user,$langs,$conf;
3265
-
3266
-		$savElementId=$elementId;  // To be used later to know if we were using the method using the id of this or not.
3267
-
3268
-		$elementId = (!empty($elementId)?$elementId:$this->id);
3269
-		$elementTable = (!empty($elementType)?$elementType:$this->table_element);
3270
-
3271
-		$this->db->begin();
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";
3280
-
3281
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
3282
-		$sql.= " SET ".$fieldstatus." = ".$status;
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;
3286
-
3287
-		dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
3288
-		if ($this->db->query($sql))
3289
-		{
3290
-			$error = 0;
3291
-
3292
-			// Try autoset of trigkey
3293
-			if (empty($trigkey))
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';
3301
-			}
3302
-
3303
-			if ($trigkey)
3304
-			{
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);
3309
-				if ($result < 0) {
3310
-					$error++; $this->errors=$interface->errors;
3311
-				}
3312
-				// Fin appel triggers
3313
-			}
850
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
851
+    /**
852
+     *      Update a link to contact line
853
+     *
854
+     *      @param	int		$rowid              Id of line contact-element
855
+     * 		@param	int		$statut	            New status of link
856
+     *      @param  int		$type_contact_id    Id of contact type (not modified if 0)
857
+     *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
858
+     *      @return int                 		<0 if KO, >= 0 if OK
859
+     */
860
+    function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
861
+    {
862
+        // phpcs:enable
863
+        // Insert into database
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);
870
+        if ($resql)
871
+        {
872
+            return 0;
873
+        }
874
+        else
875
+        {
876
+            $this->error=$this->db->lasterror();
877
+            return -1;
878
+        }
879
+    }
3314 880
 
3315
-			if (! $error)
3316
-			{
3317
-				$this->db->commit();
881
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
882
+    /**
883
+     *    Delete a link to contact line
884
+     *
885
+     *    @param	int		$rowid			Id of contact link line to delete
886
+     *    @param	int		$notrigger		Disable all triggers
887
+     *    @return   int						>0 if OK, <0 if KO
888
+     */
889
+    function delete_contact($rowid, $notrigger=0)
890
+    {
891
+        // phpcs:enable
892
+        global $user;
3318 893
 
3319
-				if (empty($savElementId))    // If the element we update was $this (so $elementId is null)
3320
-				{
3321
-					$this->statut = $status;
3322
-					$this->status = $status;
3323
-				}
3324 894
 
3325
-				return 1;
3326
-			}
3327
-			else
3328
-			{
3329
-				$this->db->rollback();
3330
-				dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
3331
-				return -1;
3332
-			}
3333
-		}
3334
-		else
3335
-		{
3336
-			$this->error=$this->db->lasterror();
3337
-			$this->db->rollback();
3338
-			return -1;
3339
-		}
3340
-	}
3341
-
3342
-
3343
-	/**
3344
-	 *  Load type of canvas of an object if it exists
3345
-	 *
3346
-	 *  @param      int		$id     Record id
3347
-	 *  @param      string	$ref    Record ref
3348
-	 *  @return		int				<0 if KO, 0 if nothing done, >0 if OK
3349
-	 */
3350
-	function getCanvas($id=0,$ref='')
3351
-	{
3352
-		global $conf;
3353
-
3354
-		if (empty($id) && empty($ref)) return 0;
3355
-		if (!empty(Globals::$conf->global->MAIN_DISABLE_CANVAS))
3356
-            return 0;    // To increase speed. Not enabled by default.
895
+        $this->db->begin();
3357 896
 
3358
-            // Clean parameters
3359
-		$ref = trim($ref);
3360
-
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)."'";
3366
-
3367
-		$resql = $this->db->query($sql);
3368
-		if ($resql)
3369
-		{
3370
-			$obj = $this->db->fetch_object($resql);
3371
-			if ($obj)
3372
-			{
3373
-				$this->canvas   = $obj->canvas;
3374
-				return 1;
3375
-			}
3376
-			else return 0;
3377
-		}
3378
-		else
3379
-		{
3380
-			dol_print_error($this->db);
3381
-			return -1;
3382
-		}
3383
-	}
3384
-
3385
-
3386
-	/**
3387
-	 * 	Get special code of a line
3388
-	 *
3389
-	 * 	@param	int		$lineid		Id of line
3390
-	 * 	@return	int					Special code
3391
-	 */
3392
-	function getSpecialCode($lineid)
3393
-	{
3394
-		$sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3395
-		$sql.= ' WHERE rowid = '.$lineid;
3396
-		$resql = $this->db->query($sql);
3397
-		if ($resql)
3398
-		{
3399
-			$row = $this->db->fetch_row($resql);
3400
-			return $row[0];
3401
-		}
3402
-	}
3403
-
3404
-	/**
3405
-	 *  Function to check if an object is used by others.
3406
-	 *  Check is done into this->childtables. There is no check into llx_element_element.
3407
-	 *
3408
-	 *  @param	int		$id			Force id of object
3409
-	 *  @return	int					<0 if KO, 0 if not used, >0 if already used
3410
-	 */
3411
-	function isObjectUsed($id=0)
3412
-	{
3413
-		global $langs;
3414
-
3415
-		if (empty($id)) $id=$this->id;
3416
-
3417
-		// Check parameters
3418
-		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3419
-		{
3420
-			dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3421
-			return -1;
3422
-		}
3423
-
3424
-		$arraytoscan = $this->childtables;
3425
-		// For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3426
-		$tmparray=array_keys($this->childtables);
3427
-		if (is_numeric($tmparray[0]))
3428
-		{
3429
-			$arraytoscan = array_flip($this->childtables);
3430
-		}
3431
-
3432
-		// Test if child exists
3433
-		$haschild=0;
3434
-		foreach($arraytoscan as $table => $elementname)
3435
-		{
3436
-			//print $id.'-'.$table.'-'.$elementname.'<br>';
3437
-			// Check if third party can be deleted
3438
-			$sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3439
-			$sql.= " WHERE ".$this->fk_element." = ".$id;
3440
-			$resql=$this->db->query($sql);
3441
-			if ($resql)
3442
-			{
3443
-				$obj=$this->db->fetch_object($resql);
3444
-				if ($obj->nb > 0)
3445
-				{
3446
-					$langs->load("errors");
3447
-					//print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3448
-					$haschild += $obj->nb;
3449
-					if (is_numeric($elementname))	// old usage
3450
-					{
3451
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3452
-					}
3453
-					else	// new usage: $elementname=Translation key
3454
-					{
3455
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3456
-					}
3457
-					break;    // We found at least one, we stop here
3458
-				}
3459
-			}
3460
-			else
3461
-			{
3462
-				$this->errors[]=$this->db->lasterror();
3463
-				return -1;
3464
-			}
3465
-		}
3466
-		if ($haschild > 0)
3467
-		{
3468
-			$this->errors[]="ErrorRecordHasChildren";
3469
-			return $haschild;
3470
-		}
3471
-		else return 0;
3472
-	}
3473
-
3474
-	/**
3475
-	 *  Function to say how many lines object contains
3476
-	 *
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
-	 *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3479
-	 */
3480
-	function hasProductsOrServices($predefined=-1)
3481
-	{
3482
-		$nb=0;
3483
-
3484
-		foreach($this->lines as $key => $val)
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;
3492
-			if ($qualified) $nb++;
3493
-		}
3494
-		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3495
-		return $nb;
3496
-	}
3497
-
3498
-	/**
3499
-	 * Function that returns the total amount HT of discounts applied for all lines.
3500
-	 *
3501
-	 * @return 	float
3502
-	 */
3503
-	function getTotalDiscount()
3504
-	{
3505
-		$total_discount=0.00;
3506
-
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;
3510
-
3511
-		dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3512
-		$resql = $this->db->query($sql);
3513
-		if ($resql)
3514
-		{
3515
-			$num=$this->db->num_rows($resql);
3516
-			$i=0;
3517
-			while ($i < $num)
3518
-			{
3519
-				$obj = $this->db->fetch_object($resql);
3520
-
3521
-				$pu_ht = $obj->pu_ht;
3522
-				$qty= $obj->qty;
3523
-				$total_ht = $obj->total_ht;
3524
-
3525
-				$total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
3526
-				$total_discount += $total_discount_line;
3527
-
3528
-				$i++;
3529
-			}
3530
-		}
3531
-
3532
-		//print $total_discount; exit;
3533
-		return price2num($total_discount);
3534
-	}
3535
-
3536
-
3537
-	/**
3538
-	 * Return into unit=0, the calculated total of weight and volume of all lines * qty
3539
-	 * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
3540
-	 *
3541
-	 * @return  array                           array('weight'=>...,'volume'=>...)
3542
-	 */
3543
-	function getTotalWeightVolume()
3544
-	{
3545
-		$totalWeight = 0;
3546
-		$totalVolume = 0;
3547
-		// defined for shipment only
3548
-		$totalOrdered = '';
3549
-		// defined for shipment only
3550
-		$totalToShip = '';
3551
-
3552
-		foreach ($this->lines as $line)
3553
-		{
3554
-			if (isset($line->qty_asked))
3555
-			{
3556
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3557
-				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3558
-			}
3559
-			if (isset($line->qty_shipped))
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))
897
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
898
+        $sql.= " WHERE rowid =".$rowid;
899
+
900
+        dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
901
+        if ($this->db->query($sql))
902
+        {
903
+            if (! $notrigger)
3564 904
             {
3565
-                if (empty($totalToShip)) $totalToShip=0;
3566
-                $totalToShip+=$line->qty;   // defined for reception only
3567
-			}
3568
-
3569
-			// Define qty, weight, volume, weight_units, volume_units
3570
-			if ($this->element == 'shipping') {
3571
-				// for shipments
3572
-				$qty = $line->qty_shipped ? $line->qty_shipped : 0;
3573
-			}
3574
-			else {
3575
-				$qty = $line->qty ? $line->qty : 0;
3576
-			}
3577
-
3578
-			$weight = $line->weight ? $line->weight : 0;
3579
-            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3580
-			$volume = $line->volume ? $line->volume : 0;
3581
-			($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
905
+                $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
906
+                if ($result < 0) { $this->db->rollback(); return -1; }
907
+            }
3582 908
 
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;
909
+            $this->db->commit();
910
+            return 1;
911
+        }
912
+        else
913
+        {
914
+            $this->error=$this->db->lasterror();
915
+            $this->db->rollback();
916
+            return -1;
917
+        }
918
+    }
3587 919
 
3588
-			$weightUnit=0;
3589
-			$volumeUnit=0;
3590
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3591
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
920
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
921
+    /**
922
+     *    Delete all links between an object $this and all its contacts
923
+     *
924
+     *	  @param	string	$source		'' or 'internal' or 'external'
925
+     *	  @param	string	$code		Type of contact (code or id)
926
+     *    @return   int					>0 if OK, <0 if KO
927
+     */
928
+    function delete_linked_contact($source='',$code='')
929
+    {
930
+        // phpcs:enable
931
+        $temp = array();
932
+        $typeContact = $this->liste_type_contact($source,'',0,0,$code);
3592 933
 
3593
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3594
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
934
+        foreach($typeContact as $key => $value)
935
+        {
936
+            array_push($temp,$key);
937
+        }
938
+        $listId = implode(",", $temp);
3595 939
 
3596
-			//var_dump($line->volume_units);
3597
-			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3598
-			{
3599
-				$trueWeightUnit=pow(10, $weightUnit);
3600
-				$totalWeight += $weight * $qty * $trueWeightUnit;
3601
-			}
3602
-			else {
3603
-		if ($weight_units == 99) {
3604
-			// conversion 1 Pound = 0.45359237 KG
3605
-			$trueWeightUnit = 0.45359237;
3606
-			$totalWeight += $weight * $qty * $trueWeightUnit;
3607
-		} elseif ($weight_units == 98) {
3608
-			// conversion 1 Ounce = 0.0283495 KG
3609
-			$trueWeightUnit = 0.0283495;
3610
-			$totalWeight += $weight * $qty * $trueWeightUnit;
3611
-		}
3612
-		else
3613
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3614
-			}
3615
-			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3616
-			{
3617
-				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3618
-				$trueVolumeUnit=pow(10, $volumeUnit);
3619
-				//print $line->volume;
3620
-				$totalVolume += $volume * $qty * $trueVolumeUnit;
3621
-			}
3622
-			else
3623
-			{
3624
-				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3625
-			}
3626
-		}
3627
-
3628
-		return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
3629
-	}
3630
-
3631
-
3632
-	/**
3633
-	 *	Set extra parameters
3634
-	 *
3635
-	 *	@return	int      <0 if KO, >0 if OK
3636
-	 */
3637
-	function setExtraParameters()
3638
-	{
3639
-		$this->db->begin();
3640
-
3641
-		$extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3642
-
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;
3646
-
3647
-		dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3648
-		$resql = $this->db->query($sql);
3649
-		if (! $resql)
3650
-		{
3651
-			$this->error=$this->db->lasterror();
3652
-			$this->db->rollback();
3653
-			return -1;
3654
-		}
3655
-		else
3656
-		{
3657
-			$this->db->commit();
3658
-			return 1;
3659
-		}
3660
-	}
940
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
941
+        $sql.= " WHERE element_id = ".$this->id;
942
+        if ($listId)
943
+            $sql.= " AND fk_c_type_contact IN (".$listId.")";
3661 944
 
945
+        dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
946
+        if ($this->db->query($sql))
947
+        {
948
+            return 1;
949
+        }
950
+        else
951
+        {
952
+            $this->error=$this->db->lasterror();
953
+            return -1;
954
+        }
955
+    }
3662 956
 
3663 957
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3664
-	/**
3665
-	 *    Return incoterms informations
3666
-	 *    TODO Use a cache for label get
3667
-	 *
3668
-	 *    @return	string	incoterms info
3669
-	 */
3670
-	function display_incoterms()
3671
-	{
958
+    /**
959
+     *    Get array of all contacts for an object
960
+     *
961
+     *    @param	int			$statut		Status of links to get (-1=all)
962
+     *    @param	string		$source		Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
963
+     *    @param	int         $list       0:Return array contains all properties, 1:Return array contains just id
964
+     *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
965
+     *    @return	array|int		        Array of contacts, -1 if error
966
+     */
967
+    function liste_contact($statut=-1,$source='external',$list=0,$code='')
968
+    {
3672 969
         // phpcs:enable
3673
-		$out = '';
3674
-		$this->libelle_incoterms = '';
3675
-		if (!empty($this->fk_incoterms))
3676
-		{
3677
-			$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3678
-			$result = $this->db->query($sql);
3679
-			if ($result)
3680
-			{
3681
-				$res = $this->db->fetch_object($result);
3682
-				$out .= $res->code;
3683
-			}
3684
-		}
3685
-
3686
-		$out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3687
-
3688
-		return $out;
3689
-	}
3690
-
3691
-	/**
3692
-	 *    Return incoterms informations for pdf display
3693
-	 *
3694
-	 *    @return	string		incoterms info
3695
-	 */
3696
-	function getIncotermsForPDF()
3697
-	{
3698
-		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3699
-		$resql = $this->db->query($sql);
3700
-		if ($resql)
3701
-		{
3702
-			$num = $this->db->num_rows($resql);
3703
-			if ($num > 0)
3704
-			{
3705
-				$res = $this->db->fetch_object($resql);
3706
-				return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3707
-			}
3708
-			else
3709
-			{
3710
-				return '';
3711
-			}
3712
-		}
3713
-		else
3714
-		{
3715
-			$this->errors[] = $this->db->lasterror();
3716
-			return false;
3717
-		}
3718
-	}
3719
-
3720
-	/**
3721
-	 *    Define incoterms values of current object
3722
-	 *
3723
-	 *    @param	int		$id_incoterm     Id of incoterm to set or '' to remove
3724
-	 * 	  @param 	string  $location		 location of incoterm
3725
-	 *    @return	int     		<0 if KO, >0 if OK
3726
-	 */
3727
-	function setIncoterms($id_incoterm, $location)
3728
-	{
3729
-		if ($this->id && $this->table_element)
3730
-		{
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;
3735
-			dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3736
-			$resql=$this->db->query($sql);
3737
-			if ($resql)
3738
-			{
3739
-				$this->fk_incoterms = $id_incoterm;
3740
-				$this->location_incoterms = $location;
970
+        global $langs;
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";
992
+
993
+        dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
994
+        $resql=$this->db->query($sql);
995
+        if ($resql)
996
+        {
997
+            $num=$this->db->num_rows($resql);
998
+            $i=0;
999
+            while ($i < $num)
1000
+            {
1001
+                $obj = $this->db->fetch_object($resql);
1002
+
1003
+                if (! $list)
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
1009
+                                    'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1010
+                                    'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1011
+                }
1012
+                else
1013
+                {
1014
+                    $tab[$i]=$obj->id;
1015
+                }
3741 1016
 
3742
-				$sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3743
-				$res = $this->db->query($sql);
3744
-				if ($res)
3745
-				{
3746
-					$obj = $this->db->fetch_object($res);
3747
-					$this->libelle_incoterms = $obj->libelle;
3748
-				}
3749
-				return 1;
3750
-			}
3751
-			else
3752
-			{
3753
-				$this->errors[] = $this->db->lasterror();
3754
-				return -1;
3755
-			}
3756
-		}
3757
-		else return -1;
3758
-	}
3759
-
3760
-
3761
-	// --------------------
3762
-	// TODO: All functions here must be redesigned and moved as they are not business functions but output functions
3763
-	// --------------------
3764
-
3765
-	/* This is to show add lines */
3766
-
3767
-	/**
3768
-	 *	Show add free and predefined products/services form
3769
-	 *
3770
-	 *  @param	int		        $dateSelector       1=Show also date range input fields
3771
-	 *  @param	Societe			$seller				Object thirdparty who sell
3772
-	 *  @param	Societe			$buyer				Object thirdparty who buy
3773
-	 *	@return	void
3774
-	 */
3775
-	function formAddObjectLine($dateSelector, $seller, $buyer)
3776
-	{
3777
-		global $conf,$user,$langs,$object,$hookmanager;
3778
-		global $form,$bcnd,$var;
3779
-
3780
-		// Line extrafield
3781
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3782
-		$extrafieldsline = new ExtraFields($this->db);
3783
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3784
-
3785
-		// Output template part (modules that overwrite templates must declare this into descriptor)
3786
-		// Use global variables + $dateSelector + $seller and $buyer
3787
-		$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
3788
-        foreach($dirtpls as $reldir)
3789
-		{
3790
-			$tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3791
-			if (empty(Globals::$conf->file->strict_mode)) {
3792
-                $res=@include $tpl;
3793
-			} else {
3794
-				$res=include $tpl; // for debug
3795
-			}
3796
-			if ($res) break;
3797
-		}
3798
-	}
3799
-
3800
-
3801
-
3802
-	/* This is to show array of line of details */
3803
-
3804
-
3805
-	/**
3806
-	 *	Return HTML table for object lines
3807
-	 *	TODO Move this into an output class file (htmlline.class.php)
3808
-	 *	If lines are into a template, title must also be into a template
3809
-	 *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
3810
-	 *
3811
-	 *	@param	string		$action				Action code
3812
-	 *	@param  string		$seller            	Object of seller third party
3813
-	 *	@param  string  	$buyer             	Object of buyer third party
3814
-	 *	@param	int			$selected		   	Object line selected
3815
-	 *	@param  int	    	$dateSelector      	1=Show also date range input fields
3816
-	 *	@return	void
3817
-	 */
3818
-	function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3819
-	{
3820
-		global $conf, $hookmanager, $langs, $user;
3821
-		// TODO We should not use global var for this !
3822
-		global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3823
-
3824
-		// Define usemargins
3825
-		$usemargins=0;
3826
-		if (!empty(Globals::$conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande')))
3827
-            $usemargins = 1;
1017
+                $i++;
1018
+            }
3828 1019
 
3829
-        $num = count($this->lines);
1020
+            return $tab;
1021
+        }
1022
+        else
1023
+        {
1024
+            $this->error=$this->db->lasterror();
1025
+            dol_print_error($this->db);
1026
+            return -1;
1027
+        }
1028
+    }
3830 1029
 
3831
-		// Line extrafield
3832
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3833
-		$extrafieldsline = new ExtraFields($this->db);
3834
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3835 1030
 
3836
-		$parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3837
-		$reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3838
-		if (empty($reshook))
3839
-		{
3840
-			// Title line
3841
-		    print "<thead>\n";
1031
+    /**
1032
+     * 		Update status of a contact linked to object
1033
+     *
1034
+     * 		@param	int		$rowid		Id of link between object and contact
1035
+     * 		@return	int					<0 if KO, >=0 if OK
1036
+     */
1037
+    function swapContactStatus($rowid)
1038
+    {
1039
+        $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1040
+        $sql.= " tc.code, tc.libelle";
1041
+        //$sql.= ", s.fk_soc";
1042
+        $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
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)."'";
1047
+
1048
+        dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1049
+        $resql=$this->db->query($sql);
1050
+        if ($resql)
1051
+        {
1052
+            $obj = $this->db->fetch_object($resql);
1053
+            $newstatut = ($obj->statut == 4) ? 5 : 4;
1054
+            $result = $this->update_contact($rowid, $newstatut);
1055
+            $this->db->free($resql);
1056
+            return $result;
1057
+        }
1058
+        else
1059
+        {
1060
+            $this->error=$this->db->error();
1061
+            dol_print_error($this->db);
1062
+            return -1;
1063
+        }
1064
+    }
3842 1065
 
3843
-			print '<tr class="liste_titre nodrag nodrop">';
1066
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1067
+    /**
1068
+     *      Return array with list of possible values for type of contacts
1069
+     *
1070
+     *      @param	string	$source     'internal', 'external' or 'all'
1071
+     *      @param	string	$order		Sort order by : 'position', 'code', 'rowid'...
1072
+     *      @param  int		$option     0=Return array id->label, 1=Return array code->label
1073
+     *      @param  int		$activeonly 0=all status of contact, 1=only the active
1074
+     *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1075
+     *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1076
+     */
1077
+    function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1078
+    {
1079
+        // phpcs:enable
1080
+        global $langs;
1081
+
1082
+        if (empty($order)) $order='position';
1083
+        if ($order == 'position') $order.=',code';
1084
+
1085
+        $tab = array();
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');
1093
+
1094
+        //print "sql=".$sql;
1095
+        $resql=$this->db->query($sql);
1096
+        if ($resql)
1097
+        {
1098
+            $num=$this->db->num_rows($resql);
1099
+            $i=0;
1100
+            while ($i < $num)
1101
+            {
1102
+                $obj = $this->db->fetch_object($resql);
3844 1103
 
3845
-			// Adds a line numbering column
3846
-			if (!empty(Globals::$conf->global->MAIN_VIEW_LINE_NUMBER))
3847
-                print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
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
+                $i++;
1109
+            }
1110
+            return $tab;
1111
+        }
1112
+        else
1113
+        {
1114
+            $this->error=$this->db->lasterror();
1115
+            //dol_print_error($this->db);
1116
+            return null;
1117
+        }
1118
+    }
3848 1119
 
3849
-            // Description
3850
-			print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
1120
+    /**
1121
+     *      Return id of contacts for a source and a contact code.
1122
+     *      Example: contact client de facturation ('external', 'BILLING')
1123
+     *      Example: contact client de livraison ('external', 'SHIPPING')
1124
+     *      Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
1125
+     *
1126
+     *		@param	string	$source		'external' or 'internal'
1127
+     *		@param	string	$code		'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
1128
+     *		@param	int		$status		limited to a certain status
1129
+     *      @return array       		List of id for such contacts
1130
+     */
1131
+    function getIdContact($source,$code,$status=0)
1132
+    {
1133
+        global $conf;
3851 1134
 
3852
-			if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier')
3853
-			{
3854
-				print '<td class="linerefsupplier"><span id="title_fourn_ref">'.$langs->trans("SupplierRef").'</span></td>';
3855
-			}
1135
+        $result=array();
1136
+        $i=0;
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';
1144
+        } else {
1145
+            $id=$this->id;
1146
+            $element=$this->element;
1147
+        }
3856 1148
 
3857
-			// VAT
3858
-			print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
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;
1164
+
1165
+        dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1166
+        $resql=$this->db->query($sql);
1167
+        if ($resql)
1168
+        {
1169
+            while ($obj = $this->db->fetch_object($resql))
1170
+            {
1171
+                $result[$i]=$obj->fk_socpeople;
1172
+                $i++;
1173
+            }
1174
+        }
1175
+        else
1176
+        {
1177
+            $this->error=$this->db->error();
1178
+            return null;
1179
+        }
3859 1180
 
3860
-			// Price HT
3861
-			print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
1181
+        return $result;
1182
+    }
3862 1183
 
3863
-			// Multicurrency
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>';
1184
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1185
+    /**
1186
+     *		Load object contact with id=$this->contactid into $this->contact
1187
+     *
1188
+     *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1189
+     *		@return	int						<0 if KO, >0 if OK
1190
+     */
1191
+    function fetch_contact($contactid=null)
1192
+    {
1193
+        // phpcs:enable
1194
+        if (empty($contactid)) $contactid=$this->contactid;
3866 1195
 
3867
-            if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
1196
+        if (empty($contactid)) return 0;
3868 1197
 
3869
-			// Qty
3870
-			print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
1198
+        require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1199
+        $contact = new Contact($this->db);
1200
+        $result=$contact->fetch($contactid);
1201
+        $this->contact = $contact;
1202
+        return $result;
1203
+    }
3871 1204
 
3872
-			if (Globals::$conf->global->PRODUCT_USE_UNITS) {
3873
-				print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
3874
-			}
1205
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1206
+    /**
1207
+     *    	Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
1208
+     *
1209
+     *		@param		int		$force_thirdparty_id	Force thirdparty id
1210
+     *		@return		int								<0 if KO, >0 if OK
1211
+     */
1212
+    function fetch_thirdparty($force_thirdparty_id=0)
1213
+    {
1214
+        // phpcs:enable
1215
+        global $conf;
3875 1216
 
3876
-			// Reduction short
3877
-			print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
1217
+        if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1218
+            return 0;
3878 1219
 
3879
-			if ($this->situation_cycle_ref) {
3880
-				print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3881
-			}
1220
+        require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
3882 1221
 
3883
-			if ($usemargins && !empty(Globals::$conf->margin->enabled) && empty($user->societe_id)) {
3884
-				if (!empty($user->rights->margins->creer))
3885
-				{
3886
-					if (Globals::$conf->global->MARGIN_TYPE == "1")
3887
-                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3888
-					else
3889
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
3890
-				}
1222
+        $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1223
+        if ($force_thirdparty_id)
1224
+            $idtofetch = $force_thirdparty_id;
3891 1225
 
3892
-				if (!empty(Globals::$conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3893
-                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3894
-				if (!empty(Globals::$conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3895
-                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
3896
-			}
1226
+        if ($idtofetch) {
1227
+            $thirdparty = new Societe($this->db);
1228
+            $result = $thirdparty->fetch($idtofetch);
1229
+            $this->thirdparty = $thirdparty;
3897 1230
 
3898
-			// Total HT
3899
-			print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
1231
+            // Use first price level if level not defined for third party
1232
+            if (!empty(Globals::$conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1233
+                $this->thirdparty->price_level = 1;
1234
+            }
3900 1235
 
3901
-			// Multicurrency
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>';
1236
+            return $result;
1237
+        } else
1238
+            return -1;
1239
+    }
3904 1240
 
3905
-            if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
3906 1241
 
3907
-			print '<td class="linecoledit"></td>';  // No width to allow autodim
1242
+    /**
1243
+     * Looks for an object with ref matching the wildcard provided
1244
+     * It does only work when $this->table_ref_field is set
1245
+     *
1246
+     * @param string $ref Wildcard
1247
+     * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
1248
+     */
1249
+    public function fetchOneLike($ref)
1250
+    {
1251
+        if (!$this->table_ref_field) {
1252
+            return 0;
1253
+        }
3908 1254
 
3909
-			print '<td class="linecoldelete" width="10"></td>';
1255
+        $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
3910 1256
 
3911
-			print '<td class="linecolmove" width="10"></td>';
1257
+        $query = $this->db->query($sql);
3912 1258
 
3913
-			if($action == 'selectlines')
3914
-			{
3915
-			    print '<td class="linecolcheckall" align="center">';
3916
-			    print '<input type="checkbox" class="linecheckboxtoggle" />';
3917
-			    print '<script type="text/javascript">$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
3918
-			    print '</td>';
3919
-			}
3920
-
3921
-			print "</tr>\n";
3922
-			print "</thead>\n";
3923
-		}
3924
-
3925
-		$var = true;
3926
-		$i	 = 0;
3927
-
3928
-		print "<tbody>\n";
3929
-		foreach ($this->lines as $line)
3930
-		{
3931
-			//Line extrafield
3932
-			$line->fetch_optionals();
3933
-
3934
-			//if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3935
-			if (is_object($hookmanager))   // Old code is commented on preceding line.
3936
-			{
3937
-				if (empty($line->fk_parent_line))
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
3941
-				}
3942
-				else
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
3946
-				}
3947
-			}
3948
-			if (empty($reshook))
3949
-			{
3950
-				$this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3951
-			}
3952
-
3953
-			$i++;
3954
-		}
3955
-		print "</tbody>\n";
3956
-	}
3957
-
3958
-	/**
3959
-	 *	Return HTML content of a detail line
3960
-	 *	TODO Move this into an output class file (htmlline.class.php)
3961
-	 *
3962
-	 *	@param	string		$action				GET/POST action
3963
-	 *	@param CommonObjectLine $line		       	Selected object line to output
3964
-	 *	@param  string	    $var               	Is it a an odd line (true)
3965
-	 *	@param  int		    $num               	Number of line (0)
3966
-	 *	@param  int		    $i					I
3967
-	 *	@param  int		    $dateSelector      	1=Show also date range input fields
3968
-	 *	@param  string	    $seller            	Object of seller third party
3969
-	 *	@param  string	    $buyer             	Object of buyer third party
3970
-	 *	@param	int			$selected		   	Object line selected
3971
-	 *  @param  int			$extrafieldsline	Object of extrafield line attribute
3972
-	 *	@return	void
3973
-	 */
3974
-	function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
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 !
3979
-
3980
-		$object_rights = $this->getRights();
3981
-
3982
-		$element=$this->element;
3983
-
3984
-		$text=''; $description=''; $type=0;
3985
-
3986
-		// Show product and description
3987
-		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
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
3991
-
3992
-		// Ligne en mode visu
3993
-		if ($action != 'editline' || $selected != $line->id)
3994
-		{
3995
-			// Product
3996
-			if ($line->fk_product > 0)
3997
-			{
3998
-				$product_static = new Product($this->db);
3999
-				$product_static->fetch($line->fk_product);
4000
-
4001
-				$product_static->ref = $line->ref; //can change ref in hook
4002
-				$product_static->label = $line->label; //can change label in hook
4003
-				$text=$product_static->getNomUrl(1);
4004
-
4005
-				// Define output language and label
4006
-				if (!empty(Globals::$conf->global->MAIN_MULTILANGS)) {
4007
-					if (! is_object($this->thirdparty))
4008
-					{
4009
-						dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4010
-						return;
4011
-					}
4012
-
4013
-					$prod = new Product($this->db);
4014
-					$prod->fetch($line->fk_product);
4015
-
4016
-					$outputlangs = $langs;
4017
-					$newlang='';
4018
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
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))
4022
-					{
4023
-						$outputlangs = new Translate("",$conf);
4024
-						$outputlangs->setDefaultLang($newlang);
4025
-					}
1259
+        if (!$this->db->num_rows($query)) {
1260
+            return 0;
1261
+        }
4026 1262
 
4027
-					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4028
-				}
4029
-				else
4030
-				{
4031
-					$label = $line->product_label;
4032
-				}
1263
+        $result = $this->db->fetch_object($query);
1264
+
1265
+        return $this->fetch($result->rowid);
1266
+    }
1267
+
1268
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1269
+    /**
1270
+     *	Load data for barcode into properties ->barcode_type*
1271
+     *	Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
1272
+     *  if it is not defined, ->element must be defined to know default barcode type.
1273
+     *
1274
+     *	@return		int			<0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
1275
+     */
1276
+    function fetch_barcode()
1277
+    {
1278
+        // phpcs:enable
1279
+        global $conf;
1280
+
1281
+        dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
4033 1282
 
4034
-				$text.= ' - '.(! empty($line->label)?$line->label:$label);
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.
1283
+        $idtype=$this->barcode_type;
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
+        {
1286
+            if ($this->element == 'product')
1287
+                $idtype = Globals::$conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1288
+            else if ($this->element == 'societe')
1289
+                $idtype = Globals::$conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1290
+            else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1291
+        }
1292
+
1293
+        if ($idtype > 0)
1294
+        {
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
+            {
1297
+                $sql = "SELECT rowid, code, libelle as label, coder";
1298
+                $sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299
+                $sql.= " WHERE rowid = ".$idtype;
1300
+                dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
1301
+                $resql = $this->db->query($sql);
1302
+                if ($resql)
1303
+                {
1304
+                    $obj = $this->db->fetch_object($resql);
1305
+                    $this->barcode_type       = $obj->rowid;
1306
+                    $this->barcode_type_code  = $obj->code;
1307
+                    $this->barcode_type_label = $obj->label;
1308
+                    $this->barcode_type_coder = $obj->coder;
1309
+                    return 1;
1310
+                }
1311
+                else
1312
+                {
1313
+                    dol_print_error($this->db);
1314
+                    return -1;
1315
+                }
4036 1316
             }
1317
+        }
1318
+        return 0;
1319
+    }
4037 1320
 
4038
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
1321
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1322
+    /**
1323
+     *		Load the project with id $this->fk_project into this->project
1324
+     *
1325
+     *		@return		int			<0 if KO, >=0 if OK
1326
+     */
1327
+    function fetch_projet()
1328
+    {
1329
+        // phpcs:enable
1330
+        include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
4039 1331
 
4040
-			// Output template part (modules that overwrite templates must declare this into descriptor)
4041
-			// Use global variables + $dateSelector + $seller and $buyer
4042
-			$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4043
-            foreach($dirtpls as $reldir)
4044
-			{
4045
-				$tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4046
-				if (empty(Globals::$conf->file->strict_mode)) {
4047
-                    $res=@include $tpl;
4048
-				} else {
4049
-					$res=include $tpl; // for debug
4050
-				}
4051
-				if ($res) break;
4052
-			}
4053
-		}
1332
+        if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet;	// For backward compatibility
1333
+        if (empty($this->fk_project)) return 0;
4054 1334
 
4055
-		// Ligne en mode update
4056
-		if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4057
-		{
4058
-			$label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4059
-			$placeholder=' placeholder="'.$langs->trans("Label").'"';
1335
+        $project = new Project($this->db);
1336
+        $result = $project->fetch($this->fk_project);
4060 1337
 
4061
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
1338
+        $this->projet = $project;	// deprecated
1339
+        $this->project = $project;
1340
+        return $result;
1341
+    }
4062 1342
 
4063
-			// Output template part (modules that overwrite templates must declare this into descriptor)
4064
-			// Use global variables + $dateSelector + $seller and $buyer
4065
-			$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4066
-            foreach($dirtpls as $reldir)
4067
-			{
4068
-				$tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4069
-				if (empty(Globals::$conf->file->strict_mode)) {
4070
-                    $res=@include $tpl;
4071
-				} else {
4072
-					$res=include $tpl; // for debug
4073
-				}
4074
-				if ($res) break;
4075
-			}
4076
-		}
4077
-	}
4078
-
4079
-
4080
-	/* This is to show array of line of details of source object */
4081
-
4082
-
4083
-	/**
4084
-	 * 	Return HTML table table of source object lines
4085
-	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
4086
-	 *  If lines are into a template, title must also be into a template
4087
-	 *  But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
4088
-	 *
4089
-	 *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4090
-	 *  @return	void
4091
-	 */
4092
-	function printOriginLinesList($restrictlist='')
4093
-	{
4094
-		global $langs, $hookmanager, $conf;
4095
-
4096
-		print '<tr class="liste_titre">';
4097
-		print '<td>'.$langs->trans('Ref').'</td>';
4098
-		print '<td>'.$langs->trans('Description').'</td>';
4099
-		print '<td align="right">'.$langs->trans('VATRate').'</td>';
4100
-		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4101
-		if (!empty(Globals::$conf->multicurrency->enabled))
4102
-            print '<td align="right">' . $langs->trans('PriceUHTCurrency') . '</td>';
4103
-        print '<td align="right">'.$langs->trans('Qty').'</td>';
4104
-		if (Globals::$conf->global->PRODUCT_USE_UNITS) {
4105
-			print '<td align="left">'.$langs->trans('Unit').'</td>';
4106
-		}
4107
-		print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
1343
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1344
+    /**
1345
+     *		Load the product with id $this->fk_product into this->product
1346
+     *
1347
+     *		@return		int			<0 if KO, >=0 if OK
1348
+     */
1349
+    function fetch_product()
1350
+    {
1351
+        // phpcs:enable
1352
+        include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
4108 1353
 
4109
-		$var = true;
4110
-		$i	 = 0;
1354
+        if (empty($this->fk_product)) return 0;
4111 1355
 
4112
-		if (! empty($this->lines))
4113
-		{
4114
-			foreach ($this->lines as $line)
4115
-			{
4116
-				if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4117
-				{
4118
-					if (empty($line->fk_parent_line))
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
4123
-					}
4124
-				}
4125
-				else
4126
-				{
4127
-					$this->printOriginLine($line, $var, $restrictlist);
4128
-				}
4129
-
4130
-				$i++;
4131
-			}
4132
-		}
4133
-	}
4134
-
4135
-	/**
4136
-	 * 	Return HTML with a line of table array of source object lines
4137
-	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
4138
-	 *  If lines are into a template, title must also be into a template
4139
-	 *  But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
4140
-	 *
4141
-	 * 	@param	CommonObjectLine	$line				Line
4142
-	 * 	@param	string				$var				Var
4143
-	 *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4144
-	 * 	@return	void
4145
-	 */
4146
-	function printOriginLine($line, $var, $restrictlist='')
4147
-	{
4148
-		global $langs, $conf;
4149
-
4150
-		//var_dump($line);
4151
-		if (!empty($line->date_start))
4152
-		{
4153
-			$date_start=$line->date_start;
4154
-		}
4155
-		else
4156
-		{
4157
-			$date_start=$line->date_debut_prevue;
4158
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4159
-		}
4160
-		if (!empty($line->date_end))
4161
-		{
4162
-			$date_end=$line->date_end;
4163
-		}
4164
-		else
4165
-		{
4166
-			$date_end=$line->date_fin_prevue;
4167
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4168
-		}
4169
-
4170
-		$this->tpl['label'] = '';
4171
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4172
-
4173
-		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4174
-		{
4175
-			$discount=new DiscountAbsolute($this->db);
4176
-			$discount->fk_soc = $this->socid;
4177
-			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4178
-		}
4179
-		else if (! empty($line->fk_product))
4180
-		{
4181
-			$productstatic = new Product($this->db);
4182
-			$productstatic->id = $line->fk_product;
4183
-			$productstatic->ref = $line->ref;
4184
-			$productstatic->type = $line->fk_product_type;
4185
-            if(empty($productstatic->ref)){
4186
-				$line->fetch_product();
4187
-				$productstatic = $line->product;
4188
-			}
4189
-			
4190
-			$this->tpl['label'].= $productstatic->getNomUrl(1);
4191
-			$this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4192
-			// Dates
4193
-			if ($line->product_type == 1 && ($date_start || $date_end))
4194
-			{
4195
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4196
-			}
4197
-		}
4198
-		else
4199
-		{
4200
-			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4201
-			if (!empty($line->desc)) {
4202
-				$this->tpl['label'].=$line->desc;
4203
-			}else {
4204
-				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4205
-			}
4206
-			
4207
-			// Dates
4208
-			if ($line->product_type == 1 && ($date_start || $date_end))
4209
-			{
4210
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4211
-			}
4212
-		}
4213
-
4214
-		if (! empty($line->desc))
4215
-		{
4216
-			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4217
-			{
4218
-				$discount=new DiscountAbsolute($this->db);
4219
-				$discount->fetch($line->fk_remise_except);
4220
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4221
-			}
4222
-			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4223
-			{
4224
-				$discount=new DiscountAbsolute($this->db);
4225
-				$discount->fetch($line->fk_remise_except);
4226
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4227
-			}
4228
-			elseif ($line->desc == '(EXCESS RECEIVED)')
4229
-			{
4230
-				$discount=new DiscountAbsolute($this->db);
4231
-				$discount->fetch($line->fk_remise_except);
4232
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4233
-			}
4234
-			elseif ($line->desc == '(EXCESS PAID)')
4235
-			{
4236
-				$discount=new DiscountAbsolute($this->db);
4237
-				$discount->fetch($line->fk_remise_except);
4238
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4239
-			}
4240
-			else
4241
-			{
4242
-				$this->tpl['description'] = dol_trunc($line->desc,60);
4243
-			}
4244
-		}
4245
-		else
4246
-		{
4247
-			$this->tpl['description'] = '&nbsp;';
4248
-		}
4249
-
4250
-        // VAT Rate
4251
-        $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
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.')';
4254
-
4255
-		$this->tpl['price'] = price($line->subprice);
4256
-		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4257
-		$this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4258
-		if (Globals::$conf->global->PRODUCT_USE_UNITS)
4259
-            $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4260
-        $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4261
-
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;
4265
-
4266
-		// Output template part (modules that overwrite templates must declare this into descriptor)
4267
-		// Use global variables + $dateSelector + $seller and $buyer
4268
-		$dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4269
-        foreach($dirtpls as $reldir)
4270
-		{
4271
-			$tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4272
-			if (empty(Globals::$conf->file->strict_mode)) {
4273
-                $res=@include $tpl;
4274
-			} else {
4275
-				$res=include $tpl; // for debug
4276
-			}
4277
-			if ($res) break;
4278
-		}
4279
-	}
1356
+        $product = new Product($this->db);
1357
+        $result = $product->fetch($this->fk_product);
4280 1358
 
1359
+        $this->product = $product;
1360
+        return $result;
1361
+    }
4281 1362
 
4282 1363
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4283
-	/**
4284
-	 *	Add resources to the current object : add entry into llx_element_resources
4285
-	 *	Need $this->element & $this->id
4286
-	 *
4287
-	 *	@param		int		$resource_id		Resource id
4288
-	 *	@param		string	$resource_type		'resource'
4289
-	 *	@param		int		$busy				Busy or not
4290
-	 *	@param		int		$mandatory			Mandatory or not
4291
-	 *	@return		int							<=0 if KO, >0 if OK
4292
-	 */
4293
-	function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4294
-	{
1364
+    /**
1365
+     *		Load the user with id $userid into this->user
1366
+     *
1367
+     *		@param	int		$userid 		Id du contact
1368
+     *		@return	int						<0 if KO, >0 if OK
1369
+     */
1370
+    function fetch_user($userid)
1371
+    {
4295 1372
         // phpcs:enable
4296
-		$this->db->begin();
4297
-
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.= ")";
4313
-
4314
-		dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4315
-		if ($this->db->query($sql))
4316
-		{
4317
-			$this->db->commit();
4318
-			return 1;
4319
-		}
4320
-		else
4321
-		{
4322
-			$this->error=$this->db->lasterror();
4323
-			$this->db->rollback();
4324
-			return  0;
4325
-		}
4326
-	}
1373
+        $user = new User($this->db);
1374
+        $result=$user->fetch($userid);
1375
+        $this->user = $user;
1376
+        return $result;
1377
+    }
4327 1378
 
4328 1379
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4329
-	/**
4330
-	 *    Delete a link to resource line
4331
-	 *
4332
-	 *    @param	int		$rowid			Id of resource line to delete
4333
-	 *    @param	int		$element		element name (for trigger) TODO: use $this->element into commonobject class
4334
-	 *    @param	int		$notrigger		Disable all triggers
4335
-	 *    @return   int						>0 if OK, <0 if KO
4336
-	 */
4337
-	function delete_resource($rowid, $element, $notrigger=0)
4338
-	{
1380
+    /**
1381
+     *	Read linked origin object
1382
+     *
1383
+     *	@return		void
1384
+     */
1385
+    function fetch_origin()
1386
+    {
4339 1387
         // phpcs:enable
4340
-		global $user;
4341
-
4342
-		$this->db->begin();
4343
-
4344
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4345
-		$sql.= " WHERE rowid=".$rowid;
4346
-
4347
-		dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
4348
-
4349
-		$resql=$this->db->query($sql);
4350
-		if (! $resql)
4351
-		{
4352
-			$this->error=$this->db->lasterror();
4353
-			$this->db->rollback();
4354
-			return -1;
4355
-		}
4356
-		else
4357
-		{
4358
-			if (! $notrigger)
4359
-			{
4360
-				$result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4361
-				if ($result < 0) { $this->db->rollback(); return -1; }
4362
-			}
4363
-			$this->db->commit();
4364
-			return 1;
4365
-		}
4366
-	}
4367
-
4368
-
4369
-	/**
4370
-	 * Overwrite magic function to solve problem of cloning object that are kept as references
4371
-	 *
4372
-	 * @return void
4373
-	 */
4374
-	function __clone()
4375
-	{
4376
-		// Force a copy of this->lines, otherwise it will point to same object.
4377
-		if (isset($this->lines) && is_array($this->lines))
4378
-		{
4379
-			$nboflines=count($this->lines);
4380
-			for($i=0; $i < $nboflines; $i++)
4381
-			{
4382
-				$this->lines[$i] = clone $this->lines[$i];
4383
-			}
4384
-		}
4385
-	}
4386
-
4387
-	/**
4388
-	 * Common function for all objects extending CommonObject for generating documents
4389
-	 *
4390
-	 * @param 	string 		$modelspath 	Relative folder where generators are placed
4391
-	 * @param 	string 		$modele 		Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
4392
-	 * @param 	Translate 	$outputlangs 	Output language to use
4393
-	 * @param 	int 		$hidedetails 	1 to hide details. 0 by default
4394
-	 * @param 	int 		$hidedesc 		1 to hide product description. 0 by default
4395
-	 * @param 	int 		$hideref 		1 to hide product reference. 0 by default
4396
-	 * @param   null|array  $moreparams     Array to provide more information
4397
-	 * @return 	int 						>0 if OK, <0 if KO
4398
-	 * @see	addFileIntoDatabaseIndex
4399
-	 */
4400
-	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4401
-	{
4402
-		global $conf, $langs, $user;
4403
-
4404
-		$srctemplatepath='';
4405
-
4406
-		// Increase limit for PDF build
4407
-		$err=error_reporting();
4408
-		error_reporting(0);
4409
-		@set_time_limit(120);
4410
-		error_reporting($err);
4411
-
4412
-		// If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4413
-		$tmp=explode(':',$modele,2);
4414
-		if (! empty($tmp[1]))
4415
-		{
4416
-			$modele=$tmp[0];
4417
-			$srctemplatepath=$tmp[1];
4418
-		}
4419
-
4420
-		// Search template files
4421
-		$file=''; $classname=''; $filefound=0;
4422
-		$dirmodels=array('/');
4423
-		if (is_array(Globals::$conf->modules_parts['models']))
4424
-            $dirmodels = array_merge($dirmodels, Globals::$conf->modules_parts['models']);
4425
-        foreach($dirmodels as $reldir)
4426
-		{
4427
-			foreach(array('doc','pdf') as $prefix)
4428
-			{
4429
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4430
-				else $file = $prefix."_".$modele.".modules.php";
4431
-
4432
-				// On verifie l'emplacement du modele
4433
-				$file=dol_buildpath($reldir.$modelspath.$file,0);
4434
-				if (file_exists($file))
4435
-				{
4436
-					$filefound=1;
4437
-					$classname=$prefix.'_'.$modele;
4438
-					break;
4439
-				}
4440
-			}
4441
-			if ($filefound) break;
4442
-		}
4443
-
4444
-		// If generator was found
4445
-		if ($filefound)
4446
-		{
4447
-			global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4448
-
4449
-			require_once $file;
4450
-
4451
-			$obj = new $classname($this->db);
1388
+        if ($this->origin == 'shipping') $this->origin = 'expedition';
1389
+        if ($this->origin == 'delivery') $this->origin = 'livraison';
1390
+        if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
4452 1391
 
4453
-			// If generator is ODT, we must have srctemplatepath defined, if not we set it.
4454
-			if ($obj->type == 'odt' && empty($srctemplatepath))
4455
-			{
4456
-				$varfortemplatedir=$obj->scandir;
4457
-				if ($varfortemplatedir && !empty(Globals::$conf->global->$varfortemplatedir)) {
4458
-					$dirtoscan = Globals::$conf->global->$varfortemplatedir;
1392
+        $origin = $this->origin;
4459 1393
 
4460
-                    $listoffiles=array();
1394
+        $classname = ucfirst($origin);
1395
+        $this->$origin = new $classname($this->db);
1396
+        $this->$origin->fetch($this->origin_id);
1397
+    }
4461 1398
 
4462
-					// Now we add first model found in directories scanned
4463
-					$listofdir=explode(',',$dirtoscan);
4464
-					foreach($listofdir as $key => $tmpdir)
4465
-					{
4466
-						$tmpdir=trim($tmpdir);
4467
-						$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4468
-						if (! $tmpdir) { unset($listofdir[$key]); continue; }
4469
-						if (is_dir($tmpdir))
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);
4473
-						}
4474
-					}
4475
-
4476
-					if (count($listoffiles))
4477
-					{
4478
-						foreach($listoffiles as $record)
4479
-						{
4480
-							$srctemplatepath=$record['fullname'];
4481
-							break;
4482
-						}
4483
-					}
4484
-				}
1399
+    /**
1400
+     *  Load object from specific field
1401
+     *
1402
+     *  @param	string	$table		Table element or element line
1403
+     *  @param	string	$field		Field selected
1404
+     *  @param	string	$key		Import key
1405
+     *  @param	string	$element	Element name
1406
+     *	@return	int					<0 if KO, >0 if OK
1407
+     */
1408
+    function fetchObjectFrom($table, $field, $key, $element = null)
1409
+    {
1410
+        global $conf;
4485 1411
 
4486
-				if (empty($srctemplatepath))
4487
-				{
4488
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4489
-					return -1;
4490
-				}
4491
-			}
1412
+        $result=false;
4492 1413
 
4493
-			if ($obj->type == 'odt' && ! empty($srctemplatepath))
4494
-			{
4495
-				if (! dol_is_file($srctemplatepath))
4496
-				{
4497
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4498
-					return -1;
4499
-				}
4500
-			}
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).")";
1418
+        } else {
1419
+            $sql .= " AND entity = " . Globals::$conf->entity;
1420
+        }
4501 1421
 
4502
-			// We save charset_output to restore it because write_file can change it if needed for
4503
-			// output format that does not support UTF8.
4504
-			$sav_charset_output=$outputlangs->charset_output;
1422
+        dol_syslog(get_class($this).'::fetchObjectFrom', LOG_DEBUG);
1423
+        $resql = $this->db->query($sql);
1424
+        if ($resql)
1425
+        {
1426
+            $row = $this->db->fetch_row($resql);
1427
+            // Test for avoid error -1
1428
+            if ($row[0] > 0) {
1429
+                $result = $this->fetch($row[0]);
1430
+            }
1431
+        }
4505 1432
 
4506
-			if (in_array(get_class($this), array('Adherent')))
4507
-			{
4508
-				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4509
-				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4510
-			}
4511
-			else
4512
-			{
4513
-				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4514
-			}
4515
-			// After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
1433
+        return $result;
1434
+    }
4516 1435
 
4517
-			if ($resultwritefile > 0)
4518
-			{
4519
-				$outputlangs->charset_output=$sav_charset_output;
1436
+    /**
1437
+     *	Getter generic. Load value from a specific field
1438
+     *
1439
+     *	@param	string	$table		Table of element or element line
1440
+     *	@param	int		$id			Element id
1441
+     *	@param	string	$field		Field selected
1442
+     *	@return	int					<0 if KO, >0 if OK
1443
+     */
1444
+    function getValueFrom($table, $id, $field)
1445
+    {
1446
+        $result=false;
1447
+        if (!empty($id) && !empty($field) && !empty($table)) {
1448
+            $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
1449
+            $sql.= " WHERE rowid = ".$id;
1450
+
1451
+            dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
1452
+            $resql = $this->db->query($sql);
1453
+            if ($resql)
1454
+            {
1455
+                $row = $this->db->fetch_row($resql);
1456
+                $result = $row[0];
1457
+            }
1458
+        }
1459
+        return $result;
1460
+    }
4520 1461
 
4521
-				// We delete old preview
4522
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4523
-				dol_delete_preview($this);
1462
+    /**
1463
+     *	Setter generic. Update a specific field into database.
1464
+     *  Warning: Trigger is run only if param trigkey is provided.
1465
+     *
1466
+     *	@param	string		$field			Field to update
1467
+     *	@param	mixed		$value			New value
1468
+     *	@param	string		$table			To force other table element or element line (should not be used)
1469
+     *	@param	int			$id				To force other object id (should not be used)
1470
+     *	@param	string		$format			Data format ('text', 'date'). 'text' is used if not defined
1471
+     *	@param	string		$id_field		To force rowid field name. 'rowid' is used if not defined
1472
+     *	@param	User|string	$fuser			Update the user of last update field with this user. If not provided, current user is used except if value is 'none'
1473
+     *  @param  string      $trigkey    	Trigger key to run (in most cases something like 'XXX_MODIFY')
1474
+     *  @param	string		$fk_user_field	Name of field to save user id making change
1475
+     *	@return	int							<0 if KO, >0 if OK
1476
+     *  @see updateExtraField
1477
+     */
1478
+    function setValueFrom($field, $value, $table='', $id=null, $format='', $id_field='', $fuser=null, $trigkey='', $fk_user_field='fk_user_modif')
1479
+    {
1480
+        global $user,$langs,$conf;
4524 1481
 
4525
-				// Index file in database
4526
-				if (! empty($obj->result['fullpath']))
4527
-				{
4528
-					$destfull = $obj->result['fullpath'];
4529
-					$upload_dir = dirname($destfull);
4530
-					$destfile = basename($destfull);
4531
-					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4532
-
4533
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4534
-					{
4535
-						$filename = basename($destfile);
4536
-						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4537
-						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4538
-
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);
4542
-
4543
-						// Set the public "share" key
4544
-						$setsharekey = false;
4545
-						if ($this->element == 'propal')
4546
-						{
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;
4549
-							if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD))
4550
-                                $setsharekey = true;
4551
-                        }
4552
-						if ($this->element == 'commande' && !empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))
4553
-                            $setsharekey = true;
4554
-                        if ($this->element == 'facture' && !empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))
4555
-                            $setsharekey = true;
4556
-                        if ($this->element == 'bank_account' && !empty(Globals::$conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD))
4557
-                            $setsharekey = true;
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';
4558 1486
 
4559
-                        if ($setsharekey)
4560
-						{
4561
-							if (empty($ecmfile->share))	// Because object not found or share not set yet
4562
-							{
4563
-								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4564
-								$ecmfile->share = getRandomPassword(true);
4565
-							}
4566
-						}
1487
+        $error=0;
4567 1488
 
4568
-						if ($result > 0)
4569
-						{
4570
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4571
-							$ecmfile->fullpath_orig = '';
4572
-							$ecmfile->gen_or_uploaded = 'generated';
4573
-							$ecmfile->description = '';    // indexed content
4574
-							$ecmfile->keyword = '';        // keyword content
4575
-							$result = $ecmfile->update($user);
4576
-							if ($result < 0)
4577
-							{
4578
-								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4579
-							}
4580
-						}
4581
-						else
4582
-						{
4583
-							$ecmfile->entity = Globals::$conf->entity;
4584
-                            $ecmfile->filepath = $rel_dir;
4585
-							$ecmfile->filename = $filename;
4586
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4587
-							$ecmfile->fullpath_orig = '';
4588
-							$ecmfile->gen_or_uploaded = 'generated';
4589
-							$ecmfile->description = '';    // indexed content
4590
-							$ecmfile->keyword = '';        // keyword content
4591
-							$ecmfile->src_object_type = $this->table_element;
4592
-							$ecmfile->src_object_id   = $this->id;
4593
-
4594
-							$result = $ecmfile->create($user);
4595
-							if ($result < 0)
4596
-							{
4597
-								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4598
-							}
4599
-						}
1489
+        $this->db->begin();
4600 1490
 
4601
-						/*$this->result['fullname']=$destfull;
4602
-						$this->result['filepath']=$ecmfile->filepath;
4603
-						$this->result['filename']=$ecmfile->filename;*/
4604
-						//var_dump($obj->update_main_doc_field);exit;
4605
-
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))
4610
-						{
4611
-							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4612
-							$sql.= ' WHERE rowid = '.$this->id;
4613
-							$resql = $this->db->query($sql);
4614
-							if (! $resql) dol_print_error($this->db);
4615
-						}
4616
-					}
4617
-				}
4618
-				else
4619
-				{
4620
-					dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
4621
-				}
1491
+        // Special case
1492
+        if ($table == 'product' && $field == 'note_private') $field='note';
1493
+        if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
4622 1494
 
4623
-				// Success in building document. We build meta file.
4624
-				dol_meta_create($this);
1495
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
4625 1496
 
4626
-				return 1;
4627
-			}
4628
-			else
4629
-			{
4630
-				$outputlangs->charset_output=$sav_charset_output;
4631
-				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4632
-				return -1;
4633
-			}
4634
-		}
4635
-		else
4636
-		{
4637
-			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4638
-			dol_print_error('',$this->error);
4639
-			return -1;
4640
-		}
4641
-	}
4642
-
4643
-	/**
4644
-	 *  Build thumb
4645
-	 *  @TODO Move this into files.lib.php
4646
-	 *
4647
-	 *  @param      string	$file           Path file in UTF8 to original file to create thumbs from.
4648
-	 *	@return		void
4649
-	 */
4650
-	function addThumbs($file)
4651
-	{
4652
-		global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4653
-
4654
-		require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4655
-
4656
-		$file_osencoded=dol_osencode($file);
4657
-		if (file_exists($file_osencoded))
4658
-		{
4659
-			// Create small thumbs for company (Ratio is near 16/9)
4660
-			// Used on logon for example
4661
-			vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
4662
-
4663
-			// Create mini thumbs for company (Ratio is near 16/9)
4664
-			// Used on menu or for setup page for example
4665
-			vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
4666
-		}
4667
-	}
4668
-
4669
-
4670
-	/* Functions common to commonobject and commonobjectline */
4671
-
4672
-	/* For default values */
4673
-
4674
-	/**
4675
-	 * Return the default value to use for a field when showing the create form of object.
4676
-	 * Return values in this order:
4677
-	 * 1) If parameter is available into POST, we return it first.
4678
-	 * 2) If not but an alternate value was provided as parameter of function, we return it.
4679
-	 * 3) If not but a constant Globals::$conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
4680
-	 * 4) Return value found into database (TODO No yet implemented)
4681
-	 *
4682
-	 * @param   string              $fieldname          Name of field
4683
-	 * @param   string              $alternatevalue     Alternate value to use
4684
-	 * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4685
-	 **/
4686
-	function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4687
-	{
4688
-		global $conf, $_POST;
4689
-
4690
-		// If param here has been posted, we use this value first.
4691
-		if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
4692
-
4693
-		if (isset($alternatevalue)) return $alternatevalue;
4694
-
4695
-		$newelement=$this->element;
4696
-		if ($newelement == 'facture') $newelement='invoice';
4697
-		if ($newelement == 'commande') $newelement='order';
4698
-		if (empty($newelement))
4699
-		{
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
-			return '';
4702
-		}
4703
-
4704
-		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4705
-		//var_dump($keyforfieldname);
4706
-		if (isset(Globals::$conf->global->$keyforfieldname))
4707
-            return Globals::$conf->global->$keyforfieldname;
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");
4708 1500
 
4709
-        // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4710
-	}
1501
+        if ($fk_user_field)
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;
1505
+        }
4711 1506
 
1507
+        $sql.= " WHERE ".$id_field." = ".$id;
4712 1508
 
4713
-	/* For triggers */
1509
+        dol_syslog(get_class($this)."::".__FUNCTION__."", LOG_DEBUG);
1510
+        $resql = $this->db->query($sql);
1511
+        if ($resql)
1512
+        {
1513
+            if ($trigkey)
1514
+            {
1515
+                // call trigger with updated object values
1516
+                if (empty($this->fields) && method_exists($this, 'fetch'))
1517
+                {
1518
+                    $result = $this->fetch($id);
1519
+                }
1520
+                else
1521
+                {
1522
+                    $result = $this->fetchCommon($id);
1523
+                }
1524
+                if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);   // This may set this->errors
1525
+                if ($result < 0) $error++;
1526
+            }
4714 1527
 
1528
+            if (! $error)
1529
+            {
1530
+                if (property_exists($this, $field)) $this->$field = $value;
1531
+                $this->db->commit();
1532
+                return 1;
1533
+            }
1534
+            else
1535
+            {
1536
+                $this->db->rollback();
1537
+                return -2;
1538
+            }
1539
+        }
1540
+        else
1541
+        {
1542
+            $this->error=$this->db->lasterror();
1543
+            $this->db->rollback();
1544
+            return -1;
1545
+        }
1546
+    }
4715 1547
 
4716 1548
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4717
-	/**
4718
-	 * Call trigger based on this instance.
4719
-	 * Some context information may also be provided into array property this->context.
4720
-	 * NB:  Error from trigger are stacked in interface->errors
4721
-	 * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
4722
-	 *
4723
-	 * @param   string    $trigger_name   trigger's name to execute
4724
-	 * @param   User      $user           Object user
4725
-	 * @return  int                       Result of run_triggers
4726
-	 */
4727
-	function call_trigger($trigger_name, $user)
4728
-	{
1549
+    /**
1550
+     *      Load properties id_previous and id_next by comparing $fieldid with $this->ref
1551
+     *
1552
+     *      @param	string	$filter		Optional filter. Example: " AND (t.field1 = 'aa' OR t.field2 = 'bb')"
1553
+     *	 	@param  string	$fieldid   	Name of field to use for the select MAX and MIN
1554
+     *		@param	int		$nodbprefix	Do not include DB prefix to forge table name
1555
+     *      @return int         		<0 if KO, >0 if OK
1556
+     */
1557
+    function load_previous_next_ref($filter, $fieldid, $nodbprefix=0)
1558
+    {
4729 1559
         // phpcs:enable
4730
-		global $langs,$conf;
1560
+        global $conf, $user;
4731 1561
 
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);
1562
+        if (! $this->table_element)
1563
+        {
1564
+            dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1565
+            return -1;
1566
+        }
1567
+        if ($fieldid == 'none') return 1;
4735 1568
 
4736
-		if ($result < 0)
4737
-		{
4738
-			if (!empty($this->errors))
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.
4741
-			}
4742
-			else
4743
-			{
4744
-				$this->errors=$interface->errors;
4745
-			}
4746
-		}
4747
-		return $result;
4748
-	}
1569
+        // Security on socid
1570
+        $socid = 0;
1571
+        if ($user->societe_id > 0) $socid = $user->societe_id;
4749 1572
 
1573
+        // this->ismultientitymanaged contains
1574
+        // 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
1575
+        $alias = 's';
1576
+        if ($this->element == 'societe') $alias = 'te';
4750 1577
 
4751
-	/* Functions for extrafields */
1578
+        $sql = "SELECT MAX(te.".$fieldid.")";
1579
+        $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
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
1597
+        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598
+            if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
+                if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1600
+                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1601
+                } else {
1602
+                    $sql.= " AND ug.fk_user = te.rowid";
1603
+                    $sql.= " AND ug.entity IN (".getEntity($this->element).")";
1604
+                }
1605
+            } else {
1606
+                $sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1607
+            }
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;
1612
+        //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
4752 1613
 
1614
+        $result = $this->db->query($sql);
1615
+        if (! $result)
1616
+        {
1617
+            $this->error=$this->db->lasterror();
1618
+            return -1;
1619
+        }
1620
+        $row = $this->db->fetch_row($result);
1621
+        $this->ref_previous = $row[0];
4753 1622
 
4754
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4755
-	/**
4756
-	 *  Function to get extra fields of an object into $this->array_options
4757
-	 *  This method is in most cases called by method fetch of objects but you can call it separately.
4758
-	 *
4759
-	 *  @param	int		$rowid			Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
4760
-	 *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
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
-	 */
4763
-	function fetch_optionals($rowid=null, $optionsArray=null)
4764
-	{
4765
-        // phpcs:enable
4766
-		if (empty($rowid)) {
4767
-            $rowid = $this->id;
1623
+
1624
+        $sql = "SELECT MIN(te.".$fieldid.")";
1625
+        $sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
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
1643
+        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644
+            if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
+                if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
1646
+                    $sql.= " AND te.entity IS NOT NULL"; // Show all users
1647
+                } else {
1648
+                    $sql.= " AND ug.fk_user = te.rowid";
1649
+                    $sql.= " AND ug.entity IN (".getEntity($this->element).")";
1650
+                }
1651
+            } else {
1652
+                $sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1653
+            }
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;
1658
+        //print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
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
+
1661
+        $result = $this->db->query($sql);
1662
+        if (! $result)
1663
+        {
1664
+            $this->error=$this->db->lasterror();
1665
+            return -2;
4768 1666
         }
1667
+        $row = $this->db->fetch_row($result);
1668
+        $this->ref_next = $row[0];
4769 1669
 
4770
-        // To avoid SQL errors. Probably not the better solution though
4771
-		if (!$this->table_element) {
4772
-			return 0;
4773
-		}
4774
-
4775
-		$this->array_options=array();
4776
-
4777
-		if (! is_array($optionsArray))
4778
-		{
4779
-			// If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4780
-			// TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
4781
-			// global $extrafields;
4782
-			//if (! is_object($extrafields))
4783
-			//{
4784
-				// require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4785
-            $extrafields = new ExtraFields();
4786
-            //}
1670
+        return 1;
1671
+    }
4787 1672
 
4788
-			// Load array of extrafields for elementype = $this->table_element
4789
-			if (empty($extrafields->attributes[$this->table_element]['loaded']))
4790
-			{
4791
-				$extrafields->fetch_name_optionals_label($this->table_element);
4792
-			}
4793
-			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4794
-		}
4795
-		else
4796
-		{
4797
-			// global $extrafields;
4798
-            dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4799
-		}
4800 1673
 
4801
-		$table_element = $this->table_element;
4802
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
1674
+    /**
1675
+     *      Return list of id of contacts of object
1676
+     *
1677
+     *      @param	string	$source     Source of contact: external (llx_socpeople) or internal (llx_user) or thirdparty (llx_societe)
1678
+     *      @return array				Array of id of contacts (if source=external or internal)
1679
+     * 									Array of id of third parties with at least one contact on object (if source=thirdparty)
1680
+     */
1681
+    function getListContactId($source='external')
1682
+    {
1683
+        $contactAlreadySelected = array();
1684
+        $tab = $this->liste_contact(-1,$source);
1685
+        $num=count($tab);
1686
+        $i = 0;
1687
+        while ($i < $num)
1688
+        {
1689
+            if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
1690
+            else  $contactAlreadySelected[$i] = $tab[$i]['id'];
1691
+            $i++;
1692
+        }
1693
+        return $contactAlreadySelected;
1694
+    }
4803 1695
 
4804
-		// Request to get complementary values
4805
-		if (is_array($optionsArray) && count($optionsArray) > 0)
4806
-		{
4807
-			$sql = "SELECT rowid";
4808
-			foreach ($optionsArray as $name => $label)
4809
-			{
4810
-				if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4811
-				{
4812
-					$sql.= ", ".$name;
4813
-				}
4814
-			}
4815
-			$sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4816
-			$sql.= " WHERE fk_object = ".$rowid;
4817 1696
 
4818
-			//dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4819
-			$resql=$this->db->query($sql);
4820
-			if ($resql)
4821
-			{
4822
-				$this->array_options = array();
4823
-				$numrows=$this->db->num_rows($resql);
4824
-				if ($numrows)
4825
-				{
4826
-					$tab = $this->db->fetch_array($resql);
4827
-
4828
-					foreach ($tab as $key => $value)
4829
-					{
4830
-						// 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)
4831
-						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4832
-						{
4833
-							// we can add this attribute to object
4834
-							if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4835
-							{
4836
-								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4837
-								$this->array_options["options_".$key]=$this->db->jdate($value);
4838
-							}
4839
-							else
4840
-							{
4841
-								$this->array_options["options_".$key]=$value;
4842
-							}
1697
+    /**
1698
+     *	Link element with a project
1699
+     *
1700
+     *	@param     	int		$projectid		Project id to link element to
1701
+     *	@return		int						<0 if KO, >0 if OK
1702
+     */
1703
+    function setProject($projectid)
1704
+    {
1705
+        if (! $this->table_element)
1706
+        {
1707
+            dol_syslog(get_class($this)."::setProject was called on objet with property table_element not defined",LOG_ERR);
1708
+            return -1;
1709
+        }
4843 1710
 
4844
-							//var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
4845
-						}
4846
-					}
4847
-				}
1711
+        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1712
+        if ($this->table_element == 'actioncomm')
1713
+        {
1714
+            if ($projectid) $sql.= ' SET fk_project = '.$projectid;
1715
+            else $sql.= ' SET fk_project = NULL';
1716
+            $sql.= ' WHERE id = '.$this->id;
1717
+        }
1718
+        else
1719
+        {
1720
+            if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
1721
+            else $sql.= ' SET fk_projet = NULL';
1722
+            $sql.= ' WHERE rowid = '.$this->id;
1723
+        }
4848 1724
 
4849
-				$this->db->free($resql);
1725
+        dol_syslog(get_class($this)."::setProject", LOG_DEBUG);
1726
+        if ($this->db->query($sql))
1727
+        {
1728
+            $this->fk_project = $projectid;
1729
+            return 1;
1730
+        }
1731
+        else
1732
+        {
1733
+            dol_print_error($this->db);
1734
+            return -1;
1735
+        }
1736
+    }
4850 1737
 
4851
-				if ($numrows) return $numrows;
4852
-				else return 0;
4853
-			}
4854
-			else
4855
-			{
4856
-				dol_print_error($this->db);
4857
-				return -1;
4858
-			}
4859
-		}
4860
-		return 0;
4861
-	}
4862
-
4863
-	/**
4864
-	 *	Delete all extra fields values for the current object.
4865
-	 *
4866
-	 *  @return	int		<0 if KO, >0 if OK
4867
-	 */
4868
-	function deleteExtraFields()
4869
-	{
4870
-		$this->db->begin();
4871
-
4872
-		$table_element = $this->table_element;
4873
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4874
-
4875
-		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4876
-		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4877
-		$resql=$this->db->query($sql_del);
4878
-		if (! $resql)
4879
-		{
4880
-			$this->error=$this->db->lasterror();
4881
-			$this->db->rollback();
4882
-			return -1;
4883
-		}
4884
-		else
4885
-		{
4886
-			$this->db->commit();
4887
-			return 1;
4888
-		}
4889
-	}
4890
-
4891
-	/**
4892
-	 *	Add/Update all extra fields values for the current object.
4893
-	 *  Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
4894
-	 *  This function delete record with all extrafields and insert them again from the array $this->array_options.
4895
-	 *
4896
-	 *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
4897
-	 *  @param	User		$userused		Object user
4898
-	 *  @return int 						-1=error, O=did nothing, 1=OK
4899
-	 *  @see updateExtraField, setValueFrom
4900
-	 */
4901
-	function insertExtraFields($trigger='', $userused=null)
4902
-	{
4903
-		global $conf,$langs,$user;
4904
-
4905
-		if (empty($userused)) $userused=$user;
4906
-
4907
-		$error=0;
4908
-
4909
-		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
4910
-            return 0; // For avoid conflicts if trigger used
1738
+    /**
1739
+     *  Change the payments methods
1740
+     *
1741
+     *  @param		int		$id		Id of new payment method
1742
+     *  @return		int				>0 if OK, <0 if KO
1743
+     */
1744
+    function setPaymentMethods($id)
1745
+    {
1746
+        dol_syslog(get_class($this).'::setPaymentMethods('.$id.')');
1747
+        if ($this->statut >= 0 || $this->element == 'societe')
1748
+        {
1749
+            // TODO uniformize field name
1750
+            $fieldname = 'fk_mode_reglement';
1751
+            if ($this->element == 'societe') $fieldname = 'mode_reglement';
1752
+            if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
4911 1753
 
4912
-        if (! empty($this->array_options))
4913
-		{
4914
-			// Check parameters
4915
-			$langs->load('admin');
4916
-			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4917
-			$extrafields = new ExtraFields($this->db);
4918
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4919
-
4920
-			//Eliminate copied source object extra_fields that do not exist in target object
4921
-			$new_array_options=array();
4922
-			foreach ($this->array_options as $key => $value) {
4923
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4924
-					$new_array_options[$key] = $value;
4925
-				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4926
-					$new_array_options['options_'.$key] = $value;
4927
-			}
4928
-
4929
-			foreach($new_array_options as $key => $value)
4930
-			{
4931
-			   	$attributeKey      = substr($key,8);   // Remove 'options_' prefix
4932
-			   	$attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4933
-			   	$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4934
-			   	$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
4935
-			   	$attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
4936
-
4937
-			   	if ($attributeRequired)
4938
-			   	{
4939
-			   		$mandatorypb=false;
4940
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4941
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
4942
-			   		if ($mandatorypb)
4943
-			   		{
4944
-			   			dol_syslog($this->error);
4945
-			   			$this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4946
-			   			return -1;
4947
-			   		}
4948
-			   	}
4949
-
4950
-				//dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
4951
-				//dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
4952
-
4953
-			   	switch ($attributeType)
4954
-			   	{
4955
-			   		case 'int':
4956
-			  			if (!is_numeric($value) && $value!='')
4957
-			   			{
4958
-			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4959
-			   				return -1;
4960
-			  			}
4961
-			   			elseif ($value=='')
4962
-			   			{
4963
-			   				$new_array_options[$key] = null;
4964
-			   			}
4965
-			 			break;
4966
-					case 'double':
4967
-						$value = price2num($value);
4968
-						if (!is_numeric($value) && $value!='')
4969
-						{
4970
-							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4971
-							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4972
-							return -1;
4973
-						}
4974
-						elseif ($value=='')
4975
-						{
4976
-							$new_array_options[$key] = null;
4977
-						}
4978
-						//dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
4979
-						$new_array_options[$key] = $value;
4980
-						break;
4981
-			 		/*case 'select':	// Not required, we chosed value='0' for undefined values
4982
-             			if ($value=='-1')
4983
-             			{
4984
-             				$this->array_options[$key] = null;
4985
-             			}
4986
-             			break;*/
4987
-			   		case 'password':
4988
-			   			$algo='';
4989
-			   			if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4990
-			   			{
4991
-			   				// If there is an encryption choice, we use it to crypt data before insert
4992
-			   				$tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4993
-			   				$algo=reset($tmparrays);
4994
-			   				if ($algo != '')
4995
-			   				{
4996
-			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
4997
-			   					//var_dump($action);
4998
-			   					//var_dump($this->oldcopy);exit;
4999
-			   					if (is_object($this->oldcopy))		// If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
5000
-			   					{
5001
-			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
5002
-				   					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.
5003
-				   					{
5004
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5005
-				   					}
5006
-									else
5007
-									{
5008
-										// var_dump($algo);
5009
-										$newvalue = dol_hash($this->array_options[$key], $algo);
5010
-										$new_array_options[$key] = $newvalue;
5011
-									}
5012
-			   					}
5013
-			   					else
5014
-			   					{
5015
-			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5016
-			   					}
5017
-			   				}
5018
-			   			}
5019
-			   			else	// Common usage
5020
-			   			{
5021
-			   				$new_array_options[$key] = $this->array_options[$key];
5022
-			   			}
5023
-			   			break;
5024
-			   		case 'price':
5025
-						$new_array_options[$key] = price2num($this->array_options[$key]);
5026
-						break;
5027
-					case 'date':
5028
-						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5029
-						break;
5030
-					case 'datetime':
5031
-						// If data is a string instead of a timestamp, we convert it
5032
-						if (! is_int($this->array_options[$key])) {
5033
-							$this->array_options[$key] = strtotime($this->array_options[$key]);
5034
-						}
5035
-						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5036
-						break;
5037
-		   			case 'link':
5038
-						$param_list=array_keys($attributeParam['options']);
5039
-						// 0 : ObjectName
5040
-						// 1 : classPath
5041
-						$InfoFieldList = explode(":", $param_list[0]);
5042
-						dol_include_once($InfoFieldList[1]);
5043
-						if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5044
-						{
5045
-							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5046
-							{
5047
-								$new_array_options[$key]='';
5048
-							}
5049
-							elseif ($value)
5050
-							{
5051
-								$object = new $InfoFieldList[0]($this->db);
5052
-								if (is_numeric($value)) $res=$object->fetch($value);
5053
-								else $res=$object->fetch('',$value);
5054
-
5055
-								if ($res > 0) $new_array_options[$key]=$object->id;
5056
-								else
5057
-								{
5058
-									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5059
-									$this->db->rollback();
5060
-									return -1;
5061
-								}
5062
-							}
5063
-						}
5064
-						else
5065
-						{
5066
-							dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5067
-						}
5068
-						break;
5069
-			   	}
5070
-			}
1754
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1755
+            $sql .= ' SET '.$fieldname.' = '.$id;
1756
+            $sql .= ' WHERE rowid='.$this->id;
5071 1757
 
5072
-			$this->db->begin();
1758
+            if ($this->db->query($sql))
1759
+            {
1760
+                $this->mode_reglement_id = $id;
1761
+                // for supplier
1762
+                if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
1763
+                return 1;
1764
+            }
1765
+            else
1766
+            {
1767
+                dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
1768
+                $this->error=$this->db->error();
1769
+                return -1;
1770
+            }
1771
+        }
1772
+        else
1773
+        {
1774
+            dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
1775
+            $this->error='Status of the object is incompatible '.$this->statut;
1776
+            return -2;
1777
+        }
1778
+    }
5073 1779
 
5074
-			$table_element = $this->table_element;
5075
-			if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
1780
+    /**
1781
+     *  Change the multicurrency code
1782
+     *
1783
+     *  @param		string	$code	multicurrency code
1784
+     *  @return		int				>0 if OK, <0 if KO
1785
+     */
1786
+    function setMulticurrencyCode($code)
1787
+    {
1788
+        dol_syslog(get_class($this).'::setMulticurrencyCode('.$id.')');
1789
+        if ($this->statut >= 0 || $this->element == 'societe')
1790
+        {
1791
+            $fieldname = 'multicurrency_code';
5076 1792
 
5077
-			$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5078
-			dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
5079
-			$this->db->query($sql_del);
1793
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1794
+            $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
1795
+            $sql .= ' WHERE rowid='.$this->id;
5080 1796
 
5081
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5082
-			foreach($new_array_options as $key => $value)
5083
-			{
5084
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5085
-				// Add field of attribut
5086
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5087
-					$sql.=",".$attributeKey;
5088
-			}
5089
-			$sql .= ") VALUES (".$this->id;
5090
-
5091
-			foreach($new_array_options as $key => $value)
5092
-			{
5093
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5094
-				// Add field of attribute
5095
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5096
-				{
5097
-					if ($new_array_options[$key] != '')
5098
-					{
5099
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5100
-					}
5101
-					else
5102
-					{
5103
-						$sql.=",null";
5104
-					}
5105
-				}
5106
-			}
5107
-			$sql.=")";
1797
+            if ($this->db->query($sql))
1798
+            {
1799
+                $this->multicurrency_code = $code;
5108 1800
 
5109
-			dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5110
-			$resql = $this->db->query($sql);
5111
-			if (! $resql)
5112
-			{
5113
-				$this->error=$this->db->lasterror();
5114
-				$error++;
5115
-			}
1801
+                list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
+                if ($rate) $this->setMulticurrencyRate($rate,2);
5116 1803
 
5117
-			if (! $error && $trigger)
5118
-			{
5119
-				// Call trigger
5120
-				$this->context=array('extrafieldaddupdate'=>1);
5121
-				$result=$this->call_trigger($trigger, $userused);
5122
-				if ($result < 0) $error++;
5123
-				// End call trigger
5124
-			}
5125
-
5126
-			if ($error)
5127
-			{
5128
-				$this->db->rollback();
5129
-				return -1;
5130
-			}
5131
-			else
5132
-			{
5133
-				$this->db->commit();
5134
-				return 1;
5135
-			}
5136
-		}
5137
-		else return 0;
5138
-	}
5139
-
5140
-	/**
5141
-	 *	Update an extra field value for the current object.
5142
-	 *  Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
5143
-	 *
5144
-	 *  @param  string      $key    		Key of the extrafield (without starting 'options_')
5145
-	 *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
5146
-	 *  @param	User		$userused		Object user
5147
-	 *  @return int                 		-1=error, O=did nothing, 1=OK
5148
-	 *  @see setValueFrom, insertExtraFields
5149
-	 */
5150
-	function updateExtraField($key, $trigger=null, $userused=null)
5151
-	{
5152
-		global $conf,$langs,$user;
5153
-
5154
-		if (empty($userused)) $userused=$user;
5155
-
5156
-		$error=0;
5157
-
5158
-		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
5159
-            return 0; // For avoid conflicts if trigger used
5160
-
5161
-        if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5162
-		{
5163
-			// Check parameters
5164
-			$langs->load('admin');
5165
-			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5166
-			$extrafields = new ExtraFields($this->db);
5167
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
1804
+                return 1;
1805
+            }
1806
+            else
1807
+            {
1808
+                dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
1809
+                $this->error=$this->db->error();
1810
+                return -1;
1811
+            }
1812
+        }
1813
+        else
1814
+        {
1815
+            dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
1816
+            $this->error='Status of the object is incompatible '.$this->statut;
1817
+            return -2;
1818
+        }
1819
+    }
5168 1820
 
5169
-			$value=$this->array_options["options_".$key];
1821
+    /**
1822
+     *  Change the multicurrency rate
1823
+     *
1824
+     *  @param		double	$rate	multicurrency rate
1825
+     *  @param		int		$mode	mode 1 : amounts in company currency will be recalculated, mode 2 : amounts in foreign currency
1826
+     *  @return		int				>0 if OK, <0 if KO
1827
+     */
1828
+    function setMulticurrencyRate($rate, $mode=1)
1829
+    {
1830
+        dol_syslog(get_class($this).'::setMulticurrencyRate('.$id.')');
1831
+        if ($this->statut >= 0 || $this->element == 'societe')
1832
+        {
1833
+            $fieldname = 'multicurrency_tx';
5170 1834
 
5171
-			$attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5172
-			$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
5173
-			$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$key];
5174
-			$attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
1835
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1836
+            $sql .= ' SET '.$fieldname.' = '.$rate;
1837
+            $sql .= ' WHERE rowid='.$this->id;
5175 1838
 
5176
-			//dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
5177
-			//dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
1839
+            if ($this->db->query($sql))
1840
+            {
1841
+                $this->multicurrency_tx = $rate;
1842
+
1843
+                // Update line price
1844
+                if (!empty($this->lines))
1845
+                {
1846
+                    foreach ($this->lines as &$line)
1847
+                    {
1848
+                        if($mode == 1) {
1849
+                            $line->subprice = 0;
1850
+                        }
5178 1851
 
5179
-			switch ($attributeType)
5180
-			{
5181
-				case 'int':
5182
-					if (!is_numeric($value) && $value!='')
5183
-					{
5184
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5185
-						return -1;
5186
-					}
5187
-					elseif ($value=='')
5188
-					{
5189
-						$this->array_options["options_".$key] = null;
5190
-					}
5191
-					break;
5192
-				case 'double':
5193
-					$value = price2num($value);
5194
-					if (!is_numeric($value) && $value!='')
5195
-					{
5196
-						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5197
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5198
-						return -1;
5199
-					}
5200
-					elseif ($value=='')
5201
-					{
5202
-						$this->array_options["options_".$key] = null;
5203
-					}
5204
-					//dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
5205
-					$this->array_options["options_".$key] = $value;
5206
-					break;
5207
-			 	/*case 'select':	// Not required, we chosed value='0' for undefined values
5208
-             		if ($value=='-1')
5209
-             		{
5210
-             			$this->array_options[$key] = null;
5211
-             		}
5212
-             		break;*/
5213
-				case 'price':
5214
-					$this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5215
-					break;
5216
-				case 'date':
5217
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5218
-					break;
5219
-				case 'datetime':
5220
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5221
-					break;
5222
-				case 'link':
5223
-					$param_list=array_keys($attributeParam['options']);
5224
-					// 0 : ObjectName
5225
-					// 1 : classPath
5226
-					$InfoFieldList = explode(":", $param_list[0]);
5227
-					dol_include_once($InfoFieldList[1]);
5228
-					if ($value)
5229
-					{
5230
-						$object = new $InfoFieldList[0]($this->db);
5231
-						$object->fetch(0,$value);
5232
-						$this->array_options["options_".$key]=$object->id;
5233
-					}
5234
-					break;
5235
-			}
5236
-
5237
-			$this->db->begin();
5238
-			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5239
-			$sql .= " WHERE fk_object = ".$this->id;
5240
-			$resql = $this->db->query($sql);
5241
-			if (! $resql)
5242
-			{
5243
-				$error++;
5244
-				$this->error=$this->db->lasterror();
5245
-			}
1852
+                        switch ($this->element) {
1853
+                            case 'propal':
1854
+                                $this->updateline(
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,
1857
+                                    $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->date_start,
1858
+                                    $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1859
+                                );
1860
+                                break;
1861
+                            case 'commande':
1862
+                                $this->updateline(
1863
+                                    $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1864
+                                    $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->date_start, $line->date_end,
1865
+                                    $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1866
+                                    $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1867
+                                );
1868
+                                break;
1869
+                            case 'facture':
1870
+                                $this->updateline(
1871
+                                    $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1872
+                                    $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits,
1873
+                                    $line->product_type, $line->fk_parent_line, $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label,
1874
+                                    $line->special_code, $line->array_options, $line->situation_percent, $line->fk_unit, $line->multicurrency_subprice
1875
+                                );
1876
+                                break;
1877
+                            case 'supplier_proposal':
1878
+                                $this->updateline(
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,
1881
+                                    $line->skip_update_total, $line->fk_fournprice, $line->pa_ht, $line->label, $line->product_type, $line->array_options,
1882
+                                    $line->ref_fourn, $line->multicurrency_subprice
1883
+                                );
1884
+                                break;
1885
+                            case 'order_supplier':
1886
+                                $this->updateline(
1887
+                                    $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->qty, $line->remise_percent,
1888
+                                    $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, false,
1889
+                                    $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1890
+                                );
1891
+                                break;
1892
+                            case 'invoice_supplier':
1893
+                                $this->updateline(
1894
+                                    $line->id, ($line->description?$line->description:$line->desc), $line->subprice, $line->tva_tx, $line->localtax1_tx,
1895
+                                    $line->localtax2_tx, $line->qty, 0, 'HT', $line->info_bits, $line->product_type, $line->remise_percent, false,
1896
+                                    $line->date_start, $line->date_end, $line->array_options, $line->fk_unit, $line->multicurrency_subprice
1897
+                                );
1898
+                                break;
1899
+                            default:
1900
+                                dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
1901
+                                break;
1902
+                        }
1903
+                    }
1904
+                }
5246 1905
 
5247
-			if (! $error && $trigger)
5248
-			{
5249
-				// Call trigger
5250
-				$this->context=array('extrafieldupdate'=>1);
5251
-				$result=$this->call_trigger($trigger, $userused);
5252
-				if ($result < 0) $error++;
5253
-				// End call trigger
5254
-			}
5255
-
5256
-			if ($error)
5257
-			{
5258
-				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5259
-				$this->db->rollback();
5260
-				return -1;
5261
-			}
5262
-			else
5263
-			{
5264
-				$this->db->commit();
5265
-				return 1;
5266
-			}
5267
-		}
5268
-		else return 0;
5269
-	}
5270
-
5271
-
5272
-	/**
5273
-	 * Return HTML string to put an input field into a page
5274
-	 * Code very similar with showInputField of extra fields
5275
-	 *
5276
-	 * @param  array   		$val	       Array of properties for field to show
5277
-	 * @param  string  		$key           Key of attribute
5278
-	 * @param  string  		$value         Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
5279
-	 * @param  string  		$moreparam     To add more parameters on html input tag
5280
-	 * @param  string  		$keysuffix     Prefix string to add into name and id of field (can be used to avoid duplicate names)
5281
-	 * @param  string  		$keyprefix     Suffix string to add into name and id of field (can be used to avoid duplicate names)
5282
-	 * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5283
-	 * @return string
5284
-	 */
5285
-	function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5286
-	{
5287
-		global $conf,$langs,$form;
5288
-
5289
-		if (! is_object($form))
5290
-		{
5291
-			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5292
-			$form=new Form($this->db);
5293
-		}
5294
-
5295
-		$val=$this->fields[$key];
5296
-
5297
-		$out='';
5298
-        $type='';
5299
-        $param = array();
5300
-        $param['options']=array();
5301
-        $size =$this->fields[$key]['size'];
5302
-        // Because we work on extrafields
5303
-        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5304
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5305
-            $type ='link';
5306
-        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5307
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5308
-            $type ='link';
5309
-        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5310
-            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5311
-            $type ='sellist';
5312
-        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5313
-            $param['options']=array();
5314
-            $type ='varchar';
5315
-            $size=$reg[1];
5316
-        } elseif(preg_match('/varchar/', $val['type'])) {
5317
-            $param['options']=array();
5318
-            $type ='varchar';
5319
-        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5320
-            $param['options']=$this->fields[$key]['arrayofkeyval'];
5321
-            $type ='select';
5322
-        } else {
5323
-            $param['options']=array();
5324
-            $type =$this->fields[$key]['type'];
1906
+                return 1;
1907
+            }
1908
+            else
1909
+            {
1910
+                dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
1911
+                $this->error=$this->db->error();
1912
+                return -1;
1913
+            }
1914
+        }
1915
+        else
1916
+        {
1917
+            dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
1918
+            $this->error='Status of the object is incompatible '.$this->statut;
1919
+            return -2;
5325 1920
         }
1921
+    }
5326 1922
 
5327
-		$label=$this->fields[$key]['label'];
5328
-		//$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5329
-		$default=$this->fields[$key]['default'];
5330
-		$computed=$this->fields[$key]['computed'];
5331
-		$unique=$this->fields[$key]['unique'];
5332
-		$required=$this->fields[$key]['required'];
1923
+    /**
1924
+     *  Change the payments terms
1925
+     *
1926
+     *  @param		int		$id		Id of new payment terms
1927
+     *  @return		int				>0 if OK, <0 if KO
1928
+     */
1929
+    function setPaymentTerms($id)
1930
+    {
1931
+        dol_syslog(get_class($this).'::setPaymentTerms('.$id.')');
1932
+        if ($this->statut >= 0 || $this->element == 'societe')
1933
+        {
1934
+            // TODO uniformize field name
1935
+            $fieldname = 'fk_cond_reglement';
1936
+            if ($this->element == 'societe') $fieldname = 'cond_reglement';
1937
+            if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
5333 1938
 
5334
-		$langfile=$this->fields[$key]['langfile'];
5335
-		$list=$this->fields[$key]['list'];
5336
-		$hidden=abs($this->fields[$key]['visible'])!=1?1:0;
1939
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1940
+            $sql .= ' SET '.$fieldname.' = '.$id;
1941
+            $sql .= ' WHERE rowid='.$this->id;
5337 1942
 
5338
-		$objectid = $this->id;
1943
+            if ($this->db->query($sql))
1944
+            {
1945
+                $this->cond_reglement_id = $id;
1946
+                // for supplier
1947
+                if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
1948
+                $this->cond_reglement = $id;	// for compatibility
1949
+                return 1;
1950
+            }
1951
+            else
1952
+            {
1953
+                dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
1954
+                $this->error=$this->db->error();
1955
+                return -1;
1956
+            }
1957
+        }
1958
+        else
1959
+        {
1960
+            dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
1961
+            $this->error='Status of the object is incompatible '.$this->statut;
1962
+            return -2;
1963
+        }
1964
+    }
5339 1965
 
1966
+    /**
1967
+     *	Define delivery address
1968
+     *  @deprecated
1969
+     *
1970
+     *	@param      int		$id		Address id
1971
+     *	@return     int				<0 si ko, >0 si ok
1972
+     */
1973
+    function setDeliveryAddress($id)
1974
+    {
1975
+        $fieldname = 'fk_delivery_address';
1976
+        if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
5340 1977
 
5341
-		if ($computed)
5342
-		{
5343
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5344
-			else return '';
5345
-		}
1978
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
1979
+        $sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
5346 1980
 
1981
+        if ($this->db->query($sql))
1982
+        {
1983
+            $this->fk_delivery_address = $id;
1984
+            return 1;
1985
+        }
1986
+        else
1987
+        {
1988
+            $this->error=$this->db->error();
1989
+            dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
1990
+            return -1;
1991
+        }
1992
+    }
5347 1993
 
5348
-		// Use in priority showsize from parameters, then $val['css'] then autodefine
5349
-		if (empty($morecss) && ! empty($val['css']))
5350
-		{
5351
-			$showsize = $val['css'];
5352
-		}
5353
-		if (empty($morecss))
5354
-		{
5355
-			if ($type == 'date')
5356
-			{
5357
-				$morecss = 'minwidth100imp';
5358
-			}
5359
-			elseif ($type == 'datetime')
5360
-			{
5361
-				$morecss = 'minwidth200imp';
5362
-			}
5363
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5364
-			{
5365
-				$morecss = 'maxwidth75';
5366
-                        }elseif ($type == 'url')
5367
-			{
5368
-				$morecss='minwidth400';
5369
-			}
5370
-			elseif ($type == 'boolean')
5371
-			{
5372
-				$morecss='';
5373
-			}
5374
-			else
5375
-			{
5376
-				if (round($size) < 12)
5377
-				{
5378
-					$morecss = 'minwidth100';
5379
-				}
5380
-				else if (round($size) <= 48)
5381
-				{
5382
-					$morecss = 'minwidth200';
5383
-				}
5384
-				else
5385
-				{
5386
-					$morecss = 'minwidth400';
5387
-				}
5388
-			}
5389
-		}
5390
-
5391
-		if (in_array($type,array('date','datetime')))
5392
-		{
5393
-			$tmp=explode(',',$size);
5394
-			$newsize=$tmp[0];
5395
-
5396
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5397
-
5398
-			// Do not show current date when field not required (see selectDate() method)
5399
-			if (!$required && $value == '') $value = '-1';
5400
-
5401
-			// TODO Must also support $moreparam
5402
-			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5403
-		}
5404
-		elseif (in_array($type,array('int','integer')))
5405
-		{
5406
-			$tmp=explode(',',$size);
5407
-			$newsize=$tmp[0];
5408
-			$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:'').'>';
5409
-		}
5410
-		elseif (preg_match('/varchar/', $type))
5411
-		{
5412
-			$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:'').'>';
5413
-		}
5414
-		elseif (in_array($type, array('mail', 'phone', 'url')))
5415
-		{
5416
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5417
-		}
5418
-		elseif ($type == 'text')
5419
-		{
5420
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5421
-			{
5422
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5423
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5424
-				$out=$doleditor->Create(1);
5425
-			}
5426
-			else
5427
-			{
5428
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5429
-			}
5430
-		}
5431
-		elseif ($type == 'html')
5432
-		{
5433
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5434
-			{
5435
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5436
-				$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%');
5437
-                $out=$doleditor->Create(1);
5438
-			}
5439
-			else
5440
-			{
5441
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5442
-			}
5443
-		}
5444
-		elseif ($type == 'boolean')
5445
-		{
5446
-			$checked='';
5447
-			if (!empty($value)) {
5448
-				$checked=' checked value="1" ';
5449
-			} else {
5450
-				$checked=' value="1" ';
5451
-			}
5452
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5453
-		}
5454
-		elseif ($type == 'price')
5455
-		{
5456
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5457
-				$value=price($value);
5458
-			}
5459
-			$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);
5460
-        }
5461
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5462
-		{
5463
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5464
-				$value=price($value);
5465
-			}
5466
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5467
-		}
5468
-		elseif ($type == 'select')
5469
-		{
5470
-			$out = '';
5471
-			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5472
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5473
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5474
-			}
5475
-
5476
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5477
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5478
-			foreach ($param['options'] as $key => $val)
5479
-			{
5480
-				if ((string) $key == '') continue;
5481
-				list($val, $parent) = explode('|', $val);
5482
-				$out.='<option value="'.$key.'"';
5483
-				$out.= (((string) $value == (string) $key)?' selected':'');
5484
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5485
-				$out.='>'.$val.'</option>';
5486
-			}
5487
-			$out.='</select>';
5488
-		}
5489
-		elseif ($type == 'sellist')
5490
-		{
5491
-			$out = '';
5492
-			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5493
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5494
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5495
-			}
5496
-
5497
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5498
-			if (is_array($param['options']))
5499
-			{
5500
-				$param_list=array_keys($param['options']);
5501
-				$InfoFieldList = explode(":", $param_list[0]);
5502
-				$parentName='';
5503
-				$parentField='';
5504
-				// 0 : tableName
5505
-				// 1 : label field name
5506
-				// 2 : key fields name (if differ of rowid)
5507
-				// 3 : key field parent (for dependent lists)
5508
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5509
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5510
-
5511
-
5512
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5513
-				{
5514
-					if (strpos($InfoFieldList[4], 'extra.') !== false)
5515
-					{
5516
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
5517
-					} else {
5518
-						$keyList=$InfoFieldList[2].' as rowid';
5519
-					}
5520
-				}
5521
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5522
-				{
5523
-					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5524
-					$keyList.= ', '.$parentField;
5525
-				}
5526 1994
 
5527
-				$fields_label = explode('|',$InfoFieldList[1]);
5528
-				if (is_array($fields_label))
5529
-				{
5530
-					$keyList .=', ';
5531
-					$keyList .= implode(', ', $fields_label);
5532
-				}
1995
+    /**
1996
+     *  Change the shipping method
1997
+     *
1998
+     *  @param      int     $shipping_method_id     Id of shipping method
1999
+     *  @param      bool    $notrigger              false=launch triggers after, true=disable triggers
2000
+     *  @param      User	$userused               Object user
2001
+     *
2002
+     *  @return     int              1 if OK, 0 if KO
2003
+     */
2004
+    function setShippingMethod($shipping_method_id, $notrigger=false, $userused=null)
2005
+    {
2006
+        global $user;
5533 2007
 
5534
-				$sqlwhere='';
5535
-				$sql = 'SELECT '.$keyList;
5536
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5537
-				if (!empty($InfoFieldList[4]))
5538
-				{
5539
-					// can use SELECT request
5540
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5541
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5542
-					}
5543
-
5544
-					// current object id can be use into filter
5545
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5546
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5547
-					} else {
5548
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5549
-					}
5550
-					//We have to join on extrafield table
5551
-					if (strpos($InfoFieldList[4], 'extra')!==false)
5552
-					{
5553
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5554
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5555
-					}
5556
-					else
5557
-					{
5558
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5559
-					}
5560
-				}
5561
-				else
5562
-				{
5563
-					$sqlwhere.= ' WHERE 1=1';
5564
-				}
5565
-				// Some tables may have field, some other not. For the moment we disable it.
5566
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
5567
-				{
5568
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5569
-                }
5570
-				$sql.=$sqlwhere;
5571
-				//print $sql;
2008
+        if (empty($userused)) $userused=$user;
5572 2009
 
5573
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
2010
+        $error = 0;
5574 2011
 
5575
-				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5576
-				$resql = $this->db->query($sql);
5577
-				if ($resql)
5578
-				{
5579
-					$out.='<option value="0">&nbsp;</option>';
5580
-					$num = $this->db->num_rows($resql);
5581
-					$i = 0;
5582
-					while ($i < $num)
5583
-					{
5584
-						$labeltoshow='';
5585
-						$obj = $this->db->fetch_object($resql);
5586
-
5587
-						// Several field into label (eq table:code|libelle:rowid)
5588
-						$notrans = false;
5589
-						$fields_label = explode('|',$InfoFieldList[1]);
5590
-						if (is_array($fields_label))
5591
-						{
5592
-							$notrans = true;
5593
-							foreach ($fields_label as $field_toshow)
5594
-							{
5595
-								$labeltoshow.= $obj->$field_toshow.' ';
5596
-							}
5597
-						}
5598
-						else
5599
-						{
5600
-							$labeltoshow=$obj->{$InfoFieldList[1]};
5601
-						}
5602
-						$labeltoshow=dol_trunc($labeltoshow,45);
5603
-
5604
-						if ($value == $obj->rowid)
5605
-						{
5606
-							foreach ($fields_label as $field_toshow)
5607
-							{
5608
-								$translabel=$langs->trans($obj->$field_toshow);
5609
-								if ($translabel!=$obj->$field_toshow) {
5610
-									$labeltoshow=dol_trunc($translabel,18).' ';
5611
-								}else {
5612
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5613
-								}
5614
-							}
5615
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5616
-						}
5617
-						else
5618
-						{
5619
-							if (! $notrans)
5620
-							{
5621
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5622
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5623
-									$labeltoshow=dol_trunc($translabel,18);
5624
-								}
5625
-								else {
5626
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5627
-								}
5628
-							}
5629
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
5630
-							if ($value==$obj->rowid)
5631
-							{
5632
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5633
-							}
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
+            return -1;
2015
+        }
5634 2016
 
5635
-							if (!empty($InfoFieldList[3]) && $parentField)
5636
-							{
5637
-								$parent = $parentName.':'.$obj->{$parentField};
5638
-							}
2017
+        $this->db->begin();
5639 2018
 
5640
-							$out.='<option value="'.$obj->rowid.'"';
5641
-							$out.= ($value==$obj->rowid?' selected':'');
5642
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5643
-							$out.='>'.$labeltoshow.'</option>';
5644
-						}
2019
+        if ($shipping_method_id<0) $shipping_method_id='NULL';
2020
+        dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
5645 2021
 
5646
-						$i++;
5647
-					}
5648
-					$this->db->free($resql);
5649
-				}
5650
-				else {
5651
-					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5652
-				}
5653
-			}
5654
-			$out.='</select>';
5655
-		}
5656
-		elseif ($type == 'checkbox')
5657
-		{
5658
-			$value_arr=explode(',',$value);
5659
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5660
-		}
5661
-		elseif ($type == 'radio')
5662
-		{
5663
-			$out='';
5664
-			foreach ($param['options'] as $keyopt => $val)
5665
-			{
5666
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5667
-				$out.=' value="'.$keyopt.'"';
5668
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5669
-				$out.= ($value==$keyopt?'checked':'');
5670
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5671
-			}
5672
-		}
5673
-		elseif ($type == 'chkbxlst')
5674
-		{
5675
-			if (is_array($value)) {
5676
-				$value_arr = $value;
5677
-			}
5678
-			else {
5679
-				$value_arr = explode(',', $value);
5680
-			}
5681
-
5682
-			if (is_array($param['options'])) {
5683
-				$param_list = array_keys($param['options']);
5684
-				$InfoFieldList = explode(":", $param_list[0]);
5685
-				$parentName='';
5686
-				$parentField='';
5687
-				// 0 : tableName
5688
-				// 1 : label field name
5689
-				// 2 : key fields name (if differ of rowid)
5690
-				// 3 : key field parent (for dependent lists)
5691
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5692
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5693
-
5694
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5695
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5696
-					$keyList .= ', ' . $parentField;
5697
-				}
5698
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5699
-					if (strpos($InfoFieldList[4], 'extra.') !== false) {
5700
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5701
-					} else {
5702
-						$keyList = $InfoFieldList[2] . ' as rowid';
5703
-					}
5704
-				}
2022
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2023
+        $sql.= " SET fk_shipping_method = ".$shipping_method_id;
2024
+        $sql.= " WHERE rowid=".$this->id;
2025
+        $resql = $this->db->query($sql);
2026
+        if (! $resql) {
2027
+            dol_syslog(get_class($this).'::setShippingMethod Error ', LOG_DEBUG);
2028
+            $this->error = $this->db->lasterror();
2029
+            $error++;
2030
+        } else {
2031
+            if (!$notrigger)
2032
+            {
2033
+                // Call trigger
2034
+                $this->context=array('shippingmethodupdate'=>1);
2035
+                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2036
+                if ($result < 0) $error++;
2037
+                // End call trigger
2038
+            }
2039
+        }
2040
+        if ($error)
2041
+        {
2042
+            $this->db->rollback();
2043
+            return -1;
2044
+        } else {
2045
+            $this->shipping_method_id = ($shipping_method_id=='NULL')?null:$shipping_method_id;
2046
+            $this->db->commit();
2047
+            return 1;
2048
+        }
2049
+    }
5705 2050
 
5706
-				$fields_label = explode('|', $InfoFieldList[1]);
5707
-				if (is_array($fields_label)) {
5708
-					$keyList .= ', ';
5709
-					$keyList .= implode(', ', $fields_label);
5710
-				}
5711 2051
 
5712
-				$sqlwhere = '';
5713
-				$sql = 'SELECT ' . $keyList;
5714
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5715
-				if (! empty($InfoFieldList[4])) {
5716
-
5717
-					// can use SELECT request
5718
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5719
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5720
-					}
5721
-
5722
-					// current object id can be use into filter
5723
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5724
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5725
-					} else {
5726
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5727
-					}
5728
-
5729
-					// We have to join on extrafield table
5730
-					if (strpos($InfoFieldList[4], 'extra') !== false) {
5731
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5732
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5733
-					} else {
5734
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5735
-					}
5736
-				} else {
5737
-					$sqlwhere .= ' WHERE 1=1';
5738
-				}
5739
-				// Some tables may have field, some other not. For the moment we disable it.
5740
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
5741
-				{
5742
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5743
-                }
5744
-				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
5745
-				// print $sql;
5746
-
5747
-				$sql .= $sqlwhere;
5748
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5749
-				$resql = $this->db->query($sql);
5750
-				if ($resql) {
5751
-					$num = $this->db->num_rows($resql);
5752
-					$i = 0;
5753
-
5754
-					$data=array();
5755
-
5756
-					while ( $i < $num ) {
5757
-						$labeltoshow = '';
5758
-						$obj = $this->db->fetch_object($resql);
5759
-
5760
-						$notrans = false;
5761
-						// Several field into label (eq table:code|libelle:rowid)
5762
-						$fields_label = explode('|', $InfoFieldList[1]);
5763
-						if (is_array($fields_label)) {
5764
-							$notrans = true;
5765
-							foreach ( $fields_label as $field_toshow ) {
5766
-								$labeltoshow .= $obj->$field_toshow . ' ';
5767
-							}
5768
-						} else {
5769
-							$labeltoshow = $obj->{$InfoFieldList[1]};
5770
-						}
5771
-						$labeltoshow = dol_trunc($labeltoshow, 45);
5772
-
5773
-						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5774
-							foreach ( $fields_label as $field_toshow ) {
5775
-								$translabel = $langs->trans($obj->$field_toshow);
5776
-								if ($translabel != $obj->$field_toshow) {
5777
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
5778
-								} else {
5779
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5780
-								}
5781
-							}
2052
+    /**
2053
+     *  Change the warehouse
2054
+     *
2055
+     *  @param      int     $warehouse_id     Id of warehouse
2056
+     *  @return     int              1 if OK, 0 if KO
2057
+     */
2058
+    function setWarehouse($warehouse_id)
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);
2062
+            return -1;
2063
+        }
2064
+        if ($warehouse_id<0) $warehouse_id='NULL';
2065
+        dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
5782 2066
 
5783
-							$data[$obj->rowid]=$labeltoshow;
5784
-						} else {
5785
-							if (! $notrans) {
5786
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5787
-								if ($translabel != $obj->{$InfoFieldList[1]}) {
5788
-									$labeltoshow = dol_trunc($translabel, 18);
5789
-								} else {
5790
-									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5791
-								}
5792
-							}
5793
-							if (empty($labeltoshow))
5794
-								$labeltoshow = '(not defined)';
2067
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2068
+        $sql.= " SET fk_warehouse = ".$warehouse_id;
2069
+        $sql.= " WHERE rowid=".$this->id;
5795 2070
 
5796
-								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5797
-									$data[$obj->rowid]=$labeltoshow;
5798
-								}
2071
+        if ($this->db->query($sql)) {
2072
+            $this->warehouse_id = ($warehouse_id=='NULL')?null:$warehouse_id;
2073
+            return 1;
2074
+        } else {
2075
+            dol_syslog(get_class($this).'::setWarehouse Error ', LOG_DEBUG);
2076
+            $this->error=$this->db->error();
2077
+            return 0;
2078
+        }
2079
+    }
5799 2080
 
5800
-								if (! empty($InfoFieldList[3]) && $parentField) {
5801
-									$parent = $parentName . ':' . $obj->{$parentField};
5802
-								}
5803 2081
 
5804
-								$data[$obj->rowid]=$labeltoshow;
5805
-						}
2082
+    /**
2083
+     *		Set last model used by doc generator
2084
+     *
2085
+     *		@param		User	$user		User object that make change
2086
+     *		@param		string	$modelpdf	Modele name
2087
+     *		@return		int					<0 if KO, >0 if OK
2088
+     */
2089
+    function setDocModel($user, $modelpdf)
2090
+    {
2091
+        if (! $this->table_element)
2092
+        {
2093
+            dol_syslog(get_class($this)."::setDocModel was called on objet with property table_element not defined",LOG_ERR);
2094
+            return -1;
2095
+        }
5806 2096
 
5807
-						$i ++;
5808
-					}
5809
-					$this->db->free($resql);
2097
+        $newmodelpdf=dol_trunc($modelpdf,255);
5810 2098
 
5811
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5812
-				} else {
5813
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5814
-				}
5815
-			}
5816
-		}
5817
-		elseif ($type == 'link')
5818
-		{
5819
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5820
-			$showempty=(($required && $default != '')?0:1);
5821
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5822
-			if (Globals::$conf->global->MAIN_FEATURES_LEVEL >= 2) {
5823
-            			list($class,$classfile)=explode(':',$param_list[0]);
5824
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5825
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5826
-            			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5827
-            			// TODO Add Javascript code to add input fields contents to new elements urls
5828
-			}
5829
-		}
5830
-		elseif ($type == 'password')
5831
-		{
5832
-			// If prefix is 'search_', field is used as a filter, we use a common text field.
5833
-			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5834
-		}
5835
-		elseif ($type == 'array')
5836
-		{
5837
-			$newval = $val;
5838
-			$newval['type'] = 'varchar(256)';
5839
-
5840
-			$out='';
5841
-
5842
-			$inputs = array();
5843
-			if(! empty($value)) {
5844
-				foreach($value as $option) {
5845
-					$out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5846
-					$out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5847
-				}
5848
-			}
2099
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2100
+        $sql.= " SET model_pdf = '".$this->db->escape($newmodelpdf)."'";
2101
+        $sql.= " WHERE rowid = ".$this->id;
2102
+        // if ($this->element == 'facture') $sql.= " AND fk_statut < 2";
2103
+        // if ($this->element == 'propal')  $sql.= " AND fk_statut = 0";
5849 2104
 
5850
-			$out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
2105
+        dol_syslog(get_class($this)."::setDocModel", LOG_DEBUG);
2106
+        $resql=$this->db->query($sql);
2107
+        if ($resql)
2108
+        {
2109
+            $this->modelpdf=$modelpdf;
2110
+            return 1;
2111
+        }
2112
+        else
2113
+        {
2114
+            dol_print_error($this->db);
2115
+            return 0;
2116
+        }
2117
+    }
5851 2118
 
5852
-			$newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5853
-			$newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5854 2119
 
5855
-			if (!empty(Globals::$conf->use_javascript_ajax)) {
5856
-                $out.= '
5857
-					<script type="text/javascript">
5858
-					$(document).ready(function() {
5859
-						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
5860
-							$("'.dol_escape_js($newInput).'").insertBefore(this);
5861
-						});
2120
+    /**
2121
+     *  Change the bank account
2122
+     *
2123
+     *  @param		int		$fk_account		Id of bank account
2124
+     *  @param      bool    $notrigger      false=launch triggers after, true=disable triggers
2125
+     *  @param      User	$userused		Object user
2126
+     *  @return		int				1 if OK, 0 if KO
2127
+     */
2128
+    function setBankAccount($fk_account, $notrigger=false, $userused=null)
2129
+    {
2130
+        global $user;
5862 2131
 
5863
-						$(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
5864
-							$(this).parent().remove();
5865
-						});
5866
-					});
5867
-					</script>';
5868
-			}
5869
-		}
5870
-		if (!empty($hidden)) {
5871
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5872
-		}
5873
-		/* Add comments
5874
-		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
5875
-		 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
5876
-		 */
5877
-		return $out;
5878
-	}
5879
-
5880
-	/**
5881
-	 * Return HTML string to show a field into a page
5882
-	 * Code very similar with showOutputField of extra fields
5883
-	 *
5884
-	 * @param  array   $val		       Array of properties of field to show
5885
-	 * @param  string  $key            Key of attribute
5886
-	 * @param  string  $value          Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
5887
-	 * @param  string  $moreparam      To add more parametes on html input tag
5888
-	 * @param  string  $keysuffix      Prefix string to add into name and id of field (can be used to avoid duplicate names)
5889
-	 * @param  string  $keyprefix      Suffix string to add into name and id of field (can be used to avoid duplicate names)
5890
-	 * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5891
-	 * @return string
5892
-	 */
5893
-	function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5894
-	{
5895
-		global $conf,$langs,$form;
5896
-
5897
-		if (! is_object($form))
5898
-		{
5899
-			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5900
-			$form=new Form($this->db);
5901
-		}
5902
-
5903
-		$objectid = $this->id;
5904
-		$label = $val['label'];
5905
-		$type  = $val['type'];
5906
-		$size  = $val['css'];
5907
-
5908
-		// Convert var to be able to share same code than showOutputField of extrafields
5909
-		if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5910
-		{
5911
-			$type = 'varchar';		// convert varchar(xx) int varchar
5912
-			$size = $reg[1];
5913
-		}
5914
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5915
-		if (is_array($val['arrayofkeyval'])) $type='select';
5916
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5917
-
5918
-		$default=$val['default'];
5919
-		$computed=$val['computed'];
5920
-		$unique=$val['unique'];
5921
-		$required=$val['required'];
5922
-		$param=$val['param'];
5923
-		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5924
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5925
-		{
5926
-			$type='link';
5927
-			$param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5928
-		}
5929
-		$langfile=$val['langfile'];
5930
-		$list=$val['list'];
5931
-		$help=$val['help'];
5932
-		$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)
5933
-
5934
-		if ($hidden) return '';
5935
-
5936
-		// If field is a computed field, value must become result of compute
5937
-		if ($computed)
5938
-		{
5939
-			// Make the eval of compute string
5940
-			//var_dump($computed);
5941
-			$value = dol_eval($computed, 1, 0);
5942
-		}
5943
-
5944
-		if (empty($showsize))
5945
-		{
5946
-			if ($type == 'date')
5947
-			{
5948
-				//$showsize=10;
5949
-				$showsize = 'minwidth100imp';
5950
-			}
5951
-			elseif ($type == 'datetime')
5952
-			{
5953
-				//$showsize=19;
5954
-				$showsize = 'minwidth200imp';
5955
-			}
5956
-			elseif (in_array($type,array('int','double','price')))
5957
-			{
5958
-				//$showsize=10;
5959
-				$showsize = 'maxwidth75';
5960
-			}
5961
-			elseif ($type == 'url')
5962
-			{
5963
-				$showsize='minwidth400';
5964
-			}
5965
-			elseif ($type == 'boolean')
5966
-			{
5967
-				$showsize='';
5968
-			}
5969
-			else
5970
-			{
5971
-				if (round($size) < 12)
5972
-				{
5973
-					$showsize = 'minwidth100';
5974
-				}
5975
-				else if (round($size) <= 48)
5976
-				{
5977
-					$showsize = 'minwidth200';
5978
-				}
5979
-				else
5980
-				{
5981
-					//$showsize=48;
5982
-					$showsize = 'minwidth400';
5983
-				}
5984
-			}
5985
-		}
5986
-
5987
-		// Format output value differently according to properties of field
5988
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5989
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5990
-		elseif ($type == 'date')
5991
-		{
5992
-			if(! empty($value)) {
5993
-				$value=dol_print_date($value,'day');
5994
-			} else {
5995
-				$value='';
5996
-			}
5997
-		}
5998
-		elseif ($type == 'datetime')
5999
-		{
6000
-			if(! empty($value)) {
6001
-				$value=dol_print_date($value,'dayhour');
6002
-			} else {
6003
-				$value='';
6004
-			}
6005
-		}
6006
-		elseif ($type == 'double')
6007
-		{
6008
-			if (!empty($value)) {
6009
-				$value=price($value);
6010
-			}
6011
-		}
6012
-		elseif ($type == 'boolean')
6013
-		{
6014
-			$checked='';
6015
-			if (!empty($value)) {
6016
-				$checked=' checked ';
6017
-			}
6018
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6019
-		}
6020
-		elseif ($type == 'mail')
6021
-		{
6022
-			$value=dol_print_email($value,0,0,0,64,1,1);
6023
-		}
6024
-		elseif ($type == 'url')
6025
-		{
6026
-			$value=dol_print_url($value,'_blank',32,1);
6027
-		}
6028
-		elseif ($type == 'phone')
6029
-		{
6030
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6031
-		}
6032
-		elseif ($type == 'price')
6033
-		{
6034
-			$value = price($value, 0, $langs, 0, 0, -1, Globals::$conf->currency);
6035
-        }
6036
-		elseif ($type == 'select')
6037
-		{
6038
-			$value=$param['options'][$value];
6039
-		}
6040
-		elseif ($type == 'sellist')
6041
-		{
6042
-			$param_list=array_keys($param['options']);
6043
-			$InfoFieldList = explode(":", $param_list[0]);
6044
-
6045
-			$selectkey="rowid";
6046
-			$keyList='rowid';
6047
-
6048
-			if (count($InfoFieldList)>=3)
6049
-			{
6050
-				$selectkey = $InfoFieldList[2];
6051
-				$keyList=$InfoFieldList[2].' as rowid';
6052
-			}
6053
-
6054
-			$fields_label = explode('|',$InfoFieldList[1]);
6055
-			if(is_array($fields_label)) {
6056
-				$keyList .=', ';
6057
-				$keyList .= implode(', ', $fields_label);
6058
-			}
6059
-
6060
-			$sql = 'SELECT '.$keyList;
6061
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6062
-			if (strpos($InfoFieldList[4], 'extra')!==false)
6063
-			{
6064
-				$sql.= ' as main';
6065
-			}
6066
-			if ($selectkey=='rowid' && empty($value)) {
6067
-				$sql.= " WHERE ".$selectkey."=0";
6068
-			} elseif ($selectkey=='rowid') {
6069
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6070
-			}else {
6071
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6072
-			}
6073
-
6074
-			//$sql.= ' AND entity = '.Globals::$conf->entity;
2132
+        if (empty($userused)) $userused=$user;
6075 2133
 
6076
-            dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
6077
-			$resql = $this->db->query($sql);
6078
-			if ($resql)
6079
-			{
6080
-				$value='';	// value was used, so now we reste it to use it to build final output
2134
+        $error = 0;
6081 2135
 
6082
-				$obj = $this->db->fetch_object($resql);
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
+            return -1;
2139
+        }
2140
+        $this->db->begin();
6083 2141
 
6084
-				// Several field into label (eq table:code|libelle:rowid)
6085
-				$fields_label = explode('|',$InfoFieldList[1]);
2142
+        if ($fk_account<0) $fk_account='NULL';
2143
+        dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
6086 2144
 
6087
-				if(is_array($fields_label) && count($fields_label)>1)
6088
-				{
6089
-					foreach ($fields_label as $field_toshow)
6090
-					{
6091
-						$translabel='';
6092
-						if (!empty($obj->$field_toshow)) {
6093
-							$translabel=$langs->trans($obj->$field_toshow);
6094
-						}
6095
-						if ($translabel!=$field_toshow) {
6096
-							$value.=dol_trunc($translabel,18).' ';
6097
-						}else {
6098
-							$value.=$obj->$field_toshow.' ';
2145
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2146
+        $sql.= " SET fk_account = ".$fk_account;
2147
+        $sql.= " WHERE rowid=".$this->id;
2148
+
2149
+        $resql = $this->db->query($sql);
2150
+        if (! $resql)
2151
+        {
2152
+            dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153
+            $this->error = $this->db->lasterror();
2154
+            $error++;
2155
+        }
2156
+        else
2157
+        {
2158
+            if (!$notrigger)
2159
+            {
2160
+                // Call trigger
2161
+                $this->context=array('bankaccountupdate'=>1);
2162
+                $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2163
+                if ($result < 0) $error++;
2164
+                // End call trigger
2165
+            }
2166
+        }
2167
+        if ($error)
2168
+        {
2169
+            $this->db->rollback();
2170
+            return -1;
2171
+        }
2172
+        else
2173
+        {
2174
+            $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2175
+            $this->db->commit();
2176
+            return 1;
2177
+        }
2178
+    }
2179
+
2180
+
2181
+    // TODO: Move line related operations to CommonObjectLine?
2182
+
2183
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2184
+    /**
2185
+     *  Save a new position (field rang) for details lines.
2186
+     *  You can choose to set position for lines with already a position or lines without any position defined.
2187
+     *
2188
+     * 	@param		boolean		$renum			   True to renum all already ordered lines, false to renum only not already ordered lines.
2189
+     * 	@param		string		$rowidorder		   ASC or DESC
2190
+     * 	@param		boolean		$fk_parent_line    Table with fk_parent_line field or not
2191
+     * 	@return		int                            <0 if KO, >0 if OK
2192
+     */
2193
+    function line_order($renum=false, $rowidorder='ASC', $fk_parent_line=true)
2194
+    {
2195
+        // phpcs:enable
2196
+        if (! $this->table_element_line)
2197
+        {
2198
+            dol_syslog(get_class($this)."::line_order was called on objet with property table_element_line not defined",LOG_ERR);
2199
+            return -1;
2200
+        }
2201
+        if (! $this->fk_element)
2202
+        {
2203
+            dol_syslog(get_class($this)."::line_order was called on objet with property fk_element not defined",LOG_ERR);
2204
+            return -1;
2205
+        }
2206
+
2207
+        // Count number of lines to reorder (according to choice $renum)
2208
+        $nl=0;
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';
2213
+
2214
+        dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
2215
+        $resql = $this->db->query($sql);
2216
+        if ($resql)
2217
+        {
2218
+            $row = $this->db->fetch_row($resql);
2219
+            $nl = $row[0];
2220
+        }
2221
+        else dol_print_error($this->db);
2222
+        if ($nl > 0)
2223
+        {
2224
+            // The goal of this part is to reorder all lines, with all children lines sharing the same
2225
+            // counter that parents.
2226
+            $rows=array();
2227
+
2228
+            // We first search all lines that are parent lines (for multilevel details lines)
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;
2233
+
2234
+            dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
2235
+            $resql = $this->db->query($sql);
2236
+            if ($resql)
2237
+            {
2238
+                $i=0;
2239
+                $num = $this->db->num_rows($resql);
2240
+                while ($i < $num)
2241
+                {
2242
+                    $row = $this->db->fetch_row($resql);
2243
+                    $rows[] = $row[0];	// Add parent line into array rows
2244
+                    $childrens = $this->getChildrenOfLine($row[0]);
2245
+                    if (! empty($childrens))
2246
+                    {
2247
+                        foreach($childrens as $child)
2248
+                        {
2249
+                            array_push($rows, $child);
2250
+                        }
2251
+                    }
2252
+                    $i++;
2253
+                }
2254
+
2255
+                // Now we set a new number for each lines (parent and children with children included into parent tree)
2256
+                if (! empty($rows))
2257
+                {
2258
+                    foreach($rows as $key => $row)
2259
+                    {
2260
+                        $this->updateRangOfLine($row, ($key+1));
2261
+                    }
2262
+                }
2263
+            }
2264
+            else
2265
+            {
2266
+                dol_print_error($this->db);
2267
+            }
2268
+        }
2269
+        return 1;
2270
+    }
2271
+
2272
+    /**
2273
+     * 	Get children of line
2274
+     *
2275
+     * 	@param	int		$id		Id of parent line
2276
+     * 	@return	array			Array with list of children lines id
2277
+     */
2278
+    function getChildrenOfLine($id)
2279
+    {
2280
+        $rows=array();
2281
+
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';
2286
+
2287
+        dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id."", LOG_DEBUG);
2288
+        $resql = $this->db->query($sql);
2289
+        if ($resql)
2290
+        {
2291
+            $i=0;
2292
+            $num = $this->db->num_rows($resql);
2293
+            while ($i < $num)
2294
+            {
2295
+                $row = $this->db->fetch_row($resql);
2296
+                $rows[$i] = $row[0];
2297
+                $i++;
2298
+            }
2299
+        }
2300
+
2301
+        return $rows;
2302
+    }
2303
+
2304
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2305
+    /**
2306
+     * 	Update a line to have a lower rank
2307
+     *
2308
+     * 	@param 	int			$rowid				Id of line
2309
+     * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2310
+     * 	@return	void
2311
+     */
2312
+    function line_up($rowid, $fk_parent_line=true)
2313
+    {
2314
+        // phpcs:enable
2315
+        $this->line_order(false, 'ASC', $fk_parent_line);
2316
+
2317
+        // Get rang of line
2318
+        $rang = $this->getRangOfLine($rowid);
2319
+
2320
+        // Update position of line
2321
+        $this->updateLineUp($rowid, $rang);
2322
+    }
2323
+
2324
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2325
+    /**
2326
+     * 	Update a line to have a higher rank
2327
+     *
2328
+     * 	@param	int			$rowid				Id of line
2329
+     * 	@param	boolean		$fk_parent_line		Table with fk_parent_line field or not
2330
+     * 	@return	void
2331
+     */
2332
+    function line_down($rowid, $fk_parent_line=true)
2333
+    {
2334
+        // phpcs:enable
2335
+        $this->line_order(false, 'ASC', $fk_parent_line);
2336
+
2337
+        // Get rang of line
2338
+        $rang = $this->getRangOfLine($rowid);
2339
+
2340
+        // Get max value for rang
2341
+        $max = $this->line_max();
2342
+
2343
+        // Update position of line
2344
+        $this->updateLineDown($rowid, $rang, $max);
2345
+    }
2346
+
2347
+    /**
2348
+     * 	Update position of line (rang)
2349
+     *
2350
+     * 	@param	int		$rowid		Id of line
2351
+     * 	@param	int		$rang		Position
2352
+     * 	@return	void
2353
+     */
2354
+    function updateRangOfLine($rowid,$rang)
2355
+    {
2356
+        $fieldposition = 'rang';
2357
+        if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2358
+
2359
+        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2360
+        $sql.= ' WHERE rowid = '.$rowid;
2361
+
2362
+        dol_syslog(get_class($this)."::updateRangOfLine", LOG_DEBUG);
2363
+        if (! $this->db->query($sql))
2364
+        {
2365
+            dol_print_error($this->db);
2366
+        }
2367
+    }
2368
+
2369
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2370
+    /**
2371
+     * 	Update position of line with ajax (rang)
2372
+     *
2373
+     * 	@param	array	$rows	Array of rows
2374
+     * 	@return	void
2375
+     */
2376
+    function line_ajaxorder($rows)
2377
+    {
2378
+        // phpcs:enable
2379
+        $num = count($rows);
2380
+        for ($i = 0 ; $i < $num ; $i++)
2381
+        {
2382
+            $this->updateRangOfLine($rows[$i], ($i+1));
2383
+        }
2384
+    }
2385
+
2386
+    /**
2387
+     * 	Update position of line up (rang)
2388
+     *
2389
+     * 	@param	int		$rowid		Id of line
2390
+     * 	@param	int		$rang		Position
2391
+     * 	@return	void
2392
+     */
2393
+    function updateLineUp($rowid,$rang)
2394
+    {
2395
+        if ($rang > 1)
2396
+        {
2397
+            $fieldposition = 'rang';
2398
+            if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
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) )
2404
+            {
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) )
2408
+                {
2409
+                    dol_print_error($this->db);
2410
+                }
2411
+            }
2412
+            else
2413
+            {
2414
+                dol_print_error($this->db);
2415
+            }
2416
+        }
2417
+    }
2418
+
2419
+    /**
2420
+     * 	Update position of line down (rang)
2421
+     *
2422
+     * 	@param	int		$rowid		Id of line
2423
+     * 	@param	int		$rang		Position
2424
+     * 	@param	int		$max		Max
2425
+     * 	@return	void
2426
+     */
2427
+    function updateLineDown($rowid,$rang,$max)
2428
+    {
2429
+        if ($rang < $max)
2430
+        {
2431
+            $fieldposition = 'rang';
2432
+            if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2433
+
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) )
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) )
2442
+                {
2443
+                    dol_print_error($this->db);
2444
+                }
2445
+            }
2446
+            else
2447
+            {
2448
+                dol_print_error($this->db);
2449
+            }
2450
+        }
2451
+    }
2452
+
2453
+    /**
2454
+     * 	Get position of line (rang)
2455
+     *
2456
+     * 	@param		int		$rowid		Id of line
2457
+     *  @return		int     			Value of rang in table of lines
2458
+     */
2459
+    function getRangOfLine($rowid)
2460
+    {
2461
+        $sql = 'SELECT rang FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2462
+        $sql.= ' WHERE rowid ='.$rowid;
2463
+
2464
+        dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
2465
+        $resql = $this->db->query($sql);
2466
+        if ($resql)
2467
+        {
2468
+            $row = $this->db->fetch_row($resql);
2469
+            return $row[0];
2470
+        }
2471
+    }
2472
+
2473
+    /**
2474
+     * 	Get rowid of the line relative to its position
2475
+     *
2476
+     * 	@param		int		$rang		Rang value
2477
+     *  @return     int     			Rowid of the line
2478
+     */
2479
+    function getIdOfLine($rang)
2480
+    {
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;
2484
+        $resql = $this->db->query($sql);
2485
+        if ($resql)
2486
+        {
2487
+            $row = $this->db->fetch_row($resql);
2488
+            return $row[0];
2489
+        }
2490
+    }
2491
+
2492
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2493
+    /**
2494
+     * 	Get max value used for position of line (rang)
2495
+     *
2496
+     * 	@param		int		$fk_parent_line		Parent line id
2497
+     *  @return     int  			   			Max value of rang in table of lines
2498
+     */
2499
+    function line_max($fk_parent_line=0)
2500
+    {
2501
+        // phpcs:enable
2502
+        // Search the last rang with fk_parent_line
2503
+        if ($fk_parent_line)
2504
+        {
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;
2508
+
2509
+            dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2510
+            $resql = $this->db->query($sql);
2511
+            if ($resql)
2512
+            {
2513
+                $row = $this->db->fetch_row($resql);
2514
+                if (! empty($row[0]))
2515
+                {
2516
+                    return $row[0];
2517
+                }
2518
+                else
2519
+                {
2520
+                    return $this->getRangOfLine($fk_parent_line);
2521
+                }
2522
+            }
2523
+        }
2524
+        // If not, search the last rang of element
2525
+        else
2526
+        {
2527
+            $sql = 'SELECT max(rang) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2528
+            $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2529
+
2530
+            dol_syslog(get_class($this)."::line_max", LOG_DEBUG);
2531
+            $resql = $this->db->query($sql);
2532
+            if ($resql)
2533
+            {
2534
+                $row = $this->db->fetch_row($resql);
2535
+                return $row[0];
2536
+            }
2537
+        }
2538
+    }
2539
+
2540
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2541
+    /**
2542
+     *  Update external ref of element
2543
+     *
2544
+     *  @param      string		$ref_ext	Update field ref_ext
2545
+     *  @return     int      		   		<0 if KO, >0 if OK
2546
+     */
2547
+    function update_ref_ext($ref_ext)
2548
+    {
2549
+        // phpcs:enable
2550
+        if (! $this->table_element)
2551
+        {
2552
+            dol_syslog(get_class($this)."::update_ref_ext was called on objet with property table_element not defined", LOG_ERR);
2553
+            return -1;
2554
+        }
2555
+
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;
2559
+
2560
+        dol_syslog(get_class($this)."::update_ref_ext", LOG_DEBUG);
2561
+        if ($this->db->query($sql))
2562
+        {
2563
+            $this->ref_ext = $ref_ext;
2564
+            return 1;
2565
+        }
2566
+        else
2567
+        {
2568
+            $this->error=$this->db->error();
2569
+            return -1;
2570
+        }
2571
+    }
2572
+
2573
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2574
+    /**
2575
+     *  Update note of element
2576
+     *
2577
+     *  @param      string		$note		New value for note
2578
+     *  @param		string		$suffix		'', '_public' or '_private'
2579
+     *  @return     int      		   		<0 if KO, >0 if OK
2580
+     */
2581
+    function update_note($note, $suffix='')
2582
+    {
2583
+        // phpcs:enable
2584
+        global $user;
2585
+
2586
+        if (! $this->table_element)
2587
+        {
2588
+            $this->error='update_note was called on objet with property table_element not defined';
2589
+            dol_syslog(get_class($this)."::update_note was called on objet with property table_element not defined", LOG_ERR);
2590
+            return -1;
2591
+        }
2592
+        if (! in_array($suffix,array('','_public','_private')))
2593
+        {
2594
+            $this->error='update_note Parameter suffix must be empty, \'_private\' or \'_public\'';
2595
+            dol_syslog(get_class($this)."::update_note Parameter suffix must be empty, '_private' or '_public'", LOG_ERR);
2596
+            return -2;
2597
+        }
2598
+        // Special cas
2599
+        //var_dump($this->table_element);exit;
2600
+        if ($this->table_element == 'product') $suffix='';
2601
+
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;
2606
+
2607
+        dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
2608
+        if ($this->db->query($sql))
2609
+        {
2610
+            if ($suffix == '_public') $this->note_public = $note;
2611
+            else if ($suffix == '_private') $this->note_private = $note;
2612
+            else
2613
+            {
2614
+                $this->note = $note;      // deprecated
2615
+                $this->note_private = $note;
2616
+            }
2617
+            return 1;
2618
+        }
2619
+        else
2620
+        {
2621
+            $this->error=$this->db->lasterror();
2622
+            return -1;
2623
+        }
2624
+    }
2625
+
2626
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2627
+    /**
2628
+     * 	Update public note (kept for backward compatibility)
2629
+     *
2630
+     * @param      string		$note		New value for note
2631
+     * @return     int      		   		<0 if KO, >0 if OK
2632
+     * @deprecated
2633
+     * @see update_note()
2634
+     */
2635
+    function update_note_public($note)
2636
+    {
2637
+        // phpcs:enable
2638
+        return $this->update_note($note,'_public');
2639
+    }
2640
+
2641
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2642
+    /**
2643
+     *	Update total_ht, total_ttc, total_vat, total_localtax1, total_localtax2 for an object (sum of lines).
2644
+     *  Must be called at end of methods addline or updateline.
2645
+     *
2646
+     *	@param	int		$exclspec          	>0 = Exclude special product (product_type=9)
2647
+     *  @param  string	$roundingadjust    	'none'=Do nothing, 'auto'=Use default method (MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND if defined, or '0'), '0'=Force mode total of rounding, '1'=Force mode rounding of total
2648
+     *  @param	int		$nodatabaseupdate	1=Do not update database. Update only properties of object.
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
+     *	@return	int    			           	<0 if KO, >0 if OK
2651
+     */
2652
+    function update_price($exclspec=0,$roundingadjust='none',$nodatabaseupdate=0,$seller=null)
2653
+    {
2654
+        // phpcs:enable
2655
+        global $conf, $hookmanager, $action;
2656
+
2657
+        // Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
2658
+        $MODULE = "";
2659
+        if ($this->element == 'propal')
2660
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
2661
+        elseif ($this->element == 'order')
2662
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
2663
+        elseif ($this->element == 'facture')
2664
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
2665
+        elseif ($this->element == 'facture_fourn')
2666
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
2667
+        elseif ($this->element == 'order_supplier')
2668
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
2669
+        elseif ($this->element == 'supplier_proposal')
2670
+            $MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2671
+
2672
+        if (! empty($MODULE)) {
2673
+            if (!empty(Globals::$conf->global->$MODULE)) {
2674
+                $modsactivated = explode(',', Globals::$conf->global->$MODULE);
2675
+                foreach ($modsactivated as $mod) {
2676
+                    if (Globals::$conf->$mod->enabled)
2677
+                        return 1; // update was disabled by specific setup
2678
+                }
2679
+            }
2680
+        }
2681
+
2682
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2683
+
2684
+        if ($roundingadjust == '-1') $roundingadjust='auto';	// For backward compatibility
2685
+
2686
+        $forcedroundingmode=$roundingadjust;
2687
+        if ($forcedroundingmode == 'auto' && isset(Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND))
2688
+            $forcedroundingmode = Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2689
+        elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2690
+
2691
+        $error=0;
2692
+
2693
+        $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2694
+
2695
+        // Define constants to find lines to sum
2696
+        $fieldtva='total_tva';
2697
+        $fieldlocaltax1='total_localtax1';
2698
+        $fieldlocaltax2='total_localtax2';
2699
+        $fieldup='subprice';
2700
+        if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2701
+        {
2702
+            $fieldtva='tva';
2703
+            $fieldup='pu_ht';
2704
+        }
2705
+        if ($this->element == 'expensereport')
2706
+        {
2707
+            $fieldup='value_unit';
2708
+        }
2709
+
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;
2716
+        if ($exclspec)
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';
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
2723
+
2724
+        dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2725
+        $resql = $this->db->query($sql);
2726
+        if ($resql)
2727
+        {
2728
+            $this->total_ht  = 0;
2729
+            $this->total_tva = 0;
2730
+            $this->total_localtax1 = 0;
2731
+            $this->total_localtax2 = 0;
2732
+            $this->total_ttc = 0;
2733
+            $total_ht_by_vats  = array();
2734
+            $total_tva_by_vats = array();
2735
+            $total_ttc_by_vats = array();
2736
+            $this->multicurrency_total_ht	= 0;
2737
+            $this->multicurrency_total_tva	= 0;
2738
+            $this->multicurrency_total_ttc	= 0;
2739
+
2740
+            $num = $this->db->num_rows($resql);
2741
+            $i = 0;
2742
+            while ($i < $num)
2743
+            {
2744
+                $obj = $this->db->fetch_object($resql);
2745
+
2746
+                // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2747
+                $parameters=array('fk_element' => $obj->rowid);
2748
+                $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2749
+
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
+                {
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
+                    if ($diff)
2756
+                    {
2757
+                        $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
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');
2761
+                                $obj->total_tva = $tmpcal[1];
2762
+                                $obj->total_ttc = $tmpcal[2];
2763
+                        //
2764
+                    }
2765
+                }
2766
+
2767
+                $this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2768
+                $this->total_tva       += $obj->total_tva;
2769
+                $this->total_localtax1 += $obj->total_localtax1;
2770
+                $this->total_localtax2 += $obj->total_localtax2;
2771
+                $this->total_ttc       += $obj->total_ttc;
2772
+                $this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2773
+                $this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2774
+                $this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
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;
2779
+                $total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2780
+                $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2781
+                $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2782
+
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
+                {
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
+                    //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
+                    if ($diff)
2789
+                    {
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;
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');
2795
+                                $this->total_tva -= $diff;
2796
+                                $this->total_ttc -= $diff;
2797
+                                $total_tva_by_vats[$obj->vatrate] -= $diff;
2798
+                                $total_ttc_by_vats[$obj->vatrate] -= $diff;
2799
+                    }
2800
+                }
2801
+
2802
+                $i++;
2803
+            }
2804
+
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;
2808
+
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 )
2811
+            {
2812
+                $prev_sits = $this->get_prev_sits();
2813
+
2814
+                foreach ($prev_sits as $sit) {				// $sit is an object Facture loaded with a fetch.
2815
+                    $this->total_ht -= $sit->total_ht;
2816
+                    $this->total_tva -= $sit->total_tva;
2817
+                    $this->total_localtax1 -= $sit->total_localtax1;
2818
+                    $this->total_localtax2 -= $sit->total_localtax2;
2819
+                    $this->total_ttc -= $sit->total_ttc;
2820
+                    $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
2821
+                    $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
2822
+                    $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
2823
+                }
2824
+            }
2825
+
2826
+            $this->db->free($resql);
2827
+
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';
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';
2840
+
2841
+            if (empty($nodatabaseupdate))
2842
+            {
2843
+                $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
2844
+                $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
2845
+                $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
2846
+                $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
2847
+                $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
2848
+                $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
2849
+                        $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
2850
+                        $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
2851
+                        $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
2852
+                $sql .= ' WHERE rowid = '.$this->id;
2853
+
2854
+
2855
+                dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2856
+                $resql=$this->db->query($sql);
2857
+                if (! $resql)
2858
+                {
2859
+                    $error++;
2860
+                    $this->error=$this->db->lasterror();
2861
+                    $this->errors[]=$this->db->lasterror();
2862
+                }
2863
+            }
2864
+
2865
+            if (! $error)
2866
+            {
2867
+                return 1;
2868
+            }
2869
+            else
2870
+            {
2871
+                return -1;
2872
+            }
2873
+        }
2874
+        else
2875
+        {
2876
+            dol_print_error($this->db,'Bad request in update_price');
2877
+            return -1;
2878
+        }
2879
+    }
2880
+
2881
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2882
+    /**
2883
+     *	Add objects linked in llx_element_element.
2884
+     *
2885
+     *	@param		string	$origin		Linked element type
2886
+     *	@param		int		$origin_id	Linked element id
2887
+     *	@return		int					<=0 if KO, >0 if OK
2888
+     *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2889
+     */
2890
+    function add_object_linked($origin=null, $origin_id=null)
2891
+    {
2892
+        // phpcs:enable
2893
+        $origin = (! empty($origin) ? $origin : $this->origin);
2894
+        $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2895
+
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';
2901
+        $this->db->begin();
2902
+
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.= ")";
2914
+
2915
+        dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2916
+        if ($this->db->query($sql))
2917
+            {
2918
+                $this->db->commit();
2919
+                return 1;
2920
+            }
2921
+            else
2922
+            {
2923
+                $this->error=$this->db->lasterror();
2924
+                $this->db->rollback();
2925
+                return 0;
2926
+            }
2927
+    }
2928
+
2929
+    /**
2930
+     *	Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
2931
+     *		this->linkedObjectsIds array and
2932
+     *		this->linkedObjects array if $loadalsoobjects = 1
2933
+     *  Possible usage for parameters:
2934
+     *  - all parameters empty -> we look all link to current object (current object can be source or target)
2935
+     *  - source id+type -> will get target list linked to source
2936
+     *  - target id+type -> will get source list linked to target
2937
+     *  - source id+type + target type -> will get target list of the type
2938
+     *  - target id+type + target source -> will get source list of the type
2939
+     *
2940
+     *	@param	int		$sourceid			Object source id (if not defined, id of object)
2941
+     *	@param  string	$sourcetype			Object source type (if not defined, element name of object)
2942
+     *	@param  int		$targetid			Object target id (if not defined, id of object)
2943
+     *	@param  string	$targettype			Object target type (if not defined, elemennt name of object)
2944
+     *	@param  string	$clause				'OR' or 'AND' clause used when both source id and target id are provided
2945
+     *  @param  int		$alsosametype		0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
2946
+     *  @param  string	$orderby			SQL 'ORDER BY' clause
2947
+     *  @param	int		$loadalsoobjects	Load also array this->linkedObjects (Use 0 to increase performances)
2948
+     *	@return int							<0 if KO, >0 if OK
2949
+     *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2950
+     */
2951
+    function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2952
+    {
2953
+        global $conf;
2954
+
2955
+        $this->linkedObjectsIds=array();
2956
+        $this->linkedObjects=array();
2957
+
2958
+        $justsource=false;
2959
+        $justtarget=false;
2960
+        $withtargettype=false;
2961
+        $withsourcetype=false;
2962
+
2963
+        if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2964
+        {
2965
+            $justsource=true;  // the source (id and type) is a search criteria
2966
+            if (! empty($targettype)) $withtargettype=true;
2967
+        }
2968
+        if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2969
+        {
2970
+            $justtarget=true;  // the target (id and type) is a search criteria
2971
+            if (! empty($sourcetype)) $withsourcetype=true;
2972
+        }
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);
2978
+
2979
+        /*if (empty($sourceid) && empty($targetid))
2980
+		 {
2981
+		 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
2982
+		 return -1;
2983
+		 }*/
2984
+
2985
+        // Links between objects are stored in table element_element
2986
+        $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2987
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2988
+        $sql.= " WHERE ";
2989
+        if ($justsource || $justtarget)
2990
+        {
2991
+            if ($justsource)
2992
+            {
2993
+                $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2994
+                if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2995
+            }
2996
+            else if ($justtarget)
2997
+            {
2998
+                $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2999
+                if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
3000
+            }
3001
+        }
3002
+        else
3003
+        {
3004
+            $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3005
+            $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3006
+        }
3007
+        $sql .= ' ORDER BY '.$orderby;
3008
+
3009
+        dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3010
+        $resql = $this->db->query($sql);
3011
+        if ($resql)
3012
+        {
3013
+            $num = $this->db->num_rows($resql);
3014
+            $i = 0;
3015
+            while ($i < $num)
3016
+            {
3017
+                $obj = $this->db->fetch_object($resql);
3018
+                if ($justsource || $justtarget)
3019
+                {
3020
+                    if ($justsource)
3021
+                    {
3022
+                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3023
+                    }
3024
+                    else if ($justtarget)
3025
+                    {
3026
+                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3027
+                    }
3028
+                }
3029
+                else
3030
+                {
3031
+                    if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3032
+                    {
3033
+                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3034
+                    }
3035
+                    if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3036
+                    {
3037
+                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3038
+                    }
3039
+                }
3040
+                $i++;
3041
+            }
3042
+
3043
+            if (! empty($this->linkedObjectsIds))
3044
+            {
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', ...)
3047
+                {
3048
+                    // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3049
+                    $module = $element = $subelement = $objecttype;
3050
+                    if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3051
+                        && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3052
+                    {
3053
+                        $module = $element = $regs[1];
3054
+                        $subelement = $regs[2];
3055
+                    }
3056
+
3057
+                    $classpath = $element.'/class';
3058
+                    // To work with non standard classpath or module name
3059
+                    if ($objecttype == 'facture')			{
3060
+                        $classpath = 'compta/facture/class';
3061
+                    }
3062
+                    else if ($objecttype == 'facturerec')			{
3063
+                        $classpath = 'compta/facture/class'; $module = 'facture';
3064
+                    }
3065
+                    else if ($objecttype == 'propal')			{
3066
+                        $classpath = 'comm/propal/class';
3067
+                    }
3068
+                    else if ($objecttype == 'supplier_proposal')			{
3069
+                        $classpath = 'supplier_proposal/class';
3070
+                    }
3071
+                    else if ($objecttype == 'shipping')			{
3072
+                        $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3073
+                    }
3074
+                    else if ($objecttype == 'delivery')			{
3075
+                        $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3076
+                    }
3077
+                    else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3078
+                        $classpath = 'fourn/class'; $module = 'fournisseur';
3079
+                    }
3080
+                    else if ($objecttype == 'fichinter')			{
3081
+                        $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3082
+                    }
3083
+                    else if ($objecttype == 'subscription')			{
3084
+                        $classpath = 'adherents/class'; $module = 'adherent';
3085
+                    }
3086
+
3087
+                    // Set classfile
3088
+                    $classfile = strtolower($subelement); $classname = ucfirst($subelement);
3089
+
3090
+                    if ($objecttype == 'order') {
3091
+                        $classfile = 'commande'; $classname = 'Commande';
3092
+                    }
3093
+                    else if ($objecttype == 'invoice_supplier') {
3094
+                        $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3095
+                    }
3096
+                    else if ($objecttype == 'order_supplier')   {
3097
+                        $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3098
+                    }
3099
+                    else if ($objecttype == 'supplier_proposal')   {
3100
+                        $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3101
+                    }
3102
+                    else if ($objecttype == 'facturerec')   {
3103
+                        $classfile = 'facture-rec'; $classname = 'FactureRec';
3104
+                    }
3105
+                    else if ($objecttype == 'subscription')   {
3106
+                        $classfile = 'subscription'; $classname = 'Subscription';
3107
+                    }
3108
+
3109
+                    // Here $module, $classfile and $classname are set
3110
+                    if (Globals::$conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
3111
+                        if ($loadalsoobjects)
3112
+                        {
3113
+                            dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
3114
+                            //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
3115
+                            if (class_exists($classname))
3116
+                            {
3117
+                                foreach($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3118
+                                {
3119
+                                    $object = new $classname($this->db);
3120
+                                    $ret = $object->fetch($objectid);
3121
+                                    if ($ret >= 0)
3122
+                                    {
3123
+                                        $this->linkedObjects[$objecttype][$i] = $object;
3124
+                                    }
3125
+                                }
3126
+                            }
3127
+                        }
3128
+                    }
3129
+                    else
3130
+                    {
3131
+                        unset($this->linkedObjectsIds[$objecttype]);
3132
+                    }
3133
+                }
3134
+            }
3135
+            return 1;
3136
+        }
3137
+        else
3138
+        {
3139
+            dol_print_error($this->db);
3140
+            return -1;
3141
+        }
3142
+    }
3143
+
3144
+    /**
3145
+     *	Update object linked of a current object
3146
+     *
3147
+     *	@param	int		$sourceid		Object source id
3148
+     *	@param  string	$sourcetype		Object source type
3149
+     *	@param  int		$targetid		Object target id
3150
+     *	@param  string	$targettype		Object target type
3151
+     *	@return							int	>0 if OK, <0 if KO
3152
+     *	@see	add_object_linked, fetObjectLinked, deleteObjectLinked
3153
+     */
3154
+    function updateObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='')
3155
+    {
3156
+        $updatesource=false;
3157
+        $updatetarget=false;
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;
3161
+
3162
+        $sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
3163
+        if ($updatesource)
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)."'";
3169
+        }
3170
+        else if ($updatetarget)
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)."'";
3176
+        }
3177
+
3178
+        dol_syslog(get_class($this)."::updateObjectLinked", LOG_DEBUG);
3179
+        if ($this->db->query($sql))
3180
+        {
3181
+            return 1;
3182
+        }
3183
+        else
3184
+        {
3185
+            $this->error=$this->db->lasterror();
3186
+            return -1;
3187
+        }
3188
+    }
3189
+
3190
+    /**
3191
+     *	Delete all links between an object $this
3192
+     *
3193
+     *	@param	int		$sourceid		Object source id
3194
+     *	@param  string	$sourcetype		Object source type
3195
+     *	@param  int		$targetid		Object target id
3196
+     *	@param  string	$targettype		Object target type
3197
+     *  @param	int		$rowid			Row id of line to delete. If defined, other parameters are not used.
3198
+     *	@return     					int	>0 if OK, <0 if KO
3199
+     *	@see	add_object_linked, updateObjectLinked, fetchObjectLinked
3200
+     */
3201
+    function deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid='')
3202
+    {
3203
+        $deletesource=false;
3204
+        $deletetarget=false;
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;
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);
3213
+
3214
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_element";
3215
+        $sql.= " WHERE";
3216
+        if ($rowid > 0)
3217
+        {
3218
+            $sql.=" rowid = ".$rowid;
3219
+        }
3220
+        else
3221
+        {
3222
+            if ($deletesource)
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)."'";
3226
+            }
3227
+            else if ($deletetarget)
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)."'";
3231
+            }
3232
+            else
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)."')";
3237
+            }
3238
+        }
3239
+
3240
+        dol_syslog(get_class($this)."::deleteObjectLinked", LOG_DEBUG);
3241
+        if ($this->db->query($sql))
3242
+        {
3243
+            return 1;
3244
+        }
3245
+        else
3246
+        {
3247
+            $this->error=$this->db->lasterror();
3248
+            $this->errors[]=$this->error;
3249
+            return -1;
3250
+        }
3251
+    }
3252
+
3253
+    /**
3254
+     *      Set status of an object
3255
+     *
3256
+     *      @param	int		$status			Status to set
3257
+     *      @param	int		$elementId		Id of element to force (use this->id by default)
3258
+     *      @param	string	$elementType	Type of element to force (use this->table_element by default)
3259
+     *      @param	string	$trigkey		Trigger key to use for trigger
3260
+     *      @return int						<0 if KO, >0 if OK
3261
+     */
3262
+    function setStatut($status, $elementId=null, $elementType='', $trigkey='')
3263
+    {
3264
+        global $user,$langs,$conf;
3265
+
3266
+        $savElementId=$elementId;  // To be used later to know if we were using the method using the id of this or not.
3267
+
3268
+        $elementId = (!empty($elementId)?$elementId:$this->id);
3269
+        $elementTable = (!empty($elementType)?$elementType:$this->table_element);
3270
+
3271
+        $this->db->begin();
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";
3280
+
3281
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
3282
+        $sql.= " SET ".$fieldstatus." = ".$status;
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;
3286
+
3287
+        dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
3288
+        if ($this->db->query($sql))
3289
+        {
3290
+            $error = 0;
3291
+
3292
+            // Try autoset of trigkey
3293
+            if (empty($trigkey))
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';
3301
+            }
3302
+
3303
+            if ($trigkey)
3304
+            {
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);
3309
+                if ($result < 0) {
3310
+                    $error++; $this->errors=$interface->errors;
3311
+                }
3312
+                // Fin appel triggers
3313
+            }
3314
+
3315
+            if (! $error)
3316
+            {
3317
+                $this->db->commit();
3318
+
3319
+                if (empty($savElementId))    // If the element we update was $this (so $elementId is null)
3320
+                {
3321
+                    $this->statut = $status;
3322
+                    $this->status = $status;
3323
+                }
3324
+
3325
+                return 1;
3326
+            }
3327
+            else
3328
+            {
3329
+                $this->db->rollback();
3330
+                dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
3331
+                return -1;
3332
+            }
3333
+        }
3334
+        else
3335
+        {
3336
+            $this->error=$this->db->lasterror();
3337
+            $this->db->rollback();
3338
+            return -1;
3339
+        }
3340
+    }
3341
+
3342
+
3343
+    /**
3344
+     *  Load type of canvas of an object if it exists
3345
+     *
3346
+     *  @param      int		$id     Record id
3347
+     *  @param      string	$ref    Record ref
3348
+     *  @return		int				<0 if KO, 0 if nothing done, >0 if OK
3349
+     */
3350
+    function getCanvas($id=0,$ref='')
3351
+    {
3352
+        global $conf;
3353
+
3354
+        if (empty($id) && empty($ref)) return 0;
3355
+        if (!empty(Globals::$conf->global->MAIN_DISABLE_CANVAS))
3356
+            return 0;    // To increase speed. Not enabled by default.
3357
+
3358
+            // Clean parameters
3359
+        $ref = trim($ref);
3360
+
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)."'";
3366
+
3367
+        $resql = $this->db->query($sql);
3368
+        if ($resql)
3369
+        {
3370
+            $obj = $this->db->fetch_object($resql);
3371
+            if ($obj)
3372
+            {
3373
+                $this->canvas   = $obj->canvas;
3374
+                return 1;
3375
+            }
3376
+            else return 0;
3377
+        }
3378
+        else
3379
+        {
3380
+            dol_print_error($this->db);
3381
+            return -1;
3382
+        }
3383
+    }
3384
+
3385
+
3386
+    /**
3387
+     * 	Get special code of a line
3388
+     *
3389
+     * 	@param	int		$lineid		Id of line
3390
+     * 	@return	int					Special code
3391
+     */
3392
+    function getSpecialCode($lineid)
3393
+    {
3394
+        $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3395
+        $sql.= ' WHERE rowid = '.$lineid;
3396
+        $resql = $this->db->query($sql);
3397
+        if ($resql)
3398
+        {
3399
+            $row = $this->db->fetch_row($resql);
3400
+            return $row[0];
3401
+        }
3402
+    }
3403
+
3404
+    /**
3405
+     *  Function to check if an object is used by others.
3406
+     *  Check is done into this->childtables. There is no check into llx_element_element.
3407
+     *
3408
+     *  @param	int		$id			Force id of object
3409
+     *  @return	int					<0 if KO, 0 if not used, >0 if already used
3410
+     */
3411
+    function isObjectUsed($id=0)
3412
+    {
3413
+        global $langs;
3414
+
3415
+        if (empty($id)) $id=$this->id;
3416
+
3417
+        // Check parameters
3418
+        if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3419
+        {
3420
+            dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3421
+            return -1;
3422
+        }
3423
+
3424
+        $arraytoscan = $this->childtables;
3425
+        // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3426
+        $tmparray=array_keys($this->childtables);
3427
+        if (is_numeric($tmparray[0]))
3428
+        {
3429
+            $arraytoscan = array_flip($this->childtables);
3430
+        }
3431
+
3432
+        // Test if child exists
3433
+        $haschild=0;
3434
+        foreach($arraytoscan as $table => $elementname)
3435
+        {
3436
+            //print $id.'-'.$table.'-'.$elementname.'<br>';
3437
+            // Check if third party can be deleted
3438
+            $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3439
+            $sql.= " WHERE ".$this->fk_element." = ".$id;
3440
+            $resql=$this->db->query($sql);
3441
+            if ($resql)
3442
+            {
3443
+                $obj=$this->db->fetch_object($resql);
3444
+                if ($obj->nb > 0)
3445
+                {
3446
+                    $langs->load("errors");
3447
+                    //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3448
+                    $haschild += $obj->nb;
3449
+                    if (is_numeric($elementname))	// old usage
3450
+                    {
3451
+                        $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3452
+                    }
3453
+                    else	// new usage: $elementname=Translation key
3454
+                    {
3455
+                        $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3456
+                    }
3457
+                    break;    // We found at least one, we stop here
3458
+                }
3459
+            }
3460
+            else
3461
+            {
3462
+                $this->errors[]=$this->db->lasterror();
3463
+                return -1;
3464
+            }
3465
+        }
3466
+        if ($haschild > 0)
3467
+        {
3468
+            $this->errors[]="ErrorRecordHasChildren";
3469
+            return $haschild;
3470
+        }
3471
+        else return 0;
3472
+    }
3473
+
3474
+    /**
3475
+     *  Function to say how many lines object contains
3476
+     *
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
+     *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3479
+     */
3480
+    function hasProductsOrServices($predefined=-1)
3481
+    {
3482
+        $nb=0;
3483
+
3484
+        foreach($this->lines as $key => $val)
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;
3492
+            if ($qualified) $nb++;
3493
+        }
3494
+        dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3495
+        return $nb;
3496
+    }
3497
+
3498
+    /**
3499
+     * Function that returns the total amount HT of discounts applied for all lines.
3500
+     *
3501
+     * @return 	float
3502
+     */
3503
+    function getTotalDiscount()
3504
+    {
3505
+        $total_discount=0.00;
3506
+
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;
3510
+
3511
+        dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3512
+        $resql = $this->db->query($sql);
3513
+        if ($resql)
3514
+        {
3515
+            $num=$this->db->num_rows($resql);
3516
+            $i=0;
3517
+            while ($i < $num)
3518
+            {
3519
+                $obj = $this->db->fetch_object($resql);
3520
+
3521
+                $pu_ht = $obj->pu_ht;
3522
+                $qty= $obj->qty;
3523
+                $total_ht = $obj->total_ht;
3524
+
3525
+                $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
3526
+                $total_discount += $total_discount_line;
3527
+
3528
+                $i++;
3529
+            }
3530
+        }
3531
+
3532
+        //print $total_discount; exit;
3533
+        return price2num($total_discount);
3534
+    }
3535
+
3536
+
3537
+    /**
3538
+     * Return into unit=0, the calculated total of weight and volume of all lines * qty
3539
+     * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
3540
+     *
3541
+     * @return  array                           array('weight'=>...,'volume'=>...)
3542
+     */
3543
+    function getTotalWeightVolume()
3544
+    {
3545
+        $totalWeight = 0;
3546
+        $totalVolume = 0;
3547
+        // defined for shipment only
3548
+        $totalOrdered = '';
3549
+        // defined for shipment only
3550
+        $totalToShip = '';
3551
+
3552
+        foreach ($this->lines as $line)
3553
+        {
3554
+            if (isset($line->qty_asked))
3555
+            {
3556
+                if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3557
+                $totalOrdered+=$line->qty_asked;    // defined for shipment only
3558
+            }
3559
+            if (isset($line->qty_shipped))
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))
3564
+            {
3565
+                if (empty($totalToShip)) $totalToShip=0;
3566
+                $totalToShip+=$line->qty;   // defined for reception only
3567
+            }
3568
+
3569
+            // Define qty, weight, volume, weight_units, volume_units
3570
+            if ($this->element == 'shipping') {
3571
+                // for shipments
3572
+                $qty = $line->qty_shipped ? $line->qty_shipped : 0;
3573
+            }
3574
+            else {
3575
+                $qty = $line->qty ? $line->qty : 0;
3576
+            }
3577
+
3578
+            $weight = $line->weight ? $line->weight : 0;
3579
+            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3580
+            $volume = $line->volume ? $line->volume : 0;
3581
+            ($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
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;
3587
+
3588
+            $weightUnit=0;
3589
+            $volumeUnit=0;
3590
+            if (! empty($weight_units)) $weightUnit = $weight_units;
3591
+            if (! empty($volume_units)) $volumeUnit = $volume_units;
3592
+
3593
+            if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3594
+            if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3595
+
3596
+            //var_dump($line->volume_units);
3597
+            if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3598
+            {
3599
+                $trueWeightUnit=pow(10, $weightUnit);
3600
+                $totalWeight += $weight * $qty * $trueWeightUnit;
3601
+            }
3602
+            else {
3603
+        if ($weight_units == 99) {
3604
+            // conversion 1 Pound = 0.45359237 KG
3605
+            $trueWeightUnit = 0.45359237;
3606
+            $totalWeight += $weight * $qty * $trueWeightUnit;
3607
+        } elseif ($weight_units == 98) {
3608
+            // conversion 1 Ounce = 0.0283495 KG
3609
+            $trueWeightUnit = 0.0283495;
3610
+            $totalWeight += $weight * $qty * $trueWeightUnit;
3611
+        }
3612
+        else
3613
+                    $totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3614
+            }
3615
+            if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3616
+            {
3617
+                //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3618
+                $trueVolumeUnit=pow(10, $volumeUnit);
3619
+                //print $line->volume;
3620
+                $totalVolume += $volume * $qty * $trueVolumeUnit;
3621
+            }
3622
+            else
3623
+            {
3624
+                $totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3625
+            }
3626
+        }
3627
+
3628
+        return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
3629
+    }
3630
+
3631
+
3632
+    /**
3633
+     *	Set extra parameters
3634
+     *
3635
+     *	@return	int      <0 if KO, >0 if OK
3636
+     */
3637
+    function setExtraParameters()
3638
+    {
3639
+        $this->db->begin();
3640
+
3641
+        $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3642
+
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;
3646
+
3647
+        dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3648
+        $resql = $this->db->query($sql);
3649
+        if (! $resql)
3650
+        {
3651
+            $this->error=$this->db->lasterror();
3652
+            $this->db->rollback();
3653
+            return -1;
3654
+        }
3655
+        else
3656
+        {
3657
+            $this->db->commit();
3658
+            return 1;
3659
+        }
3660
+    }
3661
+
3662
+
3663
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3664
+    /**
3665
+     *    Return incoterms informations
3666
+     *    TODO Use a cache for label get
3667
+     *
3668
+     *    @return	string	incoterms info
3669
+     */
3670
+    function display_incoterms()
3671
+    {
3672
+        // phpcs:enable
3673
+        $out = '';
3674
+        $this->libelle_incoterms = '';
3675
+        if (!empty($this->fk_incoterms))
3676
+        {
3677
+            $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3678
+            $result = $this->db->query($sql);
3679
+            if ($result)
3680
+            {
3681
+                $res = $this->db->fetch_object($result);
3682
+                $out .= $res->code;
3683
+            }
3684
+        }
3685
+
3686
+        $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3687
+
3688
+        return $out;
3689
+    }
3690
+
3691
+    /**
3692
+     *    Return incoterms informations for pdf display
3693
+     *
3694
+     *    @return	string		incoterms info
3695
+     */
3696
+    function getIncotermsForPDF()
3697
+    {
3698
+        $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3699
+        $resql = $this->db->query($sql);
3700
+        if ($resql)
3701
+        {
3702
+            $num = $this->db->num_rows($resql);
3703
+            if ($num > 0)
3704
+            {
3705
+                $res = $this->db->fetch_object($resql);
3706
+                return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3707
+            }
3708
+            else
3709
+            {
3710
+                return '';
3711
+            }
3712
+        }
3713
+        else
3714
+        {
3715
+            $this->errors[] = $this->db->lasterror();
3716
+            return false;
3717
+        }
3718
+    }
3719
+
3720
+    /**
3721
+     *    Define incoterms values of current object
3722
+     *
3723
+     *    @param	int		$id_incoterm     Id of incoterm to set or '' to remove
3724
+     * 	  @param 	string  $location		 location of incoterm
3725
+     *    @return	int     		<0 if KO, >0 if OK
3726
+     */
3727
+    function setIncoterms($id_incoterm, $location)
3728
+    {
3729
+        if ($this->id && $this->table_element)
3730
+        {
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;
3735
+            dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3736
+            $resql=$this->db->query($sql);
3737
+            if ($resql)
3738
+            {
3739
+                $this->fk_incoterms = $id_incoterm;
3740
+                $this->location_incoterms = $location;
3741
+
3742
+                $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3743
+                $res = $this->db->query($sql);
3744
+                if ($res)
3745
+                {
3746
+                    $obj = $this->db->fetch_object($res);
3747
+                    $this->libelle_incoterms = $obj->libelle;
3748
+                }
3749
+                return 1;
3750
+            }
3751
+            else
3752
+            {
3753
+                $this->errors[] = $this->db->lasterror();
3754
+                return -1;
3755
+            }
3756
+        }
3757
+        else return -1;
3758
+    }
3759
+
3760
+
3761
+    // --------------------
3762
+    // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
3763
+    // --------------------
3764
+
3765
+    /* This is to show add lines */
3766
+
3767
+    /**
3768
+     *	Show add free and predefined products/services form
3769
+     *
3770
+     *  @param	int		        $dateSelector       1=Show also date range input fields
3771
+     *  @param	Societe			$seller				Object thirdparty who sell
3772
+     *  @param	Societe			$buyer				Object thirdparty who buy
3773
+     *	@return	void
3774
+     */
3775
+    function formAddObjectLine($dateSelector, $seller, $buyer)
3776
+    {
3777
+        global $conf,$user,$langs,$object,$hookmanager;
3778
+        global $form,$bcnd,$var;
3779
+
3780
+        // Line extrafield
3781
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3782
+        $extrafieldsline = new ExtraFields($this->db);
3783
+        $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3784
+
3785
+        // Output template part (modules that overwrite templates must declare this into descriptor)
3786
+        // Use global variables + $dateSelector + $seller and $buyer
3787
+        $dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
3788
+        foreach($dirtpls as $reldir)
3789
+        {
3790
+            $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3791
+            if (empty(Globals::$conf->file->strict_mode)) {
3792
+                $res=@include $tpl;
3793
+            } else {
3794
+                $res=include $tpl; // for debug
3795
+            }
3796
+            if ($res) break;
3797
+        }
3798
+    }
3799
+
3800
+
3801
+
3802
+    /* This is to show array of line of details */
3803
+
3804
+
3805
+    /**
3806
+     *	Return HTML table for object lines
3807
+     *	TODO Move this into an output class file (htmlline.class.php)
3808
+     *	If lines are into a template, title must also be into a template
3809
+     *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
3810
+     *
3811
+     *	@param	string		$action				Action code
3812
+     *	@param  string		$seller            	Object of seller third party
3813
+     *	@param  string  	$buyer             	Object of buyer third party
3814
+     *	@param	int			$selected		   	Object line selected
3815
+     *	@param  int	    	$dateSelector      	1=Show also date range input fields
3816
+     *	@return	void
3817
+     */
3818
+    function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3819
+    {
3820
+        global $conf, $hookmanager, $langs, $user;
3821
+        // TODO We should not use global var for this !
3822
+        global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3823
+
3824
+        // Define usemargins
3825
+        $usemargins=0;
3826
+        if (!empty(Globals::$conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande')))
3827
+            $usemargins = 1;
3828
+
3829
+        $num = count($this->lines);
3830
+
3831
+        // Line extrafield
3832
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3833
+        $extrafieldsline = new ExtraFields($this->db);
3834
+        $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3835
+
3836
+        $parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3837
+        $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3838
+        if (empty($reshook))
3839
+        {
3840
+            // Title line
3841
+            print "<thead>\n";
3842
+
3843
+            print '<tr class="liste_titre nodrag nodrop">';
3844
+
3845
+            // Adds a line numbering column
3846
+            if (!empty(Globals::$conf->global->MAIN_VIEW_LINE_NUMBER))
3847
+                print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
3848
+
3849
+            // Description
3850
+            print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
3851
+
3852
+            if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier')
3853
+            {
3854
+                print '<td class="linerefsupplier"><span id="title_fourn_ref">'.$langs->trans("SupplierRef").'</span></td>';
3855
+            }
3856
+
3857
+            // VAT
3858
+            print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
3859
+
3860
+            // Price HT
3861
+            print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
3862
+
3863
+            // Multicurrency
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>';
3866
+
3867
+            if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
3868
+
3869
+            // Qty
3870
+            print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
3871
+
3872
+            if (Globals::$conf->global->PRODUCT_USE_UNITS) {
3873
+                print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
3874
+            }
3875
+
3876
+            // Reduction short
3877
+            print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
3878
+
3879
+            if ($this->situation_cycle_ref) {
3880
+                print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3881
+            }
3882
+
3883
+            if ($usemargins && !empty(Globals::$conf->margin->enabled) && empty($user->societe_id)) {
3884
+                if (!empty($user->rights->margins->creer))
3885
+                {
3886
+                    if (Globals::$conf->global->MARGIN_TYPE == "1")
3887
+                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3888
+                    else
3889
+                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
3890
+                }
3891
+
3892
+                if (!empty(Globals::$conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3893
+                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3894
+                if (!empty(Globals::$conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3895
+                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
3896
+            }
3897
+
3898
+            // Total HT
3899
+            print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
3900
+
3901
+            // Multicurrency
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>';
3904
+
3905
+            if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
3906
+
3907
+            print '<td class="linecoledit"></td>';  // No width to allow autodim
3908
+
3909
+            print '<td class="linecoldelete" width="10"></td>';
3910
+
3911
+            print '<td class="linecolmove" width="10"></td>';
3912
+
3913
+            if($action == 'selectlines')
3914
+            {
3915
+                print '<td class="linecolcheckall" align="center">';
3916
+                print '<input type="checkbox" class="linecheckboxtoggle" />';
3917
+                print '<script type="text/javascript">$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
3918
+                print '</td>';
3919
+            }
3920
+
3921
+            print "</tr>\n";
3922
+            print "</thead>\n";
3923
+        }
3924
+
3925
+        $var = true;
3926
+        $i	 = 0;
3927
+
3928
+        print "<tbody>\n";
3929
+        foreach ($this->lines as $line)
3930
+        {
3931
+            //Line extrafield
3932
+            $line->fetch_optionals();
3933
+
3934
+            //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3935
+            if (is_object($hookmanager))   // Old code is commented on preceding line.
3936
+            {
3937
+                if (empty($line->fk_parent_line))
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
3941
+                }
3942
+                else
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
3946
+                }
3947
+            }
3948
+            if (empty($reshook))
3949
+            {
3950
+                $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3951
+            }
3952
+
3953
+            $i++;
3954
+        }
3955
+        print "</tbody>\n";
3956
+    }
3957
+
3958
+    /**
3959
+     *	Return HTML content of a detail line
3960
+     *	TODO Move this into an output class file (htmlline.class.php)
3961
+     *
3962
+     *	@param	string		$action				GET/POST action
3963
+     *	@param CommonObjectLine $line		       	Selected object line to output
3964
+     *	@param  string	    $var               	Is it a an odd line (true)
3965
+     *	@param  int		    $num               	Number of line (0)
3966
+     *	@param  int		    $i					I
3967
+     *	@param  int		    $dateSelector      	1=Show also date range input fields
3968
+     *	@param  string	    $seller            	Object of seller third party
3969
+     *	@param  string	    $buyer             	Object of buyer third party
3970
+     *	@param	int			$selected		   	Object line selected
3971
+     *  @param  int			$extrafieldsline	Object of extrafield line attribute
3972
+     *	@return	void
3973
+     */
3974
+    function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
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 !
3979
+
3980
+        $object_rights = $this->getRights();
3981
+
3982
+        $element=$this->element;
3983
+
3984
+        $text=''; $description=''; $type=0;
3985
+
3986
+        // Show product and description
3987
+        $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
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
3991
+
3992
+        // Ligne en mode visu
3993
+        if ($action != 'editline' || $selected != $line->id)
3994
+        {
3995
+            // Product
3996
+            if ($line->fk_product > 0)
3997
+            {
3998
+                $product_static = new Product($this->db);
3999
+                $product_static->fetch($line->fk_product);
4000
+
4001
+                $product_static->ref = $line->ref; //can change ref in hook
4002
+                $product_static->label = $line->label; //can change label in hook
4003
+                $text=$product_static->getNomUrl(1);
4004
+
4005
+                // Define output language and label
4006
+                if (!empty(Globals::$conf->global->MAIN_MULTILANGS)) {
4007
+                    if (! is_object($this->thirdparty))
4008
+                    {
4009
+                        dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4010
+                        return;
4011
+                    }
4012
+
4013
+                    $prod = new Product($this->db);
4014
+                    $prod->fetch($line->fk_product);
4015
+
4016
+                    $outputlangs = $langs;
4017
+                    $newlang='';
4018
+                    if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
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))
4022
+                    {
4023
+                        $outputlangs = new Translate("",$conf);
4024
+                        $outputlangs->setDefaultLang($newlang);
4025
+                    }
4026
+
4027
+                    $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4028
+                }
4029
+                else
4030
+                {
4031
+                    $label = $line->product_label;
4032
+                }
4033
+
4034
+                $text.= ' - '.(! empty($line->label)?$line->label:$label);
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
+            }
4037
+
4038
+            $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4039
+
4040
+            // Output template part (modules that overwrite templates must declare this into descriptor)
4041
+            // Use global variables + $dateSelector + $seller and $buyer
4042
+            $dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4043
+            foreach($dirtpls as $reldir)
4044
+            {
4045
+                $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4046
+                if (empty(Globals::$conf->file->strict_mode)) {
4047
+                    $res=@include $tpl;
4048
+                } else {
4049
+                    $res=include $tpl; // for debug
4050
+                }
4051
+                if ($res) break;
4052
+            }
4053
+        }
4054
+
4055
+        // Ligne en mode update
4056
+        if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4057
+        {
4058
+            $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4059
+            $placeholder=' placeholder="'.$langs->trans("Label").'"';
4060
+
4061
+            $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4062
+
4063
+            // Output template part (modules that overwrite templates must declare this into descriptor)
4064
+            // Use global variables + $dateSelector + $seller and $buyer
4065
+            $dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4066
+            foreach($dirtpls as $reldir)
4067
+            {
4068
+                $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4069
+                if (empty(Globals::$conf->file->strict_mode)) {
4070
+                    $res=@include $tpl;
4071
+                } else {
4072
+                    $res=include $tpl; // for debug
4073
+                }
4074
+                if ($res) break;
4075
+            }
4076
+        }
4077
+    }
4078
+
4079
+
4080
+    /* This is to show array of line of details of source object */
4081
+
4082
+
4083
+    /**
4084
+     * 	Return HTML table table of source object lines
4085
+     *  TODO Move this and previous function into output html class file (htmlline.class.php).
4086
+     *  If lines are into a template, title must also be into a template
4087
+     *  But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
4088
+     *
4089
+     *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4090
+     *  @return	void
4091
+     */
4092
+    function printOriginLinesList($restrictlist='')
4093
+    {
4094
+        global $langs, $hookmanager, $conf;
4095
+
4096
+        print '<tr class="liste_titre">';
4097
+        print '<td>'.$langs->trans('Ref').'</td>';
4098
+        print '<td>'.$langs->trans('Description').'</td>';
4099
+        print '<td align="right">'.$langs->trans('VATRate').'</td>';
4100
+        print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4101
+        if (!empty(Globals::$conf->multicurrency->enabled))
4102
+            print '<td align="right">' . $langs->trans('PriceUHTCurrency') . '</td>';
4103
+        print '<td align="right">'.$langs->trans('Qty').'</td>';
4104
+        if (Globals::$conf->global->PRODUCT_USE_UNITS) {
4105
+            print '<td align="left">'.$langs->trans('Unit').'</td>';
4106
+        }
4107
+        print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
4108
+
4109
+        $var = true;
4110
+        $i	 = 0;
4111
+
4112
+        if (! empty($this->lines))
4113
+        {
4114
+            foreach ($this->lines as $line)
4115
+            {
4116
+                if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4117
+                {
4118
+                    if (empty($line->fk_parent_line))
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
4123
+                    }
4124
+                }
4125
+                else
4126
+                {
4127
+                    $this->printOriginLine($line, $var, $restrictlist);
4128
+                }
4129
+
4130
+                $i++;
4131
+            }
4132
+        }
4133
+    }
4134
+
4135
+    /**
4136
+     * 	Return HTML with a line of table array of source object lines
4137
+     *  TODO Move this and previous function into output html class file (htmlline.class.php).
4138
+     *  If lines are into a template, title must also be into a template
4139
+     *  But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
4140
+     *
4141
+     * 	@param	CommonObjectLine	$line				Line
4142
+     * 	@param	string				$var				Var
4143
+     *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4144
+     * 	@return	void
4145
+     */
4146
+    function printOriginLine($line, $var, $restrictlist='')
4147
+    {
4148
+        global $langs, $conf;
4149
+
4150
+        //var_dump($line);
4151
+        if (!empty($line->date_start))
4152
+        {
4153
+            $date_start=$line->date_start;
4154
+        }
4155
+        else
4156
+        {
4157
+            $date_start=$line->date_debut_prevue;
4158
+            if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4159
+        }
4160
+        if (!empty($line->date_end))
4161
+        {
4162
+            $date_end=$line->date_end;
4163
+        }
4164
+        else
4165
+        {
4166
+            $date_end=$line->date_fin_prevue;
4167
+            if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4168
+        }
4169
+
4170
+        $this->tpl['label'] = '';
4171
+        if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4172
+
4173
+        if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4174
+        {
4175
+            $discount=new DiscountAbsolute($this->db);
4176
+            $discount->fk_soc = $this->socid;
4177
+            $this->tpl['label'].= $discount->getNomUrl(0,'discount');
4178
+        }
4179
+        else if (! empty($line->fk_product))
4180
+        {
4181
+            $productstatic = new Product($this->db);
4182
+            $productstatic->id = $line->fk_product;
4183
+            $productstatic->ref = $line->ref;
4184
+            $productstatic->type = $line->fk_product_type;
4185
+            if(empty($productstatic->ref)){
4186
+                $line->fetch_product();
4187
+                $productstatic = $line->product;
4188
+            }
4189
+			
4190
+            $this->tpl['label'].= $productstatic->getNomUrl(1);
4191
+            $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4192
+            // Dates
4193
+            if ($line->product_type == 1 && ($date_start || $date_end))
4194
+            {
4195
+                $this->tpl['label'].= get_date_range($date_start,$date_end);
4196
+            }
4197
+        }
4198
+        else
4199
+        {
4200
+            $this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4201
+            if (!empty($line->desc)) {
4202
+                $this->tpl['label'].=$line->desc;
4203
+            }else {
4204
+                $this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4205
+            }
4206
+			
4207
+            // Dates
4208
+            if ($line->product_type == 1 && ($date_start || $date_end))
4209
+            {
4210
+                $this->tpl['label'].= get_date_range($date_start,$date_end);
4211
+            }
4212
+        }
4213
+
4214
+        if (! empty($line->desc))
4215
+        {
4216
+            if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4217
+            {
4218
+                $discount=new DiscountAbsolute($this->db);
4219
+                $discount->fetch($line->fk_remise_except);
4220
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4221
+            }
4222
+            elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4223
+            {
4224
+                $discount=new DiscountAbsolute($this->db);
4225
+                $discount->fetch($line->fk_remise_except);
4226
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4227
+            }
4228
+            elseif ($line->desc == '(EXCESS RECEIVED)')
4229
+            {
4230
+                $discount=new DiscountAbsolute($this->db);
4231
+                $discount->fetch($line->fk_remise_except);
4232
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4233
+            }
4234
+            elseif ($line->desc == '(EXCESS PAID)')
4235
+            {
4236
+                $discount=new DiscountAbsolute($this->db);
4237
+                $discount->fetch($line->fk_remise_except);
4238
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4239
+            }
4240
+            else
4241
+            {
4242
+                $this->tpl['description'] = dol_trunc($line->desc,60);
4243
+            }
4244
+        }
4245
+        else
4246
+        {
4247
+            $this->tpl['description'] = '&nbsp;';
4248
+        }
4249
+
4250
+        // VAT Rate
4251
+        $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
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.')';
4254
+
4255
+        $this->tpl['price'] = price($line->subprice);
4256
+        $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4257
+        $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4258
+        if (Globals::$conf->global->PRODUCT_USE_UNITS)
4259
+            $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4260
+        $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4261
+
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;
4265
+
4266
+        // Output template part (modules that overwrite templates must declare this into descriptor)
4267
+        // Use global variables + $dateSelector + $seller and $buyer
4268
+        $dirtpls = array_merge(Globals::$conf->modules_parts['tpl'], array('/core/tpl'));
4269
+        foreach($dirtpls as $reldir)
4270
+        {
4271
+            $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4272
+            if (empty(Globals::$conf->file->strict_mode)) {
4273
+                $res=@include $tpl;
4274
+            } else {
4275
+                $res=include $tpl; // for debug
4276
+            }
4277
+            if ($res) break;
4278
+        }
4279
+    }
4280
+
4281
+
4282
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4283
+    /**
4284
+     *	Add resources to the current object : add entry into llx_element_resources
4285
+     *	Need $this->element & $this->id
4286
+     *
4287
+     *	@param		int		$resource_id		Resource id
4288
+     *	@param		string	$resource_type		'resource'
4289
+     *	@param		int		$busy				Busy or not
4290
+     *	@param		int		$mandatory			Mandatory or not
4291
+     *	@return		int							<=0 if KO, >0 if OK
4292
+     */
4293
+    function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4294
+    {
4295
+        // phpcs:enable
4296
+        $this->db->begin();
4297
+
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.= ")";
4313
+
4314
+        dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4315
+        if ($this->db->query($sql))
4316
+        {
4317
+            $this->db->commit();
4318
+            return 1;
4319
+        }
4320
+        else
4321
+        {
4322
+            $this->error=$this->db->lasterror();
4323
+            $this->db->rollback();
4324
+            return  0;
4325
+        }
4326
+    }
4327
+
4328
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4329
+    /**
4330
+     *    Delete a link to resource line
4331
+     *
4332
+     *    @param	int		$rowid			Id of resource line to delete
4333
+     *    @param	int		$element		element name (for trigger) TODO: use $this->element into commonobject class
4334
+     *    @param	int		$notrigger		Disable all triggers
4335
+     *    @return   int						>0 if OK, <0 if KO
4336
+     */
4337
+    function delete_resource($rowid, $element, $notrigger=0)
4338
+    {
4339
+        // phpcs:enable
4340
+        global $user;
4341
+
4342
+        $this->db->begin();
4343
+
4344
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4345
+        $sql.= " WHERE rowid=".$rowid;
4346
+
4347
+        dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
4348
+
4349
+        $resql=$this->db->query($sql);
4350
+        if (! $resql)
4351
+        {
4352
+            $this->error=$this->db->lasterror();
4353
+            $this->db->rollback();
4354
+            return -1;
4355
+        }
4356
+        else
4357
+        {
4358
+            if (! $notrigger)
4359
+            {
4360
+                $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4361
+                if ($result < 0) { $this->db->rollback(); return -1; }
4362
+            }
4363
+            $this->db->commit();
4364
+            return 1;
4365
+        }
4366
+    }
4367
+
4368
+
4369
+    /**
4370
+     * Overwrite magic function to solve problem of cloning object that are kept as references
4371
+     *
4372
+     * @return void
4373
+     */
4374
+    function __clone()
4375
+    {
4376
+        // Force a copy of this->lines, otherwise it will point to same object.
4377
+        if (isset($this->lines) && is_array($this->lines))
4378
+        {
4379
+            $nboflines=count($this->lines);
4380
+            for($i=0; $i < $nboflines; $i++)
4381
+            {
4382
+                $this->lines[$i] = clone $this->lines[$i];
4383
+            }
4384
+        }
4385
+    }
4386
+
4387
+    /**
4388
+     * Common function for all objects extending CommonObject for generating documents
4389
+     *
4390
+     * @param 	string 		$modelspath 	Relative folder where generators are placed
4391
+     * @param 	string 		$modele 		Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
4392
+     * @param 	Translate 	$outputlangs 	Output language to use
4393
+     * @param 	int 		$hidedetails 	1 to hide details. 0 by default
4394
+     * @param 	int 		$hidedesc 		1 to hide product description. 0 by default
4395
+     * @param 	int 		$hideref 		1 to hide product reference. 0 by default
4396
+     * @param   null|array  $moreparams     Array to provide more information
4397
+     * @return 	int 						>0 if OK, <0 if KO
4398
+     * @see	addFileIntoDatabaseIndex
4399
+     */
4400
+    protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4401
+    {
4402
+        global $conf, $langs, $user;
4403
+
4404
+        $srctemplatepath='';
4405
+
4406
+        // Increase limit for PDF build
4407
+        $err=error_reporting();
4408
+        error_reporting(0);
4409
+        @set_time_limit(120);
4410
+        error_reporting($err);
4411
+
4412
+        // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4413
+        $tmp=explode(':',$modele,2);
4414
+        if (! empty($tmp[1]))
4415
+        {
4416
+            $modele=$tmp[0];
4417
+            $srctemplatepath=$tmp[1];
4418
+        }
4419
+
4420
+        // Search template files
4421
+        $file=''; $classname=''; $filefound=0;
4422
+        $dirmodels=array('/');
4423
+        if (is_array(Globals::$conf->modules_parts['models']))
4424
+            $dirmodels = array_merge($dirmodels, Globals::$conf->modules_parts['models']);
4425
+        foreach($dirmodels as $reldir)
4426
+        {
4427
+            foreach(array('doc','pdf') as $prefix)
4428
+            {
4429
+                if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4430
+                else $file = $prefix."_".$modele.".modules.php";
4431
+
4432
+                // On verifie l'emplacement du modele
4433
+                $file=dol_buildpath($reldir.$modelspath.$file,0);
4434
+                if (file_exists($file))
4435
+                {
4436
+                    $filefound=1;
4437
+                    $classname=$prefix.'_'.$modele;
4438
+                    break;
4439
+                }
4440
+            }
4441
+            if ($filefound) break;
4442
+        }
4443
+
4444
+        // If generator was found
4445
+        if ($filefound)
4446
+        {
4447
+            global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4448
+
4449
+            require_once $file;
4450
+
4451
+            $obj = new $classname($this->db);
4452
+
4453
+            // If generator is ODT, we must have srctemplatepath defined, if not we set it.
4454
+            if ($obj->type == 'odt' && empty($srctemplatepath))
4455
+            {
4456
+                $varfortemplatedir=$obj->scandir;
4457
+                if ($varfortemplatedir && !empty(Globals::$conf->global->$varfortemplatedir)) {
4458
+                    $dirtoscan = Globals::$conf->global->$varfortemplatedir;
4459
+
4460
+                    $listoffiles=array();
4461
+
4462
+                    // Now we add first model found in directories scanned
4463
+                    $listofdir=explode(',',$dirtoscan);
4464
+                    foreach($listofdir as $key => $tmpdir)
4465
+                    {
4466
+                        $tmpdir=trim($tmpdir);
4467
+                        $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4468
+                        if (! $tmpdir) { unset($listofdir[$key]); continue; }
4469
+                        if (is_dir($tmpdir))
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);
4473
+                        }
4474
+                    }
4475
+
4476
+                    if (count($listoffiles))
4477
+                    {
4478
+                        foreach($listoffiles as $record)
4479
+                        {
4480
+                            $srctemplatepath=$record['fullname'];
4481
+                            break;
4482
+                        }
4483
+                    }
4484
+                }
4485
+
4486
+                if (empty($srctemplatepath))
4487
+                {
4488
+                    $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4489
+                    return -1;
4490
+                }
4491
+            }
4492
+
4493
+            if ($obj->type == 'odt' && ! empty($srctemplatepath))
4494
+            {
4495
+                if (! dol_is_file($srctemplatepath))
4496
+                {
4497
+                    $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4498
+                    return -1;
4499
+                }
4500
+            }
4501
+
4502
+            // We save charset_output to restore it because write_file can change it if needed for
4503
+            // output format that does not support UTF8.
4504
+            $sav_charset_output=$outputlangs->charset_output;
4505
+
4506
+            if (in_array(get_class($this), array('Adherent')))
4507
+            {
4508
+                $arrayofrecords = array();   // The write_file of templates of adherent class need this var
4509
+                $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4510
+            }
4511
+            else
4512
+            {
4513
+                $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4514
+            }
4515
+            // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
4516
+
4517
+            if ($resultwritefile > 0)
4518
+            {
4519
+                $outputlangs->charset_output=$sav_charset_output;
4520
+
4521
+                // We delete old preview
4522
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4523
+                dol_delete_preview($this);
4524
+
4525
+                // Index file in database
4526
+                if (! empty($obj->result['fullpath']))
4527
+                {
4528
+                    $destfull = $obj->result['fullpath'];
4529
+                    $upload_dir = dirname($destfull);
4530
+                    $destfile = basename($destfull);
4531
+                    $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4532
+
4533
+                    if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4534
+                    {
4535
+                        $filename = basename($destfile);
4536
+                        $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4537
+                        $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4538
+
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);
4542
+
4543
+                        // Set the public "share" key
4544
+                        $setsharekey = false;
4545
+                        if ($this->element == 'propal')
4546
+                        {
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;
4549
+                            if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD))
4550
+                                $setsharekey = true;
4551
+                        }
4552
+                        if ($this->element == 'commande' && !empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))
4553
+                            $setsharekey = true;
4554
+                        if ($this->element == 'facture' && !empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))
4555
+                            $setsharekey = true;
4556
+                        if ($this->element == 'bank_account' && !empty(Globals::$conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD))
4557
+                            $setsharekey = true;
4558
+
4559
+                        if ($setsharekey)
4560
+                        {
4561
+                            if (empty($ecmfile->share))	// Because object not found or share not set yet
4562
+                            {
4563
+                                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4564
+                                $ecmfile->share = getRandomPassword(true);
4565
+                            }
4566
+                        }
4567
+
4568
+                        if ($result > 0)
4569
+                        {
4570
+                            $ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4571
+                            $ecmfile->fullpath_orig = '';
4572
+                            $ecmfile->gen_or_uploaded = 'generated';
4573
+                            $ecmfile->description = '';    // indexed content
4574
+                            $ecmfile->keyword = '';        // keyword content
4575
+                            $result = $ecmfile->update($user);
4576
+                            if ($result < 0)
4577
+                            {
4578
+                                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4579
+                            }
4580
+                        }
4581
+                        else
4582
+                        {
4583
+                            $ecmfile->entity = Globals::$conf->entity;
4584
+                            $ecmfile->filepath = $rel_dir;
4585
+                            $ecmfile->filename = $filename;
4586
+                            $ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4587
+                            $ecmfile->fullpath_orig = '';
4588
+                            $ecmfile->gen_or_uploaded = 'generated';
4589
+                            $ecmfile->description = '';    // indexed content
4590
+                            $ecmfile->keyword = '';        // keyword content
4591
+                            $ecmfile->src_object_type = $this->table_element;
4592
+                            $ecmfile->src_object_id   = $this->id;
4593
+
4594
+                            $result = $ecmfile->create($user);
4595
+                            if ($result < 0)
4596
+                            {
4597
+                                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4598
+                            }
4599
+                        }
4600
+
4601
+                        /*$this->result['fullname']=$destfull;
4602
+						$this->result['filepath']=$ecmfile->filepath;
4603
+						$this->result['filename']=$ecmfile->filename;*/
4604
+                        //var_dump($obj->update_main_doc_field);exit;
4605
+
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))
4610
+                        {
4611
+                            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4612
+                            $sql.= ' WHERE rowid = '.$this->id;
4613
+                            $resql = $this->db->query($sql);
4614
+                            if (! $resql) dol_print_error($this->db);
4615
+                        }
4616
+                    }
4617
+                }
4618
+                else
4619
+                {
4620
+                    dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
4621
+                }
4622
+
4623
+                // Success in building document. We build meta file.
4624
+                dol_meta_create($this);
4625
+
4626
+                return 1;
4627
+            }
4628
+            else
4629
+            {
4630
+                $outputlangs->charset_output=$sav_charset_output;
4631
+                dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4632
+                return -1;
4633
+            }
4634
+        }
4635
+        else
4636
+        {
4637
+            $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4638
+            dol_print_error('',$this->error);
4639
+            return -1;
4640
+        }
4641
+    }
4642
+
4643
+    /**
4644
+     *  Build thumb
4645
+     *  @TODO Move this into files.lib.php
4646
+     *
4647
+     *  @param      string	$file           Path file in UTF8 to original file to create thumbs from.
4648
+     *	@return		void
4649
+     */
4650
+    function addThumbs($file)
4651
+    {
4652
+        global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4653
+
4654
+        require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4655
+
4656
+        $file_osencoded=dol_osencode($file);
4657
+        if (file_exists($file_osencoded))
4658
+        {
4659
+            // Create small thumbs for company (Ratio is near 16/9)
4660
+            // Used on logon for example
4661
+            vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
4662
+
4663
+            // Create mini thumbs for company (Ratio is near 16/9)
4664
+            // Used on menu or for setup page for example
4665
+            vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
4666
+        }
4667
+    }
4668
+
4669
+
4670
+    /* Functions common to commonobject and commonobjectline */
4671
+
4672
+    /* For default values */
4673
+
4674
+    /**
4675
+     * Return the default value to use for a field when showing the create form of object.
4676
+     * Return values in this order:
4677
+     * 1) If parameter is available into POST, we return it first.
4678
+     * 2) If not but an alternate value was provided as parameter of function, we return it.
4679
+     * 3) If not but a constant Globals::$conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
4680
+     * 4) Return value found into database (TODO No yet implemented)
4681
+     *
4682
+     * @param   string              $fieldname          Name of field
4683
+     * @param   string              $alternatevalue     Alternate value to use
4684
+     * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4685
+     **/
4686
+    function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4687
+    {
4688
+        global $conf, $_POST;
4689
+
4690
+        // If param here has been posted, we use this value first.
4691
+        if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
4692
+
4693
+        if (isset($alternatevalue)) return $alternatevalue;
4694
+
4695
+        $newelement=$this->element;
4696
+        if ($newelement == 'facture') $newelement='invoice';
4697
+        if ($newelement == 'commande') $newelement='order';
4698
+        if (empty($newelement))
4699
+        {
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
+            return '';
4702
+        }
4703
+
4704
+        $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4705
+        //var_dump($keyforfieldname);
4706
+        if (isset(Globals::$conf->global->$keyforfieldname))
4707
+            return Globals::$conf->global->$keyforfieldname;
4708
+
4709
+        // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4710
+    }
4711
+
4712
+
4713
+    /* For triggers */
4714
+
4715
+
4716
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4717
+    /**
4718
+     * Call trigger based on this instance.
4719
+     * Some context information may also be provided into array property this->context.
4720
+     * NB:  Error from trigger are stacked in interface->errors
4721
+     * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
4722
+     *
4723
+     * @param   string    $trigger_name   trigger's name to execute
4724
+     * @param   User      $user           Object user
4725
+     * @return  int                       Result of run_triggers
4726
+     */
4727
+    function call_trigger($trigger_name, $user)
4728
+    {
4729
+        // phpcs:enable
4730
+        global $langs,$conf;
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);
4735
+
4736
+        if ($result < 0)
4737
+        {
4738
+            if (!empty($this->errors))
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.
4741
+            }
4742
+            else
4743
+            {
4744
+                $this->errors=$interface->errors;
4745
+            }
4746
+        }
4747
+        return $result;
4748
+    }
4749
+
4750
+
4751
+    /* Functions for extrafields */
4752
+
4753
+
4754
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4755
+    /**
4756
+     *  Function to get extra fields of an object into $this->array_options
4757
+     *  This method is in most cases called by method fetch of objects but you can call it separately.
4758
+     *
4759
+     *  @param	int		$rowid			Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
4760
+     *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
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
+     */
4763
+    function fetch_optionals($rowid=null, $optionsArray=null)
4764
+    {
4765
+        // phpcs:enable
4766
+        if (empty($rowid)) {
4767
+            $rowid = $this->id;
4768
+        }
4769
+
4770
+        // To avoid SQL errors. Probably not the better solution though
4771
+        if (!$this->table_element) {
4772
+            return 0;
4773
+        }
4774
+
4775
+        $this->array_options=array();
4776
+
4777
+        if (! is_array($optionsArray))
4778
+        {
4779
+            // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4780
+            // TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
4781
+            // global $extrafields;
4782
+            //if (! is_object($extrafields))
4783
+            //{
4784
+                // require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4785
+            $extrafields = new ExtraFields();
4786
+            //}
4787
+
4788
+            // Load array of extrafields for elementype = $this->table_element
4789
+            if (empty($extrafields->attributes[$this->table_element]['loaded']))
4790
+            {
4791
+                $extrafields->fetch_name_optionals_label($this->table_element);
4792
+            }
4793
+            $optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4794
+        }
4795
+        else
4796
+        {
4797
+            // global $extrafields;
4798
+            dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4799
+        }
4800
+
4801
+        $table_element = $this->table_element;
4802
+        if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4803
+
4804
+        // Request to get complementary values
4805
+        if (is_array($optionsArray) && count($optionsArray) > 0)
4806
+        {
4807
+            $sql = "SELECT rowid";
4808
+            foreach ($optionsArray as $name => $label)
4809
+            {
4810
+                if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4811
+                {
4812
+                    $sql.= ", ".$name;
4813
+                }
4814
+            }
4815
+            $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4816
+            $sql.= " WHERE fk_object = ".$rowid;
4817
+
4818
+            //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4819
+            $resql=$this->db->query($sql);
4820
+            if ($resql)
4821
+            {
4822
+                $this->array_options = array();
4823
+                $numrows=$this->db->num_rows($resql);
4824
+                if ($numrows)
4825
+                {
4826
+                    $tab = $this->db->fetch_array($resql);
4827
+
4828
+                    foreach ($tab as $key => $value)
4829
+                    {
4830
+                        // 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)
4831
+                        if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4832
+                        {
4833
+                            // we can add this attribute to object
4834
+                            if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4835
+                            {
4836
+                                //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4837
+                                $this->array_options["options_".$key]=$this->db->jdate($value);
4838
+                            }
4839
+                            else
4840
+                            {
4841
+                                $this->array_options["options_".$key]=$value;
4842
+                            }
4843
+
4844
+                            //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
4845
+                        }
4846
+                    }
4847
+                }
4848
+
4849
+                $this->db->free($resql);
4850
+
4851
+                if ($numrows) return $numrows;
4852
+                else return 0;
4853
+            }
4854
+            else
4855
+            {
4856
+                dol_print_error($this->db);
4857
+                return -1;
4858
+            }
4859
+        }
4860
+        return 0;
4861
+    }
4862
+
4863
+    /**
4864
+     *	Delete all extra fields values for the current object.
4865
+     *
4866
+     *  @return	int		<0 if KO, >0 if OK
4867
+     */
4868
+    function deleteExtraFields()
4869
+    {
4870
+        $this->db->begin();
4871
+
4872
+        $table_element = $this->table_element;
4873
+        if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4874
+
4875
+        $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4876
+        dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4877
+        $resql=$this->db->query($sql_del);
4878
+        if (! $resql)
4879
+        {
4880
+            $this->error=$this->db->lasterror();
4881
+            $this->db->rollback();
4882
+            return -1;
4883
+        }
4884
+        else
4885
+        {
4886
+            $this->db->commit();
4887
+            return 1;
4888
+        }
4889
+    }
4890
+
4891
+    /**
4892
+     *	Add/Update all extra fields values for the current object.
4893
+     *  Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
4894
+     *  This function delete record with all extrafields and insert them again from the array $this->array_options.
4895
+     *
4896
+     *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
4897
+     *  @param	User		$userused		Object user
4898
+     *  @return int 						-1=error, O=did nothing, 1=OK
4899
+     *  @see updateExtraField, setValueFrom
4900
+     */
4901
+    function insertExtraFields($trigger='', $userused=null)
4902
+    {
4903
+        global $conf,$langs,$user;
4904
+
4905
+        if (empty($userused)) $userused=$user;
4906
+
4907
+        $error=0;
4908
+
4909
+        if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
4910
+            return 0; // For avoid conflicts if trigger used
4911
+
4912
+        if (! empty($this->array_options))
4913
+        {
4914
+            // Check parameters
4915
+            $langs->load('admin');
4916
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4917
+            $extrafields = new ExtraFields($this->db);
4918
+            $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4919
+
4920
+            //Eliminate copied source object extra_fields that do not exist in target object
4921
+            $new_array_options=array();
4922
+            foreach ($this->array_options as $key => $value) {
4923
+                if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4924
+                    $new_array_options[$key] = $value;
4925
+                elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4926
+                    $new_array_options['options_'.$key] = $value;
4927
+            }
4928
+
4929
+            foreach($new_array_options as $key => $value)
4930
+            {
4931
+                    $attributeKey      = substr($key,8);   // Remove 'options_' prefix
4932
+                    $attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4933
+                    $attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4934
+                    $attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
4935
+                    $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
4936
+
4937
+                    if ($attributeRequired)
4938
+                    {
4939
+                        $mandatorypb=false;
4940
+                        if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4941
+                        if ($this->array_options[$key] === '') $mandatorypb=true;
4942
+                        if ($mandatorypb)
4943
+                        {
4944
+                            dol_syslog($this->error);
4945
+                            $this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4946
+                            return -1;
4947
+                        }
4948
+                    }
4949
+
4950
+                //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
4951
+                //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
4952
+
4953
+                    switch ($attributeType)
4954
+                    {
4955
+                        case 'int':
4956
+                          if (!is_numeric($value) && $value!='')
4957
+                            {
4958
+                                $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4959
+                                return -1;
4960
+                            }
4961
+                            elseif ($value=='')
4962
+                            {
4963
+                                $new_array_options[$key] = null;
4964
+                            }
4965
+                            break;
4966
+                    case 'double':
4967
+                        $value = price2num($value);
4968
+                        if (!is_numeric($value) && $value!='')
4969
+                        {
4970
+                            dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4971
+                            $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4972
+                            return -1;
4973
+                        }
4974
+                        elseif ($value=='')
4975
+                        {
4976
+                            $new_array_options[$key] = null;
4977
+                        }
4978
+                        //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
4979
+                        $new_array_options[$key] = $value;
4980
+                        break;
4981
+                        /*case 'select':	// Not required, we chosed value='0' for undefined values
4982
+             			if ($value=='-1')
4983
+             			{
4984
+             				$this->array_options[$key] = null;
4985
+             			}
4986
+             			break;*/
4987
+                        case 'password':
4988
+                           $algo='';
4989
+                            if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4990
+                            {
4991
+                                // If there is an encryption choice, we use it to crypt data before insert
4992
+                                $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4993
+                                $algo=reset($tmparrays);
4994
+                                if ($algo != '')
4995
+                                {
4996
+                                    //global $action;		// $action may be 'create', 'update', 'update_extras'...
4997
+                                    //var_dump($action);
4998
+                                    //var_dump($this->oldcopy);exit;
4999
+                                    if (is_object($this->oldcopy))		// If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
5000
+                                    {
5001
+                                        //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
5002
+                                        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.
5003
+                                        {
5004
+                                            $new_array_options[$key] = $this->array_options[$key];	// Value is kept
5005
+                                        }
5006
+                                    else
5007
+                                    {
5008
+                                        // var_dump($algo);
5009
+                                        $newvalue = dol_hash($this->array_options[$key], $algo);
5010
+                                        $new_array_options[$key] = $newvalue;
5011
+                                    }
5012
+                                    }
5013
+                                    else
5014
+                                    {
5015
+                                        $new_array_options[$key] = $this->array_options[$key];	// Value is kept
5016
+                                    }
5017
+                                }
5018
+                            }
5019
+                            else	// Common usage
5020
+                            {
5021
+                                $new_array_options[$key] = $this->array_options[$key];
5022
+                            }
5023
+                            break;
5024
+                        case 'price':
5025
+                        $new_array_options[$key] = price2num($this->array_options[$key]);
5026
+                        break;
5027
+                    case 'date':
5028
+                        $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5029
+                        break;
5030
+                    case 'datetime':
5031
+                        // If data is a string instead of a timestamp, we convert it
5032
+                        if (! is_int($this->array_options[$key])) {
5033
+                            $this->array_options[$key] = strtotime($this->array_options[$key]);
5034
+                        }
5035
+                        $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5036
+                        break;
5037
+                        case 'link':
5038
+                        $param_list=array_keys($attributeParam['options']);
5039
+                        // 0 : ObjectName
5040
+                        // 1 : classPath
5041
+                        $InfoFieldList = explode(":", $param_list[0]);
5042
+                        dol_include_once($InfoFieldList[1]);
5043
+                        if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5044
+                        {
5045
+                            if ($value == '-1')	// -1 is key for no defined in combo list of objects
5046
+                            {
5047
+                                $new_array_options[$key]='';
5048
+                            }
5049
+                            elseif ($value)
5050
+                            {
5051
+                                $object = new $InfoFieldList[0]($this->db);
5052
+                                if (is_numeric($value)) $res=$object->fetch($value);
5053
+                                else $res=$object->fetch('',$value);
5054
+
5055
+                                if ($res > 0) $new_array_options[$key]=$object->id;
5056
+                                else
5057
+                                {
5058
+                                    $this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5059
+                                    $this->db->rollback();
5060
+                                    return -1;
5061
+                                }
5062
+                            }
5063
+                        }
5064
+                        else
5065
+                        {
5066
+                            dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5067
+                        }
5068
+                        break;
5069
+                    }
5070
+            }
5071
+
5072
+            $this->db->begin();
5073
+
5074
+            $table_element = $this->table_element;
5075
+            if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5076
+
5077
+            $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5078
+            dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
5079
+            $this->db->query($sql_del);
5080
+
5081
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5082
+            foreach($new_array_options as $key => $value)
5083
+            {
5084
+                $attributeKey = substr($key,8);   // Remove 'options_' prefix
5085
+                // Add field of attribut
5086
+                if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5087
+                    $sql.=",".$attributeKey;
5088
+            }
5089
+            $sql .= ") VALUES (".$this->id;
5090
+
5091
+            foreach($new_array_options as $key => $value)
5092
+            {
5093
+                $attributeKey = substr($key,8);   // Remove 'options_' prefix
5094
+                // Add field of attribute
5095
+                if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5096
+                {
5097
+                    if ($new_array_options[$key] != '')
5098
+                    {
5099
+                        $sql.=",'".$this->db->escape($new_array_options[$key])."'";
5100
+                    }
5101
+                    else
5102
+                    {
5103
+                        $sql.=",null";
5104
+                    }
5105
+                }
5106
+            }
5107
+            $sql.=")";
5108
+
5109
+            dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5110
+            $resql = $this->db->query($sql);
5111
+            if (! $resql)
5112
+            {
5113
+                $this->error=$this->db->lasterror();
5114
+                $error++;
5115
+            }
5116
+
5117
+            if (! $error && $trigger)
5118
+            {
5119
+                // Call trigger
5120
+                $this->context=array('extrafieldaddupdate'=>1);
5121
+                $result=$this->call_trigger($trigger, $userused);
5122
+                if ($result < 0) $error++;
5123
+                // End call trigger
5124
+            }
5125
+
5126
+            if ($error)
5127
+            {
5128
+                $this->db->rollback();
5129
+                return -1;
5130
+            }
5131
+            else
5132
+            {
5133
+                $this->db->commit();
5134
+                return 1;
5135
+            }
5136
+        }
5137
+        else return 0;
5138
+    }
5139
+
5140
+    /**
5141
+     *	Update an extra field value for the current object.
5142
+     *  Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
5143
+     *
5144
+     *  @param  string      $key    		Key of the extrafield (without starting 'options_')
5145
+     *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
5146
+     *  @param	User		$userused		Object user
5147
+     *  @return int                 		-1=error, O=did nothing, 1=OK
5148
+     *  @see setValueFrom, insertExtraFields
5149
+     */
5150
+    function updateExtraField($key, $trigger=null, $userused=null)
5151
+    {
5152
+        global $conf,$langs,$user;
5153
+
5154
+        if (empty($userused)) $userused=$user;
5155
+
5156
+        $error=0;
5157
+
5158
+        if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
5159
+            return 0; // For avoid conflicts if trigger used
5160
+
5161
+        if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5162
+        {
5163
+            // Check parameters
5164
+            $langs->load('admin');
5165
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5166
+            $extrafields = new ExtraFields($this->db);
5167
+            $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5168
+
5169
+            $value=$this->array_options["options_".$key];
5170
+
5171
+            $attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5172
+            $attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
5173
+            $attributeParam    = $extrafields->attributes[$this->table_element]['param'][$key];
5174
+            $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
5175
+
5176
+            //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
5177
+            //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
5178
+
5179
+            switch ($attributeType)
5180
+            {
5181
+                case 'int':
5182
+                    if (!is_numeric($value) && $value!='')
5183
+                    {
5184
+                        $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5185
+                        return -1;
5186
+                    }
5187
+                    elseif ($value=='')
5188
+                    {
5189
+                        $this->array_options["options_".$key] = null;
5190
+                    }
5191
+                    break;
5192
+                case 'double':
5193
+                    $value = price2num($value);
5194
+                    if (!is_numeric($value) && $value!='')
5195
+                    {
5196
+                        dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5197
+                        $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5198
+                        return -1;
5199
+                    }
5200
+                    elseif ($value=='')
5201
+                    {
5202
+                        $this->array_options["options_".$key] = null;
5203
+                    }
5204
+                    //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
5205
+                    $this->array_options["options_".$key] = $value;
5206
+                    break;
5207
+                    /*case 'select':	// Not required, we chosed value='0' for undefined values
5208
+             		if ($value=='-1')
5209
+             		{
5210
+             			$this->array_options[$key] = null;
5211
+             		}
5212
+             		break;*/
5213
+                case 'price':
5214
+                    $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5215
+                    break;
5216
+                case 'date':
5217
+                    $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5218
+                    break;
5219
+                case 'datetime':
5220
+                    $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5221
+                    break;
5222
+                case 'link':
5223
+                    $param_list=array_keys($attributeParam['options']);
5224
+                    // 0 : ObjectName
5225
+                    // 1 : classPath
5226
+                    $InfoFieldList = explode(":", $param_list[0]);
5227
+                    dol_include_once($InfoFieldList[1]);
5228
+                    if ($value)
5229
+                    {
5230
+                        $object = new $InfoFieldList[0]($this->db);
5231
+                        $object->fetch(0,$value);
5232
+                        $this->array_options["options_".$key]=$object->id;
5233
+                    }
5234
+                    break;
5235
+            }
5236
+
5237
+            $this->db->begin();
5238
+            $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5239
+            $sql .= " WHERE fk_object = ".$this->id;
5240
+            $resql = $this->db->query($sql);
5241
+            if (! $resql)
5242
+            {
5243
+                $error++;
5244
+                $this->error=$this->db->lasterror();
5245
+            }
5246
+
5247
+            if (! $error && $trigger)
5248
+            {
5249
+                // Call trigger
5250
+                $this->context=array('extrafieldupdate'=>1);
5251
+                $result=$this->call_trigger($trigger, $userused);
5252
+                if ($result < 0) $error++;
5253
+                // End call trigger
5254
+            }
5255
+
5256
+            if ($error)
5257
+            {
5258
+                dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5259
+                $this->db->rollback();
5260
+                return -1;
5261
+            }
5262
+            else
5263
+            {
5264
+                $this->db->commit();
5265
+                return 1;
5266
+            }
5267
+        }
5268
+        else return 0;
5269
+    }
5270
+
5271
+
5272
+    /**
5273
+     * Return HTML string to put an input field into a page
5274
+     * Code very similar with showInputField of extra fields
5275
+     *
5276
+     * @param  array   		$val	       Array of properties for field to show
5277
+     * @param  string  		$key           Key of attribute
5278
+     * @param  string  		$value         Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
5279
+     * @param  string  		$moreparam     To add more parameters on html input tag
5280
+     * @param  string  		$keysuffix     Prefix string to add into name and id of field (can be used to avoid duplicate names)
5281
+     * @param  string  		$keyprefix     Suffix string to add into name and id of field (can be used to avoid duplicate names)
5282
+     * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5283
+     * @return string
5284
+     */
5285
+    function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5286
+    {
5287
+        global $conf,$langs,$form;
5288
+
5289
+        if (! is_object($form))
5290
+        {
5291
+            require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5292
+            $form=new Form($this->db);
5293
+        }
5294
+
5295
+        $val=$this->fields[$key];
5296
+
5297
+        $out='';
5298
+        $type='';
5299
+        $param = array();
5300
+        $param['options']=array();
5301
+        $size =$this->fields[$key]['size'];
5302
+        // Because we work on extrafields
5303
+        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5304
+            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5305
+            $type ='link';
5306
+        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5307
+            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5308
+            $type ='link';
5309
+        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5310
+            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5311
+            $type ='sellist';
5312
+        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5313
+            $param['options']=array();
5314
+            $type ='varchar';
5315
+            $size=$reg[1];
5316
+        } elseif(preg_match('/varchar/', $val['type'])) {
5317
+            $param['options']=array();
5318
+            $type ='varchar';
5319
+        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5320
+            $param['options']=$this->fields[$key]['arrayofkeyval'];
5321
+            $type ='select';
5322
+        } else {
5323
+            $param['options']=array();
5324
+            $type =$this->fields[$key]['type'];
5325
+        }
5326
+
5327
+        $label=$this->fields[$key]['label'];
5328
+        //$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5329
+        $default=$this->fields[$key]['default'];
5330
+        $computed=$this->fields[$key]['computed'];
5331
+        $unique=$this->fields[$key]['unique'];
5332
+        $required=$this->fields[$key]['required'];
5333
+
5334
+        $langfile=$this->fields[$key]['langfile'];
5335
+        $list=$this->fields[$key]['list'];
5336
+        $hidden=abs($this->fields[$key]['visible'])!=1?1:0;
5337
+
5338
+        $objectid = $this->id;
5339
+
5340
+
5341
+        if ($computed)
5342
+        {
5343
+            if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5344
+            else return '';
5345
+        }
5346
+
5347
+
5348
+        // Use in priority showsize from parameters, then $val['css'] then autodefine
5349
+        if (empty($morecss) && ! empty($val['css']))
5350
+        {
5351
+            $showsize = $val['css'];
5352
+        }
5353
+        if (empty($morecss))
5354
+        {
5355
+            if ($type == 'date')
5356
+            {
5357
+                $morecss = 'minwidth100imp';
5358
+            }
5359
+            elseif ($type == 'datetime')
5360
+            {
5361
+                $morecss = 'minwidth200imp';
5362
+            }
5363
+            elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5364
+            {
5365
+                $morecss = 'maxwidth75';
5366
+                        }elseif ($type == 'url')
5367
+            {
5368
+                $morecss='minwidth400';
5369
+            }
5370
+            elseif ($type == 'boolean')
5371
+            {
5372
+                $morecss='';
5373
+            }
5374
+            else
5375
+            {
5376
+                if (round($size) < 12)
5377
+                {
5378
+                    $morecss = 'minwidth100';
5379
+                }
5380
+                else if (round($size) <= 48)
5381
+                {
5382
+                    $morecss = 'minwidth200';
5383
+                }
5384
+                else
5385
+                {
5386
+                    $morecss = 'minwidth400';
5387
+                }
5388
+            }
5389
+        }
5390
+
5391
+        if (in_array($type,array('date','datetime')))
5392
+        {
5393
+            $tmp=explode(',',$size);
5394
+            $newsize=$tmp[0];
5395
+
5396
+            $showtime = in_array($type,array('datetime')) ? 1 : 0;
5397
+
5398
+            // Do not show current date when field not required (see selectDate() method)
5399
+            if (!$required && $value == '') $value = '-1';
5400
+
5401
+            // TODO Must also support $moreparam
5402
+            $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5403
+        }
5404
+        elseif (in_array($type,array('int','integer')))
5405
+        {
5406
+            $tmp=explode(',',$size);
5407
+            $newsize=$tmp[0];
5408
+            $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:'').'>';
5409
+        }
5410
+        elseif (preg_match('/varchar/', $type))
5411
+        {
5412
+            $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:'').'>';
5413
+        }
5414
+        elseif (in_array($type, array('mail', 'phone', 'url')))
5415
+        {
5416
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5417
+        }
5418
+        elseif ($type == 'text')
5419
+        {
5420
+            if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5421
+            {
5422
+                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5423
+                $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5424
+                $out=$doleditor->Create(1);
5425
+            }
5426
+            else
5427
+            {
5428
+                $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5429
+            }
5430
+        }
5431
+        elseif ($type == 'html')
5432
+        {
5433
+            if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5434
+            {
5435
+                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5436
+                $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%');
5437
+                $out=$doleditor->Create(1);
5438
+            }
5439
+            else
5440
+            {
5441
+                $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5442
+            }
5443
+        }
5444
+        elseif ($type == 'boolean')
5445
+        {
5446
+            $checked='';
5447
+            if (!empty($value)) {
5448
+                $checked=' checked value="1" ';
5449
+            } else {
5450
+                $checked=' value="1" ';
5451
+            }
5452
+            $out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5453
+        }
5454
+        elseif ($type == 'price')
5455
+        {
5456
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5457
+                $value=price($value);
5458
+            }
5459
+            $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);
5460
+        }
5461
+        elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5462
+        {
5463
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5464
+                $value=price($value);
5465
+            }
5466
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5467
+        }
5468
+        elseif ($type == 'select')
5469
+        {
5470
+            $out = '';
5471
+            if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5472
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5473
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5474
+            }
5475
+
5476
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5477
+                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5478
+            foreach ($param['options'] as $key => $val)
5479
+            {
5480
+                if ((string) $key == '') continue;
5481
+                list($val, $parent) = explode('|', $val);
5482
+                $out.='<option value="'.$key.'"';
5483
+                $out.= (((string) $value == (string) $key)?' selected':'');
5484
+                $out.= (!empty($parent)?' parent="'.$parent.'"':'');
5485
+                $out.='>'.$val.'</option>';
5486
+            }
5487
+            $out.='</select>';
5488
+        }
5489
+        elseif ($type == 'sellist')
5490
+        {
5491
+            $out = '';
5492
+            if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5493
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5494
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5495
+            }
5496
+
5497
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5498
+            if (is_array($param['options']))
5499
+            {
5500
+                $param_list=array_keys($param['options']);
5501
+                $InfoFieldList = explode(":", $param_list[0]);
5502
+                $parentName='';
5503
+                $parentField='';
5504
+                // 0 : tableName
5505
+                // 1 : label field name
5506
+                // 2 : key fields name (if differ of rowid)
5507
+                // 3 : key field parent (for dependent lists)
5508
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5509
+                $keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5510
+
5511
+
5512
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5513
+                {
5514
+                    if (strpos($InfoFieldList[4], 'extra.') !== false)
5515
+                    {
5516
+                        $keyList='main.'.$InfoFieldList[2].' as rowid';
5517
+                    } else {
5518
+                        $keyList=$InfoFieldList[2].' as rowid';
5519
+                    }
5520
+                }
5521
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5522
+                {
5523
+                    list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5524
+                    $keyList.= ', '.$parentField;
5525
+                }
5526
+
5527
+                $fields_label = explode('|',$InfoFieldList[1]);
5528
+                if (is_array($fields_label))
5529
+                {
5530
+                    $keyList .=', ';
5531
+                    $keyList .= implode(', ', $fields_label);
5532
+                }
5533
+
5534
+                $sqlwhere='';
5535
+                $sql = 'SELECT '.$keyList;
5536
+                $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5537
+                if (!empty($InfoFieldList[4]))
5538
+                {
5539
+                    // can use SELECT request
5540
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5541
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5542
+                    }
5543
+
5544
+                    // current object id can be use into filter
5545
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5546
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5547
+                    } else {
5548
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5549
+                    }
5550
+                    //We have to join on extrafield table
5551
+                    if (strpos($InfoFieldList[4], 'extra')!==false)
5552
+                    {
5553
+                        $sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5554
+                        $sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5555
+                    }
5556
+                    else
5557
+                    {
5558
+                        $sqlwhere.= ' WHERE '.$InfoFieldList[4];
5559
+                    }
5560
+                }
5561
+                else
5562
+                {
5563
+                    $sqlwhere.= ' WHERE 1=1';
5564
+                }
5565
+                // Some tables may have field, some other not. For the moment we disable it.
5566
+                if (in_array($InfoFieldList[0],array('tablewithentity')))
5567
+                {
5568
+                    $sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5569
+                }
5570
+                $sql.=$sqlwhere;
5571
+                //print $sql;
5572
+
5573
+                $sql .= ' ORDER BY ' . implode(', ', $fields_label);
5574
+
5575
+                dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5576
+                $resql = $this->db->query($sql);
5577
+                if ($resql)
5578
+                {
5579
+                    $out.='<option value="0">&nbsp;</option>';
5580
+                    $num = $this->db->num_rows($resql);
5581
+                    $i = 0;
5582
+                    while ($i < $num)
5583
+                    {
5584
+                        $labeltoshow='';
5585
+                        $obj = $this->db->fetch_object($resql);
5586
+
5587
+                        // Several field into label (eq table:code|libelle:rowid)
5588
+                        $notrans = false;
5589
+                        $fields_label = explode('|',$InfoFieldList[1]);
5590
+                        if (is_array($fields_label))
5591
+                        {
5592
+                            $notrans = true;
5593
+                            foreach ($fields_label as $field_toshow)
5594
+                            {
5595
+                                $labeltoshow.= $obj->$field_toshow.' ';
5596
+                            }
5597
+                        }
5598
+                        else
5599
+                        {
5600
+                            $labeltoshow=$obj->{$InfoFieldList[1]};
5601
+                        }
5602
+                        $labeltoshow=dol_trunc($labeltoshow,45);
5603
+
5604
+                        if ($value == $obj->rowid)
5605
+                        {
5606
+                            foreach ($fields_label as $field_toshow)
5607
+                            {
5608
+                                $translabel=$langs->trans($obj->$field_toshow);
5609
+                                if ($translabel!=$obj->$field_toshow) {
5610
+                                    $labeltoshow=dol_trunc($translabel,18).' ';
5611
+                                }else {
5612
+                                    $labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5613
+                                }
5614
+                            }
5615
+                            $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5616
+                        }
5617
+                        else
5618
+                        {
5619
+                            if (! $notrans)
5620
+                            {
5621
+                                $translabel=$langs->trans($obj->{$InfoFieldList[1]});
5622
+                                if ($translabel!=$obj->{$InfoFieldList[1]}) {
5623
+                                    $labeltoshow=dol_trunc($translabel,18);
5624
+                                }
5625
+                                else {
5626
+                                    $labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5627
+                                }
5628
+                            }
5629
+                            if (empty($labeltoshow)) $labeltoshow='(not defined)';
5630
+                            if ($value==$obj->rowid)
5631
+                            {
5632
+                                $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5633
+                            }
5634
+
5635
+                            if (!empty($InfoFieldList[3]) && $parentField)
5636
+                            {
5637
+                                $parent = $parentName.':'.$obj->{$parentField};
5638
+                            }
5639
+
5640
+                            $out.='<option value="'.$obj->rowid.'"';
5641
+                            $out.= ($value==$obj->rowid?' selected':'');
5642
+                            $out.= (!empty($parent)?' parent="'.$parent.'"':'');
5643
+                            $out.='>'.$labeltoshow.'</option>';
5644
+                        }
5645
+
5646
+                        $i++;
5647
+                    }
5648
+                    $this->db->free($resql);
5649
+                }
5650
+                else {
5651
+                    print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5652
+                }
5653
+            }
5654
+            $out.='</select>';
5655
+        }
5656
+        elseif ($type == 'checkbox')
5657
+        {
5658
+            $value_arr=explode(',',$value);
5659
+            $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5660
+        }
5661
+        elseif ($type == 'radio')
5662
+        {
5663
+            $out='';
5664
+            foreach ($param['options'] as $keyopt => $val)
5665
+            {
5666
+                $out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5667
+                $out.=' value="'.$keyopt.'"';
5668
+                $out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5669
+                $out.= ($value==$keyopt?'checked':'');
5670
+                $out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5671
+            }
5672
+        }
5673
+        elseif ($type == 'chkbxlst')
5674
+        {
5675
+            if (is_array($value)) {
5676
+                $value_arr = $value;
5677
+            }
5678
+            else {
5679
+                $value_arr = explode(',', $value);
5680
+            }
5681
+
5682
+            if (is_array($param['options'])) {
5683
+                $param_list = array_keys($param['options']);
5684
+                $InfoFieldList = explode(":", $param_list[0]);
5685
+                $parentName='';
5686
+                $parentField='';
5687
+                // 0 : tableName
5688
+                // 1 : label field name
5689
+                // 2 : key fields name (if differ of rowid)
5690
+                // 3 : key field parent (for dependent lists)
5691
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5692
+                $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5693
+
5694
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5695
+                    list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5696
+                    $keyList .= ', ' . $parentField;
5697
+                }
5698
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5699
+                    if (strpos($InfoFieldList[4], 'extra.') !== false) {
5700
+                        $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5701
+                    } else {
5702
+                        $keyList = $InfoFieldList[2] . ' as rowid';
5703
+                    }
5704
+                }
5705
+
5706
+                $fields_label = explode('|', $InfoFieldList[1]);
5707
+                if (is_array($fields_label)) {
5708
+                    $keyList .= ', ';
5709
+                    $keyList .= implode(', ', $fields_label);
5710
+                }
5711
+
5712
+                $sqlwhere = '';
5713
+                $sql = 'SELECT ' . $keyList;
5714
+                $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5715
+                if (! empty($InfoFieldList[4])) {
5716
+
5717
+                    // can use SELECT request
5718
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5719
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5720
+                    }
5721
+
5722
+                    // current object id can be use into filter
5723
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5724
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5725
+                    } else {
5726
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5727
+                    }
5728
+
5729
+                    // We have to join on extrafield table
5730
+                    if (strpos($InfoFieldList[4], 'extra') !== false) {
5731
+                        $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5732
+                        $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5733
+                    } else {
5734
+                        $sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5735
+                    }
5736
+                } else {
5737
+                    $sqlwhere .= ' WHERE 1=1';
5738
+                }
5739
+                // Some tables may have field, some other not. For the moment we disable it.
5740
+                if (in_array($InfoFieldList[0], array ('tablewithentity')))
5741
+                {
5742
+                    $sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5743
+                }
5744
+                // $sql.=preg_replace('/^ AND /','',$sqlwhere);
5745
+                // print $sql;
5746
+
5747
+                $sql .= $sqlwhere;
5748
+                dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5749
+                $resql = $this->db->query($sql);
5750
+                if ($resql) {
5751
+                    $num = $this->db->num_rows($resql);
5752
+                    $i = 0;
5753
+
5754
+                    $data=array();
5755
+
5756
+                    while ( $i < $num ) {
5757
+                        $labeltoshow = '';
5758
+                        $obj = $this->db->fetch_object($resql);
5759
+
5760
+                        $notrans = false;
5761
+                        // Several field into label (eq table:code|libelle:rowid)
5762
+                        $fields_label = explode('|', $InfoFieldList[1]);
5763
+                        if (is_array($fields_label)) {
5764
+                            $notrans = true;
5765
+                            foreach ( $fields_label as $field_toshow ) {
5766
+                                $labeltoshow .= $obj->$field_toshow . ' ';
5767
+                            }
5768
+                        } else {
5769
+                            $labeltoshow = $obj->{$InfoFieldList[1]};
5770
+                        }
5771
+                        $labeltoshow = dol_trunc($labeltoshow, 45);
5772
+
5773
+                        if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5774
+                            foreach ( $fields_label as $field_toshow ) {
5775
+                                $translabel = $langs->trans($obj->$field_toshow);
5776
+                                if ($translabel != $obj->$field_toshow) {
5777
+                                    $labeltoshow = dol_trunc($translabel, 18) . ' ';
5778
+                                } else {
5779
+                                    $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5780
+                                }
5781
+                            }
5782
+
5783
+                            $data[$obj->rowid]=$labeltoshow;
5784
+                        } else {
5785
+                            if (! $notrans) {
5786
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
5787
+                                if ($translabel != $obj->{$InfoFieldList[1]}) {
5788
+                                    $labeltoshow = dol_trunc($translabel, 18);
5789
+                                } else {
5790
+                                    $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5791
+                                }
5792
+                            }
5793
+                            if (empty($labeltoshow))
5794
+                                $labeltoshow = '(not defined)';
5795
+
5796
+                                if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5797
+                                    $data[$obj->rowid]=$labeltoshow;
5798
+                                }
5799
+
5800
+                                if (! empty($InfoFieldList[3]) && $parentField) {
5801
+                                    $parent = $parentName . ':' . $obj->{$parentField};
5802
+                                }
5803
+
5804
+                                $data[$obj->rowid]=$labeltoshow;
5805
+                        }
5806
+
5807
+                        $i ++;
5808
+                    }
5809
+                    $this->db->free($resql);
5810
+
5811
+                    $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5812
+                } else {
5813
+                    print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5814
+                }
5815
+            }
5816
+        }
5817
+        elseif ($type == 'link')
5818
+        {
5819
+            $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5820
+            $showempty=(($required && $default != '')?0:1);
5821
+            $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5822
+            if (Globals::$conf->global->MAIN_FEATURES_LEVEL >= 2) {
5823
+                        list($class,$classfile)=explode(':',$param_list[0]);
5824
+                        if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5825
+                        else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5826
+                        $out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5827
+                        // TODO Add Javascript code to add input fields contents to new elements urls
5828
+            }
5829
+        }
5830
+        elseif ($type == 'password')
5831
+        {
5832
+            // If prefix is 'search_', field is used as a filter, we use a common text field.
5833
+            $out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5834
+        }
5835
+        elseif ($type == 'array')
5836
+        {
5837
+            $newval = $val;
5838
+            $newval['type'] = 'varchar(256)';
5839
+
5840
+            $out='';
5841
+
5842
+            $inputs = array();
5843
+            if(! empty($value)) {
5844
+                foreach($value as $option) {
5845
+                    $out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5846
+                    $out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5847
+                }
5848
+            }
5849
+
5850
+            $out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5851
+
5852
+            $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5853
+            $newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5854
+
5855
+            if (!empty(Globals::$conf->use_javascript_ajax)) {
5856
+                $out.= '
5857
+					<script type="text/javascript">
5858
+					$(document).ready(function() {
5859
+						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
5860
+							$("'.dol_escape_js($newInput).'").insertBefore(this);
5861
+						});
5862
+
5863
+						$(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
5864
+							$(this).parent().remove();
5865
+						});
5866
+					});
5867
+					</script>';
5868
+            }
5869
+        }
5870
+        if (!empty($hidden)) {
5871
+            $out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5872
+        }
5873
+        /* Add comments
5874
+		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
5875
+		 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
5876
+		 */
5877
+        return $out;
5878
+    }
5879
+
5880
+    /**
5881
+     * Return HTML string to show a field into a page
5882
+     * Code very similar with showOutputField of extra fields
5883
+     *
5884
+     * @param  array   $val		       Array of properties of field to show
5885
+     * @param  string  $key            Key of attribute
5886
+     * @param  string  $value          Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value)
5887
+     * @param  string  $moreparam      To add more parametes on html input tag
5888
+     * @param  string  $keysuffix      Prefix string to add into name and id of field (can be used to avoid duplicate names)
5889
+     * @param  string  $keyprefix      Suffix string to add into name and id of field (can be used to avoid duplicate names)
5890
+     * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5891
+     * @return string
5892
+     */
5893
+    function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5894
+    {
5895
+        global $conf,$langs,$form;
5896
+
5897
+        if (! is_object($form))
5898
+        {
5899
+            require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5900
+            $form=new Form($this->db);
5901
+        }
5902
+
5903
+        $objectid = $this->id;
5904
+        $label = $val['label'];
5905
+        $type  = $val['type'];
5906
+        $size  = $val['css'];
5907
+
5908
+        // Convert var to be able to share same code than showOutputField of extrafields
5909
+        if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5910
+        {
5911
+            $type = 'varchar';		// convert varchar(xx) int varchar
5912
+            $size = $reg[1];
5913
+        }
5914
+        elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5915
+        if (is_array($val['arrayofkeyval'])) $type='select';
5916
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5917
+
5918
+        $default=$val['default'];
5919
+        $computed=$val['computed'];
5920
+        $unique=$val['unique'];
5921
+        $required=$val['required'];
5922
+        $param=$val['param'];
5923
+        if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5924
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5925
+        {
5926
+            $type='link';
5927
+            $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5928
+        }
5929
+        $langfile=$val['langfile'];
5930
+        $list=$val['list'];
5931
+        $help=$val['help'];
5932
+        $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)
5933
+
5934
+        if ($hidden) return '';
5935
+
5936
+        // If field is a computed field, value must become result of compute
5937
+        if ($computed)
5938
+        {
5939
+            // Make the eval of compute string
5940
+            //var_dump($computed);
5941
+            $value = dol_eval($computed, 1, 0);
5942
+        }
5943
+
5944
+        if (empty($showsize))
5945
+        {
5946
+            if ($type == 'date')
5947
+            {
5948
+                //$showsize=10;
5949
+                $showsize = 'minwidth100imp';
5950
+            }
5951
+            elseif ($type == 'datetime')
5952
+            {
5953
+                //$showsize=19;
5954
+                $showsize = 'minwidth200imp';
5955
+            }
5956
+            elseif (in_array($type,array('int','double','price')))
5957
+            {
5958
+                //$showsize=10;
5959
+                $showsize = 'maxwidth75';
5960
+            }
5961
+            elseif ($type == 'url')
5962
+            {
5963
+                $showsize='minwidth400';
5964
+            }
5965
+            elseif ($type == 'boolean')
5966
+            {
5967
+                $showsize='';
5968
+            }
5969
+            else
5970
+            {
5971
+                if (round($size) < 12)
5972
+                {
5973
+                    $showsize = 'minwidth100';
5974
+                }
5975
+                else if (round($size) <= 48)
5976
+                {
5977
+                    $showsize = 'minwidth200';
5978
+                }
5979
+                else
5980
+                {
5981
+                    //$showsize=48;
5982
+                    $showsize = 'minwidth400';
5983
+                }
5984
+            }
5985
+        }
5986
+
5987
+        // Format output value differently according to properties of field
5988
+        if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5989
+        elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5990
+        elseif ($type == 'date')
5991
+        {
5992
+            if(! empty($value)) {
5993
+                $value=dol_print_date($value,'day');
5994
+            } else {
5995
+                $value='';
5996
+            }
5997
+        }
5998
+        elseif ($type == 'datetime')
5999
+        {
6000
+            if(! empty($value)) {
6001
+                $value=dol_print_date($value,'dayhour');
6002
+            } else {
6003
+                $value='';
6004
+            }
6005
+        }
6006
+        elseif ($type == 'double')
6007
+        {
6008
+            if (!empty($value)) {
6009
+                $value=price($value);
6010
+            }
6011
+        }
6012
+        elseif ($type == 'boolean')
6013
+        {
6014
+            $checked='';
6015
+            if (!empty($value)) {
6016
+                $checked=' checked ';
6017
+            }
6018
+            $value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6019
+        }
6020
+        elseif ($type == 'mail')
6021
+        {
6022
+            $value=dol_print_email($value,0,0,0,64,1,1);
6023
+        }
6024
+        elseif ($type == 'url')
6025
+        {
6026
+            $value=dol_print_url($value,'_blank',32,1);
6027
+        }
6028
+        elseif ($type == 'phone')
6029
+        {
6030
+            $value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6031
+        }
6032
+        elseif ($type == 'price')
6033
+        {
6034
+            $value = price($value, 0, $langs, 0, 0, -1, Globals::$conf->currency);
6035
+        }
6036
+        elseif ($type == 'select')
6037
+        {
6038
+            $value=$param['options'][$value];
6039
+        }
6040
+        elseif ($type == 'sellist')
6041
+        {
6042
+            $param_list=array_keys($param['options']);
6043
+            $InfoFieldList = explode(":", $param_list[0]);
6044
+
6045
+            $selectkey="rowid";
6046
+            $keyList='rowid';
6047
+
6048
+            if (count($InfoFieldList)>=3)
6049
+            {
6050
+                $selectkey = $InfoFieldList[2];
6051
+                $keyList=$InfoFieldList[2].' as rowid';
6052
+            }
6053
+
6054
+            $fields_label = explode('|',$InfoFieldList[1]);
6055
+            if(is_array($fields_label)) {
6056
+                $keyList .=', ';
6057
+                $keyList .= implode(', ', $fields_label);
6058
+            }
6059
+
6060
+            $sql = 'SELECT '.$keyList;
6061
+            $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6062
+            if (strpos($InfoFieldList[4], 'extra')!==false)
6063
+            {
6064
+                $sql.= ' as main';
6065
+            }
6066
+            if ($selectkey=='rowid' && empty($value)) {
6067
+                $sql.= " WHERE ".$selectkey."=0";
6068
+            } elseif ($selectkey=='rowid') {
6069
+                $sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6070
+            }else {
6071
+                $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6072
+            }
6073
+
6074
+            //$sql.= ' AND entity = '.Globals::$conf->entity;
6075
+
6076
+            dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
6077
+            $resql = $this->db->query($sql);
6078
+            if ($resql)
6079
+            {
6080
+                $value='';	// value was used, so now we reste it to use it to build final output
6081
+
6082
+                $obj = $this->db->fetch_object($resql);
6083
+
6084
+                // Several field into label (eq table:code|libelle:rowid)
6085
+                $fields_label = explode('|',$InfoFieldList[1]);
6086
+
6087
+                if(is_array($fields_label) && count($fields_label)>1)
6088
+                {
6089
+                    foreach ($fields_label as $field_toshow)
6090
+                    {
6091
+                        $translabel='';
6092
+                        if (!empty($obj->$field_toshow)) {
6093
+                            $translabel=$langs->trans($obj->$field_toshow);
6094
+                        }
6095
+                        if ($translabel!=$field_toshow) {
6096
+                            $value.=dol_trunc($translabel,18).' ';
6097
+                        }else {
6098
+                            $value.=$obj->$field_toshow.' ';
6099
+                        }
6100
+                    }
6101
+                }
6102
+                else
6103
+                {
6104
+                    $translabel='';
6105
+                    if (!empty($obj->{$InfoFieldList[1]})) {
6106
+                        $translabel=$langs->trans($obj->{$InfoFieldList[1]});
6107
+                    }
6108
+                    if ($translabel!=$obj->{$InfoFieldList[1]}) {
6109
+                        $value=dol_trunc($translabel,18);
6110
+                    }else {
6111
+                        $value=$obj->{$InfoFieldList[1]};
6112
+                    }
6113
+                }
6114
+            }
6115
+            else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6116
+        }
6117
+        elseif ($type == 'radio')
6118
+        {
6119
+            $value=$param['options'][$value];
6120
+        }
6121
+        elseif ($type == 'checkbox')
6122
+        {
6123
+            $value_arr=explode(',',$value);
6124
+            $value='';
6125
+            if (is_array($value_arr) && count($value_arr)>0)
6126
+            {
6127
+                foreach ($value_arr as $keyval=>$valueval) {
6128
+                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6129
+                }
6130
+                $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6131
+            }
6132
+        }
6133
+        elseif ($type == 'chkbxlst')
6134
+        {
6135
+            $value_arr = explode(',', $value);
6136
+
6137
+            $param_list = array_keys($param['options']);
6138
+            $InfoFieldList = explode(":", $param_list[0]);
6139
+
6140
+            $selectkey = "rowid";
6141
+            $keyList = 'rowid';
6142
+
6143
+            if (count($InfoFieldList) >= 3) {
6144
+                $selectkey = $InfoFieldList[2];
6145
+                $keyList = $InfoFieldList[2] . ' as rowid';
6146
+            }
6147
+
6148
+            $fields_label = explode('|', $InfoFieldList[1]);
6149
+            if (is_array($fields_label)) {
6150
+                $keyList .= ', ';
6151
+                $keyList .= implode(', ', $fields_label);
6152
+            }
6153
+
6154
+            $sql = 'SELECT ' . $keyList;
6155
+            $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6156
+            if (strpos($InfoFieldList[4], 'extra') !== false) {
6157
+                $sql .= ' as main';
6158
+            }
6159
+            // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6160
+            // $sql.= ' AND entity = '.Globals::$conf->entity;
6161
+
6162
+            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6163
+            $resql = $this->db->query($sql);
6164
+            if ($resql) {
6165
+                $value = ''; // value was used, so now we reste it to use it to build final output
6166
+                $toprint=array();
6167
+                while ( $obj = $this->db->fetch_object($resql) ) {
6168
+
6169
+                    // Several field into label (eq table:code|libelle:rowid)
6170
+                    $fields_label = explode('|', $InfoFieldList[1]);
6171
+                    if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6172
+                        if (is_array($fields_label) && count($fields_label) > 1) {
6173
+                            foreach ( $fields_label as $field_toshow ) {
6174
+                                $translabel = '';
6175
+                                if (! empty($obj->$field_toshow)) {
6176
+                                    $translabel = $langs->trans($obj->$field_toshow);
6177
+                                }
6178
+                                if ($translabel != $field_toshow) {
6179
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6180
+                                } else {
6181
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6182
+                                }
6183
+                            }
6184
+                        } else {
6185
+                            $translabel = '';
6186
+                            if (! empty($obj->{$InfoFieldList[1]})) {
6187
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
6188
+                            }
6189
+                            if ($translabel != $obj->{$InfoFieldList[1]}) {
6190
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6191
+                            } else {
6192
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6193
+                            }
6194
+                        }
6195
+                    }
6196
+                }
6197
+                $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6198
+            } else {
6199
+                dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6200
+            }
6201
+        }
6202
+        elseif ($type == 'link')
6203
+        {
6204
+            $out='';
6205
+
6206
+            // only if something to display (perf)
6207
+            if ($value)
6208
+            {
6209
+                $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6210
+
6211
+                $InfoFieldList = explode(":", $param_list[0]);
6212
+                $classname=$InfoFieldList[0];
6213
+                $classpath=$InfoFieldList[1];
6214
+                $getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6215
+                if (! empty($classpath))
6216
+                {
6217
+                    dol_include_once($InfoFieldList[1]);
6218
+                    if ($classname && class_exists($classname))
6219
+                    {
6220
+                        $object = new $classname($this->db);
6221
+                        $object->fetch($value);
6222
+                        $value=$object->getNomUrl($getnomurlparam);
6223
+                    }
6224
+                }
6225
+                else
6226
+                {
6227
+                    dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6228
+                    return 'Error bad setup of extrafield';
6229
+                }
6230
+            }
6231
+            else $value='';
6232
+        }
6233
+        elseif ($type == 'text' || $type == 'html')
6234
+        {
6235
+            $value=dol_htmlentitiesbr($value);
6236
+        }
6237
+        elseif ($type == 'password')
6238
+        {
6239
+            $value=preg_replace('/./i','*',$value);
6240
+        }
6241
+        elseif ($type == 'array')
6242
+        {
6243
+            $value = implode('<br>', $value);
6244
+        }
6245
+
6246
+        //print $type.'-'.$size;
6247
+        $out=$value;
6248
+
6249
+        return $out;
6250
+    }
6251
+
6252
+
6253
+    /**
6254
+     * Function to show lines of extrafields with output datas
6255
+     *
6256
+     * @param 	Extrafields $extrafields    Extrafield Object
6257
+     * @param 	string      $mode           Show output (view) or input (edit) for extrafield
6258
+     * @param 	array       $params         Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
6259
+     * @param 	string      $keysuffix      Suffix string to add after name and id of field (can be used to avoid duplicate names)
6260
+     * @param 	string      $keyprefix      Prefix string to add before name and id of field (can be used to avoid duplicate names)
6261
+     * @param	string		$onetrtd		All fields in same tr td
6262
+     * @return 	string
6263
+     */
6264
+    function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6265
+    {
6266
+        global $db, $conf, $langs, $action, $form;
6267
+
6268
+        if (! is_object($form)) $form=new Form($db);
6269
+
6270
+        $out = '';
6271
+
6272
+        if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
6273
+        {
6274
+            $out .= "\n";
6275
+            $out .= '<!-- showOptionalsInput --> ';
6276
+            $out .= "\n";
6277
+
6278
+            $e = 0;
6279
+            foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6280
+            {
6281
+                // Show only the key field in params
6282
+                if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6283
+
6284
+                $enabled = 1;
6285
+                if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
6286
+                {
6287
+                    $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
6288
+                }
6289
+
6290
+                $perms = 1;
6291
+                if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
6292
+                {
6293
+                    $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6294
+                }
6295
+
6296
+                if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6297
+                if (empty($perms)) continue;
6298
+
6299
+                // Load language if required
6300
+                if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6301
+
6302
+                $colspan='3';
6303
+                if (is_array($params) && count($params)>0) {
6304
+                    if (array_key_exists('colspan',$params)) {
6305
+                        $colspan=$params['colspan'];
6306
+                    }
6307
+                }
6308
+
6309
+                switch($mode) {
6310
+                    case "view":
6311
+                        $value=$this->array_options["options_".$key.$keysuffix];
6312
+                        break;
6313
+                    case "edit":
6314
+                        $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6315
+                        // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6316
+                        if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6317
+                        {
6318
+                            if (is_array($getposttemp)) {
6319
+                                // $getposttemp is an array but following code expects a comma separated string
6320
+                                $value = implode(",", $getposttemp);
6321
+                            } else {
6322
+                                $value = $getposttemp;
6323
+                            }
6324
+                        } else {
6325
+                            $value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6326
+                        }
6327
+                        //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6328
+                        break;
6329
+                }
6330
+
6331
+                if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6332
+                {
6333
+                    $out .= $extrafields->showSeparator($key, $this);
6334
+                }
6335
+                else
6336
+                {
6337
+                    $csstyle='';
6338
+                    $class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6339
+                    if (is_array($params) && count($params)>0) {
6340
+                        if (array_key_exists('style',$params)) {
6341
+                            $csstyle=$params['style'];
6342
+                        }
6343
+                    }
6344
+
6345
+                    // add html5 elements
6346
+                    $domData  = ' data-element="extrafield"';
6347
+                    $domData .= ' data-targetelement="'.$this->element.'"';
6348
+                    $domData .= ' data-targetid="'.$this->id.'"';
6349
+
6350
+                    $html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : '';
6351
+
6352
+                    $out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
6353
+
6354
+                    if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
6355
+                        if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
6356
+                            $colspan = '0';
6357
+                        }
6358
+                    }
6359
+
6360
+                    if ($action == 'selectlines') { $colspan++; }
6361
+
6362
+                    // Convert date into timestamp format (value in memory must be a timestamp)
6363
+                    if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6364
+                    {
6365
+                        $datenotinstring = $this->array_options['options_' . $key];
6366
+                        if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6367
+                        {
6368
+                            $datenotinstring = $this->db->jdate($datenotinstring);
6369
+                        }
6370
+                        $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;
6371
+                    }
6372
+                    // Convert float submited string into real php numeric (value in memory must be a php numeric)
6373
+                    if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6374
+                    {
6375
+                        $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6376
+                    }
6377
+
6378
+                    $labeltoshow = $langs->trans($label);
6379
+
6380
+                    $out .= '<td class="titlefield';
6381
+                    if (GETPOST('action','none') == 'create') $out.='create';
6382
+                    if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6383
+                    $out .= '">';
6384
+                    if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6385
+                    else $out .= $labeltoshow;
6386
+                    $out .= '</td>';
6387
+
6388
+                    $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6389
+                    $out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6390
+
6391
+                    switch($mode) {
6392
+                        case "view":
6393
+                            $out .= $extrafields->showOutputField($key, $value);
6394
+                            break;
6395
+                        case "edit":
6396
+                            $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id);
6397
+                            break;
6398
+                    }
6399
+
6400
+                    $out .= '</td>';
6401
+
6402
+                    if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1))
6403
+                        $out .= '</tr>';
6404
+                    else $out .= '</tr>';
6405
+                    $e++;
6406
+                }
6407
+            }
6408
+            $out .= "\n";
6409
+            // Add code to manage list depending on others
6410
+            if (!empty(Globals::$conf->use_javascript_ajax)) {
6411
+                $out .= '
6412
+				<script type="text/javascript">
6413
+				    jQuery(document).ready(function() {
6414
+				    	function showOptions(child_list, parent_list)
6415
+				    	{
6416
+				    		var val = $("select[name=\"options_"+parent_list+"\"]").val();
6417
+				    		var parentVal = parent_list + ":" + val;
6418
+							if(val > 0) {
6419
+					    		$("select[name=\""+child_list+"\"] option[parent]").hide();
6420
+					    		$("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
6421
+							} else {
6422
+								$("select[name=\""+child_list+"\"] option").show();
6423
+							}
6424
+				    	}
6425
+						function setListDependencies() {
6426
+					    	jQuery("select option[parent]").parent().each(function() {
6427
+					    		var child_list = $(this).attr("name");
6428
+								var parent = $(this).find("option[parent]:first").attr("parent");
6429
+								var infos = parent.split(":");
6430
+								var parent_list = infos[0];
6431
+								$("select[name=\""+parent_list+"\"]").change(function() {
6432
+									showOptions(child_list, parent_list);
6433
+								});
6434
+					    	});
6099 6435
 						}
6100
-					}
6101
-				}
6102
-				else
6103
-				{
6104
-					$translabel='';
6105
-					if (!empty($obj->{$InfoFieldList[1]})) {
6106
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
6107
-					}
6108
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6109
-						$value=dol_trunc($translabel,18);
6110
-					}else {
6111
-						$value=$obj->{$InfoFieldList[1]};
6112
-					}
6113
-				}
6114
-			}
6115
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6116
-		}
6117
-		elseif ($type == 'radio')
6118
-		{
6119
-			$value=$param['options'][$value];
6120
-		}
6121
-		elseif ($type == 'checkbox')
6122
-		{
6123
-			$value_arr=explode(',',$value);
6124
-			$value='';
6125
-			if (is_array($value_arr) && count($value_arr)>0)
6126
-			{
6127
-				foreach ($value_arr as $keyval=>$valueval) {
6128
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6129
-				}
6130
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6131
-			}
6132
-		}
6133
-		elseif ($type == 'chkbxlst')
6134
-		{
6135
-			$value_arr = explode(',', $value);
6136
-
6137
-			$param_list = array_keys($param['options']);
6138
-			$InfoFieldList = explode(":", $param_list[0]);
6139
-
6140
-			$selectkey = "rowid";
6141
-			$keyList = 'rowid';
6142
-
6143
-			if (count($InfoFieldList) >= 3) {
6144
-				$selectkey = $InfoFieldList[2];
6145
-				$keyList = $InfoFieldList[2] . ' as rowid';
6146
-			}
6147
-
6148
-			$fields_label = explode('|', $InfoFieldList[1]);
6149
-			if (is_array($fields_label)) {
6150
-				$keyList .= ', ';
6151
-				$keyList .= implode(', ', $fields_label);
6152
-			}
6153
-
6154
-			$sql = 'SELECT ' . $keyList;
6155
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6156
-			if (strpos($InfoFieldList[4], 'extra') !== false) {
6157
-				$sql .= ' as main';
6158
-			}
6159
-			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6160
-			// $sql.= ' AND entity = '.Globals::$conf->entity;
6161 6436
 
6162
-            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6163
-			$resql = $this->db->query($sql);
6164
-			if ($resql) {
6165
-				$value = ''; // value was used, so now we reste it to use it to build final output
6166
-				$toprint=array();
6167
-				while ( $obj = $this->db->fetch_object($resql) ) {
6168
-
6169
-					// Several field into label (eq table:code|libelle:rowid)
6170
-					$fields_label = explode('|', $InfoFieldList[1]);
6171
-					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6172
-						if (is_array($fields_label) && count($fields_label) > 1) {
6173
-							foreach ( $fields_label as $field_toshow ) {
6174
-								$translabel = '';
6175
-								if (! empty($obj->$field_toshow)) {
6176
-									$translabel = $langs->trans($obj->$field_toshow);
6177
-								}
6178
-								if ($translabel != $field_toshow) {
6179
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6180
-								} else {
6181
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6182
-								}
6183
-							}
6184
-						} else {
6185
-							$translabel = '';
6186
-							if (! empty($obj->{$InfoFieldList[1]})) {
6187
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6188
-							}
6189
-							if ($translabel != $obj->{$InfoFieldList[1]}) {
6190
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6191
-							} else {
6192
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6193
-							}
6194
-						}
6195
-					}
6196
-				}
6197
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6198
-			} else {
6199
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6200
-			}
6201
-		}
6202
-		elseif ($type == 'link')
6203
-		{
6204
-			$out='';
6205
-
6206
-			// only if something to display (perf)
6207
-			if ($value)
6208
-			{
6209
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6437
+						setListDependencies();
6438
+				    });
6439
+				</script>'."\n";
6440
+                $out .= '<!-- /showOptionalsInput --> '."\n";
6441
+            }
6442
+        }
6443
+        return $out;
6444
+    }
6445
+
6446
+
6447
+    /**
6448
+     * Returns the rights used for this class
6449
+     * @return stdClass
6450
+     */
6451
+    public function getRights()
6452
+    {
6453
+        global $user;
6454
+
6455
+        $element = $this->element;
6456
+        if ($element == 'facturerec') $element='facture';
6457
+
6458
+        return $user->rights->{$element};
6459
+    }
6460
+
6461
+    /**
6462
+     * Function used to replace a thirdparty id with another one.
6463
+     * This function is meant to be called from replaceThirdparty with the appropiate tables
6464
+     * Column name fk_soc MUST be used to identify thirdparties
6465
+     *
6466
+     * @param  DoliDB 	   $db 			  Database handler
6467
+     * @param  int 		   $origin_id     Old thirdparty id (the thirdparty to delete)
6468
+     * @param  int 		   $dest_id       New thirdparty id (the thirdparty that will received element of the other)
6469
+     * @param  string[]    $tables        Tables that need to be changed
6470
+     * @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)
6471
+     * @return bool						  True if success, False if error
6472
+     */
6473
+    public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6474
+    {
6475
+        foreach ($tables as $table)
6476
+        {
6477
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6478
+
6479
+            if (! $db->query($sql))
6480
+            {
6481
+                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.
6482
+                //$this->errors = $db->lasterror();
6483
+                return false;
6484
+            }
6485
+        }
6486
+
6487
+        return true;
6488
+    }
6489
+
6490
+    /**
6491
+     * Get buy price to use for margin calculation. This function is called when buy price is unknown.
6492
+     *	 Set buy price = sell price if ForceBuyingPriceIfNull configured,
6493
+     *   else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
6494
+     *	 else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
6495
+     *	 else set min buy price as buy price
6496
+     *
6497
+     * @param float		$unitPrice		 Product unit price
6498
+     * @param float		$discountPercent Line discount percent
6499
+     * @param int		$fk_product		 Product id
6500
+     * @return	float                    <0 if KO, buyprice if OK
6501
+     */
6502
+    public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
6503
+    {
6504
+        global $conf;
6505
+
6506
+        $buyPrice = 0;
6507
+
6508
+        if (($unitPrice > 0) && (isset(Globals::$conf->global->ForceBuyingPriceIfNull) && Globals::$conf->global->ForceBuyingPriceIfNull == 1)) { // In most cases, test here is false{
6509
+            $buyPrice = $unitPrice * (1 - $discountPercent / 100);
6510
+        }
6511
+        else
6512
+        {
6513
+            // Get cost price for margin calculation
6514
+            if (! empty($fk_product))
6515
+            {
6516
+                if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'costprice') {
6517
+                    require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6518
+                    $product = new Product($this->db);
6519
+                    $result = $product->fetch($fk_product);
6520
+                    if ($result <= 0)
6521
+                    {
6522
+                        $this->errors[] = 'ErrorProductIdDoesNotExists';
6523
+                        return -1;
6524
+                    }
6525
+                    if ($product->cost_price > 0)
6526
+                    {
6527
+                        $buyPrice = $product->cost_price;
6528
+                    }
6529
+                    else if ($product->pmp > 0)
6530
+                    {
6531
+                        $buyPrice = $product->pmp;
6532
+                    }
6533
+                }
6534
+                else if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'pmp') {
6535
+                    require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6536
+                    $product = new Product($this->db);
6537
+                    $result = $product->fetch($fk_product);
6538
+                    if ($result <= 0)
6539
+                    {
6540
+                        $this->errors[] = 'ErrorProductIdDoesNotExists';
6541
+                        return -1;
6542
+                    }
6543
+                    if ($product->pmp > 0)
6544
+                    {
6545
+                        $buyPrice = $product->pmp;
6546
+                    }
6547
+                }
6548
+
6549
+                if (empty($buyPrice) && isset(Globals::$conf->global->MARGIN_TYPE) && in_array(Globals::$conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
6550
+                    require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6551
+                    $productFournisseur = new ProductFournisseur($this->db);
6552
+                    if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6553
+                    {
6554
+                        $buyPrice = $productFournisseur->fourn_unitprice;
6555
+                    }
6556
+                    else if ($result < 0)
6557
+                    {
6558
+                        $this->errors[] = $productFournisseur->error;
6559
+                        return -2;
6560
+                    }
6561
+                }
6562
+            }
6563
+        }
6564
+        return $buyPrice;
6565
+    }
6566
+
6567
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6568
+    /**
6569
+     *  Show photos of an object (nbmax maximum), into several columns
6570
+     *
6571
+     *  @param		string	$modulepart		'product', 'ticket', ...
6572
+     *  @param      string	$sdir        	Directory to scan (full absolute path)
6573
+     *  @param      int		$size        	0=original size, 1='small' use thumbnail if possible
6574
+     *  @param      int		$nbmax       	Nombre maximum de photos (0=pas de max)
6575
+     *  @param      int		$nbbyrow     	Number of image per line or -1 to use div. Used only if size=1.
6576
+     * 	@param		int		$showfilename	1=Show filename
6577
+     * 	@param		int		$showaction		1=Show icon with action links (resize, delete)
6578
+     * 	@param		int		$maxHeight		Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image.
6579
+     * 	@param		int		$maxWidth		Max width of original image when size='small'
6580
+     *  @param      int     $nolink         Do not add a href link to view enlarged imaged into a new tab
6581
+     *  @param      int     $notitle        Do not add title tag on image
6582
+     *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6583
+     *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6584
+     */
6585
+    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)
6586
+    {
6587
+        // phpcs:enable
6588
+        global $conf,$user,$langs;
6589
+
6590
+        include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6591
+        include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6592
+
6593
+        $sortfield='position_name';
6594
+        $sortorder='asc';
6595
+
6596
+        $dir = $sdir . '/';
6597
+        $pdir = '/';
6598
+        if ($modulepart == 'ticket')
6599
+        {
6600
+            $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6601
+            $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6602
+        }
6603
+        else
6604
+        {
6605
+            $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6606
+            $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6607
+        }
6608
+
6609
+        // For backward compatibility
6610
+        if ($modulepart == 'product' && !empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
6611
+            $dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6612
+            $pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6613
+        }
6614
+
6615
+        // Defined relative dir to DOL_DATA_ROOT
6616
+        $relativedir = '';
6617
+        if ($dir)
6618
+        {
6619
+            $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6620
+            $relativedir = preg_replace('/^[\\/]/','',$relativedir);
6621
+            $relativedir = preg_replace('/[\\/]$/','',$relativedir);
6622
+        }
6623
+
6624
+        $dirthumb = $dir.'thumbs/';
6625
+        $pdirthumb = $pdir.'thumbs/';
6626
+
6627
+        $return ='<!-- Photo -->'."\n";
6628
+        $nbphoto=0;
6629
+
6630
+        $filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6631
+
6632
+        /* if (! empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6633
+          {
6634
+          $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6635
+          $filearray=array_merge($filearray, $filearrayold);
6636
+          } */
6637
+
6638
+        completeFileArrayWithDatabaseInfo($filearray, $relativedir);
6639
+
6640
+        if (count($filearray))
6641
+        {
6642
+            if ($sortfield && $sortorder)
6643
+            {
6644
+                $filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6645
+            }
6646
+
6647
+            foreach($filearray as $key => $val)
6648
+            {
6649
+                $photo='';
6650
+                $file = $val['name'];
6651
+
6652
+                //if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
6653
+
6654
+                //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
6655
+                if (image_format_supported($file) >= 0)
6656
+                {
6657
+                    $nbphoto++;
6658
+                    $photo = $file;
6659
+                    $viewfilename = $file;
6660
+
6661
+                    if ($size == 1 || $size == 'small') {   // Format vignette
6662
+
6663
+                        // Find name of thumb file
6664
+                        $photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6665
+                        if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
6666
+
6667
+                        // Get filesize of original file
6668
+                        $imgarray=dol_getImageSize($dir.$photo);
6669
+
6670
+                        if ($nbbyrow > 0)
6671
+                        {
6672
+                            if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6673
+
6674
+                            if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6675
+                            $return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6676
+                        }
6677
+                        else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
6678
+
6679
+                        $return.= "\n";
6680
+
6681
+                        $relativefile=preg_replace('/^\//', '', $pdir.$photo);
6682
+                        if (empty($nolink))
6683
+                        {
6684
+                            $urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6685
+                            if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6686
+                            else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6687
+                        }
6688
+
6689
+                        // Show image (width height=$maxHeight)
6690
+                        // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6691
+                        $alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6692
+                        $alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6693
+                        if ($notitle) $alt='';
6694
+
6695
+                        if ($usesharelink)
6696
+                        {
6697
+                            if ($val['share'])
6698
+                            {
6699
+                                if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6700
+                                {
6701
+                                    $return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6702
+                                    $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
+                                }
6704
+                                else {
6705
+                                    $return.= '<!-- Show original file -->';
6706
+                                    $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6707
+                                }
6708
+                            }
6709
+                            else
6710
+                            {
6711
+                                $return.= '<!-- Show nophoto file (because file is not shared) -->';
6712
+                                $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6713
+                            }
6714
+                        }
6715
+                        else
6716
+                        {
6717
+                            if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6718
+                            {
6719
+                                $return.= '<!-- Show thumb -->';
6720
+                                $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).'">';
6721
+                            }
6722
+                            else {
6723
+                                $return.= '<!-- Show original file -->';
6724
+                                $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).'">';
6725
+                            }
6726
+                        }
6727
+
6728
+                        if (empty($nolink)) $return.= '</a>';
6729
+                        $return.="\n";
6730
+
6731
+                        if ($showfilename) $return.= '<br>'.$viewfilename;
6732
+                        if ($showaction)
6733
+                        {
6734
+                            $return.= '<br>';
6735
+                            // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6736
+                            if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6737
+                            {
6738
+                                $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>';
6739
+                            }
6740
+                            // Special cas for product
6741
+                            if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6742
+                            {
6743
+                                // Link to resize
6744
+                                $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; ';
6745
+
6746
+                                // Link to delete
6747
+                                $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6748
+                                $return.= img_delete().'</a>';
6749
+                            }
6750
+                        }
6751
+                        $return.= "\n";
6752
+
6753
+                        if ($nbbyrow > 0)
6754
+                        {
6755
+                            $return.= '</td>';
6756
+                            if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6757
+                        }
6758
+                        else if ($nbbyrow < 0) $return.='</div>';
6759
+                    }
6760
+
6761
+                    if (empty($size)) {     // Format origine
6762
+                        $return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6763
+
6764
+                        if ($showfilename) $return.= '<br>'.$viewfilename;
6765
+                        if ($showaction)
6766
+                        {
6767
+                            // Special case for product
6768
+                            if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6769
+                            {
6770
+                                // Link to resize
6771
+                                $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; ';
6772
+
6773
+                                // Link to delete
6774
+                                $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6775
+                                $return.= img_delete().'</a>';
6776
+                            }
6777
+                        }
6778
+                    }
6779
+
6780
+                    // On continue ou on arrete de boucler ?
6781
+                    if ($nbmax && $nbphoto >= $nbmax) break;
6782
+                }
6783
+            }
6784
+
6785
+            if ($size==1 || $size=='small')
6786
+            {
6787
+                if ($nbbyrow > 0)
6788
+                {
6789
+                    // Ferme tableau
6790
+                    while ($nbphoto % $nbbyrow)
6791
+                    {
6792
+                        $return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6793
+                        $nbphoto++;
6794
+                    }
6795
+
6796
+                    if ($nbphoto) $return.= '</table>';
6797
+                }
6798
+            }
6799
+        }
6800
+
6801
+        $this->nbphoto = $nbphoto;
6802
+
6803
+        return $return;
6804
+    }
6805
+
6806
+
6807
+    /**
6808
+     * Function test if type is array
6809
+     *
6810
+     * @param   array   $info   content informations of field
6811
+     * @return                  bool
6812
+     */
6813
+    protected function isArray($info)
6814
+    {
6815
+        if(is_array($info))
6816
+        {
6817
+            if(isset($info['type']) && $info['type']=='array') return true;
6818
+            else return false;
6819
+        }
6820
+        else return false;
6821
+    }
6822
+
6823
+    /**
6824
+     * Function test if type is null
6825
+     *
6826
+     * @param   array   $info   content informations of field
6827
+     * @return                  bool
6828
+     */
6829
+    protected function isNull($info)
6830
+    {
6831
+        if(is_array($info))
6832
+        {
6833
+            if(isset($info['type']) && $info['type']=='null') return true;
6834
+            else return false;
6835
+        }
6836
+        else return false;
6837
+    }
6838
+
6839
+    /**
6840
+     * Function test if type is date
6841
+     *
6842
+     * @param   array   $info   content informations of field
6843
+     * @return                  bool
6844
+     */
6845
+    public function isDate($info)
6846
+    {
6847
+        if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6848
+        else return false;
6849
+    }
6850
+
6851
+    /**
6852
+     * Function test if type is integer
6853
+     *
6854
+     * @param   array   $info   content informations of field
6855
+     * @return                  bool
6856
+     */
6857
+    public function isInt($info)
6858
+    {
6859
+        if(is_array($info))
6860
+        {
6861
+            if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6862
+            else return false;
6863
+        }
6864
+        else return false;
6865
+    }
6866
+
6867
+    /**
6868
+     * Function test if type is float
6869
+     *
6870
+     * @param   array   $info   content informations of field
6871
+     * @return                  bool
6872
+     */
6873
+    public function isFloat($info)
6874
+    {
6875
+        if(is_array($info))
6876
+        {
6877
+            if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6878
+            else return false;
6879
+        }
6880
+        else return false;
6881
+    }
6882
+
6883
+    /**
6884
+     * Function test if type is text
6885
+     *
6886
+     * @param   array   $info   content informations of field
6887
+     * @return                  bool
6888
+     */
6889
+    public function isText($info)
6890
+    {
6891
+        if(is_array($info))
6892
+        {
6893
+            if(isset($info['type']) && $info['type']=='text') return true;
6894
+            else return false;
6895
+        }
6896
+        else return false;
6897
+    }
6898
+
6899
+    /**
6900
+     * Function test if is indexed
6901
+     *
6902
+     * @param   array   $info   content informations of field
6903
+     * @return                  bool
6904
+     */
6905
+    protected function isIndex($info)
6906
+    {
6907
+        if(is_array($info))
6908
+        {
6909
+            if(isset($info['index']) && $info['index']==true) return true;
6910
+            else return false;
6911
+        }
6912
+        else return false;
6913
+    }
6914
+
6915
+    /**
6916
+     * Function to prepare the values to insert.
6917
+     * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
6918
+     *
6919
+     * @return array
6920
+     */
6921
+    protected function setSaveQuery()
6922
+    {
6923
+        global $conf;
6924
+
6925
+        $queryarray=array();
6926
+        foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6927
+        {
6928
+            // Depending on field type ('datetime', ...)
6929
+            if($this->isDate($info))
6930
+            {
6931
+                if(empty($this->{$field}))
6932
+                {
6933
+                    $queryarray[$field] = null;
6934
+                }
6935
+                else
6936
+                {
6937
+                    $queryarray[$field] = $this->db->idate($this->{$field});
6938
+                }
6939
+            }
6940
+            else if($this->isArray($info))
6941
+            {
6942
+                if(! empty($this->{$field})) {
6943
+                    if(! is_array($this->{$field})) {
6944
+                        $this->{$field} = array($this->{$field});
6945
+                    }
6946
+                    $queryarray[$field] = serialize($this->{$field});
6947
+                } else {
6948
+                    $queryarray[$field] = null;
6949
+                }
6950
+            }
6951
+            else if($this->isInt($info))
6952
+            {
6953
+                if ($field == 'entity' && is_null($this->{$field}))
6954
+                    $queryarray[$field] = Globals::$conf->entity;
6955
+                else
6956
+                {
6957
+                    $queryarray[$field] = (int) price2num($this->{$field});
6958
+                    if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6959
+                }
6960
+            }
6961
+            else if($this->isFloat($info))
6962
+            {
6963
+                $queryarray[$field] = (double) price2num($this->{$field});
6964
+                if (empty($queryarray[$field])) $queryarray[$field]=0;
6965
+            }
6966
+            else
6967
+            {
6968
+                $queryarray[$field] = $this->{$field};
6969
+            }
6970
+
6971
+            if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6972
+            if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6973
+        }
6974
+
6975
+        return $queryarray;
6976
+    }
6977
+
6978
+    /**
6979
+     * Function to load data from a SQL pointer into properties of current object $this
6980
+     *
6981
+     * @param   stdClass    $obj    Contain data of object from database
6982
+     * @return void
6983
+     */
6984
+    protected function setVarsFromFetchObj(&$obj)
6985
+    {
6986
+        foreach ($this->fields as $field => $info)
6987
+        {
6988
+            if($this->isDate($info))
6989
+            {
6990
+                if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6991
+                else $this->{$field} = strtotime($obj->{$field});
6992
+            }
6993
+            elseif($this->isArray($info))
6994
+            {
6995
+                if(! empty($obj->{$field})) {
6996
+                    $this->{$field} = @unserialize($obj->{$field});
6997
+                    // Hack for data not in UTF8
6998
+                    if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6999
+                } else {
7000
+                    $this->{$field} = array();
7001
+                }
7002
+            }
7003
+            elseif($this->isInt($info))
7004
+            {
7005
+                if ($field == 'rowid') $this->id = (int) $obj->{$field};
7006
+                else $this->{$field} = (int) $obj->{$field};
7007
+            }
7008
+            elseif($this->isFloat($info))
7009
+            {
7010
+                $this->{$field} = (double) $obj->{$field};
7011
+            }
7012
+            elseif($this->isNull($info))
7013
+            {
7014
+                $val = $obj->{$field};
7015
+                // zero is not null
7016
+                $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7017
+            }
7018
+            else
7019
+            {
7020
+                $this->{$field} = $obj->{$field};
7021
+            }
7022
+        }
7023
+
7024
+        // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7025
+        if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7026
+    }
7027
+
7028
+    /**
7029
+     * Function to concat keys of fields
7030
+     *
7031
+     * @return string
7032
+     */
7033
+    protected function getFieldList()
7034
+    {
7035
+        $keys = array_keys($this->fields);
7036
+        return implode(',', $keys);
7037
+    }
7038
+
7039
+    /**
7040
+     * Add quote to field value if necessary
7041
+     *
7042
+     * @param 	string|int	$value			Value to protect
7043
+     * @param	array		$fieldsentry	Properties of field
7044
+     * @return 	string
7045
+     */
7046
+    protected function quote($value, $fieldsentry)
7047
+    {
7048
+        if (is_null($value)) return 'NULL';
7049
+        else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7050
+        else return "'".$this->db->escape($value)."'";
7051
+    }
7052
+
7053
+
7054
+    /**
7055
+     * Create object into database
7056
+     *
7057
+     * @param  User $user      User that creates
7058
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
7059
+     * @return int             <0 if KO, Id of created object if OK
7060
+     */
7061
+    public function createCommon(User $user, $notrigger = false)
7062
+    {
7063
+        global $langs;
7064
+
7065
+        $error = 0;
6210 7066
 
6211
-				$InfoFieldList = explode(":", $param_list[0]);
6212
-				$classname=$InfoFieldList[0];
6213
-				$classpath=$InfoFieldList[1];
6214
-				$getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6215
-				if (! empty($classpath))
6216
-				{
6217
-					dol_include_once($InfoFieldList[1]);
6218
-					if ($classname && class_exists($classname))
6219
-					{
6220
-						$object = new $classname($this->db);
6221
-						$object->fetch($value);
6222
-						$value=$object->getNomUrl($getnomurlparam);
6223
-					}
6224
-				}
6225
-				else
6226
-				{
6227
-					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6228
-					return 'Error bad setup of extrafield';
6229
-				}
6230
-			}
6231
-			else $value='';
6232
-		}
6233
-		elseif ($type == 'text' || $type == 'html')
6234
-		{
6235
-			$value=dol_htmlentitiesbr($value);
6236
-		}
6237
-		elseif ($type == 'password')
6238
-		{
6239
-			$value=preg_replace('/./i','*',$value);
6240
-		}
6241
-		elseif ($type == 'array')
6242
-		{
6243
-			$value = implode('<br>', $value);
6244
-		}
6245
-
6246
-		//print $type.'-'.$size;
6247
-		$out=$value;
6248
-
6249
-		return $out;
6250
-	}
6251
-
6252
-
6253
-	/**
6254
-	 * Function to show lines of extrafields with output datas
6255
-	 *
6256
-	 * @param 	Extrafields $extrafields    Extrafield Object
6257
-	 * @param 	string      $mode           Show output (view) or input (edit) for extrafield
6258
-	 * @param 	array       $params         Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
6259
-	 * @param 	string      $keysuffix      Suffix string to add after name and id of field (can be used to avoid duplicate names)
6260
-	 * @param 	string      $keyprefix      Prefix string to add before name and id of field (can be used to avoid duplicate names)
6261
-	 * @param	string		$onetrtd		All fields in same tr td
6262
-	 * @return 	string
6263
-	 */
6264
-	function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6265
-	{
6266
-		global $db, $conf, $langs, $action, $form;
6267
-
6268
-		if (! is_object($form)) $form=new Form($db);
6269
-
6270
-		$out = '';
6271
-
6272
-		if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
6273
-		{
6274
-			$out .= "\n";
6275
-			$out .= '<!-- showOptionalsInput --> ';
6276
-			$out .= "\n";
6277
-
6278
-			$e = 0;
6279
-			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6280
-			{
6281
-				// Show only the key field in params
6282
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
7067
+        $now=dol_now();
6283 7068
 
6284
-				$enabled = 1;
6285
-				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
6286
-				{
6287
-					$enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
6288
-				}
7069
+        $fieldvalues = $this->setSaveQuery();
7070
+        if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7071
+        if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7072
+        unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
6289 7073
 
6290
-				$perms = 1;
6291
-				if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
6292
-				{
6293
-					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6294
-				}
7074
+        $keys=array();
7075
+        $values = array();
7076
+        foreach ($fieldvalues as $k => $v) {
7077
+            $keys[$k] = $k;
7078
+            $value = $this->fields[$k];
7079
+            $values[$k] = $this->quote($v, $value);
7080
+        }
6295 7081
 
6296
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6297
-				if (empty($perms)) continue;
7082
+        // Clean and check mandatory
7083
+        foreach($keys as $key)
7084
+        {
7085
+            // If field is an implicit foreign key field
7086
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7087
+            if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
6298 7088
 
6299
-				// Load language if required
6300
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
7089
+            //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7090
+            if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7091
+            {
7092
+                $error++;
7093
+                $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7094
+            }
6301 7095
 
6302
-				$colspan='3';
6303
-				if (is_array($params) && count($params)>0) {
6304
-					if (array_key_exists('colspan',$params)) {
6305
-						$colspan=$params['colspan'];
6306
-					}
6307
-				}
7096
+            // If field is an implicit foreign key field
7097
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7098
+            if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7099
+        }
6308 7100
 
6309
-				switch($mode) {
6310
-					case "view":
6311
-						$value=$this->array_options["options_".$key.$keysuffix];
6312
-						break;
6313
-					case "edit":
6314
-						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6315
-						// GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6316
-						if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6317
-						{
6318
-							if (is_array($getposttemp)) {
6319
-								// $getposttemp is an array but following code expects a comma separated string
6320
-								$value = implode(",", $getposttemp);
6321
-							} else {
6322
-								$value = $getposttemp;
6323
-							}
6324
-						} else {
6325
-							$value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6326
-						}
6327
-						//var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6328
-						break;
6329
-				}
7101
+        if ($error) return -1;
6330 7102
 
6331
-				if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6332
-				{
6333
-					$out .= $extrafields->showSeparator($key, $this);
6334
-				}
6335
-				else
6336
-				{
6337
-					$csstyle='';
6338
-					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6339
-					if (is_array($params) && count($params)>0) {
6340
-						if (array_key_exists('style',$params)) {
6341
-							$csstyle=$params['style'];
6342
-						}
6343
-					}
7103
+        $this->db->begin();
6344 7104
 
6345
-					// add html5 elements
6346
-					$domData  = ' data-element="extrafield"';
6347
-					$domData .= ' data-targetelement="'.$this->element.'"';
6348
-					$domData .= ' data-targetid="'.$this->id.'"';
7105
+        if (! $error)
7106
+        {
7107
+            $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7108
+            $sql.= ' ('.implode( ", ", $keys ).')';
7109
+            $sql.= ' VALUES ('.implode( ", ", $values ).')';
7110
+
7111
+            $res = $this->db->query($sql);
7112
+            if ($res===false) {
7113
+                $error++;
7114
+                $this->errors[] = $this->db->lasterror();
7115
+            }
7116
+        }
6349 7117
 
6350
-					$html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : '';
7118
+        if (! $error)
7119
+        {
7120
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7121
+        }
6351 7122
 
6352
-					$out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
7123
+        // Create extrafields
7124
+        if (! $error)
7125
+        {
7126
+            $result=$this->insertExtraFields();
7127
+            if ($result < 0) $error++;
7128
+        }
6353 7129
 
6354
-					if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
6355
-						if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) {
6356
-                            $colspan = '0';
6357
-                        }
6358
-                    }
7130
+        // Triggers
7131
+        if (! $error && ! $notrigger)
7132
+        {
7133
+            // Call triggers
7134
+            $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7135
+            if ($result < 0) { $error++; }
7136
+            // End call triggers
7137
+        }
6359 7138
 
6360
-					if ($action == 'selectlines') { $colspan++; }
7139
+        // Commit or rollback
7140
+        if ($error) {
7141
+            $this->db->rollback();
7142
+            return -1;
7143
+        } else {
7144
+            $this->db->commit();
7145
+            return $this->id;
7146
+        }
7147
+    }
6361 7148
 
6362
-					// Convert date into timestamp format (value in memory must be a timestamp)
6363
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6364
-					{
6365
-						$datenotinstring = $this->array_options['options_' . $key];
6366
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6367
-						{
6368
-							$datenotinstring = $this->db->jdate($datenotinstring);
6369
-						}
6370
-						$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;
6371
-					}
6372
-					// Convert float submited string into real php numeric (value in memory must be a php numeric)
6373
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6374
-					{
6375
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6376
-					}
6377
-
6378
-					$labeltoshow = $langs->trans($label);
6379
-
6380
-					$out .= '<td class="titlefield';
6381
-					if (GETPOST('action','none') == 'create') $out.='create';
6382
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6383
-					$out .= '">';
6384
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6385
-					else $out .= $labeltoshow;
6386
-					$out .= '</td>';
6387
-
6388
-					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6389
-					$out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6390
-
6391
-					switch($mode) {
6392
-						case "view":
6393
-							$out .= $extrafields->showOutputField($key, $value);
6394
-							break;
6395
-						case "edit":
6396
-							$out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id);
6397
-							break;
6398
-					}
6399
-
6400
-					$out .= '</td>';
6401
-
6402
-					if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1))
6403
-                        $out .= '</tr>';
6404
-                    else $out .= '</tr>';
6405
-					$e++;
6406
-				}
6407
-			}
6408
-			$out .= "\n";
6409
-			// Add code to manage list depending on others
6410
-			if (!empty(Globals::$conf->use_javascript_ajax)) {
6411
-                $out .= '
6412
-				<script type="text/javascript">
6413
-				    jQuery(document).ready(function() {
6414
-				    	function showOptions(child_list, parent_list)
6415
-				    	{
6416
-				    		var val = $("select[name=\"options_"+parent_list+"\"]").val();
6417
-				    		var parentVal = parent_list + ":" + val;
6418
-							if(val > 0) {
6419
-					    		$("select[name=\""+child_list+"\"] option[parent]").hide();
6420
-					    		$("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
6421
-							} else {
6422
-								$("select[name=\""+child_list+"\"] option").show();
6423
-							}
6424
-				    	}
6425
-						function setListDependencies() {
6426
-					    	jQuery("select option[parent]").parent().each(function() {
6427
-					    		var child_list = $(this).attr("name");
6428
-								var parent = $(this).find("option[parent]:first").attr("parent");
6429
-								var infos = parent.split(":");
6430
-								var parent_list = infos[0];
6431
-								$("select[name=\""+parent_list+"\"]").change(function() {
6432
-									showOptions(child_list, parent_list);
6433
-								});
6434
-					    	});
6435
-						}
6436 7149
 
6437
-						setListDependencies();
6438
-				    });
6439
-				</script>'."\n";
6440
-				$out .= '<!-- /showOptionalsInput --> '."\n";
6441
-			}
6442
-		}
6443
-		return $out;
6444
-	}
6445
-
6446
-
6447
-	/**
6448
-	 * Returns the rights used for this class
6449
-	 * @return stdClass
6450
-	 */
6451
-	public function getRights()
6452
-	{
6453
-		global $user;
6454
-
6455
-		$element = $this->element;
6456
-		if ($element == 'facturerec') $element='facture';
6457
-
6458
-		return $user->rights->{$element};
6459
-	}
6460
-
6461
-	/**
6462
-	 * Function used to replace a thirdparty id with another one.
6463
-	 * This function is meant to be called from replaceThirdparty with the appropiate tables
6464
-	 * Column name fk_soc MUST be used to identify thirdparties
6465
-	 *
6466
-	 * @param  DoliDB 	   $db 			  Database handler
6467
-	 * @param  int 		   $origin_id     Old thirdparty id (the thirdparty to delete)
6468
-	 * @param  int 		   $dest_id       New thirdparty id (the thirdparty that will received element of the other)
6469
-	 * @param  string[]    $tables        Tables that need to be changed
6470
-	 * @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)
6471
-	 * @return bool						  True if success, False if error
6472
-	 */
6473
-	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6474
-	{
6475
-		foreach ($tables as $table)
6476
-		{
6477
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6478
-
6479
-			if (! $db->query($sql))
6480
-			{
6481
-				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.
6482
-				//$this->errors = $db->lasterror();
6483
-				return false;
6484
-			}
6485
-		}
6486
-
6487
-		return true;
6488
-	}
6489
-
6490
-	/**
6491
-	 * Get buy price to use for margin calculation. This function is called when buy price is unknown.
6492
-	 *	 Set buy price = sell price if ForceBuyingPriceIfNull configured,
6493
-	 *   else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
6494
-	 *	 else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
6495
-	 *	 else set min buy price as buy price
6496
-	 *
6497
-	 * @param float		$unitPrice		 Product unit price
6498
-	 * @param float		$discountPercent Line discount percent
6499
-	 * @param int		$fk_product		 Product id
6500
-	 * @return	float                    <0 if KO, buyprice if OK
6501
-	 */
6502
-	public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
6503
-	{
6504
-		global $conf;
6505
-
6506
-		$buyPrice = 0;
6507
-
6508
-		if (($unitPrice > 0) && (isset(Globals::$conf->global->ForceBuyingPriceIfNull) && Globals::$conf->global->ForceBuyingPriceIfNull == 1)) { // In most cases, test here is false{
6509
-			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
6510
-		}
6511
-		else
6512
-		{
6513
-			// Get cost price for margin calculation
6514
-			if (! empty($fk_product))
6515
-			{
6516
-				if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'costprice') {
6517
-					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6518
-					$product = new Product($this->db);
6519
-					$result = $product->fetch($fk_product);
6520
-					if ($result <= 0)
6521
-					{
6522
-						$this->errors[] = 'ErrorProductIdDoesNotExists';
6523
-						return -1;
6524
-					}
6525
-					if ($product->cost_price > 0)
6526
-					{
6527
-						$buyPrice = $product->cost_price;
6528
-					}
6529
-					else if ($product->pmp > 0)
6530
-					{
6531
-						$buyPrice = $product->pmp;
6532
-					}
6533
-				}
6534
-				else if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'pmp') {
6535
-					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6536
-					$product = new Product($this->db);
6537
-					$result = $product->fetch($fk_product);
6538
-					if ($result <= 0)
6539
-					{
6540
-						$this->errors[] = 'ErrorProductIdDoesNotExists';
6541
-						return -1;
6542
-					}
6543
-					if ($product->pmp > 0)
6544
-					{
6545
-						$buyPrice = $product->pmp;
6546
-					}
6547
-				}
7150
+    /**
7151
+     * Load object in memory from the database
7152
+     *
7153
+     * @param	int    $id				Id object
7154
+     * @param	string $ref				Ref
7155
+     * @param	string	$morewhere		More SQL filters (' AND ...')
7156
+     * @return 	int         			<0 if KO, 0 if not found, >0 if OK
7157
+     */
7158
+    public function fetchCommon($id, $ref = null, $morewhere = '')
7159
+    {
7160
+        if (empty($id) && empty($ref) && empty($morewhere)) return -1;
6548 7161
 
6549
-				if (empty($buyPrice) && isset(Globals::$conf->global->MARGIN_TYPE) && in_array(Globals::$conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice'))) {
6550
-					require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6551
-					$productFournisseur = new ProductFournisseur($this->db);
6552
-					if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6553
-					{
6554
-						$buyPrice = $productFournisseur->fourn_unitprice;
6555
-					}
6556
-					else if ($result < 0)
6557
-					{
6558
-						$this->errors[] = $productFournisseur->error;
6559
-						return -2;
6560
-					}
6561
-				}
6562
-			}
6563
-		}
6564
-		return $buyPrice;
6565
-	}
7162
+        $sql = 'SELECT '.$this->getFieldList();
7163
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
6566 7164
 
6567
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6568
-	/**
6569
-	 *  Show photos of an object (nbmax maximum), into several columns
6570
-	 *
6571
-	 *  @param		string	$modulepart		'product', 'ticket', ...
6572
-	 *  @param      string	$sdir        	Directory to scan (full absolute path)
6573
-	 *  @param      int		$size        	0=original size, 1='small' use thumbnail if possible
6574
-	 *  @param      int		$nbmax       	Nombre maximum de photos (0=pas de max)
6575
-	 *  @param      int		$nbbyrow     	Number of image per line or -1 to use div. Used only if size=1.
6576
-	 * 	@param		int		$showfilename	1=Show filename
6577
-	 * 	@param		int		$showaction		1=Show icon with action links (resize, delete)
6578
-	 * 	@param		int		$maxHeight		Max height of original image when size='small' (so we can use original even if small requested). If 0, always use 'small' thumb image.
6579
-	 * 	@param		int		$maxWidth		Max width of original image when size='small'
6580
-	 *  @param      int     $nolink         Do not add a href link to view enlarged imaged into a new tab
6581
-	 *  @param      int     $notitle        Do not add title tag on image
6582
-	 *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6583
-	 *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6584
-	 */
6585
-	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)
6586
-	{
6587
-        // phpcs:enable
6588
-		global $conf,$user,$langs;
6589
-
6590
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6591
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6592
-
6593
-		$sortfield='position_name';
6594
-		$sortorder='asc';
6595
-
6596
-		$dir = $sdir . '/';
6597
-		$pdir = '/';
6598
-		if ($modulepart == 'ticket')
6599
-		{
6600
-			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6601
-			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6602
-		}
6603
-		else
6604
-		{
6605
-			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6606
-			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6607
-		}
6608
-
6609
-		// For backward compatibility
6610
-		if ($modulepart == 'product' && !empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
6611
-			$dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6612
-			$pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6613
-		}
6614
-
6615
-		// Defined relative dir to DOL_DATA_ROOT
6616
-		$relativedir = '';
6617
-		if ($dir)
6618
-		{
6619
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6620
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
6621
-			$relativedir = preg_replace('/[\\/]$/','',$relativedir);
6622
-		}
6623
-
6624
-		$dirthumb = $dir.'thumbs/';
6625
-		$pdirthumb = $pdir.'thumbs/';
6626
-
6627
-		$return ='<!-- Photo -->'."\n";
6628
-		$nbphoto=0;
6629
-
6630
-		$filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6631
-
6632
-		/* if (! empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6633
-          {
6634
-          $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6635
-          $filearray=array_merge($filearray, $filearrayold);
6636
-          } */
7165
+        if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7166
+        elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7167
+        else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7168
+        if ($morewhere)   $sql.= $morewhere;
7169
+        $sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
6637 7170
 
6638
-		completeFileArrayWithDatabaseInfo($filearray, $relativedir);
7171
+        $res = $this->db->query($sql);
7172
+        if ($res)
7173
+        {
7174
+            $obj = $this->db->fetch_object($res);
7175
+            if ($obj)
7176
+            {
7177
+                $this->setVarsFromFetchObj($obj);
7178
+                return $this->id;
7179
+            }
7180
+            else
7181
+            {
7182
+                return 0;
7183
+            }
7184
+        }
7185
+        else
7186
+        {
7187
+            $this->error = $this->db->lasterror();
7188
+            $this->errors[] = $this->error;
7189
+            return -1;
7190
+        }
7191
+    }
6639 7192
 
6640
-		if (count($filearray))
6641
-		{
6642
-			if ($sortfield && $sortorder)
6643
-			{
6644
-				$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6645
-			}
7193
+    /**
7194
+     * Update object into database
7195
+     *
7196
+     * @param  User $user      	User that modifies
7197
+     * @param  bool $notrigger 	false=launch triggers after, true=disable triggers
7198
+     * @return int             	<0 if KO, >0 if OK
7199
+     */
7200
+    public function updateCommon(User $user, $notrigger = false)
7201
+    {
7202
+        global $conf, $langs;
6646 7203
 
6647
-			foreach($filearray as $key => $val)
6648
-			{
6649
-				$photo='';
6650
-				$file = $val['name'];
7204
+        $error = 0;
6651 7205
 
6652
-				//if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
7206
+        $now=dol_now();
6653 7207
 
6654
-				//if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
6655
-				if (image_format_supported($file) >= 0)
6656
-				{
6657
-					$nbphoto++;
6658
-					$photo = $file;
6659
-					$viewfilename = $file;
7208
+        $fieldvalues = $this->setSaveQuery();
7209
+        if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7210
+        if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7211
+        unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
6660 7212
 
6661
-					if ($size == 1 || $size == 'small') {   // Format vignette
7213
+        $keys=array();
7214
+        $values = array();
7215
+        foreach ($fieldvalues as $k => $v) {
7216
+            $keys[$k] = $k;
7217
+            $value = $this->fields[$k];
7218
+            $values[$k] = $this->quote($v, $value);
7219
+            $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
7220
+        }
6662 7221
 
6663
-						// Find name of thumb file
6664
-						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6665
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
7222
+        // Clean and check mandatory
7223
+        foreach($keys as $key)
7224
+        {
7225
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7226
+            if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
6666 7227
 
6667
-						// Get filesize of original file
6668
-						$imgarray=dol_getImageSize($dir.$photo);
7228
+            //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7229
+            /*
7230
+			if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
7231
+			{
7232
+				$error++;
7233
+				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7234
+			}*/
7235
+        }
6669 7236
 
6670
-						if ($nbbyrow > 0)
6671
-						{
6672
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7237
+        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
6673 7238
 
6674
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6675
-							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6676
-						}
6677
-						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
7239
+        $this->db->begin();
7240
+        if (! $error)
7241
+        {
7242
+            $res = $this->db->query($sql);
7243
+            if ($res===false)
7244
+            {
7245
+                $error++;
7246
+                $this->errors[] = $this->db->lasterror();
7247
+            }
7248
+        }
6678 7249
 
6679
-						$return.= "\n";
7250
+        // Update extrafield
7251
+        if (!$error && empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) {
7252
+            $result=$this->insertExtraFields();
7253
+            if ($result < 0)
7254
+            {
7255
+                $error++;
7256
+            }
7257
+        }
6680 7258
 
6681
-						$relativefile=preg_replace('/^\//', '', $pdir.$photo);
6682
-						if (empty($nolink))
6683
-						{
6684
-							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6685
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6686
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6687
-						}
7259
+        // Triggers
7260
+        if (! $error && ! $notrigger)
7261
+        {
7262
+            // Call triggers
7263
+            $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7264
+            if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7265
+            // End call triggers
7266
+        }
6688 7267
 
6689
-						// Show image (width height=$maxHeight)
6690
-						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6691
-						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6692
-						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6693
-						if ($notitle) $alt='';
6694
-
6695
-						if ($usesharelink)
6696
-						{
6697
-							if ($val['share'])
6698
-							{
6699
-								if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6700
-								{
6701
-									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6702
-									$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
-								}
6704
-								else {
6705
-									$return.= '<!-- Show original file -->';
6706
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6707
-								}
6708
-							}
6709
-							else
6710
-							{
6711
-								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6712
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6713
-							}
6714
-						}
6715
-						else
6716
-						{
6717
-							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6718
-							{
6719
-								$return.= '<!-- Show thumb -->';
6720
-								$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).'">';
6721
-							}
6722
-							else {
6723
-								$return.= '<!-- Show original file -->';
6724
-								$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).'">';
6725
-							}
6726
-						}
7268
+        // Commit or rollback
7269
+        if ($error) {
7270
+            $this->db->rollback();
7271
+            return -1;
7272
+        } else {
7273
+            $this->db->commit();
7274
+            return $this->id;
7275
+        }
7276
+    }
6727 7277
 
6728
-						if (empty($nolink)) $return.= '</a>';
6729
-						$return.="\n";
6730
-
6731
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6732
-						if ($showaction)
6733
-						{
6734
-							$return.= '<br>';
6735
-							// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6736
-							if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6737
-							{
6738
-								$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>';
6739
-							}
6740
-							// Special cas for product
6741
-							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6742
-							{
6743
-								// Link to resize
6744
-								$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; ';
6745
-
6746
-								// Link to delete
6747
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6748
-								$return.= img_delete().'</a>';
6749
-							}
6750
-						}
6751
-						$return.= "\n";
7278
+    /**
7279
+     * Delete object in database
7280
+     *
7281
+     * @param 	User 	$user       			User that deletes
7282
+     * @param 	bool 	$notrigger  			false=launch triggers after, true=disable triggers
7283
+     * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7284
+     * @return 	int             				<=0 if KO, >0 if OK
7285
+     */
7286
+    public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7287
+    {
7288
+        $error=0;
6752 7289
 
6753
-						if ($nbbyrow > 0)
6754
-						{
6755
-							$return.= '</td>';
6756
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6757
-						}
6758
-						else if ($nbbyrow < 0) $return.='</div>';
6759
-					}
6760
-
6761
-					if (empty($size)) {     // Format origine
6762
-						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6763
-
6764
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6765
-						if ($showaction)
6766
-						{
6767
-							// Special case for product
6768
-							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6769
-							{
6770
-								// Link to resize
6771
-								$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; ';
6772
-
6773
-								// Link to delete
6774
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6775
-								$return.= img_delete().'</a>';
6776
-							}
6777
-						}
6778
-					}
7290
+        $this->db->begin();
6779 7291
 
6780
-					// On continue ou on arrete de boucler ?
6781
-					if ($nbmax && $nbphoto >= $nbmax) break;
6782
-				}
6783
-			}
7292
+        if ($forcechilddeletion)
7293
+        {
7294
+            foreach($this->childtables as $table)
7295
+            {
7296
+                $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7297
+                $resql = $this->db->query($sql);
7298
+                if (! $resql)
7299
+                {
7300
+                    $this->error=$this->db->lasterror();
7301
+                    $this->errors[]=$this->error;
7302
+                    $this->db->rollback();
7303
+                    return -1;
7304
+                }
7305
+            }
7306
+        }
7307
+        elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7308
+        {
7309
+            $objectisused = $this->isObjectUsed($this->id);
7310
+            if (! empty($objectisused))
7311
+            {
7312
+                dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7313
+                $this->error='ErrorRecordHasChildren';
7314
+                $this->errors[]=$this->error;
7315
+                $this->db->rollback();
7316
+                return 0;
7317
+            }
7318
+        }
6784 7319
 
6785
-			if ($size==1 || $size=='small')
6786
-			{
6787
-				if ($nbbyrow > 0)
6788
-				{
6789
-					// Ferme tableau
6790
-					while ($nbphoto % $nbbyrow)
6791
-					{
6792
-						$return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6793
-						$nbphoto++;
6794
-					}
6795
-
6796
-					if ($nbphoto) $return.= '</table>';
6797
-				}
6798
-			}
6799
-		}
6800
-
6801
-		$this->nbphoto = $nbphoto;
6802
-
6803
-		return $return;
6804
-	}
6805
-
6806
-
6807
-	/**
6808
-	 * Function test if type is array
6809
-	 *
6810
-	 * @param   array   $info   content informations of field
6811
-	 * @return                  bool
6812
-	 */
6813
-	protected function isArray($info)
6814
-	{
6815
-		if(is_array($info))
6816
-		{
6817
-			if(isset($info['type']) && $info['type']=='array') return true;
6818
-			else return false;
6819
-		}
6820
-		else return false;
6821
-	}
6822
-
6823
-	/**
6824
-	 * Function test if type is null
6825
-	 *
6826
-	 * @param   array   $info   content informations of field
6827
-	 * @return                  bool
6828
-	 */
6829
-	protected function isNull($info)
6830
-	{
6831
-		if(is_array($info))
6832
-		{
6833
-			if(isset($info['type']) && $info['type']=='null') return true;
6834
-			else return false;
6835
-		}
6836
-		else return false;
6837
-	}
6838
-
6839
-	/**
6840
-	 * Function test if type is date
6841
-	 *
6842
-	 * @param   array   $info   content informations of field
6843
-	 * @return                  bool
6844
-	 */
6845
-	public function isDate($info)
6846
-	{
6847
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6848
-		else return false;
6849
-	}
6850
-
6851
-	/**
6852
-	 * Function test if type is integer
6853
-	 *
6854
-	 * @param   array   $info   content informations of field
6855
-	 * @return                  bool
6856
-	 */
6857
-	public function isInt($info)
6858
-	{
6859
-		if(is_array($info))
6860
-		{
6861
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6862
-			else return false;
6863
-		}
6864
-		else return false;
6865
-	}
6866
-
6867
-	/**
6868
-	 * Function test if type is float
6869
-	 *
6870
-	 * @param   array   $info   content informations of field
6871
-	 * @return                  bool
6872
-	 */
6873
-	public function isFloat($info)
6874
-	{
6875
-		if(is_array($info))
6876
-		{
6877
-			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6878
-			else return false;
6879
-		}
6880
-		else return false;
6881
-	}
6882
-
6883
-	/**
6884
-	 * Function test if type is text
6885
-	 *
6886
-	 * @param   array   $info   content informations of field
6887
-	 * @return                  bool
6888
-	 */
6889
-	public function isText($info)
6890
-	{
6891
-		if(is_array($info))
6892
-		{
6893
-			if(isset($info['type']) && $info['type']=='text') return true;
6894
-			else return false;
6895
-		}
6896
-		else return false;
6897
-	}
6898
-
6899
-	/**
6900
-	 * Function test if is indexed
6901
-	 *
6902
-	 * @param   array   $info   content informations of field
6903
-	 * @return                  bool
6904
-	 */
6905
-	protected function isIndex($info)
6906
-	{
6907
-		if(is_array($info))
6908
-		{
6909
-			if(isset($info['index']) && $info['index']==true) return true;
6910
-			else return false;
6911
-		}
6912
-		else return false;
6913
-	}
6914
-
6915
-	/**
6916
-	 * Function to prepare the values to insert.
6917
-	 * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
6918
-	 *
6919
-	 * @return array
6920
-	 */
6921
-	protected function setSaveQuery()
6922
-	{
6923
-		global $conf;
6924
-
6925
-		$queryarray=array();
6926
-		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6927
-		{
6928
-			// Depending on field type ('datetime', ...)
6929
-			if($this->isDate($info))
6930
-			{
6931
-				if(empty($this->{$field}))
6932
-				{
6933
-					$queryarray[$field] = null;
6934
-				}
6935
-				else
6936
-				{
6937
-					$queryarray[$field] = $this->db->idate($this->{$field});
6938
-				}
6939
-			}
6940
-			else if($this->isArray($info))
6941
-			{
6942
-				if(! empty($this->{$field})) {
6943
-					if(! is_array($this->{$field})) {
6944
-						$this->{$field} = array($this->{$field});
6945
-					}
6946
-					$queryarray[$field] = serialize($this->{$field});
6947
-				} else {
6948
-					$queryarray[$field] = null;
6949
-				}
6950
-			}
6951
-			else if($this->isInt($info))
6952
-			{
6953
-				if ($field == 'entity' && is_null($this->{$field}))
6954
-                    $queryarray[$field] = Globals::$conf->entity;
6955
-                else
6956
-				{
6957
-					$queryarray[$field] = (int) price2num($this->{$field});
6958
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6959
-				}
6960
-			}
6961
-			else if($this->isFloat($info))
6962
-			{
6963
-				$queryarray[$field] = (double) price2num($this->{$field});
6964
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6965
-			}
6966
-			else
6967
-			{
6968
-				$queryarray[$field] = $this->{$field};
6969
-			}
7320
+        if (! $error) {
7321
+            if (! $notrigger) {
7322
+                // Call triggers
7323
+                $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7324
+                if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7325
+                // End call triggers
7326
+            }
7327
+        }
6970 7328
 
6971
-			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6972
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6973
-		}
7329
+        if (! $error && ! empty($this->isextrafieldmanaged))
7330
+        {
7331
+            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7332
+            $sql.= " WHERE fk_object=" . $this->id;
6974 7333
 
6975
-		return $queryarray;
6976
-	}
7334
+            $resql = $this->db->query($sql);
7335
+            if (! $resql)
7336
+            {
7337
+                $this->errors[] = $this->db->lasterror();
7338
+                $error++;
7339
+            }
7340
+        }
6977 7341
 
6978
-	/**
6979
-	 * Function to load data from a SQL pointer into properties of current object $this
6980
-	 *
6981
-	 * @param   stdClass    $obj    Contain data of object from database
6982
-     * @return void
6983
-	 */
6984
-	protected function setVarsFromFetchObj(&$obj)
6985
-	{
6986
-		foreach ($this->fields as $field => $info)
6987
-		{
6988
-			if($this->isDate($info))
6989
-			{
6990
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6991
-				else $this->{$field} = strtotime($obj->{$field});
6992
-			}
6993
-			elseif($this->isArray($info))
6994
-			{
6995
-				if(! empty($obj->{$field})) {
6996
-					$this->{$field} = @unserialize($obj->{$field});
6997
-					// Hack for data not in UTF8
6998
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6999
-				} else {
7000
-					$this->{$field} = array();
7001
-				}
7002
-			}
7003
-			elseif($this->isInt($info))
7004
-			{
7005
-				if ($field == 'rowid') $this->id = (int) $obj->{$field};
7006
-				else $this->{$field} = (int) $obj->{$field};
7007
-			}
7008
-			elseif($this->isFloat($info))
7009
-			{
7010
-				$this->{$field} = (double) $obj->{$field};
7011
-			}
7012
-			elseif($this->isNull($info))
7013
-			{
7014
-				$val = $obj->{$field};
7015
-				// zero is not null
7016
-				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7017
-			}
7018
-			else
7019
-			{
7020
-				$this->{$field} = $obj->{$field};
7021
-			}
7022
-		}
7023
-
7024
-		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7025
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7026
-	}
7027
-
7028
-	/**
7029
-	 * Function to concat keys of fields
7030
-	 *
7031
-	 * @return string
7032
-	 */
7033
-	protected function getFieldList()
7034
-	{
7035
-		$keys = array_keys($this->fields);
7036
-		return implode(',', $keys);
7037
-	}
7038
-
7039
-	/**
7040
-	 * Add quote to field value if necessary
7041
-	 *
7042
-	 * @param 	string|int	$value			Value to protect
7043
-	 * @param	array		$fieldsentry	Properties of field
7044
-	 * @return 	string
7045
-	 */
7046
-    protected function quote($value, $fieldsentry)
7047
-    {
7048
-		if (is_null($value)) return 'NULL';
7049
-		else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7050
-		else return "'".$this->db->escape($value)."'";
7051
-	}
7052
-
7053
-
7054
-	/**
7055
-	 * Create object into database
7056
-	 *
7057
-	 * @param  User $user      User that creates
7058
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
7059
-	 * @return int             <0 if KO, Id of created object if OK
7060
-	 */
7061
-	public function createCommon(User $user, $notrigger = false)
7062
-	{
7063
-		global $langs;
7064
-
7065
-		$error = 0;
7066
-
7067
-		$now=dol_now();
7068
-
7069
-		$fieldvalues = $this->setSaveQuery();
7070
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7071
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7072
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7073
-
7074
-		$keys=array();
7075
-		$values = array();
7076
-		foreach ($fieldvalues as $k => $v) {
7077
-			$keys[$k] = $k;
7078
-			$value = $this->fields[$k];
7079
-			$values[$k] = $this->quote($v, $value);
7080
-		}
7081
-
7082
-		// Clean and check mandatory
7083
-		foreach($keys as $key)
7084
-		{
7085
-			// If field is an implicit foreign key field
7086
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7087
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7088
-
7089
-			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7090
-			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7091
-			{
7092
-				$error++;
7093
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7094
-			}
7342
+        if (! $error)
7343
+        {
7344
+            $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7095 7345
 
7096
-			// If field is an implicit foreign key field
7097
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7098
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7099
-		}
7346
+            $res = $this->db->query($sql);
7347
+            if($res===false) {
7348
+                $error++;
7349
+                $this->errors[] = $this->db->lasterror();
7350
+            }
7351
+        }
7100 7352
 
7101
-		if ($error) return -1;
7353
+        // Commit or rollback
7354
+        if ($error) {
7355
+            $this->db->rollback();
7356
+            return -1;
7357
+        } else {
7358
+            $this->db->commit();
7359
+            return 1;
7360
+        }
7361
+    }
7102 7362
 
7103
-		$this->db->begin();
7363
+    /**
7364
+     * Initialise object with example values
7365
+     * Id must be 0 if object instance is a specimen
7366
+     *
7367
+     * @return void
7368
+     */
7369
+    public function initAsSpecimenCommon()
7370
+    {
7371
+        $this->id = 0;
7104 7372
 
7105
-		if (! $error)
7106
-		{
7107
-			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7108
-			$sql.= ' ('.implode( ", ", $keys ).')';
7109
-			$sql.= ' VALUES ('.implode( ", ", $values ).')';
7373
+        // TODO...
7374
+    }
7110 7375
 
7111
-			$res = $this->db->query($sql);
7112
-			if ($res===false) {
7113
-				$error++;
7114
-				$this->errors[] = $this->db->lasterror();
7115
-			}
7116
-		}
7117
-
7118
-		if (! $error)
7119
-		{
7120
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7121
-		}
7122
-
7123
-		// Create extrafields
7124
-		if (! $error)
7125
-		{
7126
-			$result=$this->insertExtraFields();
7127
-			if ($result < 0) $error++;
7128
-		}
7129
-
7130
-		// Triggers
7131
-		if (! $error && ! $notrigger)
7132
-		{
7133
-			// Call triggers
7134
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7135
-			if ($result < 0) { $error++; }
7136
-			// End call triggers
7137
-		}
7138
-
7139
-		// Commit or rollback
7140
-		if ($error) {
7141
-			$this->db->rollback();
7142
-			return -1;
7143
-		} else {
7144
-			$this->db->commit();
7145
-			return $this->id;
7146
-		}
7147
-	}
7148
-
7149
-
7150
-	/**
7151
-	 * Load object in memory from the database
7152
-	 *
7153
-	 * @param	int    $id				Id object
7154
-	 * @param	string $ref				Ref
7155
-	 * @param	string	$morewhere		More SQL filters (' AND ...')
7156
-	 * @return 	int         			<0 if KO, 0 if not found, >0 if OK
7157
-	 */
7158
-	public function fetchCommon($id, $ref = null, $morewhere = '')
7159
-	{
7160
-		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7161
-
7162
-		$sql = 'SELECT '.$this->getFieldList();
7163
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7164
-
7165
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7166
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7167
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7168
-		if ($morewhere)   $sql.= $morewhere;
7169
-		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7170
-
7171
-		$res = $this->db->query($sql);
7172
-		if ($res)
7173
-		{
7174
-			$obj = $this->db->fetch_object($res);
7175
-			if ($obj)
7176
-			{
7177
-				$this->setVarsFromFetchObj($obj);
7178
-				return $this->id;
7179
-			}
7180
-			else
7181
-			{
7182
-				return 0;
7183
-			}
7184
-		}
7185
-		else
7186
-		{
7187
-			$this->error = $this->db->lasterror();
7188
-			$this->errors[] = $this->error;
7189
-			return -1;
7190
-		}
7191
-	}
7192
-
7193
-	/**
7194
-	 * Update object into database
7195
-	 *
7196
-	 * @param  User $user      	User that modifies
7197
-	 * @param  bool $notrigger 	false=launch triggers after, true=disable triggers
7198
-	 * @return int             	<0 if KO, >0 if OK
7199
-	 */
7200
-	public function updateCommon(User $user, $notrigger = false)
7201
-	{
7202
-		global $conf, $langs;
7203
-
7204
-		$error = 0;
7205
-
7206
-		$now=dol_now();
7207
-
7208
-		$fieldvalues = $this->setSaveQuery();
7209
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7210
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7211
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7212
-
7213
-		$keys=array();
7214
-		$values = array();
7215
-		foreach ($fieldvalues as $k => $v) {
7216
-			$keys[$k] = $k;
7217
-			$value = $this->fields[$k];
7218
-			$values[$k] = $this->quote($v, $value);
7219
-			$tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
7220
-		}
7221
-
7222
-		// Clean and check mandatory
7223
-		foreach($keys as $key)
7224
-		{
7225
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7226
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7227
-
7228
-			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7229
-			/*
7230
-			if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
7231
-			{
7232
-				$error++;
7233
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7234
-			}*/
7235
-		}
7236 7376
 
7237
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
7377
+    /* Part for comments */
7238 7378
 
7239
-		$this->db->begin();
7240
-		if (! $error)
7241
-		{
7242
-			$res = $this->db->query($sql);
7243
-			if ($res===false)
7244
-			{
7245
-				$error++;
7246
-				$this->errors[] = $this->db->lasterror();
7247
-			}
7248
-		}
7249
-
7250
-		// Update extrafield
7251
-		if (!$error && empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) {
7252
-			$result=$this->insertExtraFields();
7253
-			if ($result < 0)
7254
-			{
7255
-				$error++;
7256
-			}
7257
-		}
7258
-
7259
-		// Triggers
7260
-		if (! $error && ! $notrigger)
7261
-		{
7262
-			// Call triggers
7263
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7264
-			if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7265
-			// End call triggers
7266
-		}
7267
-
7268
-		// Commit or rollback
7269
-		if ($error) {
7270
-			$this->db->rollback();
7271
-			return -1;
7272
-		} else {
7273
-			$this->db->commit();
7274
-			return $this->id;
7275
-		}
7276
-	}
7277
-
7278
-	/**
7279
-	 * Delete object in database
7280
-	 *
7281
-	 * @param 	User 	$user       			User that deletes
7282
-	 * @param 	bool 	$notrigger  			false=launch triggers after, true=disable triggers
7283
-	 * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7284
-	 * @return 	int             				<=0 if KO, >0 if OK
7285
-	 */
7286
-	public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7287
-	{
7288
-		$error=0;
7289
-
7290
-		$this->db->begin();
7291
-
7292
-		if ($forcechilddeletion)
7293
-		{
7294
-			foreach($this->childtables as $table)
7295
-			{
7296
-				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7297
-				$resql = $this->db->query($sql);
7298
-				if (! $resql)
7299
-				{
7300
-					$this->error=$this->db->lasterror();
7301
-					$this->errors[]=$this->error;
7302
-					$this->db->rollback();
7303
-					return -1;
7304
-				}
7305
-			}
7306
-		}
7307
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7308
-		{
7309
-			$objectisused = $this->isObjectUsed($this->id);
7310
-			if (! empty($objectisused))
7311
-			{
7312
-				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7313
-				$this->error='ErrorRecordHasChildren';
7314
-				$this->errors[]=$this->error;
7315
-				$this->db->rollback();
7316
-				return 0;
7317
-			}
7318
-		}
7319
-
7320
-		if (! $error) {
7321
-			if (! $notrigger) {
7322
-				// Call triggers
7323
-				$result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7324
-				if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7325
-				// End call triggers
7326
-			}
7327
-		}
7328
-
7329
-		if (! $error && ! empty($this->isextrafieldmanaged))
7330
-		{
7331
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7332
-			$sql.= " WHERE fk_object=" . $this->id;
7333
-
7334
-			$resql = $this->db->query($sql);
7335
-			if (! $resql)
7336
-			{
7337
-				$this->errors[] = $this->db->lasterror();
7338
-				$error++;
7339
-			}
7340
-		}
7379
+    /**
7380
+     * Load comments linked with current task
7381
+     *	@return boolean	1 if ok
7382
+     */
7383
+    public function fetchComments()
7384
+    {
7385
+        require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7341 7386
 
7342
-		if (! $error)
7343
-		{
7344
-			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7387
+        $comment = new Comment($this->db);
7388
+        $result=$comment->fetchAllFor($this->element, $this->id);
7389
+        if ($result<0) {
7390
+            $this->errors=array_merge($this->errors, $comment->errors);
7391
+            return -1;
7392
+        } else {
7393
+            $this->comments = $comment->comments;
7394
+        }
7395
+        return count($this->comments);
7396
+    }
7345 7397
 
7346
-			$res = $this->db->query($sql);
7347
-			if($res===false) {
7348
-				$error++;
7349
-				$this->errors[] = $this->db->lasterror();
7350
-			}
7351
-		}
7352
-
7353
-		// Commit or rollback
7354
-		if ($error) {
7355
-			$this->db->rollback();
7356
-			return -1;
7357
-		} else {
7358
-			$this->db->commit();
7359
-			return 1;
7360
-		}
7361
-	}
7362
-
7363
-	/**
7364
-	 * Initialise object with example values
7365
-	 * Id must be 0 if object instance is a specimen
7366
-	 *
7367
-	 * @return void
7368
-	 */
7369
-	public function initAsSpecimenCommon()
7370
-	{
7371
-		$this->id = 0;
7372
-
7373
-		// TODO...
7374
-	}
7375
-
7376
-
7377
-	/* Part for comments */
7378
-
7379
-	/**
7380
-	 * Load comments linked with current task
7381
-	 *	@return boolean	1 if ok
7382
-	 */
7383
-	public function fetchComments()
7384
-	{
7385
-		require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7386
-
7387
-		$comment = new Comment($this->db);
7388
-		$result=$comment->fetchAllFor($this->element, $this->id);
7389
-		if ($result<0) {
7390
-			$this->errors=array_merge($this->errors, $comment->errors);
7391
-			return -1;
7392
-		} else {
7393
-			$this->comments = $comment->comments;
7394
-		}
7395
-		return count($this->comments);
7396
-	}
7397
-
7398
-	/**
7399
-	 * Return nb comments already posted
7400
-	 *
7401
-	 * @return int
7402
-	 */
7403
-	public function getNbComments()
7404
-	{
7405
-		return count($this->comments);
7406
-	}
7398
+    /**
7399
+     * Return nb comments already posted
7400
+     *
7401
+     * @return int
7402
+     */
7403
+    public function getNbComments()
7404
+    {
7405
+        return count($this->comments);
7406
+    }
7407 7407
 
7408 7408
     /**
7409 7409
      * Trim object parameters
Please login to merge, or discard this patch.
Spacing   +1479 added lines, -1479 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,7 +4760,7 @@  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 4766
 		if (empty($rowid)) {
@@ -4772,9 +4772,9 @@  discard block
 block discarded – undo
4772 4772
 			return 0;
4773 4773
 		}
4774 4774
 
4775
-		$this->array_options=array();
4775
+		$this->array_options = array();
4776 4776
 
4777
-		if (! is_array($optionsArray))
4777
+		if (!is_array($optionsArray))
4778 4778
 		{
4779 4779
 			// If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4780 4780
 			// TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
@@ -4790,7 +4790,7 @@  discard block
 block discarded – undo
4790 4790
 			{
4791 4791
 				$extrafields->fetch_name_optionals_label($this->table_element);
4792 4792
 			}
4793
-			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4793
+			$optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
4794 4794
 		}
4795 4795
 		else
4796 4796
 		{
@@ -4809,18 +4809,18 @@  discard block
 block discarded – undo
4809 4809
 			{
4810 4810
 				if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4811 4811
 				{
4812
-					$sql.= ", ".$name;
4812
+					$sql .= ", ".$name;
4813 4813
 				}
4814 4814
 			}
4815
-			$sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4816
-			$sql.= " WHERE fk_object = ".$rowid;
4815
+			$sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4816
+			$sql .= " WHERE fk_object = ".$rowid;
4817 4817
 
4818 4818
 			//dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4819
-			$resql=$this->db->query($sql);
4819
+			$resql = $this->db->query($sql);
4820 4820
 			if ($resql)
4821 4821
 			{
4822 4822
 				$this->array_options = array();
4823
-				$numrows=$this->db->num_rows($resql);
4823
+				$numrows = $this->db->num_rows($resql);
4824 4824
 				if ($numrows)
4825 4825
 				{
4826 4826
 					$tab = $this->db->fetch_array($resql);
@@ -4828,17 +4828,17 @@  discard block
 block discarded – undo
4828 4828
 					foreach ($tab as $key => $value)
4829 4829
 					{
4830 4830
 						// 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)
4831
-						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4831
+						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
4832 4832
 						{
4833 4833
 							// we can add this attribute to object
4834
-							if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4834
+							if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
4835 4835
 							{
4836 4836
 								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4837
-								$this->array_options["options_".$key]=$this->db->jdate($value);
4837
+								$this->array_options["options_".$key] = $this->db->jdate($value);
4838 4838
 							}
4839 4839
 							else
4840 4840
 							{
4841
-								$this->array_options["options_".$key]=$value;
4841
+								$this->array_options["options_".$key] = $value;
4842 4842
 							}
4843 4843
 
4844 4844
 							//var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
@@ -4874,10 +4874,10 @@  discard block
 block discarded – undo
4874 4874
 
4875 4875
 		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4876 4876
 		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4877
-		$resql=$this->db->query($sql_del);
4878
-		if (! $resql)
4877
+		$resql = $this->db->query($sql_del);
4878
+		if (!$resql)
4879 4879
 		{
4880
-			$this->error=$this->db->lasterror();
4880
+			$this->error = $this->db->lasterror();
4881 4881
 			$this->db->rollback();
4882 4882
 			return -1;
4883 4883
 		}
@@ -4898,37 +4898,37 @@  discard block
 block discarded – undo
4898 4898
 	 *  @return int 						-1=error, O=did nothing, 1=OK
4899 4899
 	 *  @see updateExtraField, setValueFrom
4900 4900
 	 */
4901
-	function insertExtraFields($trigger='', $userused=null)
4901
+	function insertExtraFields($trigger = '', $userused = null)
4902 4902
 	{
4903
-		global $conf,$langs,$user;
4903
+		global $conf, $langs, $user;
4904 4904
 
4905
-		if (empty($userused)) $userused=$user;
4905
+		if (empty($userused)) $userused = $user;
4906 4906
 
4907
-		$error=0;
4907
+		$error = 0;
4908 4908
 
4909 4909
 		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
4910 4910
             return 0; // For avoid conflicts if trigger used
4911 4911
 
4912
-        if (! empty($this->array_options))
4912
+        if (!empty($this->array_options))
4913 4913
 		{
4914 4914
 			// Check parameters
4915 4915
 			$langs->load('admin');
4916 4916
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4917 4917
 			$extrafields = new ExtraFields($this->db);
4918
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4918
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
4919 4919
 
4920 4920
 			//Eliminate copied source object extra_fields that do not exist in target object
4921
-			$new_array_options=array();
4921
+			$new_array_options = array();
4922 4922
 			foreach ($this->array_options as $key => $value) {
4923
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4923
+				if (in_array(substr($key, 8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4924 4924
 					$new_array_options[$key] = $value;
4925 4925
 				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4926 4926
 					$new_array_options['options_'.$key] = $value;
4927 4927
 			}
4928 4928
 
4929
-			foreach($new_array_options as $key => $value)
4929
+			foreach ($new_array_options as $key => $value)
4930 4930
 			{
4931
-			   	$attributeKey      = substr($key,8);   // Remove 'options_' prefix
4931
+			   	$attributeKey      = substr($key, 8); // Remove 'options_' prefix
4932 4932
 			   	$attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4933 4933
 			   	$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4934 4934
 			   	$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
@@ -4936,13 +4936,13 @@  discard block
 block discarded – undo
4936 4936
 
4937 4937
 			   	if ($attributeRequired)
4938 4938
 			   	{
4939
-			   		$mandatorypb=false;
4940
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4941
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
4939
+			   		$mandatorypb = false;
4940
+			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
4941
+			   		if ($this->array_options[$key] === '') $mandatorypb = true;
4942 4942
 			   		if ($mandatorypb)
4943 4943
 			   		{
4944 4944
 			   			dol_syslog($this->error);
4945
-			   			$this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4945
+			   			$this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
4946 4946
 			   			return -1;
4947 4947
 			   		}
4948 4948
 			   	}
@@ -4953,25 +4953,25 @@  discard block
 block discarded – undo
4953 4953
 			   	switch ($attributeType)
4954 4954
 			   	{
4955 4955
 			   		case 'int':
4956
-			  			if (!is_numeric($value) && $value!='')
4956
+			  			if (!is_numeric($value) && $value != '')
4957 4957
 			   			{
4958
-			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4958
+			   				$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4959 4959
 			   				return -1;
4960 4960
 			  			}
4961
-			   			elseif ($value=='')
4961
+			   			elseif ($value == '')
4962 4962
 			   			{
4963 4963
 			   				$new_array_options[$key] = null;
4964 4964
 			   			}
4965 4965
 			 			break;
4966 4966
 					case 'double':
4967 4967
 						$value = price2num($value);
4968
-						if (!is_numeric($value) && $value!='')
4968
+						if (!is_numeric($value) && $value != '')
4969 4969
 						{
4970 4970
 							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4971
-							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4971
+							$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4972 4972
 							return -1;
4973 4973
 						}
4974
-						elseif ($value=='')
4974
+						elseif ($value == '')
4975 4975
 						{
4976 4976
 							$new_array_options[$key] = null;
4977 4977
 						}
@@ -4985,12 +4985,12 @@  discard block
 block discarded – undo
4985 4985
              			}
4986 4986
              			break;*/
4987 4987
 			   		case 'password':
4988
-			   			$algo='';
4988
+			   			$algo = '';
4989 4989
 			   			if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4990 4990
 			   			{
4991 4991
 			   				// If there is an encryption choice, we use it to crypt data before insert
4992 4992
 			   				$tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4993
-			   				$algo=reset($tmparrays);
4993
+			   				$algo = reset($tmparrays);
4994 4994
 			   				if ($algo != '')
4995 4995
 			   				{
4996 4996
 			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
@@ -5001,7 +5001,7 @@  discard block
 block discarded – undo
5001 5001
 			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
5002 5002
 				   					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.
5003 5003
 				   					{
5004
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5004
+				   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
5005 5005
 				   					}
5006 5006
 									else
5007 5007
 									{
@@ -5012,7 +5012,7 @@  discard block
 block discarded – undo
5012 5012
 			   					}
5013 5013
 			   					else
5014 5014
 			   					{
5015
-			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5015
+			   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
5016 5016
 			   					}
5017 5017
 			   				}
5018 5018
 			   			}
@@ -5029,13 +5029,13 @@  discard block
 block discarded – undo
5029 5029
 						break;
5030 5030
 					case 'datetime':
5031 5031
 						// If data is a string instead of a timestamp, we convert it
5032
-						if (! is_int($this->array_options[$key])) {
5032
+						if (!is_int($this->array_options[$key])) {
5033 5033
 							$this->array_options[$key] = strtotime($this->array_options[$key]);
5034 5034
 						}
5035 5035
 						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5036 5036
 						break;
5037 5037
 		   			case 'link':
5038
-						$param_list=array_keys($attributeParam['options']);
5038
+						$param_list = array_keys($attributeParam['options']);
5039 5039
 						// 0 : ObjectName
5040 5040
 						// 1 : classPath
5041 5041
 						$InfoFieldList = explode(":", $param_list[0]);
@@ -5044,18 +5044,18 @@  discard block
 block discarded – undo
5044 5044
 						{
5045 5045
 							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5046 5046
 							{
5047
-								$new_array_options[$key]='';
5047
+								$new_array_options[$key] = '';
5048 5048
 							}
5049 5049
 							elseif ($value)
5050 5050
 							{
5051 5051
 								$object = new $InfoFieldList[0]($this->db);
5052
-								if (is_numeric($value)) $res=$object->fetch($value);
5053
-								else $res=$object->fetch('',$value);
5052
+								if (is_numeric($value)) $res = $object->fetch($value);
5053
+								else $res = $object->fetch('', $value);
5054 5054
 
5055
-								if ($res > 0) $new_array_options[$key]=$object->id;
5055
+								if ($res > 0) $new_array_options[$key] = $object->id;
5056 5056
 								else
5057 5057
 								{
5058
-									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5058
+									$this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
5059 5059
 									$this->db->rollback();
5060 5060
 									return -1;
5061 5061
 								}
@@ -5079,46 +5079,46 @@  discard block
 block discarded – undo
5079 5079
 			$this->db->query($sql_del);
5080 5080
 
5081 5081
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5082
-			foreach($new_array_options as $key => $value)
5082
+			foreach ($new_array_options as $key => $value)
5083 5083
 			{
5084
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5084
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5085 5085
 				// Add field of attribut
5086 5086
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5087
-					$sql.=",".$attributeKey;
5087
+					$sql .= ",".$attributeKey;
5088 5088
 			}
5089 5089
 			$sql .= ") VALUES (".$this->id;
5090 5090
 
5091
-			foreach($new_array_options as $key => $value)
5091
+			foreach ($new_array_options as $key => $value)
5092 5092
 			{
5093
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5093
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5094 5094
 				// Add field of attribute
5095 5095
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5096 5096
 				{
5097 5097
 					if ($new_array_options[$key] != '')
5098 5098
 					{
5099
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5099
+						$sql .= ",'".$this->db->escape($new_array_options[$key])."'";
5100 5100
 					}
5101 5101
 					else
5102 5102
 					{
5103
-						$sql.=",null";
5103
+						$sql .= ",null";
5104 5104
 					}
5105 5105
 				}
5106 5106
 			}
5107
-			$sql.=")";
5107
+			$sql .= ")";
5108 5108
 
5109 5109
 			dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5110 5110
 			$resql = $this->db->query($sql);
5111
-			if (! $resql)
5111
+			if (!$resql)
5112 5112
 			{
5113
-				$this->error=$this->db->lasterror();
5113
+				$this->error = $this->db->lasterror();
5114 5114
 				$error++;
5115 5115
 			}
5116 5116
 
5117
-			if (! $error && $trigger)
5117
+			if (!$error && $trigger)
5118 5118
 			{
5119 5119
 				// Call trigger
5120
-				$this->context=array('extrafieldaddupdate'=>1);
5121
-				$result=$this->call_trigger($trigger, $userused);
5120
+				$this->context = array('extrafieldaddupdate'=>1);
5121
+				$result = $this->call_trigger($trigger, $userused);
5122 5122
 				if ($result < 0) $error++;
5123 5123
 				// End call trigger
5124 5124
 			}
@@ -5147,26 +5147,26 @@  discard block
 block discarded – undo
5147 5147
 	 *  @return int                 		-1=error, O=did nothing, 1=OK
5148 5148
 	 *  @see setValueFrom, insertExtraFields
5149 5149
 	 */
5150
-	function updateExtraField($key, $trigger=null, $userused=null)
5150
+	function updateExtraField($key, $trigger = null, $userused = null)
5151 5151
 	{
5152
-		global $conf,$langs,$user;
5152
+		global $conf, $langs, $user;
5153 5153
 
5154
-		if (empty($userused)) $userused=$user;
5154
+		if (empty($userused)) $userused = $user;
5155 5155
 
5156
-		$error=0;
5156
+		$error = 0;
5157 5157
 
5158 5158
 		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
5159 5159
             return 0; // For avoid conflicts if trigger used
5160 5160
 
5161
-        if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5161
+        if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
5162 5162
 		{
5163 5163
 			// Check parameters
5164 5164
 			$langs->load('admin');
5165 5165
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5166 5166
 			$extrafields = new ExtraFields($this->db);
5167
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5167
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
5168 5168
 
5169
-			$value=$this->array_options["options_".$key];
5169
+			$value = $this->array_options["options_".$key];
5170 5170
 
5171 5171
 			$attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5172 5172
 			$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
@@ -5179,25 +5179,25 @@  discard block
 block discarded – undo
5179 5179
 			switch ($attributeType)
5180 5180
 			{
5181 5181
 				case 'int':
5182
-					if (!is_numeric($value) && $value!='')
5182
+					if (!is_numeric($value) && $value != '')
5183 5183
 					{
5184
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5184
+						$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5185 5185
 						return -1;
5186 5186
 					}
5187
-					elseif ($value=='')
5187
+					elseif ($value == '')
5188 5188
 					{
5189 5189
 						$this->array_options["options_".$key] = null;
5190 5190
 					}
5191 5191
 					break;
5192 5192
 				case 'double':
5193 5193
 					$value = price2num($value);
5194
-					if (!is_numeric($value) && $value!='')
5194
+					if (!is_numeric($value) && $value != '')
5195 5195
 					{
5196 5196
 						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5197
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5197
+						$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5198 5198
 						return -1;
5199 5199
 					}
5200
-					elseif ($value=='')
5200
+					elseif ($value == '')
5201 5201
 					{
5202 5202
 						$this->array_options["options_".$key] = null;
5203 5203
 					}
@@ -5214,13 +5214,13 @@  discard block
 block discarded – undo
5214 5214
 					$this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5215 5215
 					break;
5216 5216
 				case 'date':
5217
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5217
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5218 5218
 					break;
5219 5219
 				case 'datetime':
5220
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5220
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5221 5221
 					break;
5222 5222
 				case 'link':
5223
-					$param_list=array_keys($attributeParam['options']);
5223
+					$param_list = array_keys($attributeParam['options']);
5224 5224
 					// 0 : ObjectName
5225 5225
 					// 1 : classPath
5226 5226
 					$InfoFieldList = explode(":", $param_list[0]);
@@ -5228,8 +5228,8 @@  discard block
 block discarded – undo
5228 5228
 					if ($value)
5229 5229
 					{
5230 5230
 						$object = new $InfoFieldList[0]($this->db);
5231
-						$object->fetch(0,$value);
5232
-						$this->array_options["options_".$key]=$object->id;
5231
+						$object->fetch(0, $value);
5232
+						$this->array_options["options_".$key] = $object->id;
5233 5233
 					}
5234 5234
 					break;
5235 5235
 			}
@@ -5238,24 +5238,24 @@  discard block
 block discarded – undo
5238 5238
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5239 5239
 			$sql .= " WHERE fk_object = ".$this->id;
5240 5240
 			$resql = $this->db->query($sql);
5241
-			if (! $resql)
5241
+			if (!$resql)
5242 5242
 			{
5243 5243
 				$error++;
5244
-				$this->error=$this->db->lasterror();
5244
+				$this->error = $this->db->lasterror();
5245 5245
 			}
5246 5246
 
5247
-			if (! $error && $trigger)
5247
+			if (!$error && $trigger)
5248 5248
 			{
5249 5249
 				// Call trigger
5250
-				$this->context=array('extrafieldupdate'=>1);
5251
-				$result=$this->call_trigger($trigger, $userused);
5250
+				$this->context = array('extrafieldupdate'=>1);
5251
+				$result = $this->call_trigger($trigger, $userused);
5252 5252
 				if ($result < 0) $error++;
5253 5253
 				// End call trigger
5254 5254
 			}
5255 5255
 
5256 5256
 			if ($error)
5257 5257
 			{
5258
-				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5258
+				dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
5259 5259
 				$this->db->rollback();
5260 5260
 				return -1;
5261 5261
 			}
@@ -5282,71 +5282,71 @@  discard block
 block discarded – undo
5282 5282
 	 * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5283 5283
 	 * @return string
5284 5284
 	 */
5285
-	function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5285
+	function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0)
5286 5286
 	{
5287
-		global $conf,$langs,$form;
5287
+		global $conf, $langs, $form;
5288 5288
 
5289
-		if (! is_object($form))
5289
+		if (!is_object($form))
5290 5290
 		{
5291 5291
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5292
-			$form=new Form($this->db);
5292
+			$form = new Form($this->db);
5293 5293
 		}
5294 5294
 
5295
-		$val=$this->fields[$key];
5295
+		$val = $this->fields[$key];
5296 5296
 
5297
-		$out='';
5298
-        $type='';
5297
+		$out = '';
5298
+        $type = '';
5299 5299
         $param = array();
5300
-        $param['options']=array();
5301
-        $size =$this->fields[$key]['size'];
5300
+        $param['options'] = array();
5301
+        $size = $this->fields[$key]['size'];
5302 5302
         // Because we work on extrafields
5303
-        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5304
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5305
-            $type ='link';
5306
-        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5307
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5308
-            $type ='link';
5309
-        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5310
-            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5311
-            $type ='sellist';
5312
-        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5313
-            $param['options']=array();
5314
-            $type ='varchar';
5315
-            $size=$reg[1];
5316
-        } elseif(preg_match('/varchar/', $val['type'])) {
5317
-            $param['options']=array();
5318
-            $type ='varchar';
5319
-        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5320
-            $param['options']=$this->fields[$key]['arrayofkeyval'];
5321
-            $type ='select';
5303
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
5304
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5305
+            $type = 'link';
5306
+        } elseif (preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5307
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5308
+            $type = 'link';
5309
+        } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5310
+            $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5311
+            $type = 'sellist';
5312
+        } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
5313
+            $param['options'] = array();
5314
+            $type = 'varchar';
5315
+            $size = $reg[1];
5316
+        } elseif (preg_match('/varchar/', $val['type'])) {
5317
+            $param['options'] = array();
5318
+            $type = 'varchar';
5319
+        } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
5320
+            $param['options'] = $this->fields[$key]['arrayofkeyval'];
5321
+            $type = 'select';
5322 5322
         } else {
5323
-            $param['options']=array();
5324
-            $type =$this->fields[$key]['type'];
5323
+            $param['options'] = array();
5324
+            $type = $this->fields[$key]['type'];
5325 5325
         }
5326 5326
 
5327
-		$label=$this->fields[$key]['label'];
5327
+		$label = $this->fields[$key]['label'];
5328 5328
 		//$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5329
-		$default=$this->fields[$key]['default'];
5330
-		$computed=$this->fields[$key]['computed'];
5331
-		$unique=$this->fields[$key]['unique'];
5332
-		$required=$this->fields[$key]['required'];
5329
+		$default = $this->fields[$key]['default'];
5330
+		$computed = $this->fields[$key]['computed'];
5331
+		$unique = $this->fields[$key]['unique'];
5332
+		$required = $this->fields[$key]['required'];
5333 5333
 
5334
-		$langfile=$this->fields[$key]['langfile'];
5335
-		$list=$this->fields[$key]['list'];
5336
-		$hidden=abs($this->fields[$key]['visible'])!=1?1:0;
5334
+		$langfile = $this->fields[$key]['langfile'];
5335
+		$list = $this->fields[$key]['list'];
5336
+		$hidden = abs($this->fields[$key]['visible']) != 1 ? 1 : 0;
5337 5337
 
5338 5338
 		$objectid = $this->id;
5339 5339
 
5340 5340
 
5341 5341
 		if ($computed)
5342 5342
 		{
5343
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5343
+			if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5344 5344
 			else return '';
5345 5345
 		}
5346 5346
 
5347 5347
 
5348 5348
 		// Use in priority showsize from parameters, then $val['css'] then autodefine
5349
-		if (empty($morecss) && ! empty($val['css']))
5349
+		if (empty($morecss) && !empty($val['css']))
5350 5350
 		{
5351 5351
 			$showsize = $val['css'];
5352 5352
 		}
@@ -5360,16 +5360,16 @@  discard block
 block discarded – undo
5360 5360
 			{
5361 5361
 				$morecss = 'minwidth200imp';
5362 5362
 			}
5363
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5363
+			elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5364 5364
 			{
5365 5365
 				$morecss = 'maxwidth75';
5366 5366
                         }elseif ($type == 'url')
5367 5367
 			{
5368
-				$morecss='minwidth400';
5368
+				$morecss = 'minwidth400';
5369 5369
 			}
5370 5370
 			elseif ($type == 'boolean')
5371 5371
 			{
5372
-				$morecss='';
5372
+				$morecss = '';
5373 5373
 			}
5374 5374
 			else
5375 5375
 			{
@@ -5388,12 +5388,12 @@  discard block
 block discarded – undo
5388 5388
 			}
5389 5389
 		}
5390 5390
 
5391
-		if (in_array($type,array('date','datetime')))
5391
+		if (in_array($type, array('date', 'datetime')))
5392 5392
 		{
5393
-			$tmp=explode(',',$size);
5394
-			$newsize=$tmp[0];
5393
+			$tmp = explode(',', $size);
5394
+			$newsize = $tmp[0];
5395 5395
 
5396
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5396
+			$showtime = in_array($type, array('datetime')) ? 1 : 0;
5397 5397
 
5398 5398
 			// Do not show current date when field not required (see selectDate() method)
5399 5399
 			if (!$required && $value == '') $value = '-1';
@@ -5401,235 +5401,235 @@  discard block
 block discarded – undo
5401 5401
 			// TODO Must also support $moreparam
5402 5402
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5403 5403
 		}
5404
-		elseif (in_array($type,array('int','integer')))
5404
+		elseif (in_array($type, array('int', 'integer')))
5405 5405
 		{
5406
-			$tmp=explode(',',$size);
5407
-			$newsize=$tmp[0];
5408
-			$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:'').'>';
5406
+			$tmp = explode(',', $size);
5407
+			$newsize = $tmp[0];
5408
+			$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 : '').'>';
5409 5409
 		}
5410 5410
 		elseif (preg_match('/varchar/', $type))
5411 5411
 		{
5412
-			$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:'').'>';
5412
+			$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 : '').'>';
5413 5413
 		}
5414 5414
 		elseif (in_array($type, array('mail', 'phone', 'url')))
5415 5415
 		{
5416
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5416
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5417 5417
 		}
5418 5418
 		elseif ($type == 'text')
5419 5419
 		{
5420
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5420
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5421 5421
 			{
5422 5422
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5423
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5424
-				$out=$doleditor->Create(1);
5423
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
5424
+				$out = $doleditor->Create(1);
5425 5425
 			}
5426 5426
 			else
5427 5427
 			{
5428
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5428
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5429 5429
 			}
5430 5430
 		}
5431 5431
 		elseif ($type == 'html')
5432 5432
 		{
5433
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5433
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5434 5434
 			{
5435 5435
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5436
-				$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%');
5437
-                $out=$doleditor->Create(1);
5436
+				$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%');
5437
+                $out = $doleditor->Create(1);
5438 5438
 			}
5439 5439
 			else
5440 5440
 			{
5441
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5441
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5442 5442
 			}
5443 5443
 		}
5444 5444
 		elseif ($type == 'boolean')
5445 5445
 		{
5446
-			$checked='';
5446
+			$checked = '';
5447 5447
 			if (!empty($value)) {
5448
-				$checked=' checked value="1" ';
5448
+				$checked = ' checked value="1" ';
5449 5449
 			} else {
5450
-				$checked=' value="1" ';
5450
+				$checked = ' value="1" ';
5451 5451
 			}
5452
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5452
+			$out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
5453 5453
 		}
5454 5454
 		elseif ($type == 'price')
5455 5455
 		{
5456 5456
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5457
-				$value=price($value);
5457
+				$value = price($value);
5458 5458
 			}
5459
-			$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);
5459
+			$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);
5460 5460
         }
5461
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5461
+		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5462 5462
 		{
5463 5463
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5464
-				$value=price($value);
5464
+				$value = price($value);
5465 5465
 			}
5466
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5466
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
5467 5467
 		}
5468 5468
 		elseif ($type == 'select')
5469 5469
 		{
5470 5470
 			$out = '';
5471 5471
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5472
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5473
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5472
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5473
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5474 5474
 			}
5475 5475
 
5476
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5477
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5476
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5477
+                if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
5478 5478
 			foreach ($param['options'] as $key => $val)
5479 5479
 			{
5480 5480
 				if ((string) $key == '') continue;
5481 5481
 				list($val, $parent) = explode('|', $val);
5482
-				$out.='<option value="'.$key.'"';
5483
-				$out.= (((string) $value == (string) $key)?' selected':'');
5484
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5485
-				$out.='>'.$val.'</option>';
5482
+				$out .= '<option value="'.$key.'"';
5483
+				$out .= (((string) $value == (string) $key) ? ' selected' : '');
5484
+				$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5485
+				$out .= '>'.$val.'</option>';
5486 5486
 			}
5487
-			$out.='</select>';
5487
+			$out .= '</select>';
5488 5488
 		}
5489 5489
 		elseif ($type == 'sellist')
5490 5490
 		{
5491 5491
 			$out = '';
5492 5492
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
5493
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5494
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5493
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5494
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5495 5495
 			}
5496 5496
 
5497
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5497
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5498 5498
 			if (is_array($param['options']))
5499 5499
 			{
5500
-				$param_list=array_keys($param['options']);
5500
+				$param_list = array_keys($param['options']);
5501 5501
 				$InfoFieldList = explode(":", $param_list[0]);
5502
-				$parentName='';
5503
-				$parentField='';
5502
+				$parentName = '';
5503
+				$parentField = '';
5504 5504
 				// 0 : tableName
5505 5505
 				// 1 : label field name
5506 5506
 				// 2 : key fields name (if differ of rowid)
5507 5507
 				// 3 : key field parent (for dependent lists)
5508 5508
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5509
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5509
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5510 5510
 
5511 5511
 
5512
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5512
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
5513 5513
 				{
5514 5514
 					if (strpos($InfoFieldList[4], 'extra.') !== false)
5515 5515
 					{
5516
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
5516
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5517 5517
 					} else {
5518
-						$keyList=$InfoFieldList[2].' as rowid';
5518
+						$keyList = $InfoFieldList[2].' as rowid';
5519 5519
 					}
5520 5520
 				}
5521
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5521
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
5522 5522
 				{
5523 5523
 					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5524
-					$keyList.= ', '.$parentField;
5524
+					$keyList .= ', '.$parentField;
5525 5525
 				}
5526 5526
 
5527
-				$fields_label = explode('|',$InfoFieldList[1]);
5527
+				$fields_label = explode('|', $InfoFieldList[1]);
5528 5528
 				if (is_array($fields_label))
5529 5529
 				{
5530
-					$keyList .=', ';
5530
+					$keyList .= ', ';
5531 5531
 					$keyList .= implode(', ', $fields_label);
5532 5532
 				}
5533 5533
 
5534
-				$sqlwhere='';
5534
+				$sqlwhere = '';
5535 5535
 				$sql = 'SELECT '.$keyList;
5536
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5536
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5537 5537
 				if (!empty($InfoFieldList[4]))
5538 5538
 				{
5539 5539
 					// can use SELECT request
5540
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5541
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5540
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5541
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5542 5542
 					}
5543 5543
 
5544 5544
 					// current object id can be use into filter
5545
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5546
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5545
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5546
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5547 5547
 					} else {
5548
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5548
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5549 5549
 					}
5550 5550
 					//We have to join on extrafield table
5551
-					if (strpos($InfoFieldList[4], 'extra')!==false)
5551
+					if (strpos($InfoFieldList[4], 'extra') !== false)
5552 5552
 					{
5553
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5554
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5553
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5554
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5555 5555
 					}
5556 5556
 					else
5557 5557
 					{
5558
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5558
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5559 5559
 					}
5560 5560
 				}
5561 5561
 				else
5562 5562
 				{
5563
-					$sqlwhere.= ' WHERE 1=1';
5563
+					$sqlwhere .= ' WHERE 1=1';
5564 5564
 				}
5565 5565
 				// Some tables may have field, some other not. For the moment we disable it.
5566
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
5566
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5567 5567
 				{
5568
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5568
+					$sqlwhere .= ' AND entity = '.Globals::$conf->entity;
5569 5569
                 }
5570
-				$sql.=$sqlwhere;
5570
+				$sql .= $sqlwhere;
5571 5571
 				//print $sql;
5572 5572
 
5573
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
5573
+				$sql .= ' ORDER BY '.implode(', ', $fields_label);
5574 5574
 
5575 5575
 				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5576 5576
 				$resql = $this->db->query($sql);
5577 5577
 				if ($resql)
5578 5578
 				{
5579
-					$out.='<option value="0">&nbsp;</option>';
5579
+					$out .= '<option value="0">&nbsp;</option>';
5580 5580
 					$num = $this->db->num_rows($resql);
5581 5581
 					$i = 0;
5582 5582
 					while ($i < $num)
5583 5583
 					{
5584
-						$labeltoshow='';
5584
+						$labeltoshow = '';
5585 5585
 						$obj = $this->db->fetch_object($resql);
5586 5586
 
5587 5587
 						// Several field into label (eq table:code|libelle:rowid)
5588 5588
 						$notrans = false;
5589
-						$fields_label = explode('|',$InfoFieldList[1]);
5589
+						$fields_label = explode('|', $InfoFieldList[1]);
5590 5590
 						if (is_array($fields_label))
5591 5591
 						{
5592 5592
 							$notrans = true;
5593 5593
 							foreach ($fields_label as $field_toshow)
5594 5594
 							{
5595
-								$labeltoshow.= $obj->$field_toshow.' ';
5595
+								$labeltoshow .= $obj->$field_toshow.' ';
5596 5596
 							}
5597 5597
 						}
5598 5598
 						else
5599 5599
 						{
5600
-							$labeltoshow=$obj->{$InfoFieldList[1]};
5600
+							$labeltoshow = $obj->{$InfoFieldList[1]};
5601 5601
 						}
5602
-						$labeltoshow=dol_trunc($labeltoshow,45);
5602
+						$labeltoshow = dol_trunc($labeltoshow, 45);
5603 5603
 
5604 5604
 						if ($value == $obj->rowid)
5605 5605
 						{
5606 5606
 							foreach ($fields_label as $field_toshow)
5607 5607
 							{
5608
-								$translabel=$langs->trans($obj->$field_toshow);
5609
-								if ($translabel!=$obj->$field_toshow) {
5610
-									$labeltoshow=dol_trunc($translabel,18).' ';
5611
-								}else {
5612
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5608
+								$translabel = $langs->trans($obj->$field_toshow);
5609
+								if ($translabel != $obj->$field_toshow) {
5610
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5611
+								} else {
5612
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5613 5613
 								}
5614 5614
 							}
5615
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5615
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5616 5616
 						}
5617 5617
 						else
5618 5618
 						{
5619
-							if (! $notrans)
5619
+							if (!$notrans)
5620 5620
 							{
5621
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5622
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5623
-									$labeltoshow=dol_trunc($translabel,18);
5621
+								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5622
+								if ($translabel != $obj->{$InfoFieldList[1]}) {
5623
+									$labeltoshow = dol_trunc($translabel, 18);
5624 5624
 								}
5625 5625
 								else {
5626
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5626
+									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]},18);
5627 5627
 								}
5628 5628
 							}
5629
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
5630
-							if ($value==$obj->rowid)
5629
+							if (empty($labeltoshow)) $labeltoshow = '(not defined)';
5630
+							if ($value == $obj->rowid)
5631 5631
 							{
5632
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5632
+								$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5633 5633
 							}
5634 5634
 
5635 5635
 							if (!empty($InfoFieldList[3]) && $parentField)
@@ -5637,10 +5637,10 @@  discard block
 block discarded – undo
5637 5637
 								$parent = $parentName.':'.$obj->{$parentField};
5638 5638
 							}
5639 5639
 
5640
-							$out.='<option value="'.$obj->rowid.'"';
5641
-							$out.= ($value==$obj->rowid?' selected':'');
5642
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5643
-							$out.='>'.$labeltoshow.'</option>';
5640
+							$out .= '<option value="'.$obj->rowid.'"';
5641
+							$out .= ($value == $obj->rowid ? ' selected' : '');
5642
+							$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5643
+							$out .= '>'.$labeltoshow.'</option>';
5644 5644
 						}
5645 5645
 
5646 5646
 						$i++;
@@ -5651,23 +5651,23 @@  discard block
 block discarded – undo
5651 5651
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5652 5652
 				}
5653 5653
 			}
5654
-			$out.='</select>';
5654
+			$out .= '</select>';
5655 5655
 		}
5656 5656
 		elseif ($type == 'checkbox')
5657 5657
 		{
5658
-			$value_arr=explode(',',$value);
5659
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5658
+			$value_arr = explode(',', $value);
5659
+			$out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5660 5660
 		}
5661 5661
 		elseif ($type == 'radio')
5662 5662
 		{
5663
-			$out='';
5663
+			$out = '';
5664 5664
 			foreach ($param['options'] as $keyopt => $val)
5665 5665
 			{
5666
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5667
-				$out.=' value="'.$keyopt.'"';
5668
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5669
-				$out.= ($value==$keyopt?'checked':'');
5670
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5666
+				$out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
5667
+				$out .= ' value="'.$keyopt.'"';
5668
+				$out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5669
+				$out .= ($value == $keyopt ? 'checked' : '');
5670
+				$out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5671 5671
 			}
5672 5672
 		}
5673 5673
 		elseif ($type == 'chkbxlst')
@@ -5682,24 +5682,24 @@  discard block
 block discarded – undo
5682 5682
 			if (is_array($param['options'])) {
5683 5683
 				$param_list = array_keys($param['options']);
5684 5684
 				$InfoFieldList = explode(":", $param_list[0]);
5685
-				$parentName='';
5686
-				$parentField='';
5685
+				$parentName = '';
5686
+				$parentField = '';
5687 5687
 				// 0 : tableName
5688 5688
 				// 1 : label field name
5689 5689
 				// 2 : key fields name (if differ of rowid)
5690 5690
 				// 3 : key field parent (for dependent lists)
5691 5691
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5692
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5692
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5693 5693
 
5694
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5695
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5696
-					$keyList .= ', ' . $parentField;
5694
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
5695
+					list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5696
+					$keyList .= ', '.$parentField;
5697 5697
 				}
5698
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5698
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
5699 5699
 					if (strpos($InfoFieldList[4], 'extra.') !== false) {
5700
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5700
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5701 5701
 					} else {
5702
-						$keyList = $InfoFieldList[2] . ' as rowid';
5702
+						$keyList = $InfoFieldList[2].' as rowid';
5703 5703
 					}
5704 5704
 				}
5705 5705
 
@@ -5710,50 +5710,50 @@  discard block
 block discarded – undo
5710 5710
 				}
5711 5711
 
5712 5712
 				$sqlwhere = '';
5713
-				$sql = 'SELECT ' . $keyList;
5714
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5715
-				if (! empty($InfoFieldList[4])) {
5713
+				$sql = 'SELECT '.$keyList;
5714
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5715
+				if (!empty($InfoFieldList[4])) {
5716 5716
 
5717 5717
 					// can use SELECT request
5718
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5719
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5718
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5719
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5720 5720
 					}
5721 5721
 
5722 5722
 					// current object id can be use into filter
5723
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5724
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5723
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5724
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5725 5725
 					} else {
5726
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5726
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5727 5727
 					}
5728 5728
 
5729 5729
 					// We have to join on extrafield table
5730 5730
 					if (strpos($InfoFieldList[4], 'extra') !== false) {
5731
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5732
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5731
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5732
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5733 5733
 					} else {
5734
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5734
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5735 5735
 					}
5736 5736
 				} else {
5737 5737
 					$sqlwhere .= ' WHERE 1=1';
5738 5738
 				}
5739 5739
 				// Some tables may have field, some other not. For the moment we disable it.
5740
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
5740
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5741 5741
 				{
5742
-					$sqlwhere .= ' AND entity = ' . Globals::$conf->entity;
5742
+					$sqlwhere .= ' AND entity = '.Globals::$conf->entity;
5743 5743
                 }
5744 5744
 				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
5745 5745
 				// print $sql;
5746 5746
 
5747 5747
 				$sql .= $sqlwhere;
5748
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5748
+				dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
5749 5749
 				$resql = $this->db->query($sql);
5750 5750
 				if ($resql) {
5751 5751
 					$num = $this->db->num_rows($resql);
5752 5752
 					$i = 0;
5753 5753
 
5754
-					$data=array();
5754
+					$data = array();
5755 5755
 
5756
-					while ( $i < $num ) {
5756
+					while ($i < $num) {
5757 5757
 						$labeltoshow = '';
5758 5758
 						$obj = $this->db->fetch_object($resql);
5759 5759
 
@@ -5762,8 +5762,8 @@  discard block
 block discarded – undo
5762 5762
 						$fields_label = explode('|', $InfoFieldList[1]);
5763 5763
 						if (is_array($fields_label)) {
5764 5764
 							$notrans = true;
5765
-							foreach ( $fields_label as $field_toshow ) {
5766
-								$labeltoshow .= $obj->$field_toshow . ' ';
5765
+							foreach ($fields_label as $field_toshow) {
5766
+								$labeltoshow .= $obj->$field_toshow.' ';
5767 5767
 							}
5768 5768
 						} else {
5769 5769
 							$labeltoshow = $obj->{$InfoFieldList[1]};
@@ -5771,18 +5771,18 @@  discard block
 block discarded – undo
5771 5771
 						$labeltoshow = dol_trunc($labeltoshow, 45);
5772 5772
 
5773 5773
 						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5774
-							foreach ( $fields_label as $field_toshow ) {
5774
+							foreach ($fields_label as $field_toshow) {
5775 5775
 								$translabel = $langs->trans($obj->$field_toshow);
5776 5776
 								if ($translabel != $obj->$field_toshow) {
5777
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
5777
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5778 5778
 								} else {
5779
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5779
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5780 5780
 								}
5781 5781
 							}
5782 5782
 
5783
-							$data[$obj->rowid]=$labeltoshow;
5783
+							$data[$obj->rowid] = $labeltoshow;
5784 5784
 						} else {
5785
-							if (! $notrans) {
5785
+							if (!$notrans) {
5786 5786
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5787 5787
 								if ($translabel != $obj->{$InfoFieldList[1]}) {
5788 5788
 									$labeltoshow = dol_trunc($translabel, 18);
@@ -5794,66 +5794,66 @@  discard block
 block discarded – undo
5794 5794
 								$labeltoshow = '(not defined)';
5795 5795
 
5796 5796
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5797
-									$data[$obj->rowid]=$labeltoshow;
5797
+									$data[$obj->rowid] = $labeltoshow;
5798 5798
 								}
5799 5799
 
5800
-								if (! empty($InfoFieldList[3]) && $parentField) {
5801
-									$parent = $parentName . ':' . $obj->{$parentField};
5800
+								if (!empty($InfoFieldList[3]) && $parentField) {
5801
+									$parent = $parentName.':'.$obj->{$parentField};
5802 5802
 								}
5803 5803
 
5804
-								$data[$obj->rowid]=$labeltoshow;
5804
+								$data[$obj->rowid] = $labeltoshow;
5805 5805
 						}
5806 5806
 
5807
-						$i ++;
5807
+						$i++;
5808 5808
 					}
5809 5809
 					$this->db->free($resql);
5810 5810
 
5811
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5811
+					$out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5812 5812
 				} else {
5813
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5813
+					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5814 5814
 				}
5815 5815
 			}
5816 5816
 		}
5817 5817
 		elseif ($type == 'link')
5818 5818
 		{
5819
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5820
-			$showempty=(($required && $default != '')?0:1);
5821
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5819
+			$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
5820
+			$showempty = (($required && $default != '') ? 0 : 1);
5821
+			$out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5822 5822
 			if (Globals::$conf->global->MAIN_FEATURES_LEVEL >= 2) {
5823
-            			list($class,$classfile)=explode(':',$param_list[0]);
5824
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5825
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5826
-            			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5823
+            			list($class, $classfile) = explode(':', $param_list[0]);
5824
+            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
5825
+            			else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php', 1);
5826
+            			$out .= '<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5827 5827
             			// TODO Add Javascript code to add input fields contents to new elements urls
5828 5828
 			}
5829 5829
 		}
5830 5830
 		elseif ($type == 'password')
5831 5831
 		{
5832 5832
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
5833
-			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5833
+			$out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
5834 5834
 		}
5835 5835
 		elseif ($type == 'array')
5836 5836
 		{
5837 5837
 			$newval = $val;
5838 5838
 			$newval['type'] = 'varchar(256)';
5839 5839
 
5840
-			$out='';
5840
+			$out = '';
5841 5841
 
5842 5842
 			$inputs = array();
5843
-			if(! empty($value)) {
5844
-				foreach($value as $option) {
5845
-					$out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5846
-					$out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5843
+			if (!empty($value)) {
5844
+				foreach ($value as $option) {
5845
+					$out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5846
+					$out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5847 5847
 				}
5848 5848
 			}
5849 5849
 
5850
-			$out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5850
+			$out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5851 5851
 
5852 5852
 			$newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5853
-			$newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5853
+			$newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5854 5854
 
5855 5855
 			if (!empty(Globals::$conf->use_javascript_ajax)) {
5856
-                $out.= '
5856
+                $out .= '
5857 5857
 					<script type="text/javascript">
5858 5858
 					$(document).ready(function() {
5859 5859
 						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
@@ -5868,7 +5868,7 @@  discard block
 block discarded – undo
5868 5868
 			}
5869 5869
 		}
5870 5870
 		if (!empty($hidden)) {
5871
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5871
+			$out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5872 5872
 		}
5873 5873
 		/* Add comments
5874 5874
 		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
@@ -5890,14 +5890,14 @@  discard block
 block discarded – undo
5890 5890
 	 * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5891 5891
 	 * @return string
5892 5892
 	 */
5893
-	function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5893
+	function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $showsize = 0)
5894 5894
 	{
5895
-		global $conf,$langs,$form;
5895
+		global $conf, $langs, $form;
5896 5896
 
5897
-		if (! is_object($form))
5897
+		if (!is_object($form))
5898 5898
 		{
5899 5899
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5900
-			$form=new Form($this->db);
5900
+			$form = new Form($this->db);
5901 5901
 		}
5902 5902
 
5903 5903
 		$objectid = $this->id;
@@ -5908,28 +5908,28 @@  discard block
 block discarded – undo
5908 5908
 		// Convert var to be able to share same code than showOutputField of extrafields
5909 5909
 		if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5910 5910
 		{
5911
-			$type = 'varchar';		// convert varchar(xx) int varchar
5911
+			$type = 'varchar'; // convert varchar(xx) int varchar
5912 5912
 			$size = $reg[1];
5913 5913
 		}
5914
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5915
-		if (is_array($val['arrayofkeyval'])) $type='select';
5916
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5914
+		elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
5915
+		if (is_array($val['arrayofkeyval'])) $type = 'select';
5916
+		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
5917 5917
 
5918
-		$default=$val['default'];
5919
-		$computed=$val['computed'];
5920
-		$unique=$val['unique'];
5921
-		$required=$val['required'];
5922
-		$param=$val['param'];
5918
+		$default = $val['default'];
5919
+		$computed = $val['computed'];
5920
+		$unique = $val['unique'];
5921
+		$required = $val['required'];
5922
+		$param = $val['param'];
5923 5923
 		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5924 5924
 		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5925 5925
 		{
5926
-			$type='link';
5927
-			$param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5926
+			$type = 'link';
5927
+			$param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5928 5928
 		}
5929
-		$langfile=$val['langfile'];
5930
-		$list=$val['list'];
5931
-		$help=$val['help'];
5932
-		$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)
5929
+		$langfile = $val['langfile'];
5930
+		$list = $val['list'];
5931
+		$help = $val['help'];
5932
+		$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)
5933 5933
 
5934 5934
 		if ($hidden) return '';
5935 5935
 
@@ -5953,18 +5953,18 @@  discard block
 block discarded – undo
5953 5953
 				//$showsize=19;
5954 5954
 				$showsize = 'minwidth200imp';
5955 5955
 			}
5956
-			elseif (in_array($type,array('int','double','price')))
5956
+			elseif (in_array($type, array('int', 'double', 'price')))
5957 5957
 			{
5958 5958
 				//$showsize=10;
5959 5959
 				$showsize = 'maxwidth75';
5960 5960
 			}
5961 5961
 			elseif ($type == 'url')
5962 5962
 			{
5963
-				$showsize='minwidth400';
5963
+				$showsize = 'minwidth400';
5964 5964
 			}
5965 5965
 			elseif ($type == 'boolean')
5966 5966
 			{
5967
-				$showsize='';
5967
+				$showsize = '';
5968 5968
 			}
5969 5969
 			else
5970 5970
 			{
@@ -5985,49 +5985,49 @@  discard block
 block discarded – undo
5985 5985
 		}
5986 5986
 
5987 5987
 		// Format output value differently according to properties of field
5988
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5989
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5988
+		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
5989
+		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
5990 5990
 		elseif ($type == 'date')
5991 5991
 		{
5992
-			if(! empty($value)) {
5993
-				$value=dol_print_date($value,'day');
5992
+			if (!empty($value)) {
5993
+				$value = dol_print_date($value, 'day');
5994 5994
 			} else {
5995
-				$value='';
5995
+				$value = '';
5996 5996
 			}
5997 5997
 		}
5998 5998
 		elseif ($type == 'datetime')
5999 5999
 		{
6000
-			if(! empty($value)) {
6001
-				$value=dol_print_date($value,'dayhour');
6000
+			if (!empty($value)) {
6001
+				$value = dol_print_date($value, 'dayhour');
6002 6002
 			} else {
6003
-				$value='';
6003
+				$value = '';
6004 6004
 			}
6005 6005
 		}
6006 6006
 		elseif ($type == 'double')
6007 6007
 		{
6008 6008
 			if (!empty($value)) {
6009
-				$value=price($value);
6009
+				$value = price($value);
6010 6010
 			}
6011 6011
 		}
6012 6012
 		elseif ($type == 'boolean')
6013 6013
 		{
6014
-			$checked='';
6014
+			$checked = '';
6015 6015
 			if (!empty($value)) {
6016
-				$checked=' checked ';
6016
+				$checked = ' checked ';
6017 6017
 			}
6018
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6018
+			$value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
6019 6019
 		}
6020 6020
 		elseif ($type == 'mail')
6021 6021
 		{
6022
-			$value=dol_print_email($value,0,0,0,64,1,1);
6022
+			$value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
6023 6023
 		}
6024 6024
 		elseif ($type == 'url')
6025 6025
 		{
6026
-			$value=dol_print_url($value,'_blank',32,1);
6026
+			$value = dol_print_url($value, '_blank', 32, 1);
6027 6027
 		}
6028 6028
 		elseif ($type == 'phone')
6029 6029
 		{
6030
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6030
+			$value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6031 6031
 		}
6032 6032
 		elseif ($type == 'price')
6033 6033
 		{
@@ -6035,40 +6035,40 @@  discard block
 block discarded – undo
6035 6035
         }
6036 6036
 		elseif ($type == 'select')
6037 6037
 		{
6038
-			$value=$param['options'][$value];
6038
+			$value = $param['options'][$value];
6039 6039
 		}
6040 6040
 		elseif ($type == 'sellist')
6041 6041
 		{
6042
-			$param_list=array_keys($param['options']);
6042
+			$param_list = array_keys($param['options']);
6043 6043
 			$InfoFieldList = explode(":", $param_list[0]);
6044 6044
 
6045
-			$selectkey="rowid";
6046
-			$keyList='rowid';
6045
+			$selectkey = "rowid";
6046
+			$keyList = 'rowid';
6047 6047
 
6048
-			if (count($InfoFieldList)>=3)
6048
+			if (count($InfoFieldList) >= 3)
6049 6049
 			{
6050 6050
 				$selectkey = $InfoFieldList[2];
6051
-				$keyList=$InfoFieldList[2].' as rowid';
6051
+				$keyList = $InfoFieldList[2].' as rowid';
6052 6052
 			}
6053 6053
 
6054
-			$fields_label = explode('|',$InfoFieldList[1]);
6055
-			if(is_array($fields_label)) {
6056
-				$keyList .=', ';
6054
+			$fields_label = explode('|', $InfoFieldList[1]);
6055
+			if (is_array($fields_label)) {
6056
+				$keyList .= ', ';
6057 6057
 				$keyList .= implode(', ', $fields_label);
6058 6058
 			}
6059 6059
 
6060 6060
 			$sql = 'SELECT '.$keyList;
6061
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6062
-			if (strpos($InfoFieldList[4], 'extra')!==false)
6061
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6062
+			if (strpos($InfoFieldList[4], 'extra') !== false)
6063 6063
 			{
6064
-				$sql.= ' as main';
6064
+				$sql .= ' as main';
6065 6065
 			}
6066
-			if ($selectkey=='rowid' && empty($value)) {
6067
-				$sql.= " WHERE ".$selectkey."=0";
6068
-			} elseif ($selectkey=='rowid') {
6069
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6070
-			}else {
6071
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6066
+			if ($selectkey == 'rowid' && empty($value)) {
6067
+				$sql .= " WHERE ".$selectkey."=0";
6068
+			} elseif ($selectkey == 'rowid') {
6069
+				$sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
6070
+			} else {
6071
+				$sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6072 6072
 			}
6073 6073
 
6074 6074
 			//$sql.= ' AND entity = '.Globals::$conf->entity;
@@ -6077,38 +6077,38 @@  discard block
 block discarded – undo
6077 6077
 			$resql = $this->db->query($sql);
6078 6078
 			if ($resql)
6079 6079
 			{
6080
-				$value='';	// value was used, so now we reste it to use it to build final output
6080
+				$value = ''; // value was used, so now we reste it to use it to build final output
6081 6081
 
6082 6082
 				$obj = $this->db->fetch_object($resql);
6083 6083
 
6084 6084
 				// Several field into label (eq table:code|libelle:rowid)
6085
-				$fields_label = explode('|',$InfoFieldList[1]);
6085
+				$fields_label = explode('|', $InfoFieldList[1]);
6086 6086
 
6087
-				if(is_array($fields_label) && count($fields_label)>1)
6087
+				if (is_array($fields_label) && count($fields_label) > 1)
6088 6088
 				{
6089 6089
 					foreach ($fields_label as $field_toshow)
6090 6090
 					{
6091
-						$translabel='';
6091
+						$translabel = '';
6092 6092
 						if (!empty($obj->$field_toshow)) {
6093
-							$translabel=$langs->trans($obj->$field_toshow);
6093
+							$translabel = $langs->trans($obj->$field_toshow);
6094 6094
 						}
6095
-						if ($translabel!=$field_toshow) {
6096
-							$value.=dol_trunc($translabel,18).' ';
6097
-						}else {
6098
-							$value.=$obj->$field_toshow.' ';
6095
+						if ($translabel != $field_toshow) {
6096
+							$value .= dol_trunc($translabel, 18).' ';
6097
+						} else {
6098
+							$value .= $obj->$field_toshow.' ';
6099 6099
 						}
6100 6100
 					}
6101 6101
 				}
6102 6102
 				else
6103 6103
 				{
6104
-					$translabel='';
6104
+					$translabel = '';
6105 6105
 					if (!empty($obj->{$InfoFieldList[1]})) {
6106
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
6106
+						$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6107 6107
 					}
6108
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6109
-						$value=dol_trunc($translabel,18);
6110
-					}else {
6111
-						$value=$obj->{$InfoFieldList[1]};
6108
+					if ($translabel != $obj->{$InfoFieldList[1]}) {
6109
+						$value = dol_trunc($translabel, 18);
6110
+					} else {
6111
+						$value = $obj->{$InfoFieldList[1]};
6112 6112
 					}
6113 6113
 				}
6114 6114
 			}
@@ -6116,18 +6116,18 @@  discard block
 block discarded – undo
6116 6116
 		}
6117 6117
 		elseif ($type == 'radio')
6118 6118
 		{
6119
-			$value=$param['options'][$value];
6119
+			$value = $param['options'][$value];
6120 6120
 		}
6121 6121
 		elseif ($type == 'checkbox')
6122 6122
 		{
6123
-			$value_arr=explode(',',$value);
6124
-			$value='';
6125
-			if (is_array($value_arr) && count($value_arr)>0)
6123
+			$value_arr = explode(',', $value);
6124
+			$value = '';
6125
+			if (is_array($value_arr) && count($value_arr) > 0)
6126 6126
 			{
6127 6127
 				foreach ($value_arr as $keyval=>$valueval) {
6128
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6128
+					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6129 6129
 				}
6130
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6130
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6131 6131
 			}
6132 6132
 		}
6133 6133
 		elseif ($type == 'chkbxlst')
@@ -6142,7 +6142,7 @@  discard block
 block discarded – undo
6142 6142
 
6143 6143
 			if (count($InfoFieldList) >= 3) {
6144 6144
 				$selectkey = $InfoFieldList[2];
6145
-				$keyList = $InfoFieldList[2] . ' as rowid';
6145
+				$keyList = $InfoFieldList[2].' as rowid';
6146 6146
 			}
6147 6147
 
6148 6148
 			$fields_label = explode('|', $InfoFieldList[1]);
@@ -6151,75 +6151,75 @@  discard block
 block discarded – undo
6151 6151
 				$keyList .= implode(', ', $fields_label);
6152 6152
 			}
6153 6153
 
6154
-			$sql = 'SELECT ' . $keyList;
6155
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6154
+			$sql = 'SELECT '.$keyList;
6155
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6156 6156
 			if (strpos($InfoFieldList[4], 'extra') !== false) {
6157 6157
 				$sql .= ' as main';
6158 6158
 			}
6159 6159
 			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6160 6160
 			// $sql.= ' AND entity = '.Globals::$conf->entity;
6161 6161
 
6162
-            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6162
+            dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
6163 6163
 			$resql = $this->db->query($sql);
6164 6164
 			if ($resql) {
6165 6165
 				$value = ''; // value was used, so now we reste it to use it to build final output
6166
-				$toprint=array();
6167
-				while ( $obj = $this->db->fetch_object($resql) ) {
6166
+				$toprint = array();
6167
+				while ($obj = $this->db->fetch_object($resql)) {
6168 6168
 
6169 6169
 					// Several field into label (eq table:code|libelle:rowid)
6170 6170
 					$fields_label = explode('|', $InfoFieldList[1]);
6171 6171
 					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6172 6172
 						if (is_array($fields_label) && count($fields_label) > 1) {
6173
-							foreach ( $fields_label as $field_toshow ) {
6173
+							foreach ($fields_label as $field_toshow) {
6174 6174
 								$translabel = '';
6175
-								if (! empty($obj->$field_toshow)) {
6175
+								if (!empty($obj->$field_toshow)) {
6176 6176
 									$translabel = $langs->trans($obj->$field_toshow);
6177 6177
 								}
6178 6178
 								if ($translabel != $field_toshow) {
6179
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6179
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6180 6180
 								} else {
6181
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6181
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6182 6182
 								}
6183 6183
 							}
6184 6184
 						} else {
6185 6185
 							$translabel = '';
6186
-							if (! empty($obj->{$InfoFieldList[1]})) {
6186
+							if (!empty($obj->{$InfoFieldList[1]})) {
6187 6187
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6188 6188
 							}
6189 6189
 							if ($translabel != $obj->{$InfoFieldList[1]}) {
6190
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6190
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6191 6191
 							} else {
6192
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6192
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6193 6193
 							}
6194 6194
 						}
6195 6195
 					}
6196 6196
 				}
6197
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6197
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6198 6198
 			} else {
6199
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6199
+				dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6200 6200
 			}
6201 6201
 		}
6202 6202
 		elseif ($type == 'link')
6203 6203
 		{
6204
-			$out='';
6204
+			$out = '';
6205 6205
 
6206 6206
 			// only if something to display (perf)
6207 6207
 			if ($value)
6208 6208
 			{
6209
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6209
+				$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
6210 6210
 
6211 6211
 				$InfoFieldList = explode(":", $param_list[0]);
6212
-				$classname=$InfoFieldList[0];
6213
-				$classpath=$InfoFieldList[1];
6214
-				$getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6215
-				if (! empty($classpath))
6212
+				$classname = $InfoFieldList[0];
6213
+				$classpath = $InfoFieldList[1];
6214
+				$getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6215
+				if (!empty($classpath))
6216 6216
 				{
6217 6217
 					dol_include_once($InfoFieldList[1]);
6218 6218
 					if ($classname && class_exists($classname))
6219 6219
 					{
6220 6220
 						$object = new $classname($this->db);
6221 6221
 						$object->fetch($value);
6222
-						$value=$object->getNomUrl($getnomurlparam);
6222
+						$value = $object->getNomUrl($getnomurlparam);
6223 6223
 					}
6224 6224
 				}
6225 6225
 				else
@@ -6228,15 +6228,15 @@  discard block
 block discarded – undo
6228 6228
 					return 'Error bad setup of extrafield';
6229 6229
 				}
6230 6230
 			}
6231
-			else $value='';
6231
+			else $value = '';
6232 6232
 		}
6233 6233
 		elseif ($type == 'text' || $type == 'html')
6234 6234
 		{
6235
-			$value=dol_htmlentitiesbr($value);
6235
+			$value = dol_htmlentitiesbr($value);
6236 6236
 		}
6237 6237
 		elseif ($type == 'password')
6238 6238
 		{
6239
-			$value=preg_replace('/./i','*',$value);
6239
+			$value = preg_replace('/./i', '*', $value);
6240 6240
 		}
6241 6241
 		elseif ($type == 'array')
6242 6242
 		{
@@ -6244,7 +6244,7 @@  discard block
 block discarded – undo
6244 6244
 		}
6245 6245
 
6246 6246
 		//print $type.'-'.$size;
6247
-		$out=$value;
6247
+		$out = $value;
6248 6248
 
6249 6249
 		return $out;
6250 6250
 	}
@@ -6261,11 +6261,11 @@  discard block
 block discarded – undo
6261 6261
 	 * @param	string		$onetrtd		All fields in same tr td
6262 6262
 	 * @return 	string
6263 6263
 	 */
6264
-	function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6264
+	function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
6265 6265
 	{
6266 6266
 		global $db, $conf, $langs, $action, $form;
6267 6267
 
6268
-		if (! is_object($form)) $form=new Form($db);
6268
+		if (!is_object($form)) $form = new Form($db);
6269 6269
 
6270 6270
 		$out = '';
6271 6271
 
@@ -6276,10 +6276,10 @@  discard block
 block discarded – undo
6276 6276
 			$out .= "\n";
6277 6277
 
6278 6278
 			$e = 0;
6279
-			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6279
+			foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6280 6280
 			{
6281 6281
 				// Show only the key field in params
6282
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6282
+				if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
6283 6283
 
6284 6284
 				$enabled = 1;
6285 6285
 				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
@@ -6293,25 +6293,25 @@  discard block
 block discarded – undo
6293 6293
 					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6294 6294
 				}
6295 6295
 
6296
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6296
+				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6297 6297
 				if (empty($perms)) continue;
6298 6298
 
6299 6299
 				// Load language if required
6300
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6300
+				if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6301 6301
 
6302
-				$colspan='3';
6303
-				if (is_array($params) && count($params)>0) {
6304
-					if (array_key_exists('colspan',$params)) {
6305
-						$colspan=$params['colspan'];
6302
+				$colspan = '3';
6303
+				if (is_array($params) && count($params) > 0) {
6304
+					if (array_key_exists('colspan', $params)) {
6305
+						$colspan = $params['colspan'];
6306 6306
 					}
6307 6307
 				}
6308 6308
 
6309
-				switch($mode) {
6309
+				switch ($mode) {
6310 6310
 					case "view":
6311
-						$value=$this->array_options["options_".$key.$keysuffix];
6311
+						$value = $this->array_options["options_".$key.$keysuffix];
6312 6312
 						break;
6313 6313
 					case "edit":
6314
-						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6314
+						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values.
6315 6315
 						// GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6316 6316
 						if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6317 6317
 						{
@@ -6322,7 +6322,7 @@  discard block
 block discarded – undo
6322 6322
 								$value = $getposttemp;
6323 6323
 							}
6324 6324
 						} else {
6325
-							$value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6325
+							$value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
6326 6326
 						}
6327 6327
 						//var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6328 6328
 						break;
@@ -6334,11 +6334,11 @@  discard block
 block discarded – undo
6334 6334
 				}
6335 6335
 				else
6336 6336
 				{
6337
-					$csstyle='';
6338
-					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6339
-					if (is_array($params) && count($params)>0) {
6340
-						if (array_key_exists('style',$params)) {
6341
-							$csstyle=$params['style'];
6337
+					$csstyle = '';
6338
+					$class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6339
+					if (is_array($params) && count($params) > 0) {
6340
+						if (array_key_exists('style', $params)) {
6341
+							$csstyle = $params['style'];
6342 6342
 						}
6343 6343
 					}
6344 6344
 
@@ -6360,35 +6360,35 @@  discard block
 block discarded – undo
6360 6360
 					if ($action == 'selectlines') { $colspan++; }
6361 6361
 
6362 6362
 					// Convert date into timestamp format (value in memory must be a timestamp)
6363
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6363
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
6364 6364
 					{
6365
-						$datenotinstring = $this->array_options['options_' . $key];
6366
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6365
+						$datenotinstring = $this->array_options['options_'.$key];
6366
+						if (!is_numeric($this->array_options['options_'.$key]))	// For backward compatibility
6367 6367
 						{
6368 6368
 							$datenotinstring = $this->db->jdate($datenotinstring);
6369 6369
 						}
6370
-						$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;
6370
+						$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;
6371 6371
 					}
6372 6372
 					// Convert float submited string into real php numeric (value in memory must be a php numeric)
6373
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6373
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
6374 6374
 					{
6375
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6375
+						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)) : $this->array_options['options_'.$key];
6376 6376
 					}
6377 6377
 
6378 6378
 					$labeltoshow = $langs->trans($label);
6379 6379
 
6380 6380
 					$out .= '<td class="titlefield';
6381
-					if (GETPOST('action','none') == 'create') $out.='create';
6382
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6381
+					if (GETPOST('action', 'none') == 'create') $out .= 'create';
6382
+					if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6383 6383
 					$out .= '">';
6384
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6384
+					if (!empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6385 6385
 					else $out .= $labeltoshow;
6386 6386
 					$out .= '</td>';
6387 6387
 
6388 6388
 					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6389
-					$out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6389
+					$out .= '<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
6390 6390
 
6391
-					switch($mode) {
6391
+					switch ($mode) {
6392 6392
 						case "view":
6393 6393
 							$out .= $extrafields->showOutputField($key, $value);
6394 6394
 							break;
@@ -6453,7 +6453,7 @@  discard block
 block discarded – undo
6453 6453
 		global $user;
6454 6454
 
6455 6455
 		$element = $this->element;
6456
-		if ($element == 'facturerec') $element='facture';
6456
+		if ($element == 'facturerec') $element = 'facture';
6457 6457
 
6458 6458
 		return $user->rights->{$element};
6459 6459
 	}
@@ -6470,15 +6470,15 @@  discard block
 block discarded – undo
6470 6470
 	 * @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)
6471 6471
 	 * @return bool						  True if success, False if error
6472 6472
 	 */
6473
-	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6473
+	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
6474 6474
 	{
6475 6475
 		foreach ($tables as $table)
6476 6476
 		{
6477 6477
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6478 6478
 
6479
-			if (! $db->query($sql))
6479
+			if (!$db->query($sql))
6480 6480
 			{
6481
-				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.
6481
+				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.
6482 6482
 				//$this->errors = $db->lasterror();
6483 6483
 				return false;
6484 6484
 			}
@@ -6511,7 +6511,7 @@  discard block
 block discarded – undo
6511 6511
 		else
6512 6512
 		{
6513 6513
 			// Get cost price for margin calculation
6514
-			if (! empty($fk_product))
6514
+			if (!empty($fk_product))
6515 6515
 			{
6516 6516
 				if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'costprice') {
6517 6517
 					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
@@ -6582,18 +6582,18 @@  discard block
 block discarded – undo
6582 6582
 	 *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6583 6583
 	 *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6584 6584
 	 */
6585
-	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)
6585
+	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)
6586 6586
 	{
6587 6587
         // phpcs:enable
6588
-		global $conf,$user,$langs;
6588
+		global $conf, $user, $langs;
6589 6589
 
6590
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6591
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6590
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6591
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6592 6592
 
6593
-		$sortfield='position_name';
6594
-		$sortorder='asc';
6593
+		$sortfield = 'position_name';
6594
+		$sortorder = 'asc';
6595 6595
 
6596
-		$dir = $sdir . '/';
6596
+		$dir = $sdir.'/';
6597 6597
 		$pdir = '/';
6598 6598
 		if ($modulepart == 'ticket')
6599 6599
 		{
@@ -6608,26 +6608,26 @@  discard block
 block discarded – undo
6608 6608
 
6609 6609
 		// For backward compatibility
6610 6610
 		if ($modulepart == 'product' && !empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
6611
-			$dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6612
-			$pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6611
+			$dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6612
+			$pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6613 6613
 		}
6614 6614
 
6615 6615
 		// Defined relative dir to DOL_DATA_ROOT
6616 6616
 		$relativedir = '';
6617 6617
 		if ($dir)
6618 6618
 		{
6619
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6620
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
6621
-			$relativedir = preg_replace('/[\\/]$/','',$relativedir);
6619
+			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
6620
+			$relativedir = preg_replace('/^[\\/]/', '', $relativedir);
6621
+			$relativedir = preg_replace('/[\\/]$/', '', $relativedir);
6622 6622
 		}
6623 6623
 
6624 6624
 		$dirthumb = $dir.'thumbs/';
6625 6625
 		$pdirthumb = $pdir.'thumbs/';
6626 6626
 
6627
-		$return ='<!-- Photo -->'."\n";
6628
-		$nbphoto=0;
6627
+		$return = '<!-- Photo -->'."\n";
6628
+		$nbphoto = 0;
6629 6629
 
6630
-		$filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6630
+		$filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
6631 6631
 
6632 6632
 		/* if (! empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6633 6633
           {
@@ -6641,12 +6641,12 @@  discard block
 block discarded – undo
6641 6641
 		{
6642 6642
 			if ($sortfield && $sortorder)
6643 6643
 			{
6644
-				$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6644
+				$filearray = dol_sort_array($filearray, $sortfield, $sortorder);
6645 6645
 			}
6646 6646
 
6647
-			foreach($filearray as $key => $val)
6647
+			foreach ($filearray as $key => $val)
6648 6648
 			{
6649
-				$photo='';
6649
+				$photo = '';
6650 6650
 				$file = $val['name'];
6651 6651
 
6652 6652
 				//if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
@@ -6661,36 +6661,36 @@  discard block
 block discarded – undo
6661 6661
 					if ($size == 1 || $size == 'small') {   // Format vignette
6662 6662
 
6663 6663
 						// Find name of thumb file
6664
-						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6665
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
6664
+						$photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
6665
+						if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
6666 6666
 
6667 6667
 						// Get filesize of original file
6668
-						$imgarray=dol_getImageSize($dir.$photo);
6668
+						$imgarray = dol_getImageSize($dir.$photo);
6669 6669
 
6670 6670
 						if ($nbbyrow > 0)
6671 6671
 						{
6672
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6672
+							if ($nbphoto == 1) $return .= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6673 6673
 
6674
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6675
-							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6674
+							if ($nbphoto % $nbbyrow == 1) $return .= '<tr align=center valign=middle border=1>';
6675
+							$return .= '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
6676 6676
 						}
6677 6677
 						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
6678 6678
 
6679
-						$return.= "\n";
6679
+						$return .= "\n";
6680 6680
 
6681
-						$relativefile=preg_replace('/^\//', '', $pdir.$photo);
6681
+						$relativefile = preg_replace('/^\//', '', $pdir.$photo);
6682 6682
 						if (empty($nolink))
6683 6683
 						{
6684
-							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6685
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6686
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6684
+							$urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6685
+							if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
6686
+							else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6687 6687
 						}
6688 6688
 
6689 6689
 						// Show image (width height=$maxHeight)
6690 6690
 						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6691
-						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6692
-						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6693
-						if ($notitle) $alt='';
6691
+						$alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
6692
+						$alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6693
+						if ($notitle) $alt = '';
6694 6694
 
6695 6695
 						if ($usesharelink)
6696 6696
 						{
@@ -6698,81 +6698,81 @@  discard block
 block discarded – undo
6698 6698
 							{
6699 6699
 								if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6700 6700
 								{
6701
-									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6702
-									$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
+									$return .= '<!-- Show original file (thumb not yet available with shared links) -->';
6702
+									$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 6703
 								}
6704 6704
 								else {
6705
-									$return.= '<!-- Show original file -->';
6706
-									$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
+									$return .= '<!-- Show original file -->';
6706
+									$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6707 6707
 								}
6708 6708
 							}
6709 6709
 							else
6710 6710
 							{
6711
-								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6712
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6711
+								$return .= '<!-- Show nophoto file (because file is not shared) -->';
6712
+								$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6713 6713
 							}
6714 6714
 						}
6715 6715
 						else
6716 6716
 						{
6717 6717
 							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6718 6718
 							{
6719
-								$return.= '<!-- Show thumb -->';
6720
-								$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
+								$return .= '<!-- Show thumb -->';
6720
+								$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).'">';
6721 6721
 							}
6722 6722
 							else {
6723
-								$return.= '<!-- Show original file -->';
6724
-								$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
+								$return .= '<!-- Show original file -->';
6724
+								$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).'">';
6725 6725
 							}
6726 6726
 						}
6727 6727
 
6728
-						if (empty($nolink)) $return.= '</a>';
6729
-						$return.="\n";
6728
+						if (empty($nolink)) $return .= '</a>';
6729
+						$return .= "\n";
6730 6730
 
6731
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6731
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6732 6732
 						if ($showaction)
6733 6733
 						{
6734
-							$return.= '<br>';
6734
+							$return .= '<br>';
6735 6735
 							// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6736 6736
 							if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6737 6737
 							{
6738
-								$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>';
6738
+								$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>';
6739 6739
 							}
6740 6740
 							// Special cas for product
6741 6741
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6742 6742
 							{
6743 6743
 								// Link to resize
6744
-								$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; ';
6744
+								$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; ';
6745 6745
 
6746 6746
 								// Link to delete
6747
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6748
-								$return.= img_delete().'</a>';
6747
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6748
+								$return .= img_delete().'</a>';
6749 6749
 							}
6750 6750
 						}
6751
-						$return.= "\n";
6751
+						$return .= "\n";
6752 6752
 
6753 6753
 						if ($nbbyrow > 0)
6754 6754
 						{
6755
-							$return.= '</td>';
6756
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6755
+							$return .= '</td>';
6756
+							if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
6757 6757
 						}
6758
-						else if ($nbbyrow < 0) $return.='</div>';
6758
+						else if ($nbbyrow < 0) $return .= '</div>';
6759 6759
 					}
6760 6760
 
6761 6761
 					if (empty($size)) {     // Format origine
6762
-						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6762
+						$return .= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6763 6763
 
6764
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6764
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6765 6765
 						if ($showaction)
6766 6766
 						{
6767 6767
 							// Special case for product
6768 6768
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6769 6769
 							{
6770 6770
 								// Link to resize
6771
-								$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; ';
6771
+								$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; ';
6772 6772
 
6773 6773
 								// Link to delete
6774
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6775
-								$return.= img_delete().'</a>';
6774
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6775
+								$return .= img_delete().'</a>';
6776 6776
 							}
6777 6777
 						}
6778 6778
 					}
@@ -6782,18 +6782,18 @@  discard block
 block discarded – undo
6782 6782
 				}
6783 6783
 			}
6784 6784
 
6785
-			if ($size==1 || $size=='small')
6785
+			if ($size == 1 || $size == 'small')
6786 6786
 			{
6787 6787
 				if ($nbbyrow > 0)
6788 6788
 				{
6789 6789
 					// Ferme tableau
6790 6790
 					while ($nbphoto % $nbbyrow)
6791 6791
 					{
6792
-						$return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6792
+						$return .= '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
6793 6793
 						$nbphoto++;
6794 6794
 					}
6795 6795
 
6796
-					if ($nbphoto) $return.= '</table>';
6796
+					if ($nbphoto) $return .= '</table>';
6797 6797
 				}
6798 6798
 			}
6799 6799
 		}
@@ -6812,9 +6812,9 @@  discard block
 block discarded – undo
6812 6812
 	 */
6813 6813
 	protected function isArray($info)
6814 6814
 	{
6815
-		if(is_array($info))
6815
+		if (is_array($info))
6816 6816
 		{
6817
-			if(isset($info['type']) && $info['type']=='array') return true;
6817
+			if (isset($info['type']) && $info['type'] == 'array') return true;
6818 6818
 			else return false;
6819 6819
 		}
6820 6820
 		else return false;
@@ -6828,9 +6828,9 @@  discard block
 block discarded – undo
6828 6828
 	 */
6829 6829
 	protected function isNull($info)
6830 6830
 	{
6831
-		if(is_array($info))
6831
+		if (is_array($info))
6832 6832
 		{
6833
-			if(isset($info['type']) && $info['type']=='null') return true;
6833
+			if (isset($info['type']) && $info['type'] == 'null') return true;
6834 6834
 			else return false;
6835 6835
 		}
6836 6836
 		else return false;
@@ -6844,7 +6844,7 @@  discard block
 block discarded – undo
6844 6844
 	 */
6845 6845
 	public function isDate($info)
6846 6846
 	{
6847
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6847
+		if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
6848 6848
 		else return false;
6849 6849
 	}
6850 6850
 
@@ -6856,9 +6856,9 @@  discard block
 block discarded – undo
6856 6856
 	 */
6857 6857
 	public function isInt($info)
6858 6858
 	{
6859
-		if(is_array($info))
6859
+		if (is_array($info))
6860 6860
 		{
6861
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6861
+			if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
6862 6862
 			else return false;
6863 6863
 		}
6864 6864
 		else return false;
@@ -6872,7 +6872,7 @@  discard block
 block discarded – undo
6872 6872
 	 */
6873 6873
 	public function isFloat($info)
6874 6874
 	{
6875
-		if(is_array($info))
6875
+		if (is_array($info))
6876 6876
 		{
6877 6877
 			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6878 6878
 			else return false;
@@ -6888,9 +6888,9 @@  discard block
 block discarded – undo
6888 6888
 	 */
6889 6889
 	public function isText($info)
6890 6890
 	{
6891
-		if(is_array($info))
6891
+		if (is_array($info))
6892 6892
 		{
6893
-			if(isset($info['type']) && $info['type']=='text') return true;
6893
+			if (isset($info['type']) && $info['type'] == 'text') return true;
6894 6894
 			else return false;
6895 6895
 		}
6896 6896
 		else return false;
@@ -6904,9 +6904,9 @@  discard block
 block discarded – undo
6904 6904
 	 */
6905 6905
 	protected function isIndex($info)
6906 6906
 	{
6907
-		if(is_array($info))
6907
+		if (is_array($info))
6908 6908
 		{
6909
-			if(isset($info['index']) && $info['index']==true) return true;
6909
+			if (isset($info['index']) && $info['index'] == true) return true;
6910 6910
 			else return false;
6911 6911
 		}
6912 6912
 		else return false;
@@ -6922,13 +6922,13 @@  discard block
 block discarded – undo
6922 6922
 	{
6923 6923
 		global $conf;
6924 6924
 
6925
-		$queryarray=array();
6925
+		$queryarray = array();
6926 6926
 		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6927 6927
 		{
6928 6928
 			// Depending on field type ('datetime', ...)
6929
-			if($this->isDate($info))
6929
+			if ($this->isDate($info))
6930 6930
 			{
6931
-				if(empty($this->{$field}))
6931
+				if (empty($this->{$field}))
6932 6932
 				{
6933 6933
 					$queryarray[$field] = null;
6934 6934
 				}
@@ -6937,10 +6937,10 @@  discard block
 block discarded – undo
6937 6937
 					$queryarray[$field] = $this->db->idate($this->{$field});
6938 6938
 				}
6939 6939
 			}
6940
-			else if($this->isArray($info))
6940
+			else if ($this->isArray($info))
6941 6941
 			{
6942
-				if(! empty($this->{$field})) {
6943
-					if(! is_array($this->{$field})) {
6942
+				if (!empty($this->{$field})) {
6943
+					if (!is_array($this->{$field})) {
6944 6944
 						$this->{$field} = array($this->{$field});
6945 6945
 					}
6946 6946
 					$queryarray[$field] = serialize($this->{$field});
@@ -6948,20 +6948,20 @@  discard block
 block discarded – undo
6948 6948
 					$queryarray[$field] = null;
6949 6949
 				}
6950 6950
 			}
6951
-			else if($this->isInt($info))
6951
+			else if ($this->isInt($info))
6952 6952
 			{
6953 6953
 				if ($field == 'entity' && is_null($this->{$field}))
6954 6954
                     $queryarray[$field] = Globals::$conf->entity;
6955 6955
                 else
6956 6956
 				{
6957 6957
 					$queryarray[$field] = (int) price2num($this->{$field});
6958
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6958
+					if (empty($queryarray[$field])) $queryarray[$field] = 0; // May be reset to null later if property 'notnull' is -1 for this field.
6959 6959
 				}
6960 6960
 			}
6961
-			else if($this->isFloat($info))
6961
+			else if ($this->isFloat($info))
6962 6962
 			{
6963 6963
 				$queryarray[$field] = (double) price2num($this->{$field});
6964
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6964
+				if (empty($queryarray[$field])) $queryarray[$field] = 0;
6965 6965
 			}
6966 6966
 			else
6967 6967
 			{
@@ -6969,7 +6969,7 @@  discard block
 block discarded – undo
6969 6969
 			}
6970 6970
 
6971 6971
 			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6972
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6972
+			if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6973 6973
 		}
6974 6974
 
6975 6975
 		return $queryarray;
@@ -6985,35 +6985,35 @@  discard block
 block discarded – undo
6985 6985
 	{
6986 6986
 		foreach ($this->fields as $field => $info)
6987 6987
 		{
6988
-			if($this->isDate($info))
6988
+			if ($this->isDate($info))
6989 6989
 			{
6990
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6990
+				if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6991 6991
 				else $this->{$field} = strtotime($obj->{$field});
6992 6992
 			}
6993
-			elseif($this->isArray($info))
6993
+			elseif ($this->isArray($info))
6994 6994
 			{
6995
-				if(! empty($obj->{$field})) {
6995
+				if (!empty($obj->{$field})) {
6996 6996
 					$this->{$field} = @unserialize($obj->{$field});
6997 6997
 					// Hack for data not in UTF8
6998
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6998
+					if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6999 6999
 				} else {
7000 7000
 					$this->{$field} = array();
7001 7001
 				}
7002 7002
 			}
7003
-			elseif($this->isInt($info))
7003
+			elseif ($this->isInt($info))
7004 7004
 			{
7005 7005
 				if ($field == 'rowid') $this->id = (int) $obj->{$field};
7006 7006
 				else $this->{$field} = (int) $obj->{$field};
7007 7007
 			}
7008
-			elseif($this->isFloat($info))
7008
+			elseif ($this->isFloat($info))
7009 7009
 			{
7010 7010
 				$this->{$field} = (double) $obj->{$field};
7011 7011
 			}
7012
-			elseif($this->isNull($info))
7012
+			elseif ($this->isNull($info))
7013 7013
 			{
7014 7014
 				$val = $obj->{$field};
7015 7015
 				// zero is not null
7016
-				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7016
+				$this->{$field} = (is_null($val) || (empty($val) && $val !== 0 && $val !== '0') ? null : $val);
7017 7017
 			}
7018 7018
 			else
7019 7019
 			{
@@ -7022,7 +7022,7 @@  discard block
 block discarded – undo
7022 7022
 		}
7023 7023
 
7024 7024
 		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7025
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7025
+		if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7026 7026
 	}
7027 7027
 
7028 7028
 	/**
@@ -7064,14 +7064,14 @@  discard block
 block discarded – undo
7064 7064
 
7065 7065
 		$error = 0;
7066 7066
 
7067
-		$now=dol_now();
7067
+		$now = dol_now();
7068 7068
 
7069 7069
 		$fieldvalues = $this->setSaveQuery();
7070
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7071
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7072
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7070
+		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
7071
+		if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
7072
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7073 7073
 
7074
-		$keys=array();
7074
+		$keys = array();
7075 7075
 		$values = array();
7076 7076
 		foreach ($fieldvalues as $k => $v) {
7077 7077
 			$keys[$k] = $k;
@@ -7080,58 +7080,58 @@  discard block
 block discarded – undo
7080 7080
 		}
7081 7081
 
7082 7082
 		// Clean and check mandatory
7083
-		foreach($keys as $key)
7083
+		foreach ($keys as $key)
7084 7084
 		{
7085 7085
 			// If field is an implicit foreign key field
7086
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7087
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7086
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
7087
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
7088 7088
 
7089 7089
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7090
-			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7090
+			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && !isset($values[$key]) && is_null($val['default']))
7091 7091
 			{
7092 7092
 				$error++;
7093
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7093
+				$this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7094 7094
 			}
7095 7095
 
7096 7096
 			// If field is an implicit foreign key field
7097
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7098
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7097
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key] = 'null';
7098
+			if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
7099 7099
 		}
7100 7100
 
7101 7101
 		if ($error) return -1;
7102 7102
 
7103 7103
 		$this->db->begin();
7104 7104
 
7105
-		if (! $error)
7105
+		if (!$error)
7106 7106
 		{
7107 7107
 			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7108
-			$sql.= ' ('.implode( ", ", $keys ).')';
7109
-			$sql.= ' VALUES ('.implode( ", ", $values ).')';
7108
+			$sql .= ' ('.implode(", ", $keys).')';
7109
+			$sql .= ' VALUES ('.implode(", ", $values).')';
7110 7110
 
7111 7111
 			$res = $this->db->query($sql);
7112
-			if ($res===false) {
7112
+			if ($res === false) {
7113 7113
 				$error++;
7114 7114
 				$this->errors[] = $this->db->lasterror();
7115 7115
 			}
7116 7116
 		}
7117 7117
 
7118
-		if (! $error)
7118
+		if (!$error)
7119 7119
 		{
7120
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7120
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
7121 7121
 		}
7122 7122
 
7123 7123
 		// Create extrafields
7124
-		if (! $error)
7124
+		if (!$error)
7125 7125
 		{
7126
-			$result=$this->insertExtraFields();
7126
+			$result = $this->insertExtraFields();
7127 7127
 			if ($result < 0) $error++;
7128 7128
 		}
7129 7129
 
7130 7130
 		// Triggers
7131
-		if (! $error && ! $notrigger)
7131
+		if (!$error && !$notrigger)
7132 7132
 		{
7133 7133
 			// Call triggers
7134
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7134
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
7135 7135
 			if ($result < 0) { $error++; }
7136 7136
 			// End call triggers
7137 7137
 		}
@@ -7160,13 +7160,13 @@  discard block
 block discarded – undo
7160 7160
 		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7161 7161
 
7162 7162
 		$sql = 'SELECT '.$this->getFieldList();
7163
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7163
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7164 7164
 
7165
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7166
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7167
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7168
-		if ($morewhere)   $sql.= $morewhere;
7169
-		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7165
+		if (!empty($id))  $sql .= ' WHERE rowid = '.$id;
7166
+		elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7167
+		else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
7168
+		if ($morewhere)   $sql .= $morewhere;
7169
+		$sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
7170 7170
 
7171 7171
 		$res = $this->db->query($sql);
7172 7172
 		if ($res)
@@ -7203,14 +7203,14 @@  discard block
 block discarded – undo
7203 7203
 
7204 7204
 		$error = 0;
7205 7205
 
7206
-		$now=dol_now();
7206
+		$now = dol_now();
7207 7207
 
7208 7208
 		$fieldvalues = $this->setSaveQuery();
7209
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7210
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7211
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7209
+		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
7210
+		if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
7211
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7212 7212
 
7213
-		$keys=array();
7213
+		$keys = array();
7214 7214
 		$values = array();
7215 7215
 		foreach ($fieldvalues as $k => $v) {
7216 7216
 			$keys[$k] = $k;
@@ -7220,10 +7220,10 @@  discard block
 block discarded – undo
7220 7220
 		}
7221 7221
 
7222 7222
 		// Clean and check mandatory
7223
-		foreach($keys as $key)
7223
+		foreach ($keys as $key)
7224 7224
 		{
7225
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7226
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7225
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
7226
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
7227 7227
 
7228 7228
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7229 7229
 			/*
@@ -7234,13 +7234,13 @@  discard block
 block discarded – undo
7234 7234
 			}*/
7235 7235
 		}
7236 7236
 
7237
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
7237
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(',', $tmp).' WHERE rowid='.$this->id;
7238 7238
 
7239 7239
 		$this->db->begin();
7240
-		if (! $error)
7240
+		if (!$error)
7241 7241
 		{
7242 7242
 			$res = $this->db->query($sql);
7243
-			if ($res===false)
7243
+			if ($res === false)
7244 7244
 			{
7245 7245
 				$error++;
7246 7246
 				$this->errors[] = $this->db->lasterror();
@@ -7249,7 +7249,7 @@  discard block
 block discarded – undo
7249 7249
 
7250 7250
 		// Update extrafield
7251 7251
 		if (!$error && empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0) {
7252
-			$result=$this->insertExtraFields();
7252
+			$result = $this->insertExtraFields();
7253 7253
 			if ($result < 0)
7254 7254
 			{
7255 7255
 				$error++;
@@ -7257,10 +7257,10 @@  discard block
 block discarded – undo
7257 7257
 		}
7258 7258
 
7259 7259
 		// Triggers
7260
-		if (! $error && ! $notrigger)
7260
+		if (!$error && !$notrigger)
7261 7261
 		{
7262 7262
 			// Call triggers
7263
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7263
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
7264 7264
 			if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7265 7265
 			// End call triggers
7266 7266
 		}
@@ -7283,68 +7283,68 @@  discard block
 block discarded – undo
7283 7283
 	 * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7284 7284
 	 * @return 	int             				<=0 if KO, >0 if OK
7285 7285
 	 */
7286
-	public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7286
+	public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
7287 7287
 	{
7288
-		$error=0;
7288
+		$error = 0;
7289 7289
 
7290 7290
 		$this->db->begin();
7291 7291
 
7292 7292
 		if ($forcechilddeletion)
7293 7293
 		{
7294
-			foreach($this->childtables as $table)
7294
+			foreach ($this->childtables as $table)
7295 7295
 			{
7296 7296
 				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7297 7297
 				$resql = $this->db->query($sql);
7298
-				if (! $resql)
7298
+				if (!$resql)
7299 7299
 				{
7300
-					$this->error=$this->db->lasterror();
7301
-					$this->errors[]=$this->error;
7300
+					$this->error = $this->db->lasterror();
7301
+					$this->errors[] = $this->error;
7302 7302
 					$this->db->rollback();
7303 7303
 					return -1;
7304 7304
 				}
7305 7305
 			}
7306 7306
 		}
7307
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7307
+		elseif (!empty($this->fk_element) && !empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7308 7308
 		{
7309 7309
 			$objectisused = $this->isObjectUsed($this->id);
7310
-			if (! empty($objectisused))
7310
+			if (!empty($objectisused))
7311 7311
 			{
7312 7312
 				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7313
-				$this->error='ErrorRecordHasChildren';
7314
-				$this->errors[]=$this->error;
7313
+				$this->error = 'ErrorRecordHasChildren';
7314
+				$this->errors[] = $this->error;
7315 7315
 				$this->db->rollback();
7316 7316
 				return 0;
7317 7317
 			}
7318 7318
 		}
7319 7319
 
7320
-		if (! $error) {
7321
-			if (! $notrigger) {
7320
+		if (!$error) {
7321
+			if (!$notrigger) {
7322 7322
 				// Call triggers
7323
-				$result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7323
+				$result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7324 7324
 				if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7325 7325
 				// End call triggers
7326 7326
 			}
7327 7327
 		}
7328 7328
 
7329
-		if (! $error && ! empty($this->isextrafieldmanaged))
7329
+		if (!$error && !empty($this->isextrafieldmanaged))
7330 7330
 		{
7331
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7332
-			$sql.= " WHERE fk_object=" . $this->id;
7331
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields";
7332
+			$sql .= " WHERE fk_object=".$this->id;
7333 7333
 
7334 7334
 			$resql = $this->db->query($sql);
7335
-			if (! $resql)
7335
+			if (!$resql)
7336 7336
 			{
7337 7337
 				$this->errors[] = $this->db->lasterror();
7338 7338
 				$error++;
7339 7339
 			}
7340 7340
 		}
7341 7341
 
7342
-		if (! $error)
7342
+		if (!$error)
7343 7343
 		{
7344 7344
 			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7345 7345
 
7346 7346
 			$res = $this->db->query($sql);
7347
-			if($res===false) {
7347
+			if ($res === false) {
7348 7348
 				$error++;
7349 7349
 				$this->errors[] = $this->db->lasterror();
7350 7350
 			}
@@ -7385,9 +7385,9 @@  discard block
 block discarded – undo
7385 7385
 		require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7386 7386
 
7387 7387
 		$comment = new Comment($this->db);
7388
-		$result=$comment->fetchAllFor($this->element, $this->id);
7389
-		if ($result<0) {
7390
-			$this->errors=array_merge($this->errors, $comment->errors);
7388
+		$result = $comment->fetchAllFor($this->element, $this->id);
7389
+		if ($result < 0) {
7390
+			$this->errors = array_merge($this->errors, $comment->errors);
7391 7391
 			return -1;
7392 7392
 		} else {
7393 7393
 			$this->comments = $comment->comments;
Please login to merge, or discard this patch.
Braces   +1373 added lines, -865 removed lines patch added patch discarded remove patch
@@ -401,24 +401,31 @@  discard block
 block discarded – undo
401 401
 		$sql.= " FROM ".MAIN_DB_PREFIX.$element;
402 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)."'";
407
-		else {
404
+		if ($id > 0) {
405
+		    $sql.= " AND rowid = ".$db->escape($id);
406
+		} else if ($ref) {
407
+		    $sql.= " AND ref = '".$db->escape($ref)."'";
408
+		} else if ($ref_ext) {
409
+		    $sql.= " AND ref_ext = '".$db->escape($ref_ext)."'";
410
+		} else {
408 411
 			$error='ErrorWrongParameters';
409 412
 			dol_print_error(get_class()."::isExistingObject ".$error, LOG_ERR);
410 413
 			return -1;
411 414
 		}
412
-		if ($ref || $ref_ext)
413
-            $sql .= " AND entity = " . Globals::$conf->entity;
415
+		if ($ref || $ref_ext) {
416
+		            $sql .= " AND entity = " . Globals::$conf->entity;
417
+		}
414 418
 
415 419
         dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
416 420
 		$resql = $db->query($sql);
417 421
 		if ($resql)
418 422
 		{
419 423
 			$num=$db->num_rows($resql);
420
-			if ($num > 0) return 1;
421
-			else return 0;
424
+			if ($num > 0) {
425
+			    return 1;
426
+			} else {
427
+			    return 0;
428
+			}
422 429
 		}
423 430
 		return -1;
424 431
 	}
@@ -447,13 +454,18 @@  discard block
 block discarded – undo
447 454
 		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
448 455
 		$lastname=$this->lastname;
449 456
 		$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:'')))));
457
+		if (empty($lastname)) {
458
+		    $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:'')))));
459
+		}
451 460
 
452 461
 		$ret='';
453 462
 		if ($option && $this->civility_id)
454 463
 		{
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.' ';
464
+			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) {
465
+			    $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
466
+			} else {
467
+			    $ret.=$this->civility_id.' ';
468
+			}
457 469
 		}
458 470
 
459 471
 		$ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
@@ -544,14 +556,15 @@  discard block
 block discarded – undo
544 556
             && empty(Globals::$conf->global->SOCIETE_DISABLE_STATE) && $this->state) {
545 557
             if (!empty(Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && Globals::$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
546 558
                 $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
547
-            }
548
-            else {
559
+            } else {
549 560
                 $out.=($outdone?' - ':'').$this->state;
550 561
             }
551 562
 			$outdone++;
552 563
 		}
553 564
 
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>':'');
565
+		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)) {
566
+		    $out.=($outdone?'<br>':'');
567
+		}
555 568
 		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
556 569
 			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
557 570
 		}
@@ -591,13 +604,21 @@  discard block
 block discarded – undo
591 604
 		}
592 605
 		$out.='<div style="clear: both;">';
593 606
 		if (!empty(Globals::$conf->socialnetworks->enabled)) {
594
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
607
+			if ($this->skype) {
608
+			    $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
609
+			}
595 610
 			$outdone++;
596
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
611
+			if ($this->jabberid) {
612
+			    $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
613
+			}
597 614
 			$outdone++;
598
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
615
+			if ($this->twitter) {
616
+			    $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
617
+			}
599 618
 			$outdone++;
600
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
619
+			if ($this->facebook) {
620
+			    $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
621
+			}
601 622
 			$outdone++;
602 623
 		}
603 624
 		$out.='</div>';
@@ -657,10 +678,10 @@  discard block
 block discarded – undo
657 678
 					$this->errors = $ecmfile->errors;
658 679
 				}
659 680
 				*/
660
-			}
661
-			else return '';
662
-		}
663
-		elseif (empty($ecmfile->share))
681
+			} else {
682
+			    return '';
683
+			}
684
+		} elseif (empty($ecmfile->share))
664 685
 		{
665 686
 			// Add entry into index
666 687
 			if ($initsharekey)
@@ -668,8 +689,9 @@  discard block
 block discarded – undo
668 689
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
669 690
 				$ecmfile->share = getRandomPassword(true);
670 691
 				$ecmfile->update($user);
671
-			}
672
-			else return '';
692
+			} else {
693
+			    return '';
694
+			}
673 695
 		}
674 696
 
675 697
 		// Define $urlwithroot
@@ -683,14 +705,18 @@  discard block
 block discarded – undo
683 705
 		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
684 706
 		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
685 707
 		//$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';
708
+		if (! empty($ecmfile->share)) {
709
+		    $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;
710
+		}
711
+		// Hash for public share
712
+		if ($forcedownload) {
713
+		    $paramlink.=($paramlink?'&':'').'attachment=1';
714
+		}
688 715
 
689 716
 		if ($relativelink)
690 717
 		{
691 718
 			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
692
-		}
693
-		else
719
+		} else
694 720
 		{
695 721
 			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
696 722
 		}
@@ -738,8 +764,7 @@  discard block
 block discarded – undo
738 764
 		if (is_numeric($type_contact))
739 765
 		{
740 766
 			$id_type_contact=$type_contact;
741
-		}
742
-		else
767
+		} else
743 768
 		{
744 769
 			// We look for id type_contact
745 770
 			$sql = "SELECT tc.rowid";
@@ -752,7 +777,9 @@  discard block
 block discarded – undo
752 777
 			if ($resql)
753 778
 			{
754 779
 				$obj = $this->db->fetch_object($resql);
755
-				if ($obj) $id_type_contact=$obj->rowid;
780
+				if ($obj) {
781
+				    $id_type_contact=$obj->rowid;
782
+				}
756 783
 			}
757 784
 		}
758 785
 
@@ -804,8 +831,7 @@  discard block
 block discarded – undo
804 831
 
805 832
 				$this->db->commit();
806 833
 				return 1;
807
-			}
808
-			else
834
+			} else
809 835
 			{
810 836
 				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
811 837
 				{
@@ -813,15 +839,16 @@  discard block
 block discarded – undo
813 839
 					$this->db->rollback();
814 840
 					echo 'err rollback';
815 841
 					return -2;
816
-				}
817
-				else
842
+				} else
818 843
 				{
819 844
 					$this->error=$this->db->error();
820 845
 					$this->db->rollback();
821 846
 					return -1;
822 847
 				}
823 848
 			}
824
-		} else return 0;
849
+		} else {
850
+		    return 0;
851
+		}
825 852
 	}
826 853
 
827 854
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -863,15 +890,18 @@  discard block
 block discarded – undo
863 890
 		// Insert into database
864 891
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
865 892
 		$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 ."'";
893
+		if ($type_contact_id) {
894
+		    $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
895
+		}
896
+		if ($fk_socpeople) {
897
+		    $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
898
+		}
868 899
 		$sql.= " where rowid = ".$rowid;
869 900
 		$resql=$this->db->query($sql);
870 901
 		if ($resql)
871 902
 		{
872 903
 			return 0;
873
-		}
874
-		else
904
+		} else
875 905
 		{
876 906
 			$this->error=$this->db->lasterror();
877 907
 			return -1;
@@ -908,8 +938,7 @@  discard block
 block discarded – undo
908 938
 
909 939
 			$this->db->commit();
910 940
 			return 1;
911
-		}
912
-		else
941
+		} else
913 942
 		{
914 943
 			$this->error=$this->db->lasterror();
915 944
 			$this->db->rollback();
@@ -939,15 +968,15 @@  discard block
 block discarded – undo
939 968
 
940 969
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
941 970
 		$sql.= " WHERE element_id = ".$this->id;
942
-		if ($listId)
943
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
971
+		if ($listId) {
972
+					$sql.= " AND fk_c_type_contact IN (".$listId.")";
973
+		}
944 974
 
945 975
 		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
946 976
 		if ($this->db->query($sql))
947 977
 		{
948 978
 			return 1;
949
-		}
950
-		else
979
+		} else
951 980
 		{
952 981
 			$this->error=$this->db->lasterror();
953 982
 			return -1;
@@ -972,22 +1001,38 @@  discard block
 block discarded – undo
972 1001
 		$tab=array();
973 1002
 
974 1003
 		$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";
1004
+		if ($source == 'internal') {
1005
+		    $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1006
+		}
1007
+		if ($source == 'external' || $source == 'thirdparty') {
1008
+		    $sql.=", t.fk_soc as socid, t.statut as statuscontact";
1009
+		}
977 1010
 		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
978 1011
 		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
979 1012
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
980 1013
 		$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";
1014
+		if ($source == 'internal') {
1015
+		    $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
1016
+		}
1017
+		if ($source == 'external'|| $source == 'thirdparty') {
1018
+		    $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
1019
+		}
983 1020
 		$sql.= " WHERE ec.element_id =".$this->id;
984 1021
 		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
985 1022
 		$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'";
1023
+		if ($code) {
1024
+		    $sql.= " AND tc.code = '".$this->db->escape($code)."'";
1025
+		}
1026
+		if ($source == 'internal') {
1027
+		    $sql.= " AND tc.source = 'internal'";
1028
+		}
1029
+		if ($source == 'external' || $source == 'thirdparty') {
1030
+		    $sql.= " AND tc.source = 'external'";
1031
+		}
989 1032
 		$sql.= " AND tc.active=1";
990
-		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
1033
+		if ($statut >= 0) {
1034
+		    $sql.= " AND ec.statut = '".$statut."'";
1035
+		}
991 1036
 		$sql.=" ORDER BY t.lastname ASC";
992 1037
 
993 1038
 		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
@@ -1008,8 +1053,7 @@  discard block
 block discarded – undo
1008 1053
 								   'nom'=>$obj->lastname,      // For backward compatibility
1009 1054
 								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1010 1055
 								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1011
-				}
1012
-				else
1056
+				} else
1013 1057
 				{
1014 1058
 					$tab[$i]=$obj->id;
1015 1059
 				}
@@ -1018,8 +1062,7 @@  discard block
 block discarded – undo
1018 1062
 			}
1019 1063
 
1020 1064
 			return $tab;
1021
-		}
1022
-		else
1065
+		} else
1023 1066
 		{
1024 1067
 			$this->error=$this->db->lasterror();
1025 1068
 			dol_print_error($this->db);
@@ -1054,8 +1097,7 @@  discard block
 block discarded – undo
1054 1097
 			$result = $this->update_contact($rowid, $newstatut);
1055 1098
 			$this->db->free($resql);
1056 1099
 			return $result;
1057
-		}
1058
-		else
1100
+		} else
1059 1101
 		{
1060 1102
 			$this->error=$this->db->error();
1061 1103
 			dol_print_error($this->db);
@@ -1079,16 +1121,27 @@  discard block
 block discarded – undo
1079 1121
         // phpcs:enable
1080 1122
 		global $langs;
1081 1123
 
1082
-		if (empty($order)) $order='position';
1083
-		if ($order == 'position') $order.=',code';
1124
+		if (empty($order)) {
1125
+		    $order='position';
1126
+		}
1127
+		if ($order == 'position') {
1128
+		    $order.=',code';
1129
+		}
1084 1130
 
1085 1131
 		$tab = array();
1086 1132
 		$sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1087 1133
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1088 1134
 		$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)."'";
1135
+		if ($activeonly == 1) {
1136
+		    $sql.= " AND tc.active=1";
1137
+		}
1138
+		// only the active types
1139
+		if (! empty($source) && $source != 'all') {
1140
+		    $sql.= " AND tc.source='".$this->db->escape($source)."'";
1141
+		}
1142
+		if (! empty($code)) {
1143
+		    $sql.= " AND tc.code='".$this->db->escape($code)."'";
1144
+		}
1092 1145
 		$sql.= $this->db->order($order,'ASC');
1093 1146
 
1094 1147
 		//print "sql=".$sql;
@@ -1103,13 +1156,15 @@  discard block
 block discarded – undo
1103 1156
 
1104 1157
 				$transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1105 1158
 				$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;
1159
+				if (empty($option)) {
1160
+				    $tab[$obj->rowid]=$libelle_type;
1161
+				} else {
1162
+				    $tab[$obj->code]=$libelle_type;
1163
+				}
1108 1164
 				$i++;
1109 1165
 			}
1110 1166
 			return $tab;
1111
-		}
1112
-		else
1167
+		} else
1113 1168
 		{
1114 1169
 			$this->error=$this->db->lasterror();
1115 1170
 			//dol_print_error($this->db);
@@ -1148,19 +1203,29 @@  discard block
 block discarded – undo
1148 1203
 
1149 1204
 		$sql = "SELECT ec.fk_socpeople";
1150 1205
 		$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,";
1206
+		if ($source == 'internal') {
1207
+		    $sql.= " ".MAIN_DB_PREFIX."user as c,";
1208
+		}
1209
+		if ($source == 'external') {
1210
+		    $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1211
+		}
1153 1212
 		$sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1154 1213
 		$sql.= " WHERE ec.element_id = ".$id;
1155 1214
 		$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').")";
1215
+		if ($source == 'internal') {
1216
+		    $sql.= " AND c.entity IN (".getEntity('user').")";
1217
+		}
1218
+		if ($source == 'external') {
1219
+		    $sql.= " AND c.entity IN (".getEntity('societe').")";
1220
+		}
1158 1221
 		$sql.= " AND ec.fk_c_type_contact = tc.rowid";
1159 1222
 		$sql.= " AND tc.element = '".$element."'";
1160 1223
 		$sql.= " AND tc.source = '".$source."'";
1161 1224
 		$sql.= " AND tc.code = '".$code."'";
1162 1225
 		$sql.= " AND tc.active = 1";
1163
-		if ($status) $sql.= " AND ec.statut = ".$status;
1226
+		if ($status) {
1227
+		    $sql.= " AND ec.statut = ".$status;
1228
+		}
1164 1229
 
1165 1230
 		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1166 1231
 		$resql=$this->db->query($sql);
@@ -1171,8 +1236,7 @@  discard block
 block discarded – undo
1171 1236
 				$result[$i]=$obj->fk_socpeople;
1172 1237
 				$i++;
1173 1238
 			}
1174
-		}
1175
-		else
1239
+		} else
1176 1240
 		{
1177 1241
 			$this->error=$this->db->error();
1178 1242
 			return null;
@@ -1191,9 +1255,13 @@  discard block
 block discarded – undo
1191 1255
 	function fetch_contact($contactid=null)
1192 1256
 	{
1193 1257
         // phpcs:enable
1194
-		if (empty($contactid)) $contactid=$this->contactid;
1258
+		if (empty($contactid)) {
1259
+		    $contactid=$this->contactid;
1260
+		}
1195 1261
 
1196
-		if (empty($contactid)) return 0;
1262
+		if (empty($contactid)) {
1263
+		    return 0;
1264
+		}
1197 1265
 
1198 1266
 		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1199 1267
 		$contact = new Contact($this->db);
@@ -1214,14 +1282,16 @@  discard block
 block discarded – undo
1214 1282
         // phpcs:enable
1215 1283
 		global $conf;
1216 1284
 
1217
-		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1218
-			return 0;
1285
+		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
1286
+					return 0;
1287
+		}
1219 1288
 
1220 1289
 		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1221 1290
 
1222 1291
 		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1223
-		if ($force_thirdparty_id)
1224
-			$idtofetch = $force_thirdparty_id;
1292
+		if ($force_thirdparty_id) {
1293
+					$idtofetch = $force_thirdparty_id;
1294
+		}
1225 1295
 
1226 1296
 		if ($idtofetch) {
1227 1297
 			$thirdparty = new Societe($this->db);
@@ -1234,8 +1304,9 @@  discard block
 block discarded – undo
1234 1304
 			}
1235 1305
 
1236 1306
 			return $result;
1237
-		} else
1238
-			return -1;
1307
+		} else {
1308
+					return -1;
1309
+		}
1239 1310
 	}
1240 1311
 
1241 1312
 
@@ -1281,20 +1352,25 @@  discard block
 block discarded – undo
1281 1352
 		dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1282 1353
 
1283 1354
 		$idtype=$this->barcode_type;
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
1355
+		if (empty($idtype) && $idtype != '0') {
1356
+		    // 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 1357
 		{
1286 1358
 			if ($this->element == 'product')
1287
-                $idtype = Globals::$conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1288
-            else if ($this->element == 'societe')
1289
-                $idtype = Globals::$conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1290
-            else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1359
+                $idtype = Globals::$conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1360
+		} else if ($this->element == 'societe') {
1361
+                            $idtype = Globals::$conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1362
+            } else {
1363
+                dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1364
+            }
1291 1365
 		}
1292 1366
 
1293 1367
 		if ($idtype > 0)
1294 1368
 		{
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
1369
+			if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1370
+			    // If data not already loaded
1296 1371
 			{
1297
-				$sql = "SELECT rowid, code, libelle as label, coder";
1372
+				$sql = "SELECT rowid, code, libelle as label, coder";
1373
+			}
1298 1374
 				$sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299 1375
 				$sql.= " WHERE rowid = ".$idtype;
1300 1376
 				dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
@@ -1307,8 +1383,7 @@  discard block
 block discarded – undo
1307 1383
 					$this->barcode_type_label = $obj->label;
1308 1384
 					$this->barcode_type_coder = $obj->coder;
1309 1385
 					return 1;
1310
-				}
1311
-				else
1386
+				} else
1312 1387
 				{
1313 1388
 					dol_print_error($this->db);
1314 1389
 					return -1;
@@ -1329,8 +1404,13 @@  discard block
 block discarded – undo
1329 1404
         // phpcs:enable
1330 1405
 		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1331 1406
 
1332
-		if (empty($this->fk_project) && ! empty($this->fk_projet)) $this->fk_project = $this->fk_projet;	// For backward compatibility
1333
-		if (empty($this->fk_project)) return 0;
1407
+		if (empty($this->fk_project) && ! empty($this->fk_projet)) {
1408
+		    $this->fk_project = $this->fk_projet;
1409
+		}
1410
+		// For backward compatibility
1411
+		if (empty($this->fk_project)) {
1412
+		    return 0;
1413
+		}
1334 1414
 
1335 1415
 		$project = new Project($this->db);
1336 1416
 		$result = $project->fetch($this->fk_project);
@@ -1351,7 +1431,9 @@  discard block
 block discarded – undo
1351 1431
         // phpcs:enable
1352 1432
 		include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1353 1433
 
1354
-		if (empty($this->fk_product)) return 0;
1434
+		if (empty($this->fk_product)) {
1435
+		    return 0;
1436
+		}
1355 1437
 
1356 1438
 		$product = new Product($this->db);
1357 1439
 		$result = $product->fetch($this->fk_product);
@@ -1385,9 +1467,15 @@  discard block
 block discarded – undo
1385 1467
 	function fetch_origin()
1386 1468
 	{
1387 1469
         // phpcs:enable
1388
-		if ($this->origin == 'shipping') $this->origin = 'expedition';
1389
-		if ($this->origin == 'delivery') $this->origin = 'livraison';
1390
-        if ($this->origin == 'order_supplier') $this->origin = 'commandeFournisseur';
1470
+		if ($this->origin == 'shipping') {
1471
+		    $this->origin = 'expedition';
1472
+		}
1473
+		if ($this->origin == 'delivery') {
1474
+		    $this->origin = 'livraison';
1475
+		}
1476
+        if ($this->origin == 'order_supplier') {
1477
+            $this->origin = 'commandeFournisseur';
1478
+        }
1391 1479
 
1392 1480
 		$origin = $this->origin;
1393 1481
 
@@ -1479,29 +1567,48 @@  discard block
 block discarded – undo
1479 1567
 	{
1480 1568
 		global $user,$langs,$conf;
1481 1569
 
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';
1570
+		if (empty($table)) {
1571
+		    $table=$this->table_element;
1572
+		}
1573
+		if (empty($id)) {
1574
+		    $id=$this->id;
1575
+		}
1576
+		if (empty($format)) {
1577
+		    $format='text';
1578
+		}
1579
+		if (empty($id_field)) {
1580
+		    $id_field='rowid';
1581
+		}
1486 1582
 
1487 1583
 		$error=0;
1488 1584
 
1489 1585
 		$this->db->begin();
1490 1586
 
1491 1587
 		// Special case
1492
-		if ($table == 'product' && $field == 'note_private') $field='note';
1493
-		if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) $fk_user_field = 'fk_user_mod';
1588
+		if ($table == 'product' && $field == 'note_private') {
1589
+		    $field='note';
1590
+		}
1591
+		if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
1592
+		    $fk_user_field = 'fk_user_mod';
1593
+		}
1494 1594
 
1495 1595
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
1496 1596
 
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");
1597
+		if ($format == 'text') {
1598
+		    $sql.= $field." = '".$this->db->escape($value)."'";
1599
+		} else if ($format == 'int') {
1600
+		    $sql.= $field." = ".$this->db->escape($value);
1601
+		} else if ($format == 'date') {
1602
+		    $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
1603
+		}
1500 1604
 
1501 1605
 		if ($fk_user_field)
1502 1606
 		{
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;
1607
+			if (! empty($fuser) && is_object($fuser)) {
1608
+			    $sql.=", ".$fk_user_field." = ".$fuser->id;
1609
+			} elseif (empty($fuser) || $fuser != 'none') {
1610
+			    $sql.=", ".$fk_user_field." = ".$user->id;
1611
+			}
1505 1612
 		}
1506 1613
 
1507 1614
 		$sql.= " WHERE ".$id_field." = ".$id;
@@ -1516,28 +1623,32 @@  discard block
 block discarded – undo
1516 1623
 				if (empty($this->fields) && method_exists($this, 'fetch'))
1517 1624
 				{
1518 1625
 					$result = $this->fetch($id);
1519
-				}
1520
-				else
1626
+				} else
1521 1627
 				{
1522 1628
 					$result = $this->fetchCommon($id);
1523 1629
 				}
1524
-				if ($result >= 0) $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);   // This may set this->errors
1525
-				if ($result < 0) $error++;
1630
+				if ($result >= 0) {
1631
+				    $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);
1632
+				}
1633
+				// This may set this->errors
1634
+				if ($result < 0) {
1635
+				    $error++;
1636
+				}
1526 1637
 			}
1527 1638
 
1528 1639
 			if (! $error)
1529 1640
 			{
1530
-				if (property_exists($this, $field)) $this->$field = $value;
1641
+				if (property_exists($this, $field)) {
1642
+				    $this->$field = $value;
1643
+				}
1531 1644
 				$this->db->commit();
1532 1645
 				return 1;
1533
-			}
1534
-			else
1646
+			} else
1535 1647
 			{
1536 1648
 				$this->db->rollback();
1537 1649
 				return -2;
1538 1650
 			}
1539
-		}
1540
-		else
1651
+		} else
1541 1652
 		{
1542 1653
 			$this->error=$this->db->lasterror();
1543 1654
 			$this->db->rollback();
@@ -1564,36 +1675,66 @@  discard block
 block discarded – undo
1564 1675
 			dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1565 1676
 			return -1;
1566 1677
 		}
1567
-		if ($fieldid == 'none') return 1;
1678
+		if ($fieldid == 'none') {
1679
+		    return 1;
1680
+		}
1568 1681
 
1569 1682
 		// Security on socid
1570 1683
 		$socid = 0;
1571
-		if ($user->societe_id > 0) $socid = $user->societe_id;
1684
+		if ($user->societe_id > 0) {
1685
+		    $socid = $user->societe_id;
1686
+		}
1572 1687
 
1573 1688
 		// this->ismultientitymanaged contains
1574 1689
 		// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
1575 1690
 		$alias = 's';
1576
-		if ($this->element == 'societe') $alias = 'te';
1691
+		if ($this->element == 'societe') {
1692
+		    $alias = 'te';
1693
+		}
1577 1694
 
1578 1695
 		$sql = "SELECT MAX(te.".$fieldid.")";
1579 1696
 		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
1580 1697
 		if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1581 1698
             $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1582 1699
 		}
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";
1700
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1701
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1702
+		}
1703
+		// If we need to link to societe to limit select to entity
1704
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1705
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1706
+		}
1707
+		// If we need to link to societe to limit select to socid
1708
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1709
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";
1710
+		}
1711
+		// If we need to link to societe to limit select to socid
1712
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
1713
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1714
+		}
1587 1715
 		$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)';
1716
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
1717
+		    $sql.= " AND sc.fk_user = " .$user->id;
1718
+		}
1719
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
1720
+		    $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1721
+		}
1590 1722
 		if (! empty($filter))
1591 1723
 		{
1592
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1724
+			if (! preg_match('/^\s*AND/i', $filter)) {
1725
+			    $sql.=" AND ";
1726
+			}
1727
+			// For backward compatibility
1593 1728
 			$sql.=$filter;
1594 1729
 		}
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
1730
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1731
+		    $sql.= ' AND te.fk_soc = s.rowid';
1732
+		}
1733
+		// If we need to link to societe to limit select to entity
1734
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1735
+		    $sql.= ' AND te.fk_soc = s.rowid';
1736
+		}
1737
+		// If we need to link to societe to limit select to socid
1597 1738
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598 1739
 			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599 1740
                 if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
@@ -1606,9 +1747,15 @@  discard block
 block discarded – undo
1606 1747
 				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1607 1748
 			}
1608 1749
 		}
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;
1750
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
1751
+		    $sql.= ' AND te.fk_soc = ' . $socid;
1752
+		}
1753
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
1754
+		    $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1755
+		}
1756
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') {
1757
+		    $sql.= ' AND te.rowid = ' . $socid;
1758
+		}
1612 1759
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1613 1760
 
1614 1761
 		$result = $this->db->query($sql);
@@ -1626,20 +1773,44 @@  discard block
 block discarded – undo
1626 1773
 		if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1627 1774
             $sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1628 1775
 		}
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";
1776
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1777
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1778
+		}
1779
+		// If we need to link to societe to limit select to entity
1780
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1781
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1782
+		}
1783
+		// If we need to link to societe to limit select to socid
1784
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1785
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";
1786
+		}
1787
+		// If we need to link to societe to limit select to socid
1788
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
1789
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1790
+		}
1633 1791
 		$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)';
1792
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
1793
+		    $sql.= " AND sc.fk_user = " .$user->id;
1794
+		}
1795
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
1796
+		    $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1797
+		}
1636 1798
 		if (! empty($filter))
1637 1799
 		{
1638
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1800
+			if (! preg_match('/^\s*AND/i', $filter)) {
1801
+			    $sql.=" AND ";
1802
+			}
1803
+			// For backward compatibility
1639 1804
 			$sql.=$filter;
1640 1805
 		}
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
1806
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1807
+		    $sql.= ' AND te.fk_soc = s.rowid';
1808
+		}
1809
+		// If we need to link to societe to limit select to entity
1810
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1811
+		    $sql.= ' AND te.fk_soc = s.rowid';
1812
+		}
1813
+		// If we need to link to societe to limit select to socid
1643 1814
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644 1815
 			if ($this->element == 'user' && !empty(Globals::$conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645 1816
                 if (!empty($user->admin) && empty($user->entity) && Globals::$conf->entity == 1) {
@@ -1652,9 +1823,15 @@  discard block
 block discarded – undo
1652 1823
 				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1653 1824
 			}
1654 1825
 		}
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;
1826
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
1827
+		    $sql.= ' AND te.fk_soc = ' . $socid;
1828
+		}
1829
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
1830
+		    $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1831
+		}
1832
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') {
1833
+		    $sql.= ' AND te.rowid = ' . $socid;
1834
+		}
1658 1835
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1659 1836
 		// 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 1837
 
@@ -1686,8 +1863,11 @@  discard block
 block discarded – undo
1686 1863
 		$i = 0;
1687 1864
 		while ($i < $num)
1688 1865
 		{
1689
-			if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
1690
-			else  $contactAlreadySelected[$i] = $tab[$i]['id'];
1866
+			if ($source == 'thirdparty') {
1867
+			    $contactAlreadySelected[$i] = $tab[$i]['socid'];
1868
+			} else {
1869
+			    $contactAlreadySelected[$i] = $tab[$i]['id'];
1870
+			}
1691 1871
 			$i++;
1692 1872
 		}
1693 1873
 		return $contactAlreadySelected;
@@ -1711,14 +1891,19 @@  discard block
 block discarded – undo
1711 1891
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1712 1892
 		if ($this->table_element == 'actioncomm')
1713 1893
 		{
1714
-			if ($projectid) $sql.= ' SET fk_project = '.$projectid;
1715
-			else $sql.= ' SET fk_project = NULL';
1894
+			if ($projectid) {
1895
+			    $sql.= ' SET fk_project = '.$projectid;
1896
+			} else {
1897
+			    $sql.= ' SET fk_project = NULL';
1898
+			}
1716 1899
 			$sql.= ' WHERE id = '.$this->id;
1717
-		}
1718
-		else
1900
+		} else
1719 1901
 		{
1720
-			if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
1721
-			else $sql.= ' SET fk_projet = NULL';
1902
+			if ($projectid) {
1903
+			    $sql.= ' SET fk_projet = '.$projectid;
1904
+			} else {
1905
+			    $sql.= ' SET fk_projet = NULL';
1906
+			}
1722 1907
 			$sql.= ' WHERE rowid = '.$this->id;
1723 1908
 		}
1724 1909
 
@@ -1727,8 +1912,7 @@  discard block
 block discarded – undo
1727 1912
 		{
1728 1913
 			$this->fk_project = $projectid;
1729 1914
 			return 1;
1730
-		}
1731
-		else
1915
+		} else
1732 1916
 		{
1733 1917
 			dol_print_error($this->db);
1734 1918
 			return -1;
@@ -1748,8 +1932,12 @@  discard block
 block discarded – undo
1748 1932
 		{
1749 1933
 			// TODO uniformize field name
1750 1934
 			$fieldname = 'fk_mode_reglement';
1751
-			if ($this->element == 'societe') $fieldname = 'mode_reglement';
1752
-			if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
1935
+			if ($this->element == 'societe') {
1936
+			    $fieldname = 'mode_reglement';
1937
+			}
1938
+			if (get_class($this) == 'Fournisseur') {
1939
+			    $fieldname = 'mode_reglement_supplier';
1940
+			}
1753 1941
 
1754 1942
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1755 1943
 			$sql .= ' SET '.$fieldname.' = '.$id;
@@ -1759,17 +1947,17 @@  discard block
 block discarded – undo
1759 1947
 			{
1760 1948
 				$this->mode_reglement_id = $id;
1761 1949
 				// for supplier
1762
-				if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
1950
+				if (get_class($this) == 'Fournisseur') {
1951
+				    $this->mode_reglement_supplier_id = $id;
1952
+				}
1763 1953
 				return 1;
1764
-			}
1765
-			else
1954
+			} else
1766 1955
 			{
1767 1956
 				dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
1768 1957
 				$this->error=$this->db->error();
1769 1958
 				return -1;
1770 1959
 			}
1771
-		}
1772
-		else
1960
+		} else
1773 1961
 		{
1774 1962
 			dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
1775 1963
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1799,18 +1987,18 @@  discard block
 block discarded – undo
1799 1987
 				$this->multicurrency_code = $code;
1800 1988
 
1801 1989
 				list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
-				if ($rate) $this->setMulticurrencyRate($rate,2);
1990
+				if ($rate) {
1991
+				    $this->setMulticurrencyRate($rate,2);
1992
+				}
1803 1993
 
1804 1994
 				return 1;
1805
-			}
1806
-			else
1995
+			} else
1807 1996
 			{
1808 1997
 				dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
1809 1998
 				$this->error=$this->db->error();
1810 1999
 				return -1;
1811 2000
 			}
1812
-		}
1813
-		else
2001
+		} else
1814 2002
 		{
1815 2003
 			dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
1816 2004
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1904,15 +2092,13 @@  discard block
 block discarded – undo
1904 2092
 				}
1905 2093
 
1906 2094
 				return 1;
1907
-			}
1908
-			else
2095
+			} else
1909 2096
 			{
1910 2097
 				dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
1911 2098
 				$this->error=$this->db->error();
1912 2099
 				return -1;
1913 2100
 			}
1914
-		}
1915
-		else
2101
+		} else
1916 2102
 		{
1917 2103
 			dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
1918 2104
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1933,8 +2119,12 @@  discard block
 block discarded – undo
1933 2119
 		{
1934 2120
 			// TODO uniformize field name
1935 2121
 			$fieldname = 'fk_cond_reglement';
1936
-			if ($this->element == 'societe') $fieldname = 'cond_reglement';
1937
-			if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
2122
+			if ($this->element == 'societe') {
2123
+			    $fieldname = 'cond_reglement';
2124
+			}
2125
+			if (get_class($this) == 'Fournisseur') {
2126
+			    $fieldname = 'cond_reglement_supplier';
2127
+			}
1938 2128
 
1939 2129
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1940 2130
 			$sql .= ' SET '.$fieldname.' = '.$id;
@@ -1944,18 +2134,18 @@  discard block
 block discarded – undo
1944 2134
 			{
1945 2135
 				$this->cond_reglement_id = $id;
1946 2136
 				// for supplier
1947
-				if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
2137
+				if (get_class($this) == 'Fournisseur') {
2138
+				    $this->cond_reglement_supplier_id = $id;
2139
+				}
1948 2140
 				$this->cond_reglement = $id;	// for compatibility
1949 2141
 				return 1;
1950
-			}
1951
-			else
2142
+			} else
1952 2143
 			{
1953 2144
 				dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
1954 2145
 				$this->error=$this->db->error();
1955 2146
 				return -1;
1956 2147
 			}
1957
-		}
1958
-		else
2148
+		} else
1959 2149
 		{
1960 2150
 			dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
1961 2151
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1973,7 +2163,9 @@  discard block
 block discarded – undo
1973 2163
 	function setDeliveryAddress($id)
1974 2164
 	{
1975 2165
 		$fieldname = 'fk_delivery_address';
1976
-		if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
2166
+		if ($this->element == 'delivery' || $this->element == 'shipping') {
2167
+		    $fieldname = 'fk_address';
2168
+		}
1977 2169
 
1978 2170
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
1979 2171
 		$sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
@@ -1982,8 +2174,7 @@  discard block
 block discarded – undo
1982 2174
 		{
1983 2175
 			$this->fk_delivery_address = $id;
1984 2176
 			return 1;
1985
-		}
1986
-		else
2177
+		} else
1987 2178
 		{
1988 2179
 			$this->error=$this->db->error();
1989 2180
 			dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
@@ -2005,7 +2196,9 @@  discard block
 block discarded – undo
2005 2196
 	{
2006 2197
         global $user;
2007 2198
 
2008
-        if (empty($userused)) $userused=$user;
2199
+        if (empty($userused)) {
2200
+            $userused=$user;
2201
+        }
2009 2202
 
2010 2203
         $error = 0;
2011 2204
 
@@ -2016,7 +2209,9 @@  discard block
 block discarded – undo
2016 2209
 
2017 2210
         $this->db->begin();
2018 2211
 
2019
-		if ($shipping_method_id<0) $shipping_method_id='NULL';
2212
+		if ($shipping_method_id<0) {
2213
+		    $shipping_method_id='NULL';
2214
+		}
2020 2215
 		dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2021 2216
 
2022 2217
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2033,7 +2228,9 @@  discard block
 block discarded – undo
2033 2228
                 // Call trigger
2034 2229
                 $this->context=array('shippingmethodupdate'=>1);
2035 2230
                 $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2036
-                if ($result < 0) $error++;
2231
+                if ($result < 0) {
2232
+                    $error++;
2233
+                }
2037 2234
                 // End call trigger
2038 2235
             }
2039 2236
         }
@@ -2061,7 +2258,9 @@  discard block
 block discarded – undo
2061 2258
 			dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
2062 2259
 			return -1;
2063 2260
 		}
2064
-		if ($warehouse_id<0) $warehouse_id='NULL';
2261
+		if ($warehouse_id<0) {
2262
+		    $warehouse_id='NULL';
2263
+		}
2065 2264
 		dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2066 2265
 
2067 2266
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2108,8 +2307,7 @@  discard block
 block discarded – undo
2108 2307
 		{
2109 2308
 			$this->modelpdf=$modelpdf;
2110 2309
 			return 1;
2111
-		}
2112
-		else
2310
+		} else
2113 2311
 		{
2114 2312
 			dol_print_error($this->db);
2115 2313
 			return 0;
@@ -2129,7 +2327,9 @@  discard block
 block discarded – undo
2129 2327
 	{
2130 2328
         global $user;
2131 2329
 
2132
-        if (empty($userused)) $userused=$user;
2330
+        if (empty($userused)) {
2331
+            $userused=$user;
2332
+        }
2133 2333
 
2134 2334
         $error = 0;
2135 2335
 
@@ -2139,7 +2339,9 @@  discard block
 block discarded – undo
2139 2339
 		}
2140 2340
         $this->db->begin();
2141 2341
 
2142
-		if ($fk_account<0) $fk_account='NULL';
2342
+		if ($fk_account<0) {
2343
+		    $fk_account='NULL';
2344
+		}
2143 2345
 		dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2144 2346
 
2145 2347
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2152,15 +2354,16 @@  discard block
 block discarded – undo
2152 2354
             dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153 2355
             $this->error = $this->db->lasterror();
2154 2356
             $error++;
2155
-        }
2156
-        else
2357
+        } else
2157 2358
         {
2158 2359
             if (!$notrigger)
2159 2360
             {
2160 2361
                 // Call trigger
2161 2362
                 $this->context=array('bankaccountupdate'=>1);
2162 2363
                 $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2163
-                if ($result < 0) $error++;
2364
+                if ($result < 0) {
2365
+                    $error++;
2366
+                }
2164 2367
                 // End call trigger
2165 2368
             }
2166 2369
         }
@@ -2168,8 +2371,7 @@  discard block
 block discarded – undo
2168 2371
         {
2169 2372
             $this->db->rollback();
2170 2373
             return -1;
2171
-        }
2172
-        else
2374
+        } else
2173 2375
         {
2174 2376
             $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2175 2377
             $this->db->commit();
@@ -2208,8 +2410,12 @@  discard block
 block discarded – undo
2208 2410
 		$nl=0;
2209 2411
 		$sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2210 2412
 		$sql.= ' WHERE '.$this->fk_element.'='.$this->id;
2211
-		if (! $renum) $sql.= ' AND rang = 0';
2212
-		if ($renum) $sql.= ' AND rang <> 0';
2413
+		if (! $renum) {
2414
+		    $sql.= ' AND rang = 0';
2415
+		}
2416
+		if ($renum) {
2417
+		    $sql.= ' AND rang <> 0';
2418
+		}
2213 2419
 
2214 2420
 		dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
2215 2421
 		$resql = $this->db->query($sql);
@@ -2217,8 +2423,9 @@  discard block
 block discarded – undo
2217 2423
 		{
2218 2424
 			$row = $this->db->fetch_row($resql);
2219 2425
 			$nl = $row[0];
2220
-		}
2221
-		else dol_print_error($this->db);
2426
+		} else {
2427
+		    dol_print_error($this->db);
2428
+		}
2222 2429
 		if ($nl > 0)
2223 2430
 		{
2224 2431
 			// The goal of this part is to reorder all lines, with all children lines sharing the same
@@ -2228,7 +2435,9 @@  discard block
 block discarded – undo
2228 2435
 			// We first search all lines that are parent lines (for multilevel details lines)
2229 2436
 			$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2230 2437
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2231
-			if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
2438
+			if ($fk_parent_line) {
2439
+			    $sql.= ' AND fk_parent_line IS NULL';
2440
+			}
2232 2441
 			$sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
2233 2442
 
2234 2443
 			dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
@@ -2260,8 +2469,7 @@  discard block
 block discarded – undo
2260 2469
 						$this->updateRangOfLine($row, ($key+1));
2261 2470
 					}
2262 2471
 				}
2263
-			}
2264
-			else
2472
+			} else
2265 2473
 			{
2266 2474
 				dol_print_error($this->db);
2267 2475
 			}
@@ -2354,7 +2562,9 @@  discard block
 block discarded – undo
2354 2562
 	function updateRangOfLine($rowid,$rang)
2355 2563
 	{
2356 2564
 		$fieldposition = 'rang';
2357
-		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2565
+		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2566
+		    $fieldposition = 'position';
2567
+		}
2358 2568
 
2359 2569
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2360 2570
 		$sql.= ' WHERE rowid = '.$rowid;
@@ -2395,7 +2605,9 @@  discard block
 block discarded – undo
2395 2605
 		if ($rang > 1)
2396 2606
 		{
2397 2607
 			$fieldposition = 'rang';
2398
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2608
+			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2609
+			    $fieldposition = 'position';
2610
+			}
2399 2611
 
2400 2612
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang ;
2401 2613
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
@@ -2408,8 +2620,7 @@  discard block
 block discarded – undo
2408 2620
 				{
2409 2621
 					dol_print_error($this->db);
2410 2622
 				}
2411
-			}
2412
-			else
2623
+			} else
2413 2624
 			{
2414 2625
 				dol_print_error($this->db);
2415 2626
 			}
@@ -2429,7 +2640,9 @@  discard block
 block discarded – undo
2429 2640
 		if ($rang < $max)
2430 2641
 		{
2431 2642
 			$fieldposition = 'rang';
2432
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2643
+			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2644
+			    $fieldposition = 'position';
2645
+			}
2433 2646
 
2434 2647
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2435 2648
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
@@ -2442,8 +2655,7 @@  discard block
 block discarded – undo
2442 2655
 				{
2443 2656
 					dol_print_error($this->db);
2444 2657
 				}
2445
-			}
2446
-			else
2658
+			} else
2447 2659
 			{
2448 2660
 				dol_print_error($this->db);
2449 2661
 			}
@@ -2514,8 +2726,7 @@  discard block
 block discarded – undo
2514 2726
 				if (! empty($row[0]))
2515 2727
 				{
2516 2728
 					return $row[0];
2517
-				}
2518
-				else
2729
+				} else
2519 2730
 				{
2520 2731
 					return $this->getRangOfLine($fk_parent_line);
2521 2732
 				}
@@ -2562,8 +2773,7 @@  discard block
 block discarded – undo
2562 2773
 		{
2563 2774
 			$this->ref_ext = $ref_ext;
2564 2775
 			return 1;
2565
-		}
2566
-		else
2776
+		} else
2567 2777
 		{
2568 2778
 			$this->error=$this->db->error();
2569 2779
 			return -1;
@@ -2597,7 +2807,9 @@  discard block
 block discarded – undo
2597 2807
 		}
2598 2808
 		// Special cas
2599 2809
 		//var_dump($this->table_element);exit;
2600
-		if ($this->table_element == 'product') $suffix='';
2810
+		if ($this->table_element == 'product') {
2811
+		    $suffix='';
2812
+		}
2601 2813
 
2602 2814
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2603 2815
 		$sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
@@ -2607,16 +2819,17 @@  discard block
 block discarded – undo
2607 2819
 		dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
2608 2820
 		if ($this->db->query($sql))
2609 2821
 		{
2610
-			if ($suffix == '_public') $this->note_public = $note;
2611
-			else if ($suffix == '_private') $this->note_private = $note;
2612
-			else
2822
+			if ($suffix == '_public') {
2823
+			    $this->note_public = $note;
2824
+			} else if ($suffix == '_private') {
2825
+			    $this->note_private = $note;
2826
+			} else
2613 2827
 			{
2614 2828
 				$this->note = $note;      // deprecated
2615 2829
 				$this->note_private = $note;
2616 2830
 			}
2617 2831
 			return 1;
2618
-		}
2619
-		else
2832
+		} else
2620 2833
 		{
2621 2834
 			$this->error=$this->db->lasterror();
2622 2835
 			return -1;
@@ -2656,37 +2869,45 @@  discard block
 block discarded – undo
2656 2869
 
2657 2870
 		// Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
2658 2871
 		$MODULE = "";
2659
-		if ($this->element == 'propal')
2660
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
2661
-		elseif ($this->element == 'order')
2662
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
2663
-		elseif ($this->element == 'facture')
2664
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
2665
-		elseif ($this->element == 'facture_fourn')
2666
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
2667
-		elseif ($this->element == 'order_supplier')
2668
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
2669
-		elseif ($this->element == 'supplier_proposal')
2670
-			$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2872
+		if ($this->element == 'propal') {
2873
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
2874
+		} elseif ($this->element == 'order') {
2875
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
2876
+		} elseif ($this->element == 'facture') {
2877
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
2878
+		} elseif ($this->element == 'facture_fourn') {
2879
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
2880
+		} elseif ($this->element == 'order_supplier') {
2881
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
2882
+		} elseif ($this->element == 'supplier_proposal') {
2883
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2884
+		}
2671 2885
 
2672 2886
 		if (! empty($MODULE)) {
2673 2887
 			if (!empty(Globals::$conf->global->$MODULE)) {
2674 2888
                 $modsactivated = explode(',', Globals::$conf->global->$MODULE);
2675 2889
                 foreach ($modsactivated as $mod) {
2676
-					if (Globals::$conf->$mod->enabled)
2677
-                        return 1; // update was disabled by specific setup
2890
+					if (Globals::$conf->$mod->enabled) {
2891
+					                        return 1;
2892
+					}
2893
+					// update was disabled by specific setup
2678 2894
 				}
2679 2895
 			}
2680 2896
 		}
2681 2897
 
2682 2898
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2683 2899
 
2684
-		if ($roundingadjust == '-1') $roundingadjust='auto';	// For backward compatibility
2900
+		if ($roundingadjust == '-1') {
2901
+		    $roundingadjust='auto';
2902
+		}
2903
+		// For backward compatibility
2685 2904
 
2686 2905
 		$forcedroundingmode=$roundingadjust;
2687
-		if ($forcedroundingmode == 'auto' && isset(Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND))
2688
-            $forcedroundingmode = Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2689
-        elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2906
+		if ($forcedroundingmode == 'auto' && isset(Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
2907
+		            $forcedroundingmode = Globals::$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2908
+		} elseif ($forcedroundingmode == 'auto') {
2909
+            $forcedroundingmode='0';
2910
+        }
2690 2911
 
2691 2912
 		$error=0;
2692 2913
 
@@ -2709,15 +2930,22 @@  discard block
 block discarded – undo
2709 2930
 
2710 2931
 		$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 2932
 		$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';
2933
+			if ($this->table_element_line == 'facturedet') {
2934
+			    $sql.= ', situation_percent';
2935
+			}
2713 2936
 			$sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2714 2937
 		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2715 2938
 		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2716 2939
 		if ($exclspec)
2717 2940
 		{
2718 2941
 			$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';
2942
+			if ($this->table_element_line == 'contratdet') {
2943
+			    $product_field='';
2944
+			}
2945
+			// contratdet table has no product_type field
2946
+			if ($product_field) {
2947
+			    $sql.= ' AND '.$product_field.' <> 9';
2948
+			}
2721 2949
 		}
2722 2950
 		$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 2951
 
@@ -2747,9 +2975,11 @@  discard block
 block discarded – undo
2747 2975
 				$parameters=array('fk_element' => $obj->rowid);
2748 2976
 				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2749 2977
 
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'
2978
+				if (empty($reshook) && $forcedroundingmode == '0') {
2979
+				    // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
2751 2980
 				{
2752
-					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2981
+					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2982
+				}
2753 2983
 					$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 2984
 					$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2755 2985
 					if ($diff)
@@ -2757,7 +2987,9 @@  discard block
 block discarded – undo
2757 2987
 						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2758 2988
 						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 2989
 								$resqlfix=$this->db->query($sqlfix);
2760
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2990
+								if (! $resqlfix) {
2991
+								    dol_print_error($this->db,'Failed to update line');
2992
+								}
2761 2993
 								$obj->total_tva = $tmpcal[1];
2762 2994
 								$obj->total_ttc = $tmpcal[2];
2763 2995
 						//
@@ -2773,16 +3005,24 @@  discard block
 block discarded – undo
2773 3005
 				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2774 3006
 				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2775 3007
 
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;
3008
+				if (! isset($total_ht_by_vats[$obj->vatrate])) {
3009
+				    $total_ht_by_vats[$obj->vatrate]=0;
3010
+				}
3011
+				if (! isset($total_tva_by_vats[$obj->vatrate])) {
3012
+				    $total_tva_by_vats[$obj->vatrate]=0;
3013
+				}
3014
+				if (! isset($total_ttc_by_vats[$obj->vatrate])) {
3015
+				    $total_ttc_by_vats[$obj->vatrate]=0;
3016
+				}
2779 3017
 				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2780 3018
 				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2781 3019
 				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2782 3020
 
2783
-				if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3021
+				if ($forcedroundingmode == '1') {
3022
+				    // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2784 3023
 				{
2785
-					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3024
+					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3025
+				}
2786 3026
 					$diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2787 3027
 					//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 3028
 					if ($diff)
@@ -2791,7 +3031,9 @@  discard block
 block discarded – undo
2791 3031
 						$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 3032
 						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 3033
 								$resqlfix=$this->db->query($sqlfix);
2794
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
3034
+								if (! $resqlfix) {
3035
+								    dol_print_error($this->db,'Failed to update line');
3036
+								}
2795 3037
 								$this->total_tva -= $diff;
2796 3038
 								$this->total_ttc -= $diff;
2797 3039
 								$total_tva_by_vats[$obj->vatrate] -= $diff;
@@ -2832,11 +3074,21 @@  discard block
 block discarded – undo
2832 3074
 			$fieldlocaltax2='localtax2';
2833 3075
 			$fieldttc='total_ttc';
2834 3076
 			// 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';
3077
+			if ($this->element == 'facture' || $this->element == 'facturerec') {
3078
+			    $fieldht='total';
3079
+			}
3080
+			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3081
+			    $fieldtva='total_tva';
3082
+			}
3083
+			if ($this->element == 'propal') {
3084
+			    $fieldttc='total';
3085
+			}
3086
+			if ($this->element == 'expensereport') {
3087
+			    $fieldtva='total_tva';
3088
+			}
3089
+			if ($this->element == 'supplier_proposal') {
3090
+			    $fieldttc='total';
3091
+			}
2840 3092
 
2841 3093
 			if (empty($nodatabaseupdate))
2842 3094
 			{
@@ -2865,13 +3117,11 @@  discard block
 block discarded – undo
2865 3117
 			if (! $error)
2866 3118
 			{
2867 3119
 				return 1;
2868
-			}
2869
-			else
3120
+			} else
2870 3121
 			{
2871 3122
 				return -1;
2872 3123
 			}
2873
-		}
2874
-		else
3124
+		} else
2875 3125
 		{
2876 3126
 			dol_print_error($this->db,'Bad request in update_price');
2877 3127
 			return -1;
@@ -2894,10 +3144,18 @@  discard block
 block discarded – undo
2894 3144
 		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2895 3145
 
2896 3146
 		// 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';
3147
+		if ($origin == 'order') {
3148
+		    $origin='commande';
3149
+		}
3150
+		if ($origin == 'invoice') {
3151
+		    $origin='facture';
3152
+		}
3153
+		if ($origin == 'invoice_template') {
3154
+		    $origin='facturerec';
3155
+		}
3156
+    	if ($origin == 'supplierorder') {
3157
+    	    $origin='order_supplier';
3158
+    	}
2901 3159
 		$this->db->begin();
2902 3160
 
2903 3161
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
@@ -2917,8 +3175,7 @@  discard block
 block discarded – undo
2917 3175
 	  	{
2918 3176
 	  		$this->db->commit();
2919 3177
 	  		return 1;
2920
-	  	}
2921
-	  	else
3178
+	  	} else
2922 3179
 	  	{
2923 3180
 	  		$this->error=$this->db->lasterror();
2924 3181
 	  		$this->db->rollback();
@@ -2963,12 +3220,16 @@  discard block
 block discarded – undo
2963 3220
 		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2964 3221
 		{
2965 3222
 			$justsource=true;  // the source (id and type) is a search criteria
2966
-			if (! empty($targettype)) $withtargettype=true;
3223
+			if (! empty($targettype)) {
3224
+			    $withtargettype=true;
3225
+			}
2967 3226
 		}
2968 3227
 		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2969 3228
 		{
2970 3229
 			$justtarget=true;  // the target (id and type) is a search criteria
2971
-			if (! empty($sourcetype)) $withsourcetype=true;
3230
+			if (! empty($sourcetype)) {
3231
+			    $withsourcetype=true;
3232
+			}
2972 3233
 		}
2973 3234
 
2974 3235
 		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
@@ -2991,15 +3252,17 @@  discard block
 block discarded – undo
2991 3252
 			if ($justsource)
2992 3253
 			{
2993 3254
 				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2994
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2995
-			}
2996
-			else if ($justtarget)
3255
+				if ($withtargettype) {
3256
+				    $sql.= " AND targettype = '".$targettype."'";
3257
+				}
3258
+			} else if ($justtarget)
2997 3259
 			{
2998 3260
 				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2999
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
3261
+				if ($withsourcetype) {
3262
+				    $sql.= " AND sourcetype = '".$sourcetype."'";
3263
+				}
3000 3264
 			}
3001
-		}
3002
-		else
3265
+		} else
3003 3266
 		{
3004 3267
 			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3005 3268
 			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
@@ -3020,13 +3283,11 @@  discard block
 block discarded – undo
3020 3283
 					if ($justsource)
3021 3284
 					{
3022 3285
 						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3023
-					}
3024
-					else if ($justtarget)
3286
+					} else if ($justtarget)
3025 3287
 					{
3026 3288
 						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3027 3289
 					}
3028
-				}
3029
-				else
3290
+				} else
3030 3291
 				{
3031 3292
 					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3032 3293
 					{
@@ -3043,10 +3304,12 @@  discard block
 block discarded – undo
3043 3304
 			if (! empty($this->linkedObjectsIds))
3044 3305
 			{
3045 3306
 				$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', ...)
3307
+				foreach($tmparray as $objecttype => $objectids) {
3308
+				    // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3047 3309
 				{
3048 3310
 					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3049
-					$module = $element = $subelement = $objecttype;
3311
+					$module = $element = $subelement = $objecttype;
3312
+				}
3050 3313
 					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3051 3314
 						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3052 3315
 					{
@@ -3058,29 +3321,21 @@  discard block
 block discarded – undo
3058 3321
 					// To work with non standard classpath or module name
3059 3322
 					if ($objecttype == 'facture')			{
3060 3323
 						$classpath = 'compta/facture/class';
3061
-					}
3062
-					else if ($objecttype == 'facturerec')			{
3324
+					} else if ($objecttype == 'facturerec')			{
3063 3325
 						$classpath = 'compta/facture/class'; $module = 'facture';
3064
-					}
3065
-					else if ($objecttype == 'propal')			{
3326
+					} else if ($objecttype == 'propal')			{
3066 3327
 						$classpath = 'comm/propal/class';
3067
-					}
3068
-					else if ($objecttype == 'supplier_proposal')			{
3328
+					} else if ($objecttype == 'supplier_proposal')			{
3069 3329
 						$classpath = 'supplier_proposal/class';
3070
-					}
3071
-					else if ($objecttype == 'shipping')			{
3330
+					} else if ($objecttype == 'shipping')			{
3072 3331
 						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3073
-					}
3074
-					else if ($objecttype == 'delivery')			{
3332
+					} else if ($objecttype == 'delivery')			{
3075 3333
 						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3076
-					}
3077
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3334
+					} else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3078 3335
 						$classpath = 'fourn/class'; $module = 'fournisseur';
3079
-					}
3080
-					else if ($objecttype == 'fichinter')			{
3336
+					} else if ($objecttype == 'fichinter')			{
3081 3337
 						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3082
-					}
3083
-					else if ($objecttype == 'subscription')			{
3338
+					} else if ($objecttype == 'subscription')			{
3084 3339
 						$classpath = 'adherents/class'; $module = 'adherent';
3085 3340
 					}
3086 3341
 
@@ -3089,20 +3344,15 @@  discard block
 block discarded – undo
3089 3344
 
3090 3345
 					if ($objecttype == 'order') {
3091 3346
 						$classfile = 'commande'; $classname = 'Commande';
3092
-					}
3093
-					else if ($objecttype == 'invoice_supplier') {
3347
+					} else if ($objecttype == 'invoice_supplier') {
3094 3348
 						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3095
-					}
3096
-					else if ($objecttype == 'order_supplier')   {
3349
+					} else if ($objecttype == 'order_supplier')   {
3097 3350
 						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3098
-					}
3099
-					else if ($objecttype == 'supplier_proposal')   {
3351
+					} else if ($objecttype == 'supplier_proposal')   {
3100 3352
 						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3101
-					}
3102
-					else if ($objecttype == 'facturerec')   {
3353
+					} else if ($objecttype == 'facturerec')   {
3103 3354
 						$classfile = 'facture-rec'; $classname = 'FactureRec';
3104
-					}
3105
-					else if ($objecttype == 'subscription')   {
3355
+					} else if ($objecttype == 'subscription')   {
3106 3356
 						$classfile = 'subscription'; $classname = 'Subscription';
3107 3357
 					}
3108 3358
 
@@ -3114,9 +3364,11 @@  discard block
 block discarded – undo
3114 3364
 							//print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
3115 3365
 							if (class_exists($classname))
3116 3366
 							{
3117
-								foreach($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3367
+								foreach($objectids as $i => $objectid) {
3368
+								    // $i is rowid into llx_element_element
3118 3369
 								{
3119
-									$object = new $classname($this->db);
3370
+									$object = new $classname($this->db);
3371
+								}
3120 3372
 									$ret = $object->fetch($objectid);
3121 3373
 									if ($ret >= 0)
3122 3374
 									{
@@ -3125,16 +3377,14 @@  discard block
 block discarded – undo
3125 3377
 								}
3126 3378
 							}
3127 3379
 						}
3128
-					}
3129
-					else
3380
+					} else
3130 3381
 					{
3131 3382
 						unset($this->linkedObjectsIds[$objecttype]);
3132 3383
 					}
3133 3384
 				}
3134 3385
 			}
3135 3386
 			return 1;
3136
-		}
3137
-		else
3387
+		} else
3138 3388
 		{
3139 3389
 			dol_print_error($this->db);
3140 3390
 			return -1;
@@ -3156,8 +3406,11 @@  discard block
 block discarded – undo
3156 3406
 		$updatesource=false;
3157 3407
 		$updatetarget=false;
3158 3408
 
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;
3409
+		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) {
3410
+		    $updatesource=true;
3411
+		} else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) {
3412
+		    $updatetarget=true;
3413
+		}
3161 3414
 
3162 3415
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
3163 3416
 		if ($updatesource)
@@ -3166,8 +3419,7 @@  discard block
 block discarded – undo
3166 3419
 			$sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'";
3167 3420
 			$sql.= " WHERE fk_target = ".$this->id;
3168 3421
 			$sql.= " AND targettype = '".$this->db->escape($this->element)."'";
3169
-		}
3170
-		else if ($updatetarget)
3422
+		} else if ($updatetarget)
3171 3423
 		{
3172 3424
 			$sql.= "fk_target = ".$targetid;
3173 3425
 			$sql.= ", targettype = '".$this->db->escape($targettype)."'";
@@ -3179,8 +3431,7 @@  discard block
 block discarded – undo
3179 3431
 		if ($this->db->query($sql))
3180 3432
 		{
3181 3433
 			return 1;
3182
-		}
3183
-		else
3434
+		} else
3184 3435
 		{
3185 3436
 			$this->error=$this->db->lasterror();
3186 3437
 			return -1;
@@ -3203,8 +3454,11 @@  discard block
 block discarded – undo
3203 3454
 		$deletesource=false;
3204 3455
 		$deletetarget=false;
3205 3456
 
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;
3457
+		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) {
3458
+		    $deletesource=true;
3459
+		} else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) {
3460
+		    $deletetarget=true;
3461
+		}
3208 3462
 
3209 3463
 		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
3210 3464
 		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
@@ -3216,20 +3470,17 @@  discard block
 block discarded – undo
3216 3470
 		if ($rowid > 0)
3217 3471
 		{
3218 3472
 			$sql.=" rowid = ".$rowid;
3219
-		}
3220
-		else
3473
+		} else
3221 3474
 		{
3222 3475
 			if ($deletesource)
3223 3476
 			{
3224 3477
 				$sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3225 3478
 				$sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
3226
-			}
3227
-			else if ($deletetarget)
3479
+			} else if ($deletetarget)
3228 3480
 			{
3229 3481
 				$sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
3230 3482
 				$sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
3231
-			}
3232
-			else
3483
+			} else
3233 3484
 			{
3234 3485
 				$sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
3235 3486
 				$sql.= " OR";
@@ -3241,8 +3492,7 @@  discard block
 block discarded – undo
3241 3492
 		if ($this->db->query($sql))
3242 3493
 		{
3243 3494
 			return 1;
3244
-		}
3245
-		else
3495
+		} else
3246 3496
 		{
3247 3497
 			$this->error=$this->db->lasterror();
3248 3498
 			$this->errors[]=$this->error;
@@ -3271,17 +3521,31 @@  discard block
 block discarded – undo
3271 3521
 		$this->db->begin();
3272 3522
 
3273 3523
 		$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";
3524
+		if ($elementTable == 'facture_rec') {
3525
+		    $fieldstatus="suspended";
3526
+		}
3527
+		if ($elementTable == 'mailing') {
3528
+		    $fieldstatus="statut";
3529
+		}
3530
+		if ($elementTable == 'cronjob') {
3531
+		    $fieldstatus="status";
3532
+		}
3533
+		if ($elementTable == 'user') {
3534
+		    $fieldstatus="statut";
3535
+		}
3536
+		if ($elementTable == 'expensereport') {
3537
+		    $fieldstatus="fk_statut";
3538
+		}
3539
+		if ($elementTable == 'commande_fournisseur_dispatch') {
3540
+		    $fieldstatus="status";
3541
+		}
3280 3542
 
3281 3543
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
3282 3544
 		$sql.= " SET ".$fieldstatus." = ".$status;
3283 3545
 		// If status = 1 = validated, update also fk_user_valid
3284
-		if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
3546
+		if ($status == 1 && $elementTable == 'expensereport') {
3547
+		    $sql.=", fk_user_valid = ".$user->id;
3548
+		}
3285 3549
 		$sql.= " WHERE rowid=".$elementId;
3286 3550
 
3287 3551
 		dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
@@ -3292,12 +3556,27 @@  discard block
 block discarded – undo
3292 3556
 			// Try autoset of trigkey
3293 3557
 			if (empty($trigkey))
3294 3558
 			{
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';
3559
+				if ($this->element == 'supplier_proposal' && $status == 2) {
3560
+				    $trigkey='SUPPLIER_PROPOSAL_SIGN';
3561
+				}
3562
+				// 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
3563
+				if ($this->element == 'supplier_proposal' && $status == 3) {
3564
+				    $trigkey='SUPPLIER_PROPOSAL_REFUSE';
3565
+				}
3566
+				// 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
3567
+				if ($this->element == 'supplier_proposal' && $status == 4) {
3568
+				    $trigkey='SUPPLIER_PROPOSAL_CLOSE';
3569
+				}
3570
+				// 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
3571
+				if ($this->element == 'fichinter' && $status == 3) {
3572
+				    $trigkey='FICHINTER_CLASSIFY_DONE';
3573
+				}
3574
+				if ($this->element == 'fichinter' && $status == 2) {
3575
+				    $trigkey='FICHINTER_CLASSIFY_BILLED';
3576
+				}
3577
+				if ($this->element == 'fichinter' && $status == 1) {
3578
+				    $trigkey='FICHINTER_CLASSIFY_UNBILLED';
3579
+				}
3301 3580
 			}
3302 3581
 
3303 3582
 			if ($trigkey)
@@ -3316,22 +3595,22 @@  discard block
 block discarded – undo
3316 3595
 			{
3317 3596
 				$this->db->commit();
3318 3597
 
3319
-				if (empty($savElementId))    // If the element we update was $this (so $elementId is null)
3598
+				if (empty($savElementId)) {
3599
+				    // If the element we update was $this (so $elementId is null)
3320 3600
 				{
3321
-					$this->statut = $status;
3601
+					$this->statut = $status;
3602
+				}
3322 3603
 					$this->status = $status;
3323 3604
 				}
3324 3605
 
3325 3606
 				return 1;
3326
-			}
3327
-			else
3607
+			} else
3328 3608
 			{
3329 3609
 				$this->db->rollback();
3330 3610
 				dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
3331 3611
 				return -1;
3332 3612
 			}
3333
-		}
3334
-		else
3613
+		} else
3335 3614
 		{
3336 3615
 			$this->error=$this->db->lasterror();
3337 3616
 			$this->db->rollback();
@@ -3351,9 +3630,13 @@  discard block
 block discarded – undo
3351 3630
 	{
3352 3631
 		global $conf;
3353 3632
 
3354
-		if (empty($id) && empty($ref)) return 0;
3355
-		if (!empty(Globals::$conf->global->MAIN_DISABLE_CANVAS))
3356
-            return 0;    // To increase speed. Not enabled by default.
3633
+		if (empty($id) && empty($ref)) {
3634
+		    return 0;
3635
+		}
3636
+		if (!empty(Globals::$conf->global->MAIN_DISABLE_CANVAS)) {
3637
+		            return 0;
3638
+		}
3639
+		// To increase speed. Not enabled by default.
3357 3640
 
3358 3641
             // Clean parameters
3359 3642
 		$ref = trim($ref);
@@ -3361,8 +3644,12 @@  discard block
 block discarded – undo
3361 3644
 		$sql = "SELECT rowid, canvas";
3362 3645
 		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3363 3646
 		$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)."'";
3647
+		if (! empty($id)) {
3648
+		    $sql.= " AND rowid = ".$id;
3649
+		}
3650
+		if (! empty($ref)) {
3651
+		    $sql.= " AND ref = '".$this->db->escape($ref)."'";
3652
+		}
3366 3653
 
3367 3654
 		$resql = $this->db->query($sql);
3368 3655
 		if ($resql)
@@ -3372,10 +3659,10 @@  discard block
 block discarded – undo
3372 3659
 			{
3373 3660
 				$this->canvas   = $obj->canvas;
3374 3661
 				return 1;
3375
-			}
3376
-			else return 0;
3377
-		}
3378
-		else
3662
+			} else {
3663
+			    return 0;
3664
+			}
3665
+		} else
3379 3666
 		{
3380 3667
 			dol_print_error($this->db);
3381 3668
 			return -1;
@@ -3412,7 +3699,9 @@  discard block
 block discarded – undo
3412 3699
 	{
3413 3700
 		global $langs;
3414 3701
 
3415
-		if (empty($id)) $id=$this->id;
3702
+		if (empty($id)) {
3703
+		    $id=$this->id;
3704
+		}
3416 3705
 
3417 3706
 		// Check parameters
3418 3707
 		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
@@ -3446,18 +3735,18 @@  discard block
 block discarded – undo
3446 3735
 					$langs->load("errors");
3447 3736
 					//print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3448 3737
 					$haschild += $obj->nb;
3449
-					if (is_numeric($elementname))	// old usage
3738
+					if (is_numeric($elementname)) {
3739
+					    // old usage
3450 3740
 					{
3451
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3452
-					}
3453
-					else	// new usage: $elementname=Translation key
3741
+						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3742
+					}
3743
+					} else	// new usage: $elementname=Translation key
3454 3744
 					{
3455 3745
 						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3456 3746
 					}
3457 3747
 					break;    // We found at least one, we stop here
3458 3748
 				}
3459
-			}
3460
-			else
3749
+			} else
3461 3750
 			{
3462 3751
 				$this->errors[]=$this->db->lasterror();
3463 3752
 				return -1;
@@ -3467,8 +3756,9 @@  discard block
 block discarded – undo
3467 3756
 		{
3468 3757
 			$this->errors[]="ErrorRecordHasChildren";
3469 3758
 			return $haschild;
3470
-		}
3471
-		else return 0;
3759
+		} else {
3760
+		    return 0;
3761
+		}
3472 3762
 	}
3473 3763
 
3474 3764
 	/**
@@ -3484,12 +3774,24 @@  discard block
 block discarded – undo
3484 3774
 		foreach($this->lines as $key => $val)
3485 3775
 		{
3486 3776
 			$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
-			if ($qualified) $nb++;
3777
+			if ($predefined == -1) {
3778
+			    $qualified=1;
3779
+			}
3780
+			if ($predefined == 1 && $val->fk_product > 0) {
3781
+			    $qualified=1;
3782
+			}
3783
+			if ($predefined == 0 && $val->fk_product <= 0) {
3784
+			    $qualified=1;
3785
+			}
3786
+			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) {
3787
+			    $qualified=1;
3788
+			}
3789
+			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) {
3790
+			    $qualified=1;
3791
+			}
3792
+			if ($qualified) {
3793
+			    $nb++;
3794
+			}
3493 3795
 		}
3494 3796
 		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3495 3797
 		return $nb;
@@ -3553,16 +3855,24 @@  discard block
 block discarded – undo
3553 3855
 		{
3554 3856
 			if (isset($line->qty_asked))
3555 3857
 			{
3556
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3858
+				if (empty($totalOrdered)) {
3859
+				    $totalOrdered=0;
3860
+				}
3861
+				// Avoid warning because $totalOrdered is ''
3557 3862
 				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3558 3863
 			}
3559 3864
 			if (isset($line->qty_shipped))
3560 3865
 			{
3561
-				if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3866
+				if (empty($totalToShip)) {
3867
+				    $totalToShip=0;
3868
+				}
3869
+				// Avoid warning because $totalToShip is ''
3562 3870
 				$totalToShip+=$line->qty_shipped;   // defined for shipment only
3563
-            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3871
+            } else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3564 3872
             {
3565
-                if (empty($totalToShip)) $totalToShip=0;
3873
+                if (empty($totalToShip)) {
3874
+                    $totalToShip=0;
3875
+                }
3566 3876
                 $totalToShip+=$line->qty;   // defined for reception only
3567 3877
 			}
3568 3878
 
@@ -3570,8 +3880,7 @@  discard block
 block discarded – undo
3570 3880
 			if ($this->element == 'shipping') {
3571 3881
 				// for shipments
3572 3882
 				$qty = $line->qty_shipped ? $line->qty_shipped : 0;
3573
-			}
3574
-			else {
3883
+			} else {
3575 3884
 				$qty = $line->qty ? $line->qty : 0;
3576 3885
 			}
3577 3886
 
@@ -3587,19 +3896,30 @@  discard block
 block discarded – undo
3587 3896
 
3588 3897
 			$weightUnit=0;
3589 3898
 			$volumeUnit=0;
3590
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3591
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
3592
-
3593
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3594
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3899
+			if (! empty($weight_units)) {
3900
+			    $weightUnit = $weight_units;
3901
+			}
3902
+			if (! empty($volume_units)) {
3903
+			    $volumeUnit = $volume_units;
3904
+			}
3905
+
3906
+			if (empty($totalWeight)) {
3907
+			    $totalWeight=0;
3908
+			}
3909
+			// Avoid warning because $totalWeight is ''
3910
+			if (empty($totalVolume)) {
3911
+			    $totalVolume=0;
3912
+			}
3913
+			// Avoid warning because $totalVolume is ''
3595 3914
 
3596 3915
 			//var_dump($line->volume_units);
3597
-			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3916
+			if ($weight_units < 50) {
3917
+			    // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3598 3918
 			{
3599
-				$trueWeightUnit=pow(10, $weightUnit);
3919
+				$trueWeightUnit=pow(10, $weightUnit);
3920
+			}
3600 3921
 				$totalWeight += $weight * $qty * $trueWeightUnit;
3601
-			}
3602
-			else {
3922
+			} else {
3603 3923
 		if ($weight_units == 99) {
3604 3924
 			// conversion 1 Pound = 0.45359237 KG
3605 3925
 			$trueWeightUnit = 0.45359237;
@@ -3608,18 +3928,20 @@  discard block
 block discarded – undo
3608 3928
 			// conversion 1 Ounce = 0.0283495 KG
3609 3929
 			$trueWeightUnit = 0.0283495;
3610 3930
 			$totalWeight += $weight * $qty * $trueWeightUnit;
3611
-		}
3612
-		else
3613
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3931
+		} else {
3932
+							$totalWeight += $weight * $qty;
3933
+		}
3934
+		// This may be wrong if we mix different units
3614 3935
 			}
3615
-			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3936
+			if ($volume_units < 50) {
3937
+			    // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3616 3938
 			{
3617 3939
 				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3618
-				$trueVolumeUnit=pow(10, $volumeUnit);
3940
+				$trueVolumeUnit=pow(10, $volumeUnit);
3941
+			}
3619 3942
 				//print $line->volume;
3620 3943
 				$totalVolume += $volume * $qty * $trueVolumeUnit;
3621
-			}
3622
-			else
3944
+			} else
3623 3945
 			{
3624 3946
 				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3625 3947
 			}
@@ -3651,8 +3973,7 @@  discard block
 block discarded – undo
3651 3973
 			$this->error=$this->db->lasterror();
3652 3974
 			$this->db->rollback();
3653 3975
 			return -1;
3654
-		}
3655
-		else
3976
+		} else
3656 3977
 		{
3657 3978
 			$this->db->commit();
3658 3979
 			return 1;
@@ -3704,13 +4025,11 @@  discard block
 block discarded – undo
3704 4025
 			{
3705 4026
 				$res = $this->db->fetch_object($resql);
3706 4027
 				return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3707
-			}
3708
-			else
4028
+			} else
3709 4029
 			{
3710 4030
 				return '';
3711 4031
 			}
3712
-		}
3713
-		else
4032
+		} else
3714 4033
 		{
3715 4034
 			$this->errors[] = $this->db->lasterror();
3716 4035
 			return false;
@@ -3747,14 +4066,14 @@  discard block
 block discarded – undo
3747 4066
 					$this->libelle_incoterms = $obj->libelle;
3748 4067
 				}
3749 4068
 				return 1;
3750
-			}
3751
-			else
4069
+			} else
3752 4070
 			{
3753 4071
 				$this->errors[] = $this->db->lasterror();
3754 4072
 				return -1;
3755 4073
 			}
3756
-		}
3757
-		else return -1;
4074
+		} else {
4075
+		    return -1;
4076
+		}
3758 4077
 	}
3759 4078
 
3760 4079
 
@@ -3793,7 +4112,9 @@  discard block
 block discarded – undo
3793 4112
 			} else {
3794 4113
 				$res=include $tpl; // for debug
3795 4114
 			}
3796
-			if ($res) break;
4115
+			if ($res) {
4116
+			    break;
4117
+			}
3797 4118
 		}
3798 4119
 	}
3799 4120
 
@@ -3823,8 +4144,9 @@  discard block
 block discarded – undo
3823 4144
 
3824 4145
 		// Define usemargins
3825 4146
 		$usemargins=0;
3826
-		if (!empty(Globals::$conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande')))
3827
-            $usemargins = 1;
4147
+		if (!empty(Globals::$conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande'))) {
4148
+		            $usemargins = 1;
4149
+		}
3828 4150
 
3829 4151
         $num = count($this->lines);
3830 4152
 
@@ -3843,8 +4165,9 @@  discard block
 block discarded – undo
3843 4165
 			print '<tr class="liste_titre nodrag nodrop">';
3844 4166
 
3845 4167
 			// Adds a line numbering column
3846
-			if (!empty(Globals::$conf->global->MAIN_VIEW_LINE_NUMBER))
3847
-                print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
4168
+			if (!empty(Globals::$conf->global->MAIN_VIEW_LINE_NUMBER)) {
4169
+			                print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
4170
+			}
3848 4171
 
3849 4172
             // Description
3850 4173
 			print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
@@ -3861,10 +4184,13 @@  discard block
 block discarded – undo
3861 4184
 			print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
3862 4185
 
3863 4186
 			// Multicurrency
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>';
4187
+			if (!empty(Globals::$conf->multicurrency->enabled) && $this->multicurrency_code != Globals::$conf->currency) {
4188
+			                print '<td class="linecoluht_currency" align="right" width="80">' . $langs->trans('PriceUHTCurrency', $this->multicurrency_code) . '</td>';
4189
+			}
3866 4190
 
3867
-            if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
4191
+            if ($inputalsopricewithtax) {
4192
+                print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
4193
+            }
3868 4194
 
3869 4195
 			// Qty
3870 4196
 			print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
@@ -3883,26 +4209,32 @@  discard block
 block discarded – undo
3883 4209
 			if ($usemargins && !empty(Globals::$conf->margin->enabled) && empty($user->societe_id)) {
3884 4210
 				if (!empty($user->rights->margins->creer))
3885 4211
 				{
3886
-					if (Globals::$conf->global->MARGIN_TYPE == "1")
3887
-                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3888
-					else
3889
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
4212
+					if (Globals::$conf->global->MARGIN_TYPE == "1") {
4213
+					                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
4214
+					} else {
4215
+											print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
4216
+					}
3890 4217
 				}
3891 4218
 
3892
-				if (!empty(Globals::$conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3893
-                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3894
-				if (!empty(Globals::$conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3895
-                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
4219
+				if (!empty(Globals::$conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) {
4220
+				                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
4221
+				}
4222
+				if (!empty(Globals::$conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) {
4223
+				                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
4224
+				}
3896 4225
 			}
3897 4226
 
3898 4227
 			// Total HT
3899 4228
 			print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
3900 4229
 
3901 4230
 			// Multicurrency
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>';
4231
+			if (!empty(Globals::$conf->multicurrency->enabled) && $this->multicurrency_code != Globals::$conf->currency) {
4232
+			                print '<td class="linecoltotalht_currency" align="right">' . $langs->trans('TotalHTShortCurrency', $this->multicurrency_code) . '</td>';
4233
+			}
3904 4234
 
3905
-            if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
4235
+            if ($outputalsopricetotalwithtax) {
4236
+                print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
4237
+            }
3906 4238
 
3907 4239
 			print '<td class="linecoledit"></td>';  // No width to allow autodim
3908 4240
 
@@ -3932,14 +4264,15 @@  discard block
 block discarded – undo
3932 4264
 			$line->fetch_optionals();
3933 4265
 
3934 4266
 			//if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3935
-			if (is_object($hookmanager))   // Old code is commented on preceding line.
4267
+			if (is_object($hookmanager)) {
4268
+			    // Old code is commented on preceding line.
3936 4269
 			{
3937 4270
 				if (empty($line->fk_parent_line))
3938 4271
 				{
3939
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
4272
+					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
4273
+			}
3940 4274
 					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3941
-				}
3942
-				else
4275
+				} else
3943 4276
 				{
3944 4277
 					$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 4278
 					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
@@ -3986,8 +4319,14 @@  discard block
 block discarded – undo
3986 4319
 		// Show product and description
3987 4320
 		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3988 4321
 		// 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
4322
+		if (! empty($line->date_start)) {
4323
+		    $type=1;
4324
+		}
4325
+		// deprecated
4326
+		if (! empty($line->date_end)) {
4327
+		    $type=1;
4328
+		}
4329
+		// deprecated
3991 4330
 
3992 4331
 		// Ligne en mode visu
3993 4332
 		if ($action != 'editline' || $selected != $line->id)
@@ -4015,9 +4354,13 @@  discard block
 block discarded – undo
4015 4354
 
4016 4355
 					$outputlangs = $langs;
4017 4356
 					$newlang='';
4018
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
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
4357
+					if (empty($newlang) && GETPOST('lang_id','aZ09')) {
4358
+					    $newlang=GETPOST('lang_id','aZ09');
4359
+					}
4360
+					if (!empty(Globals::$conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) {
4361
+					                        $newlang = $this->thirdparty->default_lang;
4362
+					}
4363
+					// For language to language of customer
4021 4364
                     if (! empty($newlang))
4022 4365
 					{
4023 4366
 						$outputlangs = new Translate("",$conf);
@@ -4025,8 +4368,7 @@  discard block
 block discarded – undo
4025 4368
 					}
4026 4369
 
4027 4370
 					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4028
-				}
4029
-				else
4371
+				} else
4030 4372
 				{
4031 4373
 					$label = $line->product_label;
4032 4374
 				}
@@ -4048,7 +4390,9 @@  discard block
 block discarded – undo
4048 4390
 				} else {
4049 4391
 					$res=include $tpl; // for debug
4050 4392
 				}
4051
-				if ($res) break;
4393
+				if ($res) {
4394
+				    break;
4395
+				}
4052 4396
 			}
4053 4397
 		}
4054 4398
 
@@ -4071,7 +4415,9 @@  discard block
 block discarded – undo
4071 4415
 				} else {
4072 4416
 					$res=include $tpl; // for debug
4073 4417
 				}
4074
-				if ($res) break;
4418
+				if ($res) {
4419
+				    break;
4420
+				}
4075 4421
 			}
4076 4422
 		}
4077 4423
 	}
@@ -4098,8 +4444,9 @@  discard block
 block discarded – undo
4098 4444
 		print '<td>'.$langs->trans('Description').'</td>';
4099 4445
 		print '<td align="right">'.$langs->trans('VATRate').'</td>';
4100 4446
 		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4101
-		if (!empty(Globals::$conf->multicurrency->enabled))
4102
-            print '<td align="right">' . $langs->trans('PriceUHTCurrency') . '</td>';
4447
+		if (!empty(Globals::$conf->multicurrency->enabled)) {
4448
+		            print '<td align="right">' . $langs->trans('PriceUHTCurrency') . '</td>';
4449
+		}
4103 4450
         print '<td align="right">'.$langs->trans('Qty').'</td>';
4104 4451
 		if (Globals::$conf->global->PRODUCT_USE_UNITS) {
4105 4452
 			print '<td align="left">'.$langs->trans('Unit').'</td>';
@@ -4121,8 +4468,7 @@  discard block
 block discarded – undo
4121 4468
 						$action='';
4122 4469
 						$hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4123 4470
 					}
4124
-				}
4125
-				else
4471
+				} else
4126 4472
 				{
4127 4473
 					$this->printOriginLine($line, $var, $restrictlist);
4128 4474
 				}
@@ -4151,32 +4497,37 @@  discard block
 block discarded – undo
4151 4497
 		if (!empty($line->date_start))
4152 4498
 		{
4153 4499
 			$date_start=$line->date_start;
4154
-		}
4155
-		else
4500
+		} else
4156 4501
 		{
4157 4502
 			$date_start=$line->date_debut_prevue;
4158
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4503
+			if ($line->date_debut_reel) {
4504
+			    $date_start=$line->date_debut_reel;
4505
+			}
4159 4506
 		}
4160 4507
 		if (!empty($line->date_end))
4161 4508
 		{
4162 4509
 			$date_end=$line->date_end;
4163
-		}
4164
-		else
4510
+		} else
4165 4511
 		{
4166 4512
 			$date_end=$line->date_fin_prevue;
4167
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4513
+			if ($line->date_fin_reel) {
4514
+			    $date_end=$line->date_fin_reel;
4515
+			}
4168 4516
 		}
4169 4517
 
4170 4518
 		$this->tpl['label'] = '';
4171
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4519
+		if (! empty($line->fk_parent_line)) {
4520
+		    $this->tpl['label'].= img_picto('', 'rightarrow');
4521
+		}
4172 4522
 
4173
-		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4523
+		if (($line->info_bits & 2) == 2) {
4524
+		    // TODO Not sure this is used for source object
4174 4525
 		{
4175
-			$discount=new DiscountAbsolute($this->db);
4526
+			$discount=new DiscountAbsolute($this->db);
4527
+		}
4176 4528
 			$discount->fk_soc = $this->socid;
4177 4529
 			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4178
-		}
4179
-		else if (! empty($line->fk_product))
4530
+		} else if (! empty($line->fk_product))
4180 4531
 		{
4181 4532
 			$productstatic = new Product($this->db);
4182 4533
 			$productstatic->id = $line->fk_product;
@@ -4194,13 +4545,12 @@  discard block
 block discarded – undo
4194 4545
 			{
4195 4546
 				$this->tpl['label'].= get_date_range($date_start,$date_end);
4196 4547
 			}
4197
-		}
4198
-		else
4548
+		} else
4199 4549
 		{
4200 4550
 			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4201 4551
 			if (!empty($line->desc)) {
4202 4552
 				$this->tpl['label'].=$line->desc;
4203
-			}else {
4553
+			} else {
4204 4554
 				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4205 4555
 			}
4206 4556
 			
@@ -4213,36 +4563,35 @@  discard block
 block discarded – undo
4213 4563
 
4214 4564
 		if (! empty($line->desc))
4215 4565
 		{
4216
-			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4566
+			if ($line->desc == '(CREDIT_NOTE)') {
4567
+			    // TODO Not sure this is used for source object
4217 4568
 			{
4218
-				$discount=new DiscountAbsolute($this->db);
4569
+				$discount=new DiscountAbsolute($this->db);
4570
+			}
4219 4571
 				$discount->fetch($line->fk_remise_except);
4220 4572
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4221
-			}
4222
-			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4573
+			} elseif ($line->desc == '(DEPOSIT)') {
4574
+			    // TODO Not sure this is used for source object
4223 4575
 			{
4224
-				$discount=new DiscountAbsolute($this->db);
4576
+				$discount=new DiscountAbsolute($this->db);
4577
+			}
4225 4578
 				$discount->fetch($line->fk_remise_except);
4226 4579
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4227
-			}
4228
-			elseif ($line->desc == '(EXCESS RECEIVED)')
4580
+			} elseif ($line->desc == '(EXCESS RECEIVED)')
4229 4581
 			{
4230 4582
 				$discount=new DiscountAbsolute($this->db);
4231 4583
 				$discount->fetch($line->fk_remise_except);
4232 4584
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4233
-			}
4234
-			elseif ($line->desc == '(EXCESS PAID)')
4585
+			} elseif ($line->desc == '(EXCESS PAID)')
4235 4586
 			{
4236 4587
 				$discount=new DiscountAbsolute($this->db);
4237 4588
 				$discount->fetch($line->fk_remise_except);
4238 4589
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4239
-			}
4240
-			else
4590
+			} else
4241 4591
 			{
4242 4592
 				$this->tpl['description'] = dol_trunc($line->desc,60);
4243 4593
 			}
4244
-		}
4245
-		else
4594
+		} else
4246 4595
 		{
4247 4596
 			$this->tpl['description'] = '&nbsp;';
4248 4597
 		}
@@ -4250,18 +4599,23 @@  discard block
 block discarded – undo
4250 4599
         // VAT Rate
4251 4600
         $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4252 4601
         $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.')';
4602
+        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) {
4603
+            $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4604
+        }
4254 4605
 
4255 4606
 		$this->tpl['price'] = price($line->subprice);
4256 4607
 		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4257 4608
 		$this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4258
-		if (Globals::$conf->global->PRODUCT_USE_UNITS)
4259
-            $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4609
+		if (Globals::$conf->global->PRODUCT_USE_UNITS) {
4610
+		            $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4611
+		}
4260 4612
         $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4261 4613
 
4262 4614
 		// Is the line strike or not
4263 4615
 		$this->tpl['strike']=0;
4264
-		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4616
+		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
4617
+		    $this->tpl['strike']=1;
4618
+		}
4265 4619
 
4266 4620
 		// Output template part (modules that overwrite templates must declare this into descriptor)
4267 4621
 		// Use global variables + $dateSelector + $seller and $buyer
@@ -4274,7 +4628,9 @@  discard block
 block discarded – undo
4274 4628
 			} else {
4275 4629
 				$res=include $tpl; // for debug
4276 4630
 			}
4277
-			if ($res) break;
4631
+			if ($res) {
4632
+			    break;
4633
+			}
4278 4634
 		}
4279 4635
 	}
4280 4636
 
@@ -4316,8 +4672,7 @@  discard block
 block discarded – undo
4316 4672
 		{
4317 4673
 			$this->db->commit();
4318 4674
 			return 1;
4319
-		}
4320
-		else
4675
+		} else
4321 4676
 		{
4322 4677
 			$this->error=$this->db->lasterror();
4323 4678
 			$this->db->rollback();
@@ -4352,8 +4707,7 @@  discard block
 block discarded – undo
4352 4707
 			$this->error=$this->db->lasterror();
4353 4708
 			$this->db->rollback();
4354 4709
 			return -1;
4355
-		}
4356
-		else
4710
+		} else
4357 4711
 		{
4358 4712
 			if (! $notrigger)
4359 4713
 			{
@@ -4420,14 +4774,20 @@  discard block
 block discarded – undo
4420 4774
 		// Search template files
4421 4775
 		$file=''; $classname=''; $filefound=0;
4422 4776
 		$dirmodels=array('/');
4423
-		if (is_array(Globals::$conf->modules_parts['models']))
4424
-            $dirmodels = array_merge($dirmodels, Globals::$conf->modules_parts['models']);
4777
+		if (is_array(Globals::$conf->modules_parts['models'])) {
4778
+		            $dirmodels = array_merge($dirmodels, Globals::$conf->modules_parts['models']);
4779
+		}
4425 4780
         foreach($dirmodels as $reldir)
4426 4781
 		{
4427 4782
 			foreach(array('doc','pdf') as $prefix)
4428 4783
 			{
4429
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4430
-				else $file = $prefix."_".$modele.".modules.php";
4784
+				if (in_array(get_class($this), array('Adherent'))) {
4785
+				    $file = $prefix."_".$modele.".class.php";
4786
+				}
4787
+				// Member module use prefix_module.class.php
4788
+				else {
4789
+				    $file = $prefix."_".$modele.".modules.php";
4790
+				}
4431 4791
 
4432 4792
 				// On verifie l'emplacement du modele
4433 4793
 				$file=dol_buildpath($reldir.$modelspath.$file,0);
@@ -4438,7 +4798,9 @@  discard block
 block discarded – undo
4438 4798
 					break;
4439 4799
 				}
4440 4800
 			}
4441
-			if ($filefound) break;
4801
+			if ($filefound) {
4802
+			    break;
4803
+			}
4442 4804
 		}
4443 4805
 
4444 4806
 		// If generator was found
@@ -4469,7 +4831,9 @@  discard block
 block discarded – undo
4469 4831
 						if (is_dir($tmpdir))
4470 4832
 						{
4471 4833
 							$tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4472
-							if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4834
+							if (count($tmpfiles)) {
4835
+							    $listoffiles=array_merge($listoffiles,$tmpfiles);
4836
+							}
4473 4837
 						}
4474 4838
 					}
4475 4839
 
@@ -4507,8 +4871,7 @@  discard block
 block discarded – undo
4507 4871
 			{
4508 4872
 				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4509 4873
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4510
-			}
4511
-			else
4874
+			} else
4512 4875
 			{
4513 4876
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4514 4877
 			}
@@ -4530,9 +4893,11 @@  discard block
 block discarded – undo
4530 4893
 					$destfile = basename($destfull);
4531 4894
 					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4532 4895
 
4533
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4896
+					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
4897
+					    // If not a tmp dir
4534 4898
 					{
4535
-						$filename = basename($destfile);
4899
+						$filename = basename($destfile);
4900
+					}
4536 4901
 						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4537 4902
 						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4538 4903
 
@@ -4545,22 +4910,30 @@  discard block
 block discarded – undo
4545 4910
 						if ($this->element == 'propal')
4546 4911
 						{
4547 4912
 							$useonlinesignature = Globals::$conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
4548
-                            if ($useonlinesignature) $setsharekey=true;
4549
-							if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD))
4550
-                                $setsharekey = true;
4913
+                            if ($useonlinesignature) {
4914
+                                $setsharekey=true;
4915
+                            }
4916
+							if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
4917
+							                                $setsharekey = true;
4918
+							}
4551 4919
                         }
4552
-						if ($this->element == 'commande' && !empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))
4553
-                            $setsharekey = true;
4554
-                        if ($this->element == 'facture' && !empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))
4555
-                            $setsharekey = true;
4556
-                        if ($this->element == 'bank_account' && !empty(Globals::$conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD))
4557
-                            $setsharekey = true;
4920
+						if ($this->element == 'commande' && !empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
4921
+						                            $setsharekey = true;
4922
+						}
4923
+                        if ($this->element == 'facture' && !empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
4924
+                                                    $setsharekey = true;
4925
+                        }
4926
+                        if ($this->element == 'bank_account' && !empty(Globals::$conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
4927
+                                                    $setsharekey = true;
4928
+                        }
4558 4929
 
4559 4930
                         if ($setsharekey)
4560 4931
 						{
4561
-							if (empty($ecmfile->share))	// Because object not found or share not set yet
4932
+							if (empty($ecmfile->share)) {
4933
+							    // Because object not found or share not set yet
4562 4934
 							{
4563
-								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4935
+								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4936
+							}
4564 4937
 								$ecmfile->share = getRandomPassword(true);
4565 4938
 							}
4566 4939
 						}
@@ -4577,8 +4950,7 @@  discard block
 block discarded – undo
4577 4950
 							{
4578 4951
 								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4579 4952
 							}
4580
-						}
4581
-						else
4953
+						} else
4582 4954
 						{
4583 4955
 							$ecmfile->entity = Globals::$conf->entity;
4584 4956
                             $ecmfile->filepath = $rel_dir;
@@ -4605,17 +4977,20 @@  discard block
 block discarded – undo
4605 4977
 
4606 4978
 						// Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4607 4979
 						$update_main_doc_field=0;
4608
-						if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4980
+						if (! empty($obj->update_main_doc_field)) {
4981
+						    $update_main_doc_field=1;
4982
+						}
4609 4983
 						if ($update_main_doc_field && ! empty($this->table_element))
4610 4984
 						{
4611 4985
 							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4612 4986
 							$sql.= ' WHERE rowid = '.$this->id;
4613 4987
 							$resql = $this->db->query($sql);
4614
-							if (! $resql) dol_print_error($this->db);
4988
+							if (! $resql) {
4989
+							    dol_print_error($this->db);
4990
+							}
4615 4991
 						}
4616 4992
 					}
4617
-				}
4618
-				else
4993
+				} else
4619 4994
 				{
4620 4995
 					dol_syslog('Method ->write_file was called on object '.get_class($obj).' and return a success but the return array ->result["fullpath"] was not set.', LOG_WARNING);
4621 4996
 				}
@@ -4624,15 +4999,13 @@  discard block
 block discarded – undo
4624 4999
 				dol_meta_create($this);
4625 5000
 
4626 5001
 				return 1;
4627
-			}
4628
-			else
5002
+			} else
4629 5003
 			{
4630 5004
 				$outputlangs->charset_output=$sav_charset_output;
4631 5005
 				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4632 5006
 				return -1;
4633 5007
 			}
4634
-		}
4635
-		else
5008
+		} else
4636 5009
 		{
4637 5010
 			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4638 5011
 			dol_print_error('',$this->error);
@@ -4688,13 +5061,21 @@  discard block
 block discarded – undo
4688 5061
 		global $conf, $_POST;
4689 5062
 
4690 5063
 		// If param here has been posted, we use this value first.
4691
-		if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
5064
+		if (isset($_POST[$fieldname])) {
5065
+		    return GETPOST($fieldname, 2);
5066
+		}
4692 5067
 
4693
-		if (isset($alternatevalue)) return $alternatevalue;
5068
+		if (isset($alternatevalue)) {
5069
+		    return $alternatevalue;
5070
+		}
4694 5071
 
4695 5072
 		$newelement=$this->element;
4696
-		if ($newelement == 'facture') $newelement='invoice';
4697
-		if ($newelement == 'commande') $newelement='order';
5073
+		if ($newelement == 'facture') {
5074
+		    $newelement='invoice';
5075
+		}
5076
+		if ($newelement == 'commande') {
5077
+		    $newelement='order';
5078
+		}
4698 5079
 		if (empty($newelement))
4699 5080
 		{
4700 5081
 			dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
@@ -4703,8 +5084,9 @@  discard block
 block discarded – undo
4703 5084
 
4704 5085
 		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4705 5086
 		//var_dump($keyforfieldname);
4706
-		if (isset(Globals::$conf->global->$keyforfieldname))
4707
-            return Globals::$conf->global->$keyforfieldname;
5087
+		if (isset(Globals::$conf->global->$keyforfieldname)) {
5088
+		            return Globals::$conf->global->$keyforfieldname;
5089
+		}
4708 5090
 
4709 5091
         // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4710 5092
 	}
@@ -4738,8 +5120,7 @@  discard block
 block discarded – undo
4738 5120
 			if (!empty($this->errors))
4739 5121
 			{
4740 5122
 				$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
-			}
4742
-			else
5123
+			} else
4743 5124
 			{
4744 5125
 				$this->errors=$interface->errors;
4745 5126
 			}
@@ -4791,15 +5172,17 @@  discard block
 block discarded – undo
4791 5172
 				$extrafields->fetch_name_optionals_label($this->table_element);
4792 5173
 			}
4793 5174
 			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4794
-		}
4795
-		else
5175
+		} else
4796 5176
 		{
4797 5177
 			// global $extrafields;
4798 5178
             dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4799 5179
 		}
4800 5180
 
4801 5181
 		$table_element = $this->table_element;
4802
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5182
+		if ($table_element == 'categorie') {
5183
+		    $table_element = 'categories';
5184
+		}
5185
+		// For compatibility
4803 5186
 
4804 5187
 		// Request to get complementary values
4805 5188
 		if (is_array($optionsArray) && count($optionsArray) > 0)
@@ -4835,8 +5218,7 @@  discard block
 block discarded – undo
4835 5218
 							{
4836 5219
 								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4837 5220
 								$this->array_options["options_".$key]=$this->db->jdate($value);
4838
-							}
4839
-							else
5221
+							} else
4840 5222
 							{
4841 5223
 								$this->array_options["options_".$key]=$value;
4842 5224
 							}
@@ -4848,10 +5230,12 @@  discard block
 block discarded – undo
4848 5230
 
4849 5231
 				$this->db->free($resql);
4850 5232
 
4851
-				if ($numrows) return $numrows;
4852
-				else return 0;
4853
-			}
4854
-			else
5233
+				if ($numrows) {
5234
+				    return $numrows;
5235
+				} else {
5236
+				    return 0;
5237
+				}
5238
+			} else
4855 5239
 			{
4856 5240
 				dol_print_error($this->db);
4857 5241
 				return -1;
@@ -4870,7 +5254,10 @@  discard block
 block discarded – undo
4870 5254
 		$this->db->begin();
4871 5255
 
4872 5256
 		$table_element = $this->table_element;
4873
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5257
+		if ($table_element == 'categorie') {
5258
+		    $table_element = 'categories';
5259
+		}
5260
+		// For compatibility
4874 5261
 
4875 5262
 		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4876 5263
 		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
@@ -4880,8 +5267,7 @@  discard block
 block discarded – undo
4880 5267
 			$this->error=$this->db->lasterror();
4881 5268
 			$this->db->rollback();
4882 5269
 			return -1;
4883
-		}
4884
-		else
5270
+		} else
4885 5271
 		{
4886 5272
 			$this->db->commit();
4887 5273
 			return 1;
@@ -4902,12 +5288,16 @@  discard block
 block discarded – undo
4902 5288
 	{
4903 5289
 		global $conf,$langs,$user;
4904 5290
 
4905
-		if (empty($userused)) $userused=$user;
5291
+		if (empty($userused)) {
5292
+		    $userused=$user;
5293
+		}
4906 5294
 
4907 5295
 		$error=0;
4908 5296
 
4909
-		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
4910
-            return 0; // For avoid conflicts if trigger used
5297
+		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
5298
+		            return 0;
5299
+		}
5300
+		// For avoid conflicts if trigger used
4911 5301
 
4912 5302
         if (! empty($this->array_options))
4913 5303
 		{
@@ -4920,10 +5310,13 @@  discard block
 block discarded – undo
4920 5310
 			//Eliminate copied source object extra_fields that do not exist in target object
4921 5311
 			$new_array_options=array();
4922 5312
 			foreach ($this->array_options as $key => $value) {
4923
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4924
-					$new_array_options[$key] = $value;
4925
-				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4926
-					$new_array_options['options_'.$key] = $value;
5313
+				if (in_array(substr($key,8), array_keys($target_extrafields))) {
5314
+				    // We remove the 'options_' from $key for test
5315
+					$new_array_options[$key] = $value;
5316
+				} elseif (in_array($key, array_keys($target_extrafields))) {
5317
+				    // We test on $key that does not contains the 'options_' prefix
5318
+					$new_array_options['options_'.$key] = $value;
5319
+				}
4927 5320
 			}
4928 5321
 
4929 5322
 			foreach($new_array_options as $key => $value)
@@ -4937,8 +5330,12 @@  discard block
 block discarded – undo
4937 5330
 			   	if ($attributeRequired)
4938 5331
 			   	{
4939 5332
 			   		$mandatorypb=false;
4940
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4941
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
5333
+			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
5334
+			   		    $mandatorypb=true;
5335
+			   		}
5336
+			   		if ($this->array_options[$key] === '') {
5337
+			   		    $mandatorypb=true;
5338
+			   		}
4942 5339
 			   		if ($mandatorypb)
4943 5340
 			   		{
4944 5341
 			   			dol_syslog($this->error);
@@ -4957,8 +5354,7 @@  discard block
 block discarded – undo
4957 5354
 			   			{
4958 5355
 			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4959 5356
 			   				return -1;
4960
-			  			}
4961
-			   			elseif ($value=='')
5357
+			  			} elseif ($value=='')
4962 5358
 			   			{
4963 5359
 			   				$new_array_options[$key] = null;
4964 5360
 			   			}
@@ -4970,8 +5366,7 @@  discard block
 block discarded – undo
4970 5366
 							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4971 5367
 							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4972 5368
 							return -1;
4973
-						}
4974
-						elseif ($value=='')
5369
+						} elseif ($value=='')
4975 5370
 						{
4976 5371
 							$new_array_options[$key] = null;
4977 5372
 						}
@@ -4996,27 +5391,27 @@  discard block
 block discarded – undo
4996 5391
 			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
4997 5392
 			   					//var_dump($action);
4998 5393
 			   					//var_dump($this->oldcopy);exit;
4999
-			   					if (is_object($this->oldcopy))		// If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
5394
+			   					if (is_object($this->oldcopy)) {
5395
+			   					    // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
5000 5396
 			   					{
5001 5397
 			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
5002 5398
 				   					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.
5003 5399
 				   					{
5004
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5005
-				   					}
5006
-									else
5400
+				   						$new_array_options[$key] = $this->array_options[$key];
5401
+			   					}
5402
+			   					// Value is kept
5403
+				   					} else
5007 5404
 									{
5008 5405
 										// var_dump($algo);
5009 5406
 										$newvalue = dol_hash($this->array_options[$key], $algo);
5010 5407
 										$new_array_options[$key] = $newvalue;
5011 5408
 									}
5012
-			   					}
5013
-			   					else
5409
+			   					} else
5014 5410
 			   					{
5015 5411
 			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5016 5412
 			   					}
5017 5413
 			   				}
5018
-			   			}
5019
-			   			else	// Common usage
5414
+			   			} else	// Common usage
5020 5415
 			   			{
5021 5416
 			   				$new_array_options[$key] = $this->array_options[$key];
5022 5417
 			   			}
@@ -5042,26 +5437,30 @@  discard block
 block discarded – undo
5042 5437
 						dol_include_once($InfoFieldList[1]);
5043 5438
 						if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5044 5439
 						{
5045
-							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5440
+							if ($value == '-1') {
5441
+							    // -1 is key for no defined in combo list of objects
5046 5442
 							{
5047
-								$new_array_options[$key]='';
5048
-							}
5049
-							elseif ($value)
5443
+								$new_array_options[$key]='';
5444
+							}
5445
+							} elseif ($value)
5050 5446
 							{
5051 5447
 								$object = new $InfoFieldList[0]($this->db);
5052
-								if (is_numeric($value)) $res=$object->fetch($value);
5053
-								else $res=$object->fetch('',$value);
5054
-
5055
-								if ($res > 0) $new_array_options[$key]=$object->id;
5056
-								else
5448
+								if (is_numeric($value)) {
5449
+								    $res=$object->fetch($value);
5450
+								} else {
5451
+								    $res=$object->fetch('',$value);
5452
+								}
5453
+
5454
+								if ($res > 0) {
5455
+								    $new_array_options[$key]=$object->id;
5456
+								} else
5057 5457
 								{
5058 5458
 									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5059 5459
 									$this->db->rollback();
5060 5460
 									return -1;
5061 5461
 								}
5062 5462
 							}
5063
-						}
5064
-						else
5463
+						} else
5065 5464
 						{
5066 5465
 							dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5067 5466
 						}
@@ -5072,7 +5471,10 @@  discard block
 block discarded – undo
5072 5471
 			$this->db->begin();
5073 5472
 
5074 5473
 			$table_element = $this->table_element;
5075
-			if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5474
+			if ($table_element == 'categorie') {
5475
+			    $table_element = 'categories';
5476
+			}
5477
+			// For compatibility
5076 5478
 
5077 5479
 			$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5078 5480
 			dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
@@ -5083,8 +5485,10 @@  discard block
 block discarded – undo
5083 5485
 			{
5084 5486
 				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5085 5487
 				// Add field of attribut
5086
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5087
-					$sql.=",".$attributeKey;
5488
+				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') {
5489
+				    // Only for other type than separator
5490
+					$sql.=",".$attributeKey;
5491
+				}
5088 5492
 			}
5089 5493
 			$sql .= ") VALUES (".$this->id;
5090 5494
 
@@ -5092,13 +5496,14 @@  discard block
 block discarded – undo
5092 5496
 			{
5093 5497
 				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5094 5498
 				// Add field of attribute
5095
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5499
+				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') {
5500
+				    // Only for other type than separator)
5096 5501
 				{
5097 5502
 					if ($new_array_options[$key] != '')
5098 5503
 					{
5099
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5100
-					}
5101
-					else
5504
+						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5505
+				}
5506
+					} else
5102 5507
 					{
5103 5508
 						$sql.=",null";
5104 5509
 					}
@@ -5119,7 +5524,9 @@  discard block
 block discarded – undo
5119 5524
 				// Call trigger
5120 5525
 				$this->context=array('extrafieldaddupdate'=>1);
5121 5526
 				$result=$this->call_trigger($trigger, $userused);
5122
-				if ($result < 0) $error++;
5527
+				if ($result < 0) {
5528
+				    $error++;
5529
+				}
5123 5530
 				// End call trigger
5124 5531
 			}
5125 5532
 
@@ -5127,14 +5534,14 @@  discard block
 block discarded – undo
5127 5534
 			{
5128 5535
 				$this->db->rollback();
5129 5536
 				return -1;
5130
-			}
5131
-			else
5537
+			} else
5132 5538
 			{
5133 5539
 				$this->db->commit();
5134 5540
 				return 1;
5135 5541
 			}
5136
-		}
5137
-		else return 0;
5542
+		} else {
5543
+		    return 0;
5544
+		}
5138 5545
 	}
5139 5546
 
5140 5547
 	/**
@@ -5151,12 +5558,16 @@  discard block
 block discarded – undo
5151 5558
 	{
5152 5559
 		global $conf,$langs,$user;
5153 5560
 
5154
-		if (empty($userused)) $userused=$user;
5561
+		if (empty($userused)) {
5562
+		    $userused=$user;
5563
+		}
5155 5564
 
5156 5565
 		$error=0;
5157 5566
 
5158
-		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED))
5159
-            return 0; // For avoid conflicts if trigger used
5567
+		if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
5568
+		            return 0;
5569
+		}
5570
+		// For avoid conflicts if trigger used
5160 5571
 
5161 5572
         if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5162 5573
 		{
@@ -5183,8 +5594,7 @@  discard block
 block discarded – undo
5183 5594
 					{
5184 5595
 						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5185 5596
 						return -1;
5186
-					}
5187
-					elseif ($value=='')
5597
+					} elseif ($value=='')
5188 5598
 					{
5189 5599
 						$this->array_options["options_".$key] = null;
5190 5600
 					}
@@ -5196,8 +5606,7 @@  discard block
 block discarded – undo
5196 5606
 						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5197 5607
 						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5198 5608
 						return -1;
5199
-					}
5200
-					elseif ($value=='')
5609
+					} elseif ($value=='')
5201 5610
 					{
5202 5611
 						$this->array_options["options_".$key] = null;
5203 5612
 					}
@@ -5249,7 +5658,9 @@  discard block
 block discarded – undo
5249 5658
 				// Call trigger
5250 5659
 				$this->context=array('extrafieldupdate'=>1);
5251 5660
 				$result=$this->call_trigger($trigger, $userused);
5252
-				if ($result < 0) $error++;
5661
+				if ($result < 0) {
5662
+				    $error++;
5663
+				}
5253 5664
 				// End call trigger
5254 5665
 			}
5255 5666
 
@@ -5258,14 +5669,14 @@  discard block
 block discarded – undo
5258 5669
 				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5259 5670
 				$this->db->rollback();
5260 5671
 				return -1;
5261
-			}
5262
-			else
5672
+			} else
5263 5673
 			{
5264 5674
 				$this->db->commit();
5265 5675
 				return 1;
5266 5676
 			}
5267
-		}
5268
-		else return 0;
5677
+		} else {
5678
+		    return 0;
5679
+		}
5269 5680
 	}
5270 5681
 
5271 5682
 
@@ -5340,8 +5751,11 @@  discard block
 block discarded – undo
5340 5751
 
5341 5752
 		if ($computed)
5342 5753
 		{
5343
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5344
-			else return '';
5754
+			if (! preg_match('/^search_/', $keyprefix)) {
5755
+			    return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5756
+			} else {
5757
+			    return '';
5758
+			}
5345 5759
 		}
5346 5760
 
5347 5761
 
@@ -5355,33 +5769,27 @@  discard block
 block discarded – undo
5355 5769
 			if ($type == 'date')
5356 5770
 			{
5357 5771
 				$morecss = 'minwidth100imp';
5358
-			}
5359
-			elseif ($type == 'datetime')
5772
+			} elseif ($type == 'datetime')
5360 5773
 			{
5361 5774
 				$morecss = 'minwidth200imp';
5362
-			}
5363
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5775
+			} elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5364 5776
 			{
5365 5777
 				$morecss = 'maxwidth75';
5366
-                        }elseif ($type == 'url')
5778
+                        } elseif ($type == 'url')
5367 5779
 			{
5368 5780
 				$morecss='minwidth400';
5369
-			}
5370
-			elseif ($type == 'boolean')
5781
+			} elseif ($type == 'boolean')
5371 5782
 			{
5372 5783
 				$morecss='';
5373
-			}
5374
-			else
5784
+			} else
5375 5785
 			{
5376 5786
 				if (round($size) < 12)
5377 5787
 				{
5378 5788
 					$morecss = 'minwidth100';
5379
-				}
5380
-				else if (round($size) <= 48)
5789
+				} else if (round($size) <= 48)
5381 5790
 				{
5382 5791
 					$morecss = 'minwidth200';
5383
-				}
5384
-				else
5792
+				} else
5385 5793
 				{
5386 5794
 					$morecss = 'minwidth400';
5387 5795
 				}
@@ -5396,52 +5804,50 @@  discard block
 block discarded – undo
5396 5804
 			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5397 5805
 
5398 5806
 			// Do not show current date when field not required (see selectDate() method)
5399
-			if (!$required && $value == '') $value = '-1';
5807
+			if (!$required && $value == '') {
5808
+			    $value = '-1';
5809
+			}
5400 5810
 
5401 5811
 			// TODO Must also support $moreparam
5402 5812
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5403
-		}
5404
-		elseif (in_array($type,array('int','integer')))
5813
+		} elseif (in_array($type,array('int','integer')))
5405 5814
 		{
5406 5815
 			$tmp=explode(',',$size);
5407 5816
 			$newsize=$tmp[0];
5408 5817
 			$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:'').'>';
5409
-		}
5410
-		elseif (preg_match('/varchar/', $type))
5818
+		} elseif (preg_match('/varchar/', $type))
5411 5819
 		{
5412 5820
 			$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:'').'>';
5413
-		}
5414
-		elseif (in_array($type, array('mail', 'phone', 'url')))
5821
+		} elseif (in_array($type, array('mail', 'phone', 'url')))
5415 5822
 		{
5416 5823
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5417
-		}
5418
-		elseif ($type == 'text')
5824
+		} elseif ($type == 'text')
5419 5825
 		{
5420
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5826
+			if (! preg_match('/search_/', $keyprefix)) {
5827
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
5421 5828
 			{
5422
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5829
+				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5830
+			}
5423 5831
 				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5424 5832
 				$out=$doleditor->Create(1);
5425
-			}
5426
-			else
5833
+			} else
5427 5834
 			{
5428 5835
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5429 5836
 			}
5430
-		}
5431
-		elseif ($type == 'html')
5837
+		} elseif ($type == 'html')
5432 5838
 		{
5433
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5839
+			if (! preg_match('/search_/', $keyprefix)) {
5840
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
5434 5841
 			{
5435
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5842
+				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5843
+			}
5436 5844
 				$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%');
5437 5845
                 $out=$doleditor->Create(1);
5438
-			}
5439
-			else
5846
+			} else
5440 5847
 			{
5441 5848
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5442 5849
 			}
5443
-		}
5444
-		elseif ($type == 'boolean')
5850
+		} elseif ($type == 'boolean')
5445 5851
 		{
5446 5852
 			$checked='';
5447 5853
 			if (!empty($value)) {
@@ -5450,22 +5856,19 @@  discard block
 block discarded – undo
5450 5856
 				$checked=' value="1" ';
5451 5857
 			}
5452 5858
 			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5453
-		}
5454
-		elseif ($type == 'price')
5859
+		} elseif ($type == 'price')
5455 5860
 		{
5456 5861
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5457 5862
 				$value=price($value);
5458 5863
 			}
5459 5864
 			$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);
5460
-        }
5461
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5865
+        } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5462 5866
 		{
5463 5867
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5464 5868
 				$value=price($value);
5465 5869
 			}
5466 5870
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5467
-		}
5468
-		elseif ($type == 'select')
5871
+		} elseif ($type == 'select')
5469 5872
 		{
5470 5873
 			$out = '';
5471 5874
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
@@ -5474,10 +5877,14 @@  discard block
 block discarded – undo
5474 5877
 			}
5475 5878
 
5476 5879
 			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5477
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5880
+                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1)) {
5881
+                    $out.='<option value="0">&nbsp;</option>';
5882
+                }
5478 5883
 			foreach ($param['options'] as $key => $val)
5479 5884
 			{
5480
-				if ((string) $key == '') continue;
5885
+				if ((string) $key == '') {
5886
+				    continue;
5887
+				}
5481 5888
 				list($val, $parent) = explode('|', $val);
5482 5889
 				$out.='<option value="'.$key.'"';
5483 5890
 				$out.= (((string) $value == (string) $key)?' selected':'');
@@ -5485,8 +5892,7 @@  discard block
 block discarded – undo
5485 5892
 				$out.='>'.$val.'</option>';
5486 5893
 			}
5487 5894
 			$out.='</select>';
5488
-		}
5489
-		elseif ($type == 'sellist')
5895
+		} elseif ($type == 'sellist')
5490 5896
 		{
5491 5897
 			$out = '';
5492 5898
 			if (!empty(Globals::$conf->use_javascript_ajax) && !empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_SELECT2)) {
@@ -5552,13 +5958,11 @@  discard block
 block discarded – undo
5552 5958
 					{
5553 5959
 						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5554 5960
 						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5555
-					}
5556
-					else
5961
+					} else
5557 5962
 					{
5558 5963
 						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5559 5964
 					}
5560
-				}
5561
-				else
5965
+				} else
5562 5966
 				{
5563 5967
 					$sqlwhere.= ' WHERE 1=1';
5564 5968
 				}
@@ -5594,8 +5998,7 @@  discard block
 block discarded – undo
5594 5998
 							{
5595 5999
 								$labeltoshow.= $obj->$field_toshow.' ';
5596 6000
 							}
5597
-						}
5598
-						else
6001
+						} else
5599 6002
 						{
5600 6003
 							$labeltoshow=$obj->{$InfoFieldList[1]};
5601 6004
 						}
@@ -5608,25 +6011,25 @@  discard block
 block discarded – undo
5608 6011
 								$translabel=$langs->trans($obj->$field_toshow);
5609 6012
 								if ($translabel!=$obj->$field_toshow) {
5610 6013
 									$labeltoshow=dol_trunc($translabel,18).' ';
5611
-								}else {
6014
+								} else {
5612 6015
 									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5613 6016
 								}
5614 6017
 							}
5615 6018
 							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5616
-						}
5617
-						else
6019
+						} else
5618 6020
 						{
5619 6021
 							if (! $notrans)
5620 6022
 							{
5621 6023
 								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5622 6024
 								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5623 6025
 									$labeltoshow=dol_trunc($translabel,18);
5624
-								}
5625
-								else {
6026
+								} else {
5626 6027
 									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5627 6028
 								}
5628 6029
 							}
5629
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
6030
+							if (empty($labeltoshow)) {
6031
+							    $labeltoshow='(not defined)';
6032
+							}
5630 6033
 							if ($value==$obj->rowid)
5631 6034
 							{
5632 6035
 								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
@@ -5646,19 +6049,16 @@  discard block
 block discarded – undo
5646 6049
 						$i++;
5647 6050
 					}
5648 6051
 					$this->db->free($resql);
5649
-				}
5650
-				else {
6052
+				} else {
5651 6053
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5652 6054
 				}
5653 6055
 			}
5654 6056
 			$out.='</select>';
5655
-		}
5656
-		elseif ($type == 'checkbox')
6057
+		} elseif ($type == 'checkbox')
5657 6058
 		{
5658 6059
 			$value_arr=explode(',',$value);
5659 6060
 			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5660
-		}
5661
-		elseif ($type == 'radio')
6061
+		} elseif ($type == 'radio')
5662 6062
 		{
5663 6063
 			$out='';
5664 6064
 			foreach ($param['options'] as $keyopt => $val)
@@ -5669,13 +6069,11 @@  discard block
 block discarded – undo
5669 6069
 				$out.= ($value==$keyopt?'checked':'');
5670 6070
 				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5671 6071
 			}
5672
-		}
5673
-		elseif ($type == 'chkbxlst')
6072
+		} elseif ($type == 'chkbxlst')
5674 6073
 		{
5675 6074
 			if (is_array($value)) {
5676 6075
 				$value_arr = $value;
5677
-			}
5678
-			else {
6076
+			} else {
5679 6077
 				$value_arr = explode(',', $value);
5680 6078
 			}
5681 6079
 
@@ -5790,8 +6188,9 @@  discard block
 block discarded – undo
5790 6188
 									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5791 6189
 								}
5792 6190
 							}
5793
-							if (empty($labeltoshow))
5794
-								$labeltoshow = '(not defined)';
6191
+							if (empty($labeltoshow)) {
6192
+															$labeltoshow = '(not defined)';
6193
+							}
5795 6194
 
5796 6195
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5797 6196
 									$data[$obj->rowid]=$labeltoshow;
@@ -5813,26 +6212,26 @@  discard block
 block discarded – undo
5813 6212
 					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5814 6213
 				}
5815 6214
 			}
5816
-		}
5817
-		elseif ($type == 'link')
6215
+		} elseif ($type == 'link')
5818 6216
 		{
5819 6217
 			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5820 6218
 			$showempty=(($required && $default != '')?0:1);
5821 6219
 			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5822 6220
 			if (Globals::$conf->global->MAIN_FEATURES_LEVEL >= 2) {
5823 6221
             			list($class,$classfile)=explode(':',$param_list[0]);
5824
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5825
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
6222
+            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
6223
+            			    $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
6224
+            			} else {
6225
+            			    $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
6226
+            			}
5826 6227
             			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5827 6228
             			// TODO Add Javascript code to add input fields contents to new elements urls
5828 6229
 			}
5829
-		}
5830
-		elseif ($type == 'password')
6230
+		} elseif ($type == 'password')
5831 6231
 		{
5832 6232
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
5833 6233
 			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5834
-		}
5835
-		elseif ($type == 'array')
6234
+		} elseif ($type == 'array')
5836 6235
 		{
5837 6236
 			$newval = $val;
5838 6237
 			$newval['type'] = 'varchar(256)';
@@ -5910,17 +6309,25 @@  discard block
 block discarded – undo
5910 6309
 		{
5911 6310
 			$type = 'varchar';		// convert varchar(xx) int varchar
5912 6311
 			$size = $reg[1];
5913
-		}
5914
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5915
-		if (is_array($val['arrayofkeyval'])) $type='select';
5916
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
6312
+		} elseif (preg_match('/varchar/', $type)) {
6313
+		    $type = 'varchar';
6314
+		}
6315
+		// convert varchar(xx) int varchar
6316
+		if (is_array($val['arrayofkeyval'])) {
6317
+		    $type='select';
6318
+		}
6319
+		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
6320
+		    $type='link';
6321
+		}
5917 6322
 
5918 6323
 		$default=$val['default'];
5919 6324
 		$computed=$val['computed'];
5920 6325
 		$unique=$val['unique'];
5921 6326
 		$required=$val['required'];
5922 6327
 		$param=$val['param'];
5923
-		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
6328
+		if (is_array($val['arrayofkeyval'])) {
6329
+		    $param['options'] = $val['arrayofkeyval'];
6330
+		}
5924 6331
 		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5925 6332
 		{
5926 6333
 			$type='link';
@@ -5931,7 +6338,9 @@  discard block
 block discarded – undo
5931 6338
 		$help=$val['help'];
5932 6339
 		$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)
5933 6340
 
5934
-		if ($hidden) return '';
6341
+		if ($hidden) {
6342
+		    return '';
6343
+		}
5935 6344
 
5936 6345
 		// If field is a computed field, value must become result of compute
5937 6346
 		if ($computed)
@@ -5947,36 +6356,29 @@  discard block
 block discarded – undo
5947 6356
 			{
5948 6357
 				//$showsize=10;
5949 6358
 				$showsize = 'minwidth100imp';
5950
-			}
5951
-			elseif ($type == 'datetime')
6359
+			} elseif ($type == 'datetime')
5952 6360
 			{
5953 6361
 				//$showsize=19;
5954 6362
 				$showsize = 'minwidth200imp';
5955
-			}
5956
-			elseif (in_array($type,array('int','double','price')))
6363
+			} elseif (in_array($type,array('int','double','price')))
5957 6364
 			{
5958 6365
 				//$showsize=10;
5959 6366
 				$showsize = 'maxwidth75';
5960
-			}
5961
-			elseif ($type == 'url')
6367
+			} elseif ($type == 'url')
5962 6368
 			{
5963 6369
 				$showsize='minwidth400';
5964
-			}
5965
-			elseif ($type == 'boolean')
6370
+			} elseif ($type == 'boolean')
5966 6371
 			{
5967 6372
 				$showsize='';
5968
-			}
5969
-			else
6373
+			} else
5970 6374
 			{
5971 6375
 				if (round($size) < 12)
5972 6376
 				{
5973 6377
 					$showsize = 'minwidth100';
5974
-				}
5975
-				else if (round($size) <= 48)
6378
+				} else if (round($size) <= 48)
5976 6379
 				{
5977 6380
 					$showsize = 'minwidth200';
5978
-				}
5979
-				else
6381
+				} else
5980 6382
 				{
5981 6383
 					//$showsize=48;
5982 6384
 					$showsize = 'minwidth400';
@@ -5985,59 +6387,52 @@  discard block
 block discarded – undo
5985 6387
 		}
5986 6388
 
5987 6389
 		// Format output value differently according to properties of field
5988
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5989
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5990
-		elseif ($type == 'date')
6390
+		if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
6391
+		    $value=$this->getNomUrl(1, '', 0, '', 1);
6392
+		} elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
6393
+		    $value=$this->getLibStatut(3);
6394
+		} elseif ($type == 'date')
5991 6395
 		{
5992 6396
 			if(! empty($value)) {
5993 6397
 				$value=dol_print_date($value,'day');
5994 6398
 			} else {
5995 6399
 				$value='';
5996 6400
 			}
5997
-		}
5998
-		elseif ($type == 'datetime')
6401
+		} elseif ($type == 'datetime')
5999 6402
 		{
6000 6403
 			if(! empty($value)) {
6001 6404
 				$value=dol_print_date($value,'dayhour');
6002 6405
 			} else {
6003 6406
 				$value='';
6004 6407
 			}
6005
-		}
6006
-		elseif ($type == 'double')
6408
+		} elseif ($type == 'double')
6007 6409
 		{
6008 6410
 			if (!empty($value)) {
6009 6411
 				$value=price($value);
6010 6412
 			}
6011
-		}
6012
-		elseif ($type == 'boolean')
6413
+		} elseif ($type == 'boolean')
6013 6414
 		{
6014 6415
 			$checked='';
6015 6416
 			if (!empty($value)) {
6016 6417
 				$checked=' checked ';
6017 6418
 			}
6018 6419
 			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6019
-		}
6020
-		elseif ($type == 'mail')
6420
+		} elseif ($type == 'mail')
6021 6421
 		{
6022 6422
 			$value=dol_print_email($value,0,0,0,64,1,1);
6023
-		}
6024
-		elseif ($type == 'url')
6423
+		} elseif ($type == 'url')
6025 6424
 		{
6026 6425
 			$value=dol_print_url($value,'_blank',32,1);
6027
-		}
6028
-		elseif ($type == 'phone')
6426
+		} elseif ($type == 'phone')
6029 6427
 		{
6030 6428
 			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6031
-		}
6032
-		elseif ($type == 'price')
6429
+		} elseif ($type == 'price')
6033 6430
 		{
6034 6431
 			$value = price($value, 0, $langs, 0, 0, -1, Globals::$conf->currency);
6035
-        }
6036
-		elseif ($type == 'select')
6432
+        } elseif ($type == 'select')
6037 6433
 		{
6038 6434
 			$value=$param['options'][$value];
6039
-		}
6040
-		elseif ($type == 'sellist')
6435
+		} elseif ($type == 'sellist')
6041 6436
 		{
6042 6437
 			$param_list=array_keys($param['options']);
6043 6438
 			$InfoFieldList = explode(":", $param_list[0]);
@@ -6067,7 +6462,7 @@  discard block
 block discarded – undo
6067 6462
 				$sql.= " WHERE ".$selectkey."=0";
6068 6463
 			} elseif ($selectkey=='rowid') {
6069 6464
 				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6070
-			}else {
6465
+			} else {
6071 6466
 				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6072 6467
 			}
6073 6468
 
@@ -6094,12 +6489,11 @@  discard block
 block discarded – undo
6094 6489
 						}
6095 6490
 						if ($translabel!=$field_toshow) {
6096 6491
 							$value.=dol_trunc($translabel,18).' ';
6097
-						}else {
6492
+						} else {
6098 6493
 							$value.=$obj->$field_toshow.' ';
6099 6494
 						}
6100 6495
 					}
6101
-				}
6102
-				else
6496
+				} else
6103 6497
 				{
6104 6498
 					$translabel='';
6105 6499
 					if (!empty($obj->{$InfoFieldList[1]})) {
@@ -6107,18 +6501,17 @@  discard block
 block discarded – undo
6107 6501
 					}
6108 6502
 					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6109 6503
 						$value=dol_trunc($translabel,18);
6110
-					}else {
6504
+					} else {
6111 6505
 						$value=$obj->{$InfoFieldList[1]};
6112 6506
 					}
6113 6507
 				}
6114
-			}
6115
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6116
-		}
6117
-		elseif ($type == 'radio')
6508
+			} else {
6509
+			    dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6510
+			}
6511
+		} elseif ($type == 'radio')
6118 6512
 		{
6119 6513
 			$value=$param['options'][$value];
6120
-		}
6121
-		elseif ($type == 'checkbox')
6514
+		} elseif ($type == 'checkbox')
6122 6515
 		{
6123 6516
 			$value_arr=explode(',',$value);
6124 6517
 			$value='';
@@ -6129,8 +6522,7 @@  discard block
 block discarded – undo
6129 6522
 				}
6130 6523
 				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6131 6524
 			}
6132
-		}
6133
-		elseif ($type == 'chkbxlst')
6525
+		} elseif ($type == 'chkbxlst')
6134 6526
 		{
6135 6527
 			$value_arr = explode(',', $value);
6136 6528
 
@@ -6198,8 +6590,7 @@  discard block
 block discarded – undo
6198 6590
 			} else {
6199 6591
 				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6200 6592
 			}
6201
-		}
6202
-		elseif ($type == 'link')
6593
+		} elseif ($type == 'link')
6203 6594
 		{
6204 6595
 			$out='';
6205 6596
 
@@ -6221,24 +6612,21 @@  discard block
 block discarded – undo
6221 6612
 						$object->fetch($value);
6222 6613
 						$value=$object->getNomUrl($getnomurlparam);
6223 6614
 					}
6224
-				}
6225
-				else
6615
+				} else
6226 6616
 				{
6227 6617
 					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6228 6618
 					return 'Error bad setup of extrafield';
6229 6619
 				}
6230
-			}
6231
-			else $value='';
6232
-		}
6233
-		elseif ($type == 'text' || $type == 'html')
6620
+			} else {
6621
+			    $value='';
6622
+			}
6623
+		} elseif ($type == 'text' || $type == 'html')
6234 6624
 		{
6235 6625
 			$value=dol_htmlentitiesbr($value);
6236
-		}
6237
-		elseif ($type == 'password')
6626
+		} elseif ($type == 'password')
6238 6627
 		{
6239 6628
 			$value=preg_replace('/./i','*',$value);
6240
-		}
6241
-		elseif ($type == 'array')
6629
+		} elseif ($type == 'array')
6242 6630
 		{
6243 6631
 			$value = implode('<br>', $value);
6244 6632
 		}
@@ -6265,7 +6653,9 @@  discard block
 block discarded – undo
6265 6653
 	{
6266 6654
 		global $db, $conf, $langs, $action, $form;
6267 6655
 
6268
-		if (! is_object($form)) $form=new Form($db);
6656
+		if (! is_object($form)) {
6657
+		    $form=new Form($db);
6658
+		}
6269 6659
 
6270 6660
 		$out = '';
6271 6661
 
@@ -6279,7 +6669,9 @@  discard block
 block discarded – undo
6279 6669
 			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6280 6670
 			{
6281 6671
 				// Show only the key field in params
6282
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6672
+				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) {
6673
+				    continue;
6674
+				}
6283 6675
 
6284 6676
 				$enabled = 1;
6285 6677
 				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
@@ -6293,11 +6685,18 @@  discard block
 block discarded – undo
6293 6685
 					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6294 6686
 				}
6295 6687
 
6296
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6297
-				if (empty($perms)) continue;
6688
+				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) {
6689
+				    continue;
6690
+				}
6691
+				// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6692
+				if (empty($perms)) {
6693
+				    continue;
6694
+				}
6298 6695
 
6299 6696
 				// Load language if required
6300
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6697
+				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
6698
+				    $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6699
+				}
6301 6700
 
6302 6701
 				$colspan='3';
6303 6702
 				if (is_array($params) && count($params)>0) {
@@ -6331,8 +6730,7 @@  discard block
 block discarded – undo
6331 6730
 				if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6332 6731
 				{
6333 6732
 					$out .= $extrafields->showSeparator($key, $this);
6334
-				}
6335
-				else
6733
+				} else
6336 6734
 				{
6337 6735
 					$csstyle='';
6338 6736
 					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
@@ -6363,9 +6761,11 @@  discard block
 block discarded – undo
6363 6761
 					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6364 6762
 					{
6365 6763
 						$datenotinstring = $this->array_options['options_' . $key];
6366
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6764
+						if (! is_numeric($this->array_options['options_' . $key])) {
6765
+						    // For backward compatibility
6367 6766
 						{
6368
-							$datenotinstring = $this->db->jdate($datenotinstring);
6767
+							$datenotinstring = $this->db->jdate($datenotinstring);
6768
+						}
6369 6769
 						}
6370 6770
 						$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;
6371 6771
 					}
@@ -6378,11 +6778,18 @@  discard block
 block discarded – undo
6378 6778
 					$labeltoshow = $langs->trans($label);
6379 6779
 
6380 6780
 					$out .= '<td class="titlefield';
6381
-					if (GETPOST('action','none') == 'create') $out.='create';
6382
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6781
+					if (GETPOST('action','none') == 'create') {
6782
+					    $out.='create';
6783
+					}
6784
+					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) {
6785
+					    $out .= ' fieldrequired';
6786
+					}
6383 6787
 					$out .= '">';
6384
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6385
-					else $out .= $labeltoshow;
6788
+					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) {
6789
+					    $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6790
+					} else {
6791
+					    $out .= $labeltoshow;
6792
+					}
6386 6793
 					$out .= '</td>';
6387 6794
 
6388 6795
 					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
@@ -6399,9 +6806,11 @@  discard block
 block discarded – undo
6399 6806
 
6400 6807
 					$out .= '</td>';
6401 6808
 
6402
-					if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1))
6403
-                        $out .= '</tr>';
6404
-                    else $out .= '</tr>';
6809
+					if (!empty(Globals::$conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
6810
+					                        $out .= '</tr>';
6811
+					} else {
6812
+                        $out .= '</tr>';
6813
+                    }
6405 6814
 					$e++;
6406 6815
 				}
6407 6816
 			}
@@ -6453,7 +6862,9 @@  discard block
 block discarded – undo
6453 6862
 		global $user;
6454 6863
 
6455 6864
 		$element = $this->element;
6456
-		if ($element == 'facturerec') $element='facture';
6865
+		if ($element == 'facturerec') {
6866
+		    $element='facture';
6867
+		}
6457 6868
 
6458 6869
 		return $user->rights->{$element};
6459 6870
 	}
@@ -6478,7 +6889,10 @@  discard block
 block discarded – undo
6478 6889
 
6479 6890
 			if (! $db->query($sql))
6480 6891
 			{
6481
-				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.
6892
+				if ($ignoreerrors) {
6893
+				    return true;
6894
+				}
6895
+				// 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.
6482 6896
 				//$this->errors = $db->lasterror();
6483 6897
 				return false;
6484 6898
 			}
@@ -6507,8 +6921,7 @@  discard block
 block discarded – undo
6507 6921
 
6508 6922
 		if (($unitPrice > 0) && (isset(Globals::$conf->global->ForceBuyingPriceIfNull) && Globals::$conf->global->ForceBuyingPriceIfNull == 1)) { // In most cases, test here is false{
6509 6923
 			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
6510
-		}
6511
-		else
6924
+		} else
6512 6925
 		{
6513 6926
 			// Get cost price for margin calculation
6514 6927
 			if (! empty($fk_product))
@@ -6525,13 +6938,11 @@  discard block
 block discarded – undo
6525 6938
 					if ($product->cost_price > 0)
6526 6939
 					{
6527 6940
 						$buyPrice = $product->cost_price;
6528
-					}
6529
-					else if ($product->pmp > 0)
6941
+					} else if ($product->pmp > 0)
6530 6942
 					{
6531 6943
 						$buyPrice = $product->pmp;
6532 6944
 					}
6533
-				}
6534
-				else if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'pmp') {
6945
+				} else if (isset(Globals::$conf->global->MARGIN_TYPE) && Globals::$conf->global->MARGIN_TYPE == 'pmp') {
6535 6946
 					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6536 6947
 					$product = new Product($this->db);
6537 6948
 					$result = $product->fetch($fk_product);
@@ -6552,8 +6963,7 @@  discard block
 block discarded – undo
6552 6963
 					if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6553 6964
 					{
6554 6965
 						$buyPrice = $productFournisseur->fourn_unitprice;
6555
-					}
6556
-					else if ($result < 0)
6966
+					} else if ($result < 0)
6557 6967
 					{
6558 6968
 						$this->errors[] = $productFournisseur->error;
6559 6969
 						return -2;
@@ -6599,8 +7009,7 @@  discard block
 block discarded – undo
6599 7009
 		{
6600 7010
 			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6601 7011
 			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6602
-		}
6603
-		else
7012
+		} else
6604 7013
 		{
6605 7014
 			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6606 7015
 			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
@@ -6662,19 +7071,26 @@  discard block
 block discarded – undo
6662 7071
 
6663 7072
 						// Find name of thumb file
6664 7073
 						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6665
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
7074
+						if (! dol_is_file($dirthumb.$photo_vignette)) {
7075
+						    $photo_vignette='';
7076
+						}
6666 7077
 
6667 7078
 						// Get filesize of original file
6668 7079
 						$imgarray=dol_getImageSize($dir.$photo);
6669 7080
 
6670 7081
 						if ($nbbyrow > 0)
6671 7082
 						{
6672
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7083
+							if ($nbphoto == 1) {
7084
+							    $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7085
+							}
6673 7086
 
6674
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
7087
+							if ($nbphoto % $nbbyrow == 1) {
7088
+							    $return.= '<tr align=center valign=middle border=1>';
7089
+							}
6675 7090
 							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6676
-						}
6677
-						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
7091
+						} else if ($nbbyrow < 0) {
7092
+						    $return .= '<div class="inline-block">';
7093
+						}
6678 7094
 
6679 7095
 						$return.= "\n";
6680 7096
 
@@ -6682,15 +7098,20 @@  discard block
 block discarded – undo
6682 7098
 						if (empty($nolink))
6683 7099
 						{
6684 7100
 							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6685
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6686
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
7101
+							if ($urladvanced) {
7102
+							    $return.='<a href="'.$urladvanced.'">';
7103
+							} else {
7104
+							    $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
7105
+							}
6687 7106
 						}
6688 7107
 
6689 7108
 						// Show image (width height=$maxHeight)
6690 7109
 						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6691 7110
 						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6692 7111
 						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6693
-						if ($notitle) $alt='';
7112
+						if ($notitle) {
7113
+						    $alt='';
7114
+						}
6694 7115
 
6695 7116
 						if ($usesharelink)
6696 7117
 						{
@@ -6700,35 +7121,35 @@  discard block
 block discarded – undo
6700 7121
 								{
6701 7122
 									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6702 7123
 									$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
-								}
6704
-								else {
7124
+								} else {
6705 7125
 									$return.= '<!-- Show original file -->';
6706 7126
 									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6707 7127
 								}
6708
-							}
6709
-							else
7128
+							} else
6710 7129
 							{
6711 7130
 								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6712 7131
 								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6713 7132
 							}
6714
-						}
6715
-						else
7133
+						} else
6716 7134
 						{
6717 7135
 							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6718 7136
 							{
6719 7137
 								$return.= '<!-- Show thumb -->';
6720 7138
 								$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).'">';
6721
-							}
6722
-							else {
7139
+							} else {
6723 7140
 								$return.= '<!-- Show original file -->';
6724 7141
 								$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).'">';
6725 7142
 							}
6726 7143
 						}
6727 7144
 
6728
-						if (empty($nolink)) $return.= '</a>';
7145
+						if (empty($nolink)) {
7146
+						    $return.= '</a>';
7147
+						}
6729 7148
 						$return.="\n";
6730 7149
 
6731
-						if ($showfilename) $return.= '<br>'.$viewfilename;
7150
+						if ($showfilename) {
7151
+						    $return.= '<br>'.$viewfilename;
7152
+						}
6732 7153
 						if ($showaction)
6733 7154
 						{
6734 7155
 							$return.= '<br>';
@@ -6753,15 +7174,20 @@  discard block
 block discarded – undo
6753 7174
 						if ($nbbyrow > 0)
6754 7175
 						{
6755 7176
 							$return.= '</td>';
6756
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6757
-						}
6758
-						else if ($nbbyrow < 0) $return.='</div>';
7177
+							if (($nbphoto % $nbbyrow) == 0) {
7178
+							    $return.= '</tr>';
7179
+							}
7180
+						} else if ($nbbyrow < 0) {
7181
+						    $return.='</div>';
7182
+						}
6759 7183
 					}
6760 7184
 
6761 7185
 					if (empty($size)) {     // Format origine
6762 7186
 						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6763 7187
 
6764
-						if ($showfilename) $return.= '<br>'.$viewfilename;
7188
+						if ($showfilename) {
7189
+						    $return.= '<br>'.$viewfilename;
7190
+						}
6765 7191
 						if ($showaction)
6766 7192
 						{
6767 7193
 							// Special case for product
@@ -6778,7 +7204,9 @@  discard block
 block discarded – undo
6778 7204
 					}
6779 7205
 
6780 7206
 					// On continue ou on arrete de boucler ?
6781
-					if ($nbmax && $nbphoto >= $nbmax) break;
7207
+					if ($nbmax && $nbphoto >= $nbmax) {
7208
+					    break;
7209
+					}
6782 7210
 				}
6783 7211
 			}
6784 7212
 
@@ -6793,7 +7221,9 @@  discard block
 block discarded – undo
6793 7221
 						$nbphoto++;
6794 7222
 					}
6795 7223
 
6796
-					if ($nbphoto) $return.= '</table>';
7224
+					if ($nbphoto) {
7225
+					    $return.= '</table>';
7226
+					}
6797 7227
 				}
6798 7228
 			}
6799 7229
 		}
@@ -6814,10 +7244,14 @@  discard block
 block discarded – undo
6814 7244
 	{
6815 7245
 		if(is_array($info))
6816 7246
 		{
6817
-			if(isset($info['type']) && $info['type']=='array') return true;
6818
-			else return false;
6819
-		}
6820
-		else return false;
7247
+			if(isset($info['type']) && $info['type']=='array') {
7248
+			    return true;
7249
+			} else {
7250
+			    return false;
7251
+			}
7252
+		} else {
7253
+		    return false;
7254
+		}
6821 7255
 	}
6822 7256
 
6823 7257
 	/**
@@ -6830,10 +7264,14 @@  discard block
 block discarded – undo
6830 7264
 	{
6831 7265
 		if(is_array($info))
6832 7266
 		{
6833
-			if(isset($info['type']) && $info['type']=='null') return true;
6834
-			else return false;
6835
-		}
6836
-		else return false;
7267
+			if(isset($info['type']) && $info['type']=='null') {
7268
+			    return true;
7269
+			} else {
7270
+			    return false;
7271
+			}
7272
+		} else {
7273
+		    return false;
7274
+		}
6837 7275
 	}
6838 7276
 
6839 7277
 	/**
@@ -6844,8 +7282,11 @@  discard block
 block discarded – undo
6844 7282
 	 */
6845 7283
 	public function isDate($info)
6846 7284
 	{
6847
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6848
-		else return false;
7285
+		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) {
7286
+		    return true;
7287
+		} else {
7288
+		    return false;
7289
+		}
6849 7290
 	}
6850 7291
 
6851 7292
 	/**
@@ -6858,10 +7299,14 @@  discard block
 block discarded – undo
6858 7299
 	{
6859 7300
 		if(is_array($info))
6860 7301
 		{
6861
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6862
-			else return false;
6863
-		}
6864
-		else return false;
7302
+			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) {
7303
+			    return true;
7304
+			} else {
7305
+			    return false;
7306
+			}
7307
+		} else {
7308
+		    return false;
7309
+		}
6865 7310
 	}
6866 7311
 
6867 7312
 	/**
@@ -6874,10 +7319,14 @@  discard block
 block discarded – undo
6874 7319
 	{
6875 7320
 		if(is_array($info))
6876 7321
 		{
6877
-			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6878
-			else return false;
6879
-		}
6880
-		else return false;
7322
+			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) {
7323
+			    return true;
7324
+			} else {
7325
+			    return false;
7326
+			}
7327
+		} else {
7328
+		    return false;
7329
+		}
6881 7330
 	}
6882 7331
 
6883 7332
 	/**
@@ -6890,10 +7339,14 @@  discard block
 block discarded – undo
6890 7339
 	{
6891 7340
 		if(is_array($info))
6892 7341
 		{
6893
-			if(isset($info['type']) && $info['type']=='text') return true;
6894
-			else return false;
6895
-		}
6896
-		else return false;
7342
+			if(isset($info['type']) && $info['type']=='text') {
7343
+			    return true;
7344
+			} else {
7345
+			    return false;
7346
+			}
7347
+		} else {
7348
+		    return false;
7349
+		}
6897 7350
 	}
6898 7351
 
6899 7352
 	/**
@@ -6906,10 +7359,14 @@  discard block
 block discarded – undo
6906 7359
 	{
6907 7360
 		if(is_array($info))
6908 7361
 		{
6909
-			if(isset($info['index']) && $info['index']==true) return true;
6910
-			else return false;
6911
-		}
6912
-		else return false;
7362
+			if(isset($info['index']) && $info['index']==true) {
7363
+			    return true;
7364
+			} else {
7365
+			    return false;
7366
+			}
7367
+		} else {
7368
+		    return false;
7369
+		}
6913 7370
 	}
6914 7371
 
6915 7372
 	/**
@@ -6923,21 +7380,21 @@  discard block
 block discarded – undo
6923 7380
 		global $conf;
6924 7381
 
6925 7382
 		$queryarray=array();
6926
-		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
7383
+		foreach ($this->fields as $field=>$info) {
7384
+		    // Loop on definition of fields
6927 7385
 		{
6928 7386
 			// Depending on field type ('datetime', ...)
6929 7387
 			if($this->isDate($info))
6930 7388
 			{
6931 7389
 				if(empty($this->{$field}))
6932 7390
 				{
6933
-					$queryarray[$field] = null;
6934
-				}
6935
-				else
7391
+					$queryarray[$field] = null;
7392
+		}
7393
+				} else
6936 7394
 				{
6937 7395
 					$queryarray[$field] = $this->db->idate($this->{$field});
6938 7396
 				}
6939
-			}
6940
-			else if($this->isArray($info))
7397
+			} else if($this->isArray($info))
6941 7398
 			{
6942 7399
 				if(! empty($this->{$field})) {
6943 7400
 					if(! is_array($this->{$field})) {
@@ -6947,29 +7404,35 @@  discard block
 block discarded – undo
6947 7404
 				} else {
6948 7405
 					$queryarray[$field] = null;
6949 7406
 				}
6950
-			}
6951
-			else if($this->isInt($info))
7407
+			} else if($this->isInt($info))
6952 7408
 			{
6953
-				if ($field == 'entity' && is_null($this->{$field}))
6954
-                    $queryarray[$field] = Globals::$conf->entity;
6955
-                else
7409
+				if ($field == 'entity' && is_null($this->{$field})) {
7410
+				                    $queryarray[$field] = Globals::$conf->entity;
7411
+				} else
6956 7412
 				{
6957 7413
 					$queryarray[$field] = (int) price2num($this->{$field});
6958
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
7414
+					if (empty($queryarray[$field])) {
7415
+					    $queryarray[$field]=0;
7416
+					}
7417
+					// May be reset to null later if property 'notnull' is -1 for this field.
6959 7418
 				}
6960
-			}
6961
-			else if($this->isFloat($info))
7419
+			} else if($this->isFloat($info))
6962 7420
 			{
6963 7421
 				$queryarray[$field] = (double) price2num($this->{$field});
6964
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6965
-			}
6966
-			else
7422
+				if (empty($queryarray[$field])) {
7423
+				    $queryarray[$field]=0;
7424
+				}
7425
+			} else
6967 7426
 			{
6968 7427
 				$queryarray[$field] = $this->{$field};
6969 7428
 			}
6970 7429
 
6971
-			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6972
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
7430
+			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
7431
+			    unset($queryarray[$field]);
7432
+			}
7433
+			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
7434
+			    $queryarray[$field] = null;
7435
+			}
6973 7436
 		}
6974 7437
 
6975 7438
 		return $queryarray;
@@ -6987,42 +7450,47 @@  discard block
 block discarded – undo
6987 7450
 		{
6988 7451
 			if($this->isDate($info))
6989 7452
 			{
6990
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6991
-				else $this->{$field} = strtotime($obj->{$field});
6992
-			}
6993
-			elseif($this->isArray($info))
7453
+				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
7454
+				    $this->{$field} = 0;
7455
+				} else {
7456
+				    $this->{$field} = strtotime($obj->{$field});
7457
+				}
7458
+			} elseif($this->isArray($info))
6994 7459
 			{
6995 7460
 				if(! empty($obj->{$field})) {
6996 7461
 					$this->{$field} = @unserialize($obj->{$field});
6997 7462
 					// Hack for data not in UTF8
6998
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
7463
+					if($this->{$field } === false) {
7464
+					    @unserialize(utf8_decode($obj->{$field}));
7465
+					}
6999 7466
 				} else {
7000 7467
 					$this->{$field} = array();
7001 7468
 				}
7002
-			}
7003
-			elseif($this->isInt($info))
7469
+			} elseif($this->isInt($info))
7004 7470
 			{
7005
-				if ($field == 'rowid') $this->id = (int) $obj->{$field};
7006
-				else $this->{$field} = (int) $obj->{$field};
7007
-			}
7008
-			elseif($this->isFloat($info))
7471
+				if ($field == 'rowid') {
7472
+				    $this->id = (int) $obj->{$field};
7473
+				} else {
7474
+				    $this->{$field} = (int) $obj->{$field};
7475
+				}
7476
+			} elseif($this->isFloat($info))
7009 7477
 			{
7010 7478
 				$this->{$field} = (double) $obj->{$field};
7011
-			}
7012
-			elseif($this->isNull($info))
7479
+			} elseif($this->isNull($info))
7013 7480
 			{
7014 7481
 				$val = $obj->{$field};
7015 7482
 				// zero is not null
7016 7483
 				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7017
-			}
7018
-			else
7484
+			} else
7019 7485
 			{
7020 7486
 				$this->{$field} = $obj->{$field};
7021 7487
 			}
7022 7488
 		}
7023 7489
 
7024 7490
 		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7025
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7491
+		if (! isset($this->fields['ref']) && isset($this->id)) {
7492
+		    $this->ref = $this->id;
7493
+		}
7026 7494
 	}
7027 7495
 
7028 7496
 	/**
@@ -7045,9 +7513,13 @@  discard block
 block discarded – undo
7045 7513
 	 */
7046 7514
     protected function quote($value, $fieldsentry)
7047 7515
     {
7048
-		if (is_null($value)) return 'NULL';
7049
-		else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7050
-		else return "'".$this->db->escape($value)."'";
7516
+		if (is_null($value)) {
7517
+		    return 'NULL';
7518
+		} else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) {
7519
+		    return $this->db->escape("$value");
7520
+		} else {
7521
+		    return "'".$this->db->escape($value)."'";
7522
+		}
7051 7523
 	}
7052 7524
 
7053 7525
 
@@ -7067,8 +7539,12 @@  discard block
 block discarded – undo
7067 7539
 		$now=dol_now();
7068 7540
 
7069 7541
 		$fieldvalues = $this->setSaveQuery();
7070
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7071
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7542
+		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
7543
+		    $fieldvalues['date_creation']=$this->db->idate($now);
7544
+		}
7545
+		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) {
7546
+		    $fieldvalues['fk_user_creat']=$user->id;
7547
+		}
7072 7548
 		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7073 7549
 
7074 7550
 		$keys=array();
@@ -7083,8 +7559,12 @@  discard block
 block discarded – undo
7083 7559
 		foreach($keys as $key)
7084 7560
 		{
7085 7561
 			// If field is an implicit foreign key field
7086
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7087
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7562
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
7563
+			    $values[$key]='';
7564
+			}
7565
+			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
7566
+			    $values[$key]='';
7567
+			}
7088 7568
 
7089 7569
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7090 7570
 			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
@@ -7094,11 +7574,17 @@  discard block
 block discarded – undo
7094 7574
 			}
7095 7575
 
7096 7576
 			// If field is an implicit foreign key field
7097
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7098
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7577
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
7578
+			    $values[$key]='null';
7579
+			}
7580
+			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
7581
+			    $values[$key]='null';
7582
+			}
7099 7583
 		}
7100 7584
 
7101
-		if ($error) return -1;
7585
+		if ($error) {
7586
+		    return -1;
7587
+		}
7102 7588
 
7103 7589
 		$this->db->begin();
7104 7590
 
@@ -7124,7 +7610,9 @@  discard block
 block discarded – undo
7124 7610
 		if (! $error)
7125 7611
 		{
7126 7612
 			$result=$this->insertExtraFields();
7127
-			if ($result < 0) $error++;
7613
+			if ($result < 0) {
7614
+			    $error++;
7615
+			}
7128 7616
 		}
7129 7617
 
7130 7618
 		// Triggers
@@ -7157,15 +7645,24 @@  discard block
 block discarded – undo
7157 7645
 	 */
7158 7646
 	public function fetchCommon($id, $ref = null, $morewhere = '')
7159 7647
 	{
7160
-		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7648
+		if (empty($id) && empty($ref) && empty($morewhere)) {
7649
+		    return -1;
7650
+		}
7161 7651
 
7162 7652
 		$sql = 'SELECT '.$this->getFieldList();
7163 7653
 		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7164 7654
 
7165
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7166
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7167
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7168
-		if ($morewhere)   $sql.= $morewhere;
7655
+		if (!empty($id)) {
7656
+		    $sql.= ' WHERE rowid = '.$id;
7657
+		} elseif (!empty($ref)) {
7658
+		    $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7659
+		} else {
7660
+		    $sql.=' WHERE 1 = 1';
7661
+		}
7662
+		// usage with empty id and empty ref is very rare
7663
+		if ($morewhere) {
7664
+		    $sql.= $morewhere;
7665
+		}
7169 7666
 		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7170 7667
 
7171 7668
 		$res = $this->db->query($sql);
@@ -7176,13 +7673,11 @@  discard block
 block discarded – undo
7176 7673
 			{
7177 7674
 				$this->setVarsFromFetchObj($obj);
7178 7675
 				return $this->id;
7179
-			}
7180
-			else
7676
+			} else
7181 7677
 			{
7182 7678
 				return 0;
7183 7679
 			}
7184
-		}
7185
-		else
7680
+		} else
7186 7681
 		{
7187 7682
 			$this->error = $this->db->lasterror();
7188 7683
 			$this->errors[] = $this->error;
@@ -7206,8 +7701,12 @@  discard block
 block discarded – undo
7206 7701
 		$now=dol_now();
7207 7702
 
7208 7703
 		$fieldvalues = $this->setSaveQuery();
7209
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7210
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7704
+		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
7705
+		    $fieldvalues['date_modification']=$this->db->idate($now);
7706
+		}
7707
+		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) {
7708
+		    $fieldvalues['fk_user_modif']=$user->id;
7709
+		}
7211 7710
 		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7212 7711
 
7213 7712
 		$keys=array();
@@ -7222,8 +7721,14 @@  discard block
 block discarded – undo
7222 7721
 		// Clean and check mandatory
7223 7722
 		foreach($keys as $key)
7224 7723
 		{
7225
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7226
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7724
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
7725
+			    $values[$key]='';
7726
+			}
7727
+			// This is an implicit foreign key field
7728
+			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
7729
+			    $values[$key]='';
7730
+			}
7731
+			// This is an explicit foreign key field
7227 7732
 
7228 7733
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7229 7734
 			/*
@@ -7303,10 +7808,11 @@  discard block
 block discarded – undo
7303 7808
 					return -1;
7304 7809
 				}
7305 7810
 			}
7306
-		}
7307
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7811
+		} elseif (! empty($this->fk_element) && ! empty($this->childtables)) {
7812
+		    // If object has childs linked with a foreign key field, we check all child tables.
7308 7813
 		{
7309
-			$objectisused = $this->isObjectUsed($this->id);
7814
+			$objectisused = $this->isObjectUsed($this->id);
7815
+		}
7310 7816
 			if (! empty($objectisused))
7311 7817
 			{
7312 7818
 				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
@@ -7413,7 +7919,9 @@  discard block
 block discarded – undo
7413 7919
      */
7414 7920
     public function trimParameters($parameters)
7415 7921
     {
7416
-        if (!is_array($parameters)) return;
7922
+        if (!is_array($parameters)) {
7923
+            return;
7924
+        }
7417 7925
         foreach ($parameters as $parameter) {
7418 7926
             if (isset($this->$parameter)) {
7419 7927
                 $this->$parameter = trim($this->$parameter);
Please login to merge, or discard this patch.
Base/Categorie.php 2 patches
Spacing   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -254,17 +254,17 @@  discard block
 block discarded – undo
254 254
         }
255 255
 
256 256
         $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type";
257
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie";
257
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
258 258
         if ($id > 0) {
259
-            $sql .= " WHERE rowid = " . $id;
259
+            $sql .= " WHERE rowid = ".$id;
260 260
         } else {
261
-            $sql .= " WHERE label = '" . $label . "' AND entity IN (" . DolUtils::getEntity('category') . ")";
261
+            $sql .= " WHERE label = '".$label."' AND entity IN (".DolUtils::getEntity('category').")";
262 262
             if (!is_null($type)) {
263
-                $sql .= " AND type = " . $type;
263
+                $sql .= " AND type = ".$type;
264 264
             }
265 265
         }
266 266
 
267
-        DolUtils::dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
267
+        DolUtils::dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
268 268
         $resql = Config::$dbEngine->select($sql);
269 269
         if ($resql) {
270 270
             if (count($resql) > 0) {
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 
324 324
         $error = 0;
325 325
 
326
-        DolUtils::dol_syslog(get_class($this) . '::create', LOG_DEBUG);
326
+        DolUtils::dol_syslog(get_class($this).'::create', LOG_DEBUG);
327 327
 
328 328
         // Clean parameters
329 329
         $this->label = trim($this->label);
@@ -337,14 +337,14 @@  discard block
 block discarded – undo
337 337
 
338 338
         if ($this->already_exists()) {
339 339
             $this->error = $langs->trans("ImpossibleAddCat", $this->label);
340
-            $this->error .= " : " . $langs->trans("CategoryExistsAtSameLevel");
340
+            $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
341 341
             dol_syslog($this->error, LOG_WARNING);
342 342
             return -4;
343 343
         }
344 344
 
345 345
         Config::$dbEngine->beginTransaction();
346 346
 
347
-        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie (";
347
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie (";
348 348
         $sql .= "fk_parent,";
349 349
         $sql .= " label,";
350 350
         $sql .= " description,";
@@ -357,22 +357,22 @@  discard block
 block discarded – undo
357 357
         $sql .= " import_key,";
358 358
         $sql .= " entity";
359 359
         $sql .= ") VALUES (";
360
-        $sql .= Config::$dbEngine->escape($this->fk_parent) . ",";
361
-        $sql .= "'" . Config::$dbEngine->escape($this->label) . "',";
362
-        $sql .= "'" . Config::$dbEngine->escape($this->description) . "',";
363
-        $sql .= "'" . Config::$dbEngine->escape($this->color) . "',";
360
+        $sql .= Config::$dbEngine->escape($this->fk_parent).",";
361
+        $sql .= "'".Config::$dbEngine->escape($this->label)."',";
362
+        $sql .= "'".Config::$dbEngine->escape($this->description)."',";
363
+        $sql .= "'".Config::$dbEngine->escape($this->color)."',";
364 364
         if (!empty(Globals::$conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) {
365
-            $sql .= ($this->socid != -1 ? $this->socid : 'null') . ",";
365
+            $sql .= ($this->socid != -1 ? $this->socid : 'null').",";
366 366
         }
367
-        $sql .= "'" . Config::$dbEngine->escape($this->visible) . "',";
368
-        $sql .= Config::$dbEngine->escape($type) . ",";
369
-        $sql .= (!empty($this->import_key) ? "'" . Config::$dbEngine->escape($this->import_key) . "'" : 'null') . ",";
367
+        $sql .= "'".Config::$dbEngine->escape($this->visible)."',";
368
+        $sql .= Config::$dbEngine->escape($type).",";
369
+        $sql .= (!empty($this->import_key) ? "'".Config::$dbEngine->escape($this->import_key)."'" : 'null').",";
370 370
         $sql .= Config::$dbEngine->escape(Globals::$conf->entity);
371 371
         $sql .= ")";
372 372
 
373 373
         $res = Config::$dbEngine->select($sql);
374 374
         if ($res) {
375
-            $id = Config::$dbEngine->last_insert_id(MAIN_DB_PREFIX . "categorie");
375
+            $id = Config::$dbEngine->last_insert_id(MAIN_DB_PREFIX."categorie");
376 376
 
377 377
             if ($id > 0) {
378 378
                 $this->id = $id;
@@ -436,24 +436,24 @@  discard block
 block discarded – undo
436 436
 
437 437
         if ($this->already_exists()) {
438 438
             $this->error = $langs->trans("ImpossibleUpdateCat");
439
-            $this->error .= " : " . $langs->trans("CategoryExistsAtSameLevel");
439
+            $this->error .= " : ".$langs->trans("CategoryExistsAtSameLevel");
440 440
             return -1;
441 441
         }
442 442
 
443 443
         Config::$dbEngine->begin();
444 444
 
445
-        $sql = "UPDATE " . MAIN_DB_PREFIX . "categorie";
446
-        $sql .= " SET label = '" . Config::$dbEngine->escape($this->label) . "',";
447
-        $sql .= " description = '" . Config::$dbEngine->escape($this->description) . "',";
448
-        $sql .= " color = '" . Config::$dbEngine->escape($this->color) . "'";
445
+        $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
446
+        $sql .= " SET label = '".Config::$dbEngine->escape($this->label)."',";
447
+        $sql .= " description = '".Config::$dbEngine->escape($this->description)."',";
448
+        $sql .= " color = '".Config::$dbEngine->escape($this->color)."'";
449 449
         if (!empty(Globals::$conf->global->CATEGORY_ASSIGNED_TO_A_CUSTOMER)) {
450
-            $sql .= ", fk_soc = " . ($this->socid != -1 ? $this->socid : 'null');
450
+            $sql .= ", fk_soc = ".($this->socid != -1 ? $this->socid : 'null');
451 451
         }
452
-        $sql .= ", visible = '" . Config::$dbEngine->escape($this->visible) . "'";
453
-        $sql .= ", fk_parent = " . $this->fk_parent;
454
-        $sql .= " WHERE rowid = " . $this->id;
452
+        $sql .= ", visible = '".Config::$dbEngine->escape($this->visible)."'";
453
+        $sql .= ", fk_parent = ".$this->fk_parent;
454
+        $sql .= " WHERE rowid = ".$this->id;
455 455
 
456
-        dol_syslog(get_class($this) . "::update", LOG_DEBUG);
456
+        dol_syslog(get_class($this)."::update", LOG_DEBUG);
457 457
         if (Config::$dbEngine->select($sql)) {
458 458
             $action = 'update';
459 459
 
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
         // Clean parameters
503 503
         $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0);
504 504
 
505
-        dol_syslog(get_class($this) . "::remove");
505
+        dol_syslog(get_class($this)."::remove");
506 506
 
507 507
         Config::$dbEngine->begin();
508 508
 
@@ -516,9 +516,9 @@  discard block
 block discarded – undo
516 516
 
517 517
         /* FIX #1317 : Check for child category and move up 1 level */
518 518
         if (!$error) {
519
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "categorie";
520
-            $sql .= " SET fk_parent = " . $this->fk_parent;
521
-            $sql .= " WHERE fk_parent = " . $this->id;
519
+            $sql = "UPDATE ".MAIN_DB_PREFIX."categorie";
520
+            $sql .= " SET fk_parent = ".$this->fk_parent;
521
+            $sql .= " WHERE fk_parent = ".$this->id;
522 522
 
523 523
             if (!Config::$dbEngine->select($sql)) {
524 524
                 $this->error = Config::$dbEngine->lasterror();
@@ -538,11 +538,11 @@  discard block
 block discarded – undo
538 538
             'categorie' => 'rowid',
539 539
         );
540 540
         foreach ($arraydelete as $key => $value) {
541
-            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $key;
542
-            $sql .= " WHERE " . $value . " = " . $this->id;
541
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX.$key;
542
+            $sql .= " WHERE ".$value." = ".$this->id;
543 543
             if (!Config::$dbEngine->select($sql)) {
544 544
                 $this->errors[] = Config::$dbEngine->lasterror();
545
-                dol_syslog("Error sql=" . $sql . " " . $this->error, LOG_ERR);
545
+                dol_syslog("Error sql=".$sql." ".$this->error, LOG_ERR);
546 546
                 $error++;
547 547
             }
548 548
         }
@@ -552,7 +552,7 @@  discard block
 block discarded – undo
552 552
             $result = $this->deleteExtraFields();
553 553
             if ($result < 0) {
554 554
                 $error++;
555
-                dol_syslog(get_class($this) . "::delete erreur " . $this->error, LOG_ERR);
555
+                dol_syslog(get_class($this)."::delete erreur ".$this->error, LOG_ERR);
556 556
             }
557 557
         }
558 558
 
@@ -585,17 +585,17 @@  discard block
 block discarded – undo
585 585
 
586 586
         Config::$dbEngine->begin();
587 587
 
588
-        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
589
-        $sql .= " (fk_categorie, fk_" . $this->MAP_CAT_FK[$type] . ")";
590
-        $sql .= " VALUES (" . $this->id . ", " . $obj->id . ")";
588
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
589
+        $sql .= " (fk_categorie, fk_".$this->MAP_CAT_FK[$type].")";
590
+        $sql .= " VALUES (".$this->id.", ".$obj->id.")";
591 591
 
592
-        dol_syslog(get_class($this) . '::add_type', LOG_DEBUG);
592
+        dol_syslog(get_class($this).'::add_type', LOG_DEBUG);
593 593
         if (Config::$dbEngine->select($sql)) {
594 594
             if (!empty(Globals::$conf->global->CATEGORIE_RECURSIV_ADD)) {
595
-                $sql = 'SELECT fk_parent FROM ' . MAIN_DB_PREFIX . 'categorie';
596
-                $sql .= " WHERE rowid = " . $this->id;
595
+                $sql = 'SELECT fk_parent FROM '.MAIN_DB_PREFIX.'categorie';
596
+                $sql .= " WHERE rowid = ".$this->id;
597 597
 
598
-                dol_syslog(get_class($this) . "::add_type", LOG_DEBUG);
598
+                dol_syslog(get_class($this)."::add_type", LOG_DEBUG);
599 599
                 $resql = Config::$dbEngine->select($sql);
600 600
                 if ($resql) {
601 601
                     if (Config::$dbEngine->num_rows($resql) > 0) {
@@ -672,19 +672,19 @@  discard block
 block discarded – undo
672 672
         // For backward compatibility
673 673
         if ($type == 'societe') {
674 674
             $type = 'customer';
675
-            dol_syslog(get_class($this) . "::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
675
+            dol_syslog(get_class($this)."::del_type(): type 'societe' is deprecated, please use 'customer' instead", LOG_WARNING);
676 676
         } elseif ($type == 'fournisseur') {
677 677
             $type = 'supplier';
678
-            dol_syslog(get_class($this) . "::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
678
+            dol_syslog(get_class($this)."::del_type(): type 'fournisseur' is deprecated, please use 'supplier' instead", LOG_WARNING);
679 679
         }
680 680
 
681 681
         Config::$dbEngine->begin();
682 682
 
683
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
684
-        $sql .= " WHERE fk_categorie = " . $this->id;
685
-        $sql .= " AND   fk_" . $this->MAP_CAT_FK[$type] . "  = " . $obj->id;
683
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
684
+        $sql .= " WHERE fk_categorie = ".$this->id;
685
+        $sql .= " AND   fk_".$this->MAP_CAT_FK[$type]."  = ".$obj->id;
686 686
 
687
-        dol_syslog(get_class($this) . '::del_type', LOG_DEBUG);
687
+        dol_syslog(get_class($this).'::del_type', LOG_DEBUG);
688 688
         if (Config::$dbEngine->select($sql)) {
689 689
             // Call trigger
690 690
             $this->context = array('unlinkoff' => $obj); // Save object we want to link category to into category instance to provide information to trigger
@@ -722,28 +722,28 @@  discard block
 block discarded – undo
722 722
 
723 723
         $obj = new $this->MAP_OBJ_CLASS[$type](Config::$dbEngine);
724 724
 
725
-        $sql = "SELECT c.fk_" . $this->MAP_CAT_FK[$type];
726
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as c";
727
-        $sql .= ", " . MAIN_DB_PREFIX . $this->MAP_OBJ_TABLE[$type] . " as o";
728
-        $sql .= " WHERE o.entity IN (" . getEntity($obj->element) . ")";
729
-        $sql .= " AND c.fk_categorie = " . $this->id;
730
-        $sql .= " AND c.fk_" . $this->MAP_CAT_FK[$type] . " = o.rowid";
725
+        $sql = "SELECT c.fk_".$this->MAP_CAT_FK[$type];
726
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as c";
727
+        $sql .= ", ".MAIN_DB_PREFIX.$this->MAP_OBJ_TABLE[$type]." as o";
728
+        $sql .= " WHERE o.entity IN (".getEntity($obj->element).")";
729
+        $sql .= " AND c.fk_categorie = ".$this->id;
730
+        $sql .= " AND c.fk_".$this->MAP_CAT_FK[$type]." = o.rowid";
731 731
 
732
-        dol_syslog(get_class($this) . "::getObjectsInCateg", LOG_DEBUG);
732
+        dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG);
733 733
         $resql = Config::$dbEngine->select($sql);
734 734
         if ($resql) {
735 735
             while ($rec = Config::$dbEngine->fetch_array($resql)) {
736 736
                 if ($onlyids) {
737
-                    $objs[] = $rec['fk_' . $this->MAP_CAT_FK[$type]];
737
+                    $objs[] = $rec['fk_'.$this->MAP_CAT_FK[$type]];
738 738
                 } else {
739 739
                     $obj = new $this->MAP_OBJ_CLASS[$type](Config::$dbEngine);
740
-                    $obj->fetch($rec['fk_' . $this->MAP_CAT_FK[$type]]);
740
+                    $obj->fetch($rec['fk_'.$this->MAP_CAT_FK[$type]]);
741 741
                     $objs[] = $obj;
742 742
                 }
743 743
             }
744 744
             return $objs;
745 745
         } else {
746
-            $this->error = Config::$dbEngine->error() . ' sql=' . $sql;
746
+            $this->error = Config::$dbEngine->error().' sql='.$sql;
747 747
             return -1;
748 748
         }
749 749
     }
@@ -758,14 +758,14 @@  discard block
 block discarded – undo
758 758
      */
759 759
     function containsObject($type, $object_id)
760 760
     {
761
-        $sql = "SELECT COUNT(*) as nb FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type];
762
-        $sql .= " WHERE fk_categorie = " . $this->id . " AND fk_" . $this->MAP_CAT_FK[$type] . " = " . $object_id;
763
-        dol_syslog(get_class($this) . "::containsObject", LOG_DEBUG);
761
+        $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type];
762
+        $sql .= " WHERE fk_categorie = ".$this->id." AND fk_".$this->MAP_CAT_FK[$type]." = ".$object_id;
763
+        dol_syslog(get_class($this)."::containsObject", LOG_DEBUG);
764 764
         $resql = Config::$dbEngine->select($sql);
765 765
         if ($resql) {
766 766
             return Config::$dbEngine->fetch_object($resql)->nb;
767 767
         } else {
768
-            $this->error = Config::$dbEngine->error() . ' sql=' . $sql;
768
+            $this->error = Config::$dbEngine->error().' sql='.$sql;
769 769
             return -1;
770 770
         }
771 771
     }
@@ -788,7 +788,7 @@  discard block
 block discarded – undo
788 788
         $categories = array();
789 789
 
790 790
         $sub_type = $type;
791
-        $subcol_name = "fk_" . $type;
791
+        $subcol_name = "fk_".$type;
792 792
         if ($type == "customer") {
793 793
             $sub_type = "societe";
794 794
             $subcol_name = "fk_soc";
@@ -801,12 +801,12 @@  discard block
 block discarded – undo
801 801
             $subcol_name = "fk_socpeople";
802 802
         }
803 803
         $sql = "SELECT s.rowid";
804
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie as s";
805
-        $sql .= " , " . MAIN_DB_PREFIX . "categorie_" . $sub_type . " as sub ";
806
-        $sql .= ' WHERE s.entity IN (' . getEntity('category') . ')';
807
-        $sql .= ' AND s.type=' . array_search($type, self::$MAP_ID_TO_CODE);
804
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie as s";
805
+        $sql .= " , ".MAIN_DB_PREFIX."categorie_".$sub_type." as sub ";
806
+        $sql .= ' WHERE s.entity IN ('.getEntity('category').')';
807
+        $sql .= ' AND s.type='.array_search($type, self::$MAP_ID_TO_CODE);
808 808
         $sql .= ' AND s.rowid = sub.fk_categorie';
809
-        $sql .= ' AND sub.' . $subcol_name . ' = ' . $id;
809
+        $sql .= ' AND sub.'.$subcol_name.' = '.$id;
810 810
 
811 811
         $sql .= Config::$dbEngine->order($sortfield, $sortorder);
812 812
 
@@ -870,8 +870,8 @@  discard block
 block discarded – undo
870 870
     function get_filles()
871 871
     {
872 872
         // phpcs:enable
873
-        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie";
874
-        $sql .= " WHERE fk_parent = " . $this->id;
873
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
874
+        $sql .= " WHERE fk_parent = ".$this->id;
875 875
 
876 876
         $res = Config::$dbEngine->select($sql);
877 877
         if ($res) {
@@ -903,11 +903,11 @@  discard block
 block discarded – undo
903 903
 
904 904
         // Load array[child]=parent
905 905
         $sql = "SELECT fk_parent as id_parent, rowid as id_son";
906
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie";
906
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie";
907 907
         $sql .= " WHERE fk_parent != 0";
908
-        $sql .= " AND entity IN (" . DolUtils::getEntity('category') . ")";
908
+        $sql .= " AND entity IN (".DolUtils::getEntity('category').")";
909 909
 
910
-        DolUtils::dol_syslog(get_class($this) . "::load_motherof", LOG_DEBUG);
910
+        DolUtils::dol_syslog(get_class($this)."::load_motherof", LOG_DEBUG);
911 911
         $resql = Config::$dbEngine->select($sql);
912 912
         if (is_array($resql)) {
913 913
             foreach ($resql as $_obj) {
@@ -959,15 +959,15 @@  discard block
 block discarded – undo
959 959
         {
960 960
             $sql .= ", t.label as label_trans, t.description as description_trans";
961 961
         }
962
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie as c";
962
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c";
963 963
         if (!empty(Globals::$conf->global->MAIN_MULTILANGS))
964 964
         {
965
-            $sql .= " LEFT  JOIN " . MAIN_DB_PREFIX . "categorie_lang as t ON t.fk_category=c.rowid AND t.lang='" . $current_lang . "'";
965
+            $sql .= " LEFT  JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$current_lang."'";
966 966
         }
967
-        $sql .= " WHERE c.entity IN (" . DolUtils::getEntity('category') . ")";
968
-        $sql .= " AND c.type = " . $type;
967
+        $sql .= " WHERE c.entity IN (".DolUtils::getEntity('category').")";
968
+        $sql .= " AND c.type = ".$type;
969 969
 
970
-        DolUtils::dol_syslog(get_class($this) . "::get_full_arbo get category list", LOG_DEBUG);
970
+        DolUtils::dol_syslog(get_class($this)."::get_full_arbo get category list", LOG_DEBUG);
971 971
         $resql = Config::$dbEngine->select($sql);
972 972
         if (is_array($resql)) {
973 973
             foreach ($resql as $_obj) {
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
         }
988 988
 
989 989
         // We add the fullpath property to each elements of first level (no parent exists)
990
-        DolUtils::dol_syslog(get_class($this) . "::get_full_arbo call to build_path_from_id_categ", LOG_DEBUG);
990
+        DolUtils::dol_syslog(get_class($this)."::get_full_arbo call to build_path_from_id_categ", LOG_DEBUG);
991 991
         foreach ($this->cats as $key => $val) {
992 992
             //print 'key='.$key.'<br>'."\n";
993 993
             $this->build_path_from_id_categ($key, 0); // Process a branch from the root category key (this category has no parent)
@@ -996,18 +996,18 @@  discard block
 block discarded – undo
996 996
         // Exclude leaf including $markafterid from tree
997 997
         if ($markafterid) {
998 998
             //print "Look to discard category ".$markafterid."\n";
999
-            $keyfilter1 = '^' . $markafterid . '$';
1000
-            $keyfilter2 = '_' . $markafterid . '$';
1001
-            $keyfilter3 = '^' . $markafterid . '_';
1002
-            $keyfilter4 = '_' . $markafterid . '_';
999
+            $keyfilter1 = '^'.$markafterid.'$';
1000
+            $keyfilter2 = '_'.$markafterid.'$';
1001
+            $keyfilter3 = '^'.$markafterid.'_';
1002
+            $keyfilter4 = '_'.$markafterid.'_';
1003 1003
             foreach ($this->cats as $key => $val) {
1004
-                if (preg_match('/' . $keyfilter1 . '/', $val['fullpath']) || preg_match('/' . $keyfilter2 . '/', $val['fullpath']) || preg_match('/' . $keyfilter3 . '/', $val['fullpath']) || preg_match('/' . $keyfilter4 . '/', $val['fullpath'])) {
1004
+                if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
1005 1005
                     unset($this->cats[$key]);
1006 1006
                 }
1007 1007
             }
1008 1008
         }
1009 1009
 
1010
-        DolUtils::dol_syslog(get_class($this) . "::get_full_arbo dol_sort_array", LOG_DEBUG);
1010
+        DolUtils::dol_syslog(get_class($this)."::get_full_arbo dol_sort_array", LOG_DEBUG);
1011 1011
         $this->cats = DolUtils::dol_sort_array($this->cats, 'fulllabel', 'asc', true, false);
1012 1012
 
1013 1013
         //$this->debug_cats();
@@ -1026,26 +1026,26 @@  discard block
 block discarded – undo
1026 1026
     function build_path_from_id_categ($id_categ, $protection = 1000)
1027 1027
     {
1028 1028
         // phpcs:enable
1029
-        dol_syslog(get_class($this) . "::build_path_from_id_categ id_categ=" . $id_categ . " protection=" . $protection, LOG_DEBUG);
1029
+        dol_syslog(get_class($this)."::build_path_from_id_categ id_categ=".$id_categ." protection=".$protection, LOG_DEBUG);
1030 1030
 
1031 1031
         if (!empty($this->cats[$id_categ]['fullpath'])) {
1032 1032
             // Already defined
1033
-            dol_syslog(get_class($this) . "::build_path_from_id_categ fullpath and fulllabel already defined", LOG_WARNING);
1033
+            dol_syslog(get_class($this)."::build_path_from_id_categ fullpath and fulllabel already defined", LOG_WARNING);
1034 1034
             return;
1035 1035
         }
1036 1036
 
1037 1037
         // First build full array $motherof
1038 1038
         //$this->load_motherof();	// Disabled because already done by caller of build_path_from_id_categ
1039 1039
         // Define fullpath and fulllabel
1040
-        $this->cats[$id_categ]['fullpath'] = '_' . $id_categ;
1040
+        $this->cats[$id_categ]['fullpath'] = '_'.$id_categ;
1041 1041
         $this->cats[$id_categ]['fulllabel'] = $this->cats[$id_categ]['label'];
1042 1042
         $i = 0;
1043 1043
         $cursor_categ = $id_categ;
1044 1044
         //print 'Work for id_categ='.$id_categ.'<br>'."\n";
1045 1045
         while ((empty($protection) || $i < $protection) && !empty($this->motherof[$cursor_categ])) {
1046 1046
             //print '&nbsp; cursor_categ='.$cursor_categ.' i='.$i.' '.$this->motherof[$cursor_categ].'<br>'."\n";
1047
-            $this->cats[$id_categ]['fullpath'] = '_' . $this->motherof[$cursor_categ] . $this->cats[$id_categ]['fullpath'];
1048
-            $this->cats[$id_categ]['fulllabel'] = $this->cats[$this->motherof[$cursor_categ]]['label'] . ' >> ' . $this->cats[$id_categ]['fulllabel'];
1047
+            $this->cats[$id_categ]['fullpath'] = '_'.$this->motherof[$cursor_categ].$this->cats[$id_categ]['fullpath'];
1048
+            $this->cats[$id_categ]['fulllabel'] = $this->cats[$this->motherof[$cursor_categ]]['label'].' >> '.$this->cats[$id_categ]['fulllabel'];
1049 1049
             //print '&nbsp; Result for id_categ='.$id_categ.' : '.$this->cats[$id_categ]['fullpath'].' '.$this->cats[$id_categ]['fulllabel'].'<br>'."\n";
1050 1050
             $i++;
1051 1051
             $cursor_categ = $this->motherof[$cursor_categ];
@@ -1068,12 +1068,12 @@  discard block
 block discarded – undo
1068 1068
         // phpcs:enable
1069 1069
         // Display $this->cats
1070 1070
         foreach ($this->cats as $key => $val) {
1071
-            print 'id: ' . $this->cats[$key]['id'];
1072
-            print ' label: ' . $this->cats[$key]['label'];
1073
-            print ' mother: ' . $this->cats[$key]['fk_parent'];
1071
+            print 'id: '.$this->cats[$key]['id'];
1072
+            print ' label: '.$this->cats[$key]['label'];
1073
+            print ' mother: '.$this->cats[$key]['fk_parent'];
1074 1074
             //print ' children: '.(is_array($this->cats[$key]['id_children'])?join(',',$this->cats[$key]['id_children']):'');
1075
-            print ' fullpath: ' . $this->cats[$key]['fullpath'];
1076
-            print ' fulllabel: ' . $this->cats[$key]['fulllabel'];
1075
+            print ' fullpath: '.$this->cats[$key]['fullpath'];
1076
+            print ' fulllabel: '.$this->cats[$key]['fulllabel'];
1077 1077
             print "<br>\n";
1078 1078
         }
1079 1079
     }
@@ -1092,10 +1092,10 @@  discard block
 block discarded – undo
1092 1092
         if (!is_numeric($type))
1093 1093
             $type = $this->MAP_ID[$type];
1094 1094
 
1095
-        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie";
1096
-        $sql .= " WHERE entity IN (" . getEntity('category') . ")";
1095
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1096
+        $sql .= " WHERE entity IN (".getEntity('category').")";
1097 1097
         if (!is_null($type))
1098
-            $sql .= " AND type = " . $type;
1098
+            $sql .= " AND type = ".$type;
1099 1099
         if ($parent)
1100 1100
             $sql .= " AND fk_parent = 0";
1101 1101
 
@@ -1132,13 +1132,13 @@  discard block
 block discarded – undo
1132 1132
          * are equals to those of the calling category
1133 1133
          */
1134 1134
         $sql = "SELECT c.rowid";
1135
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie as c ";
1136
-        $sql .= " WHERE c.entity IN (" . getEntity('category') . ")";
1137
-        $sql .= " AND c.type = " . $type;
1138
-        $sql .= " AND c.fk_parent = " . $this->fk_parent;
1139
-        $sql .= " AND c.label = '" . Config::$dbEngine->escape($this->label) . "'";
1135
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c ";
1136
+        $sql .= " WHERE c.entity IN (".getEntity('category').")";
1137
+        $sql .= " AND c.type = ".$type;
1138
+        $sql .= " AND c.fk_parent = ".$this->fk_parent;
1139
+        $sql .= " AND c.label = '".Config::$dbEngine->escape($this->label)."'";
1140 1140
 
1141
-        dol_syslog(get_class($this) . "::already_exists", LOG_DEBUG);
1141
+        dol_syslog(get_class($this)."::already_exists", LOG_DEBUG);
1142 1142
         $resql = Config::$dbEngine->select($sql);
1143 1143
         if ($resql) {
1144 1144
             if (Config::$dbEngine->num_rows($resql) > 0) {      // Checking for empty resql{
@@ -1149,11 +1149,11 @@  discard block
 block discarded – undo
1149 1149
                  * update may be for label.
1150 1150
                  */
1151 1151
                 if ($obj[0] > 0 && $obj[0] != $this->id) {
1152
-                    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);
1152
+                    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);
1153 1153
                     return 1;
1154 1154
                 }
1155 1155
             }
1156
-            dol_syslog(get_class($this) . "::already_exists no category with same name=" . $this->label . " and same parent " . $this->fk_parent . " than category id=" . $this->id, LOG_DEBUG);
1156
+            dol_syslog(get_class($this)."::already_exists no category with same name=".$this->label." and same parent ".$this->fk_parent." than category id=".$this->id, LOG_DEBUG);
1157 1157
             return 0;
1158 1158
         } else {
1159 1159
             $this->error = Config::$dbEngine->error();
@@ -1210,11 +1210,11 @@  discard block
 block discarded – undo
1210 1210
                 }
1211 1211
 
1212 1212
                 if ($url == '') {
1213
-                    $link = '<a href="' . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $cat->id . '&type=' . $cat->type . '" class="' . $forced_color . '">';
1213
+                    $link = '<a href="'.DOL_URL_ROOT.'/categories/viewcat.php?id='.$cat->id.'&type='.$cat->type.'" class="'.$forced_color.'">';
1214 1214
                     $linkend = '</a>';
1215
-                    $w[] = $link . $cat->label . $linkend;
1215
+                    $w[] = $link.$cat->label.$linkend;
1216 1216
                 } else {
1217
-                    $w[] = "<a href='" . DOL_URL_ROOT . "/$url?catid=" . $cat->id . "'>" . $cat->label . "</a>";
1217
+                    $w[] = "<a href='".DOL_URL_ROOT."/$url?catid=".$cat->id."'>".$cat->label."</a>";
1218 1218
                 }
1219 1219
             }
1220 1220
             $newcategwithpath = preg_replace('/toreplace/', $forced_color, implode($sep, $w));
@@ -1236,8 +1236,8 @@  discard block
 block discarded – undo
1236 1236
         // phpcs:enable
1237 1237
         $parents = array();
1238 1238
 
1239
-        $sql = "SELECT fk_parent FROM " . MAIN_DB_PREFIX . "categorie";
1240
-        $sql .= " WHERE rowid = " . $this->id;
1239
+        $sql = "SELECT fk_parent FROM ".MAIN_DB_PREFIX."categorie";
1240
+        $sql .= " WHERE rowid = ".$this->id;
1241 1241
 
1242 1242
         $res = Config::$dbEngine->select($sql);
1243 1243
 
@@ -1306,8 +1306,8 @@  discard block
 block discarded – undo
1306 1306
         if ($type === Categorie::TYPE_BANK_LINE) {   // TODO Remove this with standard category code
1307 1307
             // Load bank groups
1308 1308
             $sql = "SELECT c.label, c.rowid";
1309
-            $sql .= " FROM " . MAIN_DB_PREFIX . "bank_class as a, " . MAIN_DB_PREFIX . "bank_categ as c";
1310
-            $sql .= " WHERE a.lineid=" . $id . " AND a.fk_categ = c.rowid";
1309
+            $sql .= " FROM ".MAIN_DB_PREFIX."bank_class as a, ".MAIN_DB_PREFIX."bank_categ as c";
1310
+            $sql .= " WHERE a.lineid=".$id." AND a.fk_categ = c.rowid";
1311 1311
             $sql .= " ORDER BY c.label";
1312 1312
 
1313 1313
             $res = Config::$dbEngine->select($sql);
@@ -1330,9 +1330,9 @@  discard block
 block discarded – undo
1330 1330
             }
1331 1331
         } else {
1332 1332
             $sql = "SELECT ct.fk_categorie, c.label, c.rowid";
1333
-            $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_" . $this->MAP_CAT_TABLE[$type] . " as ct, " . MAIN_DB_PREFIX . "categorie as c";
1334
-            $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_" . $this->MAP_CAT_FK[$type] . " = " . (int) $id . " AND c.type = " . $this->MAP_ID[$type];
1335
-            $sql .= " AND c.entity IN (" . getEntity('category') . ")";
1333
+            $sql .= " FROM ".MAIN_DB_PREFIX."categorie_".$this->MAP_CAT_TABLE[$type]." as ct, ".MAIN_DB_PREFIX."categorie as c";
1334
+            $sql .= " WHERE ct.fk_categorie = c.rowid AND ct.fk_".$this->MAP_CAT_FK[$type]." = ".(int) $id." AND c.type = ".$this->MAP_ID[$type];
1335
+            $sql .= " AND c.entity IN (".getEntity('category').")";
1336 1336
 
1337 1337
             $res = Config::$dbEngine->select($sql);
1338 1338
             if ($res) {
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
     {
1372 1372
         // Deprecation warning
1373 1373
         if (is_numeric($type)) {
1374
-            dol_syslog(__METHOD__ . ': using numeric types is deprecated.', LOG_WARNING);
1374
+            dol_syslog(__METHOD__.': using numeric types is deprecated.', LOG_WARNING);
1375 1375
         }
1376 1376
 
1377 1377
         $cats = array();
@@ -1381,23 +1381,23 @@  discard block
 block discarded – undo
1381 1381
             // We want to reverse lookup
1382 1382
             $map_type = array_flip($this->MAP_ID);
1383 1383
             $type = $map_type[$type];
1384
-            dol_syslog(get_class($this) . "::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
1384
+            dol_syslog(get_class($this)."::rechercher(): numeric types are deprecated, please use string instead", LOG_WARNING);
1385 1385
         }
1386 1386
 
1387 1387
         // Generation requete recherche
1388
-        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie";
1389
-        $sql .= " WHERE type = " . $this->MAP_ID[$type];
1390
-        $sql .= " AND entity IN (" . getEntity('category') . ")";
1388
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie";
1389
+        $sql .= " WHERE type = ".$this->MAP_ID[$type];
1390
+        $sql .= " AND entity IN (".getEntity('category').")";
1391 1391
         if ($nom) {
1392 1392
             if (!$exact)
1393
-                $nom = '%' . str_replace('*', '%', $nom) . '%';
1393
+                $nom = '%'.str_replace('*', '%', $nom).'%';
1394 1394
             if (!$case)
1395
-                $sql .= " AND label LIKE '" . Config::$dbEngine->escape($nom) . "'";
1395
+                $sql .= " AND label LIKE '".Config::$dbEngine->escape($nom)."'";
1396 1396
             else
1397
-                $sql .= " AND label LIKE BINARY '" . Config::$dbEngine->escape($nom) . "'";
1397
+                $sql .= " AND label LIKE BINARY '".Config::$dbEngine->escape($nom)."'";
1398 1398
         }
1399 1399
         if ($id) {
1400
-            $sql .= " AND rowid = '" . $id . "'";
1400
+            $sql .= " AND rowid = '".$id."'";
1401 1401
         }
1402 1402
 
1403 1403
         $res = Config::$dbEngine->select($sql);
@@ -1410,7 +1410,7 @@  discard block
 block discarded – undo
1410 1410
 
1411 1411
             return $cats;
1412 1412
         } else {
1413
-            $this->error = Config::$dbEngine->error() . ' sql=' . $sql;
1413
+            $this->error = Config::$dbEngine->error().' sql='.$sql;
1414 1414
             return -1;
1415 1415
         }
1416 1416
     }
@@ -1429,7 +1429,7 @@  discard block
 block discarded – undo
1429 1429
         global $langs;
1430 1430
 
1431 1431
         $result = '';
1432
-        $label = $langs->trans("ShowCategory") . ': ' . ($this->ref ? $this->ref : $this->label);
1432
+        $label = $langs->trans("ShowCategory").': '.($this->ref ? $this->ref : $this->label);
1433 1433
 
1434 1434
         // Check contrast with background and correct text color
1435 1435
         $forced_color = 'categtextwhite';
@@ -1438,18 +1438,18 @@  discard block
 block discarded – undo
1438 1438
                 $forced_color = 'categtextblack';
1439 1439
         }
1440 1440
 
1441
-        $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 . '">';
1441
+        $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.'">';
1442 1442
         $linkend = '</a>';
1443 1443
 
1444 1444
         $picto = 'category';
1445 1445
 
1446 1446
 
1447 1447
         if ($withpicto)
1448
-            $result .= ($link . img_object($label, $picto, 'class="classfortooltip"') . $linkend);
1448
+            $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend);
1449 1449
         if ($withpicto && $withpicto != 2)
1450 1450
             $result .= ' ';
1451 1451
         if ($withpicto != 2)
1452
-            $result .= $link . dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength) . $linkend;
1452
+            $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend;
1453 1453
         return $result;
1454 1454
     }
1455 1455
 
@@ -1464,9 +1464,9 @@  discard block
 block discarded – undo
1464 1464
     function add_photo($sdir, $file)
1465 1465
     {
1466 1466
         // phpcs:enable
1467
-        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1467
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1468 1468
 
1469
-        $dir = $sdir . '/' . get_exdir($this->id, 2, 0, 0, $this, 'category') . $this->id . "/";
1469
+        $dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, 'category').$this->id."/";
1470 1470
         $dir .= "photos/";
1471 1471
 
1472 1472
         if (!file_exists($dir)) {
@@ -1476,9 +1476,9 @@  discard block
 block discarded – undo
1476 1476
         if (file_exists($dir)) {
1477 1477
             if (is_array($file['name']) && count($file['name']) > 0) {
1478 1478
                 $nbfile = count($file['name']);
1479
-                for ($i = 0; $i <= $nbfile; $i ++) {
1479
+                for ($i = 0; $i <= $nbfile; $i++) {
1480 1480
 
1481
-                    $originImage = $dir . $file['name'][$i];
1481
+                    $originImage = $dir.$file['name'][$i];
1482 1482
 
1483 1483
                     // Cree fichier en taille origine
1484 1484
                     dol_move_uploaded_file($file['tmp_name'][$i], $originImage, 1, 0, 0);
@@ -1489,7 +1489,7 @@  discard block
 block discarded – undo
1489 1489
                     }
1490 1490
                 }
1491 1491
             } else {
1492
-                $originImage = $dir . $file['name'];
1492
+                $originImage = $dir.$file['name'];
1493 1493
 
1494 1494
                 // Cree fichier en taille origine
1495 1495
                 dol_move_uploaded_file($file['tmp_name'], $originImage, 1, 0, 0);
@@ -1513,32 +1513,32 @@  discard block
 block discarded – undo
1513 1513
     function liste_photos($dir, $nbmax = 0)
1514 1514
     {
1515 1515
         // phpcs:enable
1516
-        include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1516
+        include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1517 1517
 
1518 1518
         $nbphoto = 0;
1519 1519
         $tabobj = array();
1520 1520
 
1521
-        $dirthumb = $dir . 'thumbs/';
1521
+        $dirthumb = $dir.'thumbs/';
1522 1522
 
1523 1523
         if (file_exists($dir)) {
1524 1524
             $handle = opendir($dir);
1525 1525
             if (is_resource($handle)) {
1526 1526
                 while (($file = readdir($handle)) !== false) {
1527
-                    if (dol_is_file($dir . $file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir . $file)) {
1527
+                    if (dol_is_file($dir.$file) && preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $dir.$file)) {
1528 1528
                         $nbphoto++;
1529 1529
                         $photo = $file;
1530 1530
 
1531 1531
                         // On determine nom du fichier vignette
1532 1532
                         $photo_vignette = '';
1533 1533
                         if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $photo, $regs)) {
1534
-                            $photo_vignette = preg_replace('/' . $regs[0] . '/i', '', $photo) . '_small' . $regs[0];
1534
+                            $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
1535 1535
                         }
1536 1536
 
1537 1537
                         // Objet
1538 1538
                         $obj = array();
1539 1539
                         $obj['photo'] = $photo;
1540
-                        if ($photo_vignette && is_file($dirthumb . $photo_vignette))
1541
-                            $obj['photo_vignette'] = 'thumbs/' . $photo_vignette;
1540
+                        if ($photo_vignette && is_file($dirthumb.$photo_vignette))
1541
+                            $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
1542 1542
                         else
1543 1543
                             $obj['photo_vignette'] = "";
1544 1544
 
@@ -1567,19 +1567,19 @@  discard block
 block discarded – undo
1567 1567
     function delete_photo($file)
1568 1568
     {
1569 1569
         // phpcs:enable
1570
-        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
1570
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1571 1571
 
1572
-        $dir = dirname($file) . '/'; // Chemin du dossier contenant l'image d'origine
1573
-        $dirthumb = $dir . '/thumbs/'; // Chemin du dossier contenant la vignette
1574
-        $filename = preg_replace('/' . preg_quote($dir, '/') . '/i', '', $file); // Nom du fichier
1572
+        $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
1573
+        $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
1574
+        $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
1575 1575
         // On efface l'image d'origine
1576 1576
         dol_delete_file($file, 1);
1577 1577
 
1578 1578
         // Si elle existe, on efface la vignette
1579 1579
         if (preg_match('/(\.jpeg|\.jpg|\.bmp|\.gif|\.png|\.tiff)$/i', $filename, $regs)) {
1580
-            $photo_vignette = preg_replace('/' . $regs[0] . '/i', '', $filename) . '_small' . $regs[0];
1581
-            if (file_exists($dirthumb . $photo_vignette)) {
1582
-                dol_delete_file($dirthumb . $photo_vignette, 1);
1580
+            $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
1581
+            if (file_exists($dirthumb.$photo_vignette)) {
1582
+                dol_delete_file($dirthumb.$photo_vignette, 1);
1583 1583
             }
1584 1584
         }
1585 1585
     }
@@ -1615,43 +1615,43 @@  discard block
 block discarded – undo
1615 1615
 
1616 1616
         foreach ($langs_available as $key => $value) {
1617 1617
             $sql = "SELECT rowid";
1618
-            $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_lang";
1619
-            $sql .= " WHERE fk_category=" . $this->id;
1620
-            $sql .= " AND lang='" . $key . "'";
1618
+            $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1619
+            $sql .= " WHERE fk_category=".$this->id;
1620
+            $sql .= " AND lang='".$key."'";
1621 1621
 
1622 1622
             $result = Config::$dbEngine->select($sql);
1623 1623
 
1624 1624
             if ($key == $current_lang) {
1625 1625
                 if (Config::$dbEngine->num_rows($result)) { // si aucune ligne dans la base{
1626
-                    $sql2 = "UPDATE " . MAIN_DB_PREFIX . "categorie_lang";
1627
-                    $sql2 .= " SET label='" . Config::$dbEngine->escape($this->label) . "',";
1628
-                    $sql2 .= " description='" . Config::$dbEngine->escape($this->description) . "'";
1629
-                    $sql2 .= " WHERE fk_category=" . $this->id . " AND lang='" . Config::$dbEngine->escape($key) . "'";
1626
+                    $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
1627
+                    $sql2 .= " SET label='".Config::$dbEngine->escape($this->label)."',";
1628
+                    $sql2 .= " description='".Config::$dbEngine->escape($this->description)."'";
1629
+                    $sql2 .= " WHERE fk_category=".$this->id." AND lang='".Config::$dbEngine->escape($key)."'";
1630 1630
                 } else {
1631
-                    $sql2 = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_lang (fk_category, lang, label, description)";
1632
-                    $sql2 .= " VALUES(" . $this->id . ",'" . $key . "','" . Config::$dbEngine->escape($this->label);
1633
-                    $sql2 .= "','" . Config::$dbEngine->escape($this->multilangs["$key"]["description"]) . "')";
1631
+                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
1632
+                    $sql2 .= " VALUES(".$this->id.",'".$key."','".Config::$dbEngine->escape($this->label);
1633
+                    $sql2 .= "','".Config::$dbEngine->escape($this->multilangs["$key"]["description"])."')";
1634 1634
                 }
1635
-                dol_syslog(get_class($this) . '::setMultiLangs', LOG_DEBUG);
1635
+                dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
1636 1636
                 if (!Config::$dbEngine->query($sql2)) {
1637 1637
                     $this->error = Config::$dbEngine->lasterror();
1638 1638
                     return -1;
1639 1639
                 }
1640 1640
             } else if (isset($this->multilangs["$key"])) {
1641 1641
                 if (Config::$dbEngine->num_rows($result)) { // si aucune ligne dans la base{
1642
-                    $sql2 = "UPDATE " . MAIN_DB_PREFIX . "categorie_lang";
1643
-                    $sql2 .= " SET label='" . Config::$dbEngine->escape($this->multilangs["$key"]["label"]) . "',";
1644
-                    $sql2 .= " description='" . Config::$dbEngine->escape($this->multilangs["$key"]["description"]) . "'";
1645
-                    $sql2 .= " WHERE fk_category=" . $this->id . " AND lang='" . Config::$dbEngine->escape($key) . "'";
1642
+                    $sql2 = "UPDATE ".MAIN_DB_PREFIX."categorie_lang";
1643
+                    $sql2 .= " SET label='".Config::$dbEngine->escape($this->multilangs["$key"]["label"])."',";
1644
+                    $sql2 .= " description='".Config::$dbEngine->escape($this->multilangs["$key"]["description"])."'";
1645
+                    $sql2 .= " WHERE fk_category=".$this->id." AND lang='".Config::$dbEngine->escape($key)."'";
1646 1646
                 } else {
1647
-                    $sql2 = "INSERT INTO " . MAIN_DB_PREFIX . "categorie_lang (fk_category, lang, label, description)";
1648
-                    $sql2 .= " VALUES(" . $this->id . ",'" . $key . "','" . Config::$dbEngine->escape($this->multilangs["$key"]["label"]);
1649
-                    $sql2 .= "','" . Config::$dbEngine->escape($this->multilangs["$key"]["description"]) . "')";
1647
+                    $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."categorie_lang (fk_category, lang, label, description)";
1648
+                    $sql2 .= " VALUES(".$this->id.",'".$key."','".Config::$dbEngine->escape($this->multilangs["$key"]["label"]);
1649
+                    $sql2 .= "','".Config::$dbEngine->escape($this->multilangs["$key"]["description"])."')";
1650 1650
                 }
1651 1651
 
1652 1652
                 // on ne sauvegarde pas des champs vides
1653 1653
                 if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"])
1654
-                    dol_syslog(get_class($this) . '::setMultiLangs', LOG_DEBUG);
1654
+                    dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG);
1655 1655
                 if (!Config::$dbEngine->query($sql2)) {
1656 1656
                     $this->error = Config::$dbEngine->lasterror();
1657 1657
                     return -1;
@@ -1682,8 +1682,8 @@  discard block
 block discarded – undo
1682 1682
         $current_lang = $langs->getDefaultLang();
1683 1683
 
1684 1684
         $sql = "SELECT lang, label, description";
1685
-        $sql .= " FROM " . MAIN_DB_PREFIX . "categorie_lang";
1686
-        $sql .= " WHERE fk_category=" . $this->id;
1685
+        $sql .= " FROM ".MAIN_DB_PREFIX."categorie_lang";
1686
+        $sql .= " WHERE fk_category=".$this->id;
1687 1687
 
1688 1688
         $result = Config::$dbEngine->select($sql);
1689 1689
         if ($result) {
@@ -1698,7 +1698,7 @@  discard block
 block discarded – undo
1698 1698
             }
1699 1699
             return 1;
1700 1700
         } else {
1701
-            $this->error = $langs->trans("Error") . " : " . Config::$dbEngine->error() . " - " . $sql;
1701
+            $this->error = $langs->trans("Error")." : ".Config::$dbEngine->error()." - ".$sql;
1702 1702
             return -1;
1703 1703
         }
1704 1704
     }
@@ -1723,7 +1723,7 @@  discard block
 block discarded – undo
1723 1723
      */
1724 1724
     function initAsSpecimen()
1725 1725
     {
1726
-        dol_syslog(get_class($this) . "::initAsSpecimen");
1726
+        dol_syslog(get_class($this)."::initAsSpecimen");
1727 1727
 
1728 1728
         // Initialise parametres
1729 1729
         $this->id = 0;
Please login to merge, or discard this patch.
Braces   +58 added lines, -40 removed lines patch added patch discarded remove patch
@@ -509,8 +509,9 @@  discard block
 block discarded – undo
509 509
         if (!$error && !$notrigger) {
510 510
             // Call trigger
511 511
             $result = $this->call_trigger('CATEGORY_DELETE', $user);
512
-            if ($result < 0)
513
-                $error++;
512
+            if ($result < 0) {
513
+                            $error++;
514
+            }
514 515
             // End call triggers
515 516
         }
516 517
 
@@ -580,8 +581,9 @@  discard block
 block discarded – undo
580 581
 
581 582
         $error = 0;
582 583
 
583
-        if ($this->id == -1)
584
-            return -2;
584
+        if ($this->id == -1) {
585
+                    return -2;
586
+        }
585 587
 
586 588
         Config::$dbEngine->begin();
587 589
 
@@ -1089,15 +1091,18 @@  discard block
 block discarded – undo
1089 1091
     function get_all_categories($type = null, $parent = false)
1090 1092
     {
1091 1093
         // phpcs:enable
1092
-        if (!is_numeric($type))
1093
-            $type = $this->MAP_ID[$type];
1094
+        if (!is_numeric($type)) {
1095
+                    $type = $this->MAP_ID[$type];
1096
+        }
1094 1097
 
1095 1098
         $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "categorie";
1096 1099
         $sql .= " WHERE entity IN (" . getEntity('category') . ")";
1097
-        if (!is_null($type))
1098
-            $sql .= " AND type = " . $type;
1099
-        if ($parent)
1100
-            $sql .= " AND fk_parent = 0";
1100
+        if (!is_null($type)) {
1101
+                    $sql .= " AND type = " . $type;
1102
+        }
1103
+        if ($parent) {
1104
+                    $sql .= " AND fk_parent = 0";
1105
+        }
1101 1106
 
1102 1107
         $res = Config::$dbEngine->select($sql);
1103 1108
         if ($res) {
@@ -1125,8 +1130,9 @@  discard block
 block discarded – undo
1125 1130
         // phpcs:enable
1126 1131
         $type = $this->type;
1127 1132
 
1128
-        if (!is_numeric($type))
1129
-            $type = $this->MAP_ID[$type];
1133
+        if (!is_numeric($type)) {
1134
+                    $type = $this->MAP_ID[$type];
1135
+        }
1130 1136
 
1131 1137
         /* We have to select any rowid from llx_categorie which category's mother and label
1132 1138
          * are equals to those of the calling category
@@ -1203,8 +1209,9 @@  discard block
 block discarded – undo
1203 1209
                         // Check contrast with background and correct text color
1204 1210
                         $forced_color = 'categtextwhite';
1205 1211
                         if ($cat->color) {
1206
-                            if (colorIsLight($cat->color))
1207
-                                $forced_color = 'categtextblack';
1212
+                            if (colorIsLight($cat->color)) {
1213
+                                                            $forced_color = 'categtextblack';
1214
+                            }
1208 1215
                         }
1209 1216
                     }
1210 1217
                 }
@@ -1280,8 +1287,9 @@  discard block
 block discarded – undo
1280 1287
             }
1281 1288
         }
1282 1289
 
1283
-        if (count($ways) == 0)
1284
-            $ways[0][0] = $this;
1290
+        if (count($ways) == 0) {
1291
+                    $ways[0][0] = $this;
1292
+        }
1285 1293
 
1286 1294
         return $ways;
1287 1295
     }
@@ -1300,8 +1308,9 @@  discard block
 block discarded – undo
1300 1308
     {
1301 1309
         $cats = array();
1302 1310
 
1303
-        if (is_numeric($type))
1304
-            $type = Categorie::$MAP_ID_TO_CODE[$type];
1311
+        if (is_numeric($type)) {
1312
+                    $type = Categorie::$MAP_ID_TO_CODE[$type];
1313
+        }
1305 1314
 
1306 1315
         if ($type === Categorie::TYPE_BANK_LINE) {   // TODO Remove this with standard category code
1307 1316
             // Load bank groups
@@ -1389,12 +1398,14 @@  discard block
 block discarded – undo
1389 1398
         $sql .= " WHERE type = " . $this->MAP_ID[$type];
1390 1399
         $sql .= " AND entity IN (" . getEntity('category') . ")";
1391 1400
         if ($nom) {
1392
-            if (!$exact)
1393
-                $nom = '%' . str_replace('*', '%', $nom) . '%';
1394
-            if (!$case)
1395
-                $sql .= " AND label LIKE '" . Config::$dbEngine->escape($nom) . "'";
1396
-            else
1397
-                $sql .= " AND label LIKE BINARY '" . Config::$dbEngine->escape($nom) . "'";
1401
+            if (!$exact) {
1402
+                            $nom = '%' . str_replace('*', '%', $nom) . '%';
1403
+            }
1404
+            if (!$case) {
1405
+                            $sql .= " AND label LIKE '" . Config::$dbEngine->escape($nom) . "'";
1406
+            } else {
1407
+                            $sql .= " AND label LIKE BINARY '" . Config::$dbEngine->escape($nom) . "'";
1408
+            }
1398 1409
         }
1399 1410
         if ($id) {
1400 1411
             $sql .= " AND rowid = '" . $id . "'";
@@ -1434,8 +1445,9 @@  discard block
 block discarded – undo
1434 1445
         // Check contrast with background and correct text color
1435 1446
         $forced_color = 'categtextwhite';
1436 1447
         if ($this->color) {
1437
-            if (colorIsLight($this->color))
1438
-                $forced_color = 'categtextblack';
1448
+            if (colorIsLight($this->color)) {
1449
+                            $forced_color = 'categtextblack';
1450
+            }
1439 1451
         }
1440 1452
 
1441 1453
         $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 . '">';
@@ -1444,12 +1456,15 @@  discard block
 block discarded – undo
1444 1456
         $picto = 'category';
1445 1457
 
1446 1458
 
1447
-        if ($withpicto)
1448
-            $result .= ($link . img_object($label, $picto, 'class="classfortooltip"') . $linkend);
1449
-        if ($withpicto && $withpicto != 2)
1450
-            $result .= ' ';
1451
-        if ($withpicto != 2)
1452
-            $result .= $link . dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength) . $linkend;
1459
+        if ($withpicto) {
1460
+                    $result .= ($link . img_object($label, $picto, 'class="classfortooltip"') . $linkend);
1461
+        }
1462
+        if ($withpicto && $withpicto != 2) {
1463
+                    $result .= ' ';
1464
+        }
1465
+        if ($withpicto != 2) {
1466
+                    $result .= $link . dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength) . $linkend;
1467
+        }
1453 1468
         return $result;
1454 1469
     }
1455 1470
 
@@ -1537,16 +1552,18 @@  discard block
 block discarded – undo
1537 1552
                         // Objet
1538 1553
                         $obj = array();
1539 1554
                         $obj['photo'] = $photo;
1540
-                        if ($photo_vignette && is_file($dirthumb . $photo_vignette))
1541
-                            $obj['photo_vignette'] = 'thumbs/' . $photo_vignette;
1542
-                        else
1543
-                            $obj['photo_vignette'] = "";
1555
+                        if ($photo_vignette && is_file($dirthumb . $photo_vignette)) {
1556
+                                                    $obj['photo_vignette'] = 'thumbs/' . $photo_vignette;
1557
+                        } else {
1558
+                                                    $obj['photo_vignette'] = "";
1559
+                        }
1544 1560
 
1545 1561
                         $tabobj[$nbphoto - 1] = $obj;
1546 1562
 
1547 1563
                         // On continue ou on arrete de boucler
1548
-                        if ($nbmax && $nbphoto >= $nbmax)
1549
-                            break;
1564
+                        if ($nbmax && $nbphoto >= $nbmax) {
1565
+                                                    break;
1566
+                        }
1550 1567
                     }
1551 1568
                 }
1552 1569
 
@@ -1650,8 +1667,9 @@  discard block
 block discarded – undo
1650 1667
                 }
1651 1668
 
1652 1669
                 // on ne sauvegarde pas des champs vides
1653
-                if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"])
1654
-                    dol_syslog(get_class($this) . '::setMultiLangs', LOG_DEBUG);
1670
+                if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) {
1671
+                                    dol_syslog(get_class($this) . '::setMultiLangs', LOG_DEBUG);
1672
+                }
1655 1673
                 if (!Config::$dbEngine->query($sql2)) {
1656 1674
                     $this->error = Config::$dbEngine->lasterror();
1657 1675
                     return -1;
Please login to merge, or discard this patch.
Helpers/DolUtils.php 2 patches
Spacing   +532 added lines, -532 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
      */
53 53
     static function getStaticMember($class, $member)
54 54
     {
55
-        DolUtils::dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
55
+        DolUtils::dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
56 56
 
57 57
         // This part is deprecated. Uncomment if for php 5.2.*, and comment next isset class::member
58 58
         /* if (version_compare(phpversion(), '5.3.0', '<'))
@@ -77,7 +77,7 @@  discard block
 block discarded – undo
77 77
 
78 78
         if (isset($class::$member))
79 79
             return $class::$member;
80
-        dol_print_error('', 'Try to get a static member "' . $member . '" in class "' . $class . '" that does not exists or is not static.');
80
+        dol_print_error('', 'Try to get a static member "'.$member.'" in class "'.$class.'" that does not exists or is not static.');
81 81
         return null;
82 82
     }
83 83
 
@@ -94,9 +94,9 @@  discard block
 block discarded – undo
94 94
      */
95 95
     static function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
96 96
     {
97
-        require_once DOL_BASE_PATH . "/core/db/" . $type . '.class.php';
97
+        require_once DOL_BASE_PATH."/core/db/".$type.'.class.php';
98 98
 
99
-        $class = 'DoliDB' . ucfirst($type);
99
+        $class = 'DoliDB'.ucfirst($type);
100 100
         $dolidb = new $class($type, $host, $user, $pass, $name, $port);
101 101
         return $dolidb;
102 102
     }
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
             $depth = $db->transaction_opened;
266 266
             $disconnectdone = $db->close();
267 267
         }
268
-        DolUtils::dol_syslog("--- End access to " . $_SERVER["PHP_SELF"] . (($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was ' . $depth . ')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
268
+        DolUtils::dol_syslog("--- End access to ".$_SERVER["PHP_SELF"].(($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was '.$depth.')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
269 269
     }
270 270
 
271 271
     /**
@@ -310,7 +310,7 @@  discard block
 block discarded – undo
310 310
         if (empty($paramname))
311 311
             return 'BadFirstParameterForDolUtils::GETPOST';
312 312
         if (empty($check)) {
313
-            DolUtils::dol_syslog("Deprecated use of DolUtils::GETPOST, called with 1st param = " . $paramname . " and 2nd param is '', when calling page " . $_SERVER["PHP_SELF"], LOG_WARNING);
313
+            DolUtils::dol_syslog("Deprecated use of DolUtils::GETPOST, called with 1st param = ".$paramname." and 2nd param is '', when calling page ".$_SERVER["PHP_SELF"], LOG_WARNING);
314 314
             // Enable this line to know who call the DolUtils::GETPOST with '' $check parameter.
315 315
             //var_dump(debug_backtrace()[0]);
316 316
         }
@@ -332,7 +332,7 @@  discard block
 block discarded – undo
332 332
             $relativepathstring = $_SERVER["PHP_SELF"];
333 333
             // Clean $relativepathstring
334 334
             if (constant('DOL_BASE_URI'))
335
-                $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
335
+                $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
336 336
             $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
337 337
             $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
338 338
             //var_dump($relativepathstring);
@@ -340,8 +340,8 @@  discard block
 block discarded – undo
340 340
             // Code for search criteria persistence.
341 341
             // Retrieve values if restore_lastsearch_values
342 342
             if (!empty($_GET['restore_lastsearch_values'])) {        // Use $_GET here and not DolUtils::GETPOST
343
-                if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
344
-                    $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
343
+                if (!empty($_SESSION['lastsearch_values_'.$relativepathstring])) { // If there is saved values
344
+                    $tmp = json_decode($_SESSION['lastsearch_values_'.$relativepathstring], true);
345 345
                     if (is_array($tmp)) {
346 346
                         foreach ($tmp as $key => $val) {
347 347
                             if ($key == $paramname) { // We are on the requested parameter
@@ -352,12 +352,12 @@  discard block
 block discarded – undo
352 352
                     }
353 353
                 }
354 354
                 // If there is saved contextpage, page or limit
355
-                if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
356
-                    $out = $_SESSION['lastsearch_contextpage_' . $relativepathstring];
357
-                } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
358
-                    $out = $_SESSION['lastsearch_page_' . $relativepathstring];
359
-                } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
360
-                    $out = $_SESSION['lastsearch_limit_' . $relativepathstring];
355
+                if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_'.$relativepathstring])) {
356
+                    $out = $_SESSION['lastsearch_contextpage_'.$relativepathstring];
357
+                } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_'.$relativepathstring])) {
358
+                    $out = $_SESSION['lastsearch_page_'.$relativepathstring];
359
+                } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_'.$relativepathstring])) {
360
+                    $out = $_SESSION['lastsearch_limit_'.$relativepathstring];
361 361
                 }
362 362
             }
363 363
             // Else, retreive default values if we are not doing a sort
@@ -425,7 +425,7 @@  discard block
 block discarded – undo
425 425
                                             $qualified = 1;
426 426
 
427 427
                                         if ($qualified) {
428
-                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
428
+                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
429 429
                                             foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
430 430
                                                 if ($out)
431 431
                                                     $out .= ', ';
@@ -461,11 +461,11 @@  discard block
 block discarded – undo
461 461
                                         if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
462 462
                                             // We made a search from quick search menu, do we still use default filter ?
463 463
                                             if (empty(Globals::$conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
464
-                                                $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
464
+                                                $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
465 465
                                                 $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
466 466
                                             }
467 467
                                         } else {
468
-                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
468
+                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "="); // we accept _, -, . and ,
469 469
                                             $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
470 470
                                         }
471 471
                                         break;
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
         // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
484 484
         if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
485 485
             $maxloop = 20;
486
-            $loopnb = 0;    // Protection against infinite loop
486
+            $loopnb = 0; // Protection against infinite loop
487 487
             while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) {    // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
488 488
                 $loopnb++;
489 489
                 $newout = '';
@@ -528,7 +528,7 @@  discard block
 block discarded – undo
528 528
                 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
529 529
                     $newout = Globals::$conf->entity;
530 530
                 } else
531
-                    $newout = '';     // Key not found, we replace with empty string
531
+                    $newout = ''; // Key not found, we replace with empty string
532 532
 
533 533
 
534 534
 
@@ -573,7 +573,7 @@  discard block
 block discarded – undo
573 573
 
574 574
                     
575 575
 //var_dump('__'.$reg[1].'__ -> '.$newout);
576
-                $out = preg_replace('/__' . preg_quote($reg[1], '/') . '__/', $newout, $out);
576
+                $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
577 577
             }
578 578
         }
579 579
 
@@ -683,7 +683,7 @@  discard block
 block discarded – undo
683 683
         // If prefix is for email
684 684
         if ($mode == 'email') {
685 685
             if (empty(Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) {
686
-                return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
686
+                return Security::dol_hash(DOL_DOCUMENT_ROOT.DOL_BASE_URI);
687 687
             }
688 688
             // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
689 689
             if (Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
@@ -693,16 +693,16 @@  discard block
 block discarded – undo
693 693
                 return $_SERVER["SERVER_NAME"];
694 694
             }
695 695
 
696
-            return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
696
+            return Security::dol_hash(DOL_DOCUMENT_ROOT.DOL_BASE_URI);
697 697
         }
698 698
 
699 699
         if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
700
-            return Security::dol_hash($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_BASE_URI);
700
+            return Security::dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_BASE_URI);
701 701
 
702 702
             // Use this for a "readable" cookie name
703 703
             //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_BASE_URI);
704 704
         }
705
-        return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
705
+        return Security::dol_hash(DOL_DOCUMENT_ROOT.DOL_BASE_URI);
706 706
     }
707 707
 
708 708
     /**
@@ -722,7 +722,7 @@  discard block
 block discarded – undo
722 722
         $fullpath = dol_buildpath($relpath);
723 723
 
724 724
         if (!file_exists($fullpath)) {
725
-            DolUtils::dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_ERR);
725
+            DolUtils::dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
726 726
             return false;
727 727
         }
728 728
 
@@ -751,14 +751,14 @@  discard block
 block discarded – undo
751 751
 
752 752
         if ($type == 0 /* empty($type) */) { // For a filesystem path
753 753
 //$res = DOL_BASE_PATH . '' . $path;  // Standard default path
754
-            $res = DOL_BASE_PATH . '/' . $path;  // Standard default path
754
+            $res = DOL_BASE_PATH.'/'.$path; // Standard default path
755 755
             if (isset(Globals::$conf->file->dol_document_root)) {
756 756
                 foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
757 757
                     if ($key == 'main') {
758 758
                         continue;
759 759
                     }
760
-                    if (file_exists($dirroot . '/' . $path)) {
761
-                        $res = $dirroot . '/' . $path;
760
+                    if (file_exists($dirroot.'/'.$path)) {
761
+                        $res = $dirroot.'/'.$path;
762 762
                         return $res;
763 763
                     }
764 764
                 }
@@ -775,13 +775,13 @@  discard block
 block discarded – undo
775 775
 // using proxy, rewriting, virtual path, etc...
776 776
             $res = '';
777 777
             if ($type == 1) {
778
-                $res = /* DOL_BASE_URI */ DOL_BASE_URI . '/' . $path;   // Standard value
778
+                $res = /* DOL_BASE_URI */ DOL_BASE_URI.'/'.$path; // Standard value
779 779
             }
780 780
             if ($type == 2) {
781
-                $res = /* DOL_MAIN_URL_ROOT */ DOL_BASE_PATH . '/' . $path;  // Standard value
781
+                $res = /* DOL_MAIN_URL_ROOT */ DOL_BASE_PATH.'/'.$path; // Standard value
782 782
             }
783 783
             if ($type == 3) {
784
-                $res = DOL_BASE_URI . '/' . $path;
784
+                $res = DOL_BASE_URI.'/'.$path;
785 785
             }
786 786
 
787 787
             foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
@@ -790,33 +790,33 @@  discard block
 block discarded – undo
790 790
                         // global $dolibarr_main_url_root;
791 791
                         // Define $urlwithroot
792 792
                         // $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
793
-                        $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim(DOL_BASE_URI));
793
+                        $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_BASE_URI, '/').'$/i', '', trim(DOL_BASE_URI));
794 794
 
795
-                        $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
795
+                        $urlwithroot = $urlwithouturlroot.DOL_BASE_URI; // This is to use external domain name found into config file
796 796
                         //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
797 797
 
798
-                        $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path;     // Test on start with http is for old conf syntax
798
+                        $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
799 799
                     }
800 800
                     continue;
801 801
                 }
802
-                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs);    // Take part before '?'
802
+                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
803 803
                 if (!empty($regs[1])) {
804 804
                     //print $key.'-'.$dirroot.'/'.$path.'-'.Globals::$conf->file->dol_url_root[$type].'<br>'."\n";
805
-                    if (file_exists($dirroot . '/' . $regs[1])) {
805
+                    if (file_exists($dirroot.'/'.$regs[1])) {
806 806
                         if ($type == 1) {
807
-                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_BASE_URI) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
807
+                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_BASE_URI).Globals::$conf->file->dol_url_root[$key].'/'.$path;
808 808
                         }
809 809
                         if ($type == 2) {
810
-                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
810
+                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).Globals::$conf->file->dol_url_root[$key].'/'.$path;
811 811
                         }
812 812
                         if ($type == 3) {
813 813
                             // global $dolibarr_main_url_root;
814 814
                             // Define $urlwithroot
815
-                            $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
816
-                            $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
815
+                            $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_BASE_URI, '/').'$/i', '', trim($dolibarr_main_url_root));
816
+                            $urlwithroot = $urlwithouturlroot.DOL_BASE_URI; // This is to use external domain name found into config file
817 817
                             //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
818 818
 
819
-                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;     // Test on start with http is for old conf syntax
819
+                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot).Globals::$conf->file->dol_url_root[$key].'/'.$path; // Test on start with http is for old conf syntax
820 820
                         }
821 821
                         break;
822 822
                     }
@@ -844,7 +844,7 @@  discard block
 block discarded – undo
844 844
         if (empty($native)) {
845 845
             $myclone = unserialize(serialize($object));
846 846
         } else {
847
-            $myclone = clone $object;     // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable)
847
+            $myclone = clone $object; // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable)
848 848
         }
849 849
 
850 850
         return $myclone;
@@ -965,7 +965,7 @@  discard block
 block discarded – undo
965 965
      */
966 966
     static function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
967 967
     {
968
-        $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°');  // more complete than dol_sanitizeFileName
968
+        $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
969 969
         $forbidden_chars_to_remove = array();
970 970
         if (is_array($badcharstoreplace))
971 971
             $forbidden_chars_to_replace = $badcharstoreplace;
@@ -1028,12 +1028,12 @@  discard block
 block discarded – undo
1028 1028
     static function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0)
1029 1029
     {
1030 1030
 // escape quotes and backslashes, newlines, etc.
1031
-        $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');  // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1031
+        $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1032 1032
         if (!$keepb)
1033 1033
             $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1034 1034
         if (!$keepn)
1035 1035
             $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1036
-        return htmlentities($tmp, ENT_COMPAT, 'UTF-8');      // TODO Use htmlspecialchars instead, that make only required change for html tags
1036
+        return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags
1037 1037
     }
1038 1038
 
1039 1039
     /**
@@ -1103,14 +1103,14 @@  discard block
 block discarded – undo
1103 1103
             $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1104 1104
 // If adding log inside HTML page is required
1105 1105
             if (!empty($_REQUEST['logtohtml']) && (!empty(Globals::$conf->global->MAIN_ENABLE_LOG_TO_HTML) || !empty(Globals::$conf->global->MAIN_LOGTOHTML))) {   // MAIN_LOGTOHTML kept for backward compatibility
1106
-                Globals::$conf->logbuffer[] = DolUtils::dol_print_date(time(), "%Y-%m-%d %H:%M:%S") . " " . $message;
1106
+                Globals::$conf->logbuffer[] = DolUtils::dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$message;
1107 1107
             }
1108 1108
 
1109 1109
 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
1110 1110
 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
1111 1111
             if (!empty(Globals::$conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
1112 1112
                 print "\n\n<!-- Log start\n";
1113
-                print $message . "\n";
1113
+                print $message."\n";
1114 1114
                 print "Log end -->\n";
1115 1115
             }
1116 1116
 
@@ -1124,7 +1124,7 @@  discard block
 block discarded – undo
1124 1124
 
1125 1125
 // This is when server run behind a reverse proxy
1126 1126
             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
1127
-                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1127
+                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"]) ? '' : '->'.$_SERVER['REMOTE_ADDR']);
1128 1128
 // This is when server run normally on a server
1129 1129
             else if (!empty($_SERVER["REMOTE_ADDR"]))
1130 1130
                 $data['ip'] = $_SERVER['REMOTE_ADDR'];
@@ -1133,10 +1133,10 @@  discard block
 block discarded – undo
1133 1133
                 $data['ip'] = $_SERVER['SERVER_ADDR'];
1134 1134
 // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
1135 1135
             else if (!empty($_SERVER['COMPUTERNAME']))
1136
-                $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1136
+                $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
1137 1137
 // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
1138 1138
             else if (!empty($_SERVER['LOGNAME']))
1139
-                $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1139
+                $data['ip'] = '???@'.$_SERVER['LOGNAME'];
1140 1140
 // Loop on each log handler and send output
1141 1141
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
1142 1142
                 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler)
@@ -1188,10 +1188,10 @@  discard block
 block discarded – undo
1188 1188
     {
1189 1189
         // global Globals::$conf, Globals::$langs, Globals::$hookManager;
1190 1190
 
1191
-        $out = "\n" . '<div class="tabs" data-role="controlgroup" data-type="horizontal">' . "\n";
1191
+        $out = "\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
1192 1192
 
1193 1193
         if ($morehtmlright) {
1194
-            $out .= '<div class="inline-block floatright tabsElem">' . $morehtmlright . '</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
1194
+            $out .= '<div class="inline-block floatright tabsElem">'.$morehtmlright.'</div>'; // Output right area first so when space is missing, text is in front of tabs and not under.
1195 1195
         }
1196 1196
 
1197 1197
 // Show title
@@ -1202,8 +1202,8 @@  discard block
 block discarded – undo
1202 1202
             $limittitle = 30;
1203 1203
             $out .= '<a class="tabTitle">';
1204 1204
             if ($picto)
1205
-                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1206
-            $out .= '<span class="tabTitleText">' . dol_trunc($title, $limittitle) . '</span>';
1205
+                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath).' ';
1206
+            $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
1207 1207
             $out .= '</a>';
1208 1208
         }
1209 1209
 
@@ -1243,23 +1243,23 @@  discard block
 block discarded – undo
1243 1243
             }
1244 1244
 
1245 1245
             if ($i < $limittoshow || $isactive) {
1246
-                $out .= '<div class="inline-block tabsElem' . ($isactive ? ' tabsElemActive' : '') . ((!$isactive && !empty(Globals::$conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '') . '"><!-- id tab = ' . (empty($links[$i][2]) ? '' : $links[$i][2]) . ' -->';
1246
+                $out .= '<div class="inline-block tabsElem'.($isactive ? ' tabsElemActive' : '').((!$isactive && !empty(Globals::$conf->global->MAIN_HIDE_INACTIVETAB_ON_PRINT)) ? ' hideonprint' : '').'"><!-- id tab = '.(empty($links[$i][2]) ? '' : $links[$i][2]).' -->';
1247 1247
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1248 1248
                     if (!empty($links[$i][0])) {
1249
-                        $out .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1249
+                        $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
1250 1250
                     } else {
1251
-                        $out .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1251
+                        $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
1252 1252
                     }
1253 1253
                 } else if (!empty($links[$i][1])) {
1254 1254
                     //print "x $i $active ".$links[$i][2]." z";
1255 1255
                     if ($isactive) {
1256
-                        $out .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="tabactive tab inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1256
+                        $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1257 1257
                         $out .= $links[$i][1];
1258
-                        $out .= '</a>' . "\n";
1258
+                        $out .= '</a>'."\n";
1259 1259
                     } else {
1260
-                        $out .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="tabunactive tab inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1260
+                        $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1261 1261
                         $out .= $links[$i][1];
1262
-                        $out .= '</a>' . "\n";
1262
+                        $out .= '</a>'."\n";
1263 1263
                     }
1264 1264
                 }
1265 1265
                 $out .= '</div>';
@@ -1272,14 +1272,14 @@  discard block
 block discarded – undo
1272 1272
                 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
1273 1273
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1274 1274
                     if (!empty($links[$i][0]))
1275
-                        $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1275
+                        $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
1276 1276
                     else
1277
-                        $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1277
+                        $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
1278 1278
                 }
1279 1279
                 else if (!empty($links[$i][1])) {
1280
-                    $outmore .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1280
+                    $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1281 1281
                     $outmore .= preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts.
1282
-                    $outmore .= '</a>' . "\n";
1282
+                    $outmore .= '</a>'."\n";
1283 1283
                 }
1284 1284
                 $outmore .= '</div>';
1285 1285
 
@@ -1295,24 +1295,24 @@  discard block
 block discarded – undo
1295 1295
             $right = (Globals::$langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
1296 1296
 
1297 1297
             $tabsname = str_replace("@", "", $picto);
1298
-            $out .= '<div id="moretabs' . $tabsname . '" class="inline-block tabsElem">';
1299
-            $out .= '<a href="#" class="tab moretab inline-block tabunactive reposition">' . Globals::$langs->trans("More") . '... (' . $nbintab . ')</a>';
1300
-            $out .= '<div id="moretabsList' . $tabsname . '" style="position: absolute; ' . $left . ': -999em; text-align: ' . $left . '; margin:0px; padding:2px">';
1298
+            $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
1299
+            $out .= '<a href="#" class="tab moretab inline-block tabunactive reposition">'.Globals::$langs->trans("More").'... ('.$nbintab.')</a>';
1300
+            $out .= '<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px">';
1301 1301
             $out .= $outmore;
1302 1302
             $out .= '</div>';
1303 1303
             $out .= '<div></div>';
1304 1304
             $out .= "</div>\n";
1305 1305
 
1306 1306
             $out .= "<script>";
1307
-            $out .= "$('#moretabs" . $tabsname . "').mouseenter( function() { console.log('mouseenter " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','auto');});";
1308
-            $out .= "$('#moretabs" . $tabsname . "').mouseleave( function() { console.log('mouseleave " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','-999em');});";
1307
+            $out .= "$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
1308
+            $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
1309 1309
             $out .= "</script>";
1310 1310
         }
1311 1311
 
1312 1312
         $out .= "</div>\n";
1313 1313
 
1314 1314
         if (!$notab || $notab == -1)
1315
-            $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1315
+            $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
1316 1316
 
1317 1317
         $parameters = array('tabname' => $active, 'out' => $out);
1318 1318
         $reshook = Globals::$hookManager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
@@ -1436,7 +1436,7 @@  discard block
 block discarded – undo
1436 1436
                 $maxvisiblephotos = 1;
1437 1437
             }
1438 1438
             if ($showimage) {
1439
-                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $object->show_photos('product', Globals::$conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0) . '</div>';
1439
+                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('product', Globals::$conf->product->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'</div>';
1440 1440
             } else {
1441 1441
                 if (!empty(Globals::$conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
1442 1442
                     $nophoto = '';
@@ -1445,19 +1445,19 @@  discard block
 block discarded – undo
1445 1445
 //elseif (Globals::$conf->browser->layout != 'phone') {    // Show no photo link
1446 1446
                 $nophoto = '/public/theme/common/nophoto.png';
1447 1447
 // $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="No photo" border="0"' . ($width ? ' width="' . $width . '"' : '') . ' src="' . DOL_BASE_URI . $nophoto . '"></div>';
1448
-                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="No photo" border="0"' . ($width ? ' width="' . $width . '"' : '') . ' src="' . DOL_BASE_URI . $nophoto . '"></div>';
1448
+                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' width="'.$width.'"' : '').' src="'.DOL_BASE_URI.$nophoto.'"></div>';
1449 1449
 //}
1450 1450
             }
1451 1451
         } elseif ($object->element == 'ticket') {
1452 1452
             $width = 80;
1453 1453
             $cssclass = 'photoref';
1454
-            $showimage = $object->is_photo_available(Globals::$conf->ticket->multidir_output[$entity] . '/' . $object->track_id);
1454
+            $showimage = $object->is_photo_available(Globals::$conf->ticket->multidir_output[$entity].'/'.$object->track_id);
1455 1455
             $maxvisiblephotos = (isset(Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO) ? Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO : 2);
1456 1456
             if (Globals::$conf->browser->layout == 'phone') {
1457 1457
                 $maxvisiblephotos = 1;
1458 1458
             }
1459 1459
             if ($showimage) {
1460
-                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $object->show_photos('ticket', Globals::$conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0) . '</div>';
1460
+                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$object->show_photos('ticket', Globals::$conf->ticket->multidir_output[$entity], 'small', $maxvisiblephotos, 0, 0, 0, $width, 0).'</div>';
1461 1461
             } else {
1462 1462
                 if (!empty(Globals::$conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
1463 1463
                     $nophoto = '';
@@ -1466,7 +1466,7 @@  discard block
 block discarded – undo
1466 1466
 //elseif (Globals::$conf->browser->layout != 'phone') {    // Show no photo link
1467 1467
                 $nophoto = '/public/theme/common/nophoto.png';
1468 1468
 //$morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="No photo" border="0"' . ($width ? ' width="' . $width . '"' : '') . ' src="' . DOL_BASE_URI . $nophoto . '"></div>';
1469
-                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="No photo" border="0"' . ($width ? ' width="' . $width . '"' : '') . ' src="' . DOL_BASE_URI . $nophoto . '"></div>';
1469
+                $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' width="'.$width.'"' : '').' src="'.DOL_BASE_URI.$nophoto.'"></div>';
1470 1470
 //}
1471 1471
             }
1472 1472
         } else {
@@ -1476,25 +1476,25 @@  discard block
 block discarded – undo
1476 1476
                     // Check if a preview file is available
1477 1477
                     if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
1478 1478
                         $objectref = dol_sanitizeFileName($object->ref);
1479
-                        $dir_output = (empty(Globals::$conf->$modulepart->multidir_output[$entity]) ? Globals::$conf->$modulepart->dir_output : Globals::$conf->$modulepart->multidir_output[$entity]) . "/";
1479
+                        $dir_output = (empty(Globals::$conf->$modulepart->multidir_output[$entity]) ? Globals::$conf->$modulepart->dir_output : Globals::$conf->$modulepart->multidir_output[$entity])."/";
1480 1480
                         if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
1481 1481
                             $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
1482
-                            $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '') . $objectref;  // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
1482
+                            $subdir .= ((!empty($subdir) && !preg_match('/\/$/', $subdir)) ? '/' : '').$objectref; // the objectref dir is not included into get_exdir when used with level=2, so we add it at end
1483 1483
                         } else {
1484 1484
                             $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
1485 1485
                         }
1486 1486
                         if (empty($subdir))
1487 1487
                             $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
1488 1488
 
1489
-                        $filepath = $dir_output . $subdir . "/";
1489
+                        $filepath = $dir_output.$subdir."/";
1490 1490
 
1491
-                        $file = $filepath . $objectref . ".pdf";
1492
-                        $relativepath = $subdir . '/' . $objectref . '.pdf';
1491
+                        $file = $filepath.$objectref.".pdf";
1492
+                        $relativepath = $subdir.'/'.$objectref.'.pdf';
1493 1493
 
1494 1494
                         // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
1495
-                        $fileimage = $file . '_preview.png';              // If PDF has 1 page
1496
-                        $fileimagebis = $file . '_preview-0.png';         // If PDF has more than one page
1497
-                        $relativepathimage = $relativepath . '_preview.png';
1495
+                        $fileimage = $file.'_preview.png'; // If PDF has 1 page
1496
+                        $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
1497
+                        $relativepathimage = $relativepath.'_preview.png';
1498 1498
 
1499 1499
                         // Si fichier PDF existe
1500 1500
                         if (file_exists($file)) {
@@ -1503,7 +1503,7 @@  discard block
 block discarded – undo
1503 1503
                             if ((!file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) && (!file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
1504 1504
                             ) {
1505 1505
                                 if (empty(Globals::$conf->global->MAIN_DISABLE_PDF_THUMBS)) {  // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
1506
-                                    include_once DOL_BASE_PATH . '/core/lib/files.lib.php';
1506
+                                    include_once DOL_BASE_PATH.'/core/lib/files.lib.php';
1507 1507
                                     $ret = dol_convert_file($file, 'png', $fileimage);
1508 1508
                                     if ($ret < 0)
1509 1509
                                         $error++;
@@ -1516,14 +1516,14 @@  discard block
 block discarded – undo
1516 1516
                             // Si fichier png PDF d'1 page trouve
1517 1517
                             if (file_exists($fileimage)) {
1518 1518
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
1519
-                                $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithmargin photowithborder" src="' . DOL_BASE_URI . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($relativepathimage) . '">';
1519
+                                $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_BASE_URI.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
1520 1520
                                 $phototoshow .= '</div></div>';
1521 1521
                             }
1522 1522
                             // Si fichier png PDF de plus d'1 page trouve
1523 1523
                             elseif (file_exists($fileimagebis)) {
1524
-                                $preview = preg_replace('/\.png/', '', $relativepathimage) . "-0.png";
1524
+                                $preview = preg_replace('/\.png/', '', $relativepathimage)."-0.png";
1525 1525
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
1526
-                                $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithmargin photowithborder" src="' . DOL_BASE_URI . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($preview) . '"><p>';
1526
+                                $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_BASE_URI.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
1527 1527
                                 $phototoshow .= '</div></div>';
1528 1528
                             }
1529 1529
                         }
@@ -1550,10 +1550,10 @@  discard block
 block discarded – undo
1550 1550
                         $picto = $object->picto;
1551 1551
                         if ($object->element == 'project' && !$object->public)
1552 1552
                             $picto = 'project'; // instead of projectpub
1553
-                        $nophoto = img_picto('', 'object_' . $picto, '', false, 1);
1553
+                        $nophoto = img_picto('', 'object_'.$picto, '', false, 1);
1554 1554
                     }
1555 1555
                     $morehtmlleft .= '<!-- No photo to show -->';
1556
-                    $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $modulepart . ($cssclass ? ' ' . $cssclass : '') . '" alt="No photo" border="0"' . ($width ? ' width="' . $width . '"' : '') . ' src="' . $nophoto . '"></div></div>';
1556
+                    $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$modulepart.($cssclass ? ' '.$cssclass : '').'" alt="No photo" border="0"'.($width ? ' width="'.$width.'"' : '').' src="'.$nophoto.'"></div></div>';
1557 1557
 
1558 1558
                     $morehtmlleft .= '</div>';
1559 1559
                 }
@@ -1561,7 +1561,7 @@  discard block
 block discarded – undo
1561 1561
         }
1562 1562
 
1563 1563
         if ($showbarcode)
1564
-            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1564
+            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
1565 1565
 
1566 1566
         if ($object->element == 'societe') {
1567 1567
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->societe->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
@@ -1574,14 +1574,14 @@  discard block
 block discarded – undo
1574 1574
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->produit->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
1575 1575
                 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
1576 1576
             } else {
1577
-                $morehtmlstatus .= '<span class="statusrefsell">' . $object->getLibStatut(5, 0) . '</span>';
1577
+                $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(5, 0).'</span>';
1578 1578
             }
1579 1579
             $morehtmlstatus .= ' &nbsp; ';
1580 1580
 //$morehtmlstatus.=Globals::$langs->trans("Status").' ('.Globals::$langs->trans("Buy").') ';
1581 1581
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->produit->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
1582 1582
                 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
1583 1583
             } else {
1584
-                $morehtmlstatus .= '<span class="statusrefbuy">' . $object->getLibStatut(5, 1) . '</span>';
1584
+                $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(5, 1).'</span>';
1585 1585
             }
1586 1586
         } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) {
1587 1587
             $tmptxt = $object->getLibStatut(6, $object->totalpaye);
@@ -1608,7 +1608,7 @@  discard block
 block discarded – undo
1608 1608
             if ($object->progress >= 100)
1609 1609
                 $object->fk_statut = 3;
1610 1610
             $tmptxt = $object->getLibStatut(5);
1611
-            $morehtmlstatus .= $tmptxt;  // No status on task
1611
+            $morehtmlstatus .= $tmptxt; // No status on task
1612 1612
         }
1613 1613
         else { // Generic case
1614 1614
             $tmptxt = $object->getLibStatut(6);
@@ -1622,18 +1622,18 @@  discard block
 block discarded – undo
1622 1622
             if (method_exists($object, 'getVentilExportCompta')) {
1623 1623
                 $accounted = $object->getVentilExportCompta();
1624 1624
                 Globals::$langs->load("accountancy");
1625
-                $morehtmlstatus .= '</div><div class="statusref statusrefbis">' . ($accounted > 0 ? Globals::$langs->trans("Accounted") : Globals::$langs->trans("NotYetAccounted"));
1625
+                $morehtmlstatus .= '</div><div class="statusref statusrefbis">'.($accounted > 0 ? Globals::$langs->trans("Accounted") : Globals::$langs->trans("NotYetAccounted"));
1626 1626
             }
1627 1627
         }
1628 1628
 
1629 1629
 // Add alias for thirdparty
1630 1630
         if (!empty($object->name_alias))
1631
-            $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1631
+            $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
1632 1632
 
1633 1633
 // Add label
1634 1634
         if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task') {
1635 1635
             if (!empty($object->label))
1636
-                $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1636
+                $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
1637 1637
         }
1638 1638
 
1639 1639
         if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files') {
@@ -1643,11 +1643,11 @@  discard block
 block discarded – undo
1643 1643
         }
1644 1644
         if (!empty(Globals::$conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) {
1645 1645
             $morehtmlref .= '<div style="clear: both;"></div><div class="refidno">';
1646
-            $morehtmlref .= Globals::$langs->trans("TechnicalID") . ': ' . $object->id;
1646
+            $morehtmlref .= Globals::$langs->trans("TechnicalID").': '.$object->id;
1647 1647
             $morehtmlref .= '</div>';
1648 1648
         }
1649 1649
 
1650
-        print '<div class="' . ($onlybanner ? 'arearefnobottom ' : 'arearef ') . 'heightref valignmiddle" width="100%">';
1650
+        print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle" width="100%">';
1651 1651
         print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
1652 1652
         print '</div>';
1653 1653
         print '<div class="underrefbanner clearboth"></div>';
@@ -1669,7 +1669,7 @@  discard block
 block discarded – undo
1669 1669
         if ($fieldrequired)
1670 1670
             $ret .= '<span class="fieldrequired">';
1671 1671
         if ((Globals::$conf->dol_use_jmobile != 4))
1672
-            $ret .= '<label for="' . $fieldkey . '">';
1672
+            $ret .= '<label for="'.$fieldkey.'">';
1673 1673
         $ret .= Globals::$langs->trans($langkey);
1674 1674
         if ((Globals::$conf->dol_use_jmobile != 4))
1675 1675
             $ret .= '</label>';
@@ -1688,9 +1688,9 @@  discard block
 block discarded – undo
1688 1688
     static function dol_bc($var, $moreclass = '')
1689 1689
     {
1690 1690
         // global $bc;
1691
-        $ret = ' ' . $bc[$var];
1691
+        $ret = ' '.$bc[$var];
1692 1692
         if ($moreclass)
1693
-            $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1693
+            $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
1694 1694
         return $ret;
1695 1695
     }
1696 1696
 
@@ -1710,50 +1710,50 @@  discard block
 block discarded – undo
1710 1710
         // global Globals::$conf, Globals::$langs;
1711 1711
 
1712 1712
         $ret = '';
1713
-        $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR');    // See also MAIN_FORCE_STATE_INTO_ADDRESS
1713
+        $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
1714 1714
 // Address
1715 1715
         if (empty($mode)) {
1716 1716
             $ret .= $object->address;
1717 1717
         }
1718 1718
 // Zip/Town/State
1719 1719
         if (in_array($object->country_code, array('AU', 'CA', 'US')) || !empty(Globals::$conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)) {    // US: title firstname name \n address lines \n town, state, zip \n country
1720
-            $ret .= ($ret ? $sep : '' ) . $object->town;
1720
+            $ret .= ($ret ? $sep : '').$object->town;
1721 1721
             if ($object->state) {
1722
-                $ret .= ($ret ? ", " : '') . $object->state;
1722
+                $ret .= ($ret ? ", " : '').$object->state;
1723 1723
             }
1724 1724
             if ($object->zip)
1725
-                $ret .= ($ret ? ", " : '') . $object->zip;
1725
+                $ret .= ($ret ? ", " : '').$object->zip;
1726 1726
         }
1727 1727
         else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1728
-            $ret .= ($ret ? $sep : '' ) . $object->town;
1728
+            $ret .= ($ret ? $sep : '').$object->town;
1729 1729
             if ($object->state) {
1730
-                $ret .= ($ret ? ", " : '') . $object->state;
1730
+                $ret .= ($ret ? ", " : '').$object->state;
1731 1731
             }
1732 1732
             if ($object->zip)
1733
-                $ret .= ($ret ? $sep : '' ) . $object->zip;
1733
+                $ret .= ($ret ? $sep : '').$object->zip;
1734 1734
         }
1735 1735
         else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1736
-            $ret .= ($ret ? $sep : '' ) . $object->zip;
1737
-            $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1736
+            $ret .= ($ret ? $sep : '').$object->zip;
1737
+            $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : '');
1738 1738
             if ($object->state) {
1739
-                $ret .= "\n" . $object->state;
1739
+                $ret .= "\n".$object->state;
1740 1740
             }
1741 1741
         } else if (in_array($object->country_code, array('IT'))) { // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
1742
-            $ret .= ($ret ? $sep : '' ) . $object->zip;
1743
-            $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1744
-            $ret .= ($object->departement_id ? (' (' . ($object->departement_id) . ')') : '');
1742
+            $ret .= ($ret ? $sep : '').$object->zip;
1743
+            $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : '');
1744
+            $ret .= ($object->departement_id ? (' ('.($object->departement_id).')') : '');
1745 1745
         } else {                                          // Other: title firstname name \n address lines \n zip town \n country
1746
-            $ret .= $object->zip ? (($ret ? $sep : '' ) . $object->zip) : '';
1747
-            $ret .= ($object->town ? (($object->zip ? ' ' : ($ret ? $sep : '' )) . $object->town) : '');
1746
+            $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
1747
+            $ret .= ($object->town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$object->town) : '');
1748 1748
             if ($object->state && in_array($object->country_code, $countriesusingstate)) {
1749
-                $ret .= ($ret ? ", " : '') . $object->state;
1749
+                $ret .= ($ret ? ", " : '').$object->state;
1750 1750
             }
1751 1751
         }
1752 1752
         if (!is_object($outputlangs))
1753 1753
             $outputlangs = Globals::$langs;
1754 1754
         if ($withcountry) {
1755 1755
             Globals::$langs->load("dict");
1756
-            $ret .= ($object->country_code ? ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)) : '');
1756
+            $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : '');
1757 1757
         }
1758 1758
 
1759 1759
         return $ret;
@@ -1807,13 +1807,13 @@  discard block
 block discarded – undo
1807 1807
             if (is_string($tzoutput)) {
1808 1808
                 if ($tzoutput == 'tzserver') {
1809 1809
                     $to_gmt = false;
1810
-                    $offsettzstring = @date_default_timezone_get();  // Example 'Europe/Berlin' or 'Indian/Reunion'
1810
+                    $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
1811 1811
                     $offsettz = 0;
1812 1812
                     $offsetdst = 0;
1813 1813
                 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
1814 1814
                     $to_gmt = true;
1815 1815
                     $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
1816
-                    $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;  // Will not be used anymore
1816
+                    $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
1817 1817
                     $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
1818 1818
                 }
1819 1819
             }
@@ -1859,9 +1859,9 @@  discard block
 block discarded – undo
1859 1859
         else if ($format == 'dayxcard')
1860 1860
             $format = '%Y%m%d';
1861 1861
         else if ($format == 'dayrfc')
1862
-            $format = '%Y-%m-%d';             // DATE_RFC3339
1862
+            $format = '%Y-%m-%d'; // DATE_RFC3339
1863 1863
         else if ($format == 'dayhourrfc')
1864
-            $format = '%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339
1864
+            $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
1865 1865
         else if ($format == 'standard')
1866 1866
             $format = '%Y-%m-%d %H:%M:%S';
1867 1867
 
@@ -1872,7 +1872,7 @@  discard block
 block discarded – undo
1872 1872
 
1873 1873
 // If date undefined or "", we return ""
1874 1874
         if (DolUtils::dol_strlen($time) == 0)
1875
-            return '';  // $time=0 allowed (it means 01/01/1970 00:00:00)
1875
+            return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
1876 1876
 
1877 1877
 
1878 1878
 
@@ -1933,7 +1933,7 @@  discard block
 block discarded – undo
1933 1933
         if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+) ?([0-9]+)?:?([0-9]+)?:?([0-9]+)?/i', $time, $reg) || preg_match('/^([0-9][0-9][0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])([0-9][0-9])$/i', $time, $reg)) { // Deprecated. Ex: 1970-01-01, 1970-01-01 01:00:00, 19700101010000
1934 1934
 // TODO Remove this.
1935 1935
 // This part of code should not be used.
1936
-            DolUtils::dol_syslog("Functions.lib::DolUtils::dol_print_date static function call with deprecated value of time in page " . $_SERVER["PHP_SELF"], LOG_ERR);
1936
+            DolUtils::dol_syslog("Functions.lib::DolUtils::dol_print_date static function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_ERR);
1937 1937
 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
1938 1938
             $syear = (!empty($reg[1]) ? $reg[1] : '');
1939 1939
             $smonth = (!empty($reg[2]) ? $reg[2] : '');
@@ -1951,7 +1951,7 @@  discard block
 block discarded – undo
1951 1951
 
1952 1952
                 $ret = adodb_strftime($format, $timetouse, $to_gmt);
1953 1953
             } else
1954
-                $ret = 'Bad value ' . $time . ' for date';
1954
+                $ret = 'Bad value '.$time.' for date';
1955 1955
         }
1956 1956
 
1957 1957
         if (preg_match('/__b__/i', $format)) {
@@ -1960,11 +1960,11 @@  discard block
 block discarded – undo
1960 1960
             $month = adodb_strftime('%m', $timetouse);
1961 1961
             $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
1962 1962
             if ($encodetooutput) {
1963
-                $monthtext = $outputlangs->transnoentities('Month' . $month);
1964
-                $monthtextshort = $outputlangs->transnoentities('MonthShort' . $month);
1963
+                $monthtext = $outputlangs->transnoentities('Month'.$month);
1964
+                $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
1965 1965
             } else {
1966
-                $monthtext = $outputlangs->transnoentitiesnoconv('Month' . $month);
1967
-                $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort' . $month);
1966
+                $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
1967
+                $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
1968 1968
             }
1969 1969
 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
1970 1970
             $ret = str_replace('__b__', $monthtextshort, $ret);
@@ -1975,8 +1975,8 @@  discard block
 block discarded – undo
1975 1975
         if (preg_match('/__a__/i', $format)) {
1976 1976
             $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1977 1977
 
1978
-            $w = adodb_strftime('%w', $timetouse);      // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1979
-            $dayweek = $outputlangs->transnoentitiesnoconv('Day' . $w);
1978
+            $w = adodb_strftime('%w', $timetouse); // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1979
+            $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
1980 1980
             $ret = str_replace('__A__', $dayweek, $ret);
1981 1981
             $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
1982 1982
         }
@@ -2023,9 +2023,9 @@  discard block
 block discarded – undo
2023 2023
 
2024 2024
         $usealternatemethod = false;
2025 2025
         if ($timestamp <= 0)
2026
-            $usealternatemethod = true;    // <= 1970
2026
+            $usealternatemethod = true; // <= 1970
2027 2027
         if ($timestamp >= 2145913200)
2028
-            $usealternatemethod = true;  // >= 2038
2028
+            $usealternatemethod = true; // >= 2038
2029 2029
 
2030 2030
         if ($usealternatemethod) {
2031 2031
             $arrayinfo = adodb_getdate($timestamp, $fast);
@@ -2085,23 +2085,23 @@  discard block
 block discarded – undo
2085 2085
 
2086 2086
         if (method_exists('DateTime', 'getTimestamp')) {
2087 2087
             if (empty($gm) || $gm === 'server') {
2088
-                $default_timezone = @date_default_timezone_get();  // Example 'Europe/Berlin'
2088
+                $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
2089 2089
                 $localtz = new \DateTimeZone($default_timezone);
2090 2090
             } else if ($gm === 'user') {
2091 2091
 // We use dol_tz_string first because it is more reliable.
2092
-                $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]);  // Example 'Europe/Berlin'
2092
+                $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
2093 2093
                 try {
2094 2094
                     $localtz = new \DateTimeZone($default_timezone);
2095 2095
                 } catch (Exception $e) {
2096
-                    DolUtils::dol_syslog("Warning dol_tz_string contains an invalid value " . $_SESSION["dol_tz_string"], LOG_WARNING);
2096
+                    DolUtils::dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
2097 2097
                     $default_timezone = @date_default_timezone_get();
2098 2098
                 }
2099 2099
             } else if (strrpos($gm, "tz,") !== false) {
2100
-                $timezone = str_replace("tz,", "", $gm);  // Example 'tz,Europe/Berlin'
2100
+                $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
2101 2101
                 try {
2102 2102
                     $localtz = new \DateTimeZone($timezone);
2103 2103
                 } catch (Exception $e) {
2104
-                    DolUtils::dol_syslog("Warning passed timezone contains an invalid value " . $timezone, LOG_WARNING);
2104
+                    DolUtils::dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
2105 2105
                 }
2106 2106
             }
2107 2107
 
@@ -2140,8 +2140,8 @@  discard block
 block discarded – undo
2140 2140
         if ($mode == 'gmt')
2141 2141
             $ret = time(); // Time for now at greenwich.
2142 2142
         else if ($mode == 'tzserver') {  // Time for now with PHP server timezone added
2143
-            require_once DOL_BASE_PATH . '/core/lib/date.lib.php';
2144
-            $tzsecond = getServerTimeZoneInt('now');    // Contains tz+dayling saving time
2143
+            require_once DOL_BASE_PATH.'/core/lib/date.lib.php';
2144
+            $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
2145 2145
             $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
2146 2146
         }
2147 2147
         /* else if ($mode == 'tzref')				// Time for now with parent company timezone is added
@@ -2187,9 +2187,9 @@  discard block
 block discarded – undo
2187 2187
         }
2188 2188
 // Use long or short text unit
2189 2189
         if (empty($shortunit)) {
2190
-            $ret .= ' ' . $textunitlong;
2190
+            $ret .= ' '.$textunitlong;
2191 2191
         } else {
2192
-            $ret .= ' ' . $textunitshort;
2192
+            $ret .= ' '.$textunitshort;
2193 2193
         }
2194 2194
 
2195 2195
         return $ret;
@@ -2217,13 +2217,13 @@  discard block
 block discarded – undo
2217 2217
         $link .= $url;
2218 2218
         $link .= '"';
2219 2219
         if ($target)
2220
-            $link .= ' target="' . $target . '"';
2220
+            $link .= ' target="'.$target.'"';
2221 2221
         $link .= '>';
2222 2222
         if (!preg_match('/^http/i', $url))
2223 2223
             $link .= 'http://';
2224 2224
         $link .= dol_trunc($url, $max);
2225 2225
         $link .= '</a>';
2226
-        return '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png') . ' ' : '') . $link . '</div>';
2226
+        return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png').' ' : '').$link.'</div>';
2227 2227
     }
2228 2228
 
2229 2229
     /**
@@ -2264,9 +2264,9 @@  discard block
 block discarded – undo
2264 2264
                 $type = 'AC_EMAIL';
2265 2265
                 $link = '';
2266 2266
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL))
2267
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2267
+                    $link = '<a href="'.DOL_BASE_URI.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object(Globals::$langs->trans("AddAction"), "calendar").'</a>';
2268 2268
                 if ($link)
2269
-                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2269
+                    $newemail = '<div>'.$newemail.' '.$link.'</div>';
2270 2270
             }
2271 2271
         }
2272 2272
         else {
@@ -2276,7 +2276,7 @@  discard block
 block discarded – undo
2276 2276
             }
2277 2277
         }
2278 2278
 
2279
-        $rep = '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("EMail"), 'object_email.png') . ' ' : '') . $newemail . '</div>';
2279
+        $rep = '<div class="nospan float" style="margin-right: 10px">'.($withpicto ? img_picto(Globals::$langs->trans("EMail"), 'object_email.png').' ' : '').$newemail.'</div>';
2280 2280
         if (Globals::$hookManager) {
2281 2281
             $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
2282 2282
             $reshook = Globals::$hookManager->executeHooks('printEmail', $parameters, $email);
@@ -2306,26 +2306,26 @@  discard block
 block discarded – undo
2306 2306
 
2307 2307
         if (!empty($type)) {
2308 2308
             $newskype = '<div class="divsocialnetwork inline-block valignmiddle">';
2309
-            $newskype .= img_picto(Globals::$langs->trans(strtoupper($type)), $type . '.png', '', false, 0, 0, '', 'paddingright');
2309
+            $newskype .= img_picto(Globals::$langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright');
2310 2310
             $newskype .= $value;
2311 2311
             if ($type == 'skype') {
2312 2312
                 $newskype .= '&nbsp;';
2313 2313
                 $newskype .= '<a href="skype:';
2314 2314
                 $newskype .= $value;
2315
-                $newskype .= '?call" alt="' . Globals::$langs->trans("Call") . '&nbsp;' . $value . '" title="' . Globals::$langs->trans("Call") . '&nbsp;' . $value . '">';
2316
-                $newskype .= '<img src="' . DOL_BASE_URI . '/theme/common/skype_callbutton.png" border="0">';
2315
+                $newskype .= '?call" alt="'.Globals::$langs->trans("Call").'&nbsp;'.$value.'" title="'.Globals::$langs->trans("Call").'&nbsp;'.$value.'">';
2316
+                $newskype .= '<img src="'.DOL_BASE_URI.'/theme/common/skype_callbutton.png" border="0">';
2317 2317
                 $newskype .= '</a><a href="skype:';
2318 2318
                 $newskype .= $value;
2319
-                $newskype .= '?chat" alt="' . Globals::$langs->trans("Chat") . '&nbsp;' . $value . '" title="' . Globals::$langs->trans("Chat") . '&nbsp;' . $value . '">';
2320
-                $newskype .= '<img class="paddingleft" src="' . DOL_BASE_URI . '/theme/common/skype_chatbutton.png" border="0">';
2319
+                $newskype .= '?chat" alt="'.Globals::$langs->trans("Chat").'&nbsp;'.$value.'" title="'.Globals::$langs->trans("Chat").'&nbsp;'.$value.'">';
2320
+                $newskype .= '<img class="paddingleft" src="'.DOL_BASE_URI.'/theme/common/skype_chatbutton.png" border="0">';
2321 2321
                 $newskype .= '</a>';
2322 2322
             }
2323 2323
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') {
2324 2324
                 $addlink = 'AC_SKYPE';
2325 2325
                 $link = '';
2326 2326
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE))
2327
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $addlink . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2328
-                $newskype .= ($link ? ' ' . $link : '');
2327
+                    $link = '<a href="'.DOL_BASE_URI.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$addlink.'&amp;contactid='.$cid.'&amp;socid='.$socid.'">'.img_object(Globals::$langs->trans("AddAction"), "calendar").'</a>';
2328
+                $newskype .= ($link ? ' '.$link : '');
2329 2329
             }
2330 2330
             $newskype .= '</div>';
2331 2331
         }
@@ -2369,165 +2369,165 @@  discard block
 block discarded – undo
2369 2369
         if (strtoupper($countrycode) == "FR") {
2370 2370
 // France
2371 2371
             if (DolUtils::dol_strlen($phone) == 10) {
2372
-                $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 2) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2);
2372
+                $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 2).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2);
2373 2373
             } elseif (DolUtils::dol_strlen($phone) == 7) {
2374
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2);
2374
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
2375 2375
             } elseif (DolUtils::dol_strlen($phone) == 9) {
2376
-                $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2);
2376
+                $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
2377 2377
             } elseif (DolUtils::dol_strlen($phone) == 11) {
2378
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
2378
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
2379 2379
             } elseif (DolUtils::dol_strlen($phone) == 12) {
2380
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2380
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2381 2381
             }
2382 2382
         } elseif (strtoupper($countrycode) == "CA") {
2383 2383
             if (DolUtils::dol_strlen($phone) == 10) {
2384
-                $newphone = ($separ != '' ? '(' : '') . substr($newphone, 0, 3) . ($separ != '' ? ')' : '') . $separ . substr($newphone, 3, 3) . ($separ != '' ? '-' : '') . substr($newphone, 6, 4);
2384
+                $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
2385 2385
             }
2386 2386
         } elseif (strtoupper($countrycode) == "PT") {//Portugal
2387 2387
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
2388
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2388
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2389 2389
             }
2390 2390
         } elseif (strtoupper($countrycode) == "SR") {//Suriname
2391 2391
             if (DolUtils::dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
2392
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3);
2392
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
2393 2393
             } elseif (DolUtils::dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
2394
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
2394
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
2395 2395
             }
2396 2396
         } elseif (strtoupper($countrycode) == "DE") {//Allemagne
2397 2397
             if (DolUtils::dol_strlen($phone) == 14) {//ex:  +49_ABCD_EFGH_IJK
2398
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 4) . $separ . substr($newphone, 11, 3);
2398
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
2399 2399
             } elseif (DolUtils::dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
2400
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 4) . $separ . substr($newphone, 10, 3);
2400
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
2401 2401
             }
2402 2402
         } elseif (strtoupper($countrycode) == "ES") {//Espagne
2403 2403
             if (DolUtils::dol_strlen($phone) == 12) {//ex:  +34_ABC_DEF_GHI
2404
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2404
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2405 2405
             }
2406 2406
         } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
2407 2407
             if (DolUtils::dol_strlen($phone) == 12) {//ex :  +22 A BC_DE_FG_HI
2408
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2408
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2409 2409
             }
2410 2410
         } elseif (strtoupper($countrycode) == "RO") {// Roumanie
2411 2411
             if (DolUtils::dol_strlen($phone) == 12) {//ex :  +40 AB_CDE_FG_HI
2412
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2412
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2413 2413
             }
2414 2414
         } elseif (strtoupper($countrycode) == "TR") {//Turquie
2415 2415
             if (DolUtils::dol_strlen($phone) == 13) {//ex :  +90 ABC_DEF_GHIJ
2416
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
2416
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
2417 2417
             }
2418 2418
         } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
2419 2419
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
2420
-                $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
2420
+                $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
2421 2421
             }
2422 2422
         } elseif (strtoupper($countrycode) == "MX") {//Mexique
2423 2423
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
2424
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
2424
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
2425 2425
             } elseif (DolUtils::dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
2426
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
2426
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
2427 2427
             } elseif (DolUtils::dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
2428
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
2428
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
2429 2429
             }
2430 2430
         } elseif (strtoupper($countrycode) == "ML") {//Mali
2431 2431
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
2432
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2432
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2433 2433
             }
2434 2434
         } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
2435 2435
             if (DolUtils::dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
2436
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
2436
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
2437 2437
             } elseif (DolUtils::dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
2438
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 3);
2438
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 3);
2439 2439
             }
2440 2440
         } elseif (strtoupper($countrycode) == "MU") {//Maurice
2441 2441
             if (DolUtils::dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
2442
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
2442
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
2443 2443
             } elseif (DolUtils::dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
2444
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2444
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2445 2445
             }
2446 2446
         } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
2447 2447
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
2448
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2448
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2449 2449
             }
2450 2450
         } elseif (strtoupper($countrycode) == "SY") {//Syrie
2451 2451
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
2452
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2452
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2453 2453
             } elseif (DolUtils::dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
2454
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 3);
2454
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3);
2455 2455
             }
2456 2456
         } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
2457 2457
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
2458
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
2458
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
2459 2459
             } elseif (DolUtils::dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
2460
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2460
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2461 2461
             } elseif (DolUtils::dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
2462
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 4);
2462
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
2463 2463
             }
2464 2464
         } elseif (strtoupper($countrycode) == "DZ") {//Algérie
2465 2465
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
2466
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2466
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2467 2467
             }
2468 2468
         } elseif (strtoupper($countrycode) == "BE") {//Belgique
2469 2469
             if (DolUtils::dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
2470
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
2470
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
2471 2471
             } elseif (DolUtils::dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
2472
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2472
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2473 2473
             }
2474 2474
         } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
2475 2475
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
2476
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2476
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2477 2477
             }
2478 2478
         } elseif (strtoupper($countrycode) == "CO") {//Colombie
2479 2479
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
2480
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 2) . $separ . substr($newphone, 11, 2);
2480
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
2481 2481
             }
2482 2482
         } elseif (strtoupper($countrycode) == "JO") {//Jordanie
2483 2483
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
2484
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 1) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
2484
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 1).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
2485 2485
             }
2486 2486
         } elseif (strtoupper($countrycode) == "MG") {//Madagascar
2487 2487
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
2488
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 3);
2488
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 3);
2489 2489
             }
2490 2490
         } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
2491 2491
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
2492
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2492
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2493 2493
             }
2494 2494
         } elseif (strtoupper($countrycode) == "CH") {//Suisse
2495 2495
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
2496
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2496
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2497 2497
             } elseif (DolUtils::dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
2498
-                $newphone = $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 3) . $separ . substr($newphone, 11, 4);
2498
+                $newphone = $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 3).$separ.substr($newphone, 11, 4);
2499 2499
             }
2500 2500
         } elseif (strtoupper($countrycode) == "TN") {//Tunisie
2501 2501
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
2502
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2502
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2503 2503
             }
2504 2504
         } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
2505 2505
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI  (ABC=594 de nouveau)
2506
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2) . $separ . substr($newphone, 11, 2);
2506
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
2507 2507
             }
2508 2508
         } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
2509 2509
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI  (ABC=590 de nouveau)
2510
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2) . $separ . substr($newphone, 11, 2);
2510
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
2511 2511
             }
2512 2512
         } elseif (strtoupper($countrycode) == "MQ") {//Martinique
2513 2513
             if (DolUtils::dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI  (ABC=596 de nouveau)
2514
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2) . $separ . substr($newphone, 11, 2);
2514
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
2515 2515
             }
2516 2516
         } elseif (strtoupper($countrycode) == "IT") {//Italie
2517 2517
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
2518
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2518
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2519 2519
             } elseif (DolUtils::dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
2520
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 2) . $separ . substr($newphone, 11, 2);
2520
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 2).$separ.substr($newphone, 11, 2);
2521 2521
             }
2522 2522
         } elseif (strtoupper($countrycode) == "AU") {//Australie
2523 2523
             if (DolUtils::dol_strlen($phone) == 12) {//ex: +61_A_BCDE_FGHI
2524
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 4);
2524
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
2525 2525
             }
2526 2526
         }
2527 2527
         if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
2528 2528
             if (Globals::$conf->browser->layout == 'phone' || (!empty(Globals::$conf->clicktodial->enabled) && !empty(Globals::$conf->global->CLICKTODIAL_USE_TEL_LINK_ON_PHONE_NUMBERS))) { // If phone or option for, we use link of phone
2529
-                $newphone = '<a href="tel:' . $phone . '"';
2530
-                $newphone .= '>' . $phone . '</a>';
2529
+                $newphone = '<a href="tel:'.$phone.'"';
2530
+                $newphone .= '>'.$phone.'</a>';
2531 2531
             } else if (!empty(Globals::$conf->clicktodial->enabled) && $addlink == 'AC_TEL') {  // If click to dial, we use click to dial url
2532 2532
                 if (empty($user->clicktodial_loaded))
2533 2533
                     $user->fetch_clicktodial();
@@ -2551,10 +2551,10 @@  discard block
 block discarded – undo
2551 2551
                     '__PASS__' => $clicktodial_password);
2552 2552
                 $url = make_substitutions($url, $substitarray);
2553 2553
                 $newphonesav = $newphone;
2554
-                $newphone = '<a href="' . $url . '"';
2554
+                $newphone = '<a href="'.$url.'"';
2555 2555
                 if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET))
2556 2556
                     $newphone .= ' target="_blank"';
2557
-                $newphone .= '>' . $newphonesav . '</a>';
2557
+                $newphone .= '>'.$newphonesav.'</a>';
2558 2558
             }
2559 2559
 
2560 2560
 //if (($cid || $socid) && ! empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create)
@@ -2564,9 +2564,9 @@  discard block
 block discarded – undo
2564 2564
                 if ($addlink == 'AC_FAX')
2565 2565
                     $type = 'AC_FAX';
2566 2566
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE))
2567
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . ($cid ? '&amp;contactid=' . $cid : '') . ($socid ? '&amp;socid=' . $socid : '') . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2567
+                    $link = '<a href="'.DOL_BASE_URI.'/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode='.$type.($cid ? '&amp;contactid='.$cid : '').($socid ? '&amp;socid='.$socid : '').'">'.img_object(Globals::$langs->trans("AddAction"), "calendar").'</a>';
2568 2568
                 if ($link)
2569
-                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2569
+                    $newphone = '<div>'.$newphone.' '.$link.'</div>';
2570 2570
             }
2571 2571
         }
2572 2572
 
@@ -2597,7 +2597,7 @@  discard block
 block discarded – undo
2597 2597
                 $rep .= '<div class="nospan float" style="margin-right: 10px">';
2598 2598
             else
2599 2599
                 $rep .= '<span style="margin-right: 10px;">';
2600
-            $rep .= ($withpicto ? img_picto($titlealt, 'object_' . $picto . '.png') . ' ' : '') . $newphone;
2600
+            $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
2601 2601
             if ($adddivfloat)
2602 2602
                 $rep .= '</div>';
2603 2603
             else
@@ -2624,15 +2624,15 @@  discard block
 block discarded – undo
2624 2624
             $ret .= $ip;
2625 2625
         }
2626 2626
 
2627
-        echo ('<p>DOL_BASE_PATH: ' . DOL_BASE_PATH . '/DOL_BASE_URI: ' . DOL_BASE_URI . '</p>');
2627
+        echo ('<p>DOL_BASE_PATH: '.DOL_BASE_PATH.'/DOL_BASE_URI: '.DOL_BASE_URI.'</p>');
2628 2628
 
2629 2629
         if ($mode != 2) {
2630 2630
             $countrycode = dolGetCountryCodeFromIp($ip);
2631 2631
             if ($countrycode) { // If success, countrycode is us, fr, ...
2632
-                if (file_exists(DOL_BASE_PATH . '/theme/common/flags/' . $countrycode . '.png')) {
2633
-                    $ret .= ' ' . img_picto($countrycode . ' ' . Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI . '/theme/common/flags/' . $countrycode . '.png', '', 1);
2632
+                if (file_exists(DOL_BASE_PATH.'/theme/common/flags/'.$countrycode.'.png')) {
2633
+                    $ret .= ' '.img_picto($countrycode.' '.Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI.'/theme/common/flags/'.$countrycode.'.png', '', 1);
2634 2634
                 } else
2635
-                    $ret .= ' (' . $countrycode . ')';
2635
+                    $ret .= ' ('.$countrycode.')';
2636 2636
             }
2637 2637
         }
2638 2638
 
@@ -2670,7 +2670,7 @@  discard block
 block discarded – undo
2670 2670
 //$ip='24.24.24.24';
2671 2671
 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';    Note that this must be downloaded datafile (not same than datafile provided with ubuntu packages)
2672 2672
 
2673
-            include_once DOL_BASE_PATH . '/core/class/dolgeoip.class.php';
2673
+            include_once DOL_BASE_PATH.'/core/class/dolgeoip.class.php';
2674 2674
             $geoip = new DolGeoIP('country', $datafile);
2675 2675
 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
2676 2676
 //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
@@ -2696,7 +2696,7 @@  discard block
 block discarded – undo
2696 2696
             $datafile = Globals::$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
2697 2697
 //$ip='24.24.24.24';
2698 2698
 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
2699
-            include_once DOL_BASE_PATH . '/core/class/dolgeoip.class.php';
2699
+            include_once DOL_BASE_PATH.'/core/class/dolgeoip.class.php';
2700 2700
             $geoip = new DolGeoIP('country', $datafile);
2701 2701
             $countrycode = $geoip->getCountryCodeFromIP($ip);
2702 2702
             $ret = $countrycode;
@@ -2751,12 +2751,12 @@  discard block
 block discarded – undo
2751 2751
                     $showomap = 1;
2752 2752
 
2753 2753
                 if ($showgmap) {
2754
-                    $url = dol_buildpath('/google/gmaps.php?mode=' . $mode . '&id=' . $id, 1);
2755
-                    $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" class="valigntextbottom" src="' . DOL_BASE_URI . '/theme/common/gmap.png"></a>';
2754
+                    $url = dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id, 1);
2755
+                    $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_BASE_URI.'/theme/common/gmap.png"></a>';
2756 2756
                 }
2757 2757
                 if ($showomap) {
2758
-                    $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $mode . '&id=' . $id, 1);
2759
-                    $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" class="valigntextbottom" src="' . DOL_BASE_URI . '/theme/common/gmap.png"></a>';
2758
+                    $url = dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id, 1);
2759
+                    $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_BASE_URI.'/theme/common/gmap.png"></a>';
2760 2760
                 }
2761 2761
             }
2762 2762
         }
@@ -2902,7 +2902,7 @@  discard block
 block discarded – undo
2902 2902
         if ($trunc == 'right') {
2903 2903
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2904 2904
             if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3)))    // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
2905
-                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
2905
+                return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
2906 2906
             else
2907 2907
             //return 'u'.$size.'-'.$newstring.'-'.DolUtils::dol_strlen($newstring,$stringencoding).'-'.$string;
2908 2908
                 return $string;
@@ -2912,21 +2912,21 @@  discard block
 block discarded – undo
2912 2912
             if (DolUtils::dol_strlen($newstring, $stringencoding) > 2 && DolUtils::dol_strlen($newstring, $stringencoding) > ($size + 1)) {
2913 2913
                 $size1 = round($size / 2);
2914 2914
                 $size2 = round($size / 2);
2915
-                return dol_substr($newstring, 0, $size1, $stringencoding) . '...' . dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2915
+                return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2916 2916
             } else
2917 2917
                 return $string;
2918 2918
         }
2919 2919
         elseif ($trunc == 'left') {
2920 2920
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2921 2921
             if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3)))    // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
2922
-                return '...' . dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2922
+                return '...'.dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2923 2923
             else
2924 2924
                 return $string;
2925 2925
         }
2926 2926
         elseif ($trunc == 'wrap') {
2927 2927
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2928 2928
             if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + 1))
2929
-                return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2929
+                return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2930 2930
             else
2931 2931
                 return $string;
2932 2932
         } else
@@ -2959,7 +2959,7 @@  discard block
 block discarded – undo
2959 2959
         $url = DOL_BASE_URI;
2960 2960
 
2961 2961
         $theme = Globals::$conf->theme;
2962
-        $path = 'theme/' . $theme;
2962
+        $path = 'theme/'.$theme;
2963 2963
 
2964 2964
 // Define fullpathpicto to use into src
2965 2965
         if ($pictoisfullpath) {
@@ -3008,7 +3008,7 @@  discard block
 block discarded – undo
3008 3008
                     $fakey = 'fa-pencil';
3009 3009
                     $facolor = '#444';
3010 3010
                 } elseif ($pictowithoutext == 'filter') {
3011
-                    $fakey = 'fa-' . $pictowithoutext;
3011
+                    $fakey = 'fa-'.$pictowithoutext;
3012 3012
                 } elseif ($pictowithoutext == 'grip_title' || $pictowithoutext == 'grip') {
3013 3013
                     $fakey = 'fa-arrows';
3014 3014
                 } elseif ($pictowithoutext == 'listlight') {
@@ -3047,15 +3047,15 @@  discard block
 block discarded – undo
3047 3047
                 } elseif ($pictowithoutext == 'jabber') {
3048 3048
                     $fakey = 'fa-comment-o';
3049 3049
                 } else {
3050
-                    $fakey = 'fa-' . $pictowithoutext;
3050
+                    $fakey = 'fa-'.$pictowithoutext;
3051 3051
                     $facolor = '#444';
3052 3052
                     $marginleftonlyshort = 0;
3053 3053
                 }
3054 3054
 
3055 3055
                 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
3056
-                    $morecss .= ($morecss ? ' ' : '') . $reg[1];
3056
+                    $morecss .= ($morecss ? ' ' : '').$reg[1];
3057 3057
                 }
3058
-                $enabledisablehtml = '<span class="fa ' . $fakey . ' ' . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? 'marginleftonlyshort' : 'marginleftonly') : '') . ' valignmiddle' . ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . '" alt="' . DolUtils::dol_escape_htmltag($titlealt) . '"' . (($notitle || empty($title)) ? '' : ' title="' . DolUtils::dol_escape_htmltag($title) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
3058
+                $enabledisablehtml = '<span class="fa '.$fakey.' '.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? 'marginleftonlyshort' : 'marginleftonly') : '').' valignmiddle'.($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').'" alt="'.DolUtils::dol_escape_htmltag($titlealt).'"'.(($notitle || empty($title)) ? '' : ' title="'.DolUtils::dol_escape_htmltag($title).'"').($moreatt ? ' '.$moreatt : '').'>';
3059 3059
                 if (!empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
3060 3060
                     $enabledisablehtml .= $titlealt;
3061 3061
                 }
@@ -3065,11 +3065,11 @@  discard block
 block discarded – undo
3065 3065
             }
3066 3066
 
3067 3067
             if (!empty(Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH)) {
3068
-                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH . '/theme/' . $theme; // If the theme does not have the same name as the module
3068
+                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
3069 3069
             } else if (!empty(Globals::$conf->global->MAIN_OVERWRITE_THEME_RES)) {
3070
-                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_RES . '/theme/' . Globals::$conf->global->MAIN_OVERWRITE_THEME_RES;  // To allow an external module to overwrite image resources whatever is activated theme
3070
+                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_RES.'/theme/'.Globals::$conf->global->MAIN_OVERWRITE_THEME_RES; // To allow an external module to overwrite image resources whatever is activated theme
3071 3071
             } else if (!empty(Globals::$conf->modules_parts['theme']) && array_key_exists($theme, Globals::$conf->modules_parts['theme'])) {
3072
-                $path = $theme . '/theme/' . $theme; // If the theme have the same name as the module
3072
+                $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
3073 3073
             }
3074 3074
 
3075 3075
 // If we ask an image into $url/$mymodule/img (instead of default path)
@@ -3089,15 +3089,15 @@  discard block
 block discarded – undo
3089 3089
                     continue;
3090 3090
                 }
3091 3091
 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
3092
-                if (file_exists($dirroot . '/' . $path . '/img/' . $picto)) {
3092
+                if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
3093 3093
                     //$url = DOL_BASE_URI . Globals::$conf->file->dol_url_root[$type];
3094
-                    $url = DOL_BASE_URI . Globals::$conf->file->dol_url_root[$type];
3094
+                    $url = DOL_BASE_URI.Globals::$conf->file->dol_url_root[$type];
3095 3095
                     break;
3096 3096
                 }
3097 3097
             }
3098 3098
 
3099 3099
 // $url is '' or '/custom', $path is current theme or
3100
-            $fullpathpicto = $url . '/' . $path . '/img/' . $picto;
3100
+            $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
3101 3101
         }
3102 3102
 
3103 3103
         if ($srconly) {
@@ -3105,7 +3105,7 @@  discard block
 block discarded – undo
3105 3105
         }
3106 3106
 
3107 3107
 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for bind people
3108
-        return '<img src="' . $fullpathpicto . '" alt="' . DolUtils::dol_escape_htmltag($alt) . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . DolUtils::dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : ' class="inline-block' . ($morecss ? ' ' . $morecss : '') . '"') . '>'; // Alt is used for accessibility, title for popup
3108
+        return '<img src="'.$fullpathpicto.'" alt="'.DolUtils::dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.DolUtils::dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
3109 3109
     }
3110 3110
 
3111 3111
     /**
@@ -3123,7 +3123,7 @@  discard block
 block discarded – undo
3123 3123
      */
3124 3124
     static function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
3125 3125
     {
3126
-        return img_picto($titlealt, 'object_' . $picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
3126
+        return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
3127 3127
     }
3128 3128
 
3129 3129
     /**
@@ -3144,7 +3144,7 @@  discard block
 block discarded – undo
3144 3144
             $picto .= '.png';
3145 3145
 
3146 3146
 //$path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3147
-        $path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3147
+        $path = DOL_BASE_URI.'/theme/'.Globals::$conf->theme.'/img/weather/'.$picto;
3148 3148
 
3149 3149
         return img_picto($titlealt, $path, $moreatt, 1);
3150 3150
     }
@@ -3171,10 +3171,10 @@  discard block
 block discarded – undo
3171 3171
             $path = $picto;
3172 3172
         } else {
3173 3173
             //$path = DOL_BASE_URI . '/theme/common/' . $picto;
3174
-            $path = DOL_BASE_URI . '/theme/common/' . $picto;
3174
+            $path = DOL_BASE_URI.'/theme/common/'.$picto;
3175 3175
 
3176 3176
             if (!empty(Globals::$conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
3177
-                $themepath = DOL_BASE_PATH . 'theme/' . Globals::$conf->theme . '/img/' . $picto;
3177
+                $themepath = DOL_BASE_PATH.'theme/'.Globals::$conf->theme.'/img/'.$picto;
3178 3178
 
3179 3179
                 if (file_exists($themepath)) {
3180 3180
                     $path = $themepath;
@@ -3213,14 +3213,14 @@  discard block
 block discarded – undo
3213 3213
                 $numaction = 3;
3214 3214
                 $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeContactDone');
3215 3215
             } else {
3216
-                $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeStatus ' . $numaction);
3216
+                $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
3217 3217
                 $numaction = 0;
3218 3218
             }
3219 3219
         }
3220 3220
         if (!is_numeric($numaction))
3221 3221
             $numaction = 0;
3222 3222
 
3223
-        return img_picto($titlealt, 'stcomm' . $numaction . '.png');
3223
+        return img_picto($titlealt, 'stcomm'.$numaction.'.png');
3224 3224
     }
3225 3225
 
3226 3226
     /**
@@ -3237,7 +3237,7 @@  discard block
 block discarded – undo
3237 3237
         if ($titlealt == 'default')
3238 3238
             $titlealt = Globals::$langs->trans('Show');
3239 3239
 
3240
-        return img_picto($titlealt, 'pdf' . $size . '.png');
3240
+        return img_picto($titlealt, 'pdf'.$size.'.png');
3241 3241
     }
3242 3242
 
3243 3243
     /**
@@ -3289,7 +3289,7 @@  discard block
 block discarded – undo
3289 3289
         if ($titlealt == 'default')
3290 3290
             $titlealt = Globals::$langs->trans('Modify');
3291 3291
 
3292
-        return img_picto($titlealt, 'edit.png', ($float ? 'style="float: ' . (Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
3292
+        return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.(Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
3293 3293
     }
3294 3294
 
3295 3295
     /**
@@ -3307,7 +3307,7 @@  discard block
 block discarded – undo
3307 3307
         if ($titlealt == 'default')
3308 3308
             $titlealt = Globals::$langs->trans('View');
3309 3309
 
3310
-        $moreatt = ($float ? 'style="float: right" ' : '') . $other;
3310
+        $moreatt = ($float ? 'style="float: right" ' : '').$other;
3311 3311
 
3312 3312
         return img_picto($titlealt, 'view.png', $moreatt);
3313 3313
     }
@@ -3380,7 +3380,7 @@  discard block
 block discarded – undo
3380 3380
                 $usealttitle = Globals::$langs->trans('Info');
3381 3381
         }
3382 3382
 
3383
-        return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
3383
+        return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
3384 3384
     }
3385 3385
 
3386 3386
     /**
@@ -3414,7 +3414,7 @@  discard block
 block discarded – undo
3414 3414
             $titlealt = Globals::$langs->trans('Warning');
3415 3415
 
3416 3416
 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
3417
-        return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
3417
+        return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
3418 3418
     }
3419 3419
 
3420 3420
     /**
@@ -3448,7 +3448,7 @@  discard block
 block discarded – undo
3448 3448
             $titlealt = Globals::$langs->trans('Next');
3449 3449
 
3450 3450
 //return img_picto($titlealt, 'next.png', $moreatt);
3451
-        return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . DolUtils::dol_escape_htmltag($titlealt) . '"></span>';
3451
+        return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.DolUtils::dol_escape_htmltag($titlealt).'"></span>';
3452 3452
     }
3453 3453
 
3454 3454
     /**
@@ -3466,7 +3466,7 @@  discard block
 block discarded – undo
3466 3466
             $titlealt = Globals::$langs->trans('Previous');
3467 3467
 
3468 3468
 //return img_picto($titlealt, 'previous.png', $moreatt);
3469
-        return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . DolUtils::dol_escape_htmltag($titlealt) . '"></span>';
3469
+        return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.DolUtils::dol_escape_htmltag($titlealt).'"></span>';
3470 3470
     }
3471 3471
 
3472 3472
     /**
@@ -3484,7 +3484,7 @@  discard block
 block discarded – undo
3484 3484
         if ($titlealt == 'default')
3485 3485
             $titlealt = Globals::$langs->trans('Down');
3486 3486
 
3487
-        return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
3487
+        return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
3488 3488
     }
3489 3489
 
3490 3490
     /**
@@ -3502,7 +3502,7 @@  discard block
 block discarded – undo
3502 3502
         if ($titlealt == 'default')
3503 3503
             $titlealt = Globals::$langs->trans('Up');
3504 3504
 
3505
-        return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
3505
+        return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
3506 3506
     }
3507 3507
 
3508 3508
     /**
@@ -3585,7 +3585,7 @@  discard block
 block discarded – undo
3585 3585
             $brand = 'credit-card';
3586 3586
         }
3587 3587
 
3588
-        return '<span class="fa fa-' . $brand . ' fa-2x fa-fw"></span>';
3588
+        return '<span class="fa fa-'.$brand.' fa-2x fa-fw"></span>';
3589 3589
     }
3590 3590
 
3591 3591
     /**
@@ -3598,17 +3598,17 @@  discard block
 block discarded – undo
3598 3598
      */
3599 3599
     static function img_mime($file, $titlealt = '', $morecss = '')
3600 3600
     {
3601
-        require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
3601
+        require_once DOL_BASE_PATH.'/core/lib/files.lib.php';
3602 3602
 
3603 3603
         $mimetype = dol_mimetype($file, '', 1);
3604 3604
         $mimeimg = dol_mimetype($file, '', 2);
3605 3605
         $mimefa = dol_mimetype($file, '', 4);
3606 3606
 
3607 3607
         if (empty($titlealt))
3608
-            $titlealt = 'Mime type: ' . $mimetype;
3608
+            $titlealt = 'Mime type: '.$mimetype;
3609 3609
 
3610 3610
 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
3611
-        return '<i class="fa fa-' . $mimefa . ' paddingright"></i>';
3611
+        return '<i class="fa fa-'.$mimefa.' paddingright"></i>';
3612 3612
     }
3613 3613
 
3614 3614
     /**
@@ -3623,7 +3623,7 @@  discard block
 block discarded – undo
3623 3623
      */
3624 3624
     static function img_phone($titlealt = 'default', $option = 0)
3625 3625
     {
3626
-        DolUtils::dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
3626
+        DolUtils::dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
3627 3627
 
3628 3628
         // global Globals::$conf, Globals::$langs;
3629 3629
 
@@ -3654,8 +3654,8 @@  discard block
 block discarded – undo
3654 3654
 
3655 3655
         $img = img_picto($titlealt, 'search.png', $other, false, 1);
3656 3656
 
3657
-        $input = '<input type="image" class="liste_titre" name="button_search" src="' . $img . '" ';
3658
-        $input .= 'value="' . DolUtils::dol_escape_htmltag($titlealt) . '" title="' . DolUtils::dol_escape_htmltag($titlealt) . '" >';
3657
+        $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
3658
+        $input .= 'value="'.DolUtils::dol_escape_htmltag($titlealt).'" title="'.DolUtils::dol_escape_htmltag($titlealt).'" >';
3659 3659
 
3660 3660
         return $input;
3661 3661
     }
@@ -3676,8 +3676,8 @@  discard block
 block discarded – undo
3676 3676
 
3677 3677
         $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
3678 3678
 
3679
-        $input = '<input type="image" class="liste_titre" name="button_removefilter" src="' . $img . '" ';
3680
-        $input .= 'value="' . DolUtils::dol_escape_htmltag($titlealt) . '" title="' . DolUtils::dol_escape_htmltag($titlealt) . '" >';
3679
+        $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
3680
+        $input .= 'value="'.DolUtils::dol_escape_htmltag($titlealt).'" title="'.DolUtils::dol_escape_htmltag($titlealt).'" >';
3681 3681
 
3682 3682
         return $input;
3683 3683
     }
@@ -3697,10 +3697,10 @@  discard block
 block discarded – undo
3697 3697
         // global Globals::$conf, Globals::$langs;
3698 3698
 
3699 3699
         if ($infoonimgalt) {
3700
-            return img_picto($text, 'info', 'class="hideonsmartphone' . ($morecss ? ' ' . $morecss : '') . '"');
3700
+            return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
3701 3701
         }
3702 3702
 
3703
-        return ($nodiv ? '' : '<div class="' . (empty($admin) ? '' : ($admin == '1' ? 'info' : $admin)) . ' hideonsmartphone' . ($morecss ? ' ' . $morecss : '') . '">') . '<span class="fa fa-info-circle" title="' . DolUtils::dol_escape_htmltag($admin ? Globals::$langs->trans('InfoAdmin') : Globals::$langs->trans('Note')) . '"></span> ' . $text . ($nodiv ? '' : '</div>');
3703
+        return ($nodiv ? '' : '<div class="'.(empty($admin) ? '' : ($admin == '1' ? 'info' : $admin)).' hideonsmartphone'.($morecss ? ' '.$morecss : '').'">').'<span class="fa fa-info-circle" title="'.DolUtils::dol_escape_htmltag($admin ? Globals::$langs->trans('InfoAdmin') : Globals::$langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
3704 3704
     }
3705 3705
 
3706 3706
     /**
@@ -3734,39 +3734,39 @@  discard block
 block discarded – undo
3734 3734
         Globals::$langs->loadLangs(array('main', 'errors'));
3735 3735
 
3736 3736
         if ($_SERVER['DOCUMENT_ROOT']) {    // Mode web
3737
-            $out .= Globals::$langs->trans("DolibarrHasDetectedError") . ".<br>\n";
3737
+            $out .= Globals::$langs->trans("DolibarrHasDetectedError").".<br>\n";
3738 3738
             if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL)) {
3739 3739
                 $out .= "You use an experimental or develop level of features, so please do NOT report any bugs, except if problem is confirmed moving option MAIN_FEATURES_LEVEL back to 0.<br>\n";
3740 3740
             }
3741
-            $out .= Globals::$langs->trans("InformationToHelpDiagnose") . ":<br>\n";
3741
+            $out .= Globals::$langs->trans("InformationToHelpDiagnose").":<br>\n";
3742 3742
 
3743
-            $out .= "<b>" . Globals::$langs->trans("Date") . ":</b> " . DolUtils::dol_print_date(time(), 'dayhourlog') . "<br>\n";
3744
-            $out .= "<b>" . Globals::$langs->trans("Dolibarr") . ":</b> " . DOL_VERSION . "<br>\n";
3743
+            $out .= "<b>".Globals::$langs->trans("Date").":</b> ".DolUtils::dol_print_date(time(), 'dayhourlog')."<br>\n";
3744
+            $out .= "<b>".Globals::$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
3745 3745
             if (isset(Globals::$conf->global->MAIN_FEATURES_LEVEL)) {
3746
-                $out .= "<b>" . Globals::$langs->trans("LevelOfFeature") . ":</b> " . Globals::$conf->global->MAIN_FEATURES_LEVEL . "<br>\n";
3746
+                $out .= "<b>".Globals::$langs->trans("LevelOfFeature").":</b> ".Globals::$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
3747 3747
             }
3748 3748
             if (function_exists("phpversion")) {
3749
-                $out .= "<b>" . Globals::$langs->trans("PHP") . ":</b> " . phpversion() . "<br>\n";
3749
+                $out .= "<b>".Globals::$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
3750 3750
             }
3751
-            $out .= "<b>" . Globals::$langs->trans("Server") . ":</b> " . $_SERVER["SERVER_SOFTWARE"] . "<br>\n";
3751
+            $out .= "<b>".Globals::$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
3752 3752
             if (function_exists("php_uname")) {
3753
-                $out .= "<b>" . Globals::$langs->trans("OS") . ":</b> " . php_uname() . "<br>\n";
3753
+                $out .= "<b>".Globals::$langs->trans("OS").":</b> ".php_uname()."<br>\n";
3754 3754
             }
3755
-            $out .= "<b>" . Globals::$langs->trans("UserAgent") . ":</b> " . $_SERVER["HTTP_USER_AGENT"] . "<br>\n";
3755
+            $out .= "<b>".Globals::$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
3756 3756
             $out .= "<br>\n";
3757
-            $out .= "<b>" . Globals::$langs->trans("RequestedUrl") . ":</b> " . DolUtils::dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8') . "<br>\n";
3758
-            $out .= "<b>" . Globals::$langs->trans("Referer") . ":</b> " . (isset($_SERVER["HTTP_REFERER"]) ? DolUtils::dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '') . "<br>\n";
3759
-            $out .= "<b>" . Globals::$langs->trans("MenuManager") . ":</b> " . (isset(Globals::$conf->standard_menu) ? Globals::$conf->standard_menu : '') . "<br>\n";
3757
+            $out .= "<b>".Globals::$langs->trans("RequestedUrl").":</b> ".DolUtils::dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
3758
+            $out .= "<b>".Globals::$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? DolUtils::dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
3759
+            $out .= "<b>".Globals::$langs->trans("MenuManager").":</b> ".(isset(Globals::$conf->standard_menu) ? Globals::$conf->standard_menu : '')."<br>\n";
3760 3760
             $out .= "<br>\n";
3761
-            $syslog .= "url=" . DolUtils::dol_escape_htmltag($_SERVER["REQUEST_URI"]);
3762
-            $syslog .= ", query_string=" . DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]);
3761
+            $syslog .= "url=".DolUtils::dol_escape_htmltag($_SERVER["REQUEST_URI"]);
3762
+            $syslog .= ", query_string=".DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]);
3763 3763
         } else {                              // Mode CLI
3764
-            $out .= '> ' . Globals::$langs->transnoentities("ErrorInternalErrorDetected") . ":\n" . $argv[0] . "\n";
3765
-            $syslog .= "pid=" . dol_getmypid();
3764
+            $out .= '> '.Globals::$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
3765
+            $syslog .= "pid=".dol_getmypid();
3766 3766
         }
3767 3767
 
3768 3768
         if (is_object($dbError)) {
3769
-            $out .= '<pre>' . print_r($dbError, true) . '</pre>';
3769
+            $out .= '<pre>'.print_r($dbError, true).'</pre>';
3770 3770
             /*
3771 3771
               if ($_SERVER['DOCUMENT_ROOT']) {  // Mode web
3772 3772
               $out .= "<b>" . Globals::$langs->trans("DatabaseTypeManager") . ":</b> " . $dbError->type . "<br>\n";
@@ -3805,31 +3805,31 @@  discard block
 block discarded – undo
3805 3805
                     continue;
3806 3806
                 }
3807 3807
                 if ($_SERVER['DOCUMENT_ROOT']) {  // Mode web
3808
-                    $out .= "<b>" . Globals::$langs->trans("Message") . ":</b> " . DolUtils::dol_escape_htmltag($msg) . "<br>\n";
3808
+                    $out .= "<b>".Globals::$langs->trans("Message").":</b> ".DolUtils::dol_escape_htmltag($msg)."<br>\n";
3809 3809
                 } else {                        // Mode CLI
3810
-                    $out .= '> ' . Globals::$langs->transnoentities("Message") . ":\n" . $msg . "\n";
3810
+                    $out .= '> '.Globals::$langs->transnoentities("Message").":\n".$msg."\n";
3811 3811
                 }
3812
-                $syslog .= ", msg=" . $msg;
3812
+                $syslog .= ", msg=".$msg;
3813 3813
             }
3814 3814
         }
3815 3815
         if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
3816 3816
             xdebug_print_function_stack();
3817
-            $out .= '<b>XDebug informations:</b>' . "<br>\n";
3818
-            $out .= 'File: ' . xdebug_call_file() . "<br>\n";
3819
-            $out .= 'Line: ' . xdebug_call_line() . "<br>\n";
3820
-            $out .= 'Function: ' . xdebug_call_function() . "<br>\n";
3817
+            $out .= '<b>XDebug informations:</b>'."<br>\n";
3818
+            $out .= 'File: '.xdebug_call_file()."<br>\n";
3819
+            $out .= 'Line: '.xdebug_call_line()."<br>\n";
3820
+            $out .= 'Function: '.xdebug_call_function()."<br>\n";
3821 3821
             $out .= "<br>\n";
3822 3822
         }
3823 3823
 
3824 3824
         if (empty($dolibarr_main_prod)) {
3825 3825
             print $out;
3826 3826
         } else {
3827
-            print Globals::$langs->trans("DolibarrHasDetectedError") . '. ';
3827
+            print Globals::$langs->trans("DolibarrHasDetectedError").'. ';
3828 3828
             print Globals::$langs->trans("YouCanSetOptionDolibarrMainProdToZero");
3829 3829
             define("MAIN_CORE_ERROR", 1);
3830 3830
         }
3831 3831
 //else print 'Sorry, an error occured but the parameter $dolibarr_main_prod is defined in conf file so no message is reported to your browser. Please read the log file for error message.';
3832
-        DolUtils::dol_syslog("Error " . $syslog, LOG_ERR);
3832
+        DolUtils::dol_syslog("Error ".$syslog, LOG_ERR);
3833 3833
     }
3834 3834
 
3835 3835
     /**
@@ -3853,14 +3853,14 @@  discard block
 block discarded – undo
3853 3853
         Globals::$langs->load("errors");
3854 3854
         $now = dol_now();
3855 3855
 
3856
-        print '<br><div class="center login_main_message"><div class="' . $morecss . '">';
3857
-        print Globals::$langs->trans("ErrorContactEMail", $email, $prefixcode . DolUtils::dol_print_date($now, '%Y%m%d'));
3856
+        print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
3857
+        print Globals::$langs->trans("ErrorContactEMail", $email, $prefixcode.DolUtils::dol_print_date($now, '%Y%m%d'));
3858 3858
         if ($errormessage) {
3859
-            print '<br><br>' . $errormessage;
3859
+            print '<br><br>'.$errormessage;
3860 3860
         }
3861 3861
         if (is_array($errormessages) && count($errormessages)) {
3862 3862
             foreach ($errormessages as $mesgtoshow) {
3863
-                print '<br><br>' . $mesgtoshow;
3863
+                print '<br><br>'.$mesgtoshow;
3864 3864
             }
3865 3865
         }
3866 3866
         print '</div></div>';
@@ -3918,16 +3918,16 @@  discard block
 block discarded – undo
3918 3918
         }
3919 3919
 
3920 3920
         $tmpsortfield = explode(',', $sortfield);
3921
-        $sortfield1 = trim($tmpsortfield[0]);    // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
3921
+        $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
3922 3922
         $tmpfield = explode(',', $field);
3923
-        $field1 = trim($tmpfield[0]);            // If $field is 'd.datep,d.id', it becomes 'd.datep'
3923
+        $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
3924 3924
 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
3925 3925
 // If field is used as sort criteria we use a specific css class liste_titre_sel
3926 3926
 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
3927 3927
         if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
3928
-            $out .= '<' . $tag . ' class="' . $prefix . 'liste_titre_sel" ' . $moreattrib . '>';
3928
+            $out .= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '.$moreattrib.'>';
3929 3929
         } else {
3930
-            $out .= '<' . $tag . ' class="' . $prefix . 'liste_titre" ' . $moreattrib . '>';
3930
+            $out .= '<'.$tag.' class="'.$prefix.'liste_titre" '.$moreattrib.'>';
3931 3931
         }
3932 3932
 
3933 3933
         if (empty($thead) && $field && empty($disablesortlink)) {    // If this is a sort field
@@ -3935,7 +3935,7 @@  discard block
 block discarded – undo
3935 3935
             $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
3936 3936
             $options = preg_replace('/&+/i', '&', $options);
3937 3937
             if (!preg_match('/^&/', $options)) {
3938
-                $options = '&' . $options;
3938
+                $options = '&'.$options;
3939 3939
             }
3940 3940
 
3941 3941
             $sortordertouseinlink = '';
@@ -3953,7 +3953,7 @@  discard block
 block discarded – undo
3953 3953
                 }
3954 3954
             }
3955 3955
             $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
3956
-            $out .= '<a class="reposition" href="' . $file . '?sortfield=' . $field . '&sortorder=' . $sortordertouseinlink . '&begin=' . $begin . $options . '">';
3956
+            $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'">';
3957 3957
         }
3958 3958
 
3959 3959
         if ($tooltip) {
@@ -3971,7 +3971,7 @@  discard block
 block discarded – undo
3971 3971
             $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
3972 3972
             $options = preg_replace('/&+/i', '&', $options);
3973 3973
             if (!preg_match('/^&/', $options)) {
3974
-                $options = '&' . $options;
3974
+                $options = '&'.$options;
3975 3975
             }
3976 3976
 
3977 3977
             if (!$sortorder || $field1 != $sortfield1) {
@@ -3981,19 +3981,19 @@  discard block
 block discarded – undo
3981 3981
                 if (preg_match('/^DESC/', $sortorder)) {
3982 3982
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
3983 3983
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
3984
-                    $sortimg .= '<span class="nowrap">' . img_up("Z-A", 0) . '</span>';
3984
+                    $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0).'</span>';
3985 3985
                 }
3986 3986
                 if (preg_match('/^ASC/', $sortorder)) {
3987 3987
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
3988 3988
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
3989
-                    $sortimg .= '<span class="nowrap">' . img_down("A-Z", 0) . '</span>';
3989
+                    $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0).'</span>';
3990 3990
                 }
3991 3991
             }
3992 3992
         }
3993 3993
 
3994 3994
         $out .= $sortimg;
3995 3995
 
3996
-        $out .= '</' . $tag . '>';
3996
+        $out .= '</'.$tag.'>';
3997 3997
 
3998 3998
         return $out;
3999 3999
     }
@@ -4008,9 +4008,9 @@  discard block
 block discarded – undo
4008 4008
      */
4009 4009
     static function print_titre($title)
4010 4010
     {
4011
-        DolUtils::dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
4011
+        DolUtils::dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
4012 4012
 
4013
-        print '<div class="titre">' . $title . '</div>';
4013
+        print '<div class="titre">'.$title.'</div>';
4014 4014
     }
4015 4015
 
4016 4016
     /**
@@ -4053,20 +4053,20 @@  discard block
 block discarded – undo
4053 4053
         }
4054 4054
 
4055 4055
         $return .= "\n";
4056
-        $return .= '<table ' . ($id ? 'id="' . $id . '" ' : '') . 'summary="" class="centpercent notopnoleftnoright' . ($morecssontable ? ' ' . $morecssontable : '') . '" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into print_barre_list
4056
+        $return .= '<table '.($id ? 'id="'.$id.'" ' : '').'summary="" class="centpercent notopnoleftnoright'.($morecssontable ? ' '.$morecssontable : '').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into print_barre_list
4057 4057
         if ($picto) {
4058
-            $return .= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">' . DolUtils::img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath) . '</td>';
4058
+            $return .= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">'.DolUtils::img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
4059 4059
         }
4060 4060
         $return .= '<td class="nobordernopadding valignmiddle">';
4061
-        $return .= '<div class="titre inline-block">' . $titre . '</div>';
4061
+        $return .= '<div class="titre inline-block">'.$titre.'</div>';
4062 4062
         $return .= '</td>';
4063 4063
         if (DolUtils::dol_strlen($morehtmlcenter)) {
4064
-            $return .= '<td class="nobordernopadding" align="center" valign="middle">' . $morehtmlcenter . '</td>';
4064
+            $return .= '<td class="nobordernopadding" align="center" valign="middle">'.$morehtmlcenter.'</td>';
4065 4065
         }
4066 4066
         if (DolUtils::dol_strlen($morehtmlright)) {
4067
-            $return .= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">' . $morehtmlright . '</td>';
4067
+            $return .= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">'.$morehtmlright.'</td>';
4068 4068
         }
4069
-        $return .= '</tr></table>' . "\n";
4069
+        $return .= '</tr></table>'."\n";
4070 4070
 
4071 4071
         return $return;
4072 4072
     }
@@ -4114,29 +4114,29 @@  discard block
 block discarded – undo
4114 4114
 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
4115 4115
 
4116 4116
         print "\n";
4117
-        print "<!-- Begin title '" . $titre . "' -->\n";
4118
-        print '<table border="0" class="centpercent notopnoleftnoright' . ($morecss ? ' ' . $morecss : '') . '" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
4117
+        print "<!-- Begin title '".$titre."' -->\n";
4118
+        print '<table border="0" class="centpercent notopnoleftnoright'.($morecss ? ' '.$morecss : '').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
4119 4119
 // Left
4120 4120
 //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
4121 4121
         print '<td class="nobordernopadding valignmiddle">';
4122 4122
         if ($picto && $titre)
4123 4123
             print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4124
-        print '<div class="titre inline-block">' . $titre;
4124
+        print '<div class="titre inline-block">'.$titre;
4125 4125
         if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '')
4126
-            print ' (' . $totalnboflines . ')';
4126
+            print ' ('.$totalnboflines.')';
4127 4127
         print '</div></td>';
4128 4128
 
4129 4129
 // Center
4130 4130
         if ($morehtmlcenter) {
4131
-            print '<td class="nobordernopadding center valignmiddle">' . $morehtmlcenter . '</td>';
4131
+            print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
4132 4132
         }
4133 4133
 
4134 4134
 // Right
4135 4135
         print '<td class="nobordernopadding valignmiddle" align="right">';
4136 4136
         if ($sortfield)
4137
-            $options .= "&sortfield=" . urlencode($sortfield);
4137
+            $options .= "&sortfield=".urlencode($sortfield);
4138 4138
         if ($sortorder)
4139
-            $options .= "&sortorder=" . urlencode($sortorder);
4139
+            $options .= "&sortorder=".urlencode($sortorder);
4140 4140
 // Show navigation bar
4141 4141
         $pagelist = '';
4142 4142
         if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
@@ -4154,40 +4154,40 @@  discard block
 block discarded – undo
4154 4154
                 }
4155 4155
 
4156 4156
                 if ($cpt >= 1) {
4157
-                    $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=0' . $options . '">1</a></li>';
4157
+                    $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
4158 4158
                     if ($cpt > 2)
4159
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4159
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '').'>...</span></li>';
4160 4160
                     else if ($cpt == 2)
4161
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4161
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
4162 4162
                 }
4163 4163
 
4164 4164
                 do {
4165 4165
                     if ($cpt == $page) {
4166
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . '</span></li>';
4166
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '').'>'.($page + 1).'</span></li>';
4167 4167
                     } else {
4168
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . $cpt . $options . '">' . ($cpt + 1) . '</a></li>';
4168
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
4169 4169
                     }
4170 4170
                     $cpt++;
4171 4171
                 } while ($cpt < $nbpages && $cpt <= $page + $maxnbofpage);
4172 4172
 
4173 4173
                 if ($cpt < $nbpages) {
4174 4174
                     if ($cpt < $nbpages - 2)
4175
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4175
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '').'>...</span></li>';
4176 4176
                     else if ($cpt == $nbpages - 2)
4177
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4178
-                    $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 1) . $options . '">' . $nbpages . '</a></li>';
4177
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
4178
+                    $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
4179 4179
                 }
4180 4180
             }
4181 4181
             else {
4182
-                $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . "</li>";
4182
+                $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '').'>'.($page + 1)."</li>";
4183 4183
             }
4184 4184
         }
4185 4185
 
4186
-        print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit);  // output the div and ul for previous/last completed with page numbers into $pagelist
4186
+        print_fleche_navigation($page, $file, $options, $nextpage, $pagelist, $morehtmlright, $savlimit, $totalnboflines, $hideselectlimit); // output the div and ul for previous/last completed with page numbers into $pagelist
4187 4187
 
4188 4188
         print '</td>';
4189 4189
 
4190
-        print '</tr></table>' . "\n";
4190
+        print '</tr></table>'."\n";
4191 4191
         print "<!-- End title -->\n\n";
4192 4192
     }
4193 4193
 
@@ -4218,12 +4218,12 @@  discard block
 block discarded – undo
4218 4218
                 $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4219 4219
 
4220 4220
             print '<li class="pagination">';
4221
-            print '<select class="flat selectlimit" name="limit" title="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")) . '">';
4221
+            print '<select class="flat selectlimit" name="limit" title="'.DolUtils::dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")).'">';
4222 4222
             $tmpchoice = explode(',', $pagesizechoices);
4223
-            $tmpkey = $limit . ':' . $limit;
4223
+            $tmpkey = $limit.':'.$limit;
4224 4224
             if (!in_array($tmpkey, $tmpchoice))
4225 4225
                 $tmpchoice[] = $tmpkey;
4226
-            $tmpkey = Globals::$conf->liste_limit . ':' . Globals::$conf->liste_limit;
4226
+            $tmpkey = Globals::$conf->liste_limit.':'.Globals::$conf->liste_limit;
4227 4227
             if (!in_array($tmpkey, $tmpchoice))
4228 4228
                 $tmpchoice[] = $tmpkey;
4229 4229
             asort($tmpchoice, SORT_NUMERIC);
@@ -4238,7 +4238,7 @@  discard block
 block discarded – undo
4238 4238
                         $selected = ' selected="selected"';
4239 4239
                         $found = true;
4240 4240
                     }
4241
-                    print '<option name="' . $key . '"' . $selected . '>' . DolUtils::dol_escape_htmltag($val) . '</option>' . "\n";
4241
+                    print '<option name="'.$key.'"'.$selected.'>'.DolUtils::dol_escape_htmltag($val).'</option>'."\n";
4242 4242
                 }
4243 4243
             }
4244 4244
             print '</select>';
@@ -4257,20 +4257,20 @@  discard block
 block discarded – undo
4257 4257
             print '</li>';
4258 4258
         }
4259 4259
         if ($page > 0) {
4260
-            print '<li class="pagination"><a class="paginationprevious" href="' . $file . '?page=' . ($page - 1) . $options . '"><i class="fa fa-chevron-left" title="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("Previous")) . '"></i></a></li>';
4260
+            print '<li class="pagination"><a class="paginationprevious" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.DolUtils::dol_escape_htmltag(Globals::$langs->trans("Previous")).'"></i></a></li>';
4261 4261
         }
4262 4262
         if ($betweenarrows) {
4263 4263
             print $betweenarrows;
4264 4264
         }
4265 4265
         if ($nextpage > 0) {
4266
-            print '<li class="pagination"><a class="paginationnext" href="' . $file . '?page=' . ($page + 1) . $options . '"><i class="fa fa-chevron-right" title="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("Next")) . '"></i></a></li>';
4266
+            print '<li class="pagination"><a class="paginationnext" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.DolUtils::dol_escape_htmltag(Globals::$langs->trans("Next")).'"></i></a></li>';
4267 4267
         }
4268 4268
         if ($afterarrows) {
4269 4269
             print '<li class="paginationafterarrows">';
4270 4270
             print $afterarrows;
4271 4271
             print '</li>';
4272 4272
         }
4273
-        print '</ul></div>' . "\n";
4273
+        print '</ul></div>'."\n";
4274 4274
     }
4275 4275
 
4276 4276
     /**
@@ -4292,8 +4292,8 @@  discard block
 block discarded – undo
4292 4292
             $addpercent = true;
4293 4293
         }
4294 4294
         if (preg_match('/\((.*)\)/', $rate, $reg)) {
4295
-            $morelabel = ' (' . $reg[1] . ')';
4296
-            $rate = preg_replace('/\s*' . preg_quote($morelabel, '/') . '/', '', $rate);
4295
+            $morelabel = ' ('.$reg[1].')';
4296
+            $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
4297 4297
         }
4298 4298
         if (preg_match('/\*/', $rate)) {
4299 4299
             $rate = str_replace('*', '', $rate);
@@ -4302,10 +4302,10 @@  discard block
 block discarded – undo
4302 4302
 
4303 4303
 // If rate is '9/9/9' we don't change it.  If rate is '9.000' we apply price()
4304 4304
         if (!preg_match('/\//', $rate))
4305
-            $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4305
+            $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
4306 4306
         else {
4307 4307
 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
4308
-            $ret = $rate . ($addpercent ? '%' : '');
4308
+            $ret = $rate.($addpercent ? '%' : '');
4309 4309
         }
4310 4310
         if (($info_bits & 1) && $usestarfornpr >= 0)
4311 4311
             $ret .= ' *';
@@ -4398,10 +4398,10 @@  discard block
 block discarded – undo
4398 4398
                 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4399 4399
             else {
4400 4400
                 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
4401
-                $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
4401
+                $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
4402 4402
             }
4403 4403
         }
4404
-        $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' ' : '') . $cursymbolafter;
4404
+        $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
4405 4405
 
4406 4406
         return $output;
4407 4407
     }
@@ -4454,7 +4454,7 @@  discard block
 block discarded – undo
4454 4454
 // Now make replace (the main goal of function)
4455 4455
             if ($thousand != ',' && $thousand != '.')
4456 4456
                 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4457
-            $amount = str_replace(' ', '', $amount);  // To avoid spaces
4457
+            $amount = str_replace(' ', '', $amount); // To avoid spaces
4458 4458
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4459 4459
             $amount = str_replace($dec, '.', $amount);
4460 4460
         }
@@ -4483,14 +4483,14 @@  discard block
 block discarded – undo
4483 4483
                 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
4484 4484
                 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
4485 4485
                 $nbofdec = max(0, DolUtils::dol_strlen($temps) - 2); // -2 to remove "0."
4486
-                $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand);  // Convert amount to format with dolibarr dec and thousand
4486
+                $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
4487 4487
             }
4488 4488
 //print "TT".$amount.'<br>';
4489 4489
 // Always make replace because each math static function (like round) replace
4490 4490
 // with local values and we want a number that has a SQL string format x.y
4491 4491
             if ($thousand != ',' && $thousand != '.')
4492 4492
                 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4493
-            $amount = str_replace(' ', '', $amount);  // To avoid spaces
4493
+            $amount = str_replace(' ', '', $amount); // To avoid spaces
4494 4494
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4495 4495
             $amount = str_replace($dec, '.', $amount);
4496 4496
         }
@@ -4511,7 +4511,7 @@  discard block
 block discarded – undo
4511 4511
      */
4512 4512
     static function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
4513 4513
     {
4514
-        require_once DOL_BASE_PATH . '/core/lib/product.lib.php';
4514
+        require_once DOL_BASE_PATH.'/core/lib/product.lib.php';
4515 4515
 
4516 4516
         if (($forceunitoutput == 'no' && $dimension < 1 / 10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
4517 4517
             $dimension = $dimension * 1000000;
@@ -4527,7 +4527,7 @@  discard block
 block discarded – undo
4527 4527
             $unit = $unit + 3;
4528 4528
         }
4529 4529
 
4530
-        $ret = price($dimension, 0, $outputlangs, 0, 0, $round) . ' ' . measuring_units_string($unit, $type);
4530
+        $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
4531 4531
 
4532 4532
         return $ret;
4533 4533
     }
@@ -4551,7 +4551,7 @@  discard block
 block discarded – undo
4551 4551
         if (empty($thirdparty_seller) || !is_object($thirdparty_seller))
4552 4552
             $thirdparty_seller = $mysoc;
4553 4553
 
4554
-        DolUtils::dol_syslog("get_localtax tva=" . $vatrate . " local=" . $local . " thirdparty_buyer id=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '') . "/country_code=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '') . " thirdparty_seller id=" . $thirdparty_seller->id . "/country_code=" . $thirdparty_seller->country_code . " thirdparty_seller localtax1_assuj=" . $thirdparty_seller->localtax1_assuj . "  thirdparty_seller localtax2_assuj=" . $thirdparty_seller->localtax2_assuj);
4554
+        DolUtils::dol_syslog("get_localtax tva=".$vatrate." local=".$local." thirdparty_buyer id=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '')."/country_code=".(is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '')." thirdparty_seller id=".$thirdparty_seller->id."/country_code=".$thirdparty_seller->country_code." thirdparty_seller localtax1_assuj=".$thirdparty_seller->localtax1_assuj."  thirdparty_seller localtax2_assuj=".$thirdparty_seller->localtax2_assuj);
4555 4555
 
4556 4556
         $vatratecleaned = $vatrate;
4557 4557
         if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "xx (yy)"
@@ -4582,7 +4582,7 @@  discard block
 block discarded – undo
4582 4582
             if ($local == 2) {
4583 4583
 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
4584 4584
                 if (!$mysoc->localtax2_assuj)
4585
-                    return 0;  // If main vat is 0, IRPF may be different than 0.
4585
+                    return 0; // If main vat is 0, IRPF may be different than 0.
4586 4586
                 if ($thirdparty_seller->id == $mysoc->id) {
4587 4587
                     if (!$thirdparty_buyer->localtax2_assuj)
4588 4588
                         return 0;
@@ -4636,13 +4636,13 @@  discard block
 block discarded – undo
4636 4636
 
4637 4637
 // By default, search value of local tax on line of common tax
4638 4638
         $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
4639
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4640
-        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $thirdparty_seller->country_code . "'";
4641
-        $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4639
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4640
+        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
4641
+        $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4642 4642
         if ($vatratecode)
4643
-            $sql .= " AND t.code ='" . $vatratecode . "'";  // If we have the code, we use it in priority
4643
+            $sql .= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
4644 4644
         else
4645
-            $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4645
+            $sql .= " AND t.recuperableonly ='".$vatnpr."'";
4646 4646
         DolUtils::dol_syslog("get_localtax", LOG_DEBUG);
4647 4647
         $resql = $db->query($sql);
4648 4648
 
@@ -4688,10 +4688,10 @@  discard block
 block discarded – undo
4688 4688
     {
4689 4689
         // global $db, $mysoc;
4690 4690
         $sql = "SELECT t.localtax1, t.localtax2 ";
4691
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t inner join " . MAIN_DB_PREFIX . "c_country as c ON c.rowid=t.fk_pays";
4692
-        $sql .= " WHERE c.code = '" . $mysoc->country_code . "' AND t.active = 1 AND t.taux=(";
4693
-        $sql .= "  SELECT max(tt.taux) FROM " . MAIN_DB_PREFIX . "c_tva as tt inner join " . MAIN_DB_PREFIX . "c_country as c ON c.rowid=tt.fk_pays";
4694
-        $sql .= "  WHERE c.code = '" . $mysoc->country_code . "' AND tt.active = 1";
4691
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
4692
+        $sql .= " WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
4693
+        $sql .= "  SELECT max(tt.taux) FROM ".MAIN_DB_PREFIX."c_tva as tt inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=tt.fk_pays";
4694
+        $sql .= "  WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
4695 4695
         $sql .= "  )";
4696 4696
 
4697 4697
         $resql = $db->query($sql);
@@ -4721,13 +4721,13 @@  discard block
 block discarded – undo
4721 4721
     {
4722 4722
         // global $db, $mysoc;
4723 4723
 
4724
-        DolUtils::dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
4724
+        DolUtils::dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
4725 4725
 
4726 4726
 // Search local taxes
4727 4727
         $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
4728
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4728
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
4729 4729
         if ($firstparamisid)
4730
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4730
+            $sql .= " WHERE t.rowid = ".(int) $vatrate;
4731 4731
         else {
4732 4732
             $vatratecleaned = $vatrate;
4733 4733
             $vatratecode = '';
@@ -4736,13 +4736,13 @@  discard block
 block discarded – undo
4736 4736
                 $vatratecode = $reg[2];
4737 4737
             }
4738 4738
 
4739
-            $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4739
+            $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
4740 4740
             /* if ($mysoc->country_code == 'ES') $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'";    // vat in spain use the buyer country ??
4741 4741
               else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; */
4742
-            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4743
-            $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4742
+            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
4743
+            $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4744 4744
             if ($vatratecode)
4745
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4745
+                $sql .= " AND t.code = '".$vatratecode."'";
4746 4746
         }
4747 4747
 
4748 4748
         $resql = $db->query($sql);
@@ -4778,13 +4778,13 @@  discard block
 block discarded – undo
4778 4778
     {
4779 4779
         // global $db, $mysoc;
4780 4780
 
4781
-        DolUtils::dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
4781
+        DolUtils::dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
4782 4782
 
4783 4783
 // Search local taxes
4784 4784
         $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
4785
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4785
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
4786 4786
         if ($firstparamisid)
4787
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4787
+            $sql .= " WHERE t.rowid = ".(int) $vatrate;
4788 4788
         else {
4789 4789
             $vatratecleaned = $vatrate;
4790 4790
             $vatratecode = '';
@@ -4793,14 +4793,14 @@  discard block
 block discarded – undo
4793 4793
                 $vatratecode = $reg[2];
4794 4794
             }
4795 4795
 
4796
-            $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4796
+            $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
4797 4797
             if ($mysoc->country_code == 'ES')
4798
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";    // local tax in spain use the buyer country ??
4798
+                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ??
4799 4799
             else
4800
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4801
-            $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4800
+                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
4801
+            $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4802 4802
             if ($vatratecode)
4803
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4803
+                $sql .= " AND t.code = '".$vatratecode."'";
4804 4804
         }
4805 4805
 
4806 4806
         $resql = $db->query($sql);
@@ -4832,7 +4832,7 @@  discard block
 block discarded – undo
4832 4832
     {
4833 4833
         // global $db, Globals::$conf, $mysoc;
4834 4834
 
4835
-        require_once DOL_BASE_PATH . '/product/class/product.class.php';
4835
+        require_once DOL_BASE_PATH.'/product/class/product.class.php';
4836 4836
 
4837 4837
         $ret = 0;
4838 4838
         $found = 0;
@@ -4847,12 +4847,12 @@  discard block
 block discarded – undo
4847 4847
                     $product->get_buyprice($idprodfournprice, 0, 0, 0);
4848 4848
                     $ret = $product->vatrate_supplier;
4849 4849
                     if ($product->default_vat_code)
4850
-                        $ret .= ' (' . $product->default_vat_code . ')';
4850
+                        $ret .= ' ('.$product->default_vat_code.')';
4851 4851
                 }
4852 4852
                 else {
4853
-                    $ret = $product->tva_tx;    // Default vat of product we defined
4853
+                    $ret = $product->tva_tx; // Default vat of product we defined
4854 4854
                     if ($product->default_vat_code)
4855
-                        $ret .= ' (' . $product->default_vat_code . ')';
4855
+                        $ret .= ' ('.$product->default_vat_code.')';
4856 4856
                 }
4857 4857
                 $found = 1;
4858 4858
             }
@@ -4866,8 +4866,8 @@  discard block
 block discarded – undo
4866 4866
             if (empty(Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
4867 4867
 // If vat of product for the country not found or not defined, we return the first higher vat of country.
4868 4868
                 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
4869
-                $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4870
-                $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $thirdparty_seller->country_code . "'";
4869
+                $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4870
+                $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
4871 4871
                 $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
4872 4872
                 $sql .= $db->plimit(1);
4873 4873
 
@@ -4877,16 +4877,16 @@  discard block
 block discarded – undo
4877 4877
                     if ($obj) {
4878 4878
                         $ret = $obj->vat_rate;
4879 4879
                         if ($obj->default_vat_code)
4880
-                            $ret .= ' (' . $obj->default_vat_code . ')';
4880
+                            $ret .= ' ('.$obj->default_vat_code.')';
4881 4881
                     }
4882 4882
                     $db->free($sql);
4883 4883
                 } else
4884 4884
                     dol_print_error($db);
4885 4885
             } else
4886
-                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;    // Forced value if autodetect fails
4886
+                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
4887 4887
         }
4888 4888
 
4889
-        DolUtils::dol_syslog("get_product_vat_for_country: ret=" . $ret);
4889
+        DolUtils::dol_syslog("get_product_vat_for_country: ret=".$ret);
4890 4890
         return $ret;
4891 4891
     }
4892 4892
 
@@ -4904,7 +4904,7 @@  discard block
 block discarded – undo
4904 4904
         // global $db, $mysoc;
4905 4905
 
4906 4906
         if (!class_exists('Product')) {
4907
-            require_once DOL_BASE_PATH . 'product/class/product.class.php';
4907
+            require_once DOL_BASE_PATH.'product/class/product.class.php';
4908 4908
         }
4909 4909
 
4910 4910
         $ret = 0;
@@ -4929,8 +4929,8 @@  discard block
 block discarded – undo
4929 4929
         if (!$found) {
4930 4930
 // If vat of product for the country not found or not defined, we return higher vat of country.
4931 4931
             $sql = "SELECT taux as vat_rate, localtax1, localtax2";
4932
-            $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4933
-            $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $thirdparty_seller->country_code . "'";
4932
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4933
+            $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
4934 4934
             $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
4935 4935
             $sql .= $db->plimit(1);
4936 4936
 
@@ -4947,7 +4947,7 @@  discard block
 block discarded – undo
4947 4947
                 dol_print_error($db);
4948 4948
         }
4949 4949
 
4950
-        DolUtils::dol_syslog("get_product_localtax_for_country: ret=" . $ret);
4950
+        DolUtils::dol_syslog("get_product_localtax_for_country: ret=".$ret);
4951 4951
         return $ret;
4952 4952
     }
4953 4953
 
@@ -4971,7 +4971,7 @@  discard block
 block discarded – undo
4971 4971
     {
4972 4972
         // global Globals::$conf;
4973 4973
 
4974
-        require_once DOL_BASE_PATH . '/core/lib/company.lib.php';
4974
+        require_once DOL_BASE_PATH.'/core/lib/company.lib.php';
4975 4975
 
4976 4976
 // Note: possible values for tva_assuj are 0/1 or franchise/reel
4977 4977
         $seller_use_vat = ((is_numeric($thirdparty_seller->tva_assuj) && !$thirdparty_seller->tva_assuj) || (!is_numeric($thirdparty_seller->tva_assuj) && $thirdparty_seller->tva_assuj == 'franchise')) ? 0 : 1;
@@ -4982,7 +4982,7 @@  discard block
 block discarded – undo
4982 4982
         $buyer_country_code = $thirdparty_buyer->country_code;
4983 4983
         $buyer_in_cee = isInEEC($thirdparty_buyer);
4984 4984
 
4985
-        DolUtils::dol_syslog("get_default_tva: seller use vat=" . $seller_use_vat . ", seller country=" . $seller_country_code . ", seller in cee=" . $seller_in_cee . ", buyer vat number=" . $thirdparty_buyer->tva_intra . " buyer country=" . $buyer_country_code . ", buyer in cee=" . $buyer_in_cee . ", idprod=" . $idprod . ", idprodfournprice=" . $idprodfournprice . ", SERVICE_ARE_ECOMMERCE_200238EC=" . (!empty(Globals::$conf->global->SERVICES_ARE_ECOMMERCE_200238EC) ? Globals::$conf->global->SERVICES_ARE_ECOMMERCE_200238EC : ''));
4985
+        DolUtils::dol_syslog("get_default_tva: seller use vat=".$seller_use_vat.", seller country=".$seller_country_code.", seller in cee=".$seller_in_cee.", buyer vat number=".$thirdparty_buyer->tva_intra." buyer country=".$buyer_country_code.", buyer in cee=".$buyer_in_cee.", idprod=".$idprod.", idprodfournprice=".$idprodfournprice.", SERVICE_ARE_ECOMMERCE_200238EC=".(!empty(Globals::$conf->global->SERVICES_ARE_ECOMMERCE_200238EC) ? Globals::$conf->global->SERVICES_ARE_ECOMMERCE_200238EC : ''));
4986 4986
 
4987 4987
 // If services are eServices according to EU Council Directive 2002/38/EC (http://ec.europa.eu/taxation_customs/taxation/vat/traders/e-commerce/article_1610_en.htm)
4988 4988
 // we use the buyer VAT.
@@ -5048,14 +5048,14 @@  discard block
 block discarded – undo
5048 5048
 
5049 5049
         if ($idprodfournprice > 0) {
5050 5050
             if (!class_exists('ProductFournisseur'))
5051
-                require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5051
+                require_once DOL_BASE_PATH.'/fourn/class/fournisseur.product.class.php';
5052 5052
             $prodprice = new ProductFournisseur($db);
5053 5053
             $prodprice->fetch_product_fournisseur_price($idprodfournprice);
5054 5054
             return $prodprice->fourn_tva_npr;
5055 5055
         }
5056 5056
         elseif ($idprod > 0) {
5057 5057
             if (!class_exists('Product'))
5058
-                require_once DOL_BASE_PATH . 'product/class/product.class.php';
5058
+                require_once DOL_BASE_PATH.'product/class/product.class.php';
5059 5059
             $prod = new Product($db);
5060 5060
             $prod->fetch($idprod);
5061 5061
             return $prod->tva_npr;
@@ -5134,7 +5134,7 @@  discard block
 block discarded – undo
5134 5134
             if ($case == 2)
5135 5135
                 $result = '<input type="checkbox" value="1" checked disabled>';
5136 5136
             if ($case == 3)
5137
-                $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5137
+                $result = '<input type="checkbox" value="1" checked disabled> '.$result;
5138 5138
 
5139 5139
             $classname = 'ok';
5140 5140
         }
@@ -5145,7 +5145,7 @@  discard block
 block discarded – undo
5145 5145
             if ($case == 2)
5146 5146
                 $result = '<input type="checkbox" value="0" disabled>';
5147 5147
             if ($case == 3)
5148
-                $result = '<input type="checkbox" value="0" disabled> ' . $result;
5148
+                $result = '<input type="checkbox" value="0" disabled> '.$result;
5149 5149
 
5150 5150
             if ($color == 2)
5151 5151
                 $classname = 'ok';
@@ -5153,7 +5153,7 @@  discard block
 block discarded – undo
5153 5153
                 $classname = 'error';
5154 5154
         }
5155 5155
         if ($color)
5156
-            return '<font class="' . $classname . '">' . $result . '</font>';
5156
+            return '<font class="'.$classname.'">'.$result.'</font>';
5157 5157
         return $result;
5158 5158
     }
5159 5159
 
@@ -5187,13 +5187,13 @@  discard block
 block discarded – undo
5187 5187
                 $num = preg_replace('/([^0-9])/i', '', $num);
5188 5188
             else
5189 5189
                 $num = preg_replace('/^.*\-/i', '', $num);
5190
-            $num = substr("000" . $num, -$level);
5190
+            $num = substr("000".$num, -$level);
5191 5191
             if ($level == 1)
5192 5192
                 $path = substr($num, 0, 1);
5193 5193
             if ($level == 2)
5194
-                $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5194
+                $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
5195 5195
             if ($level == 3)
5196
-                $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5196
+                $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
5197 5197
         }
5198 5198
         else {
5199 5199
 // TODO
@@ -5224,7 +5224,7 @@  discard block
 block discarded – undo
5224 5224
     {
5225 5225
         // global Globals::$conf;
5226 5226
 
5227
-        DolUtils::dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5227
+        DolUtils::dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
5228 5228
 
5229 5229
         $dir_osencoded = dol_osencode($dir);
5230 5230
         if (@is_dir($dir_osencoded))
@@ -5236,15 +5236,15 @@  discard block
 block discarded – undo
5236 5236
         $ccdir = '';
5237 5237
         if (!empty($dataroot)) {
5238 5238
 // Remove data root from loop
5239
-            $dir = str_replace($dataroot . '/', '', $dir);
5240
-            $ccdir = $dataroot . '/';
5239
+            $dir = str_replace($dataroot.'/', '', $dir);
5240
+            $ccdir = $dataroot.'/';
5241 5241
         }
5242 5242
 
5243 5243
         $cdir = explode("/", $dir);
5244 5244
         $num = count($cdir);
5245 5245
         for ($i = 0; $i < $num; $i++) {
5246 5246
             if ($i > 0)
5247
-                $ccdir .= '/' . $cdir[$i];
5247
+                $ccdir .= '/'.$cdir[$i];
5248 5248
             else
5249 5249
                 $ccdir .= $cdir[$i];
5250 5250
             if (preg_match("/^.:$/", $ccdir, $regs))
@@ -5298,20 +5298,20 @@  discard block
 block discarded – undo
5298 5298
             if ($ccdir) {
5299 5299
                 $ccdir_osencoded = dol_osencode($ccdir);
5300 5300
                 if (!@is_dir($ccdir_osencoded)) {
5301
-                    DolUtils::dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
5301
+                    DolUtils::dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
5302 5302
 
5303 5303
                     umask(0);
5304 5304
                     $dirmaskdec = octdec($newmask);
5305 5305
                     if (empty($newmask)) {
5306 5306
                         $dirmaskdec = empty(Globals::$conf->global->MAIN_UMASK) ? octdec('0755') : octdec(Globals::$conf->global->MAIN_UMASK);
5307 5307
                     }
5308
-                    $dirmaskdec |= octdec('0111');  // Set x bit required for directories
5308
+                    $dirmaskdec |= octdec('0111'); // Set x bit required for directories
5309 5309
                     if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
5310 5310
                         // Si le is_dir a renvoye une fausse info, alors on passe ici.
5311
-                        DolUtils::dol_syslog("functions.lib::dol_mkdir: Fails to create directory '" . $ccdir . "' or directory already exists.", LOG_WARNING);
5311
+                        DolUtils::dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
5312 5312
                         $nberr++;
5313 5313
                     } else {
5314
-                        DolUtils::dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' created", LOG_DEBUG);
5314
+                        DolUtils::dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
5315 5315
                         $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
5316 5316
                         $nbcreated++;
5317 5317
                     }
@@ -5359,9 +5359,9 @@  discard block
 block discarded – undo
5359 5359
         } else {
5360 5360
             $pattern = "/<[^<>]+>/";
5361 5361
 // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
5362
-            $temp = preg_replace($pattern, "", $temp);    // pass 1
5362
+            $temp = preg_replace($pattern, "", $temp); // pass 1
5363 5363
 // $temp after pass 1: <a href="/myurl" title="A title">0000-021
5364
-            $temp = preg_replace($pattern, "", $temp);    // pass 2
5364
+            $temp = preg_replace($pattern, "", $temp); // pass 2
5365 5365
 // $temp after pass 2: 0000-021
5366 5366
         }
5367 5367
 
@@ -5417,8 +5417,8 @@  discard block
 block discarded – undo
5417 5417
     {
5418 5418
         $temp = $stringtoclean;
5419 5419
         foreach ($disallowed_tags as $tagtoremove) {
5420
-            $temp = preg_replace('/<\/?' . $tagtoremove . '>/', '', $temp);
5421
-            $temp = preg_replace('/<\/?' . $tagtoremove . '\s+[^>]*>/', '', $temp);
5420
+            $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
5421
+            $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
5422 5422
         }
5423 5423
         return $temp;
5424 5424
     }
@@ -5435,12 +5435,12 @@  discard block
 block discarded – undo
5435 5435
     {
5436 5436
         if ($nboflines == 1) {
5437 5437
             if (DolUtils::dol_textishtml($text)) {
5438
-                $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text);  // The s pattern modifier means the . can match newline characters
5438
+                $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
5439 5439
                 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
5440 5440
             } else {
5441 5441
                 $firstline = preg_replace('/[\n\r].*/', '', $text);
5442 5442
             }
5443
-            return $firstline . ((strlen($firstline) != strlen($text)) ? '...' : '');
5443
+            return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
5444 5444
         } else {
5445 5445
             $ishtml = 0;
5446 5446
             if (DolUtils::dol_textishtml($text)) {
@@ -5456,7 +5456,7 @@  discard block
 block discarded – undo
5456 5456
                 $pattern = '/(<br[^>]*>)/Uu';
5457 5457
             } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5458 5458
             else
5459
-                $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5459
+                $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
5460 5460
             $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5461 5461
 
5462 5462
             $firstline = '';
@@ -5470,7 +5470,7 @@  discard block
 block discarded – undo
5470 5470
                 $i++;
5471 5471
             }
5472 5472
             unset($a);
5473
-            return $firstline . (($i < $nba) ? '...' : '');
5473
+            return $firstline.(($i < $nba) ? '...' : '');
5474 5474
         }
5475 5475
     }
5476 5476
 
@@ -5541,9 +5541,9 @@  discard block
 block discarded – undo
5541 5541
     static function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
5542 5542
     {
5543 5543
         $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT, $pagecodeto);
5544
-        $ret = preg_replace('/' . "\r\n" . '<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
5545
-        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\r\n" . '/i', "\r\n", $ret);
5546
-        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\n" . '/i', "\n", $ret);
5544
+        $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
5545
+        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
5546
+        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
5547 5547
         $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
5548 5548
         return $ret;
5549 5549
     }
@@ -5556,7 +5556,7 @@  discard block
 block discarded – undo
5556 5556
      */
5557 5557
     static function dol_htmlcleanlastbr($stringtodecode)
5558 5558
     {
5559
-        $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|' . "\n" . '|' . "\r" . ')+$/i', "", $stringtodecode);
5559
+        $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
5560 5560
         return $ret;
5561 5561
     }
5562 5562
 
@@ -5653,7 +5653,7 @@  discard block
 block discarded – undo
5653 5653
             $pattern = '/(<br[^>]*>)/Uu';
5654 5654
         } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5655 5655
         else
5656
-            $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5656
+            $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
5657 5657
         $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5658 5658
 
5659 5659
         $nblines = (int) floor((count($a) + 1) / 2);
@@ -5684,7 +5684,7 @@  discard block
 block discarded – undo
5684 5684
      */
5685 5685
     static function dol_microtime_float()
5686 5686
     {
5687
-        DolUtils::dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
5687
+        DolUtils::dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
5688 5688
 
5689 5689
         return microtime(true);
5690 5690
     }
@@ -5730,9 +5730,9 @@  discard block
 block discarded – undo
5730 5730
             elseif (preg_match('/<h[0-9]>/i', $msg))
5731 5731
                 return true;
5732 5732
             elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg))
5733
-                return true;    // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5733
+                return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5734 5734
             elseif (preg_match('/&#[0-9]{2,3};/i', $msg))
5735
-                return true;    // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5735
+                return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5736 5736
 
5737 5737
             return false;
5738 5738
         }
@@ -5957,7 +5957,7 @@  discard block
 block discarded – undo
5957 5957
                     if ($object->fetch_optionals() > 0) {
5958 5958
                         if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
5959 5959
                             foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
5960
-                                $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
5960
+                                $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
5961 5961
                             }
5962 5962
                         }
5963 5963
                     }
@@ -5969,7 +5969,7 @@  discard block
 block discarded – undo
5969 5969
                     $paymenturl = '';
5970 5970
                 } else {
5971 5971
                     // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
5972
-                    require_once DOL_BASE_PATH . '/core/lib/payments.lib.php';
5972
+                    require_once DOL_BASE_PATH.'/core/lib/payments.lib.php';
5973 5973
                     $outputlangs->loadLangs(array('paypal', 'other'));
5974 5974
                     $typeforonlinepayment = 'free';
5975 5975
                     if (is_object($object) && $object->element == 'commande')
@@ -6030,7 +6030,7 @@  discard block
 block discarded – undo
6030 6030
 
6031 6031
 //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
6032 6032
         if (empty($exclude) || !in_array('date', $exclude)) {
6033
-            include_once DOL_BASE_PATH . '/core/lib/date.lib.php';
6033
+            include_once DOL_BASE_PATH.'/core/lib/date.lib.php';
6034 6034
 
6035 6035
             $tmp = dol_getdate(dol_now(), true);
6036 6036
             $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
@@ -6040,13 +6040,13 @@  discard block
 block discarded – undo
6040 6040
 
6041 6041
             $substitutionarray = array_merge($substitutionarray, array(
6042 6042
                 '__DAY__' => (string) $tmp['mday'],
6043
-                '__DAY_TEXT__' => $outputlangs->trans('Day' . $tmp['wday']), // Monday
6044
-                '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'] . 'Min'), // Mon
6045
-                '__DAY_TEXT_MIN__' => $outputlangs->trans('Short' . $tmp['weekday']), // M
6043
+                '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
6044
+                '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
6045
+                '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
6046 6046
                 '__MONTH__' => (string) $tmp['mon'],
6047
-                '__MONTH_TEXT__' => $outputlangs->trans('Month' . sprintf("%02d", $tmp['mon'])),
6048
-                '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort' . sprintf("%02d", $tmp['mon'])),
6049
-                '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort' . sprintf("%02d", $tmp['mon'])),
6047
+                '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
6048
+                '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
6049
+                '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
6050 6050
                 '__YEAR__' => (string) $tmp['year'],
6051 6051
                 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
6052 6052
                 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
@@ -6105,7 +6105,7 @@  discard block
 block discarded – undo
6105 6105
                 if (!empty($tmp[1]))
6106 6106
                     $outputlangs->load($tmp[1]);
6107 6107
 
6108
-                $text = preg_replace('/__\(' . preg_quote($reg[1], '/') . '\)__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6108
+                $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6109 6109
             }
6110 6110
         }
6111 6111
 
@@ -6121,13 +6121,13 @@  discard block
 block discarded – undo
6121 6121
                 $newval = '*****forbidden*****';
6122 6122
             else
6123 6123
                 $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6124
-            $text = preg_replace('/__\[' . preg_quote($keyfound, '/') . '\]__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($newval) : $newval, $text);
6124
+            $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($newval) : $newval, $text);
6125 6125
         }
6126 6126
 
6127 6127
 // Make substitition for array $substitutionarray
6128 6128
         foreach ($substitutionarray as $key => $value) {
6129 6129
             if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6130
-                $value = '';  // Protection
6130
+                $value = ''; // Protection
6131 6131
             if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6132 6132
                 $value = ''; // Protection
6133 6133
 
@@ -6153,7 +6153,7 @@  discard block
 block discarded – undo
6153 6153
     {
6154 6154
         // global Globals::$conf, $user;
6155 6155
 
6156
-        require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
6156
+        require_once DOL_BASE_PATH.'/core/lib/files.lib.php';
6157 6157
 
6158 6158
 // Add a substitution key for each extrafields, using key __EXTRA_XXX__
6159 6159
 // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
@@ -6183,11 +6183,11 @@  discard block
 block discarded – undo
6183 6183
                 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
6184 6184
                     $module = $reg[1];
6185 6185
 
6186
-                    DolUtils::dol_syslog("Library " . $substitfile['name'] . " found into " . $dir);
6186
+                    DolUtils::dol_syslog("Library ".$substitfile['name']." found into ".$dir);
6187 6187
                     // Include the user's functions file
6188
-                    require_once $dir . $substitfile['name'];
6188
+                    require_once $dir.$substitfile['name'];
6189 6189
                     // Call the user's function, and only if it is defined
6190
-                    $function_name = $module . "_" . $callfunc;
6190
+                    $function_name = $module."_".$callfunc;
6191 6191
                     if (function_exists($function_name))
6192 6192
                         $function_name($substitutionarray, $outputlangs, $object, $parameters);
6193 6193
                 }
@@ -6229,13 +6229,13 @@  discard block
 block discarded – undo
6229 6229
             $outputlangs = Globals::$langs;
6230 6230
 
6231 6231
         if ($date_start && $date_end) {
6232
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', DolUtils::dol_print_date($date_start, $format, false, $outputlangs), DolUtils::dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6232
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', DolUtils::dol_print_date($date_start, $format, false, $outputlangs), DolUtils::dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6233 6233
         }
6234 6234
         if ($date_start && !$date_end) {
6235
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFrom', DolUtils::dol_print_date($date_start, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6235
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', DolUtils::dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6236 6236
         }
6237 6237
         if (!$date_start && $date_end) {
6238
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateUntil', DolUtils::dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6238
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', DolUtils::dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6239 6239
         }
6240 6240
 
6241 6241
         return $out;
@@ -6315,7 +6315,7 @@  discard block
 block discarded – undo
6315 6315
             DolUtils::dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
6316 6316
         } else {
6317 6317
             if (!in_array((string) $style, array('mesgs', 'warnings', 'errors')))
6318
-                dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6318
+                dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
6319 6319
             if (empty($mesgs))
6320 6320
                 setEventMessage($mesg, $style);
6321 6321
             else {
@@ -6384,7 +6384,7 @@  discard block
 block discarded – undo
6384 6384
 
6385 6385
 // If inline message with no format, we add it.
6386 6386
         if ((empty(Globals::$conf->use_javascript_ajax) || !empty(Globals::$conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
6387
-            $divstart = '<div class="' . $style . ' clearboth">';
6387
+            $divstart = '<div class="'.$style.' clearboth">';
6388 6388
             $divend = '</div>';
6389 6389
         }
6390 6390
 
@@ -6411,14 +6411,14 @@  discard block
 block discarded – undo
6411 6411
             if (!empty(Globals::$conf->use_javascript_ajax) && empty(Globals::$conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
6412 6412
                 $return = '<script type="text/javascript">
6413 6413
 					$(document).ready(function() {
6414
-						var block = ' . (!empty(Globals::$conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false") . '
6414
+						var block = ' . (!empty(Globals::$conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
6415 6415
 						if (block) {
6416
-							$.dolEventValid("","' . dol_escape_js($out) . '");
6416
+							$.dolEventValid("","' . dol_escape_js($out).'");
6417 6417
 						} else {
6418 6418
 							/* jnotify(message, preset of message type, keepmessage) */
6419
-							$.jnotify("' . dol_escape_js($out) . '",
6420
-							"' . ($style == "ok" ? 3000 : $style) . '",
6421
-							' . ($style == "ok" ? "false" : "true") . ',
6419
+							$.jnotify("' . dol_escape_js($out).'",
6420
+							"' . ($style == "ok" ? 3000 : $style).'",
6421
+							' . ($style == "ok" ? "false" : "true").',
6422 6422
 							{ remove: static function (){} } );
6423 6423
 						}
6424 6424
 					});
@@ -6613,11 +6613,11 @@  discard block
 block discarded – undo
6613 6613
     {
6614 6614
         // global Globals::$conf;
6615 6615
 
6616
-        $tmp = ini_get("unicode.filesystem_encoding");      // Disponible avec PHP 6.0
6616
+        $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
6617 6617
         if (empty($tmp) && !empty($_SERVER["WINDIR"]))
6618 6618
             $tmp = 'iso-8859-1'; // By default for windows
6619 6619
         if (empty($tmp))
6620
-            $tmp = 'utf-8';          // By default for other
6620
+            $tmp = 'utf-8'; // By default for other
6621 6621
         if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING))
6622 6622
             $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6623 6623
 
@@ -6648,16 +6648,16 @@  discard block
 block discarded – undo
6648 6648
 
6649 6649
 // Check in cache
6650 6650
         if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
6651
-            return $cache_codes[$tablename][$key][$fieldid];   // Found in cache
6651
+            return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
6652 6652
         }
6653 6653
 
6654 6654
         DolUtils::dol_syslog('dol_getIdFromCode (value not found into cache)', LOG_DEBUG);
6655 6655
 
6656
-        $sql = "SELECT " . $fieldid . " as valuetoget";
6657
-        $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
6658
-        $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($key) . "'";
6656
+        $sql = "SELECT ".$fieldid." as valuetoget";
6657
+        $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
6658
+        $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
6659 6659
         if (!empty($entityfilter))
6660
-            $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6660
+            $sql .= " AND entity IN (".getEntity($tablename).")";
6661 6661
 
6662 6662
         $resql = $db->query($sql);
6663 6663
         if ($resql) {
@@ -6688,8 +6688,8 @@  discard block
 block discarded – undo
6688 6688
 //print $strRights."<br>\n";
6689 6689
         $rights = true;
6690 6690
         if ($strRights != '') {
6691
-            $str = 'if(!(' . $strRights . ')) { $rights = false; }';
6692
-            self::dol_eval($str);  // The dol_eval must contains all the// global $xxx used into a condition
6691
+            $str = 'if(!('.$strRights.')) { $rights = false; }';
6692
+            self::dol_eval($str); // The dol_eval must contains all the// global $xxx used into a condition
6693 6693
         }
6694 6694
         return $rights;
6695 6695
     }
@@ -6716,9 +6716,9 @@  discard block
 block discarded – undo
6716 6716
 //print $s."<br>\n";
6717 6717
         if ($returnvalue) {
6718 6718
             if ($hideerrors)
6719
-                return @eval('return ' . $s . ';');
6719
+                return @eval('return '.$s.';');
6720 6720
             else
6721
-                return eval('return ' . $s . ';');
6721
+                return eval('return '.$s.';');
6722 6722
         }
6723 6723
         else {
6724 6724
             if ($hideerrors)
@@ -6772,7 +6772,7 @@  discard block
 block discarded – undo
6772 6772
             $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
6773 6773
         }
6774 6774
 
6775
-        return img_picto_common($codelang, 'flags/' . strtolower($flagImage) . '.png', $moreatt);
6775
+        return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
6776 6776
     }
6777 6777
 
6778 6778
     /**
@@ -6970,16 +6970,16 @@  discard block
 block discarded – undo
6970 6970
             'zu-ZA',
6971 6971
         );
6972 6972
 
6973
-        $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
6973
+        $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
6974 6974
         if (in_array($buildprimarykeytotest, $locales))
6975
-            return strtolower($countrycode) . '_' . strtoupper($countrycode);
6975
+            return strtolower($countrycode).'_'.strtoupper($countrycode);
6976 6976
 
6977 6977
         foreach ($locales as $locale) {
6978 6978
             $locale_language = locale_get_primary_language($locale);
6979 6979
             $locale_region = locale_get_region($locale);
6980 6980
             if (strtoupper($countrycode) == $locale_region) {
6981 6981
 //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
6982
-                return strtolower($locale_language) . '_' . strtoupper($locale_region);
6982
+                return strtolower($locale_language).'_'.strtoupper($locale_region);
6983 6983
             }
6984 6984
         }
6985 6985
 
@@ -7040,7 +7040,7 @@  discard block
 block discarded – undo
7040 7040
                                 $label = Globals::$langs->trans($values[2]);
7041 7041
 
7042 7042
                             //$head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
7043
-                            $head[$h][0] = BASE_URI . preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
7043
+                            $head[$h][0] = BASE_URI.preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
7044 7044
                             $head[$h][1] = $label;
7045 7045
                             $head[$h][2] = str_replace('+', '', $values[1]);
7046 7046
                             $h++;
@@ -7111,43 +7111,43 @@  discard block
 block discarded – undo
7111 7111
         // global $micro_start_time;
7112 7112
 
7113 7113
         if ($zone == 'private')
7114
-            print "\n" . '<!-- Common footer for private page -->' . "\n";
7114
+            print "\n".'<!-- Common footer for private page -->'."\n";
7115 7115
         else
7116
-            print "\n" . '<!-- Common footer for public page -->' . "\n";
7116
+            print "\n".'<!-- Common footer for public page -->'."\n";
7117 7117
 
7118 7118
 // A div to store page_y POST parameter so we can read it using javascript
7119 7119
         print "\n<!-- A div to store page_y POST paramater -->\n";
7120
-        print '<div id="page_y" style="display: none;">' . filter_input(INPUT_POST, 'page_y') . '</div>' . "\n";
7120
+        print '<div id="page_y" style="display: none;">'.filter_input(INPUT_POST, 'page_y').'</div>'."\n";
7121 7121
 
7122 7122
         $parameters = array();
7123
-        $reshook = Globals::$hookManager->executeHooks('printCommonFooter', $parameters);    // Note that $action and $object may have been modified by some hooks
7123
+        $reshook = Globals::$hookManager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
7124 7124
         if (empty($reshook)) {
7125 7125
             if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER))
7126
-                print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7126
+                print Globals::$conf->global->MAIN_HTML_FOOTER."\n";
7127 7127
 
7128 7128
             print "\n";
7129 7129
             if (!empty(Globals::$conf->use_javascript_ajax)) {
7130
-                print '<script type="text/javascript" language="javascript">' . "\n";
7131
-                print 'jQuery(document).ready(function() {' . "\n";
7130
+                print '<script type="text/javascript" language="javascript">'."\n";
7131
+                print 'jQuery(document).ready(function() {'."\n";
7132 7132
 
7133 7133
                 if ($zone == 'private' && empty(Globals::$conf->dol_use_jmobile)) {
7134 7134
                     print "\n";
7135
-                    print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */' . "\n";
7135
+                    print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
7136 7136
                     print 'jQuery(".menuhider").click(function() {';
7137
-                    print '  console.log("We click on .menuhider");' . "\n";
7137
+                    print '  console.log("We click on .menuhider");'."\n";
7138 7138
                     //print "  $('.side-nav').animate({width:'toggle'},200);\n";     // OK with eldy theme but not with md
7139 7139
                     print "  $('.side-nav').toggle()\n";
7140 7140
                     print "  $('.login_block').toggle()\n";
7141
-                    print '});' . "\n";
7141
+                    print '});'."\n";
7142 7142
                 }
7143 7143
 
7144 7144
 // Management of focus and mandatory for fields
7145 7145
                 if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
7146
-                    print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
7146
+                    print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
7147 7147
                     $relativepathstring = $_SERVER["PHP_SELF"];
7148 7148
                     // Clean $relativepathstring
7149 7149
                     if (constant('DOL_BASE_URI'))
7150
-                        $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7150
+                        $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
7151 7151
                     $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
7152 7152
                     $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
7153 7153
                     $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
@@ -7170,9 +7170,9 @@  discard block
 block discarded – undo
7170 7170
                             if ($qualified) {
7171 7171
                                 foreach ($defval as $paramkey => $paramval) {
7172 7172
                                     // Set focus on field
7173
-                                    print 'jQuery("input[name=\'' . $paramkey . '\']").focus();' . "\n";
7174
-                                    print 'jQuery("textarea[name=\'' . $paramkey . '\']").focus();' . "\n";
7175
-                                    print 'jQuery("select[name=\'' . $paramkey . '\']").focus();' . "\n";  // Not really usefull, but we keep it in case of.
7173
+                                    print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
7174
+                                    print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
7175
+                                    print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
7176 7176
                                 }
7177 7177
                             }
7178 7178
                         }
@@ -7196,16 +7196,16 @@  discard block
 block discarded – undo
7196 7196
                             if ($qualified) {
7197 7197
                                 foreach ($defval as $paramkey => $paramval) {
7198 7198
                                     // Add property 'required' on input
7199
-                                    print 'jQuery("input[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";
7200
-                                    print 'jQuery("textarea[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";
7201
-                                    print 'jQuery("select[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";  // required on a select works only if key is "", this does not happen in Dolibarr
7199
+                                    print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
7200
+                                    print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
7201
+                                    print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
7202 7202
                                 }
7203 7203
                             }
7204 7204
                         }
7205 7205
                     }
7206 7206
                 }
7207 7207
 
7208
-                print '});' . "\n";
7208
+                print '});'."\n";
7209 7209
 
7210 7210
 // Google Analytics
7211 7211
 // TODO Add a hook here
@@ -7213,15 +7213,15 @@  discard block
 block discarded – undo
7213 7213
                     if ((Globals::$conf->dol_use_jmobile != 4)) {
7214 7214
                         print "\n";
7215 7215
                         print "/* JS CODE TO ENABLE for google analtics tag */\n";
7216
-                        print '  var _gaq = _gaq || [];' . "\n";
7217
-                        print '  _gaq.push([\'_setAccount\', \'' . Globals::$conf->global->MAIN_GOOGLE_AN_ID . '\']);' . "\n";
7218
-                        print '  _gaq.push([\'_trackPageview\']);' . "\n";
7219
-                        print '' . "\n";
7220
-                        print '  (function() {' . "\n";
7221
-                        print '    var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;' . "\n";
7222
-                        print '    ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';' . "\n";
7223
-                        print '    var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);' . "\n";
7224
-                        print '  })();' . "\n";
7216
+                        print '  var _gaq = _gaq || [];'."\n";
7217
+                        print '  _gaq.push([\'_setAccount\', \''.Globals::$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
7218
+                        print '  _gaq.push([\'_trackPageview\']);'."\n";
7219
+                        print ''."\n";
7220
+                        print '  (function() {'."\n";
7221
+                        print '    var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
7222
+                        print '    ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
7223
+                        print '    var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
7224
+                        print '  })();'."\n";
7225 7225
                     }
7226 7226
                 }
7227 7227
 
@@ -7231,27 +7231,27 @@  discard block
 block discarded – undo
7231 7231
                     print "/* JS CODE TO ENABLE to add memory info */\n";
7232 7232
                     print 'window.console && console.log("';
7233 7233
                     if (!empty(Globals::$conf->global->MEMCACHED_SERVER))
7234
-                        print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7235
-                    print 'MAIN_OPTIMIZE_SPEED=' . (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7234
+                        print 'MEMCACHED_SERVER='.Globals::$conf->global->MEMCACHED_SERVER.' - ';
7235
+                    print 'MAIN_OPTIMIZE_SPEED='.(isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7236 7236
                     if (!empty($micro_start_time)) {   // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in// global variable.
7237 7237
                         $micro_end_time = microtime(true);
7238
-                        print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms';
7238
+                        print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
7239 7239
                     }
7240 7240
                     if (function_exists("memory_get_usage")) {
7241
-                        print ' - Mem: ' . memory_get_usage();
7241
+                        print ' - Mem: '.memory_get_usage();
7242 7242
                     }
7243 7243
                     if (function_exists("xdebug_memory_usage")) {
7244
-                        print ' - XDebug time: ' . ceil(1000 * xdebug_time_index()) . ' ms';
7245
-                        print ' - XDebug mem: ' . xdebug_memory_usage();
7246
-                        print ' - XDebug mem peak: ' . xdebug_peak_memory_usage();
7244
+                        print ' - XDebug time: '.ceil(1000 * xdebug_time_index()).' ms';
7245
+                        print ' - XDebug mem: '.xdebug_memory_usage();
7246
+                        print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
7247 7247
                     }
7248 7248
                     if (function_exists("zend_loader_file_encoded")) {
7249
-                        print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no');
7249
+                        print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
7250 7250
                     }
7251
-                    print '");' . "\n";
7251
+                    print '");'."\n";
7252 7252
                 }
7253 7253
 
7254
-                print "\n" . '</script>' . "\n";
7254
+                print "\n".'</script>'."\n";
7255 7255
             }
7256 7256
 
7257 7257
 // Add Xdebug coverage of code
@@ -7265,7 +7265,7 @@  discard block
 block discarded – undo
7265 7265
                 print "<!-- Start of log output\n";
7266 7266
 //print '<div class="hidden">'."\n";
7267 7267
                 foreach (Globals::$conf->logbuffer as $logline) {
7268
-                    print $logline . "<br>\n";
7268
+                    print $logline."<br>\n";
7269 7269
                 }
7270 7270
 //print '</div>'."\n";
7271 7271
                 print "End of log output -->\n";
@@ -7308,8 +7308,8 @@  discard block
 block discarded – undo
7308 7308
      */
7309 7309
     static function dol_set_focus($selector)
7310 7310
     {
7311
-        print "\n" . '<!-- Set focus onto a specific field -->' . "\n";
7312
-        print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("' . dol_escape_js($selector) . '").focus(); });</script>' . "\n";
7311
+        print "\n".'<!-- Set focus onto a specific field -->'."\n";
7312
+        print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
7313 7313
     }
7314 7314
 
7315 7315
     /**
@@ -7354,7 +7354,7 @@  discard block
 block discarded – undo
7354 7354
             $value = preg_replace('/\*/', '%', $value); // Replace * with %
7355 7355
         }
7356 7356
         if ($mode == 1) {
7357
-            $value = preg_replace('/([<>=]+)\s+([0-9' . preg_quote(Globals::$langs->trans("DecimalSeparator"), '/') . '\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
7357
+            $value = preg_replace('/([<>=]+)\s+([0-9'.preg_quote(Globals::$langs->trans("DecimalSeparator"), '/').'\-])/', '\1\2', $value); // Clean string '< 10' into '<10' so we can the explode on space to get all tests to do
7358 7358
         }
7359 7359
 
7360 7360
         $value = preg_replace('/\s*\|\s*/', '|', $value);
@@ -7383,14 +7383,14 @@  discard block
 block discarded – undo
7383 7383
                     if ($newcrit != '') {
7384 7384
                         $numnewcrit = price2num($newcrit);
7385 7385
                         if (is_numeric($numnewcrit)) {
7386
-                            $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' ' . $operator . ' ' . $numnewcrit;
7386
+                            $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$numnewcrit;
7387 7387
                         } else {
7388
-                            $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
7388
+                            $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
7389 7389
                         }
7390 7390
                         $i2++; // a criteria was added to string
7391 7391
                     }
7392 7392
                 } else if ($mode == 2) {
7393
-                    $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
7393
+                    $newres .= ($i2 > 0 ? ' OR ' : '').$field." IN (".$db->escape(trim($crit)).")";
7394 7394
                     $i2++; // a criteria was added to string
7395 7395
                 } else if ($mode == 3) {
7396 7396
                     $tmparray = explode(',', trim($crit));
@@ -7399,10 +7399,10 @@  discard block
 block discarded – undo
7399 7399
                         foreach ($tmparray as $val) {
7400 7400
                             if ($val) {
7401 7401
                                 $listofcodes .= ($listofcodes ? ',' : '');
7402
-                                $listofcodes .= "'" . $db->escape(trim($val)) . "'";
7402
+                                $listofcodes .= "'".$db->escape(trim($val))."'";
7403 7403
                             }
7404 7404
                         }
7405
-                        $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $listofcodes . ")";
7405
+                        $newres .= ($i2 > 0 ? ' OR ' : '').$field." IN (".$listofcodes.")";
7406 7406
                         $i2++; // a criteria was added to string
7407 7407
                     }
7408 7408
                 } else if ($mode == 4) {
@@ -7411,10 +7411,10 @@  discard block
 block discarded – undo
7411 7411
                         $listofcodes = '';
7412 7412
                         foreach ($tmparray as $val) {
7413 7413
                             if ($val) {
7414
-                                $newres .= ($i2 > 0 ? ' OR (' : '(') . $field . ' LIKE \'' . $db->escape(trim($val)) . ',%\'';
7415
-                                $newres .= ' OR ' . $field . ' = \'' . $db->escape(trim($val)) . '\'';
7416
-                                $newres .= ' OR ' . $field . ' LIKE \'%,' . $db->escape(trim($val)) . '\'';
7417
-                                $newres .= ' OR ' . $field . ' LIKE \'%,' . $db->escape(trim($val)) . ',%\'';
7414
+                                $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape(trim($val)).',%\'';
7415
+                                $newres .= ' OR '.$field.' = \''.$db->escape(trim($val)).'\'';
7416
+                                $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).'\'';
7417
+                                $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).',%\'';
7418 7418
                                 $newres .= ')';
7419 7419
                                 $i2++;
7420 7420
                             }
@@ -7431,9 +7431,9 @@  discard block
 block discarded – undo
7431 7431
                         $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
7432 7432
 
7433 7433
                         if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
7434
-                            $newres .= $field . " = " . (is_numeric(trim($tmpcrit)) ? trim($tmpcrit) : '0');
7434
+                            $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? trim($tmpcrit) : '0');
7435 7435
                         } else {
7436
-                            $newres .= $field . " LIKE '";
7436
+                            $newres .= $field." LIKE '";
7437 7437
 
7438 7438
                             $tmpcrit = trim($tmpcrit);
7439 7439
                             $tmpcrit2 = $tmpcrit;
@@ -7452,7 +7452,7 @@  discard block
 block discarded – undo
7452 7452
                             $newres .= $tmpafter;
7453 7453
                             $newres .= "'";
7454 7454
                             if ($tmpcrit2 == '') {
7455
-                                $newres .= ' OR ' . $field . " IS NULL";
7455
+                                $newres .= ' OR '.$field." IS NULL";
7456 7456
                             }
7457 7457
                         }
7458 7458
 
@@ -7463,10 +7463,10 @@  discard block
 block discarded – undo
7463 7463
                 $i++;
7464 7464
             }
7465 7465
             if ($newres)
7466
-                $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7466
+                $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
7467 7467
             $j++;
7468 7468
         }
7469
-        $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
7469
+        $res = ($nofirstand ? "" : " AND ")."(".$res.")";
7470 7470
 //print 'xx'.$res.'yy';
7471 7471
         return $res;
7472 7472
     }
@@ -7485,8 +7485,8 @@  discard block
 block discarded – undo
7485 7485
         $url = $object->getLastMainDocLink($object->element);
7486 7486
 
7487 7487
         if ($url) {
7488
-            $out .= img_picto('', 'object_globe.png') . ' ' . Globals::$langs->trans("DirectDownloadLink") . '<br>';
7489
-            $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="' . $url . '">';
7488
+            $out .= img_picto('', 'object_globe.png').' '.Globals::$langs->trans("DirectDownloadLink").'<br>';
7489
+            $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
7490 7490
             $out .= ajax_autoselect("directdownloadlink", 0);
7491 7491
         }
7492 7492
         return $out;
@@ -7527,7 +7527,7 @@  discard block
 block discarded – undo
7527 7527
         if ($extName)
7528 7528
             $subdir = 'thumbs/';
7529 7529
 
7530
-        return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
7530
+        return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
7531 7531
     }
7532 7532
 
7533 7533
     /**
@@ -7553,14 +7553,14 @@  discard block
 block discarded – undo
7553 7553
 
7554 7554
         if ($alldata == 1) {
7555 7555
             if ($num_mime !== false)
7556
-                return array('target' => '_blank', 'css' => 'documentpreview', 'url' => DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : ''), 'mime' => dol_mimetype($relativepath),);
7556
+                return array('target' => '_blank', 'css' => 'documentpreview', 'url' => DOL_BASE_URI.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : ''), 'mime' => dol_mimetype($relativepath),);
7557 7557
             else
7558 7558
                 return array();
7559 7559
         }
7560 7560
 
7561 7561
 // old behavior
7562 7562
         if ($num_mime !== false)
7563
-            return 'javascript:document_preview(\'' . dol_escape_js(DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : '')) . '\', \'' . dol_mimetype($relativepath) . '\', \'' . dol_escape_js(Globals::$langs->trans('Preview')) . '\')';
7563
+            return 'javascript:document_preview(\''.dol_escape_js(DOL_BASE_URI.'/document.php?modulepart='.$modulepart.'&attachment=0&file='.urlencode($relativepath).($param ? '&'.$param : '')).'\', \''.dol_mimetype($relativepath).'\', \''.dol_escape_js(Globals::$langs->trans('Preview')).'\')';
7564 7564
         else
7565 7565
             return '';
7566 7566
     }
@@ -7577,11 +7577,11 @@  discard block
 block discarded – undo
7577 7577
         // global Globals::$langs;
7578 7578
         $out = '<script type="text/javascript">
7579 7579
                jQuery(document).ready(static function () {
7580
-				    jQuery("#' . $htmlname . '").click(function() { jQuery(this).select(); } );
7580
+				    jQuery("#' . $htmlname.'").click(function() { jQuery(this).select(); } );
7581 7581
 				});
7582 7582
 		    </script>';
7583 7583
         if ($addlink)
7584
-            $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7584
+            $out .= ' <a href="'.$addlink.'" target="_blank">'.Globals::$langs->trans("Link").'</a>';
7585 7585
         return $out;
7586 7586
     }
7587 7587
 
@@ -7962,9 +7962,9 @@  discard block
 block discarded – undo
7962 7962
 
7963 7963
         if (!isset($dictvalues[$tablename])) {
7964 7964
             $dictvalues[$tablename] = array();
7965
-            $sql = 'SELECT * FROM ' . $tablename . ' WHERE 1';
7965
+            $sql = 'SELECT * FROM '.$tablename.' WHERE 1';
7966 7966
             if ($checkentity)
7967
-                $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
7967
+                $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
7968 7968
 
7969 7969
             $resql = $db->query($sql);
7970 7970
             if ($resql) {
@@ -8002,14 +8002,14 @@  discard block
 block discarded – undo
8002 8002
                 $g = $tmp[1];
8003 8003
                 $b = $tmp[2];
8004 8004
             } else {
8005
-                $hexr = $stringcolor[0] . $stringcolor[1];
8006
-                $hexg = $stringcolor[2] . $stringcolor[3];
8007
-                $hexb = $stringcolor[4] . $stringcolor[5];
8005
+                $hexr = $stringcolor[0].$stringcolor[1];
8006
+                $hexg = $stringcolor[2].$stringcolor[3];
8007
+                $hexb = $stringcolor[4].$stringcolor[5];
8008 8008
                 $r = hexdec($hexr);
8009 8009
                 $g = hexdec($hexg);
8010 8010
                 $b = hexdec($hexb);
8011 8011
             }
8012
-            $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0;    // HSL algorithm
8012
+            $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
8013 8013
             if ($bright > 0.6)
8014 8014
                 $res = 1;
8015 8015
         }
@@ -8044,11 +8044,11 @@  discard block
 block discarded – undo
8044 8044
                 return 0; // Entry is for menus all excluded to external users
8045 8045
         }
8046 8046
         if (!$menuentry['perms'] && $type_user)
8047
-            return 0;            // No permissions and user is external
8047
+            return 0; // No permissions and user is external
8048 8048
         if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED))
8049 8049
             return 0; // No permissions and option to hide when not allowed, even for internal user, is on
8050 8050
         if (!$menuentry['perms'])
8051
-            return 2;               // No permissions and user is external
8051
+            return 2; // No permissions and user is external
8052 8052
         return 1;
8053 8053
     }
8054 8054
 
Please login to merge, or discard this patch.
Braces   +1363 added lines, -981 removed lines patch added patch discarded remove patch
@@ -75,8 +75,9 @@  discard block
 block discarded – undo
75 75
           if ($found) return $result;
76 76
           } */
77 77
 
78
-        if (isset($class::$member))
79
-            return $class::$member;
78
+        if (isset($class::$member)) {
79
+                    return $class::$member;
80
+        }
80 81
         dol_print_error('', 'Try to get a static member "' . $member . '" in class "' . $class . '" that does not exists or is not static.');
81 82
         return null;
82 83
     }
@@ -127,8 +128,9 @@  discard block
 block discarded – undo
127 128
         } else {
128 129
             $out = '';
129 130
             $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
130
-            if (in_array($element, $addzero))
131
-                $out .= '0,';
131
+            if (in_array($element, $addzero)) {
132
+                            $out .= '0,';
133
+            }
132 134
             $out .= Globals::$conf->entity;
133 135
             return $out;
134 136
         }
@@ -307,32 +309,35 @@  discard block
 block discarded – undo
307 309
     {
308 310
         // global $mysoc, $user, Globals::$conf;
309 311
 
310
-        if (empty($paramname))
311
-            return 'BadFirstParameterForDolUtils::GETPOST';
312
+        if (empty($paramname)) {
313
+                    return 'BadFirstParameterForDolUtils::GETPOST';
314
+        }
312 315
         if (empty($check)) {
313 316
             DolUtils::dol_syslog("Deprecated use of DolUtils::GETPOST, called with 1st param = " . $paramname . " and 2nd param is '', when calling page " . $_SERVER["PHP_SELF"], LOG_WARNING);
314 317
             // Enable this line to know who call the DolUtils::GETPOST with '' $check parameter.
315 318
             //var_dump(debug_backtrace()[0]);
316 319
         }
317 320
 
318
-        if (empty($method))
319
-            $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
320
-        elseif ($method == 1)
321
-            $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
322
-        elseif ($method == 2)
323
-            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
324
-        elseif ($method == 3)
325
-            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
326
-        elseif ($method == 4)
327
-            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_COOKIE[$paramname]) ? $_COOKIE[$paramname] : ''));
328
-        else
329
-            return 'BadThirdParameterForDolUtils::GETPOST';
321
+        if (empty($method)) {
322
+                    $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
323
+        } elseif ($method == 1) {
324
+                    $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
325
+        } elseif ($method == 2) {
326
+                    $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
327
+        } elseif ($method == 3) {
328
+                    $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
329
+        } elseif ($method == 4) {
330
+                    $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_COOKIE[$paramname]) ? $_COOKIE[$paramname] : ''));
331
+        } else {
332
+                    return 'BadThirdParameterForDolUtils::GETPOST';
333
+        }
330 334
 
331 335
         if (empty($method) || $method == 3 || $method == 4) {
332 336
             $relativepathstring = $_SERVER["PHP_SELF"];
333 337
             // Clean $relativepathstring
334
-            if (constant('DOL_BASE_URI'))
335
-                $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
338
+            if (constant('DOL_BASE_URI')) {
339
+                            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
340
+            }
336 341
             $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
337 342
             $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
338 343
             //var_dump($relativepathstring);
@@ -381,14 +386,17 @@  discard block
 block discarded – undo
381 386
                                         $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
382 387
                                         $foundintru = 0;
383 388
                                         foreach ($tmpqueryarraytohave as $tmpquerytohave) {
384
-                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
385
-                                                $foundintru = 1;
389
+                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
390
+                                                                                            $foundintru = 1;
391
+                                            }
386 392
                                         }
387
-                                        if (!$foundintru)
388
-                                            $qualified = 1;
393
+                                        if (!$foundintru) {
394
+                                                                                    $qualified = 1;
395
+                                        }
389 396
                                         //var_dump($defkey.'-'.$qualified);
390
-                                    } else
391
-                                        $qualified = 1;
397
+                                    } else {
398
+                                                                            $qualified = 1;
399
+                                    }
392 400
 
393 401
                                     if ($qualified) {
394 402
                                         //var_dump($user->default_values[$relativepathstring][$defkey]['createform']);
@@ -415,20 +423,24 @@  discard block
 block discarded – undo
415 423
                                             $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
416 424
                                             $foundintru = 0;
417 425
                                             foreach ($tmpqueryarraytohave as $tmpquerytohave) {
418
-                                                if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
419
-                                                    $foundintru = 1;
426
+                                                if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
427
+                                                                                                    $foundintru = 1;
428
+                                                }
420 429
                                             }
421
-                                            if (!$foundintru)
422
-                                                $qualified = 1;
430
+                                            if (!$foundintru) {
431
+                                                                                            $qualified = 1;
432
+                                            }
423 433
                                             //var_dump($defkey.'-'.$qualified);
424
-                                        } else
425
-                                            $qualified = 1;
434
+                                        } else {
435
+                                                                                    $qualified = 1;
436
+                                        }
426 437
 
427 438
                                         if ($qualified) {
428 439
                                             $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
429 440
                                             foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
430
-                                                if ($out)
431
-                                                    $out .= ', ';
441
+                                                if ($out) {
442
+                                                                                                    $out .= ', ';
443
+                                                }
432 444
                                                 if ($paramname == 'sortfield') {
433 445
                                                     $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
434 446
                                                 }
@@ -448,14 +460,17 @@  discard block
 block discarded – undo
448 460
                                         $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
449 461
                                         $foundintru = 0;
450 462
                                         foreach ($tmpqueryarraytohave as $tmpquerytohave) {
451
-                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
452
-                                                $foundintru = 1;
463
+                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
464
+                                                                                            $foundintru = 1;
465
+                                            }
453 466
                                         }
454
-                                        if (!$foundintru)
455
-                                            $qualified = 1;
467
+                                        if (!$foundintru) {
468
+                                                                                    $qualified = 1;
469
+                                        }
456 470
                                         //var_dump($defkey.'-'.$qualified);
457
-                                    } else
458
-                                        $qualified = 1;
471
+                                    } else {
472
+                                                                            $qualified = 1;
473
+                                    }
459 474
 
460 475
                                     if ($qualified) {
461 476
                                         if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
@@ -527,8 +542,10 @@  discard block
 block discarded – undo
527 542
                     $newout = $user->fk_user;
528 543
                 } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
529 544
                     $newout = Globals::$conf->entity;
530
-                } else
531
-                    $newout = '';     // Key not found, we replace with empty string
545
+                } else {
546
+                                    $newout = '';
547
+                }
548
+                // Key not found, we replace with empty string
532 549
 
533 550
 
534 551
 
@@ -587,18 +604,20 @@  discard block
 block discarded – undo
587 604
                 }
588 605
                 break;
589 606
             case 'intcomma':
590
-                if (preg_match('/[^0-9,-]+/i', $out))
591
-                    $out = '';
607
+                if (preg_match('/[^0-9,-]+/i', $out)) {
608
+                                    $out = '';
609
+                }
592 610
                 break;
593 611
             case 'alpha':
594 612
                 if (!is_array($out)) {
595 613
                     $out = trim($out);
596 614
                     // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
597 615
                     // '../' is dangerous because it allows dir transversals
598
-                    if (preg_match('/"/', $out))
599
-                        $out = '';
600
-                    else if (preg_match('/\.\.\//', $out))
601
-                        $out = '';
616
+                    if (preg_match('/"/', $out)) {
617
+                                            $out = '';
618
+                    } else if (preg_match('/\.\.\//', $out)) {
619
+                                            $out = '';
620
+                    }
602 621
                 }
603 622
                 break;
604 623
             case 'san_alpha':
@@ -607,27 +626,31 @@  discard block
 block discarded – undo
607 626
             case 'aZ':
608 627
                 if (!is_array($out)) {
609 628
                     $out = trim($out);
610
-                    if (preg_match('/[^a-z]+/i', $out))
611
-                        $out = '';
629
+                    if (preg_match('/[^a-z]+/i', $out)) {
630
+                                            $out = '';
631
+                    }
612 632
                 }
613 633
                 break;
614 634
             case 'aZ09':
615 635
                 if (!is_array($out)) {
616 636
                     $out = trim($out);
617
-                    if (preg_match('/[^a-z0-9_\-\.]+/i', $out))
618
-                        $out = '';
637
+                    if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
638
+                                            $out = '';
639
+                    }
619 640
                 }
620 641
                 break;
621 642
             case 'aZ09comma':  // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
622 643
                 if (!is_array($out)) {
623 644
                     $out = trim($out);
624
-                    if (preg_match('/[^a-z0-9_\-\.,]+/i', $out))
625
-                        $out = '';
645
+                    if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
646
+                                            $out = '';
647
+                    }
626 648
                 }
627 649
                 break;
628 650
             case 'array':
629
-                if (!is_array($out) || empty($out))
630
-                    $out = array();
651
+                if (!is_array($out) || empty($out)) {
652
+                                    $out = array();
653
+                }
631 654
                 break;
632 655
             case 'nohtml':  // Recommended for most scalar parameters
633 656
                 $out = dol_string_nohtmltag($out, 0);
@@ -637,16 +660,18 @@  discard block
 block discarded – undo
637 660
                     $out = trim($out);
638 661
                     // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
639 662
                     // '../' is dangerous because it allows dir transversals
640
-                    if (preg_match('/"/', $out))
641
-                        $out = '';
642
-                    else if (preg_match('/\.\.\//', $out))
643
-                        $out = '';
663
+                    if (preg_match('/"/', $out)) {
664
+                                            $out = '';
665
+                    } else if (preg_match('/\.\.\//', $out)) {
666
+                                            $out = '';
667
+                    }
644 668
                     $out = dol_string_nohtmltag($out);
645 669
                 }
646 670
                 break;
647 671
             case 'custom':
648
-                if (empty($filter))
649
-                    return 'BadFourthParameterForDolUtils::GETPOST';
672
+                if (empty($filter)) {
673
+                                    return 'BadFourthParameterForDolUtils::GETPOST';
674
+                }
650 675
                 $out = filter_var($out, $filter, $options);
651 676
                 break;
652 677
         }
@@ -764,11 +789,11 @@  discard block
 block discarded – undo
764 789
                 }
765 790
             }
766 791
             if ($returnemptyifnotfound) {        // Not found into alternate dir
767
-                if ($returnemptyifnotfound == 1 || !file_exists($res))
768
-                    return '';
792
+                if ($returnemptyifnotfound == 1 || !file_exists($res)) {
793
+                                    return '';
794
+                }
769 795
             }
770
-        }
771
-        else {    // For an url path
796
+        } else {    // For an url path
772 797
 // We try to get local path of file on filesystem from url
773 798
 // Note that trying to know if a file on disk exist by forging path on disk from url
774 799
 // works only for some web server and some setup. This is bugged when
@@ -862,12 +887,14 @@  discard block
 block discarded – undo
862 887
     static function dol_size($size, $type = '')
863 888
     {
864 889
         //global Globals::$conf;
865
-        if (empty(Globals::$conf->dol_optimize_smallscreen))
866
-            return $size;
867
-        if ($type == 'width' && $size > 250)
868
-            return 250;
869
-        else
870
-            return 10;
890
+        if (empty(Globals::$conf->dol_optimize_smallscreen)) {
891
+                    return $size;
892
+        }
893
+        if ($type == 'width' && $size > 250) {
894
+                    return 250;
895
+        } else {
896
+                    return 10;
897
+        }
871 898
     }
872 899
 
873 900
     /**
@@ -967,9 +994,10 @@  discard block
 block discarded – undo
967 994
     {
968 995
         $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°');  // more complete than dol_sanitizeFileName
969 996
         $forbidden_chars_to_remove = array();
970
-        if (is_array($badcharstoreplace))
971
-            $forbidden_chars_to_replace = $badcharstoreplace;
972
-//$forbidden_chars_to_remove=array("(",")");
997
+        if (is_array($badcharstoreplace)) {
998
+                    $forbidden_chars_to_replace = $badcharstoreplace;
999
+        }
1000
+        //$forbidden_chars_to_remove=array("(",")");
973 1001
 
974 1002
         return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
975 1003
     }
@@ -1005,9 +1033,9 @@  discard block
 block discarded – undo
1005 1033
         if (empty($mode)) {
1006 1034
             $substitjs["'"] = "\\'";
1007 1035
             $substitjs['"'] = "\\'";
1008
-        } else if ($mode == 1)
1009
-            $substitjs["'"] = "\\'";
1010
-        else if ($mode == 2) {
1036
+        } else if ($mode == 1) {
1037
+                    $substitjs["'"] = "\\'";
1038
+        } else if ($mode == 2) {
1011 1039
             $substitjs['"'] = '\\"';
1012 1040
         } else if ($mode == 3) {
1013 1041
             $substitjs["'"] = "\\'";
@@ -1029,10 +1057,12 @@  discard block
 block discarded – undo
1029 1057
     {
1030 1058
 // escape quotes and backslashes, newlines, etc.
1031 1059
         $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');  // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1032
-        if (!$keepb)
1033
-            $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1034
-        if (!$keepn)
1035
-            $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1060
+        if (!$keepb) {
1061
+                    $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1062
+        }
1063
+        if (!$keepn) {
1064
+                    $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1065
+        }
1036 1066
         return htmlentities($tmp, ENT_COMPAT, 'UTF-8');      // TODO Use htmlspecialchars instead, that make only required change for html tags
1037 1067
     }
1038 1068
 
@@ -1082,8 +1112,9 @@  discard block
 block discarded – undo
1082 1112
     {
1083 1113
         // global Globals::$conf, $user;
1084 1114
 // If syslog module enabled
1085
-        if (empty(Globals::$conf->syslog->enabled))
1086
-            return;
1115
+        if (empty(Globals::$conf->syslog->enabled)) {
1116
+                    return;
1117
+        }
1087 1118
 
1088 1119
         if ($ident < 0) {
1089 1120
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
@@ -1097,8 +1128,9 @@  discard block
 block discarded – undo
1097 1128
             if (!in_array($level, $logLevels, true)) {
1098 1129
                 throw new Exception('Incorrect log level');
1099 1130
             }
1100
-            if ($level > Globals::$conf->global->SYSLOG_LEVEL)
1101
-                return;
1131
+            if ($level > Globals::$conf->global->SYSLOG_LEVEL) {
1132
+                            return;
1133
+            }
1102 1134
 
1103 1135
             $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1104 1136
 // If adding log inside HTML page is required
@@ -1123,24 +1155,30 @@  discard block
 block discarded – undo
1123 1155
             );
1124 1156
 
1125 1157
 // This is when server run behind a reverse proxy
1126
-            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
1127
-                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1128
-// This is when server run normally on a server
1129
-            else if (!empty($_SERVER["REMOTE_ADDR"]))
1130
-                $data['ip'] = $_SERVER['REMOTE_ADDR'];
1131
-// This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1132
-            else if (!empty($_SERVER['SERVER_ADDR']))
1133
-                $data['ip'] = $_SERVER['SERVER_ADDR'];
1134
-// This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
1135
-            else if (!empty($_SERVER['COMPUTERNAME']))
1136
-                $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1137
-// This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
1138
-            else if (!empty($_SERVER['LOGNAME']))
1139
-                $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1140
-// Loop on each log handler and send output
1158
+            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1159
+                            $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1160
+            }
1161
+            // This is when server run normally on a server
1162
+            else if (!empty($_SERVER["REMOTE_ADDR"])) {
1163
+                            $data['ip'] = $_SERVER['REMOTE_ADDR'];
1164
+            }
1165
+            // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1166
+            else if (!empty($_SERVER['SERVER_ADDR'])) {
1167
+                            $data['ip'] = $_SERVER['SERVER_ADDR'];
1168
+            }
1169
+            // This is when PHP session is ran outside a web server, like from Windows command line (Not always defined, but useful if OS defined it).
1170
+            else if (!empty($_SERVER['COMPUTERNAME'])) {
1171
+                            $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1172
+            }
1173
+            // This is when PHP session is ran outside a web server, like from Linux command line (Not always defined, but usefull if OS defined it).
1174
+            else if (!empty($_SERVER['LOGNAME'])) {
1175
+                            $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1176
+            }
1177
+            // Loop on each log handler and send output
1141 1178
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
1142
-                if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler)
1143
-                    continue;
1179
+                if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
1180
+                                    continue;
1181
+                }
1144 1182
                 $loghandlerinstance->export($data, $suffixinfilename);
1145 1183
             }
1146 1184
             unset($data);
@@ -1196,13 +1234,15 @@  discard block
 block discarded – undo
1196 1234
 
1197 1235
 // Show title
1198 1236
         $showtitle = 1;
1199
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
1200
-            $showtitle = 0;
1237
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1238
+                    $showtitle = 0;
1239
+        }
1201 1240
         if (!empty($title) && $showtitle) {
1202 1241
             $limittitle = 30;
1203 1242
             $out .= '<a class="tabTitle">';
1204
-            if ($picto)
1205
-                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1243
+            if ($picto) {
1244
+                            $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1245
+            }
1206 1246
             $out .= '<span class="tabTitleText">' . dol_trunc($title, $limittitle) . '</span>';
1207 1247
             $out .= '</a>';
1208 1248
         }
@@ -1211,12 +1251,14 @@  discard block
 block discarded – undo
1211 1251
         $maxkey = -1;
1212 1252
         if (is_array($links) && !empty($links)) {
1213 1253
             $keys = array_keys($links);
1214
-            if (count($keys))
1215
-                $maxkey = max($keys);
1254
+            if (count($keys)) {
1255
+                            $maxkey = max($keys);
1256
+            }
1216 1257
         }
1217 1258
 
1218
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
1219
-            Globals::$conf->global->MAIN_MAXTABS_IN_CARD = 2;
1259
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1260
+                    Globals::$conf->global->MAIN_MAXTABS_IN_CARD = 2;
1261
+        }
1220 1262
 
1221 1263
 // Show tabs
1222 1264
         $bactive = false;
@@ -1229,8 +1271,9 @@  discard block
 block discarded – undo
1229 1271
         for ($i = 0; $i <= $maxkey; $i++) {
1230 1272
             if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
1231 1273
 // If active tab is already present
1232
-                if ($i >= $limittoshow)
1233
-                    $limittoshow--;
1274
+                if ($i >= $limittoshow) {
1275
+                                    $limittoshow--;
1276
+                }
1234 1277
             }
1235 1278
         }
1236 1279
 
@@ -1271,12 +1314,12 @@  discard block
 block discarded – undo
1271 1314
                 }
1272 1315
                 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
1273 1316
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1274
-                    if (!empty($links[$i][0]))
1275
-                        $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1276
-                    else
1277
-                        $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1278
-                }
1279
-                else if (!empty($links[$i][1])) {
1317
+                    if (!empty($links[$i][0])) {
1318
+                                            $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1319
+                    } else {
1320
+                                            $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1321
+                    }
1322
+                } else if (!empty($links[$i][1])) {
1280 1323
                     $outmore .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1281 1324
                     $outmore .= preg_replace('/([a-z])\/([a-z])/i', '\\1 / \\2', $links[$i][1]); // Replace x/y with x / y to allow wrap on long composed texts.
1282 1325
                     $outmore .= '</a>' . "\n";
@@ -1287,8 +1330,9 @@  discard block
 block discarded – undo
1287 1330
             }
1288 1331
             $displaytab = $i;
1289 1332
         }
1290
-        if ($popuptab)
1291
-            $outmore .= '</div>';
1333
+        if ($popuptab) {
1334
+                    $outmore .= '</div>';
1335
+        }
1292 1336
 
1293 1337
         if ($displaytab > $limittoshow) {
1294 1338
             $left = (Globals::$langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
@@ -1311,8 +1355,9 @@  discard block
 block discarded – undo
1311 1355
 
1312 1356
         $out .= "</div>\n";
1313 1357
 
1314
-        if (!$notab || $notab == -1)
1315
-            $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1358
+        if (!$notab || $notab == -1) {
1359
+                    $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1360
+        }
1316 1361
 
1317 1362
         $parameters = array('tabname' => $active, 'out' => $out);
1318 1363
         $reshook = Globals::$hookManager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
@@ -1342,10 +1387,11 @@  discard block
 block discarded – undo
1342 1387
      */
1343 1388
     static function dol_get_fiche_end($notab = 0)
1344 1389
     {
1345
-        if (!$notab || $notab == -1)
1346
-            return "\n</div>\n";
1347
-        else
1348
-            return '';
1390
+        if (!$notab || $notab == -1) {
1391
+                    return "\n</div>\n";
1392
+        } else {
1393
+                    return '';
1394
+        }
1349 1395
     }
1350 1396
 
1351 1397
     /**
@@ -1377,8 +1423,9 @@  discard block
 block discarded – undo
1377 1423
         $showimage = 1;
1378 1424
         $entity = (empty($object->entity) ? Globals::$conf->entity : $object->entity);
1379 1425
         $showbarcode = empty(Globals::$conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
1380
-        if (!empty(Globals::$conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance))
1381
-            $showbarcode = 0;
1426
+        if (!empty(Globals::$conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
1427
+                    $showbarcode = 0;
1428
+        }
1382 1429
         $modulepart = 'unknown';
1383 1430
 
1384 1431
         if ($object->element == 'societe') {
@@ -1483,8 +1530,10 @@  discard block
 block discarded – undo
1483 1530
                         } else {
1484 1531
                             $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
1485 1532
                         }
1486
-                        if (empty($subdir))
1487
-                            $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
1533
+                        if (empty($subdir)) {
1534
+                                                    $subdir = 'errorgettingsubdirofobject';
1535
+                        }
1536
+                        // Protection to avoid to return empty path
1488 1537
 
1489 1538
                         $filepath = $dir_output . $subdir . "/";
1490 1539
 
@@ -1505,14 +1554,16 @@  discard block
 block discarded – undo
1505 1554
                                 if (empty(Globals::$conf->global->MAIN_DISABLE_PDF_THUMBS)) {  // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
1506 1555
                                     include_once DOL_BASE_PATH . '/core/lib/files.lib.php';
1507 1556
                                     $ret = dol_convert_file($file, 'png', $fileimage);
1508
-                                    if ($ret < 0)
1509
-                                        $error++;
1557
+                                    if ($ret < 0) {
1558
+                                                                            $error++;
1559
+                                    }
1510 1560
                                 }
1511 1561
                             }
1512 1562
 
1513 1563
                             $heightforphotref = 70;
1514
-                            if (!empty(Globals::$conf->dol_optimize_smallscreen))
1515
-                                $heightforphotref = 60;
1564
+                            if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1565
+                                                            $heightforphotref = 60;
1566
+                            }
1516 1567
                             // Si fichier png PDF d'1 page trouve
1517 1568
                             if (file_exists($fileimage)) {
1518 1569
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
@@ -1548,8 +1599,10 @@  discard block
 block discarded – undo
1548 1599
                         $width = 14;
1549 1600
                         $cssclass = 'photorefcenter';
1550 1601
                         $picto = $object->picto;
1551
-                        if ($object->element == 'project' && !$object->public)
1552
-                            $picto = 'project'; // instead of projectpub
1602
+                        if ($object->element == 'project' && !$object->public) {
1603
+                                                    $picto = 'project';
1604
+                        }
1605
+                        // instead of projectpub
1553 1606
                         $nophoto = img_picto('', 'object_' . $picto, '', false, 1);
1554 1607
                     }
1555 1608
                     $morehtmlleft .= '<!-- No photo to show -->';
@@ -1560,8 +1613,9 @@  discard block
 block discarded – undo
1560 1613
             }
1561 1614
         }
1562 1615
 
1563
-        if ($showbarcode)
1564
-            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1616
+        if ($showbarcode) {
1617
+                    $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1618
+        }
1565 1619
 
1566 1620
         if ($object->element == 'societe') {
1567 1621
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->societe->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
@@ -1585,35 +1639,37 @@  discard block
 block discarded – undo
1585 1639
             }
1586 1640
         } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) {
1587 1641
             $tmptxt = $object->getLibStatut(6, $object->totalpaye);
1588
-            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone')
1589
-                $tmptxt = $object->getLibStatut(5, $object->totalpaye);
1642
+            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone') {
1643
+                            $tmptxt = $object->getLibStatut(5, $object->totalpaye);
1644
+            }
1590 1645
             $morehtmlstatus .= $tmptxt;
1591
-        }
1592
-        elseif ($object->element == 'contrat' || $object->element == 'contract') {
1593
-            if ($object->statut == 0)
1594
-                $morehtmlstatus .= $object->getLibStatut(5);
1595
-            else
1596
-                $morehtmlstatus .= $object->getLibStatut(4);
1597
-        }
1598
-        elseif ($object->element == 'facturerec') {
1599
-            if ($object->frequency == 0)
1600
-                $morehtmlstatus .= $object->getLibStatut(2);
1601
-            else
1602
-                $morehtmlstatus .= $object->getLibStatut(5);
1603
-        }
1604
-        elseif ($object->element == 'project_task') {
1646
+        } elseif ($object->element == 'contrat' || $object->element == 'contract') {
1647
+            if ($object->statut == 0) {
1648
+                            $morehtmlstatus .= $object->getLibStatut(5);
1649
+            } else {
1650
+                            $morehtmlstatus .= $object->getLibStatut(4);
1651
+            }
1652
+        } elseif ($object->element == 'facturerec') {
1653
+            if ($object->frequency == 0) {
1654
+                            $morehtmlstatus .= $object->getLibStatut(2);
1655
+            } else {
1656
+                            $morehtmlstatus .= $object->getLibStatut(5);
1657
+            }
1658
+        } elseif ($object->element == 'project_task') {
1605 1659
             $object->fk_statut = 1;
1606
-            if ($object->progress > 0)
1607
-                $object->fk_statut = 2;
1608
-            if ($object->progress >= 100)
1609
-                $object->fk_statut = 3;
1660
+            if ($object->progress > 0) {
1661
+                            $object->fk_statut = 2;
1662
+            }
1663
+            if ($object->progress >= 100) {
1664
+                            $object->fk_statut = 3;
1665
+            }
1610 1666
             $tmptxt = $object->getLibStatut(5);
1611 1667
             $morehtmlstatus .= $tmptxt;  // No status on task
1612
-        }
1613
-        else { // Generic case
1668
+        } else { // Generic case
1614 1669
             $tmptxt = $object->getLibStatut(6);
1615
-            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone')
1616
-                $tmptxt = $object->getLibStatut(5);
1670
+            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone') {
1671
+                            $tmptxt = $object->getLibStatut(5);
1672
+            }
1617 1673
             $morehtmlstatus .= $tmptxt;
1618 1674
         }
1619 1675
 
@@ -1627,13 +1683,15 @@  discard block
 block discarded – undo
1627 1683
         }
1628 1684
 
1629 1685
 // Add alias for thirdparty
1630
-        if (!empty($object->name_alias))
1631
-            $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1686
+        if (!empty($object->name_alias)) {
1687
+                    $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1688
+        }
1632 1689
 
1633 1690
 // Add label
1634 1691
         if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task') {
1635
-            if (!empty($object->label))
1636
-                $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1692
+            if (!empty($object->label)) {
1693
+                            $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1694
+            }
1637 1695
         }
1638 1696
 
1639 1697
         if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files') {
@@ -1666,15 +1724,19 @@  discard block
 block discarded – undo
1666 1724
     {
1667 1725
         // global Globals::$conf, Globals::$langs;
1668 1726
         $ret = '';
1669
-        if ($fieldrequired)
1670
-            $ret .= '<span class="fieldrequired">';
1671
-        if ((Globals::$conf->dol_use_jmobile != 4))
1672
-            $ret .= '<label for="' . $fieldkey . '">';
1727
+        if ($fieldrequired) {
1728
+                    $ret .= '<span class="fieldrequired">';
1729
+        }
1730
+        if ((Globals::$conf->dol_use_jmobile != 4)) {
1731
+                    $ret .= '<label for="' . $fieldkey . '">';
1732
+        }
1673 1733
         $ret .= Globals::$langs->trans($langkey);
1674
-        if ((Globals::$conf->dol_use_jmobile != 4))
1675
-            $ret .= '</label>';
1676
-        if ($fieldrequired)
1677
-            $ret .= '</span>';
1734
+        if ((Globals::$conf->dol_use_jmobile != 4)) {
1735
+                    $ret .= '</label>';
1736
+        }
1737
+        if ($fieldrequired) {
1738
+                    $ret .= '</span>';
1739
+        }
1678 1740
         return $ret;
1679 1741
     }
1680 1742
 
@@ -1689,8 +1751,9 @@  discard block
 block discarded – undo
1689 1751
     {
1690 1752
         // global $bc;
1691 1753
         $ret = ' ' . $bc[$var];
1692
-        if ($moreclass)
1693
-            $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1754
+        if ($moreclass) {
1755
+                    $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1756
+        }
1694 1757
         return $ret;
1695 1758
     }
1696 1759
 
@@ -1721,18 +1784,18 @@  discard block
 block discarded – undo
1721 1784
             if ($object->state) {
1722 1785
                 $ret .= ($ret ? ", " : '') . $object->state;
1723 1786
             }
1724
-            if ($object->zip)
1725
-                $ret .= ($ret ? ", " : '') . $object->zip;
1726
-        }
1727
-        else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1787
+            if ($object->zip) {
1788
+                            $ret .= ($ret ? ", " : '') . $object->zip;
1789
+            }
1790
+        } else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1728 1791
             $ret .= ($ret ? $sep : '' ) . $object->town;
1729 1792
             if ($object->state) {
1730 1793
                 $ret .= ($ret ? ", " : '') . $object->state;
1731 1794
             }
1732
-            if ($object->zip)
1733
-                $ret .= ($ret ? $sep : '' ) . $object->zip;
1734
-        }
1735
-        else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1795
+            if ($object->zip) {
1796
+                            $ret .= ($ret ? $sep : '' ) . $object->zip;
1797
+            }
1798
+        } else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1736 1799
             $ret .= ($ret ? $sep : '' ) . $object->zip;
1737 1800
             $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1738 1801
             if ($object->state) {
@@ -1749,8 +1812,9 @@  discard block
 block discarded – undo
1749 1812
                 $ret .= ($ret ? ", " : '') . $object->state;
1750 1813
             }
1751 1814
         }
1752
-        if (!is_object($outputlangs))
1753
-            $outputlangs = Globals::$langs;
1815
+        if (!is_object($outputlangs)) {
1816
+                    $outputlangs = Globals::$langs;
1817
+        }
1754 1818
         if ($withcountry) {
1755 1819
             Globals::$langs->load("dict");
1756 1820
             $ret .= ($object->country_code ? ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)) : '');
@@ -1771,8 +1835,9 @@  discard block
 block discarded – undo
1771 1835
     {
1772 1836
         if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
1773 1837
             return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
1774
-        } else
1775
-            return 'Error date into a not supported range';
1838
+        } else {
1839
+                    return 'Error date into a not supported range';
1840
+        }
1776 1841
     }
1777 1842
 
1778 1843
     /**
@@ -1818,10 +1883,12 @@  discard block
 block discarded – undo
1818 1883
                 }
1819 1884
             }
1820 1885
         }
1821
-        if (!is_object($outputlangs))
1822
-            $outputlangs = Globals::$langs;
1823
-        if (!$format)
1824
-            $format = 'daytextshort';
1886
+        if (!is_object($outputlangs)) {
1887
+                    $outputlangs = Globals::$langs;
1888
+        }
1889
+        if (!$format) {
1890
+                    $format = 'daytextshort';
1891
+        }
1825 1892
         $reduceformat = (!empty(Globals::$conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
1826 1893
         $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
1827 1894
         if ($formatwithoutreduce != $format) {
@@ -1830,40 +1897,46 @@  discard block
 block discarded – undo
1830 1897
         }  // so format 'dayreduceformat' is processed like day
1831 1898
 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
1832 1899
 // TODO Add format daysmallyear and dayhoursmallyear
1833
-        if ($format == 'day')
1834
-            $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : Globals::$conf->format_date_short);
1835
-        else if ($format == 'hour')
1836
-            $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : Globals::$conf->format_hour_short);
1837
-        else if ($format == 'hourduration')
1838
-            $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : Globals::$conf->format_hour_short_duration);
1839
-        else if ($format == 'daytext')
1840
-            $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : Globals::$conf->format_date_text);
1841
-        else if ($format == 'daytextshort')
1842
-// Notice: Undefined property: stdClass::$format_date_text_short in \alixar\dolibarr\htdocs\core\lib\functions.lib.php on line 1781
1843
-            $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : Globals::$conf->format_date_text_short);
1844
-        else if ($format == 'dayhour')
1845
-            $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : Globals::$conf->format_date_hour_short ?? "%d/%m/%Y %H:%M");
1846
-        else if ($format == 'dayhoursec')
1847
-            $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : Globals::$conf->format_date_hour_sec_short);
1848
-        else if ($format == 'dayhourtext')
1849
-            $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : Globals::$conf->format_date_hour_text);
1850
-        else if ($format == 'dayhourtextshort')
1851
-            $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : Globals::$conf->format_date_hour_text_short);
1852
-// Format not sensitive to language
1853
-        else if ($format == 'dayhourlog')
1854
-            $format = '%Y%m%d%H%M%S';
1855
-        else if ($format == 'dayhourldap')
1856
-            $format = '%Y%m%d%H%M%SZ';
1857
-        else if ($format == 'dayhourxcard')
1858
-            $format = '%Y%m%dT%H%M%SZ';
1859
-        else if ($format == 'dayxcard')
1860
-            $format = '%Y%m%d';
1861
-        else if ($format == 'dayrfc')
1862
-            $format = '%Y-%m-%d';             // DATE_RFC3339
1863
-        else if ($format == 'dayhourrfc')
1864
-            $format = '%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339
1865
-        else if ($format == 'standard')
1866
-            $format = '%Y-%m-%d %H:%M:%S';
1900
+        if ($format == 'day') {
1901
+                    $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : Globals::$conf->format_date_short);
1902
+        } else if ($format == 'hour') {
1903
+                    $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : Globals::$conf->format_hour_short);
1904
+        } else if ($format == 'hourduration') {
1905
+                    $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : Globals::$conf->format_hour_short_duration);
1906
+        } else if ($format == 'daytext') {
1907
+                    $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : Globals::$conf->format_date_text);
1908
+        } else if ($format == 'daytextshort') {
1909
+            // Notice: Undefined property: stdClass::$format_date_text_short in \alixar\dolibarr\htdocs\core\lib\functions.lib.php on line 1781
1910
+            $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : Globals::$conf->format_date_text_short);
1911
+        } else if ($format == 'dayhour') {
1912
+                    $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : Globals::$conf->format_date_hour_short ?? "%d/%m/%Y %H:%M");
1913
+        } else if ($format == 'dayhoursec') {
1914
+                    $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : Globals::$conf->format_date_hour_sec_short);
1915
+        } else if ($format == 'dayhourtext') {
1916
+                    $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : Globals::$conf->format_date_hour_text);
1917
+        } else if ($format == 'dayhourtextshort') {
1918
+                    $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : Globals::$conf->format_date_hour_text_short);
1919
+        }
1920
+        // Format not sensitive to language
1921
+        else if ($format == 'dayhourlog') {
1922
+                    $format = '%Y%m%d%H%M%S';
1923
+        } else if ($format == 'dayhourldap') {
1924
+                    $format = '%Y%m%d%H%M%SZ';
1925
+        } else if ($format == 'dayhourxcard') {
1926
+                    $format = '%Y%m%dT%H%M%SZ';
1927
+        } else if ($format == 'dayxcard') {
1928
+                    $format = '%Y%m%d';
1929
+        } else if ($format == 'dayrfc') {
1930
+                    $format = '%Y-%m-%d';
1931
+        }
1932
+        // DATE_RFC3339
1933
+        else if ($format == 'dayhourrfc') {
1934
+                    $format = '%Y-%m-%dT%H:%M:%SZ';
1935
+        }
1936
+        // DATETIME RFC3339
1937
+        else if ($format == 'standard') {
1938
+                    $format = '%Y-%m-%d %H:%M:%S';
1939
+        }
1867 1940
 
1868 1941
         if ($reduceformat) {
1869 1942
             $format = str_replace('%Y', '%y', $format);
@@ -1871,8 +1944,10 @@  discard block
 block discarded – undo
1871 1944
         }
1872 1945
 
1873 1946
 // If date undefined or "", we return ""
1874
-        if (DolUtils::dol_strlen($time) == 0)
1875
-            return '';  // $time=0 allowed (it means 01/01/1970 00:00:00)
1947
+        if (DolUtils::dol_strlen($time) == 0) {
1948
+                    return '';
1949
+        }
1950
+        // $time=0 allowed (it means 01/01/1970 00:00:00)
1876 1951
 
1877 1952
 
1878 1953
 
@@ -1950,8 +2025,9 @@  discard block
 block discarded – undo
1950 2025
                 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1951 2026
 
1952 2027
                 $ret = adodb_strftime($format, $timetouse, $to_gmt);
1953
-            } else
1954
-                $ret = 'Bad value ' . $time . ' for date';
2028
+            } else {
2029
+                            $ret = 'Bad value ' . $time . ' for date';
2030
+            }
1955 2031
         }
1956 2032
 
1957 2033
         if (preg_match('/__b__/i', $format)) {
@@ -2022,10 +2098,14 @@  discard block
 block discarded – undo
2022 2098
         // global Globals::$conf;
2023 2099
 
2024 2100
         $usealternatemethod = false;
2025
-        if ($timestamp <= 0)
2026
-            $usealternatemethod = true;    // <= 1970
2027
-        if ($timestamp >= 2145913200)
2028
-            $usealternatemethod = true;  // >= 2038
2101
+        if ($timestamp <= 0) {
2102
+                    $usealternatemethod = true;
2103
+        }
2104
+        // <= 1970
2105
+        if ($timestamp >= 2145913200) {
2106
+                    $usealternatemethod = true;
2107
+        }
2108
+        // >= 2038
2029 2109
 
2030 2110
         if ($usealternatemethod) {
2031 2111
             $arrayinfo = adodb_getdate($timestamp, $fast);
@@ -2060,27 +2140,36 @@  discard block
 block discarded – undo
2060 2140
         // global Globals::$conf;
2061 2141
 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
2062 2142
 // Clean parameters
2063
-        if ($hour == -1 || empty($hour))
2064
-            $hour = 0;
2065
-        if ($minute == -1 || empty($minute))
2066
-            $minute = 0;
2067
-        if ($second == -1 || empty($second))
2068
-            $second = 0;
2143
+        if ($hour == -1 || empty($hour)) {
2144
+                    $hour = 0;
2145
+        }
2146
+        if ($minute == -1 || empty($minute)) {
2147
+                    $minute = 0;
2148
+        }
2149
+        if ($second == -1 || empty($second)) {
2150
+                    $second = 0;
2151
+        }
2069 2152
 
2070 2153
 // Check parameters
2071 2154
         if ($check) {
2072
-            if (!$month || !$day)
2073
-                return '';
2074
-            if ($day > 31)
2075
-                return '';
2076
-            if ($month > 12)
2077
-                return '';
2078
-            if ($hour < 0 || $hour > 24)
2079
-                return '';
2080
-            if ($minute < 0 || $minute > 60)
2081
-                return '';
2082
-            if ($second < 0 || $second > 60)
2083
-                return '';
2155
+            if (!$month || !$day) {
2156
+                            return '';
2157
+            }
2158
+            if ($day > 31) {
2159
+                            return '';
2160
+            }
2161
+            if ($month > 12) {
2162
+                            return '';
2163
+            }
2164
+            if ($hour < 0 || $hour > 24) {
2165
+                            return '';
2166
+            }
2167
+            if ($minute < 0 || $minute > 60) {
2168
+                            return '';
2169
+            }
2170
+            if ($second < 0 || $second > 60) {
2171
+                            return '';
2172
+            }
2084 2173
         }
2085 2174
 
2086 2175
         if (method_exists('DateTime', 'getTimestamp')) {
@@ -2137,8 +2226,10 @@  discard block
 block discarded – undo
2137 2226
 
2138 2227
 // Note that gmmktime and mktime return same value (GMT) when used without parameters
2139 2228
 //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() static function instead
2140
-        if ($mode == 'gmt')
2141
-            $ret = time(); // Time for now at greenwich.
2229
+        if ($mode == 'gmt') {
2230
+                    $ret = time();
2231
+        }
2232
+        // Time for now at greenwich.
2142 2233
         else if ($mode == 'tzserver') {  // Time for now with PHP server timezone added
2143 2234
             require_once DOL_BASE_PATH . '/core/lib/date.lib.php';
2144 2235
             $tzsecond = getServerTimeZoneInt('now');    // Contains tz+dayling saving time
@@ -2172,8 +2263,9 @@  discard block
 block discarded – undo
2172 2263
         // global Globals::$conf, Globals::$langs;
2173 2264
         $level = 1024;
2174 2265
 
2175
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
2176
-            $shortunit = 1;
2266
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
2267
+                    $shortunit = 1;
2268
+        }
2177 2269
 
2178 2270
 // Set value text
2179 2271
         if (empty($shortvalue) || $size < ($level * 10)) {
@@ -2208,19 +2300,23 @@  discard block
 block discarded – undo
2208 2300
     {
2209 2301
         // global Globals::$langs;
2210 2302
 
2211
-        if (empty($url))
2212
-            return '';
2303
+        if (empty($url)) {
2304
+                    return '';
2305
+        }
2213 2306
 
2214 2307
         $link = '<a href="';
2215
-        if (!preg_match('/^http/i', $url))
2216
-            $link .= 'http://';
2308
+        if (!preg_match('/^http/i', $url)) {
2309
+                    $link .= 'http://';
2310
+        }
2217 2311
         $link .= $url;
2218 2312
         $link .= '"';
2219
-        if ($target)
2220
-            $link .= ' target="' . $target . '"';
2313
+        if ($target) {
2314
+                    $link .= ' target="' . $target . '"';
2315
+        }
2221 2316
         $link .= '>';
2222
-        if (!preg_match('/^http/i', $url))
2223
-            $link .= 'http://';
2317
+        if (!preg_match('/^http/i', $url)) {
2318
+                    $link .= 'http://';
2319
+        }
2224 2320
         $link .= dol_trunc($url, $max);
2225 2321
         $link .= '</a>';
2226 2322
         return '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png') . ' ' : '') . $link . '</div>';
@@ -2244,13 +2340,15 @@  discard block
 block discarded – undo
2244 2340
 
2245 2341
         $newemail = $email;
2246 2342
 
2247
-        if (empty($email))
2248
-            return '&nbsp;';
2343
+        if (empty($email)) {
2344
+                    return '&nbsp;';
2345
+        }
2249 2346
 
2250 2347
         if (!empty($addlink)) {
2251 2348
             $newemail = '<a style="text-overflow: ellipsis;" href="';
2252
-            if (!preg_match('/^mailto:/i', $email))
2253
-                $newemail .= 'mailto:';
2349
+            if (!preg_match('/^mailto:/i', $email)) {
2350
+                            $newemail .= 'mailto:';
2351
+            }
2254 2352
             $newemail .= $email;
2255 2353
             $newemail .= '">';
2256 2354
             $newemail .= dol_trunc($email, $max);
@@ -2263,13 +2361,14 @@  discard block
 block discarded – undo
2263 2361
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
2264 2362
                 $type = 'AC_EMAIL';
2265 2363
                 $link = '';
2266
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL))
2267
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2268
-                if ($link)
2269
-                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2364
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL)) {
2365
+                                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2366
+                }
2367
+                if ($link) {
2368
+                                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2369
+                }
2270 2370
             }
2271
-        }
2272
-        else {
2371
+        } else {
2273 2372
             if ($showinvalid && !isValidEmail($email)) {
2274 2373
                 Globals::$langs->load("errors");
2275 2374
                 $newemail .= img_warning(Globals::$langs->trans("ErrorBadEMail", $email));
@@ -2301,8 +2400,9 @@  discard block
 block discarded – undo
2301 2400
 
2302 2401
         $newskype = $value;
2303 2402
 
2304
-        if (empty($value))
2305
-            return '&nbsp;';
2403
+        if (empty($value)) {
2404
+                    return '&nbsp;';
2405
+        }
2306 2406
 
2307 2407
         if (!empty($type)) {
2308 2408
             $newskype = '<div class="divsocialnetwork inline-block valignmiddle">';
@@ -2323,13 +2423,13 @@  discard block
 block discarded – undo
2323 2423
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') {
2324 2424
                 $addlink = 'AC_SKYPE';
2325 2425
                 $link = '';
2326
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE))
2327
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $addlink . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2426
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE)) {
2427
+                                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $addlink . '&amp;contactid=' . $cid . '&amp;socid=' . $socid . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2428
+                }
2328 2429
                 $newskype .= ($link ? ' ' . $link : '');
2329 2430
             }
2330 2431
             $newskype .= '</div>';
2331
-        }
2332
-        else {
2432
+        } else {
2333 2433
             Globals::$langs->load("errors");
2334 2434
             $newskype .= img_warning(Globals::$langs->trans("ErrorBadSocialNetworkValue", $value));
2335 2435
         }
@@ -2358,12 +2458,14 @@  discard block
 block discarded – undo
2358 2458
         if (empty($phone)) {
2359 2459
             return '';
2360 2460
         }
2361
-        if (empty($countrycode))
2362
-            $countrycode = $mysoc->country_code;
2461
+        if (empty($countrycode)) {
2462
+                    $countrycode = $mysoc->country_code;
2463
+        }
2363 2464
 
2364 2465
 // Short format for small screens
2365
-        if (Globals::$conf->dol_optimize_smallscreen)
2366
-            $separ = '';
2466
+        if (Globals::$conf->dol_optimize_smallscreen) {
2467
+                    $separ = '';
2468
+        }
2367 2469
 
2368 2470
         $newphone = $phone;
2369 2471
         if (strtoupper($countrycode) == "FR") {
@@ -2529,15 +2631,18 @@  discard block
 block discarded – undo
2529 2631
                 $newphone = '<a href="tel:' . $phone . '"';
2530 2632
                 $newphone .= '>' . $phone . '</a>';
2531 2633
             } else if (!empty(Globals::$conf->clicktodial->enabled) && $addlink == 'AC_TEL') {  // If click to dial, we use click to dial url
2532
-                if (empty($user->clicktodial_loaded))
2533
-                    $user->fetch_clicktodial();
2634
+                if (empty($user->clicktodial_loaded)) {
2635
+                                    $user->fetch_clicktodial();
2636
+                }
2534 2637
 
2535 2638
 // Define urlmask
2536 2639
                 $urlmask = 'ErrorClickToDialModuleNotConfigured';
2537
-                if (!empty(Globals::$conf->global->CLICKTODIAL_URL))
2538
-                    $urlmask = Globals::$conf->global->CLICKTODIAL_URL;
2539
-                if (!empty($user->clicktodial_url))
2540
-                    $urlmask = $user->clicktodial_url;
2640
+                if (!empty(Globals::$conf->global->CLICKTODIAL_URL)) {
2641
+                                    $urlmask = Globals::$conf->global->CLICKTODIAL_URL;
2642
+                }
2643
+                if (!empty($user->clicktodial_url)) {
2644
+                                    $urlmask = $user->clicktodial_url;
2645
+                }
2541 2646
 
2542 2647
                 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
2543 2648
                 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
@@ -2552,8 +2657,9 @@  discard block
 block discarded – undo
2552 2657
                 $url = make_substitutions($url, $substitarray);
2553 2658
                 $newphonesav = $newphone;
2554 2659
                 $newphone = '<a href="' . $url . '"';
2555
-                if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET))
2556
-                    $newphone .= ' target="_blank"';
2660
+                if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET)) {
2661
+                                    $newphone .= ' target="_blank"';
2662
+                }
2557 2663
                 $newphone .= '>' . $newphonesav . '</a>';
2558 2664
             }
2559 2665
 
@@ -2561,12 +2667,15 @@  discard block
 block discarded – undo
2561 2667
             if (!empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
2562 2668
                 $type = 'AC_TEL';
2563 2669
                 $link = '';
2564
-                if ($addlink == 'AC_FAX')
2565
-                    $type = 'AC_FAX';
2566
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE))
2567
-                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . ($cid ? '&amp;contactid=' . $cid : '') . ($socid ? '&amp;socid=' . $socid : '') . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2568
-                if ($link)
2569
-                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2670
+                if ($addlink == 'AC_FAX') {
2671
+                                    $type = 'AC_FAX';
2672
+                }
2673
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE)) {
2674
+                                    $link = '<a href="' . DOL_BASE_URI . '/comm/action/card.php?action=create&amp;backtopage=1&amp;actioncode=' . $type . ($cid ? '&amp;contactid=' . $cid : '') . ($socid ? '&amp;socid=' . $socid : '') . '">' . img_object(Globals::$langs->trans("AddAction"), "calendar") . '</a>';
2675
+                }
2676
+                if ($link) {
2677
+                                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2678
+                }
2570 2679
             }
2571 2680
         }
2572 2681
 
@@ -2593,15 +2702,17 @@  discard block
 block discarded – undo
2593 2702
                     $picto = '';
2594 2703
                 }
2595 2704
             }
2596
-            if ($adddivfloat)
2597
-                $rep .= '<div class="nospan float" style="margin-right: 10px">';
2598
-            else
2599
-                $rep .= '<span style="margin-right: 10px;">';
2705
+            if ($adddivfloat) {
2706
+                            $rep .= '<div class="nospan float" style="margin-right: 10px">';
2707
+            } else {
2708
+                            $rep .= '<span style="margin-right: 10px;">';
2709
+            }
2600 2710
             $rep .= ($withpicto ? img_picto($titlealt, 'object_' . $picto . '.png') . ' ' : '') . $newphone;
2601
-            if ($adddivfloat)
2602
-                $rep .= '</div>';
2603
-            else
2604
-                $rep .= '</span>';
2711
+            if ($adddivfloat) {
2712
+                            $rep .= '</div>';
2713
+            } else {
2714
+                            $rep .= '</span>';
2715
+            }
2605 2716
         }
2606 2717
 
2607 2718
         return $rep;
@@ -2631,8 +2742,9 @@  discard block
 block discarded – undo
2631 2742
             if ($countrycode) { // If success, countrycode is us, fr, ...
2632 2743
                 if (file_exists(DOL_BASE_PATH . '/theme/common/flags/' . $countrycode . '.png')) {
2633 2744
                     $ret .= ' ' . img_picto($countrycode . ' ' . Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI . '/theme/common/flags/' . $countrycode . '.png', '', 1);
2634
-                } else
2635
-                    $ret .= ' (' . $countrycode . ')';
2745
+                } else {
2746
+                                    $ret .= ' (' . $countrycode . ')';
2747
+                }
2636 2748
             }
2637 2749
         }
2638 2750
 
@@ -2729,26 +2841,33 @@  discard block
 block discarded – undo
2729 2841
                 $out .= Globals::$hookManager->resPrint;
2730 2842
             }
2731 2843
             if (empty($reshook)) {
2732
-                if (empty($charfornl))
2733
-                    $out .= nl2br($address);
2734
-                else
2735
-                    $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
2844
+                if (empty($charfornl)) {
2845
+                                    $out .= nl2br($address);
2846
+                } else {
2847
+                                    $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
2848
+                }
2736 2849
 
2737 2850
                 $showgmap = $showomap = 0;
2738 2851
 
2739 2852
 // TODO Add a hook here
2740
-                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS))
2741
-                    $showgmap = 1;
2742
-                if ($mode == 'contact' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS))
2743
-                    $showgmap = 1;
2744
-                if ($mode == 'member' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS))
2745
-                    $showgmap = 1;
2746
-                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS))
2747
-                    $showomap = 1;
2748
-                if ($mode == 'contact' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS))
2749
-                    $showomap = 1;
2750
-                if ($mode == 'member' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS))
2751
-                    $showomap = 1;
2853
+                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS)) {
2854
+                                    $showgmap = 1;
2855
+                }
2856
+                if ($mode == 'contact' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
2857
+                                    $showgmap = 1;
2858
+                }
2859
+                if ($mode == 'member' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
2860
+                                    $showgmap = 1;
2861
+                }
2862
+                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
2863
+                                    $showomap = 1;
2864
+                }
2865
+                if ($mode == 'contact' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
2866
+                                    $showomap = 1;
2867
+                }
2868
+                if ($mode == 'member' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
2869
+                                    $showomap = 1;
2870
+                }
2752 2871
 
2753 2872
                 if ($showgmap) {
2754 2873
                     $url = dol_buildpath('/google/gmaps.php?mode=' . $mode . '&id=' . $id, 1);
@@ -2760,10 +2879,11 @@  discard block
 block discarded – undo
2760 2879
                 }
2761 2880
             }
2762 2881
         }
2763
-        if ($noprint)
2764
-            return $out;
2765
-        else
2766
-            print $out;
2882
+        if ($noprint) {
2883
+                    return $out;
2884
+        } else {
2885
+                    print $out;
2886
+        }
2767 2887
     }
2768 2888
 
2769 2889
     /**
@@ -2775,10 +2895,12 @@  discard block
 block discarded – undo
2775 2895
      */
2776 2896
     static function isValidEmail($address, $acceptsupervisorkey = 0)
2777 2897
     {
2778
-        if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__')
2779
-            return true;
2780
-        if (filter_var($address, FILTER_VALIDATE_EMAIL))
2781
-            return true;
2898
+        if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
2899
+                    return true;
2900
+        }
2901
+        if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
2902
+                    return true;
2903
+        }
2782 2904
 
2783 2905
         return false;
2784 2906
     }
@@ -2800,10 +2922,12 @@  discard block
 block discarded – undo
2800 2922
                 $mxhosts = array();
2801 2923
                 $weight = array();
2802 2924
                 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
2803
-                if (count($mxhosts) > 1)
2804
-                    return 1;
2805
-                if (count($mxhosts) == 1 && !empty($mxhosts[0]))
2806
-                    return 1;
2925
+                if (count($mxhosts) > 1) {
2926
+                                    return 1;
2927
+                }
2928
+                if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
2929
+                                    return 1;
2930
+                }
2807 2931
 
2808 2932
                 return 0;
2809 2933
             }
@@ -2832,10 +2956,11 @@  discard block
 block discarded – undo
2832 2956
      */
2833 2957
     static function dol_strlen($string, $stringencoding = 'UTF-8')
2834 2958
     {
2835
-        if (function_exists('mb_strlen'))
2836
-            return mb_strlen($string, $stringencoding);
2837
-        else
2838
-            return strlen($string);
2959
+        if (function_exists('mb_strlen')) {
2960
+                    return mb_strlen($string, $stringencoding);
2961
+        } else {
2962
+                    return strlen($string);
2963
+        }
2839 2964
     }
2840 2965
 
2841 2966
     /**
@@ -2852,8 +2977,9 @@  discard block
 block discarded – undo
2852 2977
     {
2853 2978
         // global Globals::$langs;
2854 2979
 
2855
-        if (empty($stringencoding))
2856
-            $stringencoding = Globals::$langs->charset_output;
2980
+        if (empty($stringencoding)) {
2981
+                    $stringencoding = Globals::$langs->charset_output;
2982
+        }
2857 2983
 
2858 2984
         $ret = '';
2859 2985
         if (empty($trunconbytes)) {
@@ -2889,48 +3015,55 @@  discard block
 block discarded – undo
2889 3015
     {
2890 3016
         // global Globals::$conf;
2891 3017
 
2892
-        if ($size == 0 || !empty(Globals::$conf->global->MAIN_DISABLE_TRUNC))
2893
-            return $string;
3018
+        if ($size == 0 || !empty(Globals::$conf->global->MAIN_DISABLE_TRUNC)) {
3019
+                    return $string;
3020
+        }
2894 3021
 
2895
-        if (empty($stringencoding))
2896
-            $stringencoding = 'UTF-8';
2897
-// reduce for small screen
2898
-        if (Globals::$conf->dol_optimize_smallscreen == 1 && $display == 1)
2899
-            $size = round($size / 3);
3022
+        if (empty($stringencoding)) {
3023
+                    $stringencoding = 'UTF-8';
3024
+        }
3025
+        // reduce for small screen
3026
+        if (Globals::$conf->dol_optimize_smallscreen == 1 && $display == 1) {
3027
+                    $size = round($size / 3);
3028
+        }
2900 3029
 
2901 3030
 // We go always here
2902 3031
         if ($trunc == 'right') {
2903 3032
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2904
-            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3)))    // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
2905
-                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
2906
-            else
2907
-            //return 'u'.$size.'-'.$newstring.'-'.DolUtils::dol_strlen($newstring,$stringencoding).'-'.$string;
2908
-                return $string;
2909
-        }
2910
-        elseif ($trunc == 'middle') {
3033
+            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) {
3034
+                // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
3035
+                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
3036
+            } else {
3037
+                        //return 'u'.$size.'-'.$newstring.'-'.DolUtils::dol_strlen($newstring,$stringencoding).'-'.$string;
3038
+                return $string;
3039
+            }
3040
+        } elseif ($trunc == 'middle') {
2911 3041
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2912 3042
             if (DolUtils::dol_strlen($newstring, $stringencoding) > 2 && DolUtils::dol_strlen($newstring, $stringencoding) > ($size + 1)) {
2913 3043
                 $size1 = round($size / 2);
2914 3044
                 $size2 = round($size / 2);
2915 3045
                 return dol_substr($newstring, 0, $size1, $stringencoding) . '...' . dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2916
-            } else
2917
-                return $string;
2918
-        }
2919
-        elseif ($trunc == 'left') {
3046
+            } else {
3047
+                            return $string;
3048
+            }
3049
+        } elseif ($trunc == 'left') {
2920 3050
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2921
-            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3)))    // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
2922
-                return '...' . dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2923
-            else
2924
-                return $string;
2925
-        }
2926
-        elseif ($trunc == 'wrap') {
3051
+            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) {
3052
+                // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
3053
+                return '...' . dol_substr($newstring, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
3054
+            } else {
3055
+                            return $string;
3056
+            }
3057
+        } elseif ($trunc == 'wrap') {
2927 3058
             $newstring = DolUtils::dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2928
-            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + 1))
2929
-                return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2930
-            else
2931
-                return $string;
2932
-        } else
2933
-            return 'BadParam3CallingDolTrunc';
3059
+            if (DolUtils::dol_strlen($newstring, $stringencoding) > ($size + 1)) {
3060
+                            return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, DolUtils::dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
3061
+            } else {
3062
+                            return $string;
3063
+            }
3064
+        } else {
3065
+                    return 'BadParam3CallingDolTrunc';
3066
+        }
2934 3067
     }
2935 3068
 
2936 3069
     /**
@@ -3140,8 +3273,9 @@  discard block
 block discarded – undo
3140 3273
     {
3141 3274
         // global Globals::$conf;
3142 3275
 
3143
-        if (!preg_match('/(\.png|\.gif)$/i', $picto))
3144
-            $picto .= '.png';
3276
+        if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
3277
+                    $picto .= '.png';
3278
+        }
3145 3279
 
3146 3280
 //$path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3147 3281
         $path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
@@ -3217,8 +3351,9 @@  discard block
 block discarded – undo
3217 3351
                 $numaction = 0;
3218 3352
             }
3219 3353
         }
3220
-        if (!is_numeric($numaction))
3221
-            $numaction = 0;
3354
+        if (!is_numeric($numaction)) {
3355
+                    $numaction = 0;
3356
+        }
3222 3357
 
3223 3358
         return img_picto($titlealt, 'stcomm' . $numaction . '.png');
3224 3359
     }
@@ -3234,8 +3369,9 @@  discard block
 block discarded – undo
3234 3369
     {
3235 3370
         // global Globals::$conf, Globals::$langs;
3236 3371
 
3237
-        if ($titlealt == 'default')
3238
-            $titlealt = Globals::$langs->trans('Show');
3372
+        if ($titlealt == 'default') {
3373
+                    $titlealt = Globals::$langs->trans('Show');
3374
+        }
3239 3375
 
3240 3376
         return img_picto($titlealt, 'pdf' . $size . '.png');
3241 3377
     }
@@ -3251,8 +3387,9 @@  discard block
 block discarded – undo
3251 3387
     {
3252 3388
         // global Globals::$conf, Globals::$langs;
3253 3389
 
3254
-        if ($titlealt == 'default')
3255
-            $titlealt = Globals::$langs->trans('Add');
3390
+        if ($titlealt == 'default') {
3391
+                    $titlealt = Globals::$langs->trans('Add');
3392
+        }
3256 3393
 
3257 3394
         return img_picto($titlealt, 'edit_add.png', $other);
3258 3395
     }
@@ -3268,8 +3405,9 @@  discard block
 block discarded – undo
3268 3405
     {
3269 3406
         // global Globals::$conf, Globals::$langs;
3270 3407
 
3271
-        if ($titlealt == 'default')
3272
-            $titlealt = Globals::$langs->trans('Remove');
3408
+        if ($titlealt == 'default') {
3409
+                    $titlealt = Globals::$langs->trans('Remove');
3410
+        }
3273 3411
 
3274 3412
         return img_picto($titlealt, 'edit_remove.png', $other);
3275 3413
     }
@@ -3286,8 +3424,9 @@  discard block
 block discarded – undo
3286 3424
     {
3287 3425
         // global Globals::$conf, Globals::$langs;
3288 3426
 
3289
-        if ($titlealt == 'default')
3290
-            $titlealt = Globals::$langs->trans('Modify');
3427
+        if ($titlealt == 'default') {
3428
+                    $titlealt = Globals::$langs->trans('Modify');
3429
+        }
3291 3430
 
3292 3431
         return img_picto($titlealt, 'edit.png', ($float ? 'style="float: ' . (Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
3293 3432
     }
@@ -3304,8 +3443,9 @@  discard block
 block discarded – undo
3304 3443
     {
3305 3444
         // global Globals::$conf, Globals::$langs;
3306 3445
 
3307
-        if ($titlealt == 'default')
3308
-            $titlealt = Globals::$langs->trans('View');
3446
+        if ($titlealt == 'default') {
3447
+                    $titlealt = Globals::$langs->trans('View');
3448
+        }
3309 3449
 
3310 3450
         $moreatt = ($float ? 'style="float: right" ' : '') . $other;
3311 3451
 
@@ -3323,8 +3463,9 @@  discard block
 block discarded – undo
3323 3463
     {
3324 3464
         // global Globals::$conf, Globals::$langs;
3325 3465
 
3326
-        if ($titlealt == 'default')
3327
-            $titlealt = Globals::$langs->trans('Delete');
3466
+        if ($titlealt == 'default') {
3467
+                    $titlealt = Globals::$langs->trans('Delete');
3468
+        }
3328 3469
 
3329 3470
         return img_picto($titlealt, 'delete.png', $other);
3330 3471
 //return '<span class="fa fa-trash fa-2x fa-fw" style="font-size: 1.7em;" title="'.$titlealt.'"></span>';
@@ -3340,8 +3481,9 @@  discard block
 block discarded – undo
3340 3481
     static function img_printer($titlealt = "default", $other = '')
3341 3482
     {
3342 3483
         // global Globals::$conf, Globals::$langs;
3343
-        if ($titlealt == "default")
3344
-            $titlealt = Globals::$langs->trans("Print");
3484
+        if ($titlealt == "default") {
3485
+                    $titlealt = Globals::$langs->trans("Print");
3486
+        }
3345 3487
         return img_picto($titlealt, 'printer.png', $other);
3346 3488
     }
3347 3489
 
@@ -3356,8 +3498,9 @@  discard block
 block discarded – undo
3356 3498
     {
3357 3499
         // global Globals::$conf, Globals::$langs;
3358 3500
 
3359
-        if ($titlealt == 'default')
3360
-            $titlealt = Globals::$langs->trans('Split');
3501
+        if ($titlealt == 'default') {
3502
+                    $titlealt = Globals::$langs->trans('Split');
3503
+        }
3361 3504
 
3362 3505
         return img_picto($titlealt, 'split.png', $other);
3363 3506
     }
@@ -3374,10 +3517,11 @@  discard block
 block discarded – undo
3374 3517
         // global Globals::$conf, Globals::$langs;
3375 3518
 
3376 3519
         if ($usealttitle) {
3377
-            if (is_string($usealttitle))
3378
-                $usealttitle = DolUtils::dol_escape_htmltag($usealttitle);
3379
-            else
3380
-                $usealttitle = Globals::$langs->trans('Info');
3520
+            if (is_string($usealttitle)) {
3521
+                            $usealttitle = DolUtils::dol_escape_htmltag($usealttitle);
3522
+            } else {
3523
+                            $usealttitle = Globals::$langs->trans('Info');
3524
+            }
3381 3525
         }
3382 3526
 
3383 3527
         return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
@@ -3393,8 +3537,9 @@  discard block
 block discarded – undo
3393 3537
     {
3394 3538
         // global Globals::$conf, Globals::$langs;
3395 3539
 
3396
-        if ($titlealt == 'default')
3397
-            $titlealt = Globals::$langs->trans('Informations');
3540
+        if ($titlealt == 'default') {
3541
+                    $titlealt = Globals::$langs->trans('Informations');
3542
+        }
3398 3543
 
3399 3544
         return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
3400 3545
     }
@@ -3410,8 +3555,9 @@  discard block
 block discarded – undo
3410 3555
     {
3411 3556
         // global Globals::$conf, Globals::$langs;
3412 3557
 
3413
-        if ($titlealt == 'default')
3414
-            $titlealt = Globals::$langs->trans('Warning');
3558
+        if ($titlealt == 'default') {
3559
+                    $titlealt = Globals::$langs->trans('Warning');
3560
+        }
3415 3561
 
3416 3562
 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
3417 3563
         return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
@@ -3427,8 +3573,9 @@  discard block
 block discarded – undo
3427 3573
     {
3428 3574
         // global Globals::$conf, Globals::$langs;
3429 3575
 
3430
-        if ($titlealt == 'default')
3431
-            $titlealt = Globals::$langs->trans('Error');
3576
+        if ($titlealt == 'default') {
3577
+                    $titlealt = Globals::$langs->trans('Error');
3578
+        }
3432 3579
 
3433 3580
         return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
3434 3581
     }
@@ -3444,8 +3591,9 @@  discard block
 block discarded – undo
3444 3591
     {
3445 3592
         // global Globals::$conf, Globals::$langs;
3446 3593
 
3447
-        if ($titlealt == 'default')
3448
-            $titlealt = Globals::$langs->trans('Next');
3594
+        if ($titlealt == 'default') {
3595
+                    $titlealt = Globals::$langs->trans('Next');
3596
+        }
3449 3597
 
3450 3598
 //return img_picto($titlealt, 'next.png', $moreatt);
3451 3599
         return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . DolUtils::dol_escape_htmltag($titlealt) . '"></span>';
@@ -3462,8 +3610,9 @@  discard block
 block discarded – undo
3462 3610
     {
3463 3611
         // global Globals::$conf, Globals::$langs;
3464 3612
 
3465
-        if ($titlealt == 'default')
3466
-            $titlealt = Globals::$langs->trans('Previous');
3613
+        if ($titlealt == 'default') {
3614
+                    $titlealt = Globals::$langs->trans('Previous');
3615
+        }
3467 3616
 
3468 3617
 //return img_picto($titlealt, 'previous.png', $moreatt);
3469 3618
         return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . DolUtils::dol_escape_htmltag($titlealt) . '"></span>';
@@ -3481,8 +3630,9 @@  discard block
 block discarded – undo
3481 3630
     {
3482 3631
         // global Globals::$conf, Globals::$langs;
3483 3632
 
3484
-        if ($titlealt == 'default')
3485
-            $titlealt = Globals::$langs->trans('Down');
3633
+        if ($titlealt == 'default') {
3634
+                    $titlealt = Globals::$langs->trans('Down');
3635
+        }
3486 3636
 
3487 3637
         return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
3488 3638
     }
@@ -3499,8 +3649,9 @@  discard block
 block discarded – undo
3499 3649
     {
3500 3650
         // global Globals::$conf, Globals::$langs;
3501 3651
 
3502
-        if ($titlealt == 'default')
3503
-            $titlealt = Globals::$langs->trans('Up');
3652
+        if ($titlealt == 'default') {
3653
+                    $titlealt = Globals::$langs->trans('Up');
3654
+        }
3504 3655
 
3505 3656
         return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
3506 3657
     }
@@ -3517,8 +3668,9 @@  discard block
 block discarded – undo
3517 3668
     {
3518 3669
         // global Globals::$conf, Globals::$langs;
3519 3670
 
3520
-        if ($titlealt == 'default')
3521
-            $titlealt = Globals::$langs->trans('Left');
3671
+        if ($titlealt == 'default') {
3672
+                    $titlealt = Globals::$langs->trans('Left');
3673
+        }
3522 3674
 
3523 3675
         return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
3524 3676
     }
@@ -3535,8 +3687,9 @@  discard block
 block discarded – undo
3535 3687
     {
3536 3688
         // global Globals::$conf, Globals::$langs;
3537 3689
 
3538
-        if ($titlealt == 'default')
3539
-            $titlealt = Globals::$langs->trans('Right');
3690
+        if ($titlealt == 'default') {
3691
+                    $titlealt = Globals::$langs->trans('Right');
3692
+        }
3540 3693
 
3541 3694
         return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
3542 3695
     }
@@ -3552,11 +3705,13 @@  discard block
 block discarded – undo
3552 3705
     {
3553 3706
         // global Globals::$conf, Globals::$langs;
3554 3707
 
3555
-        if ($titlealt == 'default')
3556
-            $titlealt = Globals::$langs->trans('Active');
3708
+        if ($titlealt == 'default') {
3709
+                    $titlealt = Globals::$langs->trans('Active');
3710
+        }
3557 3711
 
3558
-        if ($allow == 1)
3559
-            return img_picto($titlealt, 'tick.png');
3712
+        if ($allow == 1) {
3713
+                    return img_picto($titlealt, 'tick.png');
3714
+        }
3560 3715
 
3561 3716
         return '-';
3562 3717
     }
@@ -3604,8 +3759,9 @@  discard block
 block discarded – undo
3604 3759
         $mimeimg = dol_mimetype($file, '', 2);
3605 3760
         $mimefa = dol_mimetype($file, '', 4);
3606 3761
 
3607
-        if (empty($titlealt))
3608
-            $titlealt = 'Mime type: ' . $mimetype;
3762
+        if (empty($titlealt)) {
3763
+                    $titlealt = 'Mime type: ' . $mimetype;
3764
+        }
3609 3765
 
3610 3766
 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
3611 3767
         return '<i class="fa fa-' . $mimefa . ' paddingright"></i>';
@@ -3627,13 +3783,15 @@  discard block
 block discarded – undo
3627 3783
 
3628 3784
         // global Globals::$conf, Globals::$langs;
3629 3785
 
3630
-        if ($titlealt == 'default')
3631
-            $titlealt = Globals::$langs->trans('Call');
3786
+        if ($titlealt == 'default') {
3787
+                    $titlealt = Globals::$langs->trans('Call');
3788
+        }
3632 3789
 
3633
-        if ($option == 1)
3634
-            $img = 'call';
3635
-        else
3636
-            $img = 'call_out';
3790
+        if ($option == 1) {
3791
+                    $img = 'call';
3792
+        } else {
3793
+                    $img = 'call_out';
3794
+        }
3637 3795
 
3638 3796
         return img_picto($titlealt, $img);
3639 3797
     }
@@ -3649,8 +3807,9 @@  discard block
 block discarded – undo
3649 3807
     {
3650 3808
         // global Globals::$conf, Globals::$langs;
3651 3809
 
3652
-        if ($titlealt == 'default')
3653
-            $titlealt = Globals::$langs->trans('Search');
3810
+        if ($titlealt == 'default') {
3811
+                    $titlealt = Globals::$langs->trans('Search');
3812
+        }
3654 3813
 
3655 3814
         $img = img_picto($titlealt, 'search.png', $other, false, 1);
3656 3815
 
@@ -3671,8 +3830,9 @@  discard block
 block discarded – undo
3671 3830
     {
3672 3831
         // global Globals::$conf, Globals::$langs;
3673 3832
 
3674
-        if ($titlealt == 'default')
3675
-            $titlealt = Globals::$langs->trans('Search');
3833
+        if ($titlealt == 'default') {
3834
+                    $titlealt = Globals::$langs->trans('Search');
3835
+        }
3676 3836
 
3677 3837
         $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
3678 3838
 
@@ -4100,12 +4260,15 @@  discard block
 block discarded – undo
4100 4260
         $savtotalnboflines = $totalnboflines;
4101 4261
         $totalnboflines = abs($totalnboflines);
4102 4262
 
4103
-        if ($picto == 'setup')
4104
-            $picto = 'title_setup.png';
4105
-        if ((Globals::$conf->browser->name == 'ie') && $picto == 'title_generic.png')
4106
-            $picto = 'title.gif';
4107
-        if ($limit < 0)
4108
-            $limit = Globals::$conf->liste_limit;
4263
+        if ($picto == 'setup') {
4264
+                    $picto = 'title_setup.png';
4265
+        }
4266
+        if ((Globals::$conf->browser->name == 'ie') && $picto == 'title_generic.png') {
4267
+                    $picto = 'title.gif';
4268
+        }
4269
+        if ($limit < 0) {
4270
+                    $limit = Globals::$conf->liste_limit;
4271
+        }
4109 4272
         if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
4110 4273
             $nextpage = 1;
4111 4274
         } else {
@@ -4119,11 +4282,13 @@  discard block
 block discarded – undo
4119 4282
 // Left
4120 4283
 //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
4121 4284
         print '<td class="nobordernopadding valignmiddle">';
4122
-        if ($picto && $titre)
4123
-            print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4285
+        if ($picto && $titre) {
4286
+                    print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4287
+        }
4124 4288
         print '<div class="titre inline-block">' . $titre;
4125
-        if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '')
4126
-            print ' (' . $totalnboflines . ')';
4289
+        if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
4290
+                    print ' (' . $totalnboflines . ')';
4291
+        }
4127 4292
         print '</div></td>';
4128 4293
 
4129 4294
 // Center
@@ -4133,21 +4298,24 @@  discard block
 block discarded – undo
4133 4298
 
4134 4299
 // Right
4135 4300
         print '<td class="nobordernopadding valignmiddle" align="right">';
4136
-        if ($sortfield)
4137
-            $options .= "&sortfield=" . urlencode($sortfield);
4138
-        if ($sortorder)
4139
-            $options .= "&sortorder=" . urlencode($sortorder);
4140
-// Show navigation bar
4301
+        if ($sortfield) {
4302
+                    $options .= "&sortfield=" . urlencode($sortfield);
4303
+        }
4304
+        if ($sortorder) {
4305
+                    $options .= "&sortorder=" . urlencode($sortorder);
4306
+        }
4307
+        // Show navigation bar
4141 4308
         $pagelist = '';
4142 4309
         if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
4143 4310
             if ($totalnboflines) { // If we know total nb of lines
4144 4311
 // Define nb of extra page links before and after selected page + ... + first or last
4145 4312
                 $maxnbofpage = (empty(Globals::$conf->dol_optimize_smallscreen) ? 4 : 1);
4146 4313
 
4147
-                if ($limit > 0)
4148
-                    $nbpages = ceil($totalnboflines / $limit);
4149
-                else
4150
-                    $nbpages = 1;
4314
+                if ($limit > 0) {
4315
+                                    $nbpages = ceil($totalnboflines / $limit);
4316
+                } else {
4317
+                                    $nbpages = 1;
4318
+                }
4151 4319
                 $cpt = ($page - $maxnbofpage);
4152 4320
                 if ($cpt < 0) {
4153 4321
                     $cpt = 0;
@@ -4155,10 +4323,11 @@  discard block
 block discarded – undo
4155 4323
 
4156 4324
                 if ($cpt >= 1) {
4157 4325
                     $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=0' . $options . '">1</a></li>';
4158
-                    if ($cpt > 2)
4159
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4160
-                    else if ($cpt == 2)
4161
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4326
+                    if ($cpt > 2) {
4327
+                                            $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4328
+                    } else if ($cpt == 2) {
4329
+                                            $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4330
+                    }
4162 4331
                 }
4163 4332
 
4164 4333
                 do {
@@ -4171,14 +4340,14 @@  discard block
 block discarded – undo
4171 4340
                 } while ($cpt < $nbpages && $cpt <= $page + $maxnbofpage);
4172 4341
 
4173 4342
                 if ($cpt < $nbpages) {
4174
-                    if ($cpt < $nbpages - 2)
4175
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4176
-                    else if ($cpt == $nbpages - 2)
4177
-                        $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4343
+                    if ($cpt < $nbpages - 2) {
4344
+                                            $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4345
+                    } else if ($cpt == $nbpages - 2) {
4346
+                                            $pagelist .= '<li' . ( (Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4347
+                    }
4178 4348
                     $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 1) . $options . '">' . $nbpages . '</a></li>';
4179 4349
                 }
4180
-            }
4181
-            else {
4350
+            } else {
4182 4351
                 $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . "</li>";
4183 4352
             }
4184 4353
         }
@@ -4214,18 +4383,21 @@  discard block
 block discarded – undo
4214 4383
             $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
4215 4384
 //$pagesizechoices.=',0:'.Globals::$langs->trans("All");     // Not yet supported
4216 4385
 //$pagesizechoices.=',2:2';
4217
-            if (!empty(Globals::$conf->global->MAIN_PAGESIZE_CHOICES))
4218
-                $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4386
+            if (!empty(Globals::$conf->global->MAIN_PAGESIZE_CHOICES)) {
4387
+                            $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4388
+            }
4219 4389
 
4220 4390
             print '<li class="pagination">';
4221 4391
             print '<select class="flat selectlimit" name="limit" title="' . DolUtils::dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")) . '">';
4222 4392
             $tmpchoice = explode(',', $pagesizechoices);
4223 4393
             $tmpkey = $limit . ':' . $limit;
4224
-            if (!in_array($tmpkey, $tmpchoice))
4225
-                $tmpchoice[] = $tmpkey;
4394
+            if (!in_array($tmpkey, $tmpchoice)) {
4395
+                            $tmpchoice[] = $tmpkey;
4396
+            }
4226 4397
             $tmpkey = Globals::$conf->liste_limit . ':' . Globals::$conf->liste_limit;
4227
-            if (!in_array($tmpkey, $tmpchoice))
4228
-                $tmpchoice[] = $tmpkey;
4398
+            if (!in_array($tmpkey, $tmpchoice)) {
4399
+                            $tmpchoice[] = $tmpkey;
4400
+            }
4229 4401
             asort($tmpchoice, SORT_NUMERIC);
4230 4402
             $found = false;
4231 4403
             foreach ($tmpchoice as $val) {
@@ -4301,14 +4473,15 @@  discard block
 block discarded – undo
4301 4473
         }
4302 4474
 
4303 4475
 // If rate is '9/9/9' we don't change it.  If rate is '9.000' we apply price()
4304
-        if (!preg_match('/\//', $rate))
4305
-            $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4306
-        else {
4476
+        if (!preg_match('/\//', $rate)) {
4477
+                    $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4478
+        } else {
4307 4479
 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
4308 4480
             $ret = $rate . ($addpercent ? '%' : '');
4309 4481
         }
4310
-        if (($info_bits & 1) && $usestarfornpr >= 0)
4311
-            $ret .= ' *';
4482
+        if (($info_bits & 1) && $usestarfornpr >= 0) {
4483
+                    $ret .= ' *';
4484
+        }
4312 4485
         $ret .= $morelabel;
4313 4486
         return $ret;
4314 4487
     }
@@ -4332,11 +4505,14 @@  discard block
 block discarded – undo
4332 4505
     {
4333 4506
         // global Globals::$langs, Globals::$conf;
4334 4507
 // Clean parameters
4335
-        if (empty($amount))
4336
-            $amount = 0; // To have a numeric value if amount not defined or = ''
4508
+        if (empty($amount)) {
4509
+                    $amount = 0;
4510
+        }
4511
+        // To have a numeric value if amount not defined or = ''
4337 4512
         $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
4338
-        if ($rounding < 0)
4339
-            $rounding = min(Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT, Globals::$conf->global->MAIN_MAX_DECIMALS_TOT);
4513
+        if ($rounding < 0) {
4514
+                    $rounding = min(Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT, Globals::$conf->global->MAIN_MAX_DECIMALS_TOT);
4515
+        }
4340 4516
         $nbdecimal = $rounding;
4341 4517
 
4342 4518
 // Output separators by default (french)
@@ -4344,18 +4520,22 @@  discard block
 block discarded – undo
4344 4520
         $thousand = ' ';
4345 4521
 
4346 4522
 // If $outlangs not forced, we use use language
4347
-        if (!is_object($outlangs))
4348
-            $outlangs = Globals::$langs;
4349
-
4350
-        if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal")
4351
-            $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
4352
-        if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand")
4353
-            $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
4354
-        if ($thousand == 'None')
4355
-            $thousand = '';
4356
-        else if ($thousand == 'Space')
4357
-            $thousand = ' ';
4358
-//print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4523
+        if (!is_object($outlangs)) {
4524
+                    $outlangs = Globals::$langs;
4525
+        }
4526
+
4527
+        if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4528
+                    $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
4529
+        }
4530
+        if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4531
+                    $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
4532
+        }
4533
+        if ($thousand == 'None') {
4534
+                    $thousand = '';
4535
+        } else if ($thousand == 'Space') {
4536
+                    $thousand = ' ';
4537
+        }
4538
+        //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4359 4539
 //print "amount=".$amount."-";
4360 4540
         $amount = str_replace(',', '.', $amount); // should be useless
4361 4541
 //print $amount."-";
@@ -4366,9 +4546,10 @@  discard block
 block discarded – undo
4366 4546
         $end = '';
4367 4547
 
4368 4548
 // We increase nbdecimal if there is more decimal than asked (to not loose information)
4369
-        if (DolUtils::dol_strlen($decpart) > $nbdecimal)
4370
-            $nbdecimal = DolUtils::dol_strlen($decpart);
4371
-// Si on depasse max
4549
+        if (DolUtils::dol_strlen($decpart) > $nbdecimal) {
4550
+                    $nbdecimal = DolUtils::dol_strlen($decpart);
4551
+        }
4552
+        // Si on depasse max
4372 4553
         if ($trunc && $nbdecimal > Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN) {
4373 4554
             $nbdecimal = Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN;
4374 4555
             if (preg_match('/\.\.\./i', Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
@@ -4378,8 +4559,9 @@  discard block
 block discarded – undo
4378 4559
         }
4379 4560
 
4380 4561
 // If force rounding
4381
-        if ($forcerounding >= 0)
4382
-            $nbdecimal = $forcerounding;
4562
+        if ($forcerounding >= 0) {
4563
+                    $nbdecimal = $forcerounding;
4564
+        }
4383 4565
 
4384 4566
 // Format number
4385 4567
         $output = number_format($amount, $nbdecimal, $dec, $thousand);
@@ -4390,13 +4572,14 @@  discard block
 block discarded – undo
4390 4572
 // Add symbol of currency if requested
4391 4573
         $cursymbolbefore = $cursymbolafter = '';
4392 4574
         if ($currency_code) {
4393
-            if ($currency_code == 'auto')
4394
-                $currency_code = Globals::$conf->currency;
4575
+            if ($currency_code == 'auto') {
4576
+                            $currency_code = Globals::$conf->currency;
4577
+            }
4395 4578
 
4396 4579
             $listofcurrenciesbefore = array('USD', 'GBP', 'AUD', 'MXN', 'PEN', 'CNY');
4397
-            if (in_array($currency_code, $listofcurrenciesbefore))
4398
-                $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4399
-            else {
4580
+            if (in_array($currency_code, $listofcurrenciesbefore)) {
4581
+                            $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4582
+            } else {
4400 4583
                 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
4401 4584
                 $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
4402 4585
             }
@@ -4429,15 +4612,18 @@  discard block
 block discarded – undo
4429 4612
 // Decimal delimiter for PHP and database SQL requests must be '.'
4430 4613
         $dec = ',';
4431 4614
         $thousand = ' ';
4432
-        if (Globals::$langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal")
4433
-            $dec = Globals::$langs->transnoentitiesnoconv("SeparatorDecimal");
4434
-        if (Globals::$langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand")
4435
-            $thousand = Globals::$langs->transnoentitiesnoconv("SeparatorThousand");
4436
-        if ($thousand == 'None')
4437
-            $thousand = '';
4438
-        elseif ($thousand == 'Space')
4439
-            $thousand = ' ';
4440
-//print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4615
+        if (Globals::$langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4616
+                    $dec = Globals::$langs->transnoentitiesnoconv("SeparatorDecimal");
4617
+        }
4618
+        if (Globals::$langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4619
+                    $thousand = Globals::$langs->transnoentitiesnoconv("SeparatorThousand");
4620
+        }
4621
+        if ($thousand == 'None') {
4622
+                    $thousand = '';
4623
+        } elseif ($thousand == 'Space') {
4624
+                    $thousand = ' ';
4625
+        }
4626
+        //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4441 4627
 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
4442 4628
         if ($alreadysqlnb != 1) { // If not a PHP number or unknown, we change format
4443 4629
 //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
@@ -4452,8 +4638,10 @@  discard block
 block discarded – undo
4452 4638
             }
4453 4639
 //print "QQ".$amount.'<br>';
4454 4640
 // Now make replace (the main goal of function)
4455
-            if ($thousand != ',' && $thousand != '.')
4456
-                $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4641
+            if ($thousand != ',' && $thousand != '.') {
4642
+                            $amount = str_replace(',', '.', $amount);
4643
+            }
4644
+            // To accept 2 notations for french users
4457 4645
             $amount = str_replace(' ', '', $amount);  // To avoid spaces
4458 4646
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4459 4647
             $amount = str_replace($dec, '.', $amount);
@@ -4462,20 +4650,24 @@  discard block
 block discarded – undo
4462 4650
 // Now, make a rounding if required
4463 4651
         if ($rounding) {
4464 4652
             $nbofdectoround = '';
4465
-            if ($rounding == 'MU')
4466
-                $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT;
4467
-            elseif ($rounding == 'MT')
4468
-                $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_TOT;
4469
-            elseif ($rounding == 'MS')
4470
-                $nbofdectoround = empty(Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK;
4471
-            elseif (is_numeric($rounding))
4472
-                $nbofdectoround = $rounding;
4473
-//print "RR".$amount.' - '.$nbofdectoround.'<br>';
4474
-            if (DolUtils::dol_strlen($nbofdectoround))
4475
-                $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0.
4476
-            else
4477
-                return 'ErrorBadParameterProvidedToFunction';
4478
-//print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
4653
+            if ($rounding == 'MU') {
4654
+                            $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT;
4655
+            } elseif ($rounding == 'MT') {
4656
+                            $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_TOT;
4657
+            } elseif ($rounding == 'MS') {
4658
+                            $nbofdectoround = empty(Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK;
4659
+            } elseif (is_numeric($rounding)) {
4660
+                            $nbofdectoround = $rounding;
4661
+            }
4662
+            //print "RR".$amount.' - '.$nbofdectoround.'<br>';
4663
+            if (DolUtils::dol_strlen($nbofdectoround)) {
4664
+                            $amount = round($amount, $nbofdectoround);
4665
+            }
4666
+            // $nbofdectoround can be 0.
4667
+            else {
4668
+                            return 'ErrorBadParameterProvidedToFunction';
4669
+            }
4670
+            //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
4479 4671
 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
4480 4672
 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
4481 4673
             if (is_numeric($amount)) {
@@ -4488,8 +4680,10 @@  discard block
 block discarded – undo
4488 4680
 //print "TT".$amount.'<br>';
4489 4681
 // Always make replace because each math static function (like round) replace
4490 4682
 // with local values and we want a number that has a SQL string format x.y
4491
-            if ($thousand != ',' && $thousand != '.')
4492
-                $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4683
+            if ($thousand != ',' && $thousand != '.') {
4684
+                            $amount = str_replace(',', '.', $amount);
4685
+            }
4686
+            // To accept 2 notations for french users
4493 4687
             $amount = str_replace(' ', '', $amount);  // To avoid spaces
4494 4688
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4495 4689
             $amount = str_replace($dec, '.', $amount);
@@ -4548,8 +4742,9 @@  discard block
 block discarded – undo
4548 4742
     {
4549 4743
         // global $db, Globals::$conf, $mysoc;
4550 4744
 
4551
-        if (empty($thirdparty_seller) || !is_object($thirdparty_seller))
4552
-            $thirdparty_seller = $mysoc;
4745
+        if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
4746
+                    $thirdparty_seller = $mysoc;
4747
+        }
4553 4748
 
4554 4749
         DolUtils::dol_syslog("get_localtax tva=" . $vatrate . " local=" . $local . " thirdparty_buyer id=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->id : '') . "/country_code=" . (is_object($thirdparty_buyer) ? $thirdparty_buyer->country_code : '') . " thirdparty_seller id=" . $thirdparty_seller->id . "/country_code=" . $thirdparty_seller->country_code . " thirdparty_seller localtax1_assuj=" . $thirdparty_seller->localtax1_assuj . "  thirdparty_seller localtax2_assuj=" . $thirdparty_seller->localtax2_assuj);
4555 4750
 
@@ -4567,37 +4762,43 @@  discard block
 block discarded – undo
4567 4762
 // Some test to guess with no need to make database access
4568 4763
         if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
4569 4764
             if ($local == 1) {
4570
-                if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0")
4571
-                    return 0;
4765
+                if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
4766
+                                    return 0;
4767
+                }
4572 4768
                 if ($thirdparty_seller->id == $mysoc->id) {
4573
-                    if (!$thirdparty_buyer->localtax1_assuj)
4574
-                        return 0;
4575
-                }
4576
-                else {
4577
-                    if (!$thirdparty_seller->localtax1_assuj)
4578
-                        return 0;
4769
+                    if (!$thirdparty_buyer->localtax1_assuj) {
4770
+                                            return 0;
4771
+                    }
4772
+                } else {
4773
+                    if (!$thirdparty_seller->localtax1_assuj) {
4774
+                                            return 0;
4775
+                    }
4579 4776
                 }
4580 4777
             }
4581 4778
 
4582 4779
             if ($local == 2) {
4583 4780
 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
4584
-                if (!$mysoc->localtax2_assuj)
4585
-                    return 0;  // If main vat is 0, IRPF may be different than 0.
4781
+                if (!$mysoc->localtax2_assuj) {
4782
+                                    return 0;
4783
+                }
4784
+                // If main vat is 0, IRPF may be different than 0.
4586 4785
                 if ($thirdparty_seller->id == $mysoc->id) {
4587
-                    if (!$thirdparty_buyer->localtax2_assuj)
4588
-                        return 0;
4589
-                }
4590
-                else {
4591
-                    if (!$thirdparty_seller->localtax2_assuj)
4592
-                        return 0;
4786
+                    if (!$thirdparty_buyer->localtax2_assuj) {
4787
+                                            return 0;
4788
+                    }
4789
+                } else {
4790
+                    if (!$thirdparty_seller->localtax2_assuj) {
4791
+                                            return 0;
4792
+                    }
4593 4793
                 }
4594 4794
             }
4595
-        }
4596
-        else {
4597
-            if ($local == 1 && !$thirdparty_seller->localtax1_assuj)
4598
-                return 0;
4599
-            if ($local == 2 && !$thirdparty_seller->localtax2_assuj)
4600
-                return 0;
4795
+        } else {
4796
+            if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
4797
+                            return 0;
4798
+            }
4799
+            if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
4800
+                            return 0;
4801
+            }
4601 4802
         }
4602 4803
 
4603 4804
 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
@@ -4639,19 +4840,23 @@  discard block
 block discarded – undo
4639 4840
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4640 4841
         $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $thirdparty_seller->country_code . "'";
4641 4842
         $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4642
-        if ($vatratecode)
4643
-            $sql .= " AND t.code ='" . $vatratecode . "'";  // If we have the code, we use it in priority
4644
-        else
4645
-            $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4843
+        if ($vatratecode) {
4844
+                    $sql .= " AND t.code ='" . $vatratecode . "'";
4845
+        }
4846
+        // If we have the code, we use it in priority
4847
+        else {
4848
+                    $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4849
+        }
4646 4850
         DolUtils::dol_syslog("get_localtax", LOG_DEBUG);
4647 4851
         $resql = $db->query($sql);
4648 4852
 
4649 4853
         if ($resql) {
4650 4854
             $obj = $db->fetch_object($resql);
4651
-            if ($local == 1)
4652
-                return $obj->localtax1;
4653
-            elseif ($local == 2)
4654
-                return $obj->localtax2;
4855
+            if ($local == 1) {
4856
+                            return $obj->localtax1;
4857
+            } elseif ($local == 2) {
4858
+                            return $obj->localtax2;
4859
+            }
4655 4860
         }
4656 4861
 
4657 4862
         return 0;
@@ -4697,10 +4902,11 @@  discard block
 block discarded – undo
4697 4902
         $resql = $db->query($sql);
4698 4903
         if ($resql) {
4699 4904
             $obj = $db->fetch_object($resql);
4700
-            if ($local == 1)
4701
-                return $obj->localtax1;
4702
-            elseif ($local == 2)
4703
-                return $obj->localtax2;
4905
+            if ($local == 1) {
4906
+                            return $obj->localtax1;
4907
+            } elseif ($local == 2) {
4908
+                            return $obj->localtax2;
4909
+            }
4704 4910
         }
4705 4911
 
4706 4912
         return 0;
@@ -4726,9 +4932,9 @@  discard block
 block discarded – undo
4726 4932
 // Search local taxes
4727 4933
         $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
4728 4934
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4729
-        if ($firstparamisid)
4730
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4731
-        else {
4935
+        if ($firstparamisid) {
4936
+                    $sql .= " WHERE t.rowid = " . (int) $vatrate;
4937
+        } else {
4732 4938
             $vatratecleaned = $vatrate;
4733 4939
             $vatratecode = '';
4734 4940
             if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "xx (yy)"
@@ -4741,19 +4947,22 @@  discard block
 block discarded – undo
4741 4947
               else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; */
4742 4948
             $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4743 4949
             $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4744
-            if ($vatratecode)
4745
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4950
+            if ($vatratecode) {
4951
+                            $sql .= " AND t.code = '" . $vatratecode . "'";
4952
+            }
4746 4953
         }
4747 4954
 
4748 4955
         $resql = $db->query($sql);
4749 4956
         if ($resql) {
4750 4957
             $obj = $db->fetch_object($resql);
4751
-            if ($obj)
4752
-                return array('rowid' => $obj->rowid, 'code' => $obj->code, 'rate' => $obj->rate, 'npr' => $obj->npr, 'accountancy_code_sell' => $obj->accountancy_code_sell, 'accountancy_code_buy' => $obj->accountancy_code_buy);
4753
-            else
4754
-                return array();
4755
-        } else
4756
-            dol_print_error($db);
4958
+            if ($obj) {
4959
+                            return array('rowid' => $obj->rowid, 'code' => $obj->code, 'rate' => $obj->rate, 'npr' => $obj->npr, 'accountancy_code_sell' => $obj->accountancy_code_sell, 'accountancy_code_buy' => $obj->accountancy_code_buy);
4960
+            } else {
4961
+                            return array();
4962
+            }
4963
+        } else {
4964
+                    dol_print_error($db);
4965
+        }
4757 4966
 
4758 4967
         return array();
4759 4968
     }
@@ -4783,9 +4992,9 @@  discard block
 block discarded – undo
4783 4992
 // Search local taxes
4784 4993
         $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
4785 4994
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4786
-        if ($firstparamisid)
4787
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4788
-        else {
4995
+        if ($firstparamisid) {
4996
+                    $sql .= " WHERE t.rowid = " . (int) $vatrate;
4997
+        } else {
4789 4998
             $vatratecleaned = $vatrate;
4790 4999
             $vatratecode = '';
4791 5000
             if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "x.x (yy)"
@@ -4794,13 +5003,17 @@  discard block
 block discarded – undo
4794 5003
             }
4795 5004
 
4796 5005
             $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4797
-            if ($mysoc->country_code == 'ES')
4798
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";    // local tax in spain use the buyer country ??
4799
-            else
4800
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
5006
+            if ($mysoc->country_code == 'ES') {
5007
+                            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";
5008
+            }
5009
+            // local tax in spain use the buyer country ??
5010
+            else {
5011
+                            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
5012
+            }
4801 5013
             $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4802
-            if ($vatratecode)
4803
-                $sql .= " AND t.code = '" . $vatratecode . "'";
5014
+            if ($vatratecode) {
5015
+                            $sql .= " AND t.code = '" . $vatratecode . "'";
5016
+            }
4804 5017
         }
4805 5018
 
4806 5019
         $resql = $db->query($sql);
@@ -4846,17 +5059,17 @@  discard block
 block discarded – undo
4846 5059
                 if ($idprodfournprice > 0) {     // We want vat for product for a "supplier" object
4847 5060
                     $product->get_buyprice($idprodfournprice, 0, 0, 0);
4848 5061
                     $ret = $product->vatrate_supplier;
4849
-                    if ($product->default_vat_code)
4850
-                        $ret .= ' (' . $product->default_vat_code . ')';
4851
-                }
4852
-                else {
5062
+                    if ($product->default_vat_code) {
5063
+                                            $ret .= ' (' . $product->default_vat_code . ')';
5064
+                    }
5065
+                } else {
4853 5066
                     $ret = $product->tva_tx;    // Default vat of product we defined
4854
-                    if ($product->default_vat_code)
4855
-                        $ret .= ' (' . $product->default_vat_code . ')';
5067
+                    if ($product->default_vat_code) {
5068
+                                            $ret .= ' (' . $product->default_vat_code . ')';
5069
+                    }
4856 5070
                 }
4857 5071
                 $found = 1;
4858
-            }
4859
-            else {
5072
+            } else {
4860 5073
 // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
4861 5074
 // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
4862 5075
             }
@@ -4876,14 +5089,18 @@  discard block
 block discarded – undo
4876 5089
                     $obj = $db->fetch_object($resql);
4877 5090
                     if ($obj) {
4878 5091
                         $ret = $obj->vat_rate;
4879
-                        if ($obj->default_vat_code)
4880
-                            $ret .= ' (' . $obj->default_vat_code . ')';
5092
+                        if ($obj->default_vat_code) {
5093
+                                                    $ret .= ' (' . $obj->default_vat_code . ')';
5094
+                        }
4881 5095
                     }
4882 5096
                     $db->free($sql);
4883
-                } else
4884
-                    dol_print_error($db);
4885
-            } else
4886
-                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;    // Forced value if autodetect fails
5097
+                } else {
5098
+                                    dol_print_error($db);
5099
+                }
5100
+            } else {
5101
+                            $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
5102
+            }
5103
+            // Forced value if autodetect fails
4887 5104
         }
4888 5105
 
4889 5106
         DolUtils::dol_syslog("get_product_vat_for_country: ret=" . $ret);
@@ -4938,13 +5155,15 @@  discard block
 block discarded – undo
4938 5155
             if ($resql) {
4939 5156
                 $obj = $db->fetch_object($resql);
4940 5157
                 if ($obj) {
4941
-                    if ($local == 1)
4942
-                        $ret = $obj->localtax1;
4943
-                    elseif ($local == 2)
4944
-                        $ret = $obj->localtax2;
5158
+                    if ($local == 1) {
5159
+                                            $ret = $obj->localtax1;
5160
+                    } elseif ($local == 2) {
5161
+                                            $ret = $obj->localtax2;
5162
+                    }
4945 5163
                 }
4946
-            } else
4947
-                dol_print_error($db);
5164
+            } else {
5165
+                            dol_print_error($db);
5166
+            }
4948 5167
         }
4949 5168
 
4950 5169
         DolUtils::dol_syslog("get_product_localtax_for_country: ret=" . $ret);
@@ -5047,15 +5266,16 @@  discard block
 block discarded – undo
5047 5266
         // global $db;
5048 5267
 
5049 5268
         if ($idprodfournprice > 0) {
5050
-            if (!class_exists('ProductFournisseur'))
5051
-                require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5269
+            if (!class_exists('ProductFournisseur')) {
5270
+                            require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5271
+            }
5052 5272
             $prodprice = new ProductFournisseur($db);
5053 5273
             $prodprice->fetch_product_fournisseur_price($idprodfournprice);
5054 5274
             return $prodprice->fourn_tva_npr;
5055
-        }
5056
-        elseif ($idprod > 0) {
5057
-            if (!class_exists('Product'))
5058
-                require_once DOL_BASE_PATH . 'product/class/product.class.php';
5275
+        } elseif ($idprod > 0) {
5276
+            if (!class_exists('Product')) {
5277
+                            require_once DOL_BASE_PATH . 'product/class/product.class.php';
5278
+            }
5059 5279
             $prod = new Product($db);
5060 5280
             $prod->fetch($idprod);
5061 5281
             return $prod->tva_npr;
@@ -5081,30 +5301,35 @@  discard block
 block discarded – undo
5081 5301
     {
5082 5302
         // global $mysoc;
5083 5303
 
5084
-        if (!is_object($thirdparty_seller))
5085
-            return -1;
5086
-        if (!is_object($thirdparty_buyer))
5087
-            return -1;
5304
+        if (!is_object($thirdparty_seller)) {
5305
+                    return -1;
5306
+        }
5307
+        if (!is_object($thirdparty_buyer)) {
5308
+                    return -1;
5309
+        }
5088 5310
 
5089 5311
         if ($local == 1) { // Localtax 1
5090 5312
             if ($mysoc->country_code == 'ES') {
5091
-                if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj)
5092
-                    return 0;
5093
-            }
5094
-            else {
5313
+                if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
5314
+                                    return 0;
5315
+                }
5316
+            } else {
5095 5317
 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
5096
-                if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj)
5097
-                    return 0;
5098
-                if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off')
5099
-                    return 0;
5100
-            }
5101
-        }
5102
-        elseif ($local == 2) { //I Localtax 2
5318
+                if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
5319
+                                    return 0;
5320
+                }
5321
+                if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
5322
+                                    return 0;
5323
+                }
5324
+            }
5325
+        } elseif ($local == 2) { //I Localtax 2
5103 5326
 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
5104
-            if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj)
5105
-                return 0;
5106
-            if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off')
5107
-                return 0;
5327
+            if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
5328
+                            return 0;
5329
+            }
5330
+            if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
5331
+                            return 0;
5332
+            }
5108 5333
         }
5109 5334
 
5110 5335
         if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
@@ -5129,31 +5354,38 @@  discard block
 block discarded – undo
5129 5354
         $classname = '';
5130 5355
         if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') {  // A mettre avant test sur no a cause du == 0
5131 5356
             $result = Globals::$langs->trans('yes');
5132
-            if ($case == 1 || $case == 3)
5133
-                $result = Globals::$langs->trans("Yes");
5134
-            if ($case == 2)
5135
-                $result = '<input type="checkbox" value="1" checked disabled>';
5136
-            if ($case == 3)
5137
-                $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5357
+            if ($case == 1 || $case == 3) {
5358
+                            $result = Globals::$langs->trans("Yes");
5359
+            }
5360
+            if ($case == 2) {
5361
+                            $result = '<input type="checkbox" value="1" checked disabled>';
5362
+            }
5363
+            if ($case == 3) {
5364
+                            $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5365
+            }
5138 5366
 
5139 5367
             $classname = 'ok';
5140
-        }
5141
-        elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
5368
+        } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
5142 5369
             $result = Globals::$langs->trans("no");
5143
-            if ($case == 1 || $case == 3)
5144
-                $result = Globals::$langs->trans("No");
5145
-            if ($case == 2)
5146
-                $result = '<input type="checkbox" value="0" disabled>';
5147
-            if ($case == 3)
5148
-                $result = '<input type="checkbox" value="0" disabled> ' . $result;
5149
-
5150
-            if ($color == 2)
5151
-                $classname = 'ok';
5152
-            else
5153
-                $classname = 'error';
5154
-        }
5155
-        if ($color)
5156
-            return '<font class="' . $classname . '">' . $result . '</font>';
5370
+            if ($case == 1 || $case == 3) {
5371
+                            $result = Globals::$langs->trans("No");
5372
+            }
5373
+            if ($case == 2) {
5374
+                            $result = '<input type="checkbox" value="0" disabled>';
5375
+            }
5376
+            if ($case == 3) {
5377
+                            $result = '<input type="checkbox" value="0" disabled> ' . $result;
5378
+            }
5379
+
5380
+            if ($color == 2) {
5381
+                            $classname = 'ok';
5382
+            } else {
5383
+                            $classname = 'error';
5384
+            }
5385
+        }
5386
+        if ($color) {
5387
+                    return '<font class="' . $classname . '">' . $result . '</font>';
5388
+        }
5157 5389
         return $result;
5158 5390
     }
5159 5391
 
@@ -5179,23 +5411,27 @@  discard block
 block discarded – undo
5179 5411
         $path = '';
5180 5412
 
5181 5413
         $arrayforoldpath = array('cheque', 'user', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
5182
-        if (!empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
5183
-            $arrayforoldpath[] = 'product';
5414
+        if (!empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5415
+                    $arrayforoldpath[] = 'product';
5416
+        }
5184 5417
         if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
5185 5418
 // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
5186
-            if (empty($alpha))
5187
-                $num = preg_replace('/([^0-9])/i', '', $num);
5188
-            else
5189
-                $num = preg_replace('/^.*\-/i', '', $num);
5419
+            if (empty($alpha)) {
5420
+                            $num = preg_replace('/([^0-9])/i', '', $num);
5421
+            } else {
5422
+                            $num = preg_replace('/^.*\-/i', '', $num);
5423
+            }
5190 5424
             $num = substr("000" . $num, -$level);
5191
-            if ($level == 1)
5192
-                $path = substr($num, 0, 1);
5193
-            if ($level == 2)
5194
-                $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5195
-            if ($level == 3)
5196
-                $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5197
-        }
5198
-        else {
5425
+            if ($level == 1) {
5426
+                            $path = substr($num, 0, 1);
5427
+            }
5428
+            if ($level == 2) {
5429
+                            $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5430
+            }
5431
+            if ($level == 3) {
5432
+                            $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5433
+            }
5434
+        } else {
5199 5435
 // TODO
5200 5436
 // We will enhance here a common way of forging path for document storage
5201 5437
 // Here, object->id, object->ref and modulepart are required.
@@ -5206,8 +5442,9 @@  discard block
 block discarded – undo
5206 5442
             }
5207 5443
         }
5208 5444
 
5209
-        if (empty($withoutslash) && !empty($path))
5210
-            $path .= '/';
5445
+        if (empty($withoutslash) && !empty($path)) {
5446
+                    $path .= '/';
5447
+        }
5211 5448
 
5212 5449
         return $path;
5213 5450
     }
@@ -5227,8 +5464,9 @@  discard block
 block discarded – undo
5227 5464
         DolUtils::dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5228 5465
 
5229 5466
         $dir_osencoded = dol_osencode($dir);
5230
-        if (@is_dir($dir_osencoded))
5231
-            return 0;
5467
+        if (@is_dir($dir_osencoded)) {
5468
+                    return 0;
5469
+        }
5232 5470
 
5233 5471
         $nberr = 0;
5234 5472
         $nbcreated = 0;
@@ -5243,12 +5481,15 @@  discard block
 block discarded – undo
5243 5481
         $cdir = explode("/", $dir);
5244 5482
         $num = count($cdir);
5245 5483
         for ($i = 0; $i < $num; $i++) {
5246
-            if ($i > 0)
5247
-                $ccdir .= '/' . $cdir[$i];
5248
-            else
5249
-                $ccdir .= $cdir[$i];
5250
-            if (preg_match("/^.:$/", $ccdir, $regs))
5251
-                continue; // Si chemin Windows incomplet, on poursuit par rep suivant
5484
+            if ($i > 0) {
5485
+                            $ccdir .= '/' . $cdir[$i];
5486
+            } else {
5487
+                            $ccdir .= $cdir[$i];
5488
+            }
5489
+            if (preg_match("/^.:$/", $ccdir, $regs)) {
5490
+                            continue;
5491
+            }
5492
+            // Si chemin Windows incomplet, on poursuit par rep suivant
5252 5493
 
5253 5494
 
5254 5495
 
@@ -5350,8 +5591,9 @@  discard block
 block discarded – undo
5350 5591
      */
5351 5592
     static function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0)
5352 5593
     {
5353
-        if ($removelinefeed == 2)
5354
-            $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
5594
+        if ($removelinefeed == 2) {
5595
+                    $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
5596
+        }
5355 5597
         $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
5356 5598
 
5357 5599
         if ($strip_tags) {
@@ -5368,8 +5610,9 @@  discard block
 block discarded – undo
5368 5610
         $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
5369 5611
 
5370 5612
 // Supprime aussi les retours
5371
-        if ($removelinefeed == 1)
5372
-            $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
5613
+        if ($removelinefeed == 1) {
5614
+                    $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
5615
+        }
5373 5616
 
5374 5617
 // et les espaces doubles
5375 5618
         while (strpos($temp, "  ")) {
@@ -5455,18 +5698,21 @@  discard block
 block discarded – undo
5455 5698
             if ($charset == 'UTF-8') {
5456 5699
                 $pattern = '/(<br[^>]*>)/Uu';
5457 5700
             } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5458
-            else
5459
-                $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5701
+            else {
5702
+                            $pattern = '/(<br[^>]*>)/U';
5703
+            }
5704
+            // /U is to have UNGREEDY regex to limit to one html tag.
5460 5705
             $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5461 5706
 
5462 5707
             $firstline = '';
5463 5708
             $i = 0;
5464 5709
             $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
5465 5710
             while (($i < $nba) && ($i < ($nboflines * 2))) {
5466
-                if ($i % 2 == 0)
5467
-                    $firstline .= $a[$i];
5468
-                elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1)))
5469
-                    $firstline .= ($ishtml ? "<br>\n" : "\n");
5711
+                if ($i % 2 == 0) {
5712
+                                    $firstline .= $a[$i];
5713
+                } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
5714
+                                    $firstline .= ($ishtml ? "<br>\n" : "\n");
5715
+                }
5470 5716
                 $i++;
5471 5717
             }
5472 5718
             unset($a);
@@ -5515,15 +5761,18 @@  discard block
 block discarded – undo
5515 5761
         $newstring = $stringtoencode;
5516 5762
         if (DolUtils::dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
5517 5763
             $newstring = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', '<br>', $newstring); // Replace "<br type="_moz" />" by "<br>". It's same and avoid pb with FPDF.
5518
-            if ($removelasteolbr)
5519
-                $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
5764
+            if ($removelasteolbr) {
5765
+                            $newstring = preg_replace('/<br>$/i', '', $newstring);
5766
+            }
5767
+            // Remove last <br> (remove only last one)
5520 5768
             $newstring = strtr($newstring, array('&' => '__and__', '<' => '__lt__', '>' => '__gt__', '"' => '__dquot__'));
5521 5769
             $newstring = DolUtils::dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
5522 5770
             $newstring = strtr($newstring, array('__and__' => '&', '__lt__' => '<', '__gt__' => '>', '__dquot__' => '"'));
5523
-        }
5524
-        else {
5525
-            if ($removelasteolbr)
5526
-                $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
5771
+        } else {
5772
+            if ($removelasteolbr) {
5773
+                            $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring);
5774
+            }
5775
+            // Remove last \n (may remove several)
5527 5776
             $newstring = dol_nl2br(DolUtils::dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
5528 5777
         }
5529 5778
 // Other substitutions that htmlentities does not do
@@ -5625,8 +5874,9 @@  discard block
 block discarded – undo
5625 5874
      */
5626 5875
     static function dol_nboflines($s, $maxchar = 0)
5627 5876
     {
5628
-        if ($s == '')
5629
-            return 0;
5877
+        if ($s == '') {
5878
+                    return 0;
5879
+        }
5630 5880
         $arraystring = explode("\n", $s);
5631 5881
         $nb = count($arraystring);
5632 5882
 
@@ -5645,15 +5895,18 @@  discard block
 block discarded – undo
5645 5895
     static function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
5646 5896
     {
5647 5897
         $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
5648
-        if (DolUtils::dol_textishtml($text))
5649
-            $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
5898
+        if (DolUtils::dol_textishtml($text)) {
5899
+                    $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
5900
+        }
5650 5901
 
5651 5902
         $text = strtr($text, $repTable);
5652 5903
         if ($charset == 'UTF-8') {
5653 5904
             $pattern = '/(<br[^>]*>)/Uu';
5654 5905
         } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5655
-        else
5656
-            $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5906
+        else {
5907
+                    $pattern = '/(<br[^>]*>)/U';
5908
+        }
5909
+        // /U is to have UNGREEDY regex to limit to one html tag.
5657 5910
         $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5658 5911
 
5659 5912
         $nblines = (int) floor((count($a) + 1) / 2);
@@ -5700,39 +5953,47 @@  discard block
 block discarded – undo
5700 5953
     static function dol_textishtml($msg, $option = 0)
5701 5954
     {
5702 5955
         if ($option == 1) {
5703
-            if (preg_match('/<html/i', $msg))
5704
-                return true;
5705
-            elseif (preg_match('/<body/i', $msg))
5706
-                return true;
5707
-            elseif (preg_match('/<br/i', $msg))
5708
-                return true;
5956
+            if (preg_match('/<html/i', $msg)) {
5957
+                            return true;
5958
+            } elseif (preg_match('/<body/i', $msg)) {
5959
+                            return true;
5960
+            } elseif (preg_match('/<br/i', $msg)) {
5961
+                            return true;
5962
+            }
5709 5963
             return false;
5710
-        }
5711
-        else {
5712
-            if (preg_match('/<html/i', $msg))
5713
-                return true;
5714
-            elseif (preg_match('/<body/i', $msg))
5715
-                return true;
5716
-            elseif (preg_match('/<(b|em|i|u)>/i', $msg))
5717
-                return true;
5718
-            elseif (preg_match('/<br\/>/i', $msg))
5719
-                return true;
5720
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg))
5721
-                return true;
5722
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg))
5723
-                return true;
5724
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg))
5725
-                return true;
5726
-            elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg))
5727
-                return true; // must accept <img src="http://example.com/aaa.png" />
5728
-            elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg))
5729
-                return true; // must accept <a href="http://example.com/aaa.png" />
5730
-            elseif (preg_match('/<h[0-9]>/i', $msg))
5731
-                return true;
5732
-            elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg))
5733
-                return true;    // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5734
-            elseif (preg_match('/&#[0-9]{2,3};/i', $msg))
5735
-                return true;    // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5964
+        } else {
5965
+            if (preg_match('/<html/i', $msg)) {
5966
+                            return true;
5967
+            } elseif (preg_match('/<body/i', $msg)) {
5968
+                            return true;
5969
+            } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
5970
+                            return true;
5971
+            } elseif (preg_match('/<br\/>/i', $msg)) {
5972
+                            return true;
5973
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
5974
+                            return true;
5975
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) {
5976
+                            return true;
5977
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) {
5978
+                            return true;
5979
+            } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
5980
+                            return true;
5981
+            }
5982
+            // must accept <img src="http://example.com/aaa.png" />
5983
+            elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
5984
+                            return true;
5985
+            }
5986
+            // must accept <a href="http://example.com/aaa.png" />
5987
+            elseif (preg_match('/<h[0-9]>/i', $msg)) {
5988
+                            return true;
5989
+            } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
5990
+                            return true;
5991
+            }
5992
+            // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5993
+            elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
5994
+                            return true;
5995
+            }
5996
+            // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5736 5997
 
5737 5998
             return false;
5738 5999
         }
@@ -5884,12 +6145,14 @@  discard block
 block discarded – undo
5884 6145
                 $birthday = DolUtils::dol_print_date($object->birth, 'day');
5885 6146
 
5886 6147
                 $substitutionarray['__MEMBER_ID__'] = $object->id;
5887
-                if (method_exists($object, 'getCivilityLabel'))
5888
-                    $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
6148
+                if (method_exists($object, 'getCivilityLabel')) {
6149
+                                    $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
6150
+                }
5889 6151
                 $substitutionarray['__MEMBER_FIRSTNAME__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->firstname) : $object->firstname;
5890 6152
                 $substitutionarray['__MEMBER_LASTNAME__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->lastname) : $object->lastname;
5891
-                if (method_exists($object, 'getFullName'))
5892
-                    $substitutionarray['__MEMBER_FULLNAME__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->getFullName($outputlangs)) : $object->getFullName($outputlangs);
6153
+                if (method_exists($object, 'getFullName')) {
6154
+                                    $substitutionarray['__MEMBER_FULLNAME__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->getFullName($outputlangs)) : $object->getFullName($outputlangs);
6155
+                }
5893 6156
                 $substitutionarray['__MEMBER_COMPANY__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->societe) : $object->societe;
5894 6157
                 $substitutionarray['__MEMBER_ADDRESS__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->address) : $object->address;
5895 6158
                 $substitutionarray['__MEMBER_ZIP__'] = $msgishtml ? DolUtils::dol_htmlentitiesbr($object->zip) : $object->zip;
@@ -5937,10 +6200,12 @@  discard block
 block discarded – undo
5937 6200
                     $dateplannedstart = '';
5938 6201
                     $datenextexpiration = '';
5939 6202
                     foreach ($object->lines as $line) {
5940
-                        if ($line->date_ouverture_prevue > $dateplannedstart)
5941
-                            $dateplannedstart = $line->date_ouverture_prevue;
5942
-                        if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration))
5943
-                            $datenextexpiration = $line->date_fin_prevue;
6203
+                        if ($line->date_ouverture_prevue > $dateplannedstart) {
6204
+                                                    $dateplannedstart = $line->date_ouverture_prevue;
6205
+                        }
6206
+                        if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
6207
+                                                    $datenextexpiration = $line->date_fin_prevue;
6208
+                        }
5944 6209
                     }
5945 6210
                     $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = DolUtils::dol_print_date($dateplannedstart, 'dayrfc');
5946 6211
                     $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = DolUtils::dol_print_date($dateplannedstart, 'standard');
@@ -5950,8 +6215,9 @@  discard block
 block discarded – undo
5950 6215
 
5951 6216
 // Create dynamic tags for __EXTRAFIELD_FIELD__
5952 6217
                 if ($object->table_element && $object->id > 0) {
5953
-                    if (!is_object($extrafields))
5954
-                        $extrafields = new ExtraFields($db);
6218
+                    if (!is_object($extrafields)) {
6219
+                                            $extrafields = new ExtraFields($db);
6220
+                    }
5955 6221
                     $extrafields->fetch_name_optionals_label($object->table_element, true);
5956 6222
 
5957 6223
                     if ($object->fetch_optionals() > 0) {
@@ -5972,12 +6238,15 @@  discard block
 block discarded – undo
5972 6238
                     require_once DOL_BASE_PATH . '/core/lib/payments.lib.php';
5973 6239
                     $outputlangs->loadLangs(array('paypal', 'other'));
5974 6240
                     $typeforonlinepayment = 'free';
5975
-                    if (is_object($object) && $object->element == 'commande')
5976
-                        $typeforonlinepayment = 'order';
5977
-                    if (is_object($object) && $object->element == 'facture')
5978
-                        $typeforonlinepayment = 'invoice';
5979
-                    if (is_object($object) && $object->element == 'member')
5980
-                        $typeforonlinepayment = 'member';
6241
+                    if (is_object($object) && $object->element == 'commande') {
6242
+                                            $typeforonlinepayment = 'order';
6243
+                    }
6244
+                    if (is_object($object) && $object->element == 'facture') {
6245
+                                            $typeforonlinepayment = 'invoice';
6246
+                    }
6247
+                    if (is_object($object) && $object->element == 'member') {
6248
+                                            $typeforonlinepayment = 'member';
6249
+                    }
5981 6250
                     $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
5982 6251
                     $paymenturl = $url;
5983 6252
                 }
@@ -5987,16 +6256,19 @@  discard block
 block discarded – undo
5987 6256
 
5988 6257
                 if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
5989 6258
                     $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
5990
-                } else
5991
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
6259
+                } else {
6260
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
6261
+                }
5992 6262
                 if (!empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
5993 6263
                     $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
5994
-                } else
5995
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
6264
+                } else {
6265
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
6266
+                }
5996 6267
                 if (!empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
5997 6268
                     $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
5998
-                } else
5999
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
6269
+                } else {
6270
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
6271
+                }
6000 6272
             }
6001 6273
         }
6002 6274
         if (empty($exclude) || !in_array('objectamount', $exclude)) {
@@ -6006,18 +6278,22 @@  discard block
 block discarded – undo
6006 6278
             $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
6007 6279
             $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
6008 6280
             $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
6009
-            if ($onlykey != 2 || $mysoc->useLocalTax(1))
6010
-                $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
6011
-            if ($onlykey != 2 || $mysoc->useLocalTax(2))
6012
-                $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
6281
+            if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
6282
+                            $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
6283
+            }
6284
+            if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
6285
+                            $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
6286
+            }
6013 6287
 
6014 6288
             $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6015 6289
             $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6016 6290
             $substitutionarray['__AMOUNT_VAT_FORMATED__'] = is_object($object) ? ($object->total_vat ? price($object->total_vat, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : price($object->total_tva, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency)) : '';
6017
-            if ($onlykey != 2 || $mysoc->useLocalTax(1))
6018
-                $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6019
-            if ($onlykey != 2 || $mysoc->useLocalTax(2))
6020
-                $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6291
+            if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
6292
+                            $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6293
+            }
6294
+            if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
6295
+                            $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6296
+            }
6021 6297
 
6022 6298
 // TODO Add keys for foreign multicurrency
6023 6299
 // For backward compatibility
@@ -6087,23 +6363,27 @@  discard block
 block discarded – undo
6087 6363
     {
6088 6364
         // global Globals::$conf, Globals::$langs;
6089 6365
 
6090
-        if (!is_array($substitutionarray))
6091
-            return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
6366
+        if (!is_array($substitutionarray)) {
6367
+                    return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
6368
+        }
6092 6369
 
6093
-        if (empty($outputlangs))
6094
-            $outputlangs = Globals::$langs;
6370
+        if (empty($outputlangs)) {
6371
+                    $outputlangs = Globals::$langs;
6372
+        }
6095 6373
 
6096 6374
 // Make substitution for language keys
6097 6375
         if (is_object($outputlangs)) {
6098 6376
             while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
6099 6377
                 $msgishtml = 0;
6100
-                if (DolUtils::dol_textishtml($text, 1))
6101
-                    $msgishtml = 1;
6378
+                if (DolUtils::dol_textishtml($text, 1)) {
6379
+                                    $msgishtml = 1;
6380
+                }
6102 6381
 
6103 6382
 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
6104 6383
                 $tmp = explode('|', $reg[1]);
6105
-                if (!empty($tmp[1]))
6106
-                    $outputlangs->load($tmp[1]);
6384
+                if (!empty($tmp[1])) {
6385
+                                    $outputlangs->load($tmp[1]);
6386
+                }
6107 6387
 
6108 6388
                 $text = preg_replace('/__\(' . preg_quote($reg[1], '/') . '\)__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6109 6389
             }
@@ -6113,23 +6393,29 @@  discard block
 block discarded – undo
6113 6393
 // it is also converted.
6114 6394
         while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
6115 6395
             $msgishtml = 0;
6116
-            if (DolUtils::dol_textishtml($text, 1))
6117
-                $msgishtml = 1;
6396
+            if (DolUtils::dol_textishtml($text, 1)) {
6397
+                            $msgishtml = 1;
6398
+            }
6118 6399
 
6119 6400
             $keyfound = $reg[1];
6120
-            if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound))
6121
-                $newval = '*****forbidden*****';
6122
-            else
6123
-                $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6401
+            if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound)) {
6402
+                            $newval = '*****forbidden*****';
6403
+            } else {
6404
+                            $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6405
+            }
6124 6406
             $text = preg_replace('/__\[' . preg_quote($keyfound, '/') . '\]__/', $msgishtml ? DolUtils::dol_htmlentitiesbr($newval) : $newval, $text);
6125 6407
         }
6126 6408
 
6127 6409
 // Make substitition for array $substitutionarray
6128 6410
         foreach ($substitutionarray as $key => $value) {
6129
-            if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6130
-                $value = '';  // Protection
6131
-            if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6132
-                $value = ''; // Protection
6411
+            if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
6412
+                            $value = '';
6413
+            }
6414
+            // Protection
6415
+            if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
6416
+                            $value = '';
6417
+            }
6418
+            // Protection
6133 6419
 
6134 6420
             $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
6135 6421
         }
@@ -6175,8 +6461,9 @@  discard block
 block discarded – undo
6175 6461
             $dir = dol_buildpath($reldir, 0);
6176 6462
 
6177 6463
 // Check if directory exists
6178
-            if (!dol_is_dir($dir))
6179
-                continue;
6464
+            if (!dol_is_dir($dir)) {
6465
+                            continue;
6466
+            }
6180 6467
 
6181 6468
             $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
6182 6469
             foreach ($substitfiles as $substitfile) {
@@ -6188,8 +6475,9 @@  discard block
 block discarded – undo
6188 6475
                     require_once $dir . $substitfile['name'];
6189 6476
                     // Call the user's function, and only if it is defined
6190 6477
                     $function_name = $module . "_" . $callfunc;
6191
-                    if (function_exists($function_name))
6192
-                        $function_name($substitutionarray, $outputlangs, $object, $parameters);
6478
+                    if (function_exists($function_name)) {
6479
+                                            $function_name($substitutionarray, $outputlangs, $object, $parameters);
6480
+                    }
6193 6481
                 }
6194 6482
             }
6195 6483
         }
@@ -6225,8 +6513,9 @@  discard block
 block discarded – undo
6225 6513
 
6226 6514
         $out = '';
6227 6515
 
6228
-        if (!is_object($outputlangs))
6229
-            $outputlangs = Globals::$langs;
6516
+        if (!is_object($outputlangs)) {
6517
+                    $outputlangs = Globals::$langs;
6518
+        }
6230 6519
 
6231 6520
         if ($date_start && $date_end) {
6232 6521
             $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', DolUtils::dol_print_date($date_start, $format, false, $outputlangs), DolUtils::dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
@@ -6255,20 +6544,22 @@  discard block
 block discarded – undo
6255 6544
 
6256 6545
         $ret = '';
6257 6546
 // If order not defined, we use the setup
6258
-        if ($nameorder < 0)
6259
-            $nameorder = (empty(Globals::$conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
6547
+        if ($nameorder < 0) {
6548
+                    $nameorder = (empty(Globals::$conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
6549
+        }
6260 6550
         if ($nameorder && ((string) $nameorder != '2')) {
6261 6551
             $ret .= $firstname;
6262
-            if ($firstname && $lastname)
6263
-                $ret .= ' ';
6552
+            if ($firstname && $lastname) {
6553
+                            $ret .= ' ';
6554
+            }
6264 6555
             $ret .= $lastname;
6265
-        }
6266
-        else if ($nameorder == 2) {
6556
+        } else if ($nameorder == 2) {
6267 6557
             $ret .= $firstname;
6268 6558
         } else {
6269 6559
             $ret .= $lastname;
6270
-            if ($firstname && $lastname)
6271
-                $ret .= ' ';
6560
+            if ($firstname && $lastname) {
6561
+                            $ret .= ' ';
6562
+            }
6272 6563
             $ret .= $firstname;
6273 6564
         }
6274 6565
         return $ret;
@@ -6288,13 +6579,14 @@  discard block
 block discarded – undo
6288 6579
     {
6289 6580
 //DolUtils::dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);		This is not deprecated, it is used by setEventMessages function
6290 6581
         if (!is_array($mesgs)) {  // If mesgs is a string
6291
-            if ($mesgs)
6292
-                $_SESSION['dol_events'][$style][] = $mesgs;
6293
-        }
6294
-        else {      // If mesgs is an array
6582
+            if ($mesgs) {
6583
+                            $_SESSION['dol_events'][$style][] = $mesgs;
6584
+            }
6585
+        } else {      // If mesgs is an array
6295 6586
             foreach ($mesgs as $mesg) {
6296
-                if ($mesg)
6297
-                    $_SESSION['dol_events'][$style][] = $mesg;
6587
+                if ($mesg) {
6588
+                                    $_SESSION['dol_events'][$style][] = $mesg;
6589
+                }
6298 6590
             }
6299 6591
         }
6300 6592
     }
@@ -6314,13 +6606,16 @@  discard block
 block discarded – undo
6314 6606
         if (empty($mesg) && empty($mesgs)) {
6315 6607
             DolUtils::dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
6316 6608
         } else {
6317
-            if (!in_array((string) $style, array('mesgs', 'warnings', 'errors')))
6318
-                dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6319
-            if (empty($mesgs))
6320
-                setEventMessage($mesg, $style);
6321
-            else {
6322
-                if (!empty($mesg) && !in_array($mesg, $mesgs))
6323
-                    setEventMessage($mesg, $style); // Add message string if not already into array
6609
+            if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
6610
+                            dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6611
+            }
6612
+            if (empty($mesgs)) {
6613
+                            setEventMessage($mesg, $style);
6614
+            } else {
6615
+                if (!empty($mesg) && !in_array($mesg, $mesgs)) {
6616
+                                    setEventMessage($mesg, $style);
6617
+                }
6618
+                // Add message string if not already into array
6324 6619
                 setEventMessage($mesgs, $style);
6325 6620
             }
6326 6621
         }
@@ -6339,22 +6634,25 @@  discard block
 block discarded – undo
6339 6634
     {
6340 6635
 // Show mesgs
6341 6636
         if (isset($_SESSION['dol_events']['mesgs'])) {
6342
-            if (empty($disabledoutputofmessages))
6343
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
6637
+            if (empty($disabledoutputofmessages)) {
6638
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
6639
+            }
6344 6640
             unset($_SESSION['dol_events']['mesgs']);
6345 6641
         }
6346 6642
 
6347 6643
 // Show errors
6348 6644
         if (isset($_SESSION['dol_events']['errors'])) {
6349
-            if (empty($disabledoutputofmessages))
6350
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
6645
+            if (empty($disabledoutputofmessages)) {
6646
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
6647
+            }
6351 6648
             unset($_SESSION['dol_events']['errors']);
6352 6649
         }
6353 6650
 
6354 6651
 // Show warnings
6355 6652
         if (isset($_SESSION['dol_events']['warnings'])) {
6356
-            if (empty($disabledoutputofmessages))
6357
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
6653
+            if (empty($disabledoutputofmessages)) {
6654
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
6655
+            }
6358 6656
             unset($_SESSION['dol_events']['warnings']);
6359 6657
         }
6360 6658
     }
@@ -6395,8 +6693,9 @@  discard block
 block discarded – undo
6395 6693
                 foreach ($mesgarray as $message) {
6396 6694
                     $ret++;
6397 6695
                     $out .= Globals::$langs->trans($message);
6398
-                    if ($ret < count($mesgarray))
6399
-                        $out .= "<br>\n";
6696
+                    if ($ret < count($mesgarray)) {
6697
+                                            $out .= "<br>\n";
6698
+                    }
6400 6699
                 }
6401 6700
             }
6402 6701
             if ($mesgstring) {
@@ -6462,8 +6761,9 @@  discard block
 block discarded – undo
6462 6761
      */
6463 6762
     static function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
6464 6763
     {
6465
-        if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0))
6466
-            return;
6764
+        if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
6765
+                    return;
6766
+        }
6467 6767
 
6468 6768
         $iserror = 0;
6469 6769
         $iswarning = 0;
@@ -6478,14 +6778,17 @@  discard block
 block discarded – undo
6478 6778
                     break;
6479 6779
                 }
6480 6780
             }
6481
-        } else if ($mesgstring && preg_match('/class="error"/i', $mesgstring))
6482
-            $iserror++;
6483
-        else if ($mesgstring && preg_match('/class="warning"/i', $mesgstring))
6484
-            $iswarning++;
6485
-        if ($style == 'error')
6486
-            $iserror++;
6487
-        if ($style == 'warning')
6488
-            $iswarning++;
6781
+        } else if ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
6782
+                    $iserror++;
6783
+        } else if ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
6784
+                    $iswarning++;
6785
+        }
6786
+        if ($style == 'error') {
6787
+                    $iserror++;
6788
+        }
6789
+        if ($style == 'warning') {
6790
+                    $iswarning++;
6791
+        }
6489 6792
 
6490 6793
         if ($iserror || $iswarning) {
6491 6794
 // Remove div from texts
@@ -6504,8 +6807,9 @@  discard block
 block discarded – undo
6504 6807
                 $mesgarray = $newmesgarray;
6505 6808
             }
6506 6809
             print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
6507
-        } else
6508
-            print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
6810
+        } else {
6811
+                    print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
6812
+        }
6509 6813
     }
6510 6814
 
6511 6815
     /**
@@ -6546,15 +6850,17 @@  discard block
 block discarded – undo
6546 6850
             $sizearray = count($array);
6547 6851
             if ($sizearray > 0) {
6548 6852
                 $temp = array();
6549
-                foreach (array_keys($array) as $key)
6550
-                    $temp[$key] = $array[$key][$index];
6853
+                foreach (array_keys($array) as $key) {
6854
+                                    $temp[$key] = $array[$key][$index];
6855
+                }
6551 6856
 
6552
-                if (!$natsort)
6553
-                    ($order == 'asc') ? asort($temp) : arsort($temp);
6554
-                else {
6857
+                if (!$natsort) {
6858
+                                    ($order == 'asc') ? asort($temp) : arsort($temp);
6859
+                } else {
6555 6860
                     ($case_sensitive) ? natsort($temp) : natcasesort($temp);
6556
-                    if ($order != 'asc')
6557
-                        $temp = array_reverse($temp, true);
6861
+                    if ($order != 'asc') {
6862
+                                            $temp = array_reverse($temp, true);
6863
+                    }
6558 6864
                 }
6559 6865
 
6560 6866
                 $sorted = array();
@@ -6580,23 +6886,38 @@  discard block
 block discarded – undo
6580 6886
         // We must use here a binary strlen static function (so not DolUtils::dol_strlen)
6581 6887
         $strLength = DolUtils::dol_strlen($str);
6582 6888
         for ($i = 0; $i < $strLength; $i++) {
6583
-            if (ord($str[$i]) < 0x80)
6584
-                continue; // 0bbbbbbb
6585
-            elseif ((ord($str[$i]) & 0xE0) == 0xC0)
6586
-                $n = 1; // 110bbbbb
6587
-            elseif ((ord($str[$i]) & 0xF0) == 0xE0)
6588
-                $n = 2; // 1110bbbb
6589
-            elseif ((ord($str[$i]) & 0xF8) == 0xF0)
6590
-                $n = 3; // 11110bbb
6591
-            elseif ((ord($str[$i]) & 0xFC) == 0xF8)
6592
-                $n = 4; // 111110bb
6593
-            elseif ((ord($str[$i]) & 0xFE) == 0xFC)
6594
-                $n = 5; // 1111110b
6595
-            else
6596
-                return false; // Does not match any model
6889
+            if (ord($str[$i]) < 0x80) {
6890
+                            continue;
6891
+            }
6892
+            // 0bbbbbbb
6893
+            elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
6894
+                            $n = 1;
6895
+            }
6896
+            // 110bbbbb
6897
+            elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
6898
+                            $n = 2;
6899
+            }
6900
+            // 1110bbbb
6901
+            elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
6902
+                            $n = 3;
6903
+            }
6904
+            // 11110bbb
6905
+            elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
6906
+                            $n = 4;
6907
+            }
6908
+            // 111110bb
6909
+            elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
6910
+                            $n = 5;
6911
+            }
6912
+            // 1111110b
6913
+            else {
6914
+                            return false;
6915
+            }
6916
+            // Does not match any model
6597 6917
             for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
6598
-                if (( ++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
6599
-                    return false;
6918
+                if (( ++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
6919
+                                    return false;
6920
+                }
6600 6921
             }
6601 6922
         }
6602 6923
         return true;
@@ -6614,15 +6935,21 @@  discard block
 block discarded – undo
6614 6935
         // global Globals::$conf;
6615 6936
 
6616 6937
         $tmp = ini_get("unicode.filesystem_encoding");      // Disponible avec PHP 6.0
6617
-        if (empty($tmp) && !empty($_SERVER["WINDIR"]))
6618
-            $tmp = 'iso-8859-1'; // By default for windows
6619
-        if (empty($tmp))
6620
-            $tmp = 'utf-8';          // By default for other
6621
-        if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING))
6622
-            $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6623
-
6624
-        if ($tmp == 'iso-8859-1')
6625
-            return utf8_decode($str);
6938
+        if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
6939
+                    $tmp = 'iso-8859-1';
6940
+        }
6941
+        // By default for windows
6942
+        if (empty($tmp)) {
6943
+                    $tmp = 'utf-8';
6944
+        }
6945
+        // By default for other
6946
+        if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING)) {
6947
+                    $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6948
+        }
6949
+
6950
+        if ($tmp == 'iso-8859-1') {
6951
+                    return utf8_decode($str);
6952
+        }
6626 6953
         return $str;
6627 6954
     }
6628 6955
 
@@ -6643,8 +6970,9 @@  discard block
 block discarded – undo
6643 6970
     {
6644 6971
         // global $cache_codes;
6645 6972
 // If key empty
6646
-        if ($key == '')
6647
-            return '';
6973
+        if ($key == '') {
6974
+                    return '';
6975
+        }
6648 6976
 
6649 6977
 // Check in cache
6650 6978
         if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
@@ -6656,20 +6984,21 @@  discard block
 block discarded – undo
6656 6984
         $sql = "SELECT " . $fieldid . " as valuetoget";
6657 6985
         $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
6658 6986
         $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($key) . "'";
6659
-        if (!empty($entityfilter))
6660
-            $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6987
+        if (!empty($entityfilter)) {
6988
+                    $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6989
+        }
6661 6990
 
6662 6991
         $resql = $db->query($sql);
6663 6992
         if ($resql) {
6664 6993
             $obj = $db->fetch_object($resql);
6665
-            if ($obj)
6666
-                $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
6667
-            else
6668
-                $cache_codes[$tablename][$key][$fieldid] = '';
6994
+            if ($obj) {
6995
+                            $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
6996
+            } else {
6997
+                            $cache_codes[$tablename][$key][$fieldid] = '';
6998
+            }
6669 6999
             $db->free($resql);
6670 7000
             return $cache_codes[$tablename][$key][$fieldid];
6671
-        }
6672
-        else {
7001
+        } else {
6673 7002
             return -1;
6674 7003
         }
6675 7004
     }
@@ -6715,16 +7044,17 @@  discard block
 block discarded – undo
6715 7044
         // global $soc;       // For backward compatibility
6716 7045
 //print $s."<br>\n";
6717 7046
         if ($returnvalue) {
6718
-            if ($hideerrors)
6719
-                return @eval('return ' . $s . ';');
6720
-            else
6721
-                return eval('return ' . $s . ';');
6722
-        }
6723
-        else {
6724
-            if ($hideerrors)
6725
-                @eval($s);
6726
-            else
6727
-                eval($s);
7047
+            if ($hideerrors) {
7048
+                            return @eval('return ' . $s . ';');
7049
+            } else {
7050
+                            return eval('return ' . $s . ';');
7051
+            }
7052
+        } else {
7053
+            if ($hideerrors) {
7054
+                            @eval($s);
7055
+            } else {
7056
+                            eval($s);
7057
+            }
6728 7058
         }
6729 7059
     }
6730 7060
 
@@ -6750,8 +7080,9 @@  discard block
 block discarded – undo
6750 7080
     {
6751 7081
         // global Globals::$langs;
6752 7082
 
6753
-        if (empty($codelang))
6754
-            return '';
7083
+        if (empty($codelang)) {
7084
+                    return '';
7085
+        }
6755 7086
 
6756 7087
         if ($codelang == 'auto') {
6757 7088
             return '<span class="fa fa-globe"></span>';
@@ -6765,9 +7096,9 @@  discard block
 block discarded – undo
6765 7096
             'sv_SV' => 'se'
6766 7097
         );
6767 7098
 
6768
-        if (isset($langtocountryflag[$codelang]))
6769
-            $flagImage = $langtocountryflag[$codelang];
6770
-        else {
7099
+        if (isset($langtocountryflag[$codelang])) {
7100
+                    $flagImage = $langtocountryflag[$codelang];
7101
+        } else {
6771 7102
             $tmparray = explode('_', $codelang);
6772 7103
             $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
6773 7104
         }
@@ -6785,15 +7116,20 @@  discard block
 block discarded – undo
6785 7116
     {
6786 7117
         // global $mysoc;
6787 7118
 
6788
-        if (strtoupper($countrycode) == 'MQ')
6789
-            return 'fr_CA';
6790
-        if (strtoupper($countrycode) == 'SE')
6791
-            return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
7119
+        if (strtoupper($countrycode) == 'MQ') {
7120
+                    return 'fr_CA';
7121
+        }
7122
+        if (strtoupper($countrycode) == 'SE') {
7123
+                    return 'sv_SE';
7124
+        }
7125
+        // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
6792 7126
         if (strtoupper($countrycode) == 'CH') {
6793
-            if ($mysoc->country_code == 'FR')
6794
-                return 'fr_CH';
6795
-            if ($mysoc->country_code == 'DE')
6796
-                return 'de_CH';
7127
+            if ($mysoc->country_code == 'FR') {
7128
+                            return 'fr_CH';
7129
+            }
7130
+            if ($mysoc->country_code == 'DE') {
7131
+                            return 'de_CH';
7132
+            }
6797 7133
         }
6798 7134
 
6799 7135
 // Locale list taken from:
@@ -6971,8 +7307,9 @@  discard block
 block discarded – undo
6971 7307
         );
6972 7308
 
6973 7309
         $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
6974
-        if (in_array($buildprimarykeytotest, $locales))
6975
-            return strtolower($countrycode) . '_' . strtoupper($countrycode);
7310
+        if (in_array($buildprimarykeytotest, $locales)) {
7311
+                    return strtolower($countrycode) . '_' . strtoupper($countrycode);
7312
+        }
6976 7313
 
6977 7314
         foreach ($locales as $locale) {
6978 7315
             $locale_language = locale_get_primary_language($locale);
@@ -7026,18 +7363,21 @@  discard block
 block discarded – undo
7026 7363
 
7027 7364
                 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
7028 7365
                     if (count($values) == 6) {       // new declaration with permissions:  $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
7029
-                        if ($values[0] != $type)
7030
-                            continue;
7366
+                        if ($values[0] != $type) {
7367
+                                                    continue;
7368
+                        }
7031 7369
 
7032 7370
                         if (verifCond($values[4])) {
7033
-                            if ($values[3])
7034
-                                Globals::$langs->load($values[3]);
7371
+                            if ($values[3]) {
7372
+                                                            Globals::$langs->load($values[3]);
7373
+                            }
7035 7374
                             if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
7036 7375
                                 $substitutionarray = array();
7037 7376
                                 complete_substitutions_array($substitutionarray, Globals::$langs, $object, array('needforkey' => $values[2]));
7038 7377
                                 $label = make_substitutions($reg[1], $substitutionarray);
7039
-                            } else
7040
-                                $label = Globals::$langs->trans($values[2]);
7378
+                            } else {
7379
+                                                            $label = Globals::$langs->trans($values[2]);
7380
+                            }
7041 7381
 
7042 7382
                             //$head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
7043 7383
                             $head[$h][0] = BASE_URI . preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
@@ -7045,30 +7385,32 @@  discard block
 block discarded – undo
7045 7385
                             $head[$h][2] = str_replace('+', '', $values[1]);
7046 7386
                             $h++;
7047 7387
                         }
7048
-                    }
7049
-                    else if (count($values) == 5) {       // deprecated
7388
+                    } else if (count($values) == 5) {       // deprecated
7050 7389
                         DolUtils::dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
7051 7390
 
7052
-                        if ($values[0] != $type)
7053
-                            continue;
7054
-                        if ($values[3])
7055
-                            Globals::$langs->load($values[3]);
7391
+                        if ($values[0] != $type) {
7392
+                                                    continue;
7393
+                        }
7394
+                        if ($values[3]) {
7395
+                                                    Globals::$langs->load($values[3]);
7396
+                        }
7056 7397
                         if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
7057 7398
                             $substitutionarray = array();
7058 7399
                             complete_substitutions_array($substitutionarray, Globals::$langs, $object, array('needforkey' => $values[2]));
7059 7400
                             $label = make_substitutions($reg[1], $substitutionarray);
7060
-                        } else
7061
-                            $label = Globals::$langs->trans($values[2]);
7401
+                        } else {
7402
+                                                    $label = Globals::$langs->trans($values[2]);
7403
+                        }
7062 7404
 
7063 7405
                         $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
7064 7406
                         $head[$h][1] = $label;
7065 7407
                         $head[$h][2] = str_replace('+', '', $values[1]);
7066 7408
                         $h++;
7067 7409
                     }
7068
-                }
7069
-                else if ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
7070
-                    if ($values[0] != $type)
7071
-                        continue;
7410
+                } else if ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
7411
+                    if ($values[0] != $type) {
7412
+                                            continue;
7413
+                    }
7072 7414
                     $tabname = str_replace('-', '', $values[1]);
7073 7415
                     foreach ($head as $key => $val) {
7074 7416
                         $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
@@ -7110,10 +7452,11 @@  discard block
 block discarded – undo
7110 7452
         // global $action;
7111 7453
         // global $micro_start_time;
7112 7454
 
7113
-        if ($zone == 'private')
7114
-            print "\n" . '<!-- Common footer for private page -->' . "\n";
7115
-        else
7116
-            print "\n" . '<!-- Common footer for public page -->' . "\n";
7455
+        if ($zone == 'private') {
7456
+                    print "\n" . '<!-- Common footer for private page -->' . "\n";
7457
+        } else {
7458
+                    print "\n" . '<!-- Common footer for public page -->' . "\n";
7459
+        }
7117 7460
 
7118 7461
 // A div to store page_y POST parameter so we can read it using javascript
7119 7462
         print "\n<!-- A div to store page_y POST paramater -->\n";
@@ -7122,8 +7465,9 @@  discard block
 block discarded – undo
7122 7465
         $parameters = array();
7123 7466
         $reshook = Globals::$hookManager->executeHooks('printCommonFooter', $parameters);    // Note that $action and $object may have been modified by some hooks
7124 7467
         if (empty($reshook)) {
7125
-            if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER))
7126
-                print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7468
+            if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER)) {
7469
+                            print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7470
+            }
7127 7471
 
7128 7472
             print "\n";
7129 7473
             if (!empty(Globals::$conf->use_javascript_ajax)) {
@@ -7146,8 +7490,9 @@  discard block
 block discarded – undo
7146 7490
                     print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
7147 7491
                     $relativepathstring = $_SERVER["PHP_SELF"];
7148 7492
                     // Clean $relativepathstring
7149
-                    if (constant('DOL_BASE_URI'))
7150
-                        $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7493
+                    if (constant('DOL_BASE_URI')) {
7494
+                                            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7495
+                    }
7151 7496
                     $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
7152 7497
                     $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
7153 7498
                     $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
@@ -7158,14 +7503,17 @@  discard block
 block discarded – undo
7158 7503
                                 $tmpqueryarraytohave = explode('&', $defkey);
7159 7504
                                 $foundintru = 0;
7160 7505
                                 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
7161
-                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
7162
-                                        $foundintru = 1;
7506
+                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
7507
+                                                                            $foundintru = 1;
7508
+                                    }
7163 7509
                                 }
7164
-                                if (!$foundintru)
7165
-                                    $qualified = 1;
7510
+                                if (!$foundintru) {
7511
+                                                                    $qualified = 1;
7512
+                                }
7166 7513
                                 //var_dump($defkey.'-'.$qualified);
7167
-                            } else
7168
-                                $qualified = 1;
7514
+                            } else {
7515
+                                                            $qualified = 1;
7516
+                            }
7169 7517
 
7170 7518
                             if ($qualified) {
7171 7519
                                 foreach ($defval as $paramkey => $paramval) {
@@ -7184,14 +7532,17 @@  discard block
 block discarded – undo
7184 7532
                                 $tmpqueryarraytohave = explode('&', $defkey);
7185 7533
                                 $foundintru = 0;
7186 7534
                                 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
7187
-                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
7188
-                                        $foundintru = 1;
7535
+                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
7536
+                                                                            $foundintru = 1;
7537
+                                    }
7189 7538
                                 }
7190
-                                if (!$foundintru)
7191
-                                    $qualified = 1;
7539
+                                if (!$foundintru) {
7540
+                                                                    $qualified = 1;
7541
+                                }
7192 7542
                                 //var_dump($defkey.'-'.$qualified);
7193
-                            } else
7194
-                                $qualified = 1;
7543
+                            } else {
7544
+                                                            $qualified = 1;
7545
+                            }
7195 7546
 
7196 7547
                             if ($qualified) {
7197 7548
                                 foreach ($defval as $paramkey => $paramval) {
@@ -7230,8 +7581,9 @@  discard block
 block discarded – undo
7230 7581
                     print "\n";
7231 7582
                     print "/* JS CODE TO ENABLE to add memory info */\n";
7232 7583
                     print 'window.console && console.log("';
7233
-                    if (!empty(Globals::$conf->global->MEMCACHED_SERVER))
7234
-                        print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7584
+                    if (!empty(Globals::$conf->global->MEMCACHED_SERVER)) {
7585
+                                            print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7586
+                    }
7235 7587
                     print 'MAIN_OPTIMIZE_SPEED=' . (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7236 7588
                     if (!empty($micro_start_time)) {   // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in// global variable.
7237 7589
                         $micro_end_time = microtime(true);
@@ -7361,8 +7713,9 @@  discard block
 block discarded – undo
7361 7713
 
7362 7714
         $crits = explode(' ', $value);
7363 7715
         $res = '';
7364
-        if (!is_array($fields))
7365
-            $fields = array($fields);
7716
+        if (!is_array($fields)) {
7717
+                    $fields = array($fields);
7718
+        }
7366 7719
 
7367 7720
         $nboffields = count($fields);
7368 7721
         $end2 = count($crits);
@@ -7425,8 +7778,9 @@  discard block
 block discarded – undo
7425 7778
                     $tmpcrits = explode('|', $crit);
7426 7779
                     $i3 = 0;
7427 7780
                     foreach ($tmpcrits as $tmpcrit) {
7428
-                        if (empty($tmpcrit))
7429
-                            continue;
7781
+                        if (empty($tmpcrit)) {
7782
+                                                    continue;
7783
+                        }
7430 7784
 
7431 7785
                         $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
7432 7786
 
@@ -7462,8 +7816,9 @@  discard block
 block discarded – undo
7462 7816
                 }
7463 7817
                 $i++;
7464 7818
             }
7465
-            if ($newres)
7466
-                $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7819
+            if ($newres) {
7820
+                            $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7821
+            }
7467 7822
             $j++;
7468 7823
         }
7469 7824
         $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
@@ -7503,29 +7858,37 @@  discard block
 block discarded – undo
7503 7858
     static function getImageFileNameForSize($file, $extName, $extImgTarget = '')
7504 7859
     {
7505 7860
         $dirName = dirname($file);
7506
-        if ($dirName == '.')
7507
-            $dirName = '';
7861
+        if ($dirName == '.') {
7862
+                    $dirName = '';
7863
+        }
7508 7864
 
7509 7865
         $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i', '', $file); // We remove extension, whatever is its case
7510 7866
         $fileName = basename($fileName);
7511 7867
 
7512
-        if (empty($extImgTarget))
7513
-            $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
7514
-        if (empty($extImgTarget))
7515
-            $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
7516
-        if (empty($extImgTarget))
7517
-            $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
7518
-        if (empty($extImgTarget))
7519
-            $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
7520
-        if (empty($extImgTarget))
7521
-            $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
7522
-
7523
-        if (!$extImgTarget)
7524
-            return $file;
7868
+        if (empty($extImgTarget)) {
7869
+                    $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
7870
+        }
7871
+        if (empty($extImgTarget)) {
7872
+                    $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
7873
+        }
7874
+        if (empty($extImgTarget)) {
7875
+                    $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
7876
+        }
7877
+        if (empty($extImgTarget)) {
7878
+                    $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
7879
+        }
7880
+        if (empty($extImgTarget)) {
7881
+                    $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
7882
+        }
7883
+
7884
+        if (!$extImgTarget) {
7885
+                    return $file;
7886
+        }
7525 7887
 
7526 7888
         $subdir = '';
7527
-        if ($extName)
7528
-            $subdir = 'thumbs/';
7889
+        if ($extName) {
7890
+                    $subdir = 'thumbs/';
7891
+        }
7529 7892
 
7530 7893
         return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
7531 7894
     }
@@ -7543,8 +7906,9 @@  discard block
 block discarded – undo
7543 7906
     {
7544 7907
         // global Globals::$conf, Globals::$langs;
7545 7908
 
7546
-        if (empty(Globals::$conf->use_javascript_ajax))
7547
-            return '';
7909
+        if (empty(Globals::$conf->use_javascript_ajax)) {
7910
+                    return '';
7911
+        }
7548 7912
 
7549 7913
         $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'svg+xml');
7550 7914
 //$mime_preview[]='vnd.oasis.opendocument.presentation';
@@ -7552,17 +7916,19 @@  discard block
 block discarded – undo
7552 7916
         $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
7553 7917
 
7554 7918
         if ($alldata == 1) {
7555
-            if ($num_mime !== false)
7556
-                return array('target' => '_blank', 'css' => 'documentpreview', 'url' => DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : ''), 'mime' => dol_mimetype($relativepath),);
7557
-            else
7558
-                return array();
7919
+            if ($num_mime !== false) {
7920
+                            return array('target' => '_blank', 'css' => 'documentpreview', 'url' => DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : ''), 'mime' => dol_mimetype($relativepath),);
7921
+            } else {
7922
+                            return array();
7923
+            }
7559 7924
         }
7560 7925
 
7561 7926
 // old behavior
7562
-        if ($num_mime !== false)
7563
-            return 'javascript:document_preview(\'' . dol_escape_js(DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : '')) . '\', \'' . dol_mimetype($relativepath) . '\', \'' . dol_escape_js(Globals::$langs->trans('Preview')) . '\')';
7564
-        else
7565
-            return '';
7927
+        if ($num_mime !== false) {
7928
+                    return 'javascript:document_preview(\'' . dol_escape_js(DOL_BASE_URI . '/document.php?modulepart=' . $modulepart . '&attachment=0&file=' . urlencode($relativepath) . ($param ? '&' . $param : '')) . '\', \'' . dol_mimetype($relativepath) . '\', \'' . dol_escape_js(Globals::$langs->trans('Preview')) . '\')';
7929
+        } else {
7930
+                    return '';
7931
+        }
7566 7932
     }
7567 7933
 
7568 7934
     /**
@@ -7580,8 +7946,9 @@  discard block
 block discarded – undo
7580 7946
 				    jQuery("#' . $htmlname . '").click(function() { jQuery(this).select(); } );
7581 7947
 				});
7582 7948
 		    </script>';
7583
-        if ($addlink)
7584
-            $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7949
+        if ($addlink) {
7950
+                    $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7951
+        }
7585 7952
         return $out;
7586 7953
     }
7587 7954
 
@@ -7963,8 +8330,9 @@  discard block
 block discarded – undo
7963 8330
         if (!isset($dictvalues[$tablename])) {
7964 8331
             $dictvalues[$tablename] = array();
7965 8332
             $sql = 'SELECT * FROM ' . $tablename . ' WHERE 1';
7966
-            if ($checkentity)
7967
-                $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
8333
+            if ($checkentity) {
8334
+                            $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
8335
+            }
7968 8336
 
7969 8337
             $resql = $db->query($sql);
7970 8338
             if ($resql) {
@@ -7976,11 +8344,14 @@  discard block
 block discarded – undo
7976 8344
             }
7977 8345
         }
7978 8346
 
7979
-        if (!empty($dictvalues[$tablename][$id]))
7980
-            return $dictvalues[$tablename][$id]->{$field}; // Found
8347
+        if (!empty($dictvalues[$tablename][$id])) {
8348
+                    return $dictvalues[$tablename][$id]->{$field};
8349
+        }
8350
+        // Found
7981 8351
         else { // Not found
7982
-            if ($id > 0)
7983
-                return $id;
8352
+            if ($id > 0) {
8353
+                            return $id;
8354
+            }
7984 8355
             return '';
7985 8356
         }
7986 8357
     }
@@ -8010,8 +8381,9 @@  discard block
 block discarded – undo
8010 8381
                 $b = hexdec($hexb);
8011 8382
             }
8012 8383
             $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0;    // HSL algorithm
8013
-            if ($bright > 0.6)
8014
-                $res = 1;
8384
+            if ($bright > 0.6) {
8385
+                            $res = 1;
8386
+            }
8015 8387
         }
8016 8388
         return $res;
8017 8389
     }
@@ -8029,8 +8401,10 @@  discard block
 block discarded – undo
8029 8401
         // global Globals::$conf;
8030 8402
 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
8031 8403
 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
8032
-        if (empty($menuentry['enabled']))
8033
-            return 0; // Entry disabled by condition
8404
+        if (empty($menuentry['enabled'])) {
8405
+                    return 0;
8406
+        }
8407
+        // Entry disabled by condition
8034 8408
         if ($type_user && $menuentry['module']) {
8035 8409
             $tmploops = explode('|', $menuentry['module']);
8036 8410
             $found = 0;
@@ -8040,15 +8414,23 @@  discard block
 block discarded – undo
8040 8414
                     break;
8041 8415
                 }
8042 8416
             }
8043
-            if (!$found)
8044
-                return 0; // Entry is for menus all excluded to external users
8045
-        }
8046
-        if (!$menuentry['perms'] && $type_user)
8047
-            return 0;            // No permissions and user is external
8048
-        if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED))
8049
-            return 0; // No permissions and option to hide when not allowed, even for internal user, is on
8050
-        if (!$menuentry['perms'])
8051
-            return 2;               // No permissions and user is external
8417
+            if (!$found) {
8418
+                            return 0;
8419
+            }
8420
+            // Entry is for menus all excluded to external users
8421
+        }
8422
+        if (!$menuentry['perms'] && $type_user) {
8423
+                    return 0;
8424
+        }
8425
+        // No permissions and user is external
8426
+        if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
8427
+                    return 0;
8428
+        }
8429
+        // No permissions and option to hide when not allowed, even for internal user, is on
8430
+        if (!$menuentry['perms']) {
8431
+                    return 2;
8432
+        }
8433
+        // No permissions and user is external
8052 8434
         return 1;
8053 8435
     }
8054 8436
 
Please login to merge, or discard this patch.