Passed
Push — master ( 4e88da...5feb35 )
by Alxarafe
26:36
created
Helpers/DolUtils.php 3 patches
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
      */
259 259
     static function dol_shutdown()
260 260
     {
261
-       // global Globals::$conf, $user, Globals::$langs, $db;
261
+        // global Globals::$conf, $user, Globals::$langs, $db;
262 262
         $disconnectdone = false;
263 263
         $depth = 0;
264 264
         if (is_object($db) && !empty($db->connected)) {
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
      */
306 306
     static function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $options = null, $noreplace = 0)
307 307
     {
308
-       // global $mysoc, $user, Globals::$conf;
308
+        // global $mysoc, $user, Globals::$conf;
309 309
 
310 310
         if (empty($paramname))
311 311
             return 'BadFirstParameterForDolUtils::GETPOST';
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
             elseif (!isset($_GET['sortfield'])) { // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
365 365
                 if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
366 366
                     // Search default value from $object->field
367
-                   // global $object;
367
+                    // global $object;
368 368
                     if (is_object($object) && isset($object->fields[$paramname]['default'])) {
369 369
                         $out = $object->fields[$paramname]['default'];
370 370
                     }
@@ -707,7 +707,7 @@  discard block
 block discarded – undo
707 707
      */
708 708
     static function dol_include_once($relpath, $classname = '')
709 709
     {
710
-       // global Globals::$conf, Globals::$langs, $user, $mysoc;   // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
710
+        // global Globals::$conf, Globals::$langs, $user, $mysoc;   // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
711 711
 
712 712
         $fullpath = dol_buildpath($relpath);
713 713
 
@@ -735,7 +735,7 @@  discard block
 block discarded – undo
735 735
      */
736 736
     static function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
737 737
     {
738
-       // global Globals::$conf;
738
+        // global Globals::$conf;
739 739
 
740 740
         $path = preg_replace('/^\//', '', $path);
741 741
 
@@ -777,7 +777,7 @@  discard block
 block discarded – undo
777 777
             foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
778 778
                 if ($key == 'main') {
779 779
                     if ($type == 3) {
780
-                       // global $dolibarr_main_url_root;
780
+                        // global $dolibarr_main_url_root;
781 781
                         // Define $urlwithroot
782 782
 
783 783
                         // $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
@@ -801,7 +801,7 @@  discard block
 block discarded – undo
801 801
                             $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
802 802
                         }
803 803
                         if ($type == 3) {
804
-                           // global $dolibarr_main_url_root;
804
+                            // global $dolibarr_main_url_root;
805 805
                             // Define $urlwithroot
806 806
                             $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
807 807
                             $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
@@ -1071,7 +1071,7 @@  discard block
 block discarded – undo
1071 1071
      */
1072 1072
     static function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '')
1073 1073
     {
1074
-       // global Globals::$conf, $user;
1074
+        // global Globals::$conf, $user;
1075 1075
 // If syslog module enabled
1076 1076
         if (empty(Globals::$conf->syslog->enabled))
1077 1077
             return;
@@ -1177,7 +1177,7 @@  discard block
 block discarded – undo
1177 1177
      */
1178 1178
     static function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '')
1179 1179
     {
1180
-       // global Globals::$conf, Globals::$langs, $hookmanager;
1180
+        // global Globals::$conf, Globals::$langs, $hookmanager;
1181 1181
 
1182 1182
         $out = "\n" . '<div class="tabs" data-role="controlgroup" data-type="horizontal">' . "\n";
1183 1183
 
@@ -1360,7 +1360,7 @@  discard block
 block discarded – undo
1360 1360
      */
1361 1361
     static function dol_banner_tab($object, $paramid, $morehtml = '', $shownav = 1, $fieldid = 'rowid', $fieldref = 'ref', $morehtmlref = '', $moreparam = '', $nodbprefix = 0, $morehtmlleft = '', $morehtmlstatus = '', $onlybanner = 0, $morehtmlright = '')
1362 1362
     {
1363
-       // global Globals::$conf, $form, $user, Globals::$langs;
1363
+        // global Globals::$conf, $form, $user, Globals::$langs;
1364 1364
 
1365 1365
         $error = 0;
1366 1366
 
@@ -1639,7 +1639,7 @@  discard block
 block discarded – undo
1639 1639
      */
1640 1640
     static function fieldLabel($langkey, $fieldkey, $fieldrequired = 0)
1641 1641
     {
1642
-       // global Globals::$conf, Globals::$langs;
1642
+        // global Globals::$conf, Globals::$langs;
1643 1643
         $ret = '';
1644 1644
         if ($fieldrequired)
1645 1645
             $ret .= '<span class="fieldrequired">';
@@ -1662,7 +1662,7 @@  discard block
 block discarded – undo
1662 1662
      */
1663 1663
     static function dol_bc($var, $moreclass = '')
1664 1664
     {
1665
-       // global $bc;
1665
+        // global $bc;
1666 1666
         $ret = ' ' . $bc[$var];
1667 1667
         if ($moreclass)
1668 1668
             $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
@@ -1682,7 +1682,7 @@  discard block
 block discarded – undo
1682 1682
      */
1683 1683
     static function dol_format_address($object, $withcountry = 0, $sep = "\n", $outputlangs = '', $mode = 0)
1684 1684
     {
1685
-       // global Globals::$conf, Globals::$langs;
1685
+        // global Globals::$conf, Globals::$langs;
1686 1686
 
1687 1687
         $ret = '';
1688 1688
         $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR');    // See also MAIN_FORCE_STATE_INTO_ADDRESS
@@ -1773,7 +1773,7 @@  discard block
 block discarded – undo
1773 1773
      */
1774 1774
     static function dol_print_date($time, $format = '', $tzoutput = 'tzserver', $outputlangs = '', $encodetooutput = false)
1775 1775
     {
1776
-       // global Globals::$conf, Globals::$langs;
1776
+        // global Globals::$conf, Globals::$langs;
1777 1777
 // Clean parameters
1778 1778
         $to_gmt = false;
1779 1779
         $offsettz = $offsetdst = 0;
@@ -1984,7 +1984,7 @@  discard block
 block discarded – undo
1984 1984
      */
1985 1985
     static function dol_getdate($timestamp, $fast = false)
1986 1986
     {
1987
-       // global Globals::$conf;
1987
+        // global Globals::$conf;
1988 1988
 
1989 1989
         $usealternatemethod = false;
1990 1990
         if ($timestamp <= 0)
@@ -2022,7 +2022,7 @@  discard block
 block discarded – undo
2022 2022
      */
2023 2023
     static function dol_mktime($hour, $minute, $second, $month, $day, $year, $gm = false, $check = 1)
2024 2024
     {
2025
-       // global Globals::$conf;
2025
+        // global Globals::$conf;
2026 2026
 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
2027 2027
 // Clean parameters
2028 2028
         if ($hour == -1 || empty($hour))
@@ -2134,7 +2134,7 @@  discard block
 block discarded – undo
2134 2134
      */
2135 2135
     static function dol_print_size($size, $shortvalue = 0, $shortunit = 0)
2136 2136
     {
2137
-       // global Globals::$conf, Globals::$langs;
2137
+        // global Globals::$conf, Globals::$langs;
2138 2138
         $level = 1024;
2139 2139
 
2140 2140
         if (!empty(Globals::$conf->dol_optimize_smallscreen))
@@ -2171,7 +2171,7 @@  discard block
 block discarded – undo
2171 2171
      */
2172 2172
     static function dol_print_url($url, $target = '_blank', $max = 32, $withpicto = 0)
2173 2173
     {
2174
-       // global Globals::$langs;
2174
+        // global Globals::$langs;
2175 2175
 
2176 2176
         if (empty($url))
2177 2177
             return '';
@@ -2205,7 +2205,7 @@  discard block
 block discarded – undo
2205 2205
      */
2206 2206
     static function dol_print_email($email, $cid = 0, $socid = 0, $addlink = 0, $max = 64, $showinvalid = 1, $withpicto = 0)
2207 2207
     {
2208
-       // global Globals::$conf, $user, Globals::$langs, $hookmanager;
2208
+        // global Globals::$conf, $user, Globals::$langs, $hookmanager;
2209 2209
 
2210 2210
         $newemail = $email;
2211 2211
 
@@ -2262,7 +2262,7 @@  discard block
 block discarded – undo
2262 2262
      */
2263 2263
     static function dol_print_socialnetworks($value, $cid, $socid, $type)
2264 2264
     {
2265
-       // global Globals::$conf, $user, Globals::$langs;
2265
+        // global Globals::$conf, $user, Globals::$langs;
2266 2266
 
2267 2267
         $newskype = $value;
2268 2268
 
@@ -2317,7 +2317,7 @@  discard block
 block discarded – undo
2317 2317
      */
2318 2318
     static function dol_print_phone($phone, $countrycode = '', $cid = 0, $socid = 0, $addlink = '', $separ = "&nbsp;", $withpicto = '', $titlealt = '', $adddivfloat = 0)
2319 2319
     {
2320
-       // global Globals::$conf, $user, Globals::$langs, $mysoc, $hookmanager;
2320
+        // global Globals::$conf, $user, Globals::$langs, $mysoc, $hookmanager;
2321 2321
 // Clean phone parameter
2322 2322
         $phone = preg_replace("/[\s.-]/", "", trim($phone));
2323 2323
         if (empty($phone)) {
@@ -2581,7 +2581,7 @@  discard block
 block discarded – undo
2581 2581
      */
2582 2582
     static function dol_print_ip($ip, $mode = 0)
2583 2583
     {
2584
-       // global Globals::$conf, Globals::$langs;
2584
+        // global Globals::$conf, Globals::$langs;
2585 2585
 
2586 2586
         $ret = '';
2587 2587
 
@@ -2626,7 +2626,7 @@  discard block
 block discarded – undo
2626 2626
      */
2627 2627
     static function dolGetCountryCodeFromIp($ip)
2628 2628
     {
2629
-       // global Globals::$conf;
2629
+        // global Globals::$conf;
2630 2630
 
2631 2631
         $countrycode = '';
2632 2632
 
@@ -2653,7 +2653,7 @@  discard block
 block discarded – undo
2653 2653
      */
2654 2654
     static function dol_user_country()
2655 2655
     {
2656
-       // global Globals::$conf, Globals::$langs, $user;
2656
+        // global Globals::$conf, Globals::$langs, $user;
2657 2657
 //$ret=$user->xxx;
2658 2658
         $ret = '';
2659 2659
         if (!empty(Globals::$conf->geoipmaxmind->enabled)) {
@@ -2683,7 +2683,7 @@  discard block
 block discarded – undo
2683 2683
      */
2684 2684
     static function dol_print_address($address, $htmlid, $mode, $id, $noprint = 0, $charfornl = '')
2685 2685
     {
2686
-       // global Globals::$conf, $user, Globals::$langs, $hookmanager;
2686
+        // global Globals::$conf, $user, Globals::$langs, $hookmanager;
2687 2687
 
2688 2688
         $out = '';
2689 2689
 
@@ -2815,7 +2815,7 @@  discard block
 block discarded – undo
2815 2815
      */
2816 2816
     static function dol_substr($string, $start, $length, $stringencoding = '', $trunconbytes = 0)
2817 2817
     {
2818
-       // global Globals::$langs;
2818
+        // global Globals::$langs;
2819 2819
 
2820 2820
         if (empty($stringencoding))
2821 2821
             $stringencoding = Globals::$langs->charset_output;
@@ -2852,7 +2852,7 @@  discard block
 block discarded – undo
2852 2852
      */
2853 2853
     static function dol_trunc($string, $size = 40, $trunc = 'right', $stringencoding = 'UTF-8', $nodot = 0, $display = 0)
2854 2854
     {
2855
-       // global Globals::$conf;
2855
+        // global Globals::$conf;
2856 2856
 
2857 2857
         if ($size == 0 || !empty(Globals::$conf->global->MAIN_DISABLE_TRUNC))
2858 2858
             return $string;
@@ -2918,7 +2918,7 @@  discard block
 block discarded – undo
2918 2918
      */
2919 2919
     static function img_picto($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0, $alt = '', $morecss = '')
2920 2920
     {
2921
-       // global Globals::$conf, Globals::$langs;
2921
+        // global Globals::$conf, Globals::$langs;
2922 2922
 // We forge fullpathpicto for image to $path/img/$picto. By default, we take DOL_BASE_URI/theme/$conf->theme/img/$picto
2923 2923
 //$url = DOL_BASE_URI;
2924 2924
         $url = DOL_BASE_URI;
@@ -3103,7 +3103,7 @@  discard block
 block discarded – undo
3103 3103
      */
3104 3104
     static function img_weather($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
3105 3105
     {
3106
-       // global Globals::$conf;
3106
+        // global Globals::$conf;
3107 3107
 
3108 3108
         if (!preg_match('/(\.png|\.gif)$/i', $picto))
3109 3109
             $picto .= '.png';
@@ -3126,7 +3126,7 @@  discard block
 block discarded – undo
3126 3126
      */
3127 3127
     static function img_picto_common($titlealt, $picto, $moreatt = '', $pictoisfullpath = 0)
3128 3128
     {
3129
-       // global Globals::$conf;
3129
+        // global Globals::$conf;
3130 3130
 
3131 3131
         if (!preg_match('/(\.png|\.gif)$/i', $picto))
3132 3132
             $picto .= '.png';
@@ -3157,7 +3157,7 @@  discard block
 block discarded – undo
3157 3157
      */
3158 3158
     static function img_action($titlealt, $numaction)
3159 3159
     {
3160
-       // global Globals::$conf, Globals::$langs;
3160
+        // global Globals::$conf, Globals::$langs;
3161 3161
 
3162 3162
         if (empty($titlealt) || $titlealt == 'default') {
3163 3163
             if ($numaction == '-1' || $numaction == 'ST_NO') {
@@ -3195,7 +3195,7 @@  discard block
 block discarded – undo
3195 3195
      */
3196 3196
     static function img_pdf($titlealt = 'default', $size = 3)
3197 3197
     {
3198
-       // global Globals::$conf, Globals::$langs;
3198
+        // global Globals::$conf, Globals::$langs;
3199 3199
 
3200 3200
         if ($titlealt == 'default')
3201 3201
             $titlealt = Globals::$langs->trans('Show');
@@ -3212,7 +3212,7 @@  discard block
 block discarded – undo
3212 3212
      */
3213 3213
     static function img_edit_add($titlealt = 'default', $other = '')
3214 3214
     {
3215
-       // global Globals::$conf, Globals::$langs;
3215
+        // global Globals::$conf, Globals::$langs;
3216 3216
 
3217 3217
         if ($titlealt == 'default')
3218 3218
             $titlealt = Globals::$langs->trans('Add');
@@ -3229,7 +3229,7 @@  discard block
 block discarded – undo
3229 3229
      */
3230 3230
     static function img_edit_remove($titlealt = 'default', $other = '')
3231 3231
     {
3232
-       // global Globals::$conf, Globals::$langs;
3232
+        // global Globals::$conf, Globals::$langs;
3233 3233
 
3234 3234
         if ($titlealt == 'default')
3235 3235
             $titlealt = Globals::$langs->trans('Remove');
@@ -3247,7 +3247,7 @@  discard block
 block discarded – undo
3247 3247
      */
3248 3248
     static function img_edit($titlealt = 'default', $float = 0, $other = 'class="pictoedit"')
3249 3249
     {
3250
-       // global Globals::$conf, Globals::$langs;
3250
+        // global Globals::$conf, Globals::$langs;
3251 3251
 
3252 3252
         if ($titlealt == 'default')
3253 3253
             $titlealt = Globals::$langs->trans('Modify');
@@ -3265,7 +3265,7 @@  discard block
 block discarded – undo
3265 3265
      */
3266 3266
     static function img_view($titlealt = 'default', $float = 0, $other = '')
3267 3267
     {
3268
-       // global Globals::$conf, Globals::$langs;
3268
+        // global Globals::$conf, Globals::$langs;
3269 3269
 
3270 3270
         if ($titlealt == 'default')
3271 3271
             $titlealt = Globals::$langs->trans('View');
@@ -3284,7 +3284,7 @@  discard block
 block discarded – undo
3284 3284
      */
3285 3285
     static function img_delete($titlealt = 'default', $other = 'class="pictodelete"')
3286 3286
     {
3287
-       // global Globals::$conf, Globals::$langs;
3287
+        // global Globals::$conf, Globals::$langs;
3288 3288
 
3289 3289
         if ($titlealt == 'default')
3290 3290
             $titlealt = Globals::$langs->trans('Delete');
@@ -3302,7 +3302,7 @@  discard block
 block discarded – undo
3302 3302
      */
3303 3303
     static function img_printer($titlealt = "default", $other = '')
3304 3304
     {
3305
-       // global Globals::$conf, Globals::$langs;
3305
+        // global Globals::$conf, Globals::$langs;
3306 3306
         if ($titlealt == "default")
3307 3307
             $titlealt = Globals::$langs->trans("Print");
3308 3308
         return img_picto($titlealt, 'printer.png', $other);
@@ -3317,7 +3317,7 @@  discard block
 block discarded – undo
3317 3317
      */
3318 3318
     static function img_split($titlealt = 'default', $other = 'class="pictosplit"')
3319 3319
     {
3320
-       // global Globals::$conf, Globals::$langs;
3320
+        // global Globals::$conf, Globals::$langs;
3321 3321
 
3322 3322
         if ($titlealt == 'default')
3323 3323
             $titlealt = Globals::$langs->trans('Split');
@@ -3334,7 +3334,7 @@  discard block
 block discarded – undo
3334 3334
      */
3335 3335
     static function img_help($usehelpcursor = 1, $usealttitle = 1)
3336 3336
     {
3337
-       // global Globals::$conf, Globals::$langs;
3337
+        // global Globals::$conf, Globals::$langs;
3338 3338
 
3339 3339
         if ($usealttitle) {
3340 3340
             if (is_string($usealttitle))
@@ -3354,7 +3354,7 @@  discard block
 block discarded – undo
3354 3354
      */
3355 3355
     static function img_info($titlealt = 'default')
3356 3356
     {
3357
-       // global Globals::$conf, Globals::$langs;
3357
+        // global Globals::$conf, Globals::$langs;
3358 3358
 
3359 3359
         if ($titlealt == 'default')
3360 3360
             $titlealt = Globals::$langs->trans('Informations');
@@ -3371,7 +3371,7 @@  discard block
 block discarded – undo
3371 3371
      */
3372 3372
     static function img_warning($titlealt = 'default', $moreatt = '')
3373 3373
     {
3374
-       // global Globals::$conf, Globals::$langs;
3374
+        // global Globals::$conf, Globals::$langs;
3375 3375
 
3376 3376
         if ($titlealt == 'default')
3377 3377
             $titlealt = Globals::$langs->trans('Warning');
@@ -3388,7 +3388,7 @@  discard block
 block discarded – undo
3388 3388
      */
3389 3389
     static function img_error($titlealt = 'default')
3390 3390
     {
3391
-       // global Globals::$conf, Globals::$langs;
3391
+        // global Globals::$conf, Globals::$langs;
3392 3392
 
3393 3393
         if ($titlealt == 'default')
3394 3394
             $titlealt = Globals::$langs->trans('Error');
@@ -3405,7 +3405,7 @@  discard block
 block discarded – undo
3405 3405
      */
3406 3406
     static function img_next($titlealt = 'default', $moreatt = '')
3407 3407
     {
3408
-       // global Globals::$conf, Globals::$langs;
3408
+        // global Globals::$conf, Globals::$langs;
3409 3409
 
3410 3410
         if ($titlealt == 'default')
3411 3411
             $titlealt = Globals::$langs->trans('Next');
@@ -3423,7 +3423,7 @@  discard block
 block discarded – undo
3423 3423
      */
3424 3424
     static function img_previous($titlealt = 'default', $moreatt = '')
3425 3425
     {
3426
-       // global Globals::$conf, Globals::$langs;
3426
+        // global Globals::$conf, Globals::$langs;
3427 3427
 
3428 3428
         if ($titlealt == 'default')
3429 3429
             $titlealt = Globals::$langs->trans('Previous');
@@ -3442,7 +3442,7 @@  discard block
 block discarded – undo
3442 3442
      */
3443 3443
     static function img_down($titlealt = 'default', $selected = 0, $moreclass = '')
3444 3444
     {
3445
-       // global Globals::$conf, Globals::$langs;
3445
+        // global Globals::$conf, Globals::$langs;
3446 3446
 
3447 3447
         if ($titlealt == 'default')
3448 3448
             $titlealt = Globals::$langs->trans('Down');
@@ -3460,7 +3460,7 @@  discard block
 block discarded – undo
3460 3460
      */
3461 3461
     static function img_up($titlealt = 'default', $selected = 0, $moreclass = '')
3462 3462
     {
3463
-       // global Globals::$conf, Globals::$langs;
3463
+        // global Globals::$conf, Globals::$langs;
3464 3464
 
3465 3465
         if ($titlealt == 'default')
3466 3466
             $titlealt = Globals::$langs->trans('Up');
@@ -3478,7 +3478,7 @@  discard block
 block discarded – undo
3478 3478
      */
3479 3479
     static function img_left($titlealt = 'default', $selected = 0, $moreatt = '')
3480 3480
     {
3481
-       // global Globals::$conf, Globals::$langs;
3481
+        // global Globals::$conf, Globals::$langs;
3482 3482
 
3483 3483
         if ($titlealt == 'default')
3484 3484
             $titlealt = Globals::$langs->trans('Left');
@@ -3496,7 +3496,7 @@  discard block
 block discarded – undo
3496 3496
      */
3497 3497
     static function img_right($titlealt = 'default', $selected = 0, $moreatt = '')
3498 3498
     {
3499
-       // global Globals::$conf, Globals::$langs;
3499
+        // global Globals::$conf, Globals::$langs;
3500 3500
 
3501 3501
         if ($titlealt == 'default')
3502 3502
             $titlealt = Globals::$langs->trans('Right');
@@ -3513,7 +3513,7 @@  discard block
 block discarded – undo
3513 3513
      */
3514 3514
     static function img_allow($allow, $titlealt = 'default')
3515 3515
     {
3516
-       // global Globals::$conf, Globals::$langs;
3516
+        // global Globals::$conf, Globals::$langs;
3517 3517
 
3518 3518
         if ($titlealt == 'default')
3519 3519
             $titlealt = Globals::$langs->trans('Active');
@@ -3588,7 +3588,7 @@  discard block
 block discarded – undo
3588 3588
     {
3589 3589
         dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
3590 3590
 
3591
-       // global Globals::$conf, Globals::$langs;
3591
+        // global Globals::$conf, Globals::$langs;
3592 3592
 
3593 3593
         if ($titlealt == 'default')
3594 3594
             $titlealt = Globals::$langs->trans('Call');
@@ -3610,7 +3610,7 @@  discard block
 block discarded – undo
3610 3610
      */
3611 3611
     static function img_search($titlealt = 'default', $other = '')
3612 3612
     {
3613
-       // global Globals::$conf, Globals::$langs;
3613
+        // global Globals::$conf, Globals::$langs;
3614 3614
 
3615 3615
         if ($titlealt == 'default')
3616 3616
             $titlealt = Globals::$langs->trans('Search');
@@ -3632,7 +3632,7 @@  discard block
 block discarded – undo
3632 3632
      */
3633 3633
     static function img_searchclear($titlealt = 'default', $other = '')
3634 3634
     {
3635
-       // global Globals::$conf, Globals::$langs;
3635
+        // global Globals::$conf, Globals::$langs;
3636 3636
 
3637 3637
         if ($titlealt == 'default')
3638 3638
             $titlealt = Globals::$langs->trans('Search');
@@ -3657,7 +3657,7 @@  discard block
 block discarded – undo
3657 3657
      */
3658 3658
     static function info_admin($text, $infoonimgalt = 0, $nodiv = 0, $admin = '1', $morecss = '')
3659 3659
     {
3660
-       // global Globals::$conf, Globals::$langs;
3660
+        // global Globals::$conf, Globals::$langs;
3661 3661
 
3662 3662
         if ($infoonimgalt) {
3663 3663
             return img_picto($text, 'info', 'class="hideonsmartphone' . ($morecss ? ' ' . $morecss : '') . '"');
@@ -3680,7 +3680,7 @@  discard block
 block discarded – undo
3680 3680
      */
3681 3681
     static function dol_print_error($db = '', $error = '', $errors = null)
3682 3682
     {
3683
-       // global Globals::$conf, Globals::$langs, $argv;
3683
+        // global Globals::$conf, Globals::$langs, $argv;
3684 3684
         // global $dolibarr_main_prod;
3685 3685
 
3686 3686
         $out = '';
@@ -3799,7 +3799,7 @@  discard block
 block discarded – undo
3799 3799
      */
3800 3800
     static function dol_print_error_email($prefixcode, $errormessage = '', $errormessages = array(), $morecss = 'error', $email = '')
3801 3801
     {
3802
-       // global Globals::$langs, Globals::$conf;
3802
+        // global Globals::$langs, Globals::$conf;
3803 3803
 
3804 3804
         if (empty($email))
3805 3805
             $email = Globals::$conf->global->MAIN_INFO_SOCIETE_MAIL;
@@ -3858,7 +3858,7 @@  discard block
 block discarded – undo
3858 3858
      */
3859 3859
     static function getTitleFieldOfList($name, $thead = 0, $file = "", $field = "", $begin = "", $moreparam = "", $moreattrib = "", $sortfield = "", $sortorder = "", $prefix = "", $disablesortlink = 0, $tooltip = '')
3860 3860
     {
3861
-       // global Globals::$conf, Globals::$langs, $form;
3861
+        // global Globals::$conf, Globals::$langs, $form;
3862 3862
 //print "$name, $file, $field, $begin, $options, $moreattrib, $sortfield, $sortorder<br>\n";
3863 3863
 
3864 3864
         $sortorder = strtoupper($sortorder);
@@ -3997,7 +3997,7 @@  discard block
 block discarded – undo
3997 3997
      */
3998 3998
     static function load_fiche_titre($titre, $morehtmlright = '', $picto = 'title_generic.png', $pictoisfullpath = 0, $id = '', $morecssontable = '', $morehtmlcenter = '')
3999 3999
     {
4000
-       // global Globals::$conf;
4000
+        // global Globals::$conf;
4001 4001
 
4002 4002
         $return = '';
4003 4003
 
@@ -4047,7 +4047,7 @@  discard block
 block discarded – undo
4047 4047
      */
4048 4048
     static function print_barre_liste($titre, $page, $file, $options = '', $sortfield = '', $sortorder = '', $morehtmlcenter = '', $num = -1, $totalnboflines = '', $picto = 'title_generic.png', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limit = -1, $hideselectlimit = 0, $hidenavigation = 0)
4049 4049
     {
4050
-       // global Globals::$conf, Globals::$langs;
4050
+        // global Globals::$conf, Globals::$langs;
4051 4051
 
4052 4052
         $savlimit = $limit;
4053 4053
         $savtotalnboflines = $totalnboflines;
@@ -4160,7 +4160,7 @@  discard block
 block discarded – undo
4160 4160
      */
4161 4161
     static function print_fleche_navigation($page, $file, $options = '', $nextpage = 0, $betweenarrows = '', $afterarrows = '', $limit = -1, $totalnboflines = 0, $hideselectlimit = 0)
4162 4162
     {
4163
-       // global Globals::$conf, Globals::$langs;
4163
+        // global Globals::$conf, Globals::$langs;
4164 4164
 
4165 4165
         print '<div class="pagination"><ul>';
4166 4166
         if ((int) $limit >= 0 && empty($hideselectlimit)) {
@@ -4283,7 +4283,7 @@  discard block
 block discarded – undo
4283 4283
      */
4284 4284
     static function price($amount, $form = 0, $outlangs = '', $trunc = 1, $rounding = -1, $forcerounding = -1, $currency_code = '')
4285 4285
     {
4286
-       // global Globals::$langs, Globals::$conf;
4286
+        // global Globals::$langs, Globals::$conf;
4287 4287
 // Clean parameters
4288 4288
         if (empty($amount))
4289 4289
             $amount = 0; // To have a numeric value if amount not defined or = ''
@@ -4376,7 +4376,7 @@  discard block
 block discarded – undo
4376 4376
      */
4377 4377
     static function price2num($amount, $rounding = '', $alreadysqlnb = 0)
4378 4378
     {
4379
-       // global Globals::$langs, Globals::$conf;
4379
+        // global Globals::$langs, Globals::$conf;
4380 4380
 // Round PHP static function does not allow number like '1,234.56' nor '1.234,56' nor '1 234,56'
4381 4381
 // Numbers must be '1234.56'
4382 4382
 // Decimal delimiter for PHP and database SQL requests must be '.'
@@ -4499,7 +4499,7 @@  discard block
 block discarded – undo
4499 4499
      */
4500 4500
     static function get_localtax($vatrate, $local, $thirdparty_buyer = "", $thirdparty_seller = "", $vatnpr = 0)
4501 4501
     {
4502
-       // global $db, Globals::$conf, $mysoc;
4502
+        // global $db, Globals::$conf, $mysoc;
4503 4503
 
4504 4504
         if (empty($thirdparty_seller) || !is_object($thirdparty_seller))
4505 4505
             $thirdparty_seller = $mysoc;
@@ -4639,7 +4639,7 @@  discard block
 block discarded – undo
4639 4639
      */
4640 4640
     static function get_localtax_by_third($local)
4641 4641
     {
4642
-       // global $db, $mysoc;
4642
+        // global $db, $mysoc;
4643 4643
         $sql = "SELECT t.localtax1, t.localtax2 ";
4644 4644
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t inner join " . MAIN_DB_PREFIX . "c_country as c ON c.rowid=t.fk_pays";
4645 4645
         $sql .= " WHERE c.code = '" . $mysoc->country_code . "' AND t.active = 1 AND t.taux=(";
@@ -4672,7 +4672,7 @@  discard block
 block discarded – undo
4672 4672
      */
4673 4673
     static function getTaxesFromId($vatrate, $buyer = null, $seller = null, $firstparamisid = 1)
4674 4674
     {
4675
-       // global $db, $mysoc;
4675
+        // global $db, $mysoc;
4676 4676
 
4677 4677
         dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
4678 4678
 
@@ -4729,7 +4729,7 @@  discard block
 block discarded – undo
4729 4729
      */
4730 4730
     static function getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid = 0)
4731 4731
     {
4732
-       // global $db, $mysoc;
4732
+        // global $db, $mysoc;
4733 4733
 
4734 4734
         dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
4735 4735
 
@@ -4783,7 +4783,7 @@  discard block
 block discarded – undo
4783 4783
      */
4784 4784
     static function get_product_vat_for_country($idprod, $thirdparty_seller, $idprodfournprice = 0)
4785 4785
     {
4786
-       // global $db, Globals::$conf, $mysoc;
4786
+        // global $db, Globals::$conf, $mysoc;
4787 4787
 
4788 4788
         require_once DOL_BASE_PATH . '/product/class/product.class.php';
4789 4789
 
@@ -4854,7 +4854,7 @@  discard block
 block discarded – undo
4854 4854
      */
4855 4855
     static function get_product_localtax_for_country($idprod, $local, $thirdparty_seller)
4856 4856
     {
4857
-       // global $db, $mysoc;
4857
+        // global $db, $mysoc;
4858 4858
 
4859 4859
         if (!class_exists('Product')) {
4860 4860
             require_once DOL_BASE_PATH . 'product/class/product.class.php';
@@ -4922,7 +4922,7 @@  discard block
 block discarded – undo
4922 4922
      */
4923 4923
     static function get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
4924 4924
     {
4925
-       // global Globals::$conf;
4925
+        // global Globals::$conf;
4926 4926
 
4927 4927
         require_once DOL_BASE_PATH . '/core/lib/company.lib.php';
4928 4928
 
@@ -4997,7 +4997,7 @@  discard block
 block discarded – undo
4997 4997
      */
4998 4998
     static function get_default_npr(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod = 0, $idprodfournprice = 0)
4999 4999
     {
5000
-       // global $db;
5000
+        // global $db;
5001 5001
 
5002 5002
         if ($idprodfournprice > 0) {
5003 5003
             if (!class_exists('ProductFournisseur'))
@@ -5032,7 +5032,7 @@  discard block
 block discarded – undo
5032 5032
      */
5033 5033
     static function get_default_localtax($thirdparty_seller, $thirdparty_buyer, $local, $idprod = 0)
5034 5034
     {
5035
-       // global $mysoc;
5035
+        // global $mysoc;
5036 5036
 
5037 5037
         if (!is_object($thirdparty_seller))
5038 5038
             return -1;
@@ -5077,7 +5077,7 @@  discard block
 block discarded – undo
5077 5077
      */
5078 5078
     static function yn($yesno, $case = 1, $color = 0)
5079 5079
     {
5080
-       // global Globals::$langs;
5080
+        // global Globals::$langs;
5081 5081
         $result = 'unknown';
5082 5082
         $classname = '';
5083 5083
         if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') {  // A mettre avant test sur no a cause du == 0
@@ -5127,7 +5127,7 @@  discard block
 block discarded – undo
5127 5127
      */
5128 5128
     static function get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
5129 5129
     {
5130
-       // global Globals::$conf;
5130
+        // global Globals::$conf;
5131 5131
 
5132 5132
         $path = '';
5133 5133
 
@@ -5175,7 +5175,7 @@  discard block
 block discarded – undo
5175 5175
      */
5176 5176
     static function dol_mkdir($dir, $dataroot = '', $newmask = null)
5177 5177
     {
5178
-       // global Globals::$conf;
5178
+        // global Globals::$conf;
5179 5179
 
5180 5180
         dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5181 5181
 
@@ -5722,7 +5722,7 @@  discard block
 block discarded – undo
5722 5722
      */
5723 5723
     static function getCommonSubstitutionArray($outputlangs, $onlykey = 0, $exclude = null, $object = null)
5724 5724
     {
5725
-       // global $db, Globals::$conf, $mysoc, $user, $extrafields;
5725
+        // global $db, Globals::$conf, $mysoc, $user, $extrafields;
5726 5726
 
5727 5727
         $substitutionarray = array();
5728 5728
 
@@ -6028,7 +6028,7 @@  discard block
 block discarded – undo
6028 6028
      */
6029 6029
     static function make_substitutions($text, $substitutionarray, $outputlangs = null)
6030 6030
     {
6031
-       // global Globals::$conf, Globals::$langs;
6031
+        // global Globals::$conf, Globals::$langs;
6032 6032
 
6033 6033
         if (!is_array($substitutionarray))
6034 6034
             return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
@@ -6094,7 +6094,7 @@  discard block
 block discarded – undo
6094 6094
      */
6095 6095
     static function complete_substitutions_array(&$substitutionarray, $outputlangs, $object = null, $parameters = null, $callfunc = "completesubstitutionarray")
6096 6096
     {
6097
-       // global Globals::$conf, $user;
6097
+        // global Globals::$conf, $user;
6098 6098
 
6099 6099
         require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
6100 6100
 
@@ -6164,7 +6164,7 @@  discard block
 block discarded – undo
6164 6164
      */
6165 6165
     static function get_date_range($date_start, $date_end, $format = '', $outputlangs = '', $withparenthesis = 1)
6166 6166
     {
6167
-       // global Globals::$langs;
6167
+        // global Globals::$langs;
6168 6168
 
6169 6169
         $out = '';
6170 6170
 
@@ -6194,7 +6194,7 @@  discard block
 block discarded – undo
6194 6194
      */
6195 6195
     static function dolGetFirstLastname($firstname, $lastname, $nameorder = -1)
6196 6196
     {
6197
-       // global Globals::$conf;
6197
+        // global Globals::$conf;
6198 6198
 
6199 6199
         $ret = '';
6200 6200
 // If order not defined, we use the setup
@@ -6318,7 +6318,7 @@  discard block
 block discarded – undo
6318 6318
      */
6319 6319
     static function get_htmloutput_mesg($mesgstring = '', $mesgarray = '', $style = 'ok', $keepembedded = 0)
6320 6320
     {
6321
-       // global Globals::$conf, Globals::$langs;
6321
+        // global Globals::$conf, Globals::$langs;
6322 6322
 
6323 6323
         $ret = 0;
6324 6324
         $return = '';
@@ -6554,7 +6554,7 @@  discard block
 block discarded – undo
6554 6554
      */
6555 6555
     function dol_osencode($str)
6556 6556
     {
6557
-       // global Globals::$conf;
6557
+        // global Globals::$conf;
6558 6558
 
6559 6559
         $tmp = ini_get("unicode.filesystem_encoding");      // Disponible avec PHP 6.0
6560 6560
         if (empty($tmp) && !empty($_SERVER["WINDIR"]))
@@ -6584,7 +6584,7 @@  discard block
 block discarded – undo
6584 6584
      */
6585 6585
     static function dol_getIdFromCode($db, $key, $tablename, $fieldkey = 'code', $fieldid = 'id', $entityfilter = 0)
6586 6586
     {
6587
-       // global $cache_codes;
6587
+        // global $cache_codes;
6588 6588
 // If key empty
6589 6589
         if ($key == '')
6590 6590
             return '';
@@ -6625,7 +6625,7 @@  discard block
 block discarded – undo
6625 6625
      */
6626 6626
     static function verifCond($strRights)
6627 6627
     {
6628
-       // global $user, Globals::$conf, Globals::$langs;
6628
+        // global $user, Globals::$conf, Globals::$langs;
6629 6629
         // global $leftmenu;
6630 6630
         // global $rights;    // To export to dol_eval function
6631 6631
 //print $strRights."<br>\n";
@@ -6691,7 +6691,7 @@  discard block
 block discarded – undo
6691 6691
      */
6692 6692
     static function picto_from_langcode($codelang, $moreatt = '')
6693 6693
     {
6694
-       // global Globals::$langs;
6694
+        // global Globals::$langs;
6695 6695
 
6696 6696
         if (empty($codelang))
6697 6697
             return '';
@@ -6726,7 +6726,7 @@  discard block
 block discarded – undo
6726 6726
      */
6727 6727
     static function getLanguageCodeFromCountryCode($countrycode)
6728 6728
     {
6729
-       // global $mysoc;
6729
+        // global $mysoc;
6730 6730
 
6731 6731
         if (strtoupper($countrycode) == 'MQ')
6732 6732
             return 'fr_CA';
@@ -6960,7 +6960,7 @@  discard block
 block discarded – undo
6960 6960
      */
6961 6961
     static function complete_head_from_modules($conf, $langs, $object, &$head, &$h, $type, $mode = 'add')
6962 6962
     {
6963
-       // global $hookmanager;
6963
+        // global $hookmanager;
6964 6964
 
6965 6965
         if (isset(Globals::$conf->modules_parts['tabs'][$type]) && is_array(Globals::$conf->modules_parts['tabs'][$type])) {
6966 6966
             foreach (Globals::$conf->modules_parts['tabs'][$type] as $value) {
@@ -7049,7 +7049,7 @@  discard block
 block discarded – undo
7049 7049
      */
7050 7050
     static function printCommonFooter($zone = 'private')
7051 7051
     {
7052
-       // global Globals::$conf, $hookmanager, $user;
7052
+        // global Globals::$conf, $hookmanager, $user;
7053 7053
         // global $action;
7054 7054
         // global $micro_start_time;
7055 7055
 
@@ -7289,7 +7289,7 @@  discard block
 block discarded – undo
7289 7289
      */
7290 7290
     static function natural_search($fields, $value, $mode = 0, $nofirstand = 0)
7291 7291
     {
7292
-       // global $db, Globals::$langs;
7292
+        // global $db, Globals::$langs;
7293 7293
 
7294 7294
         $value = trim($value);
7295 7295
 
@@ -7422,7 +7422,7 @@  discard block
 block discarded – undo
7422 7422
      */
7423 7423
     static function showDirectDownloadLink($object)
7424 7424
     {
7425
-       // global Globals::$conf, Globals::$langs;
7425
+        // global Globals::$conf, Globals::$langs;
7426 7426
 
7427 7427
         $out = '';
7428 7428
         $url = $object->getLastMainDocLink($object->element);
@@ -7484,7 +7484,7 @@  discard block
 block discarded – undo
7484 7484
      */
7485 7485
     static function getAdvancedPreviewUrl($modulepart, $relativepath, $alldata = 0, $param = '')
7486 7486
     {
7487
-       // global Globals::$conf, Globals::$langs;
7487
+        // global Globals::$conf, Globals::$langs;
7488 7488
 
7489 7489
         if (empty(Globals::$conf->use_javascript_ajax))
7490 7490
             return '';
@@ -7517,7 +7517,7 @@  discard block
 block discarded – undo
7517 7517
      */
7518 7518
     static function ajax_autoselect($htmlname, $addlink = '')
7519 7519
     {
7520
-       // global Globals::$langs;
7520
+        // global Globals::$langs;
7521 7521
         $out = '<script type="text/javascript">
7522 7522
                jQuery(document).ready(static function () {
7523 7523
 				    jQuery("#' . $htmlname . '").click(function() { jQuery(this).select(); } );
@@ -7901,7 +7901,7 @@  discard block
 block discarded – undo
7901 7901
      */
7902 7902
     static function getDictvalue($tablename, $field, $id, $checkentity = false, $rowidfield = 'rowid')
7903 7903
     {
7904
-       // global $dictvalues, $db, Globals::$langs;
7904
+        // global $dictvalues, $db, Globals::$langs;
7905 7905
 
7906 7906
         if (!isset($dictvalues[$tablename])) {
7907 7907
             $dictvalues[$tablename] = array();
@@ -7969,7 +7969,7 @@  discard block
 block discarded – undo
7969 7969
      */
7970 7970
     static function isVisibleToUserType($type_user, &$menuentry, &$listofmodulesforexternal)
7971 7971
     {
7972
-       // global Globals::$conf;
7972
+        // global Globals::$conf;
7973 7973
 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
7974 7974
 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
7975 7975
         if (empty($menuentry['enabled']))
Please login to merge, or discard this patch.
Spacing   +542 added lines, -542 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
-        dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
55
+        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
-        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
+        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
-            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
+            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
 
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 
564 564
                     
565 565
 //var_dump('__'.$reg[1].'__ -> '.$newout);
566
-                $out = preg_replace('/__' . preg_quote($reg[1], '/') . '__/', $newout, $out);
566
+                $out = preg_replace('/__'.preg_quote($reg[1], '/').'__/', $newout, $out);
567 567
             }
568 568
         }
569 569
 
@@ -673,7 +673,7 @@  discard block
 block discarded – undo
673 673
         // If prefix is for email
674 674
         if ($mode == 'email') {
675 675
             if (empty(Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) {
676
-                return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
676
+                return Security::dol_hash(DOL_DOCUMENT_ROOT.DOL_BASE_URI);
677 677
             }
678 678
             // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
679 679
             if (Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
@@ -683,16 +683,16 @@  discard block
 block discarded – undo
683 683
                 return $_SERVER["SERVER_NAME"];
684 684
             }
685 685
 
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
 
689 689
         if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
690
-            return Security::dol_hash($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_BASE_URI);
690
+            return Security::dol_hash($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_BASE_URI);
691 691
 
692 692
             // Use this for a "readable" cookie name
693 693
             //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_BASE_URI);
694 694
         }
695
-        return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
695
+        return Security::dol_hash(DOL_DOCUMENT_ROOT.DOL_BASE_URI);
696 696
     }
697 697
 
698 698
     /**
@@ -712,7 +712,7 @@  discard block
 block discarded – undo
712 712
         $fullpath = dol_buildpath($relpath);
713 713
 
714 714
         if (!file_exists($fullpath)) {
715
-            dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_ERR);
715
+            dol_syslog('functions::dol_include_once Tried to load unexisting file: '.$relpath, LOG_ERR);
716 716
             return false;
717 717
         }
718 718
 
@@ -741,14 +741,14 @@  discard block
 block discarded – undo
741 741
 
742 742
         if ($type == 0 /* empty($type) */) { // For a filesystem path
743 743
 //$res = DOL_BASE_PATH . '' . $path;  // Standard default path
744
-            $res = DOL_BASE_PATH . '/' . $path;  // Standard default path
744
+            $res = DOL_BASE_PATH.'/'.$path; // Standard default path
745 745
             if (isset(Globals::$conf->file->dol_document_root)) {
746 746
                 foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
747 747
                     if ($key == 'main') {
748 748
                         continue;
749 749
                     }
750
-                    if (file_exists($dirroot . '/' . $path)) {
751
-                        $res = $dirroot . '/' . $path;
750
+                    if (file_exists($dirroot.'/'.$path)) {
751
+                        $res = $dirroot.'/'.$path;
752 752
                         return $res;
753 753
                     }
754 754
                 }
@@ -765,13 +765,13 @@  discard block
 block discarded – undo
765 765
 // using proxy, rewriting, virtual path, etc...
766 766
             $res = '';
767 767
             if ($type == 1) {
768
-                $res = /* DOL_BASE_URI */ DOL_BASE_URI . '/' . $path;   // Standard value
768
+                $res = /* DOL_BASE_URI */ DOL_BASE_URI.'/'.$path; // Standard value
769 769
             }
770 770
             if ($type == 2) {
771
-                $res = /* DOL_MAIN_URL_ROOT */ DOL_BASE_PATH . '/' . $path;  // Standard value
771
+                $res = /* DOL_MAIN_URL_ROOT */ DOL_BASE_PATH.'/'.$path; // Standard value
772 772
             }
773 773
             if ($type == 3) {
774
-                $res = DOL_BASE_URI . '/' . $path;
774
+                $res = DOL_BASE_URI.'/'.$path;
775 775
             }
776 776
 
777 777
             foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
@@ -781,33 +781,33 @@  discard block
 block discarded – undo
781 781
                         // Define $urlwithroot
782 782
 
783 783
                         // $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
784
-                        $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim(DOL_BASE_URI));
784
+                        $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_BASE_URI, '/').'$/i', '', trim(DOL_BASE_URI));
785 785
 
786
-                        $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
786
+                        $urlwithroot = $urlwithouturlroot.DOL_BASE_URI; // This is to use external domain name found into config file
787 787
                         //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
788 788
 
789
-                        $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path;     // Test on start with http is for old conf syntax
789
+                        $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot).'/'.$path; // Test on start with http is for old conf syntax
790 790
                     }
791 791
                     continue;
792 792
                 }
793
-                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs);    // Take part before '?'
793
+                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs); // Take part before '?'
794 794
                 if (!empty($regs[1])) {
795 795
                     //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
796
-                    if (file_exists($dirroot . '/' . $regs[1])) {
796
+                    if (file_exists($dirroot.'/'.$regs[1])) {
797 797
                         if ($type == 1) {
798
-                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_BASE_URI) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
798
+                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_BASE_URI).Globals::$conf->file->dol_url_root[$key].'/'.$path;
799 799
                         }
800 800
                         if ($type == 2) {
801
-                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
801
+                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT).Globals::$conf->file->dol_url_root[$key].'/'.$path;
802 802
                         }
803 803
                         if ($type == 3) {
804 804
                            // global $dolibarr_main_url_root;
805 805
                             // Define $urlwithroot
806
-                            $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
807
-                            $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
806
+                            $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_BASE_URI, '/').'$/i', '', trim($dolibarr_main_url_root));
807
+                            $urlwithroot = $urlwithouturlroot.DOL_BASE_URI; // This is to use external domain name found into config file
808 808
                             //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
809 809
 
810
-                            $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
810
+                            $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
811 811
                         }
812 812
                         break;
813 813
                     }
@@ -835,7 +835,7 @@  discard block
 block discarded – undo
835 835
         if (empty($native)) {
836 836
             $myclone = unserialize(serialize($object));
837 837
         } else {
838
-            $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)
838
+            $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)
839 839
         }
840 840
 
841 841
         return $myclone;
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
      */
957 957
     static function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
958 958
     {
959
-        $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°');  // more complete than dol_sanitizeFileName
959
+        $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°'); // more complete than dol_sanitizeFileName
960 960
         $forbidden_chars_to_remove = array();
961 961
         if (is_array($badcharstoreplace))
962 962
             $forbidden_chars_to_replace = $badcharstoreplace;
@@ -1019,12 +1019,12 @@  discard block
 block discarded – undo
1019 1019
     static function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0)
1020 1020
     {
1021 1021
 // escape quotes and backslashes, newlines, etc.
1022
-        $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');  // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1022
+        $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1023 1023
         if (!$keepb)
1024 1024
             $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1025 1025
         if (!$keepn)
1026 1026
             $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1027
-        return htmlentities($tmp, ENT_COMPAT, 'UTF-8');      // TODO Use htmlspecialchars instead, that make only required change for html tags
1027
+        return htmlentities($tmp, ENT_COMPAT, 'UTF-8'); // TODO Use htmlspecialchars instead, that make only required change for html tags
1028 1028
     }
1029 1029
 
1030 1030
     /**
@@ -1094,14 +1094,14 @@  discard block
 block discarded – undo
1094 1094
             $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1095 1095
 // If adding log inside HTML page is required
1096 1096
             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
1097
-                Globals::$conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S") . " " . $message;
1097
+                Globals::$conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S")." ".$message;
1098 1098
             }
1099 1099
 
1100 1100
 //TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
1101 1101
 // If html log tag enabled and url parameter log defined, we show output log on HTML comments
1102 1102
             if (!empty(Globals::$conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
1103 1103
                 print "\n\n<!-- Log start\n";
1104
-                print $message . "\n";
1104
+                print $message."\n";
1105 1105
                 print "Log end -->\n";
1106 1106
             }
1107 1107
 
@@ -1115,7 +1115,7 @@  discard block
 block discarded – undo
1115 1115
 
1116 1116
 // This is when server run behind a reverse proxy
1117 1117
             if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
1118
-                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1118
+                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'].(empty($_SERVER["REMOTE_ADDR"]) ? '' : '->'.$_SERVER['REMOTE_ADDR']);
1119 1119
 // This is when server run normally on a server
1120 1120
             else if (!empty($_SERVER["REMOTE_ADDR"]))
1121 1121
                 $data['ip'] = $_SERVER['REMOTE_ADDR'];
@@ -1124,10 +1124,10 @@  discard block
 block discarded – undo
1124 1124
                 $data['ip'] = $_SERVER['SERVER_ADDR'];
1125 1125
 // 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).
1126 1126
             else if (!empty($_SERVER['COMPUTERNAME']))
1127
-                $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1127
+                $data['ip'] = $_SERVER['COMPUTERNAME'].(empty($_SERVER['USERNAME']) ? '' : '@'.$_SERVER['USERNAME']);
1128 1128
 // 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).
1129 1129
             else if (!empty($_SERVER['LOGNAME']))
1130
-                $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1130
+                $data['ip'] = '???@'.$_SERVER['LOGNAME'];
1131 1131
 // Loop on each log handler and send output
1132 1132
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
1133 1133
                 if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler)
@@ -1179,10 +1179,10 @@  discard block
 block discarded – undo
1179 1179
     {
1180 1180
        // global Globals::$conf, Globals::$langs, $hookmanager;
1181 1181
 
1182
-        $out = "\n" . '<div class="tabs" data-role="controlgroup" data-type="horizontal">' . "\n";
1182
+        $out = "\n".'<div class="tabs" data-role="controlgroup" data-type="horizontal">'."\n";
1183 1183
 
1184 1184
         if ($morehtmlright) {
1185
-            $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.
1185
+            $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.
1186 1186
         }
1187 1187
 
1188 1188
 // Show title
@@ -1193,8 +1193,8 @@  discard block
 block discarded – undo
1193 1193
             $limittitle = 30;
1194 1194
             $out .= '<a class="tabTitle">';
1195 1195
             if ($picto)
1196
-                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1197
-            $out .= '<span class="tabTitleText">' . dol_trunc($title, $limittitle) . '</span>';
1196
+                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_').$picto, '', $pictoisfullpath).' ';
1197
+            $out .= '<span class="tabTitleText">'.dol_trunc($title, $limittitle).'</span>';
1198 1198
             $out .= '</a>';
1199 1199
         }
1200 1200
 
@@ -1234,23 +1234,23 @@  discard block
 block discarded – undo
1234 1234
             }
1235 1235
 
1236 1236
             if ($i < $limittoshow || $isactive) {
1237
-                $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]) . ' -->';
1237
+                $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]).' -->';
1238 1238
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1239 1239
                     if (!empty($links[$i][0])) {
1240
-                        $out .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1240
+                        $out .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
1241 1241
                     } else {
1242
-                        $out .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1242
+                        $out .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
1243 1243
                     }
1244 1244
                 } else if (!empty($links[$i][1])) {
1245 1245
                     //print "x $i $active ".$links[$i][2]." z";
1246 1246
                     if ($isactive) {
1247
-                        $out .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="tabactive tab inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1247
+                        $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1248 1248
                         $out .= $links[$i][1];
1249
-                        $out .= '</a>' . "\n";
1249
+                        $out .= '</a>'."\n";
1250 1250
                     } else {
1251
-                        $out .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="tabunactive tab inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1251
+                        $out .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="tabunactive tab inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1252 1252
                         $out .= $links[$i][1];
1253
-                        $out .= '</a>' . "\n";
1253
+                        $out .= '</a>'."\n";
1254 1254
                     }
1255 1255
                 }
1256 1256
                 $out .= '</div>';
@@ -1263,14 +1263,14 @@  discard block
 block discarded – undo
1263 1263
                 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
1264 1264
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1265 1265
                     if (!empty($links[$i][0]))
1266
-                        $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1266
+                        $outmore .= '<a class="tabimage'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">'.$links[$i][1].'</a>'."\n";
1267 1267
                     else
1268
-                        $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1268
+                        $outmore .= '<span class="tabspan">'.$links[$i][1].'</span>'."\n";
1269 1269
                 }
1270 1270
                 else if (!empty($links[$i][1])) {
1271
-                    $outmore .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1271
+                    $outmore .= '<a'.(!empty($links[$i][2]) ? ' id="'.$links[$i][2].'"' : '').' class="wordwrap inline-block'.($morecss ? ' '.$morecss : '').'" href="'.$links[$i][0].'">';
1272 1272
                     $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.
1273
-                    $outmore .= '</a>' . "\n";
1273
+                    $outmore .= '</a>'."\n";
1274 1274
                 }
1275 1275
                 $outmore .= '</div>';
1276 1276
 
@@ -1286,24 +1286,24 @@  discard block
 block discarded – undo
1286 1286
             $right = (Globals::$langs->trans("DIRECTION") == 'rtl' ? 'left' : 'right');
1287 1287
 
1288 1288
             $tabsname = str_replace("@", "", $picto);
1289
-            $out .= '<div id="moretabs' . $tabsname . '" class="inline-block tabsElem">';
1290
-            $out .= '<a href="#" class="tab moretab inline-block tabunactive reposition">' . Globals::$langs->trans("More") . '... (' . $nbintab . ')</a>';
1291
-            $out .= '<div id="moretabsList' . $tabsname . '" style="position: absolute; ' . $left . ': -999em; text-align: ' . $left . '; margin:0px; padding:2px">';
1289
+            $out .= '<div id="moretabs'.$tabsname.'" class="inline-block tabsElem">';
1290
+            $out .= '<a href="#" class="tab moretab inline-block tabunactive reposition">'.Globals::$langs->trans("More").'... ('.$nbintab.')</a>';
1291
+            $out .= '<div id="moretabsList'.$tabsname.'" style="position: absolute; '.$left.': -999em; text-align: '.$left.'; margin:0px; padding:2px">';
1292 1292
             $out .= $outmore;
1293 1293
             $out .= '</div>';
1294 1294
             $out .= '<div></div>';
1295 1295
             $out .= "</div>\n";
1296 1296
 
1297 1297
             $out .= "<script>";
1298
-            $out .= "$('#moretabs" . $tabsname . "').mouseenter( function() { console.log('mouseenter " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','auto');});";
1299
-            $out .= "$('#moretabs" . $tabsname . "').mouseleave( function() { console.log('mouseleave " . $left . "'); $('#moretabsList" . $tabsname . "').css('" . $left . "','-999em');});";
1298
+            $out .= "$('#moretabs".$tabsname."').mouseenter( function() { console.log('mouseenter ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','auto');});";
1299
+            $out .= "$('#moretabs".$tabsname."').mouseleave( function() { console.log('mouseleave ".$left."'); $('#moretabsList".$tabsname."').css('".$left."','-999em');});";
1300 1300
             $out .= "</script>";
1301 1301
         }
1302 1302
 
1303 1303
         $out .= "</div>\n";
1304 1304
 
1305 1305
         if (!$notab || $notab == -1)
1306
-            $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1306
+            $out .= "\n".'<div class="tabBar'.($notab == -1 ? '' : ' tabBarWithBottom').'">'."\n";
1307 1307
 
1308 1308
         $parameters = array('tabname' => $active, 'out' => $out);
1309 1309
         $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
@@ -1412,7 +1412,7 @@  discard block
 block discarded – undo
1412 1412
             if (Globals::$conf->browser->layout == 'phone')
1413 1413
                 $maxvisiblephotos = 1;
1414 1414
             if ($showimage)
1415
-                $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>';
1415
+                $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>';
1416 1416
             else {
1417 1417
                 if (!empty(Globals::$conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
1418 1418
                     $nophoto = '';
@@ -1421,18 +1421,18 @@  discard block
 block discarded – undo
1421 1421
 //elseif (Globals::$conf->browser->layout != 'phone') {    // Show no photo link
1422 1422
                 $nophoto = '/public/theme/common/nophoto.png';
1423 1423
 // $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>';
1424
-                $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>';
1424
+                $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>';
1425 1425
 //}
1426 1426
             }
1427 1427
         } elseif ($object->element == 'ticket') {
1428 1428
             $width = 80;
1429 1429
             $cssclass = 'photoref';
1430
-            $showimage = $object->is_photo_available(Globals::$conf->ticket->multidir_output[$entity] . '/' . $object->track_id);
1430
+            $showimage = $object->is_photo_available(Globals::$conf->ticket->multidir_output[$entity].'/'.$object->track_id);
1431 1431
             $maxvisiblephotos = (isset(Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO) ? Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO : 2);
1432 1432
             if (Globals::$conf->browser->layout == 'phone')
1433 1433
                 $maxvisiblephotos = 1;
1434 1434
             if ($showimage)
1435
-                $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>';
1435
+                $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>';
1436 1436
             else {
1437 1437
                 if (!empty(Globals::$conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
1438 1438
                     $nophoto = '';
@@ -1441,7 +1441,7 @@  discard block
 block discarded – undo
1441 1441
 //elseif (Globals::$conf->browser->layout != 'phone') {    // Show no photo link
1442 1442
                 $nophoto = '/public/theme/common/nophoto.png';
1443 1443
 //$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>';
1444
-                $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>';
1444
+                $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>';
1445 1445
 //}
1446 1446
             }
1447 1447
         } else {
@@ -1451,25 +1451,25 @@  discard block
 block discarded – undo
1451 1451
                     // Check if a preview file is available
1452 1452
                     if (in_array($modulepart, array('propal', 'commande', 'facture', 'ficheinter', 'contract', 'supplier_order', 'supplier_proposal', 'supplier_invoice', 'expensereport')) && class_exists("Imagick")) {
1453 1453
                         $objectref = dol_sanitizeFileName($object->ref);
1454
-                        $dir_output = (empty(Globals::$conf->$modulepart->multidir_output[$entity]) ? Globals::$conf->$modulepart->dir_output : Globals::$conf->$modulepart->multidir_output[$entity]) . "/";
1454
+                        $dir_output = (empty(Globals::$conf->$modulepart->multidir_output[$entity]) ? Globals::$conf->$modulepart->dir_output : Globals::$conf->$modulepart->multidir_output[$entity])."/";
1455 1455
                         if (in_array($modulepart, array('invoice_supplier', 'supplier_invoice'))) {
1456 1456
                             $subdir = get_exdir($object->id, 2, 0, 1, $object, $modulepart);
1457
-                            $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
1457
+                            $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
1458 1458
                         } else {
1459 1459
                             $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
1460 1460
                         }
1461 1461
                         if (empty($subdir))
1462 1462
                             $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
1463 1463
 
1464
-                        $filepath = $dir_output . $subdir . "/";
1464
+                        $filepath = $dir_output.$subdir."/";
1465 1465
 
1466
-                        $file = $filepath . $objectref . ".pdf";
1467
-                        $relativepath = $subdir . '/' . $objectref . '.pdf';
1466
+                        $file = $filepath.$objectref.".pdf";
1467
+                        $relativepath = $subdir.'/'.$objectref.'.pdf';
1468 1468
 
1469 1469
                         // Define path to preview pdf file (preview precompiled "file.ext" are "file.ext_preview.png")
1470
-                        $fileimage = $file . '_preview.png';              // If PDF has 1 page
1471
-                        $fileimagebis = $file . '_preview-0.png';         // If PDF has more than one page
1472
-                        $relativepathimage = $relativepath . '_preview.png';
1470
+                        $fileimage = $file.'_preview.png'; // If PDF has 1 page
1471
+                        $fileimagebis = $file.'_preview-0.png'; // If PDF has more than one page
1472
+                        $relativepathimage = $relativepath.'_preview.png';
1473 1473
 
1474 1474
                         // Si fichier PDF existe
1475 1475
                         if (file_exists($file)) {
@@ -1478,7 +1478,7 @@  discard block
 block discarded – undo
1478 1478
                             if ((!file_exists($fileimage) || (filemtime($fileimage) < filemtime($file))) && (!file_exists($fileimagebis) || (filemtime($fileimagebis) < filemtime($file)))
1479 1479
                             ) {
1480 1480
                                 if (empty(Globals::$conf->global->MAIN_DISABLE_PDF_THUMBS)) {  // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
1481
-                                    include_once DOL_BASE_PATH . '/core/lib/files.lib.php';
1481
+                                    include_once DOL_BASE_PATH.'/core/lib/files.lib.php';
1482 1482
                                     $ret = dol_convert_file($file, 'png', $fileimage);
1483 1483
                                     if ($ret < 0)
1484 1484
                                         $error++;
@@ -1491,14 +1491,14 @@  discard block
 block discarded – undo
1491 1491
                             // Si fichier png PDF d'1 page trouve
1492 1492
                             if (file_exists($fileimage)) {
1493 1493
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
1494
-                                $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithmargin photowithborder" src="' . DOL_BASE_URI . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($relativepathimage) . '">';
1494
+                                $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_BASE_URI.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($relativepathimage).'">';
1495 1495
                                 $phototoshow .= '</div></div>';
1496 1496
                             }
1497 1497
                             // Si fichier png PDF de plus d'1 page trouve
1498 1498
                             elseif (file_exists($fileimagebis)) {
1499
-                                $preview = preg_replace('/\.png/', '', $relativepathimage) . "-0.png";
1499
+                                $preview = preg_replace('/\.png/', '', $relativepathimage)."-0.png";
1500 1500
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
1501
-                                $phototoshow .= '<img height="' . $heightforphotref . '" class="photo photowithmargin photowithborder" src="' . DOL_BASE_URI . '/viewimage.php?modulepart=apercu' . $modulepart . '&amp;file=' . urlencode($preview) . '"><p>';
1501
+                                $phototoshow .= '<img height="'.$heightforphotref.'" class="photo photowithmargin photowithborder" src="'.DOL_BASE_URI.'/viewimage.php?modulepart=apercu'.$modulepart.'&amp;file='.urlencode($preview).'"><p>';
1502 1502
                                 $phototoshow .= '</div></div>';
1503 1503
                             }
1504 1504
                         }
@@ -1525,10 +1525,10 @@  discard block
 block discarded – undo
1525 1525
                         $picto = $object->picto;
1526 1526
                         if ($object->element == 'project' && !$object->public)
1527 1527
                             $picto = 'project'; // instead of projectpub
1528
-                        $nophoto = img_picto('', 'object_' . $picto, '', false, 1);
1528
+                        $nophoto = img_picto('', 'object_'.$picto, '', false, 1);
1529 1529
                     }
1530 1530
                     $morehtmlleft .= '<!-- No photo to show -->';
1531
-                    $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>';
1531
+                    $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>';
1532 1532
 
1533 1533
                     $morehtmlleft .= '</div>';
1534 1534
                 }
@@ -1536,7 +1536,7 @@  discard block
 block discarded – undo
1536 1536
         }
1537 1537
 
1538 1538
         if ($showbarcode)
1539
-            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1539
+            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">'.$form->showbarcode($object).'</div>';
1540 1540
 
1541 1541
         if ($object->element == 'societe') {
1542 1542
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->societe->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
@@ -1549,14 +1549,14 @@  discard block
 block discarded – undo
1549 1549
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->produit->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
1550 1550
                 $morehtmlstatus .= ajax_object_onoff($object, 'status', 'tosell', 'ProductStatusOnSell', 'ProductStatusNotOnSell');
1551 1551
             } else {
1552
-                $morehtmlstatus .= '<span class="statusrefsell">' . $object->getLibStatut(5, 0) . '</span>';
1552
+                $morehtmlstatus .= '<span class="statusrefsell">'.$object->getLibStatut(5, 0).'</span>';
1553 1553
             }
1554 1554
             $morehtmlstatus .= ' &nbsp; ';
1555 1555
 //$morehtmlstatus.=Globals::$langs->trans("Status").' ('.Globals::$langs->trans("Buy").') ';
1556 1556
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->produit->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
1557 1557
                 $morehtmlstatus .= ajax_object_onoff($object, 'status_buy', 'tobuy', 'ProductStatusOnBuy', 'ProductStatusNotOnBuy');
1558 1558
             } else {
1559
-                $morehtmlstatus .= '<span class="statusrefbuy">' . $object->getLibStatut(5, 1) . '</span>';
1559
+                $morehtmlstatus .= '<span class="statusrefbuy">'.$object->getLibStatut(5, 1).'</span>';
1560 1560
             }
1561 1561
         } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) {
1562 1562
             $tmptxt = $object->getLibStatut(6, $object->totalpaye);
@@ -1583,7 +1583,7 @@  discard block
 block discarded – undo
1583 1583
             if ($object->progress >= 100)
1584 1584
                 $object->fk_statut = 3;
1585 1585
             $tmptxt = $object->getLibStatut(5);
1586
-            $morehtmlstatus .= $tmptxt;  // No status on task
1586
+            $morehtmlstatus .= $tmptxt; // No status on task
1587 1587
         }
1588 1588
         else { // Generic case
1589 1589
             $tmptxt = $object->getLibStatut(6);
@@ -1597,18 +1597,18 @@  discard block
 block discarded – undo
1597 1597
             if (method_exists($object, 'getVentilExportCompta')) {
1598 1598
                 $accounted = $object->getVentilExportCompta();
1599 1599
                 Globals::$langs->load("accountancy");
1600
-                $morehtmlstatus .= '</div><div class="statusref statusrefbis">' . ($accounted > 0 ? Globals::$langs->trans("Accounted") : Globals::$langs->trans("NotYetAccounted"));
1600
+                $morehtmlstatus .= '</div><div class="statusref statusrefbis">'.($accounted > 0 ? Globals::$langs->trans("Accounted") : Globals::$langs->trans("NotYetAccounted"));
1601 1601
             }
1602 1602
         }
1603 1603
 
1604 1604
 // Add alias for thirdparty
1605 1605
         if (!empty($object->name_alias))
1606
-            $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1606
+            $morehtmlref .= '<div class="refidno">'.$object->name_alias.'</div>';
1607 1607
 
1608 1608
 // Add label
1609 1609
         if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task') {
1610 1610
             if (!empty($object->label))
1611
-                $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1611
+                $morehtmlref .= '<div class="refidno">'.$object->label.'</div>';
1612 1612
         }
1613 1613
 
1614 1614
         if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files') {
@@ -1618,11 +1618,11 @@  discard block
 block discarded – undo
1618 1618
         }
1619 1619
         if (!empty(Globals::$conf->global->MAIN_SHOW_TECHNICAL_ID) && in_array($object->element, array('societe', 'contact', 'member', 'product'))) {
1620 1620
             $morehtmlref .= '<div style="clear: both;"></div><div class="refidno">';
1621
-            $morehtmlref .= Globals::$langs->trans("TechnicalID") . ': ' . $object->id;
1621
+            $morehtmlref .= Globals::$langs->trans("TechnicalID").': '.$object->id;
1622 1622
             $morehtmlref .= '</div>';
1623 1623
         }
1624 1624
 
1625
-        print '<div class="' . ($onlybanner ? 'arearefnobottom ' : 'arearef ') . 'heightref valignmiddle" width="100%">';
1625
+        print '<div class="'.($onlybanner ? 'arearefnobottom ' : 'arearef ').'heightref valignmiddle" width="100%">';
1626 1626
         print $form->showrefnav($object, $paramid, $morehtml, $shownav, $fieldid, $fieldref, $morehtmlref, $moreparam, $nodbprefix, $morehtmlleft, $morehtmlstatus, $morehtmlright);
1627 1627
         print '</div>';
1628 1628
         print '<div class="underrefbanner clearboth"></div>';
@@ -1644,7 +1644,7 @@  discard block
 block discarded – undo
1644 1644
         if ($fieldrequired)
1645 1645
             $ret .= '<span class="fieldrequired">';
1646 1646
         if ((Globals::$conf->dol_use_jmobile != 4))
1647
-            $ret .= '<label for="' . $fieldkey . '">';
1647
+            $ret .= '<label for="'.$fieldkey.'">';
1648 1648
         $ret .= Globals::$langs->trans($langkey);
1649 1649
         if ((Globals::$conf->dol_use_jmobile != 4))
1650 1650
             $ret .= '</label>';
@@ -1663,9 +1663,9 @@  discard block
 block discarded – undo
1663 1663
     static function dol_bc($var, $moreclass = '')
1664 1664
     {
1665 1665
        // global $bc;
1666
-        $ret = ' ' . $bc[$var];
1666
+        $ret = ' '.$bc[$var];
1667 1667
         if ($moreclass)
1668
-            $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1668
+            $ret = preg_replace('/class=\"/', 'class="'.$moreclass.' ', $ret);
1669 1669
         return $ret;
1670 1670
     }
1671 1671
 
@@ -1685,50 +1685,50 @@  discard block
 block discarded – undo
1685 1685
        // global Globals::$conf, Globals::$langs;
1686 1686
 
1687 1687
         $ret = '';
1688
-        $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR');    // See also MAIN_FORCE_STATE_INTO_ADDRESS
1688
+        $countriesusingstate = array('AU', 'CA', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also MAIN_FORCE_STATE_INTO_ADDRESS
1689 1689
 // Address
1690 1690
         if (empty($mode)) {
1691 1691
             $ret .= $object->address;
1692 1692
         }
1693 1693
 // Zip/Town/State
1694 1694
         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
1695
-            $ret .= ($ret ? $sep : '' ) . $object->town;
1695
+            $ret .= ($ret ? $sep : '').$object->town;
1696 1696
             if ($object->state) {
1697
-                $ret .= ($ret ? ", " : '') . $object->state;
1697
+                $ret .= ($ret ? ", " : '').$object->state;
1698 1698
             }
1699 1699
             if ($object->zip)
1700
-                $ret .= ($ret ? ", " : '') . $object->zip;
1700
+                $ret .= ($ret ? ", " : '').$object->zip;
1701 1701
         }
1702 1702
         else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1703
-            $ret .= ($ret ? $sep : '' ) . $object->town;
1703
+            $ret .= ($ret ? $sep : '').$object->town;
1704 1704
             if ($object->state) {
1705
-                $ret .= ($ret ? ", " : '') . $object->state;
1705
+                $ret .= ($ret ? ", " : '').$object->state;
1706 1706
             }
1707 1707
             if ($object->zip)
1708
-                $ret .= ($ret ? $sep : '' ) . $object->zip;
1708
+                $ret .= ($ret ? $sep : '').$object->zip;
1709 1709
         }
1710 1710
         else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1711
-            $ret .= ($ret ? $sep : '' ) . $object->zip;
1712
-            $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1711
+            $ret .= ($ret ? $sep : '').$object->zip;
1712
+            $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : '');
1713 1713
             if ($object->state) {
1714
-                $ret .= "\n" . $object->state;
1714
+                $ret .= "\n".$object->state;
1715 1715
             }
1716 1716
         } else if (in_array($object->country_code, array('IT'))) { // IT: tile firstname name\n address lines \n zip (Code Departement) \n country
1717
-            $ret .= ($ret ? $sep : '' ) . $object->zip;
1718
-            $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1719
-            $ret .= ($object->departement_id ? (' (' . ($object->departement_id) . ')') : '');
1717
+            $ret .= ($ret ? $sep : '').$object->zip;
1718
+            $ret .= ($object->town ? (($object->zip ? ' ' : '').$object->town) : '');
1719
+            $ret .= ($object->departement_id ? (' ('.($object->departement_id).')') : '');
1720 1720
         } else {                                          // Other: title firstname name \n address lines \n zip town \n country
1721
-            $ret .= $object->zip ? (($ret ? $sep : '' ) . $object->zip) : '';
1722
-            $ret .= ($object->town ? (($object->zip ? ' ' : ($ret ? $sep : '' )) . $object->town) : '');
1721
+            $ret .= $object->zip ? (($ret ? $sep : '').$object->zip) : '';
1722
+            $ret .= ($object->town ? (($object->zip ? ' ' : ($ret ? $sep : '')).$object->town) : '');
1723 1723
             if ($object->state && in_array($object->country_code, $countriesusingstate)) {
1724
-                $ret .= ($ret ? ", " : '') . $object->state;
1724
+                $ret .= ($ret ? ", " : '').$object->state;
1725 1725
             }
1726 1726
         }
1727 1727
         if (!is_object($outputlangs))
1728 1728
             $outputlangs = Globals::$langs;
1729 1729
         if ($withcountry) {
1730 1730
             Globals::$langs->load("dict");
1731
-            $ret .= ($object->country_code ? ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)) : '');
1731
+            $ret .= ($object->country_code ? ($ret ? $sep : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$object->country_code)) : '');
1732 1732
         }
1733 1733
 
1734 1734
         return $ret;
@@ -1782,13 +1782,13 @@  discard block
 block discarded – undo
1782 1782
             if (is_string($tzoutput)) {
1783 1783
                 if ($tzoutput == 'tzserver') {
1784 1784
                     $to_gmt = false;
1785
-                    $offsettzstring = @date_default_timezone_get();  // Example 'Europe/Berlin' or 'Indian/Reunion'
1785
+                    $offsettzstring = @date_default_timezone_get(); // Example 'Europe/Berlin' or 'Indian/Reunion'
1786 1786
                     $offsettz = 0;
1787 1787
                     $offsetdst = 0;
1788 1788
                 } elseif ($tzoutput == 'tzuser' || $tzoutput == 'tzuserrel') {
1789 1789
                     $to_gmt = true;
1790 1790
                     $offsettzstring = (empty($_SESSION['dol_tz_string']) ? 'UTC' : $_SESSION['dol_tz_string']); // Example 'Europe/Berlin' or 'Indian/Reunion'
1791
-                    $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60;  // Will not be used anymore
1791
+                    $offsettz = (empty($_SESSION['dol_tz']) ? 0 : $_SESSION['dol_tz']) * 60 * 60; // Will not be used anymore
1792 1792
                     $offsetdst = (empty($_SESSION['dol_dst']) ? 0 : $_SESSION['dol_dst']) * 60 * 60; // Will not be used anymore
1793 1793
                 }
1794 1794
             }
@@ -1834,9 +1834,9 @@  discard block
 block discarded – undo
1834 1834
         else if ($format == 'dayxcard')
1835 1835
             $format = '%Y%m%d';
1836 1836
         else if ($format == 'dayrfc')
1837
-            $format = '%Y-%m-%d';             // DATE_RFC3339
1837
+            $format = '%Y-%m-%d'; // DATE_RFC3339
1838 1838
         else if ($format == 'dayhourrfc')
1839
-            $format = '%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339
1839
+            $format = '%Y-%m-%dT%H:%M:%SZ'; // DATETIME RFC3339
1840 1840
         else if ($format == 'standard')
1841 1841
             $format = '%Y-%m-%d %H:%M:%S';
1842 1842
 
@@ -1847,7 +1847,7 @@  discard block
 block discarded – undo
1847 1847
 
1848 1848
 // If date undefined or "", we return ""
1849 1849
         if (dol_strlen($time) == 0)
1850
-            return '';  // $time=0 allowed (it means 01/01/1970 00:00:00)
1850
+            return ''; // $time=0 allowed (it means 01/01/1970 00:00:00)
1851 1851
 
1852 1852
 
1853 1853
 
@@ -1898,7 +1898,7 @@  discard block
 block discarded – undo
1898 1898
         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
1899 1899
 // TODO Remove this.
1900 1900
 // This part of code should not be used.
1901
-            dol_syslog("Functions.lib::dol_print_date static function call with deprecated value of time in page " . $_SERVER["PHP_SELF"], LOG_ERR);
1901
+            dol_syslog("Functions.lib::dol_print_date static function call with deprecated value of time in page ".$_SERVER["PHP_SELF"], LOG_ERR);
1902 1902
 // Date has format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' or 'YYYYMMDDHHMMSS'
1903 1903
             $syear = (!empty($reg[1]) ? $reg[1] : '');
1904 1904
             $smonth = (!empty($reg[2]) ? $reg[2] : '');
@@ -1916,7 +1916,7 @@  discard block
 block discarded – undo
1916 1916
 
1917 1917
                 $ret = adodb_strftime($format, $timetouse, $to_gmt);
1918 1918
             } else
1919
-                $ret = 'Bad value ' . $time . ' for date';
1919
+                $ret = 'Bad value '.$time.' for date';
1920 1920
         }
1921 1921
 
1922 1922
         if (preg_match('/__b__/i', $format)) {
@@ -1925,11 +1925,11 @@  discard block
 block discarded – undo
1925 1925
             $month = adodb_strftime('%m', $timetouse);
1926 1926
             $month = sprintf("%02d", $month); // $month may be return with format '06' on some installation and '6' on other, so we force it to '06'.
1927 1927
             if ($encodetooutput) {
1928
-                $monthtext = $outputlangs->transnoentities('Month' . $month);
1929
-                $monthtextshort = $outputlangs->transnoentities('MonthShort' . $month);
1928
+                $monthtext = $outputlangs->transnoentities('Month'.$month);
1929
+                $monthtextshort = $outputlangs->transnoentities('MonthShort'.$month);
1930 1930
             } else {
1931
-                $monthtext = $outputlangs->transnoentitiesnoconv('Month' . $month);
1932
-                $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort' . $month);
1931
+                $monthtext = $outputlangs->transnoentitiesnoconv('Month'.$month);
1932
+                $monthtextshort = $outputlangs->transnoentitiesnoconv('MonthShort'.$month);
1933 1933
             }
1934 1934
 //print 'monthtext='.$monthtext.' monthtextshort='.$monthtextshort;
1935 1935
             $ret = str_replace('__b__', $monthtextshort, $ret);
@@ -1940,8 +1940,8 @@  discard block
 block discarded – undo
1940 1940
         if (preg_match('/__a__/i', $format)) {
1941 1941
             $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1942 1942
 
1943
-            $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.
1944
-            $dayweek = $outputlangs->transnoentitiesnoconv('Day' . $w);
1943
+            $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.
1944
+            $dayweek = $outputlangs->transnoentitiesnoconv('Day'.$w);
1945 1945
             $ret = str_replace('__A__', $dayweek, $ret);
1946 1946
             $ret = str_replace('__a__', dol_substr($dayweek, 0, 3), $ret);
1947 1947
         }
@@ -1988,9 +1988,9 @@  discard block
 block discarded – undo
1988 1988
 
1989 1989
         $usealternatemethod = false;
1990 1990
         if ($timestamp <= 0)
1991
-            $usealternatemethod = true;    // <= 1970
1991
+            $usealternatemethod = true; // <= 1970
1992 1992
         if ($timestamp >= 2145913200)
1993
-            $usealternatemethod = true;  // >= 2038
1993
+            $usealternatemethod = true; // >= 2038
1994 1994
 
1995 1995
         if ($usealternatemethod) {
1996 1996
             $arrayinfo = adodb_getdate($timestamp, $fast);
@@ -2050,23 +2050,23 @@  discard block
 block discarded – undo
2050 2050
 
2051 2051
         if (method_exists('DateTime', 'getTimestamp')) {
2052 2052
             if (empty($gm) || $gm === 'server') {
2053
-                $default_timezone = @date_default_timezone_get();  // Example 'Europe/Berlin'
2053
+                $default_timezone = @date_default_timezone_get(); // Example 'Europe/Berlin'
2054 2054
                 $localtz = new DateTimeZone($default_timezone);
2055 2055
             } else if ($gm === 'user') {
2056 2056
 // We use dol_tz_string first because it is more reliable.
2057
-                $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]);  // Example 'Europe/Berlin'
2057
+                $default_timezone = (empty($_SESSION["dol_tz_string"]) ? @date_default_timezone_get() : $_SESSION["dol_tz_string"]); // Example 'Europe/Berlin'
2058 2058
                 try {
2059 2059
                     $localtz = new DateTimeZone($default_timezone);
2060 2060
                 } catch (Exception $e) {
2061
-                    dol_syslog("Warning dol_tz_string contains an invalid value " . $_SESSION["dol_tz_string"], LOG_WARNING);
2061
+                    dol_syslog("Warning dol_tz_string contains an invalid value ".$_SESSION["dol_tz_string"], LOG_WARNING);
2062 2062
                     $default_timezone = @date_default_timezone_get();
2063 2063
                 }
2064 2064
             } else if (strrpos($gm, "tz,") !== false) {
2065
-                $timezone = str_replace("tz,", "", $gm);  // Example 'tz,Europe/Berlin'
2065
+                $timezone = str_replace("tz,", "", $gm); // Example 'tz,Europe/Berlin'
2066 2066
                 try {
2067 2067
                     $localtz = new DateTimeZone($timezone);
2068 2068
                 } catch (Exception $e) {
2069
-                    dol_syslog("Warning passed timezone contains an invalid value " . $timezone, LOG_WARNING);
2069
+                    dol_syslog("Warning passed timezone contains an invalid value ".$timezone, LOG_WARNING);
2070 2070
                 }
2071 2071
             }
2072 2072
 
@@ -2105,8 +2105,8 @@  discard block
 block discarded – undo
2105 2105
         if ($mode == 'gmt')
2106 2106
             $ret = time(); // Time for now at greenwich.
2107 2107
         else if ($mode == 'tzserver') {  // Time for now with PHP server timezone added
2108
-            require_once DOL_BASE_PATH . '/core/lib/date.lib.php';
2109
-            $tzsecond = getServerTimeZoneInt('now');    // Contains tz+dayling saving time
2108
+            require_once DOL_BASE_PATH.'/core/lib/date.lib.php';
2109
+            $tzsecond = getServerTimeZoneInt('now'); // Contains tz+dayling saving time
2110 2110
             $ret = (int) (dol_now('gmt') + ($tzsecond * 3600));
2111 2111
         }
2112 2112
         /* else if ($mode == 'tzref')				// Time for now with parent company timezone is added
@@ -2152,9 +2152,9 @@  discard block
 block discarded – undo
2152 2152
         }
2153 2153
 // Use long or short text unit
2154 2154
         if (empty($shortunit)) {
2155
-            $ret .= ' ' . $textunitlong;
2155
+            $ret .= ' '.$textunitlong;
2156 2156
         } else {
2157
-            $ret .= ' ' . $textunitshort;
2157
+            $ret .= ' '.$textunitshort;
2158 2158
         }
2159 2159
 
2160 2160
         return $ret;
@@ -2182,13 +2182,13 @@  discard block
 block discarded – undo
2182 2182
         $link .= $url;
2183 2183
         $link .= '"';
2184 2184
         if ($target)
2185
-            $link .= ' target="' . $target . '"';
2185
+            $link .= ' target="'.$target.'"';
2186 2186
         $link .= '>';
2187 2187
         if (!preg_match('/^http/i', $url))
2188 2188
             $link .= 'http://';
2189 2189
         $link .= dol_trunc($url, $max);
2190 2190
         $link .= '</a>';
2191
-        return '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png') . ' ' : '') . $link . '</div>';
2191
+        return '<div class="nospan float" style="margin-right: 10px">'.($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png').' ' : '').$link.'</div>';
2192 2192
     }
2193 2193
 
2194 2194
     /**
@@ -2229,9 +2229,9 @@  discard block
 block discarded – undo
2229 2229
                 $type = 'AC_EMAIL';
2230 2230
                 $link = '';
2231 2231
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL))
2232
-                    $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>';
2232
+                    $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>';
2233 2233
                 if ($link)
2234
-                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2234
+                    $newemail = '<div>'.$newemail.' '.$link.'</div>';
2235 2235
             }
2236 2236
         }
2237 2237
         else {
@@ -2241,7 +2241,7 @@  discard block
 block discarded – undo
2241 2241
             }
2242 2242
         }
2243 2243
 
2244
-        $rep = '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("EMail"), 'object_email.png') . ' ' : '') . $newemail . '</div>';
2244
+        $rep = '<div class="nospan float" style="margin-right: 10px">'.($withpicto ? img_picto(Globals::$langs->trans("EMail"), 'object_email.png').' ' : '').$newemail.'</div>';
2245 2245
         if ($hookmanager) {
2246 2246
             $parameters = array('cid' => $cid, 'socid' => $socid, 'addlink' => $addlink, 'picto' => $withpicto);
2247 2247
             $reshook = $hookmanager->executeHooks('printEmail', $parameters, $email);
@@ -2271,26 +2271,26 @@  discard block
 block discarded – undo
2271 2271
 
2272 2272
         if (!empty($type)) {
2273 2273
             $newskype = '<div class="divsocialnetwork inline-block valignmiddle">';
2274
-            $newskype .= img_picto(Globals::$langs->trans(strtoupper($type)), $type . '.png', '', false, 0, 0, '', 'paddingright');
2274
+            $newskype .= img_picto(Globals::$langs->trans(strtoupper($type)), $type.'.png', '', false, 0, 0, '', 'paddingright');
2275 2275
             $newskype .= $value;
2276 2276
             if ($type == 'skype') {
2277 2277
                 $newskype .= '&nbsp;';
2278 2278
                 $newskype .= '<a href="skype:';
2279 2279
                 $newskype .= $value;
2280
-                $newskype .= '?call" alt="' . Globals::$langs->trans("Call") . '&nbsp;' . $value . '" title="' . Globals::$langs->trans("Call") . '&nbsp;' . $value . '">';
2281
-                $newskype .= '<img src="' . DOL_BASE_URI . '/theme/common/skype_callbutton.png" border="0">';
2280
+                $newskype .= '?call" alt="'.Globals::$langs->trans("Call").'&nbsp;'.$value.'" title="'.Globals::$langs->trans("Call").'&nbsp;'.$value.'">';
2281
+                $newskype .= '<img src="'.DOL_BASE_URI.'/theme/common/skype_callbutton.png" border="0">';
2282 2282
                 $newskype .= '</a><a href="skype:';
2283 2283
                 $newskype .= $value;
2284
-                $newskype .= '?chat" alt="' . Globals::$langs->trans("Chat") . '&nbsp;' . $value . '" title="' . Globals::$langs->trans("Chat") . '&nbsp;' . $value . '">';
2285
-                $newskype .= '<img class="paddingleft" src="' . DOL_BASE_URI . '/theme/common/skype_chatbutton.png" border="0">';
2284
+                $newskype .= '?chat" alt="'.Globals::$langs->trans("Chat").'&nbsp;'.$value.'" title="'.Globals::$langs->trans("Chat").'&nbsp;'.$value.'">';
2285
+                $newskype .= '<img class="paddingleft" src="'.DOL_BASE_URI.'/theme/common/skype_chatbutton.png" border="0">';
2286 2286
                 $newskype .= '</a>';
2287 2287
             }
2288 2288
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') {
2289 2289
                 $addlink = 'AC_SKYPE';
2290 2290
                 $link = '';
2291 2291
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE))
2292
-                    $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>';
2293
-                $newskype .= ($link ? ' ' . $link : '');
2292
+                    $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>';
2293
+                $newskype .= ($link ? ' '.$link : '');
2294 2294
             }
2295 2295
             $newskype .= '</div>';
2296 2296
         }
@@ -2334,165 +2334,165 @@  discard block
 block discarded – undo
2334 2334
         if (strtoupper($countrycode) == "FR") {
2335 2335
 // France
2336 2336
             if (dol_strlen($phone) == 10) {
2337
-                $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);
2337
+                $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);
2338 2338
             } elseif (dol_strlen($phone) == 7) {
2339
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 2) . $separ . substr($newphone, 5, 2);
2339
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 2).$separ.substr($newphone, 5, 2);
2340 2340
             } elseif (dol_strlen($phone) == 9) {
2341
-                $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 2) . $separ . substr($newphone, 7, 2);
2341
+                $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 2).$separ.substr($newphone, 7, 2);
2342 2342
             } elseif (dol_strlen($phone) == 11) {
2343
-                $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);
2343
+                $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);
2344 2344
             } elseif (dol_strlen($phone) == 12) {
2345
-                $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);
2345
+                $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);
2346 2346
             }
2347 2347
         } elseif (strtoupper($countrycode) == "CA") {
2348 2348
             if (dol_strlen($phone) == 10) {
2349
-                $newphone = ($separ != '' ? '(' : '') . substr($newphone, 0, 3) . ($separ != '' ? ')' : '') . $separ . substr($newphone, 3, 3) . ($separ != '' ? '-' : '') . substr($newphone, 6, 4);
2349
+                $newphone = ($separ != '' ? '(' : '').substr($newphone, 0, 3).($separ != '' ? ')' : '').$separ.substr($newphone, 3, 3).($separ != '' ? '-' : '').substr($newphone, 6, 4);
2350 2350
             }
2351 2351
         } elseif (strtoupper($countrycode) == "PT") {//Portugal
2352 2352
             if (dol_strlen($phone) == 13) {//ex: +351_ABC_DEF_GHI
2353
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2353
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2354 2354
             }
2355 2355
         } elseif (strtoupper($countrycode) == "SR") {//Suriname
2356 2356
             if (dol_strlen($phone) == 10) {//ex: +597_ABC_DEF
2357
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3);
2357
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3);
2358 2358
             } elseif (dol_strlen($phone) == 11) {//ex: +597_ABC_DEFG
2359
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 4);
2359
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 4);
2360 2360
             }
2361 2361
         } elseif (strtoupper($countrycode) == "DE") {//Allemagne
2362 2362
             if (dol_strlen($phone) == 14) {//ex:  +49_ABCD_EFGH_IJK
2363
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 4) . $separ . substr($newphone, 11, 3);
2363
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 4).$separ.substr($newphone, 11, 3);
2364 2364
             } elseif (dol_strlen($phone) == 13) {//ex: +49_ABC_DEFG_HIJ
2365
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 4) . $separ . substr($newphone, 10, 3);
2365
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 4).$separ.substr($newphone, 10, 3);
2366 2366
             }
2367 2367
         } elseif (strtoupper($countrycode) == "ES") {//Espagne
2368 2368
             if (dol_strlen($phone) == 12) {//ex:  +34_ABC_DEF_GHI
2369
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2369
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2370 2370
             }
2371 2371
         } elseif (strtoupper($countrycode) == "BF") {// Burkina Faso
2372 2372
             if (dol_strlen($phone) == 12) {//ex :  +22 A BC_DE_FG_HI
2373
-                $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);
2373
+                $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);
2374 2374
             }
2375 2375
         } elseif (strtoupper($countrycode) == "RO") {// Roumanie
2376 2376
             if (dol_strlen($phone) == 12) {//ex :  +40 AB_CDE_FG_HI
2377
-                $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);
2377
+                $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);
2378 2378
             }
2379 2379
         } elseif (strtoupper($countrycode) == "TR") {//Turquie
2380 2380
             if (dol_strlen($phone) == 13) {//ex :  +90 ABC_DEF_GHIJ
2381
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
2381
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
2382 2382
             }
2383 2383
         } elseif (strtoupper($countrycode) == "US") {//Etat-Unis
2384 2384
             if (dol_strlen($phone) == 12) {//ex: +1 ABC_DEF_GHIJ
2385
-                $newphone = substr($newphone, 0, 2) . $separ . substr($newphone, 2, 3) . $separ . substr($newphone, 5, 3) . $separ . substr($newphone, 8, 4);
2385
+                $newphone = substr($newphone, 0, 2).$separ.substr($newphone, 2, 3).$separ.substr($newphone, 5, 3).$separ.substr($newphone, 8, 4);
2386 2386
             }
2387 2387
         } elseif (strtoupper($countrycode) == "MX") {//Mexique
2388 2388
             if (dol_strlen($phone) == 12) {//ex: +52 ABCD_EFG_HI
2389
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
2389
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
2390 2390
             } elseif (dol_strlen($phone) == 11) {//ex: +52 AB_CD_EF_GH
2391
-                $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);
2391
+                $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);
2392 2392
             } elseif (dol_strlen($phone) == 13) {//ex: +52 ABC_DEF_GHIJ
2393
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 4);
2393
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 4);
2394 2394
             }
2395 2395
         } elseif (strtoupper($countrycode) == "ML") {//Mali
2396 2396
             if (dol_strlen($phone) == 12) {//ex: +223 AB_CD_EF_GH
2397
-                $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);
2397
+                $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);
2398 2398
             }
2399 2399
         } elseif (strtoupper($countrycode) == "TH") {//Thaïlande
2400 2400
             if (dol_strlen($phone) == 11) {//ex: +66_ABC_DE_FGH
2401
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
2401
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
2402 2402
             } elseif (dol_strlen($phone) == 12) {//ex: +66_A_BCD_EF_GHI
2403
-                $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);
2403
+                $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);
2404 2404
             }
2405 2405
         } elseif (strtoupper($countrycode) == "MU") {//Maurice
2406 2406
             if (dol_strlen($phone) == 11) {//ex: +230_ABC_DE_FG
2407
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 2) . $separ . substr($newphone, 9, 2);
2407
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 2).$separ.substr($newphone, 9, 2);
2408 2408
             } elseif (dol_strlen($phone) == 12) {//ex: +230_ABCD_EF_GH
2409
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 2) . $separ . substr($newphone, 10, 2);
2409
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 2).$separ.substr($newphone, 10, 2);
2410 2410
             }
2411 2411
         } elseif (strtoupper($countrycode) == "ZA") {//Afrique du sud
2412 2412
             if (dol_strlen($phone) == 12) {//ex: +27_AB_CDE_FG_HI
2413
-                $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
+                $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);
2414 2414
             }
2415 2415
         } elseif (strtoupper($countrycode) == "SY") {//Syrie
2416 2416
             if (dol_strlen($phone) == 12) {//ex: +963_AB_CD_EF_GH
2417
-                $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);
2417
+                $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);
2418 2418
             } elseif (dol_strlen($phone) == 13) {//ex: +963_AB_CD_EF_GHI
2419
-                $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);
2419
+                $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);
2420 2420
             }
2421 2421
         } elseif (strtoupper($countrycode) == "AE") {//Emirats Arabes Unis
2422 2422
             if (dol_strlen($phone) == 12) {//ex: +971_ABC_DEF_GH
2423
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 2);
2423
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 2);
2424 2424
             } elseif (dol_strlen($phone) == 13) {//ex: +971_ABC_DEF_GHI
2425
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2425
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2426 2426
             } elseif (dol_strlen($phone) == 14) {//ex: +971_ABC_DEF_GHIK
2427
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 4);
2427
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 4);
2428 2428
             }
2429 2429
         } elseif (strtoupper($countrycode) == "DZ") {//Algérie
2430 2430
             if (dol_strlen($phone) == 13) {//ex: +213_ABC_DEF_GHI
2431
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 3) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2431
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 3).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2432 2432
             }
2433 2433
         } elseif (strtoupper($countrycode) == "BE") {//Belgique
2434 2434
             if (dol_strlen($phone) == 11) {//ex: +32_ABC_DE_FGH
2435
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 2) . $separ . substr($newphone, 8, 3);
2435
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 2).$separ.substr($newphone, 8, 3);
2436 2436
             } elseif (dol_strlen($phone) == 12) {//ex: +32_ABC_DEF_GHI
2437
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2437
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2438 2438
             }
2439 2439
         } elseif (strtoupper($countrycode) == "PF") {//Polynésie française
2440 2440
             if (dol_strlen($phone) == 12) {//ex: +689_AB_CD_EF_GH
2441
-                $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);
2441
+                $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);
2442 2442
             }
2443 2443
         } elseif (strtoupper($countrycode) == "CO") {//Colombie
2444 2444
             if (dol_strlen($phone) == 13) {//ex: +57_ABC_DEF_GH_IJ
2445
-                $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);
2445
+                $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);
2446 2446
             }
2447 2447
         } elseif (strtoupper($countrycode) == "JO") {//Jordanie
2448 2448
             if (dol_strlen($phone) == 12) {//ex: +962_A_BCD_EF_GH
2449
-                $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);
2449
+                $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);
2450 2450
             }
2451 2451
         } elseif (strtoupper($countrycode) == "MG") {//Madagascar
2452 2452
             if (dol_strlen($phone) == 13) {//ex: +261_AB_CD_EF_GHI
2453
-                $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);
2453
+                $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 2454
             }
2455 2455
         } elseif (strtoupper($countrycode) == "GB") {//Royaume uni
2456 2456
             if (dol_strlen($phone) == 13) {//ex: +44_ABCD_EFG_HIJ
2457
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 4) . $separ . substr($newphone, 7, 3) . $separ . substr($newphone, 10, 3);
2457
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 4).$separ.substr($newphone, 7, 3).$separ.substr($newphone, 10, 3);
2458 2458
             }
2459 2459
         } elseif (strtoupper($countrycode) == "CH") {//Suisse
2460 2460
             if (dol_strlen($phone) == 12) {//ex: +41_AB_CDE_FG_HI
2461
-                $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);
2461
+                $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);
2462 2462
             } elseif (dol_strlen($phone) == 15) {// +41_AB_CDE_FGH_IJKL
2463
-                $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);
2463
+                $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);
2464 2464
             }
2465 2465
         } elseif (strtoupper($countrycode) == "TN") {//Tunisie
2466 2466
             if (dol_strlen($phone) == 12) {//ex: +216_AB_CDE_FGH
2467
-                $newphone = substr($newphone, 0, 4) . $separ . substr($newphone, 4, 2) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2467
+                $newphone = substr($newphone, 0, 4).$separ.substr($newphone, 4, 2).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2468 2468
             }
2469 2469
         } elseif (strtoupper($countrycode) == "GF") {//Guyane francaise
2470 2470
             if (dol_strlen($phone) == 13) {//ex: +594_ABC_DE_FG_HI  (ABC=594 de nouveau)
2471
-                $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);
2471
+                $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);
2472 2472
             }
2473 2473
         } elseif (strtoupper($countrycode) == "GP") {//Guadeloupe
2474 2474
             if (dol_strlen($phone) == 13) {//ex: +590_ABC_DE_FG_HI  (ABC=590 de nouveau)
2475
-                $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);
2475
+                $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);
2476 2476
             }
2477 2477
         } elseif (strtoupper($countrycode) == "MQ") {//Martinique
2478 2478
             if (dol_strlen($phone) == 13) {//ex: +596_ABC_DE_FG_HI  (ABC=596 de nouveau)
2479
-                $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);
2479
+                $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);
2480 2480
             }
2481 2481
         } elseif (strtoupper($countrycode) == "IT") {//Italie
2482 2482
             if (dol_strlen($phone) == 12) {//ex: +39_ABC_DEF_GHI
2483
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 3) . $separ . substr($newphone, 6, 3) . $separ . substr($newphone, 9, 3);
2483
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 3).$separ.substr($newphone, 6, 3).$separ.substr($newphone, 9, 3);
2484 2484
             } elseif (dol_strlen($phone) == 13) {//ex: +39_ABC_DEF_GH_IJ
2485
-                $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);
2485
+                $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);
2486 2486
             }
2487 2487
         } elseif (strtoupper($countrycode) == "AU") {//Australie
2488 2488
             if (dol_strlen($phone) == 12) {//ex: +61_A_BCDE_FGHI
2489
-                $newphone = substr($newphone, 0, 3) . $separ . substr($newphone, 3, 1) . $separ . substr($newphone, 4, 4) . $separ . substr($newphone, 8, 4);
2489
+                $newphone = substr($newphone, 0, 3).$separ.substr($newphone, 3, 1).$separ.substr($newphone, 4, 4).$separ.substr($newphone, 8, 4);
2490 2490
             }
2491 2491
         }
2492 2492
         if (!empty($addlink)) { // Link on phone number (+ link to add action if conf->global->AGENDA_ADDACTIONFORPHONE set)
2493 2493
             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
2494
-                $newphone = '<a href="tel:' . $phone . '"';
2495
-                $newphone .= '>' . $phone . '</a>';
2494
+                $newphone = '<a href="tel:'.$phone.'"';
2495
+                $newphone .= '>'.$phone.'</a>';
2496 2496
             } else if (!empty(Globals::$conf->clicktodial->enabled) && $addlink == 'AC_TEL') {  // If click to dial, we use click to dial url
2497 2497
                 if (empty($user->clicktodial_loaded))
2498 2498
                     $user->fetch_clicktodial();
@@ -2516,10 +2516,10 @@  discard block
 block discarded – undo
2516 2516
                     '__PASS__' => $clicktodial_password);
2517 2517
                 $url = make_substitutions($url, $substitarray);
2518 2518
                 $newphonesav = $newphone;
2519
-                $newphone = '<a href="' . $url . '"';
2519
+                $newphone = '<a href="'.$url.'"';
2520 2520
                 if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET))
2521 2521
                     $newphone .= ' target="_blank"';
2522
-                $newphone .= '>' . $newphonesav . '</a>';
2522
+                $newphone .= '>'.$newphonesav.'</a>';
2523 2523
             }
2524 2524
 
2525 2525
 //if (($cid || $socid) && ! empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create)
@@ -2529,9 +2529,9 @@  discard block
 block discarded – undo
2529 2529
                 if ($addlink == 'AC_FAX')
2530 2530
                     $type = 'AC_FAX';
2531 2531
                 if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE))
2532
-                    $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>';
2532
+                    $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>';
2533 2533
                 if ($link)
2534
-                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2534
+                    $newphone = '<div>'.$newphone.' '.$link.'</div>';
2535 2535
             }
2536 2536
         }
2537 2537
 
@@ -2562,7 +2562,7 @@  discard block
 block discarded – undo
2562 2562
                 $rep .= '<div class="nospan float" style="margin-right: 10px">';
2563 2563
             else
2564 2564
                 $rep .= '<span style="margin-right: 10px;">';
2565
-            $rep .= ($withpicto ? img_picto($titlealt, 'object_' . $picto . '.png') . ' ' : '') . $newphone;
2565
+            $rep .= ($withpicto ? img_picto($titlealt, 'object_'.$picto.'.png').' ' : '').$newphone;
2566 2566
             if ($adddivfloat)
2567 2567
                 $rep .= '</div>';
2568 2568
             else
@@ -2589,15 +2589,15 @@  discard block
 block discarded – undo
2589 2589
             $ret .= $ip;
2590 2590
         }
2591 2591
 
2592
-        echo ('<p>DOL_BASE_PATH: ' . DOL_BASE_PATH . '/DOL_BASE_URI: ' . DOL_BASE_URI . '</p>');
2592
+        echo ('<p>DOL_BASE_PATH: '.DOL_BASE_PATH.'/DOL_BASE_URI: '.DOL_BASE_URI.'</p>');
2593 2593
 
2594 2594
         if ($mode != 2) {
2595 2595
             $countrycode = dolGetCountryCodeFromIp($ip);
2596 2596
             if ($countrycode) { // If success, countrycode is us, fr, ...
2597
-                if (file_exists(DOL_BASE_PATH . '/theme/common/flags/' . $countrycode . '.png')) {
2598
-                    $ret .= ' ' . img_picto($countrycode . ' ' . Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI . '/theme/common/flags/' . $countrycode . '.png', '', 1);
2597
+                if (file_exists(DOL_BASE_PATH.'/theme/common/flags/'.$countrycode.'.png')) {
2598
+                    $ret .= ' '.img_picto($countrycode.' '.Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI.'/theme/common/flags/'.$countrycode.'.png', '', 1);
2599 2599
                 } else
2600
-                    $ret .= ' (' . $countrycode . ')';
2600
+                    $ret .= ' ('.$countrycode.')';
2601 2601
             }
2602 2602
         }
2603 2603
 
@@ -2635,7 +2635,7 @@  discard block
 block discarded – undo
2635 2635
 //$ip='24.24.24.24';
2636 2636
 //$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)
2637 2637
 
2638
-            include_once DOL_BASE_PATH . '/core/class/dolgeoip.class.php';
2638
+            include_once DOL_BASE_PATH.'/core/class/dolgeoip.class.php';
2639 2639
             $geoip = new DolGeoIP('country', $datafile);
2640 2640
 //print 'ip='.$ip.' databaseType='.$geoip->gi->databaseType." GEOIP_CITY_EDITION_REV1=".GEOIP_CITY_EDITION_REV1."\n";
2641 2641
 //print "geoip_country_id_by_addr=".geoip_country_id_by_addr($geoip->gi,$ip)."\n";
@@ -2661,7 +2661,7 @@  discard block
 block discarded – undo
2661 2661
             $datafile = Globals::$conf->global->GEOIPMAXMIND_COUNTRY_DATAFILE;
2662 2662
 //$ip='24.24.24.24';
2663 2663
 //$datafile='E:\Mes Sites\Web\Admin1\awstats\maxmind\GeoIP.dat';
2664
-            include_once DOL_BASE_PATH . '/core/class/dolgeoip.class.php';
2664
+            include_once DOL_BASE_PATH.'/core/class/dolgeoip.class.php';
2665 2665
             $geoip = new DolGeoIP('country', $datafile);
2666 2666
             $countrycode = $geoip->getCountryCodeFromIP($ip);
2667 2667
             $ret = $countrycode;
@@ -2716,12 +2716,12 @@  discard block
 block discarded – undo
2716 2716
                     $showomap = 1;
2717 2717
 
2718 2718
                 if ($showgmap) {
2719
-                    $url = dol_buildpath('/google/gmaps.php?mode=' . $mode . '&id=' . $id, 1);
2720
-                    $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '" class="valigntextbottom" src="' . DOL_BASE_URI . '/theme/common/gmap.png"></a>';
2719
+                    $url = dol_buildpath('/google/gmaps.php?mode='.$mode.'&id='.$id, 1);
2720
+                    $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'" class="valigntextbottom" src="'.DOL_BASE_URI.'/theme/common/gmap.png"></a>';
2721 2721
                 }
2722 2722
                 if ($showomap) {
2723
-                    $url = dol_buildpath('/openstreetmap/maps.php?mode=' . $mode . '&id=' . $id, 1);
2724
-                    $out .= ' <a href="' . $url . '" target="_gmaps"><img id="' . $htmlid . '_openstreetmap" class="valigntextbottom" src="' . DOL_BASE_URI . '/theme/common/gmap.png"></a>';
2723
+                    $url = dol_buildpath('/openstreetmap/maps.php?mode='.$mode.'&id='.$id, 1);
2724
+                    $out .= ' <a href="'.$url.'" target="_gmaps"><img id="'.$htmlid.'_openstreetmap" class="valigntextbottom" src="'.DOL_BASE_URI.'/theme/common/gmap.png"></a>';
2725 2725
                 }
2726 2726
             }
2727 2727
         }
@@ -2867,7 +2867,7 @@  discard block
 block discarded – undo
2867 2867
         if ($trunc == 'right') {
2868 2868
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2869 2869
             if (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 ...
2870
-                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
2870
+                return dol_substr($newstring, 0, $size, $stringencoding).($nodot ? '' : '...');
2871 2871
             else
2872 2872
 //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
2873 2873
                 return $string;
@@ -2877,21 +2877,21 @@  discard block
 block discarded – undo
2877 2877
             if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
2878 2878
                 $size1 = round($size / 2);
2879 2879
                 $size2 = round($size / 2);
2880
-                return dol_substr($newstring, 0, $size1, $stringencoding) . '...' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2880
+                return dol_substr($newstring, 0, $size1, $stringencoding).'...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2881 2881
             } else
2882 2882
                 return $string;
2883 2883
         }
2884 2884
         elseif ($trunc == 'left') {
2885 2885
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2886 2886
             if (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 ...
2887
-                return '...' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2887
+                return '...'.dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2888 2888
             else
2889 2889
                 return $string;
2890 2890
         }
2891 2891
         elseif ($trunc == 'wrap') {
2892 2892
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2893 2893
             if (dol_strlen($newstring, $stringencoding) > ($size + 1))
2894
-                return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2894
+                return dol_substr($newstring, 0, $size, $stringencoding)."\n".dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2895 2895
             else
2896 2896
                 return $string;
2897 2897
         } else
@@ -2924,7 +2924,7 @@  discard block
 block discarded – undo
2924 2924
         $url = DOL_BASE_URI;
2925 2925
 
2926 2926
         $theme = Globals::$conf->theme;
2927
-        $path = 'theme/' . $theme;
2927
+        $path = 'theme/'.$theme;
2928 2928
 
2929 2929
 // Define fullpathpicto to use into src
2930 2930
         if ($pictoisfullpath) {
@@ -2973,7 +2973,7 @@  discard block
 block discarded – undo
2973 2973
                     $fakey = 'fa-pencil';
2974 2974
                     $facolor = '#444';
2975 2975
                 } elseif ($pictowithoutext == 'filter') {
2976
-                    $fakey = 'fa-' . $pictowithoutext;
2976
+                    $fakey = 'fa-'.$pictowithoutext;
2977 2977
                 } elseif ($pictowithoutext == 'grip_title' || $pictowithoutext == 'grip') {
2978 2978
                     $fakey = 'fa-arrows';
2979 2979
                 } elseif ($pictowithoutext == 'listlight') {
@@ -3012,15 +3012,15 @@  discard block
 block discarded – undo
3012 3012
                 } elseif ($pictowithoutext == 'jabber') {
3013 3013
                     $fakey = 'fa-comment-o';
3014 3014
                 } else {
3015
-                    $fakey = 'fa-' . $pictowithoutext;
3015
+                    $fakey = 'fa-'.$pictowithoutext;
3016 3016
                     $facolor = '#444';
3017 3017
                     $marginleftonlyshort = 0;
3018 3018
                 }
3019 3019
 
3020 3020
                 if (preg_match('/class="([^"]+)"/', $moreatt, $reg)) {
3021
-                    $morecss .= ($morecss ? ' ' : '') . $reg[1];
3021
+                    $morecss .= ($morecss ? ' ' : '').$reg[1];
3022 3022
                 }
3023
-                $enabledisablehtml = '<span class="fa ' . $fakey . ' ' . ($marginleftonlyshort ? ($marginleftonlyshort == 1 ? 'marginleftonlyshort' : 'marginleftonly') : '') . ' valignmiddle' . ($morecss ? ' ' . $morecss : '') . '" style="' . ($fasize ? ('font-size: ' . $fasize . ';') : '') . ($facolor ? (' color: ' . $facolor . ';') : '') . '" alt="' . dol_escape_htmltag($titlealt) . '"' . (($notitle || empty($title)) ? '' : ' title="' . dol_escape_htmltag($title) . '"') . ($moreatt ? ' ' . $moreatt : '') . '>';
3023
+                $enabledisablehtml = '<span class="fa '.$fakey.' '.($marginleftonlyshort ? ($marginleftonlyshort == 1 ? 'marginleftonlyshort' : 'marginleftonly') : '').' valignmiddle'.($morecss ? ' '.$morecss : '').'" style="'.($fasize ? ('font-size: '.$fasize.';') : '').($facolor ? (' color: '.$facolor.';') : '').'" alt="'.dol_escape_htmltag($titlealt).'"'.(($notitle || empty($title)) ? '' : ' title="'.dol_escape_htmltag($title).'"').($moreatt ? ' '.$moreatt : '').'>';
3024 3024
                 if (!empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
3025 3025
                     $enabledisablehtml .= $titlealt;
3026 3026
                 }
@@ -3030,11 +3030,11 @@  discard block
 block discarded – undo
3030 3030
             }
3031 3031
 
3032 3032
             if (!empty(Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH)) {
3033
-                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH . '/theme/' . $theme; // If the theme does not have the same name as the module
3033
+                $path = Globals::$conf->global->MAIN_OVERWRITE_THEME_PATH.'/theme/'.$theme; // If the theme does not have the same name as the module
3034 3034
             } else if (!empty(Globals::$conf->global->MAIN_OVERWRITE_THEME_RES)) {
3035
-                $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
3035
+                $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
3036 3036
             } else if (!empty(Globals::$conf->modules_parts['theme']) && array_key_exists($theme, Globals::$conf->modules_parts['theme'])) {
3037
-                $path = $theme . '/theme/' . $theme; // If the theme have the same name as the module
3037
+                $path = $theme.'/theme/'.$theme; // If the theme have the same name as the module
3038 3038
             }
3039 3039
 
3040 3040
 // If we ask an image into $url/$mymodule/img (instead of default path)
@@ -3054,15 +3054,15 @@  discard block
 block discarded – undo
3054 3054
                     continue;
3055 3055
                 }
3056 3056
 // This need a lot of time, that's why enabling alternative dir like "custom" dir is not recommanded
3057
-                if (file_exists($dirroot . '/' . $path . '/img/' . $picto)) {
3057
+                if (file_exists($dirroot.'/'.$path.'/img/'.$picto)) {
3058 3058
                     //$url = DOL_BASE_URI . Globals::$conf->file->dol_url_root[$type];
3059
-                    $url = DOL_BASE_URI . Globals::$conf->file->dol_url_root[$type];
3059
+                    $url = DOL_BASE_URI.Globals::$conf->file->dol_url_root[$type];
3060 3060
                     break;
3061 3061
                 }
3062 3062
             }
3063 3063
 
3064 3064
 // $url is '' or '/custom', $path is current theme or
3065
-            $fullpathpicto = $url . '/' . $path . '/img/' . $picto;
3065
+            $fullpathpicto = $url.'/'.$path.'/img/'.$picto;
3066 3066
         }
3067 3067
 
3068 3068
         if ($srconly) {
@@ -3070,7 +3070,7 @@  discard block
 block discarded – undo
3070 3070
         }
3071 3071
 
3072 3072
 // tag title is used for tooltip on <a>, tag alt can be used with very simple text on image for bind people
3073
-        return '<img src="' . $fullpathpicto . '" alt="' . dol_escape_htmltag($alt) . '"' . (($notitle || empty($titlealt)) ? '' : ' title="' . dol_escape_htmltag($titlealt) . '"') . ($moreatt ? ' ' . $moreatt : ' class="inline-block' . ($morecss ? ' ' . $morecss : '') . '"') . '>'; // Alt is used for accessibility, title for popup
3073
+        return '<img src="'.$fullpathpicto.'" alt="'.dol_escape_htmltag($alt).'"'.(($notitle || empty($titlealt)) ? '' : ' title="'.dol_escape_htmltag($titlealt).'"').($moreatt ? ' '.$moreatt : ' class="inline-block'.($morecss ? ' '.$morecss : '').'"').'>'; // Alt is used for accessibility, title for popup
3074 3074
     }
3075 3075
 
3076 3076
     /**
@@ -3088,7 +3088,7 @@  discard block
 block discarded – undo
3088 3088
      */
3089 3089
     static function img_object($titlealt, $picto, $moreatt = '', $pictoisfullpath = false, $srconly = 0, $notitle = 0)
3090 3090
     {
3091
-        return img_picto($titlealt, 'object_' . $picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
3091
+        return img_picto($titlealt, 'object_'.$picto, $moreatt, $pictoisfullpath, $srconly, $notitle);
3092 3092
     }
3093 3093
 
3094 3094
     /**
@@ -3109,7 +3109,7 @@  discard block
 block discarded – undo
3109 3109
             $picto .= '.png';
3110 3110
 
3111 3111
 //$path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3112
-        $path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3112
+        $path = DOL_BASE_URI.'/theme/'.Globals::$conf->theme.'/img/weather/'.$picto;
3113 3113
 
3114 3114
         return img_picto($titlealt, $path, $moreatt, 1);
3115 3115
     }
@@ -3135,10 +3135,10 @@  discard block
 block discarded – undo
3135 3135
             $path = $picto;
3136 3136
         else {
3137 3137
 //$path = DOL_BASE_URI . '/theme/common/' . $picto;
3138
-            $path = DOL_BASE_URI . '/theme/common/' . $picto;
3138
+            $path = DOL_BASE_URI.'/theme/common/'.$picto;
3139 3139
 
3140 3140
             if (!empty(Globals::$conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
3141
-                $themepath = DOL_BASE_PATH . 'theme/' . Globals::$conf->theme . '/img/' . $picto;
3141
+                $themepath = DOL_BASE_PATH.'theme/'.Globals::$conf->theme.'/img/'.$picto;
3142 3142
 
3143 3143
                 if (file_exists($themepath))
3144 3144
                     $path = $themepath;
@@ -3176,14 +3176,14 @@  discard block
 block discarded – undo
3176 3176
                 $numaction = 3;
3177 3177
                 $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeContactDone');
3178 3178
             } else {
3179
-                $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeStatus ' . $numaction);
3179
+                $titlealt = Globals::$langs->transnoentitiesnoconv('ChangeStatus '.$numaction);
3180 3180
                 $numaction = 0;
3181 3181
             }
3182 3182
         }
3183 3183
         if (!is_numeric($numaction))
3184 3184
             $numaction = 0;
3185 3185
 
3186
-        return img_picto($titlealt, 'stcomm' . $numaction . '.png');
3186
+        return img_picto($titlealt, 'stcomm'.$numaction.'.png');
3187 3187
     }
3188 3188
 
3189 3189
     /**
@@ -3200,7 +3200,7 @@  discard block
 block discarded – undo
3200 3200
         if ($titlealt == 'default')
3201 3201
             $titlealt = Globals::$langs->trans('Show');
3202 3202
 
3203
-        return img_picto($titlealt, 'pdf' . $size . '.png');
3203
+        return img_picto($titlealt, 'pdf'.$size.'.png');
3204 3204
     }
3205 3205
 
3206 3206
     /**
@@ -3252,7 +3252,7 @@  discard block
 block discarded – undo
3252 3252
         if ($titlealt == 'default')
3253 3253
             $titlealt = Globals::$langs->trans('Modify');
3254 3254
 
3255
-        return img_picto($titlealt, 'edit.png', ($float ? 'style="float: ' . (Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
3255
+        return img_picto($titlealt, 'edit.png', ($float ? 'style="float: '.(Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right').'"' : "").($other ? ' '.$other : ''));
3256 3256
     }
3257 3257
 
3258 3258
     /**
@@ -3270,7 +3270,7 @@  discard block
 block discarded – undo
3270 3270
         if ($titlealt == 'default')
3271 3271
             $titlealt = Globals::$langs->trans('View');
3272 3272
 
3273
-        $moreatt = ($float ? 'style="float: right" ' : '') . $other;
3273
+        $moreatt = ($float ? 'style="float: right" ' : '').$other;
3274 3274
 
3275 3275
         return img_picto($titlealt, 'view.png', $moreatt);
3276 3276
     }
@@ -3343,7 +3343,7 @@  discard block
 block discarded – undo
3343 3343
                 $usealttitle = Globals::$langs->trans('Info');
3344 3344
         }
3345 3345
 
3346
-        return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
3346
+        return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;'.($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')).'"');
3347 3347
     }
3348 3348
 
3349 3349
     /**
@@ -3377,7 +3377,7 @@  discard block
 block discarded – undo
3377 3377
             $titlealt = Globals::$langs->trans('Warning');
3378 3378
 
3379 3379
 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
3380
-        return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
3380
+        return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt) : ''));
3381 3381
     }
3382 3382
 
3383 3383
     /**
@@ -3411,7 +3411,7 @@  discard block
 block discarded – undo
3411 3411
             $titlealt = Globals::$langs->trans('Next');
3412 3412
 
3413 3413
 //return img_picto($titlealt, 'next.png', $moreatt);
3414
-        return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
3414
+        return '<span class="fa fa-chevron-right paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
3415 3415
     }
3416 3416
 
3417 3417
     /**
@@ -3429,7 +3429,7 @@  discard block
 block discarded – undo
3429 3429
             $titlealt = Globals::$langs->trans('Previous');
3430 3430
 
3431 3431
 //return img_picto($titlealt, 'previous.png', $moreatt);
3432
-        return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
3432
+        return '<span class="fa fa-chevron-left paddingright paddingleft" title="'.dol_escape_htmltag($titlealt).'"></span>';
3433 3433
     }
3434 3434
 
3435 3435
     /**
@@ -3447,7 +3447,7 @@  discard block
 block discarded – undo
3447 3447
         if ($titlealt == 'default')
3448 3448
             $titlealt = Globals::$langs->trans('Down');
3449 3449
 
3450
-        return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
3450
+        return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown'.($moreclass ? " ".$moreclass : "").'"');
3451 3451
     }
3452 3452
 
3453 3453
     /**
@@ -3465,7 +3465,7 @@  discard block
 block discarded – undo
3465 3465
         if ($titlealt == 'default')
3466 3466
             $titlealt = Globals::$langs->trans('Up');
3467 3467
 
3468
-        return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
3468
+        return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup'.($moreclass ? " ".$moreclass : "").'"');
3469 3469
     }
3470 3470
 
3471 3471
     /**
@@ -3548,7 +3548,7 @@  discard block
 block discarded – undo
3548 3548
             $brand = 'credit-card';
3549 3549
         }
3550 3550
 
3551
-        return '<span class="fa fa-' . $brand . ' fa-2x fa-fw"></span>';
3551
+        return '<span class="fa fa-'.$brand.' fa-2x fa-fw"></span>';
3552 3552
     }
3553 3553
 
3554 3554
     /**
@@ -3561,17 +3561,17 @@  discard block
 block discarded – undo
3561 3561
      */
3562 3562
     static function img_mime($file, $titlealt = '', $morecss = '')
3563 3563
     {
3564
-        require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
3564
+        require_once DOL_BASE_PATH.'/core/lib/files.lib.php';
3565 3565
 
3566 3566
         $mimetype = dol_mimetype($file, '', 1);
3567 3567
         $mimeimg = dol_mimetype($file, '', 2);
3568 3568
         $mimefa = dol_mimetype($file, '', 4);
3569 3569
 
3570 3570
         if (empty($titlealt))
3571
-            $titlealt = 'Mime type: ' . $mimetype;
3571
+            $titlealt = 'Mime type: '.$mimetype;
3572 3572
 
3573 3573
 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
3574
-        return '<i class="fa fa-' . $mimefa . ' paddingright"></i>';
3574
+        return '<i class="fa fa-'.$mimefa.' paddingright"></i>';
3575 3575
     }
3576 3576
 
3577 3577
     /**
@@ -3586,7 +3586,7 @@  discard block
 block discarded – undo
3586 3586
      */
3587 3587
     static function img_phone($titlealt = 'default', $option = 0)
3588 3588
     {
3589
-        dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
3589
+        dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
3590 3590
 
3591 3591
        // global Globals::$conf, Globals::$langs;
3592 3592
 
@@ -3617,8 +3617,8 @@  discard block
 block discarded – undo
3617 3617
 
3618 3618
         $img = img_picto($titlealt, 'search.png', $other, false, 1);
3619 3619
 
3620
-        $input = '<input type="image" class="liste_titre" name="button_search" src="' . $img . '" ';
3621
-        $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
3620
+        $input = '<input type="image" class="liste_titre" name="button_search" src="'.$img.'" ';
3621
+        $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
3622 3622
 
3623 3623
         return $input;
3624 3624
     }
@@ -3639,8 +3639,8 @@  discard block
 block discarded – undo
3639 3639
 
3640 3640
         $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
3641 3641
 
3642
-        $input = '<input type="image" class="liste_titre" name="button_removefilter" src="' . $img . '" ';
3643
-        $input .= 'value="' . dol_escape_htmltag($titlealt) . '" title="' . dol_escape_htmltag($titlealt) . '" >';
3642
+        $input = '<input type="image" class="liste_titre" name="button_removefilter" src="'.$img.'" ';
3643
+        $input .= 'value="'.dol_escape_htmltag($titlealt).'" title="'.dol_escape_htmltag($titlealt).'" >';
3644 3644
 
3645 3645
         return $input;
3646 3646
     }
@@ -3660,10 +3660,10 @@  discard block
 block discarded – undo
3660 3660
        // global Globals::$conf, Globals::$langs;
3661 3661
 
3662 3662
         if ($infoonimgalt) {
3663
-            return img_picto($text, 'info', 'class="hideonsmartphone' . ($morecss ? ' ' . $morecss : '') . '"');
3663
+            return img_picto($text, 'info', 'class="hideonsmartphone'.($morecss ? ' '.$morecss : '').'"');
3664 3664
         }
3665 3665
 
3666
-        return ($nodiv ? '' : '<div class="' . (empty($admin) ? '' : ($admin == '1' ? 'info' : $admin)) . ' hideonsmartphone' . ($morecss ? ' ' . $morecss : '') . '">') . '<span class="fa fa-info-circle" title="' . dol_escape_htmltag($admin ? Globals::$langs->trans('InfoAdmin') : Globals::$langs->trans('Note')) . '"></span> ' . $text . ($nodiv ? '' : '</div>');
3666
+        return ($nodiv ? '' : '<div class="'.(empty($admin) ? '' : ($admin == '1' ? 'info' : $admin)).' hideonsmartphone'.($morecss ? ' '.$morecss : '').'">').'<span class="fa fa-info-circle" title="'.dol_escape_htmltag($admin ? Globals::$langs->trans('InfoAdmin') : Globals::$langs->trans('Note')).'"></span> '.$text.($nodiv ? '' : '</div>');
3667 3667
     }
3668 3668
 
3669 3669
     /**
@@ -3688,7 +3688,7 @@  discard block
 block discarded – undo
3688 3688
 
3689 3689
 // Si erreur intervenue avant chargement langue
3690 3690
         if (!Globals::$langs) {
3691
-            require_once DOL_BASE_PATH . '/core/class/translate.class.php';
3691
+            require_once DOL_BASE_PATH.'/core/class/translate.class.php';
3692 3692
             Globals::$langs = new Translate('', Globals::$conf);
3693 3693
             Globals::$langs->load("main");
3694 3694
         }
@@ -3696,51 +3696,51 @@  discard block
 block discarded – undo
3696 3696
         Globals::$langs->loadLangs(array('main', 'errors'));
3697 3697
 
3698 3698
         if ($_SERVER['DOCUMENT_ROOT']) {    // Mode web
3699
-            $out .= Globals::$langs->trans("DolibarrHasDetectedError") . ".<br>\n";
3699
+            $out .= Globals::$langs->trans("DolibarrHasDetectedError").".<br>\n";
3700 3700
             if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL))
3701 3701
                 $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";
3702
-            $out .= Globals::$langs->trans("InformationToHelpDiagnose") . ":<br>\n";
3702
+            $out .= Globals::$langs->trans("InformationToHelpDiagnose").":<br>\n";
3703 3703
 
3704
-            $out .= "<b>" . Globals::$langs->trans("Date") . ":</b> " . dol_print_date(time(), 'dayhourlog') . "<br>\n";
3705
-            $out .= "<b>" . Globals::$langs->trans("Dolibarr") . ":</b> " . DOL_VERSION . "<br>\n";
3704
+            $out .= "<b>".Globals::$langs->trans("Date").":</b> ".dol_print_date(time(), 'dayhourlog')."<br>\n";
3705
+            $out .= "<b>".Globals::$langs->trans("Dolibarr").":</b> ".DOL_VERSION."<br>\n";
3706 3706
             if (isset(Globals::$conf->global->MAIN_FEATURES_LEVEL))
3707
-                $out .= "<b>" . Globals::$langs->trans("LevelOfFeature") . ":</b> " . Globals::$conf->global->MAIN_FEATURES_LEVEL . "<br>\n";
3707
+                $out .= "<b>".Globals::$langs->trans("LevelOfFeature").":</b> ".Globals::$conf->global->MAIN_FEATURES_LEVEL."<br>\n";
3708 3708
             if (function_exists("phpversion")) {
3709
-                $out .= "<b>" . Globals::$langs->trans("PHP") . ":</b> " . phpversion() . "<br>\n";
3709
+                $out .= "<b>".Globals::$langs->trans("PHP").":</b> ".phpversion()."<br>\n";
3710 3710
             }
3711
-            $out .= "<b>" . Globals::$langs->trans("Server") . ":</b> " . $_SERVER["SERVER_SOFTWARE"] . "<br>\n";
3711
+            $out .= "<b>".Globals::$langs->trans("Server").":</b> ".$_SERVER["SERVER_SOFTWARE"]."<br>\n";
3712 3712
             if (function_exists("php_uname")) {
3713
-                $out .= "<b>" . Globals::$langs->trans("OS") . ":</b> " . php_uname() . "<br>\n";
3713
+                $out .= "<b>".Globals::$langs->trans("OS").":</b> ".php_uname()."<br>\n";
3714 3714
             }
3715
-            $out .= "<b>" . Globals::$langs->trans("UserAgent") . ":</b> " . $_SERVER["HTTP_USER_AGENT"] . "<br>\n";
3715
+            $out .= "<b>".Globals::$langs->trans("UserAgent").":</b> ".$_SERVER["HTTP_USER_AGENT"]."<br>\n";
3716 3716
             $out .= "<br>\n";
3717
-            $out .= "<b>" . Globals::$langs->trans("RequestedUrl") . ":</b> " . dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8') . "<br>\n";
3718
-            $out .= "<b>" . Globals::$langs->trans("Referer") . ":</b> " . (isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '') . "<br>\n";
3719
-            $out .= "<b>" . Globals::$langs->trans("MenuManager") . ":</b> " . (isset(Globals::$conf->standard_menu) ? Globals::$conf->standard_menu : '') . "<br>\n";
3717
+            $out .= "<b>".Globals::$langs->trans("RequestedUrl").":</b> ".dol_htmlentities($_SERVER["REQUEST_URI"], ENT_COMPAT, 'UTF-8')."<br>\n";
3718
+            $out .= "<b>".Globals::$langs->trans("Referer").":</b> ".(isset($_SERVER["HTTP_REFERER"]) ? dol_htmlentities($_SERVER["HTTP_REFERER"], ENT_COMPAT, 'UTF-8') : '')."<br>\n";
3719
+            $out .= "<b>".Globals::$langs->trans("MenuManager").":</b> ".(isset(Globals::$conf->standard_menu) ? Globals::$conf->standard_menu : '')."<br>\n";
3720 3720
             $out .= "<br>\n";
3721
-            $syslog .= "url=" . dol_escape_htmltag($_SERVER["REQUEST_URI"]);
3722
-            $syslog .= ", query_string=" . dol_escape_htmltag($_SERVER["QUERY_STRING"]);
3721
+            $syslog .= "url=".dol_escape_htmltag($_SERVER["REQUEST_URI"]);
3722
+            $syslog .= ", query_string=".dol_escape_htmltag($_SERVER["QUERY_STRING"]);
3723 3723
         } else {                              // Mode CLI
3724
-            $out .= '> ' . Globals::$langs->transnoentities("ErrorInternalErrorDetected") . ":\n" . $argv[0] . "\n";
3725
-            $syslog .= "pid=" . dol_getmypid();
3724
+            $out .= '> '.Globals::$langs->transnoentities("ErrorInternalErrorDetected").":\n".$argv[0]."\n";
3725
+            $syslog .= "pid=".dol_getmypid();
3726 3726
         }
3727 3727
 
3728 3728
         if (is_object($db)) {
3729 3729
             if ($_SERVER['DOCUMENT_ROOT']) {  // Mode web
3730
-                $out .= "<b>" . Globals::$langs->trans("DatabaseTypeManager") . ":</b> " . $db->type . "<br>\n";
3731
-                $out .= "<b>" . Globals::$langs->trans("RequestLastAccessInError") . ":</b> " . ($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : Globals::$langs->trans("ErrorNoRequestInError")) . "<br>\n";
3732
-                $out .= "<b>" . Globals::$langs->trans("ReturnCodeLastAccessInError") . ":</b> " . ($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : Globals::$langs->trans("ErrorNoRequestInError")) . "<br>\n";
3733
-                $out .= "<b>" . Globals::$langs->trans("InformationLastAccessInError") . ":</b> " . ($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : Globals::$langs->trans("ErrorNoRequestInError")) . "<br>\n";
3730
+                $out .= "<b>".Globals::$langs->trans("DatabaseTypeManager").":</b> ".$db->type."<br>\n";
3731
+                $out .= "<b>".Globals::$langs->trans("RequestLastAccessInError").":</b> ".($db->lastqueryerror() ? dol_escape_htmltag($db->lastqueryerror()) : Globals::$langs->trans("ErrorNoRequestInError"))."<br>\n";
3732
+                $out .= "<b>".Globals::$langs->trans("ReturnCodeLastAccessInError").":</b> ".($db->lasterrno() ? dol_escape_htmltag($db->lasterrno()) : Globals::$langs->trans("ErrorNoRequestInError"))."<br>\n";
3733
+                $out .= "<b>".Globals::$langs->trans("InformationLastAccessInError").":</b> ".($db->lasterror() ? dol_escape_htmltag($db->lasterror()) : Globals::$langs->trans("ErrorNoRequestInError"))."<br>\n";
3734 3734
                 $out .= "<br>\n";
3735 3735
             } else {                            // Mode CLI
3736 3736
 // No dol_escape_htmltag for output, we are in CLI mode
3737
-                $out .= '> ' . Globals::$langs->transnoentities("DatabaseTypeManager") . ":\n" . $db->type . "\n";
3738
-                $out .= '> ' . Globals::$langs->transnoentities("RequestLastAccessInError") . ":\n" . ($db->lastqueryerror() ? $db->lastqueryerror() : Globals::$langs->transnoentities("ErrorNoRequestInError")) . "\n";
3739
-                $out .= '> ' . Globals::$langs->transnoentities("ReturnCodeLastAccessInError") . ":\n" . ($db->lasterrno() ? $db->lasterrno() : Globals::$langs->transnoentities("ErrorNoRequestInError")) . "\n";
3740
-                $out .= '> ' . Globals::$langs->transnoentities("InformationLastAccessInError") . ":\n" . ($db->lasterror() ? $db->lasterror() : Globals::$langs->transnoentities("ErrorNoRequestInError")) . "\n";
3737
+                $out .= '> '.Globals::$langs->transnoentities("DatabaseTypeManager").":\n".$db->type."\n";
3738
+                $out .= '> '.Globals::$langs->transnoentities("RequestLastAccessInError").":\n".($db->lastqueryerror() ? $db->lastqueryerror() : Globals::$langs->transnoentities("ErrorNoRequestInError"))."\n";
3739
+                $out .= '> '.Globals::$langs->transnoentities("ReturnCodeLastAccessInError").":\n".($db->lasterrno() ? $db->lasterrno() : Globals::$langs->transnoentities("ErrorNoRequestInError"))."\n";
3740
+                $out .= '> '.Globals::$langs->transnoentities("InformationLastAccessInError").":\n".($db->lasterror() ? $db->lasterror() : Globals::$langs->transnoentities("ErrorNoRequestInError"))."\n";
3741 3741
             }
3742
-            $syslog .= ", sql=" . $db->lastquery();
3743
-            $syslog .= ", db_error=" . $db->lasterror();
3742
+            $syslog .= ", sql=".$db->lastquery();
3743
+            $syslog .= ", db_error=".$db->lasterror();
3744 3744
         }
3745 3745
 
3746 3746
         if ($error || $errors) {
@@ -3760,31 +3760,31 @@  discard block
 block discarded – undo
3760 3760
                 if (empty($msg))
3761 3761
                     continue;
3762 3762
                 if ($_SERVER['DOCUMENT_ROOT']) {  // Mode web
3763
-                    $out .= "<b>" . Globals::$langs->trans("Message") . ":</b> " . dol_escape_htmltag($msg) . "<br>\n";
3763
+                    $out .= "<b>".Globals::$langs->trans("Message").":</b> ".dol_escape_htmltag($msg)."<br>\n";
3764 3764
                 } else {                        // Mode CLI
3765
-                    $out .= '> ' . Globals::$langs->transnoentities("Message") . ":\n" . $msg . "\n";
3765
+                    $out .= '> '.Globals::$langs->transnoentities("Message").":\n".$msg."\n";
3766 3766
                 }
3767
-                $syslog .= ", msg=" . $msg;
3767
+                $syslog .= ", msg=".$msg;
3768 3768
             }
3769 3769
         }
3770 3770
         if (empty($dolibarr_main_prod) && $_SERVER['DOCUMENT_ROOT'] && function_exists('xdebug_print_function_stack') && function_exists('xdebug_call_file')) {
3771 3771
             xdebug_print_function_stack();
3772
-            $out .= '<b>XDebug informations:</b>' . "<br>\n";
3773
-            $out .= 'File: ' . xdebug_call_file() . "<br>\n";
3774
-            $out .= 'Line: ' . xdebug_call_line() . "<br>\n";
3775
-            $out .= 'Function: ' . xdebug_call_function() . "<br>\n";
3772
+            $out .= '<b>XDebug informations:</b>'."<br>\n";
3773
+            $out .= 'File: '.xdebug_call_file()."<br>\n";
3774
+            $out .= 'Line: '.xdebug_call_line()."<br>\n";
3775
+            $out .= 'Function: '.xdebug_call_function()."<br>\n";
3776 3776
             $out .= "<br>\n";
3777 3777
         }
3778 3778
 
3779 3779
         if (empty($dolibarr_main_prod))
3780 3780
             print $out;
3781 3781
         else {
3782
-            print Globals::$langs->trans("DolibarrHasDetectedError") . '. ';
3782
+            print Globals::$langs->trans("DolibarrHasDetectedError").'. ';
3783 3783
             print Globals::$langs->trans("YouCanSetOptionDolibarrMainProdToZero");
3784 3784
             define("MAIN_CORE_ERROR", 1);
3785 3785
         }
3786 3786
 //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.';
3787
-        dol_syslog("Error " . $syslog, LOG_ERR);
3787
+        dol_syslog("Error ".$syslog, LOG_ERR);
3788 3788
     }
3789 3789
 
3790 3790
     /**
@@ -3807,13 +3807,13 @@  discard block
 block discarded – undo
3807 3807
         Globals::$langs->load("errors");
3808 3808
         $now = dol_now();
3809 3809
 
3810
-        print '<br><div class="center login_main_message"><div class="' . $morecss . '">';
3811
-        print Globals::$langs->trans("ErrorContactEMail", $email, $prefixcode . dol_print_date($now, '%Y%m%d'));
3810
+        print '<br><div class="center login_main_message"><div class="'.$morecss.'">';
3811
+        print Globals::$langs->trans("ErrorContactEMail", $email, $prefixcode.dol_print_date($now, '%Y%m%d'));
3812 3812
         if ($errormessage)
3813
-            print '<br><br>' . $errormessage;
3813
+            print '<br><br>'.$errormessage;
3814 3814
         if (is_array($errormessages) && count($errormessages)) {
3815 3815
             foreach ($errormessages as $mesgtoshow) {
3816
-                print '<br><br>' . $mesgtoshow;
3816
+                print '<br><br>'.$mesgtoshow;
3817 3817
             }
3818 3818
         }
3819 3819
         print '</div></div>';
@@ -3871,16 +3871,16 @@  discard block
 block discarded – undo
3871 3871
         }
3872 3872
 
3873 3873
         $tmpsortfield = explode(',', $sortfield);
3874
-        $sortfield1 = trim($tmpsortfield[0]);    // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
3874
+        $sortfield1 = trim($tmpsortfield[0]); // If $sortfield is 'd.datep,d.id', it becomes 'd.datep'
3875 3875
         $tmpfield = explode(',', $field);
3876
-        $field1 = trim($tmpfield[0]);            // If $field is 'd.datep,d.id', it becomes 'd.datep'
3876
+        $field1 = trim($tmpfield[0]); // If $field is 'd.datep,d.id', it becomes 'd.datep'
3877 3877
 //var_dump('field='.$field.' field1='.$field1.' sortfield='.$sortfield.' sortfield1='.$sortfield1);
3878 3878
 // If field is used as sort criteria we use a specific css class liste_titre_sel
3879 3879
 // Example if (sortfield,field)=("nom","xxx.nom") or (sortfield,field)=("nom","nom")
3880 3880
         if ($field1 && ($sortfield1 == $field1 || $sortfield1 == preg_replace("/^[^\.]+\./", "", $field1))) {
3881
-            $out .= '<' . $tag . ' class="' . $prefix . 'liste_titre_sel" ' . $moreattrib . '>';
3881
+            $out .= '<'.$tag.' class="'.$prefix.'liste_titre_sel" '.$moreattrib.'>';
3882 3882
         } else {
3883
-            $out .= '<' . $tag . ' class="' . $prefix . 'liste_titre" ' . $moreattrib . '>';
3883
+            $out .= '<'.$tag.' class="'.$prefix.'liste_titre" '.$moreattrib.'>';
3884 3884
         }
3885 3885
 
3886 3886
         if (empty($thead) && $field && empty($disablesortlink)) {    // If this is a sort field
@@ -3888,7 +3888,7 @@  discard block
 block discarded – undo
3888 3888
             $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
3889 3889
             $options = preg_replace('/&+/i', '&', $options);
3890 3890
             if (!preg_match('/^&/', $options)) {
3891
-                $options = '&' . $options;
3891
+                $options = '&'.$options;
3892 3892
             }
3893 3893
 
3894 3894
             $sortordertouseinlink = '';
@@ -3906,7 +3906,7 @@  discard block
 block discarded – undo
3906 3906
                 }
3907 3907
             }
3908 3908
             $sortordertouseinlink = preg_replace('/,$/', '', $sortordertouseinlink);
3909
-            $out .= '<a class="reposition" href="' . $file . '?sortfield=' . $field . '&sortorder=' . $sortordertouseinlink . '&begin=' . $begin . $options . '">';
3909
+            $out .= '<a class="reposition" href="'.$file.'?sortfield='.$field.'&sortorder='.$sortordertouseinlink.'&begin='.$begin.$options.'">';
3910 3910
         }
3911 3911
 
3912 3912
         if ($tooltip) {
@@ -3924,7 +3924,7 @@  discard block
 block discarded – undo
3924 3924
             $options = preg_replace('/sortorder=([a-zA-Z0-9,\s\.]+)/i', '', $options);
3925 3925
             $options = preg_replace('/&+/i', '&', $options);
3926 3926
             if (!preg_match('/^&/', $options)) {
3927
-                $options = '&' . $options;
3927
+                $options = '&'.$options;
3928 3928
             }
3929 3929
 
3930 3930
             if (!$sortorder || $field1 != $sortfield1) {
@@ -3934,19 +3934,19 @@  discard block
 block discarded – undo
3934 3934
                 if (preg_match('/^DESC/', $sortorder)) {
3935 3935
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",0).'</a>';
3936 3936
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",1).'</a>';
3937
-                    $sortimg .= '<span class="nowrap">' . img_up("Z-A", 0) . '</span>';
3937
+                    $sortimg .= '<span class="nowrap">'.img_up("Z-A", 0).'</span>';
3938 3938
                 }
3939 3939
                 if (preg_match('/^ASC/', $sortorder)) {
3940 3940
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=asc&begin='.$begin.$options.'">'.img_down("A-Z",1).'</a>';
3941 3941
                     //$out.= '<a href="'.$file.'?sortfield='.$field.'&sortorder=desc&begin='.$begin.$options.'">'.img_up("Z-A",0).'</a>';
3942
-                    $sortimg .= '<span class="nowrap">' . img_down("A-Z", 0) . '</span>';
3942
+                    $sortimg .= '<span class="nowrap">'.img_down("A-Z", 0).'</span>';
3943 3943
                 }
3944 3944
             }
3945 3945
         }
3946 3946
 
3947 3947
         $out .= $sortimg;
3948 3948
 
3949
-        $out .= '</' . $tag . '>';
3949
+        $out .= '</'.$tag.'>';
3950 3950
 
3951 3951
         return $out;
3952 3952
     }
@@ -3961,9 +3961,9 @@  discard block
 block discarded – undo
3961 3961
      */
3962 3962
     static function print_titre($title)
3963 3963
     {
3964
-        dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
3964
+        dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
3965 3965
 
3966
-        print '<div class="titre">' . $title . '</div>';
3966
+        print '<div class="titre">'.$title.'</div>';
3967 3967
     }
3968 3968
 
3969 3969
     /**
@@ -4006,20 +4006,20 @@  discard block
 block discarded – undo
4006 4006
         }
4007 4007
 
4008 4008
         $return .= "\n";
4009
-        $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
4009
+        $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
4010 4010
         if ($picto) {
4011
-            $return .= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">' . img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath) . '</td>';
4011
+            $return .= '<td class="nobordernopadding widthpictotitle opacityhigh" valign="middle">'.img_picto('', $picto, 'class="valignmiddle widthpictotitle pictotitle"', $pictoisfullpath).'</td>';
4012 4012
         }
4013 4013
         $return .= '<td class="nobordernopadding valignmiddle">';
4014
-        $return .= '<div class="titre inline-block">' . $titre . '</div>';
4014
+        $return .= '<div class="titre inline-block">'.$titre.'</div>';
4015 4015
         $return .= '</td>';
4016 4016
         if (dol_strlen($morehtmlcenter)) {
4017
-            $return .= '<td class="nobordernopadding" align="center" valign="middle">' . $morehtmlcenter . '</td>';
4017
+            $return .= '<td class="nobordernopadding" align="center" valign="middle">'.$morehtmlcenter.'</td>';
4018 4018
         }
4019 4019
         if (dol_strlen($morehtmlright)) {
4020
-            $return .= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">' . $morehtmlright . '</td>';
4020
+            $return .= '<td class="nobordernopadding titre_right wordbreak" align="right" valign="middle">'.$morehtmlright.'</td>';
4021 4021
         }
4022
-        $return .= '</tr></table>' . "\n";
4022
+        $return .= '</tr></table>'."\n";
4023 4023
 
4024 4024
         return $return;
4025 4025
     }
@@ -4067,29 +4067,29 @@  discard block
 block discarded – undo
4067 4067
 //print 'totalnboflines='.$totalnboflines.'-savlimit='.$savlimit.'-limit='.$limit.'-num='.$num.'-nextpage='.$nextpage;
4068 4068
 
4069 4069
         print "\n";
4070
-        print "<!-- Begin title '" . $titre . "' -->\n";
4071
-        print '<table border="0" class="centpercent notopnoleftnoright' . ($morecss ? ' ' . $morecss : '') . '" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
4070
+        print "<!-- Begin title '".$titre."' -->\n";
4071
+        print '<table border="0" class="centpercent notopnoleftnoright'.($morecss ? ' '.$morecss : '').'" style="margin-bottom: 6px;"><tr>'; // maring bottom must be same than into load_fiche_tire
4072 4072
 // Left
4073 4073
 //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
4074 4074
         print '<td class="nobordernopadding valignmiddle">';
4075 4075
         if ($picto && $titre)
4076 4076
             print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4077
-        print '<div class="titre inline-block">' . $titre;
4077
+        print '<div class="titre inline-block">'.$titre;
4078 4078
         if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '')
4079
-            print ' (' . $totalnboflines . ')';
4079
+            print ' ('.$totalnboflines.')';
4080 4080
         print '</div></td>';
4081 4081
 
4082 4082
 // Center
4083 4083
         if ($morehtmlcenter) {
4084
-            print '<td class="nobordernopadding center valignmiddle">' . $morehtmlcenter . '</td>';
4084
+            print '<td class="nobordernopadding center valignmiddle">'.$morehtmlcenter.'</td>';
4085 4085
         }
4086 4086
 
4087 4087
 // Right
4088 4088
         print '<td class="nobordernopadding valignmiddle" align="right">';
4089 4089
         if ($sortfield)
4090
-            $options .= "&sortfield=" . urlencode($sortfield);
4090
+            $options .= "&sortfield=".urlencode($sortfield);
4091 4091
         if ($sortorder)
4092
-            $options .= "&sortorder=" . urlencode($sortorder);
4092
+            $options .= "&sortorder=".urlencode($sortorder);
4093 4093
 // Show navigation bar
4094 4094
         $pagelist = '';
4095 4095
         if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
@@ -4107,40 +4107,40 @@  discard block
 block discarded – undo
4107 4107
                 }
4108 4108
 
4109 4109
                 if ($cpt >= 1) {
4110
-                    $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=0' . $options . '">1</a></li>';
4110
+                    $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page=0'.$options.'">1</a></li>';
4111 4111
                     if ($cpt > 2)
4112
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4112
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '').'>...</span></li>';
4113 4113
                     else if ($cpt == 2)
4114
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4114
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page=1'.$options.'">2</a></li>';
4115 4115
                 }
4116 4116
 
4117 4117
                 do {
4118 4118
                     if ($cpt == $page) {
4119
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . '</span></li>';
4119
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '').'>'.($page + 1).'</span></li>';
4120 4120
                     } else {
4121
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . $cpt . $options . '">' . ($cpt + 1) . '</a></li>';
4121
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.$cpt.$options.'">'.($cpt + 1).'</a></li>';
4122 4122
                     }
4123 4123
                     $cpt++;
4124 4124
                 } while ($cpt < $nbpages && $cpt <= $page + $maxnbofpage);
4125 4125
 
4126 4126
                 if ($cpt < $nbpages) {
4127 4127
                     if ($cpt < $nbpages - 2)
4128
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4128
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '').'>...</span></li>';
4129 4129
                     else if ($cpt == $nbpages - 2)
4130
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4131
-                    $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 1) . $options . '">' . $nbpages . '</a></li>';
4130
+                        $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.($nbpages - 2).$options.'">'.($nbpages - 1).'</a></li>';
4131
+                    $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><a href="'.$file.'?page='.($nbpages - 1).$options.'">'.$nbpages.'</a></li>';
4132 4132
                 }
4133 4133
             }
4134 4134
             else {
4135
-                $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . "</li>";
4135
+                $pagelist .= '<li'.((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '').'><span '.((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '').'>'.($page + 1)."</li>";
4136 4136
             }
4137 4137
         }
4138 4138
 
4139
-        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
4139
+        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
4140 4140
 
4141 4141
         print '</td>';
4142 4142
 
4143
-        print '</tr></table>' . "\n";
4143
+        print '</tr></table>'."\n";
4144 4144
         print "<!-- End title -->\n\n";
4145 4145
     }
4146 4146
 
@@ -4171,12 +4171,12 @@  discard block
 block discarded – undo
4171 4171
                 $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4172 4172
 
4173 4173
             print '<li class="pagination">';
4174
-            print '<select class="flat selectlimit" name="limit" title="' . dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")) . '">';
4174
+            print '<select class="flat selectlimit" name="limit" title="'.dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")).'">';
4175 4175
             $tmpchoice = explode(',', $pagesizechoices);
4176
-            $tmpkey = $limit . ':' . $limit;
4176
+            $tmpkey = $limit.':'.$limit;
4177 4177
             if (!in_array($tmpkey, $tmpchoice))
4178 4178
                 $tmpchoice[] = $tmpkey;
4179
-            $tmpkey = Globals::$conf->liste_limit . ':' . Globals::$conf->liste_limit;
4179
+            $tmpkey = Globals::$conf->liste_limit.':'.Globals::$conf->liste_limit;
4180 4180
             if (!in_array($tmpkey, $tmpchoice))
4181 4181
                 $tmpchoice[] = $tmpkey;
4182 4182
             asort($tmpchoice, SORT_NUMERIC);
@@ -4191,7 +4191,7 @@  discard block
 block discarded – undo
4191 4191
                         $selected = ' selected="selected"';
4192 4192
                         $found = true;
4193 4193
                     }
4194
-                    print '<option name="' . $key . '"' . $selected . '>' . dol_escape_htmltag($val) . '</option>' . "\n";
4194
+                    print '<option name="'.$key.'"'.$selected.'>'.dol_escape_htmltag($val).'</option>'."\n";
4195 4195
                 }
4196 4196
             }
4197 4197
             print '</select>';
@@ -4210,20 +4210,20 @@  discard block
 block discarded – undo
4210 4210
             print '</li>';
4211 4211
         }
4212 4212
         if ($page > 0) {
4213
-            print '<li class="pagination"><a class="paginationprevious" href="' . $file . '?page=' . ($page - 1) . $options . '"><i class="fa fa-chevron-left" title="' . dol_escape_htmltag(Globals::$langs->trans("Previous")) . '"></i></a></li>';
4213
+            print '<li class="pagination"><a class="paginationprevious" href="'.$file.'?page='.($page - 1).$options.'"><i class="fa fa-chevron-left" title="'.dol_escape_htmltag(Globals::$langs->trans("Previous")).'"></i></a></li>';
4214 4214
         }
4215 4215
         if ($betweenarrows) {
4216 4216
             print $betweenarrows;
4217 4217
         }
4218 4218
         if ($nextpage > 0) {
4219
-            print '<li class="pagination"><a class="paginationnext" href="' . $file . '?page=' . ($page + 1) . $options . '"><i class="fa fa-chevron-right" title="' . dol_escape_htmltag(Globals::$langs->trans("Next")) . '"></i></a></li>';
4219
+            print '<li class="pagination"><a class="paginationnext" href="'.$file.'?page='.($page + 1).$options.'"><i class="fa fa-chevron-right" title="'.dol_escape_htmltag(Globals::$langs->trans("Next")).'"></i></a></li>';
4220 4220
         }
4221 4221
         if ($afterarrows) {
4222 4222
             print '<li class="paginationafterarrows">';
4223 4223
             print $afterarrows;
4224 4224
             print '</li>';
4225 4225
         }
4226
-        print '</ul></div>' . "\n";
4226
+        print '</ul></div>'."\n";
4227 4227
     }
4228 4228
 
4229 4229
     /**
@@ -4245,8 +4245,8 @@  discard block
 block discarded – undo
4245 4245
             $addpercent = true;
4246 4246
         }
4247 4247
         if (preg_match('/\((.*)\)/', $rate, $reg)) {
4248
-            $morelabel = ' (' . $reg[1] . ')';
4249
-            $rate = preg_replace('/\s*' . preg_quote($morelabel, '/') . '/', '', $rate);
4248
+            $morelabel = ' ('.$reg[1].')';
4249
+            $rate = preg_replace('/\s*'.preg_quote($morelabel, '/').'/', '', $rate);
4250 4250
         }
4251 4251
         if (preg_match('/\*/', $rate)) {
4252 4252
             $rate = str_replace('*', '', $rate);
@@ -4255,10 +4255,10 @@  discard block
 block discarded – undo
4255 4255
 
4256 4256
 // If rate is '9/9/9' we don't change it.  If rate is '9.000' we apply price()
4257 4257
         if (!preg_match('/\//', $rate))
4258
-            $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4258
+            $ret = price($rate, 0, '', 0, 0).($addpercent ? '%' : '');
4259 4259
         else {
4260 4260
 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
4261
-            $ret = $rate . ($addpercent ? '%' : '');
4261
+            $ret = $rate.($addpercent ? '%' : '');
4262 4262
         }
4263 4263
         if (($info_bits & 1) && $usestarfornpr >= 0)
4264 4264
             $ret .= ' *';
@@ -4351,10 +4351,10 @@  discard block
 block discarded – undo
4351 4351
                 $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4352 4352
             else {
4353 4353
                 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
4354
-                $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
4354
+                $cursymbolafter .= ($tmpcur == $currency_code ? ' '.$tmpcur : $tmpcur);
4355 4355
             }
4356 4356
         }
4357
-        $output = $cursymbolbefore . $output . $end . ($cursymbolafter ? ' ' : '') . $cursymbolafter;
4357
+        $output = $cursymbolbefore.$output.$end.($cursymbolafter ? ' ' : '').$cursymbolafter;
4358 4358
 
4359 4359
         return $output;
4360 4360
     }
@@ -4407,7 +4407,7 @@  discard block
 block discarded – undo
4407 4407
 // Now make replace (the main goal of function)
4408 4408
             if ($thousand != ',' && $thousand != '.')
4409 4409
                 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4410
-            $amount = str_replace(' ', '', $amount);  // To avoid spaces
4410
+            $amount = str_replace(' ', '', $amount); // To avoid spaces
4411 4411
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4412 4412
             $amount = str_replace($dec, '.', $amount);
4413 4413
         }
@@ -4436,14 +4436,14 @@  discard block
 block discarded – undo
4436 4436
                 $temps = sprintf("%0.10F", $amount - intval($amount)); // temps=0.0000000000 or 0.0000200000 or 9999.1000000000
4437 4437
                 $temps = preg_replace('/([\.1-9])0+$/', '\\1', $temps); // temps=0. or 0.00002 or 9999.1
4438 4438
                 $nbofdec = max(0, dol_strlen($temps) - 2); // -2 to remove "0."
4439
-                $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand);  // Convert amount to format with dolibarr dec and thousand
4439
+                $amount = number_format($amount, min($nbofdec, $nbofdectoround), $dec, $thousand); // Convert amount to format with dolibarr dec and thousand
4440 4440
             }
4441 4441
 //print "TT".$amount.'<br>';
4442 4442
 // Always make replace because each math static function (like round) replace
4443 4443
 // with local values and we want a number that has a SQL string format x.y
4444 4444
             if ($thousand != ',' && $thousand != '.')
4445 4445
                 $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4446
-            $amount = str_replace(' ', '', $amount);  // To avoid spaces
4446
+            $amount = str_replace(' ', '', $amount); // To avoid spaces
4447 4447
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4448 4448
             $amount = str_replace($dec, '.', $amount);
4449 4449
         }
@@ -4464,7 +4464,7 @@  discard block
 block discarded – undo
4464 4464
      */
4465 4465
     static function showDimensionInBestUnit($dimension, $unit, $type, $outputlangs, $round = -1, $forceunitoutput = 'no')
4466 4466
     {
4467
-        require_once DOL_BASE_PATH . '/core/lib/product.lib.php';
4467
+        require_once DOL_BASE_PATH.'/core/lib/product.lib.php';
4468 4468
 
4469 4469
         if (($forceunitoutput == 'no' && $dimension < 1 / 10000) || (is_numeric($forceunitoutput) && $forceunitoutput == -6)) {
4470 4470
             $dimension = $dimension * 1000000;
@@ -4480,7 +4480,7 @@  discard block
 block discarded – undo
4480 4480
             $unit = $unit + 3;
4481 4481
         }
4482 4482
 
4483
-        $ret = price($dimension, 0, $outputlangs, 0, 0, $round) . ' ' . measuring_units_string($unit, $type);
4483
+        $ret = price($dimension, 0, $outputlangs, 0, 0, $round).' '.measuring_units_string($unit, $type);
4484 4484
 
4485 4485
         return $ret;
4486 4486
     }
@@ -4504,7 +4504,7 @@  discard block
 block discarded – undo
4504 4504
         if (empty($thirdparty_seller) || !is_object($thirdparty_seller))
4505 4505
             $thirdparty_seller = $mysoc;
4506 4506
 
4507
-        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);
4507
+        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);
4508 4508
 
4509 4509
         $vatratecleaned = $vatrate;
4510 4510
         if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "xx (yy)"
@@ -4535,7 +4535,7 @@  discard block
 block discarded – undo
4535 4535
             if ($local == 2) {
4536 4536
 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
4537 4537
                 if (!$mysoc->localtax2_assuj)
4538
-                    return 0;  // If main vat is 0, IRPF may be different than 0.
4538
+                    return 0; // If main vat is 0, IRPF may be different than 0.
4539 4539
                 if ($thirdparty_seller->id == $mysoc->id) {
4540 4540
                     if (!$thirdparty_buyer->localtax2_assuj)
4541 4541
                         return 0;
@@ -4589,13 +4589,13 @@  discard block
 block discarded – undo
4589 4589
 
4590 4590
 // By default, search value of local tax on line of common tax
4591 4591
         $sql = "SELECT t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type";
4592
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4593
-        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $thirdparty_seller->country_code . "'";
4594
-        $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4592
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4593
+        $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$thirdparty_seller->country_code."'";
4594
+        $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4595 4595
         if ($vatratecode)
4596
-            $sql .= " AND t.code ='" . $vatratecode . "'";  // If we have the code, we use it in priority
4596
+            $sql .= " AND t.code ='".$vatratecode."'"; // If we have the code, we use it in priority
4597 4597
         else
4598
-            $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4598
+            $sql .= " AND t.recuperableonly ='".$vatnpr."'";
4599 4599
         dol_syslog("get_localtax", LOG_DEBUG);
4600 4600
         $resql = $db->query($sql);
4601 4601
 
@@ -4641,10 +4641,10 @@  discard block
 block discarded – undo
4641 4641
     {
4642 4642
        // global $db, $mysoc;
4643 4643
         $sql = "SELECT t.localtax1, t.localtax2 ";
4644
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t inner join " . MAIN_DB_PREFIX . "c_country as c ON c.rowid=t.fk_pays";
4645
-        $sql .= " WHERE c.code = '" . $mysoc->country_code . "' AND t.active = 1 AND t.taux=(";
4646
-        $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";
4647
-        $sql .= "  WHERE c.code = '" . $mysoc->country_code . "' AND tt.active = 1";
4644
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t inner join ".MAIN_DB_PREFIX."c_country as c ON c.rowid=t.fk_pays";
4645
+        $sql .= " WHERE c.code = '".$mysoc->country_code."' AND t.active = 1 AND t.taux=(";
4646
+        $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";
4647
+        $sql .= "  WHERE c.code = '".$mysoc->country_code."' AND tt.active = 1";
4648 4648
         $sql .= "  )";
4649 4649
 
4650 4650
         $resql = $db->query($sql);
@@ -4674,13 +4674,13 @@  discard block
 block discarded – undo
4674 4674
     {
4675 4675
        // global $db, $mysoc;
4676 4676
 
4677
-        dol_syslog("getTaxesFromId vat id or rate = " . $vatrate);
4677
+        dol_syslog("getTaxesFromId vat id or rate = ".$vatrate);
4678 4678
 
4679 4679
 // Search local taxes
4680 4680
         $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
4681
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4681
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
4682 4682
         if ($firstparamisid)
4683
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4683
+            $sql .= " WHERE t.rowid = ".(int) $vatrate;
4684 4684
         else {
4685 4685
             $vatratecleaned = $vatrate;
4686 4686
             $vatratecode = '';
@@ -4689,13 +4689,13 @@  discard block
 block discarded – undo
4689 4689
                 $vatratecode = $reg[2];
4690 4690
             }
4691 4691
 
4692
-            $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4692
+            $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
4693 4693
             /* 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 ??
4694 4694
               else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; */
4695
-            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4696
-            $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4695
+            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
4696
+            $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4697 4697
             if ($vatratecode)
4698
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4698
+                $sql .= " AND t.code = '".$vatratecode."'";
4699 4699
         }
4700 4700
 
4701 4701
         $resql = $db->query($sql);
@@ -4731,13 +4731,13 @@  discard block
 block discarded – undo
4731 4731
     {
4732 4732
        // global $db, $mysoc;
4733 4733
 
4734
-        dol_syslog("getLocalTaxesFromRate vatrate=" . $vatrate . " local=" . $local);
4734
+        dol_syslog("getLocalTaxesFromRate vatrate=".$vatrate." local=".$local);
4735 4735
 
4736 4736
 // Search local taxes
4737 4737
         $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
4738
-        $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4738
+        $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t";
4739 4739
         if ($firstparamisid)
4740
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4740
+            $sql .= " WHERE t.rowid = ".(int) $vatrate;
4741 4741
         else {
4742 4742
             $vatratecleaned = $vatrate;
4743 4743
             $vatratecode = '';
@@ -4746,14 +4746,14 @@  discard block
 block discarded – undo
4746 4746
                 $vatratecode = $reg[2];
4747 4747
             }
4748 4748
 
4749
-            $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4749
+            $sql .= ", ".MAIN_DB_PREFIX."c_country as c";
4750 4750
             if ($mysoc->country_code == 'ES')
4751
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";    // local tax in spain use the buyer country ??
4751
+                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$buyer->country_code."'"; // local tax in spain use the buyer country ??
4752 4752
             else
4753
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4754
-            $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4753
+                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'";
4754
+            $sql .= " AND t.taux = ".((float) $vatratecleaned)." AND t.active = 1";
4755 4755
             if ($vatratecode)
4756
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4756
+                $sql .= " AND t.code = '".$vatratecode."'";
4757 4757
         }
4758 4758
 
4759 4759
         $resql = $db->query($sql);
@@ -4785,7 +4785,7 @@  discard block
 block discarded – undo
4785 4785
     {
4786 4786
        // global $db, Globals::$conf, $mysoc;
4787 4787
 
4788
-        require_once DOL_BASE_PATH . '/product/class/product.class.php';
4788
+        require_once DOL_BASE_PATH.'/product/class/product.class.php';
4789 4789
 
4790 4790
         $ret = 0;
4791 4791
         $found = 0;
@@ -4800,12 +4800,12 @@  discard block
 block discarded – undo
4800 4800
                     $product->get_buyprice($idprodfournprice, 0, 0, 0);
4801 4801
                     $ret = $product->vatrate_supplier;
4802 4802
                     if ($product->default_vat_code)
4803
-                        $ret .= ' (' . $product->default_vat_code . ')';
4803
+                        $ret .= ' ('.$product->default_vat_code.')';
4804 4804
                 }
4805 4805
                 else {
4806
-                    $ret = $product->tva_tx;    // Default vat of product we defined
4806
+                    $ret = $product->tva_tx; // Default vat of product we defined
4807 4807
                     if ($product->default_vat_code)
4808
-                        $ret .= ' (' . $product->default_vat_code . ')';
4808
+                        $ret .= ' ('.$product->default_vat_code.')';
4809 4809
                 }
4810 4810
                 $found = 1;
4811 4811
             }
@@ -4819,8 +4819,8 @@  discard block
 block discarded – undo
4819 4819
             if (empty(Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS)) {
4820 4820
 // If vat of product for the country not found or not defined, we return the first higher vat of country.
4821 4821
                 $sql = "SELECT t.taux as vat_rate, t.code as default_vat_code";
4822
-                $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4823
-                $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $thirdparty_seller->country_code . "'";
4822
+                $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4823
+                $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
4824 4824
                 $sql .= " ORDER BY t.taux DESC, t.code ASC, t.recuperableonly ASC";
4825 4825
                 $sql .= $db->plimit(1);
4826 4826
 
@@ -4830,16 +4830,16 @@  discard block
 block discarded – undo
4830 4830
                     if ($obj) {
4831 4831
                         $ret = $obj->vat_rate;
4832 4832
                         if ($obj->default_vat_code)
4833
-                            $ret .= ' (' . $obj->default_vat_code . ')';
4833
+                            $ret .= ' ('.$obj->default_vat_code.')';
4834 4834
                     }
4835 4835
                     $db->free($sql);
4836 4836
                 } else
4837 4837
                     dol_print_error($db);
4838 4838
             } else
4839
-                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;    // Forced value if autodetect fails
4839
+                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS; // Forced value if autodetect fails
4840 4840
         }
4841 4841
 
4842
-        dol_syslog("get_product_vat_for_country: ret=" . $ret);
4842
+        dol_syslog("get_product_vat_for_country: ret=".$ret);
4843 4843
         return $ret;
4844 4844
     }
4845 4845
 
@@ -4857,7 +4857,7 @@  discard block
 block discarded – undo
4857 4857
        // global $db, $mysoc;
4858 4858
 
4859 4859
         if (!class_exists('Product')) {
4860
-            require_once DOL_BASE_PATH . 'product/class/product.class.php';
4860
+            require_once DOL_BASE_PATH.'product/class/product.class.php';
4861 4861
         }
4862 4862
 
4863 4863
         $ret = 0;
@@ -4882,8 +4882,8 @@  discard block
 block discarded – undo
4882 4882
         if (!$found) {
4883 4883
 // If vat of product for the country not found or not defined, we return higher vat of country.
4884 4884
             $sql = "SELECT taux as vat_rate, localtax1, localtax2";
4885
-            $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4886
-            $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='" . $thirdparty_seller->country_code . "'";
4885
+            $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
4886
+            $sql .= " WHERE t.active=1 AND t.fk_pays = c.rowid AND c.code='".$thirdparty_seller->country_code."'";
4887 4887
             $sql .= " ORDER BY t.taux DESC, t.recuperableonly ASC";
4888 4888
             $sql .= $db->plimit(1);
4889 4889
 
@@ -4900,7 +4900,7 @@  discard block
 block discarded – undo
4900 4900
                 dol_print_error($db);
4901 4901
         }
4902 4902
 
4903
-        dol_syslog("get_product_localtax_for_country: ret=" . $ret);
4903
+        dol_syslog("get_product_localtax_for_country: ret=".$ret);
4904 4904
         return $ret;
4905 4905
     }
4906 4906
 
@@ -4924,7 +4924,7 @@  discard block
 block discarded – undo
4924 4924
     {
4925 4925
        // global Globals::$conf;
4926 4926
 
4927
-        require_once DOL_BASE_PATH . '/core/lib/company.lib.php';
4927
+        require_once DOL_BASE_PATH.'/core/lib/company.lib.php';
4928 4928
 
4929 4929
 // Note: possible values for tva_assuj are 0/1 or franchise/reel
4930 4930
         $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;
@@ -4935,7 +4935,7 @@  discard block
 block discarded – undo
4935 4935
         $buyer_country_code = $thirdparty_buyer->country_code;
4936 4936
         $buyer_in_cee = isInEEC($thirdparty_buyer);
4937 4937
 
4938
-        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 : ''));
4938
+        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 : ''));
4939 4939
 
4940 4940
 // 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)
4941 4941
 // we use the buyer VAT.
@@ -5001,14 +5001,14 @@  discard block
 block discarded – undo
5001 5001
 
5002 5002
         if ($idprodfournprice > 0) {
5003 5003
             if (!class_exists('ProductFournisseur'))
5004
-                require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5004
+                require_once DOL_BASE_PATH.'/fourn/class/fournisseur.product.class.php';
5005 5005
             $prodprice = new ProductFournisseur($db);
5006 5006
             $prodprice->fetch_product_fournisseur_price($idprodfournprice);
5007 5007
             return $prodprice->fourn_tva_npr;
5008 5008
         }
5009 5009
         elseif ($idprod > 0) {
5010 5010
             if (!class_exists('Product'))
5011
-                require_once DOL_BASE_PATH . 'product/class/product.class.php';
5011
+                require_once DOL_BASE_PATH.'product/class/product.class.php';
5012 5012
             $prod = new Product($db);
5013 5013
             $prod->fetch($idprod);
5014 5014
             return $prod->tva_npr;
@@ -5087,7 +5087,7 @@  discard block
 block discarded – undo
5087 5087
             if ($case == 2)
5088 5088
                 $result = '<input type="checkbox" value="1" checked disabled>';
5089 5089
             if ($case == 3)
5090
-                $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5090
+                $result = '<input type="checkbox" value="1" checked disabled> '.$result;
5091 5091
 
5092 5092
             $classname = 'ok';
5093 5093
         }
@@ -5098,7 +5098,7 @@  discard block
 block discarded – undo
5098 5098
             if ($case == 2)
5099 5099
                 $result = '<input type="checkbox" value="0" disabled>';
5100 5100
             if ($case == 3)
5101
-                $result = '<input type="checkbox" value="0" disabled> ' . $result;
5101
+                $result = '<input type="checkbox" value="0" disabled> '.$result;
5102 5102
 
5103 5103
             if ($color == 2)
5104 5104
                 $classname = 'ok';
@@ -5106,7 +5106,7 @@  discard block
 block discarded – undo
5106 5106
                 $classname = 'error';
5107 5107
         }
5108 5108
         if ($color)
5109
-            return '<font class="' . $classname . '">' . $result . '</font>';
5109
+            return '<font class="'.$classname.'">'.$result.'</font>';
5110 5110
         return $result;
5111 5111
     }
5112 5112
 
@@ -5140,13 +5140,13 @@  discard block
 block discarded – undo
5140 5140
                 $num = preg_replace('/([^0-9])/i', '', $num);
5141 5141
             else
5142 5142
                 $num = preg_replace('/^.*\-/i', '', $num);
5143
-            $num = substr("000" . $num, -$level);
5143
+            $num = substr("000".$num, -$level);
5144 5144
             if ($level == 1)
5145 5145
                 $path = substr($num, 0, 1);
5146 5146
             if ($level == 2)
5147
-                $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5147
+                $path = substr($num, 1, 1).'/'.substr($num, 0, 1);
5148 5148
             if ($level == 3)
5149
-                $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5149
+                $path = substr($num, 2, 1).'/'.substr($num, 1, 1).'/'.substr($num, 0, 1);
5150 5150
         }
5151 5151
         else {
5152 5152
 // TODO
@@ -5177,7 +5177,7 @@  discard block
 block discarded – undo
5177 5177
     {
5178 5178
        // global Globals::$conf;
5179 5179
 
5180
-        dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5180
+        dol_syslog("functions.lib::dol_mkdir: dir=".$dir, LOG_INFO);
5181 5181
 
5182 5182
         $dir_osencoded = dol_osencode($dir);
5183 5183
         if (@is_dir($dir_osencoded))
@@ -5189,15 +5189,15 @@  discard block
 block discarded – undo
5189 5189
         $ccdir = '';
5190 5190
         if (!empty($dataroot)) {
5191 5191
 // Remove data root from loop
5192
-            $dir = str_replace($dataroot . '/', '', $dir);
5193
-            $ccdir = $dataroot . '/';
5192
+            $dir = str_replace($dataroot.'/', '', $dir);
5193
+            $ccdir = $dataroot.'/';
5194 5194
         }
5195 5195
 
5196 5196
         $cdir = explode("/", $dir);
5197 5197
         $num = count($cdir);
5198 5198
         for ($i = 0; $i < $num; $i++) {
5199 5199
             if ($i > 0)
5200
-                $ccdir .= '/' . $cdir[$i];
5200
+                $ccdir .= '/'.$cdir[$i];
5201 5201
             else
5202 5202
                 $ccdir .= $cdir[$i];
5203 5203
             if (preg_match("/^.:$/", $ccdir, $regs))
@@ -5241,20 +5241,20 @@  discard block
 block discarded – undo
5241 5241
             if ($ccdir) {
5242 5242
                 $ccdir_osencoded = dol_osencode($ccdir);
5243 5243
                 if (!@is_dir($ccdir_osencoded)) {
5244
-                    dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
5244
+                    dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' does not exists or is outside open_basedir PHP setting.", LOG_DEBUG);
5245 5245
 
5246 5246
                     umask(0);
5247 5247
                     $dirmaskdec = octdec($newmask);
5248 5248
                     if (empty($newmask)) {
5249 5249
                         $dirmaskdec = empty(Globals::$conf->global->MAIN_UMASK) ? octdec('0755') : octdec(Globals::$conf->global->MAIN_UMASK);
5250 5250
                     }
5251
-                    $dirmaskdec |= octdec('0111');  // Set x bit required for directories
5251
+                    $dirmaskdec |= octdec('0111'); // Set x bit required for directories
5252 5252
                     if (!@mkdir($ccdir_osencoded, $dirmaskdec)) {
5253 5253
                         // Si le is_dir a renvoye une fausse info, alors on passe ici.
5254
-                        dol_syslog("functions.lib::dol_mkdir: Fails to create directory '" . $ccdir . "' or directory already exists.", LOG_WARNING);
5254
+                        dol_syslog("functions.lib::dol_mkdir: Fails to create directory '".$ccdir."' or directory already exists.", LOG_WARNING);
5255 5255
                         $nberr++;
5256 5256
                     } else {
5257
-                        dol_syslog("functions.lib::dol_mkdir: Directory '" . $ccdir . "' created", LOG_DEBUG);
5257
+                        dol_syslog("functions.lib::dol_mkdir: Directory '".$ccdir."' created", LOG_DEBUG);
5258 5258
                         $nberr = 0; // On remet a zero car si on arrive ici, cela veut dire que les echecs precedents peuvent etre ignore
5259 5259
                         $nbcreated++;
5260 5260
                     }
@@ -5302,9 +5302,9 @@  discard block
 block discarded – undo
5302 5302
         } else {
5303 5303
             $pattern = "/<[^<>]+>/";
5304 5304
 // Exemple of $temp: <a href="/myurl" title="<u>A title</u>">0000-021</a>
5305
-            $temp = preg_replace($pattern, "", $temp);    // pass 1
5305
+            $temp = preg_replace($pattern, "", $temp); // pass 1
5306 5306
 // $temp after pass 1: <a href="/myurl" title="A title">0000-021
5307
-            $temp = preg_replace($pattern, "", $temp);    // pass 2
5307
+            $temp = preg_replace($pattern, "", $temp); // pass 2
5308 5308
 // $temp after pass 2: 0000-021
5309 5309
         }
5310 5310
 
@@ -5360,8 +5360,8 @@  discard block
 block discarded – undo
5360 5360
     {
5361 5361
         $temp = $stringtoclean;
5362 5362
         foreach ($disallowed_tags as $tagtoremove) {
5363
-            $temp = preg_replace('/<\/?' . $tagtoremove . '>/', '', $temp);
5364
-            $temp = preg_replace('/<\/?' . $tagtoremove . '\s+[^>]*>/', '', $temp);
5363
+            $temp = preg_replace('/<\/?'.$tagtoremove.'>/', '', $temp);
5364
+            $temp = preg_replace('/<\/?'.$tagtoremove.'\s+[^>]*>/', '', $temp);
5365 5365
         }
5366 5366
         return $temp;
5367 5367
     }
@@ -5378,12 +5378,12 @@  discard block
 block discarded – undo
5378 5378
     {
5379 5379
         if ($nboflines == 1) {
5380 5380
             if (dol_textishtml($text)) {
5381
-                $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text);  // The s pattern modifier means the . can match newline characters
5381
+                $firstline = preg_replace('/<br[^>]*>.*$/s', '', $text); // The s pattern modifier means the . can match newline characters
5382 5382
                 $firstline = preg_replace('/<div[^>]*>.*$/s', '', $firstline); // The s pattern modifier means the . can match newline characters
5383 5383
             } else {
5384 5384
                 $firstline = preg_replace('/[\n\r].*/', '', $text);
5385 5385
             }
5386
-            return $firstline . ((strlen($firstline) != strlen($text)) ? '...' : '');
5386
+            return $firstline.((strlen($firstline) != strlen($text)) ? '...' : '');
5387 5387
         } else {
5388 5388
             $ishtml = 0;
5389 5389
             if (dol_textishtml($text)) {
@@ -5399,7 +5399,7 @@  discard block
 block discarded – undo
5399 5399
                 $pattern = '/(<br[^>]*>)/Uu';
5400 5400
             } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5401 5401
             else
5402
-                $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5402
+                $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
5403 5403
             $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5404 5404
 
5405 5405
             $firstline = '';
@@ -5413,7 +5413,7 @@  discard block
 block discarded – undo
5413 5413
                 $i++;
5414 5414
             }
5415 5415
             unset($a);
5416
-            return $firstline . (($i < $nba) ? '...' : '');
5416
+            return $firstline.(($i < $nba) ? '...' : '');
5417 5417
         }
5418 5418
     }
5419 5419
 
@@ -5484,9 +5484,9 @@  discard block
 block discarded – undo
5484 5484
     static function dol_htmlentitiesbr_decode($stringtodecode, $pagecodeto = 'UTF-8')
5485 5485
     {
5486 5486
         $ret = dol_html_entity_decode($stringtodecode, ENT_COMPAT, $pagecodeto);
5487
-        $ret = preg_replace('/' . "\r\n" . '<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
5488
-        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\r\n" . '/i', "\r\n", $ret);
5489
-        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>' . "\n" . '/i', "\n", $ret);
5487
+        $ret = preg_replace('/'."\r\n".'<br(\s[\sa-zA-Z_="]*)?\/?>/i', "<br>", $ret);
5488
+        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\r\n".'/i', "\r\n", $ret);
5489
+        $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>'."\n".'/i', "\n", $ret);
5490 5490
         $ret = preg_replace('/<br(\s[\sa-zA-Z_="]*)?\/?>/i', "\n", $ret);
5491 5491
         return $ret;
5492 5492
     }
@@ -5499,7 +5499,7 @@  discard block
 block discarded – undo
5499 5499
      */
5500 5500
     static function dol_htmlcleanlastbr($stringtodecode)
5501 5501
     {
5502
-        $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|' . "\n" . '|' . "\r" . ')+$/i', "", $stringtodecode);
5502
+        $ret = preg_replace('/(<br>|<br(\s[\sa-zA-Z_="]*)?\/?>|'."\n".'|'."\r".')+$/i', "", $stringtodecode);
5503 5503
         return $ret;
5504 5504
     }
5505 5505
 
@@ -5596,7 +5596,7 @@  discard block
 block discarded – undo
5596 5596
             $pattern = '/(<br[^>]*>)/Uu';
5597 5597
         } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5598 5598
         else
5599
-            $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5599
+            $pattern = '/(<br[^>]*>)/U'; // /U is to have UNGREEDY regex to limit to one html tag.
5600 5600
         $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5601 5601
 
5602 5602
         $nblines = (int) floor((count($a) + 1) / 2);
@@ -5627,7 +5627,7 @@  discard block
 block discarded – undo
5627 5627
      */
5628 5628
     static function dol_microtime_float()
5629 5629
     {
5630
-        dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
5630
+        dol_syslog(__FUNCTION__." is deprecated", LOG_WARNING);
5631 5631
 
5632 5632
         return microtime(true);
5633 5633
     }
@@ -5673,9 +5673,9 @@  discard block
 block discarded – undo
5673 5673
             elseif (preg_match('/<h[0-9]>/i', $msg))
5674 5674
                 return true;
5675 5675
             elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg))
5676
-                return true;    // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5676
+                return true; // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5677 5677
             elseif (preg_match('/&#[0-9]{2,3};/i', $msg))
5678
-                return true;    // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5678
+                return true; // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5679 5679
 
5680 5680
             return false;
5681 5681
         }
@@ -5900,7 +5900,7 @@  discard block
 block discarded – undo
5900 5900
                     if ($object->fetch_optionals() > 0) {
5901 5901
                         if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) {
5902 5902
                             foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) {
5903
-                                $substitutionarray['__EXTRAFIELD_' . strtoupper($key) . '__'] = $object->array_options['options_' . $key];
5903
+                                $substitutionarray['__EXTRAFIELD_'.strtoupper($key).'__'] = $object->array_options['options_'.$key];
5904 5904
                             }
5905 5905
                         }
5906 5906
                     }
@@ -5912,7 +5912,7 @@  discard block
 block discarded – undo
5912 5912
                     $paymenturl = '';
5913 5913
                 } else {
5914 5914
                     // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
5915
-                    require_once DOL_BASE_PATH . '/core/lib/payments.lib.php';
5915
+                    require_once DOL_BASE_PATH.'/core/lib/payments.lib.php';
5916 5916
                     $outputlangs->loadLangs(array('paypal', 'other'));
5917 5917
                     $typeforonlinepayment = 'free';
5918 5918
                     if (is_object($object) && $object->element == 'commande')
@@ -5973,7 +5973,7 @@  discard block
 block discarded – undo
5973 5973
 
5974 5974
 //var_dump($substitutionarray['__AMOUNT_FORMATED__']);
5975 5975
         if (empty($exclude) || !in_array('date', $exclude)) {
5976
-            include_once DOL_BASE_PATH . '/core/lib/date.lib.php';
5976
+            include_once DOL_BASE_PATH.'/core/lib/date.lib.php';
5977 5977
 
5978 5978
             $tmp = dol_getdate(dol_now(), true);
5979 5979
             $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
@@ -5983,13 +5983,13 @@  discard block
 block discarded – undo
5983 5983
 
5984 5984
             $substitutionarray = array_merge($substitutionarray, array(
5985 5985
                 '__DAY__' => (string) $tmp['mday'],
5986
-                '__DAY_TEXT__' => $outputlangs->trans('Day' . $tmp['wday']), // Monday
5987
-                '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'] . 'Min'), // Mon
5988
-                '__DAY_TEXT_MIN__' => $outputlangs->trans('Short' . $tmp['weekday']), // M
5986
+                '__DAY_TEXT__' => $outputlangs->trans('Day'.$tmp['wday']), // Monday
5987
+                '__DAY_TEXT_SHORT__' => $outputlangs->trans($tmp['weekday'].'Min'), // Mon
5988
+                '__DAY_TEXT_MIN__' => $outputlangs->trans('Short'.$tmp['weekday']), // M
5989 5989
                 '__MONTH__' => (string) $tmp['mon'],
5990
-                '__MONTH_TEXT__' => $outputlangs->trans('Month' . sprintf("%02d", $tmp['mon'])),
5991
-                '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort' . sprintf("%02d", $tmp['mon'])),
5992
-                '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort' . sprintf("%02d", $tmp['mon'])),
5990
+                '__MONTH_TEXT__' => $outputlangs->trans('Month'.sprintf("%02d", $tmp['mon'])),
5991
+                '__MONTH_TEXT_SHORT__' => $outputlangs->trans('MonthShort'.sprintf("%02d", $tmp['mon'])),
5992
+                '__MONTH_TEXT_MIN__' => $outputlangs->trans('MonthVeryShort'.sprintf("%02d", $tmp['mon'])),
5993 5993
                 '__YEAR__' => (string) $tmp['year'],
5994 5994
                 '__PREVIOUS_DAY__' => (string) $tmp2['day'],
5995 5995
                 '__PREVIOUS_MONTH__' => (string) $tmp3['month'],
@@ -6048,7 +6048,7 @@  discard block
 block discarded – undo
6048 6048
                 if (!empty($tmp[1]))
6049 6049
                     $outputlangs->load($tmp[1]);
6050 6050
 
6051
-                $text = preg_replace('/__\(' . preg_quote($reg[1], '/') . '\)__/', $msgishtml ? dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6051
+                $text = preg_replace('/__\('.preg_quote($reg[1], '/').'\)__/', $msgishtml ? dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6052 6052
             }
6053 6053
         }
6054 6054
 
@@ -6064,13 +6064,13 @@  discard block
 block discarded – undo
6064 6064
                 $newval = '*****forbidden*****';
6065 6065
             else
6066 6066
                 $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6067
-            $text = preg_replace('/__\[' . preg_quote($keyfound, '/') . '\]__/', $msgishtml ? dol_htmlentitiesbr($newval) : $newval, $text);
6067
+            $text = preg_replace('/__\['.preg_quote($keyfound, '/').'\]__/', $msgishtml ? dol_htmlentitiesbr($newval) : $newval, $text);
6068 6068
         }
6069 6069
 
6070 6070
 // Make substitition for array $substitutionarray
6071 6071
         foreach ($substitutionarray as $key => $value) {
6072 6072
             if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6073
-                $value = '';  // Protection
6073
+                $value = ''; // Protection
6074 6074
             if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6075 6075
                 $value = ''; // Protection
6076 6076
 
@@ -6096,7 +6096,7 @@  discard block
 block discarded – undo
6096 6096
     {
6097 6097
        // global Globals::$conf, $user;
6098 6098
 
6099
-        require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
6099
+        require_once DOL_BASE_PATH.'/core/lib/files.lib.php';
6100 6100
 
6101 6101
 // Add a substitution key for each extrafields, using key __EXTRA_XXX__
6102 6102
 // TODO Remove this. Already available into the getCommonSubstitutionArray used to build the substitution array.
@@ -6126,11 +6126,11 @@  discard block
 block discarded – undo
6126 6126
                 if (preg_match('/functions_(.*)\.lib\.php/i', $substitfile['name'], $reg)) {
6127 6127
                     $module = $reg[1];
6128 6128
 
6129
-                    dol_syslog("Library " . $substitfile['name'] . " found into " . $dir);
6129
+                    dol_syslog("Library ".$substitfile['name']." found into ".$dir);
6130 6130
                     // Include the user's functions file
6131
-                    require_once $dir . $substitfile['name'];
6131
+                    require_once $dir.$substitfile['name'];
6132 6132
                     // Call the user's function, and only if it is defined
6133
-                    $function_name = $module . "_" . $callfunc;
6133
+                    $function_name = $module."_".$callfunc;
6134 6134
                     if (function_exists($function_name))
6135 6135
                         $function_name($substitutionarray, $outputlangs, $object, $parameters);
6136 6136
                 }
@@ -6172,13 +6172,13 @@  discard block
 block discarded – undo
6172 6172
             $outputlangs = Globals::$langs;
6173 6173
 
6174 6174
         if ($date_start && $date_end) {
6175
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6175
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6176 6176
         }
6177 6177
         if ($date_start && !$date_end) {
6178
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6178
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($date_start, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6179 6179
         }
6180 6180
         if (!$date_start && $date_end) {
6181
-            $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
6181
+            $out .= ($withparenthesis ? ' (' : '').$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($date_end, $format, false, $outputlangs)).($withparenthesis ? ')' : '');
6182 6182
         }
6183 6183
 
6184 6184
         return $out;
@@ -6258,7 +6258,7 @@  discard block
 block discarded – undo
6258 6258
             dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
6259 6259
         } else {
6260 6260
             if (!in_array((string) $style, array('mesgs', 'warnings', 'errors')))
6261
-                dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6261
+                dol_print_error('', 'Bad parameter style='.$style.' for setEventMessages');
6262 6262
             if (empty($mesgs))
6263 6263
                 setEventMessage($mesg, $style);
6264 6264
             else {
@@ -6327,7 +6327,7 @@  discard block
 block discarded – undo
6327 6327
 
6328 6328
 // If inline message with no format, we add it.
6329 6329
         if ((empty(Globals::$conf->use_javascript_ajax) || !empty(Globals::$conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) || $keepembedded) && !preg_match('/<div class=".*">/i', $out)) {
6330
-            $divstart = '<div class="' . $style . ' clearboth">';
6330
+            $divstart = '<div class="'.$style.' clearboth">';
6331 6331
             $divend = '</div>';
6332 6332
         }
6333 6333
 
@@ -6354,14 +6354,14 @@  discard block
 block discarded – undo
6354 6354
             if (!empty(Globals::$conf->use_javascript_ajax) && empty(Globals::$conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && empty($keepembedded)) {
6355 6355
                 $return = '<script type="text/javascript">
6356 6356
 					$(document).ready(function() {
6357
-						var block = ' . (!empty(Globals::$conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false") . '
6357
+						var block = ' . (!empty(Globals::$conf->global->MAIN_USE_JQUERY_BLOCKUI) ? "true" : "false").'
6358 6358
 						if (block) {
6359
-							$.dolEventValid("","' . dol_escape_js($out) . '");
6359
+							$.dolEventValid("","' . dol_escape_js($out).'");
6360 6360
 						} else {
6361 6361
 							/* jnotify(message, preset of message type, keepmessage) */
6362
-							$.jnotify("' . dol_escape_js($out) . '",
6363
-							"' . ($style == "ok" ? 3000 : $style) . '",
6364
-							' . ($style == "ok" ? "false" : "true") . ',
6362
+							$.jnotify("' . dol_escape_js($out).'",
6363
+							"' . ($style == "ok" ? 3000 : $style).'",
6364
+							' . ($style == "ok" ? "false" : "true").',
6365 6365
 							{ remove: static function (){} } );
6366 6366
 						}
6367 6367
 					});
@@ -6556,11 +6556,11 @@  discard block
 block discarded – undo
6556 6556
     {
6557 6557
        // global Globals::$conf;
6558 6558
 
6559
-        $tmp = ini_get("unicode.filesystem_encoding");      // Disponible avec PHP 6.0
6559
+        $tmp = ini_get("unicode.filesystem_encoding"); // Disponible avec PHP 6.0
6560 6560
         if (empty($tmp) && !empty($_SERVER["WINDIR"]))
6561 6561
             $tmp = 'iso-8859-1'; // By default for windows
6562 6562
         if (empty($tmp))
6563
-            $tmp = 'utf-8';          // By default for other
6563
+            $tmp = 'utf-8'; // By default for other
6564 6564
         if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING))
6565 6565
             $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6566 6566
 
@@ -6591,16 +6591,16 @@  discard block
 block discarded – undo
6591 6591
 
6592 6592
 // Check in cache
6593 6593
         if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
6594
-            return $cache_codes[$tablename][$key][$fieldid];   // Found in cache
6594
+            return $cache_codes[$tablename][$key][$fieldid]; // Found in cache
6595 6595
         }
6596 6596
 
6597 6597
         dol_syslog('dol_getIdFromCode (value not found into cache)', LOG_DEBUG);
6598 6598
 
6599
-        $sql = "SELECT " . $fieldid . " as valuetoget";
6600
-        $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
6601
-        $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($key) . "'";
6599
+        $sql = "SELECT ".$fieldid." as valuetoget";
6600
+        $sql .= " FROM ".MAIN_DB_PREFIX.$tablename;
6601
+        $sql .= " WHERE ".$fieldkey." = '".$db->escape($key)."'";
6602 6602
         if (!empty($entityfilter))
6603
-            $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6603
+            $sql .= " AND entity IN (".getEntity($tablename).")";
6604 6604
 
6605 6605
         $resql = $db->query($sql);
6606 6606
         if ($resql) {
@@ -6631,8 +6631,8 @@  discard block
 block discarded – undo
6631 6631
 //print $strRights."<br>\n";
6632 6632
         $rights = true;
6633 6633
         if ($strRights != '') {
6634
-            $str = 'if(!(' . $strRights . ')) { $rights = false; }';
6635
-            self::dol_eval($str);  // The dol_eval must contains all the// global $xxx used into a condition
6634
+            $str = 'if(!('.$strRights.')) { $rights = false; }';
6635
+            self::dol_eval($str); // The dol_eval must contains all the// global $xxx used into a condition
6636 6636
         }
6637 6637
         return $rights;
6638 6638
     }
@@ -6659,9 +6659,9 @@  discard block
 block discarded – undo
6659 6659
 //print $s."<br>\n";
6660 6660
         if ($returnvalue) {
6661 6661
             if ($hideerrors)
6662
-                return @eval('return ' . $s . ';');
6662
+                return @eval('return '.$s.';');
6663 6663
             else
6664
-                return eval('return ' . $s . ';');
6664
+                return eval('return '.$s.';');
6665 6665
         }
6666 6666
         else {
6667 6667
             if ($hideerrors)
@@ -6715,7 +6715,7 @@  discard block
 block discarded – undo
6715 6715
             $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
6716 6716
         }
6717 6717
 
6718
-        return img_picto_common($codelang, 'flags/' . strtolower($flagImage) . '.png', $moreatt);
6718
+        return img_picto_common($codelang, 'flags/'.strtolower($flagImage).'.png', $moreatt);
6719 6719
     }
6720 6720
 
6721 6721
     /**
@@ -6913,16 +6913,16 @@  discard block
 block discarded – undo
6913 6913
             'zu-ZA',
6914 6914
         );
6915 6915
 
6916
-        $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
6916
+        $buildprimarykeytotest = strtolower($countrycode).'-'.strtoupper($countrycode);
6917 6917
         if (in_array($buildprimarykeytotest, $locales))
6918
-            return strtolower($countrycode) . '_' . strtoupper($countrycode);
6918
+            return strtolower($countrycode).'_'.strtoupper($countrycode);
6919 6919
 
6920 6920
         foreach ($locales as $locale) {
6921 6921
             $locale_language = locale_get_primary_language($locale);
6922 6922
             $locale_region = locale_get_region($locale);
6923 6923
             if (strtoupper($countrycode) == $locale_region) {
6924 6924
 //var_dump($locale.'-'.$locale_language.'-'.$locale_region);
6925
-                return strtolower($locale_language) . '_' . strtoupper($locale_region);
6925
+                return strtolower($locale_language).'_'.strtoupper($locale_region);
6926 6926
             }
6927 6927
         }
6928 6928
 
@@ -6983,7 +6983,7 @@  discard block
 block discarded – undo
6983 6983
                                 $label = Globals::$langs->trans($values[2]);
6984 6984
 
6985 6985
                             //$head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
6986
-                            $head[$h][0] = BASE_URI . preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
6986
+                            $head[$h][0] = BASE_URI.preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
6987 6987
                             $head[$h][1] = $label;
6988 6988
                             $head[$h][2] = str_replace('+', '', $values[1]);
6989 6989
                             $h++;
@@ -7054,43 +7054,43 @@  discard block
 block discarded – undo
7054 7054
         // global $micro_start_time;
7055 7055
 
7056 7056
         if ($zone == 'private')
7057
-            print "\n" . '<!-- Common footer for private page -->' . "\n";
7057
+            print "\n".'<!-- Common footer for private page -->'."\n";
7058 7058
         else
7059
-            print "\n" . '<!-- Common footer for public page -->' . "\n";
7059
+            print "\n".'<!-- Common footer for public page -->'."\n";
7060 7060
 
7061 7061
 // A div to store page_y POST parameter so we can read it using javascript
7062 7062
         print "\n<!-- A div to store page_y POST paramater -->\n";
7063
-        print '<div id="page_y" style="display: none;">' . $_POST['page_y'] . '</div>' . "\n";
7063
+        print '<div id="page_y" style="display: none;">'.$_POST['page_y'].'</div>'."\n";
7064 7064
 
7065 7065
         $parameters = array();
7066
-        $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters);    // Note that $action and $object may have been modified by some hooks
7066
+        $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters); // Note that $action and $object may have been modified by some hooks
7067 7067
         if (empty($reshook)) {
7068 7068
             if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER))
7069
-                print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7069
+                print Globals::$conf->global->MAIN_HTML_FOOTER."\n";
7070 7070
 
7071 7071
             print "\n";
7072 7072
             if (!empty(Globals::$conf->use_javascript_ajax)) {
7073
-                print '<script type="text/javascript" language="javascript">' . "\n";
7074
-                print 'jQuery(document).ready(function() {' . "\n";
7073
+                print '<script type="text/javascript" language="javascript">'."\n";
7074
+                print 'jQuery(document).ready(function() {'."\n";
7075 7075
 
7076 7076
                 if ($zone == 'private' && empty(Globals::$conf->dol_use_jmobile)) {
7077 7077
                     print "\n";
7078
-                    print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */' . "\n";
7078
+                    print '/* JS CODE TO ENABLE to manage handler to switch left menu page (menuhider) */'."\n";
7079 7079
                     print 'jQuery(".menuhider").click(function() {';
7080
-                    print '  console.log("We click on .menuhider");' . "\n";
7080
+                    print '  console.log("We click on .menuhider");'."\n";
7081 7081
                     //print "  $('.side-nav').animate({width:'toggle'},200);\n";     // OK with eldy theme but not with md
7082 7082
                     print "  $('.side-nav').toggle()\n";
7083 7083
                     print "  $('.login_block').toggle()\n";
7084
-                    print '});' . "\n";
7084
+                    print '});'."\n";
7085 7085
                 }
7086 7086
 
7087 7087
 // Management of focus and mandatory for fields
7088 7088
                 if ($action == 'create' || $action == 'edit' || (empty($action) && (preg_match('/new\.php/', $_SERVER["PHP_SELF"])))) {
7089
-                    print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
7089
+                    print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */'."\n";
7090 7090
                     $relativepathstring = $_SERVER["PHP_SELF"];
7091 7091
                     // Clean $relativepathstring
7092 7092
                     if (constant('DOL_BASE_URI'))
7093
-                        $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7093
+                        $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
7094 7094
                     $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
7095 7095
                     $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
7096 7096
                     $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
@@ -7113,9 +7113,9 @@  discard block
 block discarded – undo
7113 7113
                             if ($qualified) {
7114 7114
                                 foreach ($defval as $paramkey => $paramval) {
7115 7115
                                     // Set focus on field
7116
-                                    print 'jQuery("input[name=\'' . $paramkey . '\']").focus();' . "\n";
7117
-                                    print 'jQuery("textarea[name=\'' . $paramkey . '\']").focus();' . "\n";
7118
-                                    print 'jQuery("select[name=\'' . $paramkey . '\']").focus();' . "\n";  // Not really usefull, but we keep it in case of.
7116
+                                    print 'jQuery("input[name=\''.$paramkey.'\']").focus();'."\n";
7117
+                                    print 'jQuery("textarea[name=\''.$paramkey.'\']").focus();'."\n";
7118
+                                    print 'jQuery("select[name=\''.$paramkey.'\']").focus();'."\n"; // Not really usefull, but we keep it in case of.
7119 7119
                                 }
7120 7120
                             }
7121 7121
                         }
@@ -7139,16 +7139,16 @@  discard block
 block discarded – undo
7139 7139
                             if ($qualified) {
7140 7140
                                 foreach ($defval as $paramkey => $paramval) {
7141 7141
                                     // Add property 'required' on input
7142
-                                    print 'jQuery("input[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";
7143
-                                    print 'jQuery("textarea[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";
7144
-                                    print 'jQuery("select[name=\'' . $paramkey . '\']").prop(\'required\',true);' . "\n";  // required on a select works only if key is "", this does not happen in Dolibarr
7142
+                                    print 'jQuery("input[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
7143
+                                    print 'jQuery("textarea[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n";
7144
+                                    print 'jQuery("select[name=\''.$paramkey.'\']").prop(\'required\',true);'."\n"; // required on a select works only if key is "", this does not happen in Dolibarr
7145 7145
                                 }
7146 7146
                             }
7147 7147
                         }
7148 7148
                     }
7149 7149
                 }
7150 7150
 
7151
-                print '});' . "\n";
7151
+                print '});'."\n";
7152 7152
 
7153 7153
 // Google Analytics
7154 7154
 // TODO Add a hook here
@@ -7156,15 +7156,15 @@  discard block
 block discarded – undo
7156 7156
                     if ((Globals::$conf->dol_use_jmobile != 4)) {
7157 7157
                         print "\n";
7158 7158
                         print "/* JS CODE TO ENABLE for google analtics tag */\n";
7159
-                        print '  var _gaq = _gaq || [];' . "\n";
7160
-                        print '  _gaq.push([\'_setAccount\', \'' . Globals::$conf->global->MAIN_GOOGLE_AN_ID . '\']);' . "\n";
7161
-                        print '  _gaq.push([\'_trackPageview\']);' . "\n";
7162
-                        print '' . "\n";
7163
-                        print '  (function() {' . "\n";
7164
-                        print '    var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;' . "\n";
7165
-                        print '    ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';' . "\n";
7166
-                        print '    var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);' . "\n";
7167
-                        print '  })();' . "\n";
7159
+                        print '  var _gaq = _gaq || [];'."\n";
7160
+                        print '  _gaq.push([\'_setAccount\', \''.Globals::$conf->global->MAIN_GOOGLE_AN_ID.'\']);'."\n";
7161
+                        print '  _gaq.push([\'_trackPageview\']);'."\n";
7162
+                        print ''."\n";
7163
+                        print '  (function() {'."\n";
7164
+                        print '    var ga = document.createElement(\'script\'); ga.type = \'text/javascript\'; ga.async = true;'."\n";
7165
+                        print '    ga.src = (\'https:\' == document.location.protocol ? \'https://ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';'."\n";
7166
+                        print '    var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(ga, s);'."\n";
7167
+                        print '  })();'."\n";
7168 7168
                     }
7169 7169
                 }
7170 7170
 
@@ -7174,27 +7174,27 @@  discard block
 block discarded – undo
7174 7174
                     print "/* JS CODE TO ENABLE to add memory info */\n";
7175 7175
                     print 'window.console && console.log("';
7176 7176
                     if (!empty(Globals::$conf->global->MEMCACHED_SERVER))
7177
-                        print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7178
-                    print 'MAIN_OPTIMIZE_SPEED=' . (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7177
+                        print 'MEMCACHED_SERVER='.Globals::$conf->global->MEMCACHED_SERVER.' - ';
7178
+                    print 'MAIN_OPTIMIZE_SPEED='.(isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7179 7179
                     if (!empty($micro_start_time)) {   // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in// global variable.
7180 7180
                         $micro_end_time = microtime(true);
7181
-                        print ' - Build time: ' . ceil(1000 * ($micro_end_time - $micro_start_time)) . ' ms';
7181
+                        print ' - Build time: '.ceil(1000 * ($micro_end_time - $micro_start_time)).' ms';
7182 7182
                     }
7183 7183
                     if (function_exists("memory_get_usage")) {
7184
-                        print ' - Mem: ' . memory_get_usage();
7184
+                        print ' - Mem: '.memory_get_usage();
7185 7185
                     }
7186 7186
                     if (function_exists("xdebug_memory_usage")) {
7187
-                        print ' - XDebug time: ' . ceil(1000 * xdebug_time_index()) . ' ms';
7188
-                        print ' - XDebug mem: ' . xdebug_memory_usage();
7189
-                        print ' - XDebug mem peak: ' . xdebug_peak_memory_usage();
7187
+                        print ' - XDebug time: '.ceil(1000 * xdebug_time_index()).' ms';
7188
+                        print ' - XDebug mem: '.xdebug_memory_usage();
7189
+                        print ' - XDebug mem peak: '.xdebug_peak_memory_usage();
7190 7190
                     }
7191 7191
                     if (function_exists("zend_loader_file_encoded")) {
7192
-                        print ' - Zend encoded file: ' . (zend_loader_file_encoded() ? 'yes' : 'no');
7192
+                        print ' - Zend encoded file: '.(zend_loader_file_encoded() ? 'yes' : 'no');
7193 7193
                     }
7194
-                    print '");' . "\n";
7194
+                    print '");'."\n";
7195 7195
                 }
7196 7196
 
7197
-                print "\n" . '</script>' . "\n";
7197
+                print "\n".'</script>'."\n";
7198 7198
             }
7199 7199
 
7200 7200
 // Add Xdebug coverage of code
@@ -7208,7 +7208,7 @@  discard block
 block discarded – undo
7208 7208
                 print "<!-- Start of log output\n";
7209 7209
 //print '<div class="hidden">'."\n";
7210 7210
                 foreach (Globals::$conf->logbuffer as $logline) {
7211
-                    print $logline . "<br>\n";
7211
+                    print $logline."<br>\n";
7212 7212
                 }
7213 7213
 //print '</div>'."\n";
7214 7214
                 print "End of log output -->\n";
@@ -7251,8 +7251,8 @@  discard block
 block discarded – undo
7251 7251
      */
7252 7252
     static function dol_set_focus($selector)
7253 7253
     {
7254
-        print "\n" . '<!-- Set focus onto a specific field -->' . "\n";
7255
-        print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("' . dol_escape_js($selector) . '").focus(); });</script>' . "\n";
7254
+        print "\n".'<!-- Set focus onto a specific field -->'."\n";
7255
+        print '<script type="text/javascript" language="javascript">jQuery(document).ready(function() { jQuery("'.dol_escape_js($selector).'").focus(); });</script>'."\n";
7256 7256
     }
7257 7257
 
7258 7258
     /**
@@ -7297,7 +7297,7 @@  discard block
 block discarded – undo
7297 7297
             $value = preg_replace('/\*/', '%', $value); // Replace * with %
7298 7298
         }
7299 7299
         if ($mode == 1) {
7300
-            $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
7300
+            $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
7301 7301
         }
7302 7302
 
7303 7303
         $value = preg_replace('/\s*\|\s*/', '|', $value);
@@ -7326,14 +7326,14 @@  discard block
 block discarded – undo
7326 7326
                     if ($newcrit != '') {
7327 7327
                         $numnewcrit = price2num($newcrit);
7328 7328
                         if (is_numeric($numnewcrit)) {
7329
-                            $newres .= ($i2 > 0 ? ' OR ' : '') . $field . ' ' . $operator . ' ' . $numnewcrit;
7329
+                            $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$numnewcrit;
7330 7330
                         } else {
7331
-                            $newres .= ($i2 > 0 ? ' OR ' : '') . '1 = 2'; // force false
7331
+                            $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false
7332 7332
                         }
7333 7333
                         $i2++; // a criteria was added to string
7334 7334
                     }
7335 7335
                 } else if ($mode == 2) {
7336
-                    $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $db->escape(trim($crit)) . ")";
7336
+                    $newres .= ($i2 > 0 ? ' OR ' : '').$field." IN (".$db->escape(trim($crit)).")";
7337 7337
                     $i2++; // a criteria was added to string
7338 7338
                 } else if ($mode == 3) {
7339 7339
                     $tmparray = explode(',', trim($crit));
@@ -7342,10 +7342,10 @@  discard block
 block discarded – undo
7342 7342
                         foreach ($tmparray as $val) {
7343 7343
                             if ($val) {
7344 7344
                                 $listofcodes .= ($listofcodes ? ',' : '');
7345
-                                $listofcodes .= "'" . $db->escape(trim($val)) . "'";
7345
+                                $listofcodes .= "'".$db->escape(trim($val))."'";
7346 7346
                             }
7347 7347
                         }
7348
-                        $newres .= ($i2 > 0 ? ' OR ' : '') . $field . " IN (" . $listofcodes . ")";
7348
+                        $newres .= ($i2 > 0 ? ' OR ' : '').$field." IN (".$listofcodes.")";
7349 7349
                         $i2++; // a criteria was added to string
7350 7350
                     }
7351 7351
                 } else if ($mode == 4) {
@@ -7354,10 +7354,10 @@  discard block
 block discarded – undo
7354 7354
                         $listofcodes = '';
7355 7355
                         foreach ($tmparray as $val) {
7356 7356
                             if ($val) {
7357
-                                $newres .= ($i2 > 0 ? ' OR (' : '(') . $field . ' LIKE \'' . $db->escape(trim($val)) . ',%\'';
7358
-                                $newres .= ' OR ' . $field . ' = \'' . $db->escape(trim($val)) . '\'';
7359
-                                $newres .= ' OR ' . $field . ' LIKE \'%,' . $db->escape(trim($val)) . '\'';
7360
-                                $newres .= ' OR ' . $field . ' LIKE \'%,' . $db->escape(trim($val)) . ',%\'';
7357
+                                $newres .= ($i2 > 0 ? ' OR (' : '(').$field.' LIKE \''.$db->escape(trim($val)).',%\'';
7358
+                                $newres .= ' OR '.$field.' = \''.$db->escape(trim($val)).'\'';
7359
+                                $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).'\'';
7360
+                                $newres .= ' OR '.$field.' LIKE \'%,'.$db->escape(trim($val)).',%\'';
7361 7361
                                 $newres .= ')';
7362 7362
                                 $i2++;
7363 7363
                             }
@@ -7374,9 +7374,9 @@  discard block
 block discarded – undo
7374 7374
                         $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
7375 7375
 
7376 7376
                         if (preg_match('/\.(id|rowid)$/', $field)) { // Special case for rowid that is sometimes a ref so used as a search field
7377
-                            $newres .= $field . " = " . (is_numeric(trim($tmpcrit)) ? trim($tmpcrit) : '0');
7377
+                            $newres .= $field." = ".(is_numeric(trim($tmpcrit)) ? trim($tmpcrit) : '0');
7378 7378
                         } else {
7379
-                            $newres .= $field . " LIKE '";
7379
+                            $newres .= $field." LIKE '";
7380 7380
 
7381 7381
                             $tmpcrit = trim($tmpcrit);
7382 7382
                             $tmpcrit2 = $tmpcrit;
@@ -7395,7 +7395,7 @@  discard block
 block discarded – undo
7395 7395
                             $newres .= $tmpafter;
7396 7396
                             $newres .= "'";
7397 7397
                             if ($tmpcrit2 == '') {
7398
-                                $newres .= ' OR ' . $field . " IS NULL";
7398
+                                $newres .= ' OR '.$field." IS NULL";
7399 7399
                             }
7400 7400
                         }
7401 7401
 
@@ -7406,10 +7406,10 @@  discard block
 block discarded – undo
7406 7406
                 $i++;
7407 7407
             }
7408 7408
             if ($newres)
7409
-                $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7409
+                $res = $res.($res ? ' AND ' : '').($i2 > 1 ? '(' : '').$newres.($i2 > 1 ? ')' : '');
7410 7410
             $j++;
7411 7411
         }
7412
-        $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
7412
+        $res = ($nofirstand ? "" : " AND ")."(".$res.")";
7413 7413
 //print 'xx'.$res.'yy';
7414 7414
         return $res;
7415 7415
     }
@@ -7428,8 +7428,8 @@  discard block
 block discarded – undo
7428 7428
         $url = $object->getLastMainDocLink($object->element);
7429 7429
 
7430 7430
         if ($url) {
7431
-            $out .= img_picto('', 'object_globe.png') . ' ' . Globals::$langs->trans("DirectDownloadLink") . '<br>';
7432
-            $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="' . $url . '">';
7431
+            $out .= img_picto('', 'object_globe.png').' '.Globals::$langs->trans("DirectDownloadLink").'<br>';
7432
+            $out .= '<input type="text" id="directdownloadlink" class="quatrevingtpercent" value="'.$url.'">';
7433 7433
             $out .= ajax_autoselect("directdownloadlink", 0);
7434 7434
         }
7435 7435
         return $out;
@@ -7470,7 +7470,7 @@  discard block
 block discarded – undo
7470 7470
         if ($extName)
7471 7471
             $subdir = 'thumbs/';
7472 7472
 
7473
-        return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
7473
+        return ($dirName ? $dirName.'/' : '').$subdir.$fileName.$extName.$extImgTarget; // New filename for thumb
7474 7474
     }
7475 7475
 
7476 7476
     /**
@@ -7496,14 +7496,14 @@  discard block
 block discarded – undo
7496 7496
 
7497 7497
         if ($alldata == 1) {
7498 7498
             if ($num_mime !== false)
7499
-                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),);
7499
+                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),);
7500 7500
             else
7501 7501
                 return array();
7502 7502
         }
7503 7503
 
7504 7504
 // old behavior
7505 7505
         if ($num_mime !== false)
7506
-            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')) . '\')';
7506
+            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')).'\')';
7507 7507
         else
7508 7508
             return '';
7509 7509
     }
@@ -7520,11 +7520,11 @@  discard block
 block discarded – undo
7520 7520
        // global Globals::$langs;
7521 7521
         $out = '<script type="text/javascript">
7522 7522
                jQuery(document).ready(static function () {
7523
-				    jQuery("#' . $htmlname . '").click(function() { jQuery(this).select(); } );
7523
+				    jQuery("#' . $htmlname.'").click(function() { jQuery(this).select(); } );
7524 7524
 				});
7525 7525
 		    </script>';
7526 7526
         if ($addlink)
7527
-            $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7527
+            $out .= ' <a href="'.$addlink.'" target="_blank">'.Globals::$langs->trans("Link").'</a>';
7528 7528
         return $out;
7529 7529
     }
7530 7530
 
@@ -7905,9 +7905,9 @@  discard block
 block discarded – undo
7905 7905
 
7906 7906
         if (!isset($dictvalues[$tablename])) {
7907 7907
             $dictvalues[$tablename] = array();
7908
-            $sql = 'SELECT * FROM ' . $tablename . ' WHERE 1';
7908
+            $sql = 'SELECT * FROM '.$tablename.' WHERE 1';
7909 7909
             if ($checkentity)
7910
-                $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
7910
+                $sql .= ' AND entity IN (0,'.getEntity($tablename).')';
7911 7911
 
7912 7912
             $resql = $db->query($sql);
7913 7913
             if ($resql) {
@@ -7945,14 +7945,14 @@  discard block
 block discarded – undo
7945 7945
                 $g = $tmp[1];
7946 7946
                 $b = $tmp[2];
7947 7947
             } else {
7948
-                $hexr = $stringcolor[0] . $stringcolor[1];
7949
-                $hexg = $stringcolor[2] . $stringcolor[3];
7950
-                $hexb = $stringcolor[4] . $stringcolor[5];
7948
+                $hexr = $stringcolor[0].$stringcolor[1];
7949
+                $hexg = $stringcolor[2].$stringcolor[3];
7950
+                $hexb = $stringcolor[4].$stringcolor[5];
7951 7951
                 $r = hexdec($hexr);
7952 7952
                 $g = hexdec($hexg);
7953 7953
                 $b = hexdec($hexb);
7954 7954
             }
7955
-            $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0;    // HSL algorithm
7955
+            $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0; // HSL algorithm
7956 7956
             if ($bright > 0.6)
7957 7957
                 $res = 1;
7958 7958
         }
@@ -7987,11 +7987,11 @@  discard block
 block discarded – undo
7987 7987
                 return 0; // Entry is for menus all excluded to external users
7988 7988
         }
7989 7989
         if (!$menuentry['perms'] && $type_user)
7990
-            return 0;            // No permissions and user is external
7990
+            return 0; // No permissions and user is external
7991 7991
         if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED))
7992 7992
             return 0; // No permissions and option to hide when not allowed, even for internal user, is on
7993 7993
         if (!$menuentry['perms'])
7994
-            return 2;               // No permissions and user is external
7994
+            return 2; // No permissions and user is external
7995 7995
         return 1;
7996 7996
     }
7997 7997
 
Please login to merge, or discard this patch.
Braces   +1453 added lines, -1047 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
             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
 
@@ -577,18 +594,20 @@  discard block
 block discarded – undo
577 594
                 }
578 595
                 break;
579 596
             case 'intcomma':
580
-                if (preg_match('/[^0-9,-]+/i', $out))
581
-                    $out = '';
597
+                if (preg_match('/[^0-9,-]+/i', $out)) {
598
+                                    $out = '';
599
+                }
582 600
                 break;
583 601
             case 'alpha':
584 602
                 if (!is_array($out)) {
585 603
                     $out = trim($out);
586 604
                     // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
587 605
                     // '../' is dangerous because it allows dir transversals
588
-                    if (preg_match('/"/', $out))
589
-                        $out = '';
590
-                    else if (preg_match('/\.\.\//', $out))
591
-                        $out = '';
606
+                    if (preg_match('/"/', $out)) {
607
+                                            $out = '';
608
+                    } else if (preg_match('/\.\.\//', $out)) {
609
+                                            $out = '';
610
+                    }
592 611
                 }
593 612
                 break;
594 613
             case 'san_alpha':
@@ -597,27 +616,31 @@  discard block
 block discarded – undo
597 616
             case 'aZ':
598 617
                 if (!is_array($out)) {
599 618
                     $out = trim($out);
600
-                    if (preg_match('/[^a-z]+/i', $out))
601
-                        $out = '';
619
+                    if (preg_match('/[^a-z]+/i', $out)) {
620
+                                            $out = '';
621
+                    }
602 622
                 }
603 623
                 break;
604 624
             case 'aZ09':
605 625
                 if (!is_array($out)) {
606 626
                     $out = trim($out);
607
-                    if (preg_match('/[^a-z0-9_\-\.]+/i', $out))
608
-                        $out = '';
627
+                    if (preg_match('/[^a-z0-9_\-\.]+/i', $out)) {
628
+                                            $out = '';
629
+                    }
609 630
                 }
610 631
                 break;
611 632
             case 'aZ09comma':  // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
612 633
                 if (!is_array($out)) {
613 634
                     $out = trim($out);
614
-                    if (preg_match('/[^a-z0-9_\-\.,]+/i', $out))
615
-                        $out = '';
635
+                    if (preg_match('/[^a-z0-9_\-\.,]+/i', $out)) {
636
+                                            $out = '';
637
+                    }
616 638
                 }
617 639
                 break;
618 640
             case 'array':
619
-                if (!is_array($out) || empty($out))
620
-                    $out = array();
641
+                if (!is_array($out) || empty($out)) {
642
+                                    $out = array();
643
+                }
621 644
                 break;
622 645
             case 'nohtml':  // Recommended for most scalar parameters
623 646
                 $out = dol_string_nohtmltag($out, 0);
@@ -627,16 +650,18 @@  discard block
 block discarded – undo
627 650
                     $out = trim($out);
628 651
                     // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
629 652
                     // '../' is dangerous because it allows dir transversals
630
-                    if (preg_match('/"/', $out))
631
-                        $out = '';
632
-                    else if (preg_match('/\.\.\//', $out))
633
-                        $out = '';
653
+                    if (preg_match('/"/', $out)) {
654
+                                            $out = '';
655
+                    } else if (preg_match('/\.\.\//', $out)) {
656
+                                            $out = '';
657
+                    }
634 658
                     $out = dol_string_nohtmltag($out);
635 659
                 }
636 660
                 break;
637 661
             case 'custom':
638
-                if (empty($filter))
639
-                    return 'BadFourthParameterForDolUtils::GETPOST';
662
+                if (empty($filter)) {
663
+                                    return 'BadFourthParameterForDolUtils::GETPOST';
664
+                }
640 665
                 $out = filter_var($out, $filter, $options);
641 666
                 break;
642 667
         }
@@ -754,11 +779,11 @@  discard block
 block discarded – undo
754 779
                 }
755 780
             }
756 781
             if ($returnemptyifnotfound) {        // Not found into alternate dir
757
-                if ($returnemptyifnotfound == 1 || !file_exists($res))
758
-                    return '';
782
+                if ($returnemptyifnotfound == 1 || !file_exists($res)) {
783
+                                    return '';
784
+                }
759 785
             }
760
-        }
761
-        else {    // For an url path
786
+        } else {    // For an url path
762 787
 // We try to get local path of file on filesystem from url
763 788
 // Note that trying to know if a file on disk exist by forging path on disk from url
764 789
 // works only for some web server and some setup. This is bugged when
@@ -853,12 +878,14 @@  discard block
 block discarded – undo
853 878
     static function dol_size($size, $type = '')
854 879
     {
855 880
         //global Globals::$conf;
856
-        if (empty(Globals::$conf->dol_optimize_smallscreen))
857
-            return $size;
858
-        if ($type == 'width' && $size > 250)
859
-            return 250;
860
-        else
861
-            return 10;
881
+        if (empty(Globals::$conf->dol_optimize_smallscreen)) {
882
+                    return $size;
883
+        }
884
+        if ($type == 'width' && $size > 250) {
885
+                    return 250;
886
+        } else {
887
+                    return 10;
888
+        }
862 889
     }
863 890
 
864 891
     /**
@@ -958,9 +985,10 @@  discard block
 block discarded – undo
958 985
     {
959 986
         $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°');  // more complete than dol_sanitizeFileName
960 987
         $forbidden_chars_to_remove = array();
961
-        if (is_array($badcharstoreplace))
962
-            $forbidden_chars_to_replace = $badcharstoreplace;
963
-//$forbidden_chars_to_remove=array("(",")");
988
+        if (is_array($badcharstoreplace)) {
989
+                    $forbidden_chars_to_replace = $badcharstoreplace;
990
+        }
991
+        //$forbidden_chars_to_remove=array("(",")");
964 992
 
965 993
         return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
966 994
     }
@@ -996,9 +1024,9 @@  discard block
 block discarded – undo
996 1024
         if (empty($mode)) {
997 1025
             $substitjs["'"] = "\\'";
998 1026
             $substitjs['"'] = "\\'";
999
-        } else if ($mode == 1)
1000
-            $substitjs["'"] = "\\'";
1001
-        else if ($mode == 2) {
1027
+        } else if ($mode == 1) {
1028
+                    $substitjs["'"] = "\\'";
1029
+        } else if ($mode == 2) {
1002 1030
             $substitjs['"'] = '\\"';
1003 1031
         } else if ($mode == 3) {
1004 1032
             $substitjs["'"] = "\\'";
@@ -1020,10 +1048,12 @@  discard block
 block discarded – undo
1020 1048
     {
1021 1049
 // escape quotes and backslashes, newlines, etc.
1022 1050
         $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');  // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1023
-        if (!$keepb)
1024
-            $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1025
-        if (!$keepn)
1026
-            $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1051
+        if (!$keepb) {
1052
+                    $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1053
+        }
1054
+        if (!$keepn) {
1055
+                    $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1056
+        }
1027 1057
         return htmlentities($tmp, ENT_COMPAT, 'UTF-8');      // TODO Use htmlspecialchars instead, that make only required change for html tags
1028 1058
     }
1029 1059
 
@@ -1073,8 +1103,9 @@  discard block
 block discarded – undo
1073 1103
     {
1074 1104
        // global Globals::$conf, $user;
1075 1105
 // If syslog module enabled
1076
-        if (empty(Globals::$conf->syslog->enabled))
1077
-            return;
1106
+        if (empty(Globals::$conf->syslog->enabled)) {
1107
+                    return;
1108
+        }
1078 1109
 
1079 1110
         if ($ident < 0) {
1080 1111
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
@@ -1088,8 +1119,9 @@  discard block
 block discarded – undo
1088 1119
             if (!in_array($level, $logLevels, true)) {
1089 1120
                 throw new Exception('Incorrect log level');
1090 1121
             }
1091
-            if ($level > Globals::$conf->global->SYSLOG_LEVEL)
1092
-                return;
1122
+            if ($level > Globals::$conf->global->SYSLOG_LEVEL) {
1123
+                            return;
1124
+            }
1093 1125
 
1094 1126
             $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1095 1127
 // If adding log inside HTML page is required
@@ -1114,24 +1146,30 @@  discard block
 block discarded – undo
1114 1146
             );
1115 1147
 
1116 1148
 // This is when server run behind a reverse proxy
1117
-            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
1118
-                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1119
-// This is when server run normally on a server
1120
-            else if (!empty($_SERVER["REMOTE_ADDR"]))
1121
-                $data['ip'] = $_SERVER['REMOTE_ADDR'];
1122
-// This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1123
-            else if (!empty($_SERVER['SERVER_ADDR']))
1124
-                $data['ip'] = $_SERVER['SERVER_ADDR'];
1125
-// 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).
1126
-            else if (!empty($_SERVER['COMPUTERNAME']))
1127
-                $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1128
-// 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).
1129
-            else if (!empty($_SERVER['LOGNAME']))
1130
-                $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1131
-// Loop on each log handler and send output
1149
+            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
1150
+                            $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1151
+            }
1152
+            // This is when server run normally on a server
1153
+            else if (!empty($_SERVER["REMOTE_ADDR"])) {
1154
+                            $data['ip'] = $_SERVER['REMOTE_ADDR'];
1155
+            }
1156
+            // This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1157
+            else if (!empty($_SERVER['SERVER_ADDR'])) {
1158
+                            $data['ip'] = $_SERVER['SERVER_ADDR'];
1159
+            }
1160
+            // 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).
1161
+            else if (!empty($_SERVER['COMPUTERNAME'])) {
1162
+                            $data['ip'] = $_SERVER['COMPUTERNAME'] . (empty($_SERVER['USERNAME']) ? '' : '@' . $_SERVER['USERNAME']);
1163
+            }
1164
+            // 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).
1165
+            else if (!empty($_SERVER['LOGNAME'])) {
1166
+                            $data['ip'] = '???@' . $_SERVER['LOGNAME'];
1167
+            }
1168
+            // Loop on each log handler and send output
1132 1169
             foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
1133
-                if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler)
1134
-                    continue;
1170
+                if ($restricttologhandler && $loghandlerinstance->code != $restricttologhandler) {
1171
+                                    continue;
1172
+                }
1135 1173
                 $loghandlerinstance->export($data, $suffixinfilename);
1136 1174
             }
1137 1175
             unset($data);
@@ -1187,13 +1225,15 @@  discard block
 block discarded – undo
1187 1225
 
1188 1226
 // Show title
1189 1227
         $showtitle = 1;
1190
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
1191
-            $showtitle = 0;
1228
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1229
+                    $showtitle = 0;
1230
+        }
1192 1231
         if (!empty($title) && $showtitle) {
1193 1232
             $limittitle = 30;
1194 1233
             $out .= '<a class="tabTitle">';
1195
-            if ($picto)
1196
-                $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1234
+            if ($picto) {
1235
+                            $out .= img_picto($title, ($pictoisfullpath ? '' : 'object_') . $picto, '', $pictoisfullpath) . ' ';
1236
+            }
1197 1237
             $out .= '<span class="tabTitleText">' . dol_trunc($title, $limittitle) . '</span>';
1198 1238
             $out .= '</a>';
1199 1239
         }
@@ -1202,12 +1242,14 @@  discard block
 block discarded – undo
1202 1242
         $maxkey = -1;
1203 1243
         if (is_array($links) && !empty($links)) {
1204 1244
             $keys = array_keys($links);
1205
-            if (count($keys))
1206
-                $maxkey = max($keys);
1245
+            if (count($keys)) {
1246
+                            $maxkey = max($keys);
1247
+            }
1207 1248
         }
1208 1249
 
1209
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
1210
-            Globals::$conf->global->MAIN_MAXTABS_IN_CARD = 2;
1250
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1251
+                    Globals::$conf->global->MAIN_MAXTABS_IN_CARD = 2;
1252
+        }
1211 1253
 
1212 1254
 // Show tabs
1213 1255
         $bactive = false;
@@ -1220,8 +1262,9 @@  discard block
 block discarded – undo
1220 1262
         for ($i = 0; $i <= $maxkey; $i++) {
1221 1263
             if ((is_numeric($active) && $i == $active) || (!empty($links[$i][2]) && !is_numeric($active) && $active == $links[$i][2])) {
1222 1264
 // If active tab is already present
1223
-                if ($i >= $limittoshow)
1224
-                    $limittoshow--;
1265
+                if ($i >= $limittoshow) {
1266
+                                    $limittoshow--;
1267
+                }
1225 1268
             }
1226 1269
         }
1227 1270
 
@@ -1262,12 +1305,12 @@  discard block
 block discarded – undo
1262 1305
                 }
1263 1306
                 $outmore .= '<div class="popuptab wordwrap" style="display:inherit;">';
1264 1307
                 if (isset($links[$i][2]) && $links[$i][2] == 'image') {
1265
-                    if (!empty($links[$i][0]))
1266
-                        $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1267
-                    else
1268
-                        $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1269
-                }
1270
-                else if (!empty($links[$i][1])) {
1308
+                    if (!empty($links[$i][0])) {
1309
+                                            $outmore .= '<a class="tabimage' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">' . $links[$i][1] . '</a>' . "\n";
1310
+                    } else {
1311
+                                            $outmore .= '<span class="tabspan">' . $links[$i][1] . '</span>' . "\n";
1312
+                    }
1313
+                } else if (!empty($links[$i][1])) {
1271 1314
                     $outmore .= '<a' . (!empty($links[$i][2]) ? ' id="' . $links[$i][2] . '"' : '') . ' class="wordwrap inline-block' . ($morecss ? ' ' . $morecss : '') . '" href="' . $links[$i][0] . '">';
1272 1315
                     $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.
1273 1316
                     $outmore .= '</a>' . "\n";
@@ -1278,8 +1321,9 @@  discard block
 block discarded – undo
1278 1321
             }
1279 1322
             $displaytab = $i;
1280 1323
         }
1281
-        if ($popuptab)
1282
-            $outmore .= '</div>';
1324
+        if ($popuptab) {
1325
+                    $outmore .= '</div>';
1326
+        }
1283 1327
 
1284 1328
         if ($displaytab > $limittoshow) {
1285 1329
             $left = (Globals::$langs->trans("DIRECTION") == 'rtl' ? 'right' : 'left');
@@ -1302,8 +1346,9 @@  discard block
 block discarded – undo
1302 1346
 
1303 1347
         $out .= "</div>\n";
1304 1348
 
1305
-        if (!$notab || $notab == -1)
1306
-            $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1349
+        if (!$notab || $notab == -1) {
1350
+                    $out .= "\n" . '<div class="tabBar' . ($notab == -1 ? '' : ' tabBarWithBottom') . '">' . "\n";
1351
+        }
1307 1352
 
1308 1353
         $parameters = array('tabname' => $active, 'out' => $out);
1309 1354
         $reshook = $hookmanager->executeHooks('printTabsHead', $parameters); // This hook usage is called just before output the head of tabs. Take also a look at "completeTabsHead"
@@ -1333,10 +1378,11 @@  discard block
 block discarded – undo
1333 1378
      */
1334 1379
     static function dol_get_fiche_end($notab = 0)
1335 1380
     {
1336
-        if (!$notab || $notab == -1)
1337
-            return "\n</div>\n";
1338
-        else
1339
-            return '';
1381
+        if (!$notab || $notab == -1) {
1382
+                    return "\n</div>\n";
1383
+        } else {
1384
+                    return '';
1385
+        }
1340 1386
     }
1341 1387
 
1342 1388
     /**
@@ -1368,40 +1414,55 @@  discard block
 block discarded – undo
1368 1414
         $showimage = 1;
1369 1415
         $entity = (empty($object->entity) ? Globals::$conf->entity : $object->entity);
1370 1416
         $showbarcode = empty(Globals::$conf->barcode->enabled) ? 0 : ($object->barcode ? 1 : 0);
1371
-        if (!empty(Globals::$conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance))
1372
-            $showbarcode = 0;
1417
+        if (!empty(Globals::$conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->barcode->lire_advance)) {
1418
+                    $showbarcode = 0;
1419
+        }
1373 1420
         $modulepart = 'unknown';
1374 1421
 
1375
-        if ($object->element == 'societe')
1376
-            $modulepart = 'societe';
1377
-        if ($object->element == 'contact')
1378
-            $modulepart = 'contact';
1379
-        if ($object->element == 'member')
1380
-            $modulepart = 'memberphoto';
1381
-        if ($object->element == 'user')
1382
-            $modulepart = 'userphoto';
1383
-        if ($object->element == 'product')
1384
-            $modulepart = 'product';
1422
+        if ($object->element == 'societe') {
1423
+                    $modulepart = 'societe';
1424
+        }
1425
+        if ($object->element == 'contact') {
1426
+                    $modulepart = 'contact';
1427
+        }
1428
+        if ($object->element == 'member') {
1429
+                    $modulepart = 'memberphoto';
1430
+        }
1431
+        if ($object->element == 'user') {
1432
+                    $modulepart = 'userphoto';
1433
+        }
1434
+        if ($object->element == 'product') {
1435
+                    $modulepart = 'product';
1436
+        }
1385 1437
 
1386 1438
         if (class_exists("Imagick")) {
1387
-            if ($object->element == 'propal')
1388
-                $modulepart = 'propal';
1389
-            if ($object->element == 'commande')
1390
-                $modulepart = 'commande';
1391
-            if ($object->element == 'facture')
1392
-                $modulepart = 'facture';
1393
-            if ($object->element == 'fichinter')
1394
-                $modulepart = 'ficheinter';
1395
-            if ($object->element == 'contrat')
1396
-                $modulepart = 'contract';
1397
-            if ($object->element == 'supplier_proposal')
1398
-                $modulepart = 'supplier_proposal';
1399
-            if ($object->element == 'order_supplier')
1400
-                $modulepart = 'supplier_order';
1401
-            if ($object->element == 'invoice_supplier')
1402
-                $modulepart = 'supplier_invoice';
1403
-            if ($object->element == 'expensereport')
1404
-                $modulepart = 'expensereport';
1439
+            if ($object->element == 'propal') {
1440
+                            $modulepart = 'propal';
1441
+            }
1442
+            if ($object->element == 'commande') {
1443
+                            $modulepart = 'commande';
1444
+            }
1445
+            if ($object->element == 'facture') {
1446
+                            $modulepart = 'facture';
1447
+            }
1448
+            if ($object->element == 'fichinter') {
1449
+                            $modulepart = 'ficheinter';
1450
+            }
1451
+            if ($object->element == 'contrat') {
1452
+                            $modulepart = 'contract';
1453
+            }
1454
+            if ($object->element == 'supplier_proposal') {
1455
+                            $modulepart = 'supplier_proposal';
1456
+            }
1457
+            if ($object->element == 'order_supplier') {
1458
+                            $modulepart = 'supplier_order';
1459
+            }
1460
+            if ($object->element == 'invoice_supplier') {
1461
+                            $modulepart = 'supplier_invoice';
1462
+            }
1463
+            if ($object->element == 'expensereport') {
1464
+                            $modulepart = 'expensereport';
1465
+            }
1405 1466
         }
1406 1467
 
1407 1468
         if ($object->element == 'product') {
@@ -1409,11 +1470,12 @@  discard block
 block discarded – undo
1409 1470
             $cssclass = 'photoref';
1410 1471
             $showimage = $object->is_photo_available(Globals::$conf->product->multidir_output[$entity]);
1411 1472
             $maxvisiblephotos = (isset(Globals::$conf->global->PRODUCT_MAX_VISIBLE_PHOTO) ? Globals::$conf->global->PRODUCT_MAX_VISIBLE_PHOTO : 5);
1412
-            if (Globals::$conf->browser->layout == 'phone')
1413
-                $maxvisiblephotos = 1;
1414
-            if ($showimage)
1415
-                $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>';
1416
-            else {
1473
+            if (Globals::$conf->browser->layout == 'phone') {
1474
+                            $maxvisiblephotos = 1;
1475
+            }
1476
+            if ($showimage) {
1477
+                            $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>';
1478
+            } else {
1417 1479
                 if (!empty(Globals::$conf->global->PRODUCT_NODISPLAYIFNOPHOTO)) {
1418 1480
                     $nophoto = '';
1419 1481
                     $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
@@ -1429,11 +1491,12 @@  discard block
 block discarded – undo
1429 1491
             $cssclass = 'photoref';
1430 1492
             $showimage = $object->is_photo_available(Globals::$conf->ticket->multidir_output[$entity] . '/' . $object->track_id);
1431 1493
             $maxvisiblephotos = (isset(Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO) ? Globals::$conf->global->TICKETSUP_MAX_VISIBLE_PHOTO : 2);
1432
-            if (Globals::$conf->browser->layout == 'phone')
1433
-                $maxvisiblephotos = 1;
1434
-            if ($showimage)
1435
-                $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>';
1436
-            else {
1494
+            if (Globals::$conf->browser->layout == 'phone') {
1495
+                            $maxvisiblephotos = 1;
1496
+            }
1497
+            if ($showimage) {
1498
+                            $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>';
1499
+            } else {
1437 1500
                 if (!empty(Globals::$conf->global->TICKETSUP_NODISPLAYIFNOPHOTO)) {
1438 1501
                     $nophoto = '';
1439 1502
                     $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref"></div>';
@@ -1458,8 +1521,10 @@  discard block
 block discarded – undo
1458 1521
                         } else {
1459 1522
                             $subdir = get_exdir($object->id, 0, 0, 1, $object, $modulepart);
1460 1523
                         }
1461
-                        if (empty($subdir))
1462
-                            $subdir = 'errorgettingsubdirofobject'; // Protection to avoid to return empty path
1524
+                        if (empty($subdir)) {
1525
+                                                    $subdir = 'errorgettingsubdirofobject';
1526
+                        }
1527
+                        // Protection to avoid to return empty path
1463 1528
 
1464 1529
                         $filepath = $dir_output . $subdir . "/";
1465 1530
 
@@ -1480,14 +1545,16 @@  discard block
 block discarded – undo
1480 1545
                                 if (empty(Globals::$conf->global->MAIN_DISABLE_PDF_THUMBS)) {  // If you experienc trouble with pdf thumb generation and imagick, you can disable here.
1481 1546
                                     include_once DOL_BASE_PATH . '/core/lib/files.lib.php';
1482 1547
                                     $ret = dol_convert_file($file, 'png', $fileimage);
1483
-                                    if ($ret < 0)
1484
-                                        $error++;
1548
+                                    if ($ret < 0) {
1549
+                                                                            $error++;
1550
+                                    }
1485 1551
                                 }
1486 1552
                             }
1487 1553
 
1488 1554
                             $heightforphotref = 70;
1489
-                            if (!empty(Globals::$conf->dol_optimize_smallscreen))
1490
-                                $heightforphotref = 60;
1555
+                            if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
1556
+                                                            $heightforphotref = 60;
1557
+                            }
1491 1558
                             // Si fichier png PDF d'1 page trouve
1492 1559
                             if (file_exists($fileimage)) {
1493 1560
                                 $phototoshow = '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref">';
@@ -1523,8 +1590,10 @@  discard block
 block discarded – undo
1523 1590
                         $width = 14;
1524 1591
                         $cssclass = 'photorefcenter';
1525 1592
                         $picto = $object->picto;
1526
-                        if ($object->element == 'project' && !$object->public)
1527
-                            $picto = 'project'; // instead of projectpub
1593
+                        if ($object->element == 'project' && !$object->public) {
1594
+                                                    $picto = 'project';
1595
+                        }
1596
+                        // instead of projectpub
1528 1597
                         $nophoto = img_picto('', 'object_' . $picto, '', false, 1);
1529 1598
                     }
1530 1599
                     $morehtmlleft .= '<!-- No photo to show -->';
@@ -1535,8 +1604,9 @@  discard block
 block discarded – undo
1535 1604
             }
1536 1605
         }
1537 1606
 
1538
-        if ($showbarcode)
1539
-            $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1607
+        if ($showbarcode) {
1608
+                    $morehtmlleft .= '<div class="floatleft inline-block valignmiddle divphotoref">' . $form->showbarcode($object) . '</div>';
1609
+        }
1540 1610
 
1541 1611
         if ($object->element == 'societe') {
1542 1612
             if (!empty(Globals::$conf->use_javascript_ajax) && $user->rights->societe->creer && !empty(Globals::$conf->global->MAIN_DIRECT_STATUS_UPDATE)) {
@@ -1560,35 +1630,37 @@  discard block
 block discarded – undo
1560 1630
             }
1561 1631
         } elseif (in_array($object->element, array('facture', 'invoice', 'invoice_supplier', 'chargesociales', 'loan'))) {
1562 1632
             $tmptxt = $object->getLibStatut(6, $object->totalpaye);
1563
-            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone')
1564
-                $tmptxt = $object->getLibStatut(5, $object->totalpaye);
1633
+            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone') {
1634
+                            $tmptxt = $object->getLibStatut(5, $object->totalpaye);
1635
+            }
1565 1636
             $morehtmlstatus .= $tmptxt;
1566
-        }
1567
-        elseif ($object->element == 'contrat' || $object->element == 'contract') {
1568
-            if ($object->statut == 0)
1569
-                $morehtmlstatus .= $object->getLibStatut(5);
1570
-            else
1571
-                $morehtmlstatus .= $object->getLibStatut(4);
1572
-        }
1573
-        elseif ($object->element == 'facturerec') {
1574
-            if ($object->frequency == 0)
1575
-                $morehtmlstatus .= $object->getLibStatut(2);
1576
-            else
1577
-                $morehtmlstatus .= $object->getLibStatut(5);
1578
-        }
1579
-        elseif ($object->element == 'project_task') {
1637
+        } elseif ($object->element == 'contrat' || $object->element == 'contract') {
1638
+            if ($object->statut == 0) {
1639
+                            $morehtmlstatus .= $object->getLibStatut(5);
1640
+            } else {
1641
+                            $morehtmlstatus .= $object->getLibStatut(4);
1642
+            }
1643
+        } elseif ($object->element == 'facturerec') {
1644
+            if ($object->frequency == 0) {
1645
+                            $morehtmlstatus .= $object->getLibStatut(2);
1646
+            } else {
1647
+                            $morehtmlstatus .= $object->getLibStatut(5);
1648
+            }
1649
+        } elseif ($object->element == 'project_task') {
1580 1650
             $object->fk_statut = 1;
1581
-            if ($object->progress > 0)
1582
-                $object->fk_statut = 2;
1583
-            if ($object->progress >= 100)
1584
-                $object->fk_statut = 3;
1651
+            if ($object->progress > 0) {
1652
+                            $object->fk_statut = 2;
1653
+            }
1654
+            if ($object->progress >= 100) {
1655
+                            $object->fk_statut = 3;
1656
+            }
1585 1657
             $tmptxt = $object->getLibStatut(5);
1586 1658
             $morehtmlstatus .= $tmptxt;  // No status on task
1587
-        }
1588
-        else { // Generic case
1659
+        } else { // Generic case
1589 1660
             $tmptxt = $object->getLibStatut(6);
1590
-            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone')
1591
-                $tmptxt = $object->getLibStatut(5);
1661
+            if (empty($tmptxt) || $tmptxt == $object->getLibStatut(3) || Globals::$conf->browser->layout == 'phone') {
1662
+                            $tmptxt = $object->getLibStatut(5);
1663
+            }
1592 1664
             $morehtmlstatus .= $tmptxt;
1593 1665
         }
1594 1666
 
@@ -1602,13 +1674,15 @@  discard block
 block discarded – undo
1602 1674
         }
1603 1675
 
1604 1676
 // Add alias for thirdparty
1605
-        if (!empty($object->name_alias))
1606
-            $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1677
+        if (!empty($object->name_alias)) {
1678
+                    $morehtmlref .= '<div class="refidno">' . $object->name_alias . '</div>';
1679
+        }
1607 1680
 
1608 1681
 // Add label
1609 1682
         if ($object->element == 'product' || $object->element == 'bank_account' || $object->element == 'project_task') {
1610
-            if (!empty($object->label))
1611
-                $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1683
+            if (!empty($object->label)) {
1684
+                            $morehtmlref .= '<div class="refidno">' . $object->label . '</div>';
1685
+            }
1612 1686
         }
1613 1687
 
1614 1688
         if (method_exists($object, 'getBannerAddress') && $object->element != 'product' && $object->element != 'bookmark' && $object->element != 'ecm_directories' && $object->element != 'ecm_files') {
@@ -1641,15 +1715,19 @@  discard block
 block discarded – undo
1641 1715
     {
1642 1716
        // global Globals::$conf, Globals::$langs;
1643 1717
         $ret = '';
1644
-        if ($fieldrequired)
1645
-            $ret .= '<span class="fieldrequired">';
1646
-        if ((Globals::$conf->dol_use_jmobile != 4))
1647
-            $ret .= '<label for="' . $fieldkey . '">';
1718
+        if ($fieldrequired) {
1719
+                    $ret .= '<span class="fieldrequired">';
1720
+        }
1721
+        if ((Globals::$conf->dol_use_jmobile != 4)) {
1722
+                    $ret .= '<label for="' . $fieldkey . '">';
1723
+        }
1648 1724
         $ret .= Globals::$langs->trans($langkey);
1649
-        if ((Globals::$conf->dol_use_jmobile != 4))
1650
-            $ret .= '</label>';
1651
-        if ($fieldrequired)
1652
-            $ret .= '</span>';
1725
+        if ((Globals::$conf->dol_use_jmobile != 4)) {
1726
+                    $ret .= '</label>';
1727
+        }
1728
+        if ($fieldrequired) {
1729
+                    $ret .= '</span>';
1730
+        }
1653 1731
         return $ret;
1654 1732
     }
1655 1733
 
@@ -1664,8 +1742,9 @@  discard block
 block discarded – undo
1664 1742
     {
1665 1743
        // global $bc;
1666 1744
         $ret = ' ' . $bc[$var];
1667
-        if ($moreclass)
1668
-            $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1745
+        if ($moreclass) {
1746
+                    $ret = preg_replace('/class=\"/', 'class="' . $moreclass . ' ', $ret);
1747
+        }
1669 1748
         return $ret;
1670 1749
     }
1671 1750
 
@@ -1696,18 +1775,18 @@  discard block
 block discarded – undo
1696 1775
             if ($object->state) {
1697 1776
                 $ret .= ($ret ? ", " : '') . $object->state;
1698 1777
             }
1699
-            if ($object->zip)
1700
-                $ret .= ($ret ? ", " : '') . $object->zip;
1701
-        }
1702
-        else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1778
+            if ($object->zip) {
1779
+                            $ret .= ($ret ? ", " : '') . $object->zip;
1780
+            }
1781
+        } else if (in_array($object->country_code, array('GB', 'UK'))) { // UK: title firstname name \n address lines \n town state \n zip \n country
1703 1782
             $ret .= ($ret ? $sep : '' ) . $object->town;
1704 1783
             if ($object->state) {
1705 1784
                 $ret .= ($ret ? ", " : '') . $object->state;
1706 1785
             }
1707
-            if ($object->zip)
1708
-                $ret .= ($ret ? $sep : '' ) . $object->zip;
1709
-        }
1710
-        else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1786
+            if ($object->zip) {
1787
+                            $ret .= ($ret ? $sep : '' ) . $object->zip;
1788
+            }
1789
+        } else if (in_array($object->country_code, array('ES', 'TR'))) { // ES: title firstname name \n address lines \n zip town \n state \n country
1711 1790
             $ret .= ($ret ? $sep : '' ) . $object->zip;
1712 1791
             $ret .= ($object->town ? (($object->zip ? ' ' : '') . $object->town) : '');
1713 1792
             if ($object->state) {
@@ -1724,8 +1803,9 @@  discard block
 block discarded – undo
1724 1803
                 $ret .= ($ret ? ", " : '') . $object->state;
1725 1804
             }
1726 1805
         }
1727
-        if (!is_object($outputlangs))
1728
-            $outputlangs = Globals::$langs;
1806
+        if (!is_object($outputlangs)) {
1807
+                    $outputlangs = Globals::$langs;
1808
+        }
1729 1809
         if ($withcountry) {
1730 1810
             Globals::$langs->load("dict");
1731 1811
             $ret .= ($object->country_code ? ($ret ? $sep : '') . $outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country" . $object->country_code)) : '');
@@ -1746,8 +1826,9 @@  discard block
 block discarded – undo
1746 1826
     {
1747 1827
         if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
1748 1828
             return ($is_gmt) ? @gmstrftime($fmt, $ts) : @strftime($fmt, $ts);
1749
-        } else
1750
-            return 'Error date into a not supported range';
1829
+        } else {
1830
+                    return 'Error date into a not supported range';
1831
+        }
1751 1832
     }
1752 1833
 
1753 1834
     /**
@@ -1793,10 +1874,12 @@  discard block
 block discarded – undo
1793 1874
                 }
1794 1875
             }
1795 1876
         }
1796
-        if (!is_object($outputlangs))
1797
-            $outputlangs = Globals::$langs;
1798
-        if (!$format)
1799
-            $format = 'daytextshort';
1877
+        if (!is_object($outputlangs)) {
1878
+                    $outputlangs = Globals::$langs;
1879
+        }
1880
+        if (!$format) {
1881
+                    $format = 'daytextshort';
1882
+        }
1800 1883
         $reduceformat = (!empty(Globals::$conf->dol_optimize_smallscreen) && in_array($format, array('day', 'dayhour'))) ? 1 : 0;
1801 1884
         $formatwithoutreduce = preg_replace('/reduceformat/', '', $format);
1802 1885
         if ($formatwithoutreduce != $format) {
@@ -1805,40 +1888,46 @@  discard block
 block discarded – undo
1805 1888
         }  // so format 'dayreduceformat' is processed like day
1806 1889
 // Change predefined format into computer format. If found translation in lang file we use it, otherwise we use default.
1807 1890
 // TODO Add format daysmallyear and dayhoursmallyear
1808
-        if ($format == 'day')
1809
-            $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : Globals::$conf->format_date_short);
1810
-        else if ($format == 'hour')
1811
-            $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : Globals::$conf->format_hour_short);
1812
-        else if ($format == 'hourduration')
1813
-            $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : Globals::$conf->format_hour_short_duration);
1814
-        else if ($format == 'daytext')
1815
-            $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : Globals::$conf->format_date_text);
1816
-        else if ($format == 'daytextshort')
1817
-// Notice: Undefined property: stdClass::$format_date_text_short in \alixar\dolibarr\htdocs\core\lib\functions.lib.php on line 1781
1818
-            $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : Globals::$conf->format_date_text_short);
1819
-        else if ($format == 'dayhour')
1820
-            $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : Globals::$conf->format_date_hour_short);
1821
-        else if ($format == 'dayhoursec')
1822
-            $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : Globals::$conf->format_date_hour_sec_short);
1823
-        else if ($format == 'dayhourtext')
1824
-            $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : Globals::$conf->format_date_hour_text);
1825
-        else if ($format == 'dayhourtextshort')
1826
-            $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : Globals::$conf->format_date_hour_text_short);
1827
-// Format not sensitive to language
1828
-        else if ($format == 'dayhourlog')
1829
-            $format = '%Y%m%d%H%M%S';
1830
-        else if ($format == 'dayhourldap')
1831
-            $format = '%Y%m%d%H%M%SZ';
1832
-        else if ($format == 'dayhourxcard')
1833
-            $format = '%Y%m%dT%H%M%SZ';
1834
-        else if ($format == 'dayxcard')
1835
-            $format = '%Y%m%d';
1836
-        else if ($format == 'dayrfc')
1837
-            $format = '%Y-%m-%d';             // DATE_RFC3339
1838
-        else if ($format == 'dayhourrfc')
1839
-            $format = '%Y-%m-%dT%H:%M:%SZ';   // DATETIME RFC3339
1840
-        else if ($format == 'standard')
1841
-            $format = '%Y-%m-%d %H:%M:%S';
1891
+        if ($format == 'day') {
1892
+                    $format = ($outputlangs->trans("FormatDateShort") != "FormatDateShort" ? $outputlangs->trans("FormatDateShort") : Globals::$conf->format_date_short);
1893
+        } else if ($format == 'hour') {
1894
+                    $format = ($outputlangs->trans("FormatHourShort") != "FormatHourShort" ? $outputlangs->trans("FormatHourShort") : Globals::$conf->format_hour_short);
1895
+        } else if ($format == 'hourduration') {
1896
+                    $format = ($outputlangs->trans("FormatHourShortDuration") != "FormatHourShortDuration" ? $outputlangs->trans("FormatHourShortDuration") : Globals::$conf->format_hour_short_duration);
1897
+        } else if ($format == 'daytext') {
1898
+                    $format = ($outputlangs->trans("FormatDateText") != "FormatDateText" ? $outputlangs->trans("FormatDateText") : Globals::$conf->format_date_text);
1899
+        } else if ($format == 'daytextshort') {
1900
+            // Notice: Undefined property: stdClass::$format_date_text_short in \alixar\dolibarr\htdocs\core\lib\functions.lib.php on line 1781
1901
+            $format = ($outputlangs->trans("FormatDateTextShort") != "FormatDateTextShort" ? $outputlangs->trans("FormatDateTextShort") : Globals::$conf->format_date_text_short);
1902
+        } else if ($format == 'dayhour') {
1903
+                    $format = ($outputlangs->trans("FormatDateHourShort") != "FormatDateHourShort" ? $outputlangs->trans("FormatDateHourShort") : Globals::$conf->format_date_hour_short);
1904
+        } else if ($format == 'dayhoursec') {
1905
+                    $format = ($outputlangs->trans("FormatDateHourSecShort") != "FormatDateHourSecShort" ? $outputlangs->trans("FormatDateHourSecShort") : Globals::$conf->format_date_hour_sec_short);
1906
+        } else if ($format == 'dayhourtext') {
1907
+                    $format = ($outputlangs->trans("FormatDateHourText") != "FormatDateHourText" ? $outputlangs->trans("FormatDateHourText") : Globals::$conf->format_date_hour_text);
1908
+        } else if ($format == 'dayhourtextshort') {
1909
+                    $format = ($outputlangs->trans("FormatDateHourTextShort") != "FormatDateHourTextShort" ? $outputlangs->trans("FormatDateHourTextShort") : Globals::$conf->format_date_hour_text_short);
1910
+        }
1911
+        // Format not sensitive to language
1912
+        else if ($format == 'dayhourlog') {
1913
+                    $format = '%Y%m%d%H%M%S';
1914
+        } else if ($format == 'dayhourldap') {
1915
+                    $format = '%Y%m%d%H%M%SZ';
1916
+        } else if ($format == 'dayhourxcard') {
1917
+                    $format = '%Y%m%dT%H%M%SZ';
1918
+        } else if ($format == 'dayxcard') {
1919
+                    $format = '%Y%m%d';
1920
+        } else if ($format == 'dayrfc') {
1921
+                    $format = '%Y-%m-%d';
1922
+        }
1923
+        // DATE_RFC3339
1924
+        else if ($format == 'dayhourrfc') {
1925
+                    $format = '%Y-%m-%dT%H:%M:%SZ';
1926
+        }
1927
+        // DATETIME RFC3339
1928
+        else if ($format == 'standard') {
1929
+                    $format = '%Y-%m-%d %H:%M:%S';
1930
+        }
1842 1931
 
1843 1932
         if ($reduceformat) {
1844 1933
             $format = str_replace('%Y', '%y', $format);
@@ -1846,8 +1935,10 @@  discard block
 block discarded – undo
1846 1935
         }
1847 1936
 
1848 1937
 // If date undefined or "", we return ""
1849
-        if (dol_strlen($time) == 0)
1850
-            return '';  // $time=0 allowed (it means 01/01/1970 00:00:00)
1938
+        if (dol_strlen($time) == 0) {
1939
+                    return '';
1940
+        }
1941
+        // $time=0 allowed (it means 01/01/1970 00:00:00)
1851 1942
 
1852 1943
 
1853 1944
 
@@ -1915,8 +2006,9 @@  discard block
 block discarded – undo
1915 2006
                 $timetouse = $time + $offsettz + $offsetdst; // TODO Replace this with static function Date PHP. We also should not use anymore offsettz and offsetdst but only offsettzstring.
1916 2007
 
1917 2008
                 $ret = adodb_strftime($format, $timetouse, $to_gmt);
1918
-            } else
1919
-                $ret = 'Bad value ' . $time . ' for date';
2009
+            } else {
2010
+                            $ret = 'Bad value ' . $time . ' for date';
2011
+            }
1920 2012
         }
1921 2013
 
1922 2014
         if (preg_match('/__b__/i', $format)) {
@@ -1987,10 +2079,14 @@  discard block
 block discarded – undo
1987 2079
        // global Globals::$conf;
1988 2080
 
1989 2081
         $usealternatemethod = false;
1990
-        if ($timestamp <= 0)
1991
-            $usealternatemethod = true;    // <= 1970
1992
-        if ($timestamp >= 2145913200)
1993
-            $usealternatemethod = true;  // >= 2038
2082
+        if ($timestamp <= 0) {
2083
+                    $usealternatemethod = true;
2084
+        }
2085
+        // <= 1970
2086
+        if ($timestamp >= 2145913200) {
2087
+                    $usealternatemethod = true;
2088
+        }
2089
+        // >= 2038
1994 2090
 
1995 2091
         if ($usealternatemethod) {
1996 2092
             $arrayinfo = adodb_getdate($timestamp, $fast);
@@ -2025,27 +2121,36 @@  discard block
 block discarded – undo
2025 2121
        // global Globals::$conf;
2026 2122
 //print "- ".$hour.",".$minute.",".$second.",".$month.",".$day.",".$year.",".$_SERVER["WINDIR"]." -";
2027 2123
 // Clean parameters
2028
-        if ($hour == -1 || empty($hour))
2029
-            $hour = 0;
2030
-        if ($minute == -1 || empty($minute))
2031
-            $minute = 0;
2032
-        if ($second == -1 || empty($second))
2033
-            $second = 0;
2124
+        if ($hour == -1 || empty($hour)) {
2125
+                    $hour = 0;
2126
+        }
2127
+        if ($minute == -1 || empty($minute)) {
2128
+                    $minute = 0;
2129
+        }
2130
+        if ($second == -1 || empty($second)) {
2131
+                    $second = 0;
2132
+        }
2034 2133
 
2035 2134
 // Check parameters
2036 2135
         if ($check) {
2037
-            if (!$month || !$day)
2038
-                return '';
2039
-            if ($day > 31)
2040
-                return '';
2041
-            if ($month > 12)
2042
-                return '';
2043
-            if ($hour < 0 || $hour > 24)
2044
-                return '';
2045
-            if ($minute < 0 || $minute > 60)
2046
-                return '';
2047
-            if ($second < 0 || $second > 60)
2048
-                return '';
2136
+            if (!$month || !$day) {
2137
+                            return '';
2138
+            }
2139
+            if ($day > 31) {
2140
+                            return '';
2141
+            }
2142
+            if ($month > 12) {
2143
+                            return '';
2144
+            }
2145
+            if ($hour < 0 || $hour > 24) {
2146
+                            return '';
2147
+            }
2148
+            if ($minute < 0 || $minute > 60) {
2149
+                            return '';
2150
+            }
2151
+            if ($second < 0 || $second > 60) {
2152
+                            return '';
2153
+            }
2049 2154
         }
2050 2155
 
2051 2156
         if (method_exists('DateTime', 'getTimestamp')) {
@@ -2102,8 +2207,10 @@  discard block
 block discarded – undo
2102 2207
 
2103 2208
 // Note that gmmktime and mktime return same value (GMT) when used without parameters
2104 2209
 //if ($mode == 'gmt') $ret=gmmktime(); // Strict Standards: gmmktime(): You should be using the time() static function instead
2105
-        if ($mode == 'gmt')
2106
-            $ret = time(); // Time for now at greenwich.
2210
+        if ($mode == 'gmt') {
2211
+                    $ret = time();
2212
+        }
2213
+        // Time for now at greenwich.
2107 2214
         else if ($mode == 'tzserver') {  // Time for now with PHP server timezone added
2108 2215
             require_once DOL_BASE_PATH . '/core/lib/date.lib.php';
2109 2216
             $tzsecond = getServerTimeZoneInt('now');    // Contains tz+dayling saving time
@@ -2137,8 +2244,9 @@  discard block
 block discarded – undo
2137 2244
        // global Globals::$conf, Globals::$langs;
2138 2245
         $level = 1024;
2139 2246
 
2140
-        if (!empty(Globals::$conf->dol_optimize_smallscreen))
2141
-            $shortunit = 1;
2247
+        if (!empty(Globals::$conf->dol_optimize_smallscreen)) {
2248
+                    $shortunit = 1;
2249
+        }
2142 2250
 
2143 2251
 // Set value text
2144 2252
         if (empty($shortvalue) || $size < ($level * 10)) {
@@ -2173,19 +2281,23 @@  discard block
 block discarded – undo
2173 2281
     {
2174 2282
        // global Globals::$langs;
2175 2283
 
2176
-        if (empty($url))
2177
-            return '';
2284
+        if (empty($url)) {
2285
+                    return '';
2286
+        }
2178 2287
 
2179 2288
         $link = '<a href="';
2180
-        if (!preg_match('/^http/i', $url))
2181
-            $link .= 'http://';
2289
+        if (!preg_match('/^http/i', $url)) {
2290
+                    $link .= 'http://';
2291
+        }
2182 2292
         $link .= $url;
2183 2293
         $link .= '"';
2184
-        if ($target)
2185
-            $link .= ' target="' . $target . '"';
2294
+        if ($target) {
2295
+                    $link .= ' target="' . $target . '"';
2296
+        }
2186 2297
         $link .= '>';
2187
-        if (!preg_match('/^http/i', $url))
2188
-            $link .= 'http://';
2298
+        if (!preg_match('/^http/i', $url)) {
2299
+                    $link .= 'http://';
2300
+        }
2189 2301
         $link .= dol_trunc($url, $max);
2190 2302
         $link .= '</a>';
2191 2303
         return '<div class="nospan float" style="margin-right: 10px">' . ($withpicto ? img_picto(Globals::$langs->trans("Url"), 'object_globe.png') . ' ' : '') . $link . '</div>';
@@ -2209,13 +2321,15 @@  discard block
 block discarded – undo
2209 2321
 
2210 2322
         $newemail = $email;
2211 2323
 
2212
-        if (empty($email))
2213
-            return '&nbsp;';
2324
+        if (empty($email)) {
2325
+                    return '&nbsp;';
2326
+        }
2214 2327
 
2215 2328
         if (!empty($addlink)) {
2216 2329
             $newemail = '<a style="text-overflow: ellipsis;" href="';
2217
-            if (!preg_match('/^mailto:/i', $email))
2218
-                $newemail .= 'mailto:';
2330
+            if (!preg_match('/^mailto:/i', $email)) {
2331
+                            $newemail .= 'mailto:';
2332
+            }
2219 2333
             $newemail .= $email;
2220 2334
             $newemail .= '">';
2221 2335
             $newemail .= dol_trunc($email, $max);
@@ -2228,13 +2342,14 @@  discard block
 block discarded – undo
2228 2342
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
2229 2343
                 $type = 'AC_EMAIL';
2230 2344
                 $link = '';
2231
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL))
2232
-                    $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>';
2233
-                if ($link)
2234
-                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2345
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFOREMAIL)) {
2346
+                                    $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>';
2347
+                }
2348
+                if ($link) {
2349
+                                    $newemail = '<div>' . $newemail . ' ' . $link . '</div>';
2350
+                }
2235 2351
             }
2236
-        }
2237
-        else {
2352
+        } else {
2238 2353
             if ($showinvalid && !isValidEmail($email)) {
2239 2354
                 Globals::$langs->load("errors");
2240 2355
                 $newemail .= img_warning(Globals::$langs->trans("ErrorBadEMail", $email));
@@ -2266,8 +2381,9 @@  discard block
 block discarded – undo
2266 2381
 
2267 2382
         $newskype = $value;
2268 2383
 
2269
-        if (empty($value))
2270
-            return '&nbsp;';
2384
+        if (empty($value)) {
2385
+                    return '&nbsp;';
2386
+        }
2271 2387
 
2272 2388
         if (!empty($type)) {
2273 2389
             $newskype = '<div class="divsocialnetwork inline-block valignmiddle">';
@@ -2288,13 +2404,13 @@  discard block
 block discarded – undo
2288 2404
             if (($cid || $socid) && !empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create && $type == 'skype') {
2289 2405
                 $addlink = 'AC_SKYPE';
2290 2406
                 $link = '';
2291
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE))
2292
-                    $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>';
2407
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORSKYPE)) {
2408
+                                    $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>';
2409
+                }
2293 2410
                 $newskype .= ($link ? ' ' . $link : '');
2294 2411
             }
2295 2412
             $newskype .= '</div>';
2296
-        }
2297
-        else {
2413
+        } else {
2298 2414
             Globals::$langs->load("errors");
2299 2415
             $newskype .= img_warning(Globals::$langs->trans("ErrorBadSocialNetworkValue", $value));
2300 2416
         }
@@ -2323,12 +2439,14 @@  discard block
 block discarded – undo
2323 2439
         if (empty($phone)) {
2324 2440
             return '';
2325 2441
         }
2326
-        if (empty($countrycode))
2327
-            $countrycode = $mysoc->country_code;
2442
+        if (empty($countrycode)) {
2443
+                    $countrycode = $mysoc->country_code;
2444
+        }
2328 2445
 
2329 2446
 // Short format for small screens
2330
-        if (Globals::$conf->dol_optimize_smallscreen)
2331
-            $separ = '';
2447
+        if (Globals::$conf->dol_optimize_smallscreen) {
2448
+                    $separ = '';
2449
+        }
2332 2450
 
2333 2451
         $newphone = $phone;
2334 2452
         if (strtoupper($countrycode) == "FR") {
@@ -2494,15 +2612,18 @@  discard block
 block discarded – undo
2494 2612
                 $newphone = '<a href="tel:' . $phone . '"';
2495 2613
                 $newphone .= '>' . $phone . '</a>';
2496 2614
             } else if (!empty(Globals::$conf->clicktodial->enabled) && $addlink == 'AC_TEL') {  // If click to dial, we use click to dial url
2497
-                if (empty($user->clicktodial_loaded))
2498
-                    $user->fetch_clicktodial();
2615
+                if (empty($user->clicktodial_loaded)) {
2616
+                                    $user->fetch_clicktodial();
2617
+                }
2499 2618
 
2500 2619
 // Define urlmask
2501 2620
                 $urlmask = 'ErrorClickToDialModuleNotConfigured';
2502
-                if (!empty(Globals::$conf->global->CLICKTODIAL_URL))
2503
-                    $urlmask = Globals::$conf->global->CLICKTODIAL_URL;
2504
-                if (!empty($user->clicktodial_url))
2505
-                    $urlmask = $user->clicktodial_url;
2621
+                if (!empty(Globals::$conf->global->CLICKTODIAL_URL)) {
2622
+                                    $urlmask = Globals::$conf->global->CLICKTODIAL_URL;
2623
+                }
2624
+                if (!empty($user->clicktodial_url)) {
2625
+                                    $urlmask = $user->clicktodial_url;
2626
+                }
2506 2627
 
2507 2628
                 $clicktodial_poste = (!empty($user->clicktodial_poste) ? urlencode($user->clicktodial_poste) : '');
2508 2629
                 $clicktodial_login = (!empty($user->clicktodial_login) ? urlencode($user->clicktodial_login) : '');
@@ -2517,8 +2638,9 @@  discard block
 block discarded – undo
2517 2638
                 $url = make_substitutions($url, $substitarray);
2518 2639
                 $newphonesav = $newphone;
2519 2640
                 $newphone = '<a href="' . $url . '"';
2520
-                if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET))
2521
-                    $newphone .= ' target="_blank"';
2641
+                if (!empty(Globals::$conf->global->CLICKTODIAL_FORCENEWTARGET)) {
2642
+                                    $newphone .= ' target="_blank"';
2643
+                }
2522 2644
                 $newphone .= '>' . $newphonesav . '</a>';
2523 2645
             }
2524 2646
 
@@ -2526,12 +2648,15 @@  discard block
 block discarded – undo
2526 2648
             if (!empty(Globals::$conf->agenda->enabled) && $user->rights->agenda->myactions->create) {
2527 2649
                 $type = 'AC_TEL';
2528 2650
                 $link = '';
2529
-                if ($addlink == 'AC_FAX')
2530
-                    $type = 'AC_FAX';
2531
-                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE))
2532
-                    $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>';
2533
-                if ($link)
2534
-                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2651
+                if ($addlink == 'AC_FAX') {
2652
+                                    $type = 'AC_FAX';
2653
+                }
2654
+                if (!empty(Globals::$conf->global->AGENDA_ADDACTIONFORPHONE)) {
2655
+                                    $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>';
2656
+                }
2657
+                if ($link) {
2658
+                                    $newphone = '<div>' . $newphone . ' ' . $link . '</div>';
2659
+                }
2535 2660
             }
2536 2661
         }
2537 2662
 
@@ -2558,15 +2683,17 @@  discard block
 block discarded – undo
2558 2683
                     $picto = '';
2559 2684
                 }
2560 2685
             }
2561
-            if ($adddivfloat)
2562
-                $rep .= '<div class="nospan float" style="margin-right: 10px">';
2563
-            else
2564
-                $rep .= '<span style="margin-right: 10px;">';
2686
+            if ($adddivfloat) {
2687
+                            $rep .= '<div class="nospan float" style="margin-right: 10px">';
2688
+            } else {
2689
+                            $rep .= '<span style="margin-right: 10px;">';
2690
+            }
2565 2691
             $rep .= ($withpicto ? img_picto($titlealt, 'object_' . $picto . '.png') . ' ' : '') . $newphone;
2566
-            if ($adddivfloat)
2567
-                $rep .= '</div>';
2568
-            else
2569
-                $rep .= '</span>';
2692
+            if ($adddivfloat) {
2693
+                            $rep .= '</div>';
2694
+            } else {
2695
+                            $rep .= '</span>';
2696
+            }
2570 2697
         }
2571 2698
 
2572 2699
         return $rep;
@@ -2596,8 +2723,9 @@  discard block
 block discarded – undo
2596 2723
             if ($countrycode) { // If success, countrycode is us, fr, ...
2597 2724
                 if (file_exists(DOL_BASE_PATH . '/theme/common/flags/' . $countrycode . '.png')) {
2598 2725
                     $ret .= ' ' . img_picto($countrycode . ' ' . Globals::$langs->trans("AccordingToGeoIPDatabase"), DOL_BASE_URI . '/theme/common/flags/' . $countrycode . '.png', '', 1);
2599
-                } else
2600
-                    $ret .= ' (' . $countrycode . ')';
2726
+                } else {
2727
+                                    $ret .= ' (' . $countrycode . ')';
2728
+                }
2601 2729
             }
2602 2730
         }
2603 2731
 
@@ -2694,26 +2822,33 @@  discard block
 block discarded – undo
2694 2822
                 $out .= $hookmanager->resPrint;
2695 2823
             }
2696 2824
             if (empty($reshook)) {
2697
-                if (empty($charfornl))
2698
-                    $out .= nl2br($address);
2699
-                else
2700
-                    $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
2825
+                if (empty($charfornl)) {
2826
+                                    $out .= nl2br($address);
2827
+                } else {
2828
+                                    $out .= preg_replace('/[\r\n]+/', $charfornl, $address);
2829
+                }
2701 2830
 
2702 2831
                 $showgmap = $showomap = 0;
2703 2832
 
2704 2833
 // TODO Add a hook here
2705
-                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS))
2706
-                    $showgmap = 1;
2707
-                if ($mode == 'contact' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS))
2708
-                    $showgmap = 1;
2709
-                if ($mode == 'member' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS))
2710
-                    $showgmap = 1;
2711
-                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS))
2712
-                    $showomap = 1;
2713
-                if ($mode == 'contact' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS))
2714
-                    $showomap = 1;
2715
-                if ($mode == 'member' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS))
2716
-                    $showomap = 1;
2834
+                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS)) {
2835
+                                    $showgmap = 1;
2836
+                }
2837
+                if ($mode == 'contact' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_CONTACTS)) {
2838
+                                    $showgmap = 1;
2839
+                }
2840
+                if ($mode == 'member' && !empty(Globals::$conf->google->enabled) && !empty(Globals::$conf->global->GOOGLE_ENABLE_GMAPS_MEMBERS)) {
2841
+                                    $showgmap = 1;
2842
+                }
2843
+                if (($mode == 'thirdparty' || $mode == 'societe') && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS)) {
2844
+                                    $showomap = 1;
2845
+                }
2846
+                if ($mode == 'contact' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_CONTACTS)) {
2847
+                                    $showomap = 1;
2848
+                }
2849
+                if ($mode == 'member' && !empty(Globals::$conf->openstreetmap->enabled) && !empty(Globals::$conf->global->OPENSTREETMAP_ENABLE_MAPS_MEMBERS)) {
2850
+                                    $showomap = 1;
2851
+                }
2717 2852
 
2718 2853
                 if ($showgmap) {
2719 2854
                     $url = dol_buildpath('/google/gmaps.php?mode=' . $mode . '&id=' . $id, 1);
@@ -2725,10 +2860,11 @@  discard block
 block discarded – undo
2725 2860
                 }
2726 2861
             }
2727 2862
         }
2728
-        if ($noprint)
2729
-            return $out;
2730
-        else
2731
-            print $out;
2863
+        if ($noprint) {
2864
+                    return $out;
2865
+        } else {
2866
+                    print $out;
2867
+        }
2732 2868
     }
2733 2869
 
2734 2870
     /**
@@ -2740,10 +2876,12 @@  discard block
 block discarded – undo
2740 2876
      */
2741 2877
     static function isValidEmail($address, $acceptsupervisorkey = 0)
2742 2878
     {
2743
-        if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__')
2744
-            return true;
2745
-        if (filter_var($address, FILTER_VALIDATE_EMAIL))
2746
-            return true;
2879
+        if ($acceptsupervisorkey && $address == '__SUPERVISOREMAIL__') {
2880
+                    return true;
2881
+        }
2882
+        if (filter_var($address, FILTER_VALIDATE_EMAIL)) {
2883
+                    return true;
2884
+        }
2747 2885
 
2748 2886
         return false;
2749 2887
     }
@@ -2765,10 +2903,12 @@  discard block
 block discarded – undo
2765 2903
                 $mxhosts = array();
2766 2904
                 $weight = array();
2767 2905
                 getmxrr(idn_to_ascii($domain), $mxhosts, $weight);
2768
-                if (count($mxhosts) > 1)
2769
-                    return 1;
2770
-                if (count($mxhosts) == 1 && !empty($mxhosts[0]))
2771
-                    return 1;
2906
+                if (count($mxhosts) > 1) {
2907
+                                    return 1;
2908
+                }
2909
+                if (count($mxhosts) == 1 && !empty($mxhosts[0])) {
2910
+                                    return 1;
2911
+                }
2772 2912
 
2773 2913
                 return 0;
2774 2914
             }
@@ -2797,10 +2937,11 @@  discard block
 block discarded – undo
2797 2937
      */
2798 2938
     static function dol_strlen($string, $stringencoding = 'UTF-8')
2799 2939
     {
2800
-        if (function_exists('mb_strlen'))
2801
-            return mb_strlen($string, $stringencoding);
2802
-        else
2803
-            return strlen($string);
2940
+        if (function_exists('mb_strlen')) {
2941
+                    return mb_strlen($string, $stringencoding);
2942
+        } else {
2943
+                    return strlen($string);
2944
+        }
2804 2945
     }
2805 2946
 
2806 2947
     /**
@@ -2817,8 +2958,9 @@  discard block
 block discarded – undo
2817 2958
     {
2818 2959
        // global Globals::$langs;
2819 2960
 
2820
-        if (empty($stringencoding))
2821
-            $stringencoding = Globals::$langs->charset_output;
2961
+        if (empty($stringencoding)) {
2962
+                    $stringencoding = Globals::$langs->charset_output;
2963
+        }
2822 2964
 
2823 2965
         $ret = '';
2824 2966
         if (empty($trunconbytes)) {
@@ -2854,48 +2996,55 @@  discard block
 block discarded – undo
2854 2996
     {
2855 2997
        // global Globals::$conf;
2856 2998
 
2857
-        if ($size == 0 || !empty(Globals::$conf->global->MAIN_DISABLE_TRUNC))
2858
-            return $string;
2999
+        if ($size == 0 || !empty(Globals::$conf->global->MAIN_DISABLE_TRUNC)) {
3000
+                    return $string;
3001
+        }
2859 3002
 
2860
-        if (empty($stringencoding))
2861
-            $stringencoding = 'UTF-8';
2862
-// reduce for small screen
2863
-        if (Globals::$conf->dol_optimize_smallscreen == 1 && $display == 1)
2864
-            $size = round($size / 3);
3003
+        if (empty($stringencoding)) {
3004
+                    $stringencoding = 'UTF-8';
3005
+        }
3006
+        // reduce for small screen
3007
+        if (Globals::$conf->dol_optimize_smallscreen == 1 && $display == 1) {
3008
+                    $size = round($size / 3);
3009
+        }
2865 3010
 
2866 3011
 // We go always here
2867 3012
         if ($trunc == 'right') {
2868 3013
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2869
-            if (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 ...
2870
-                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
2871
-            else
2872
-//return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
2873
-                return $string;
2874
-        }
2875
-        elseif ($trunc == 'middle') {
3014
+            if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) {
3015
+                // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
3016
+                return dol_substr($newstring, 0, $size, $stringencoding) . ($nodot ? '' : '...');
3017
+            } else {
3018
+                //return 'u'.$size.'-'.$newstring.'-'.dol_strlen($newstring,$stringencoding).'-'.$string;
3019
+                return $string;
3020
+            }
3021
+        } elseif ($trunc == 'middle') {
2876 3022
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2877 3023
             if (dol_strlen($newstring, $stringencoding) > 2 && dol_strlen($newstring, $stringencoding) > ($size + 1)) {
2878 3024
                 $size1 = round($size / 2);
2879 3025
                 $size2 = round($size / 2);
2880 3026
                 return dol_substr($newstring, 0, $size1, $stringencoding) . '...' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size2, $size2, $stringencoding);
2881
-            } else
2882
-                return $string;
2883
-        }
2884
-        elseif ($trunc == 'left') {
3027
+            } else {
3028
+                            return $string;
3029
+            }
3030
+        } elseif ($trunc == 'left') {
2885 3031
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2886
-            if (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 ...
2887
-                return '...' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
2888
-            else
2889
-                return $string;
2890
-        }
2891
-        elseif ($trunc == 'wrap') {
3032
+            if (dol_strlen($newstring, $stringencoding) > ($size + ($nodot ? 0 : 3))) {
3033
+                // If nodot is 0 and size is 1,2 or 3 chars more, we don't trunc and don't add ...
3034
+                return '...' . dol_substr($newstring, dol_strlen($newstring, $stringencoding) - $size, $size, $stringencoding);
3035
+            } else {
3036
+                            return $string;
3037
+            }
3038
+        } elseif ($trunc == 'wrap') {
2892 3039
             $newstring = dol_textishtml($string) ? dol_string_nohtmltag($string, 1) : $string;
2893
-            if (dol_strlen($newstring, $stringencoding) > ($size + 1))
2894
-                return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
2895
-            else
2896
-                return $string;
2897
-        } else
2898
-            return 'BadParam3CallingDolTrunc';
3040
+            if (dol_strlen($newstring, $stringencoding) > ($size + 1)) {
3041
+                            return dol_substr($newstring, 0, $size, $stringencoding) . "\n" . dol_trunc(dol_substr($newstring, $size, dol_strlen($newstring, $stringencoding) - $size, $stringencoding), $size, $trunc);
3042
+            } else {
3043
+                            return $string;
3044
+            }
3045
+        } else {
3046
+                    return 'BadParam3CallingDolTrunc';
3047
+        }
2899 3048
     }
2900 3049
 
2901 3050
     /**
@@ -3105,8 +3254,9 @@  discard block
 block discarded – undo
3105 3254
     {
3106 3255
        // global Globals::$conf;
3107 3256
 
3108
-        if (!preg_match('/(\.png|\.gif)$/i', $picto))
3109
-            $picto .= '.png';
3257
+        if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
3258
+                    $picto .= '.png';
3259
+        }
3110 3260
 
3111 3261
 //$path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
3112 3262
         $path = DOL_BASE_URI . '/theme/' . Globals::$conf->theme . '/img/weather/' . $picto;
@@ -3128,20 +3278,22 @@  discard block
 block discarded – undo
3128 3278
     {
3129 3279
        // global Globals::$conf;
3130 3280
 
3131
-        if (!preg_match('/(\.png|\.gif)$/i', $picto))
3132
-            $picto .= '.png';
3281
+        if (!preg_match('/(\.png|\.gif)$/i', $picto)) {
3282
+                    $picto .= '.png';
3283
+        }
3133 3284
 
3134
-        if ($pictoisfullpath)
3135
-            $path = $picto;
3136
-        else {
3285
+        if ($pictoisfullpath) {
3286
+                    $path = $picto;
3287
+        } else {
3137 3288
 //$path = DOL_BASE_URI . '/theme/common/' . $picto;
3138 3289
             $path = DOL_BASE_URI . '/theme/common/' . $picto;
3139 3290
 
3140 3291
             if (!empty(Globals::$conf->global->MAIN_MODULE_CAN_OVERWRITE_COMMONICONS)) {
3141 3292
                 $themepath = DOL_BASE_PATH . 'theme/' . Globals::$conf->theme . '/img/' . $picto;
3142 3293
 
3143
-                if (file_exists($themepath))
3144
-                    $path = $themepath;
3294
+                if (file_exists($themepath)) {
3295
+                                    $path = $themepath;
3296
+                }
3145 3297
             }
3146 3298
         }
3147 3299
 
@@ -3180,8 +3332,9 @@  discard block
 block discarded – undo
3180 3332
                 $numaction = 0;
3181 3333
             }
3182 3334
         }
3183
-        if (!is_numeric($numaction))
3184
-            $numaction = 0;
3335
+        if (!is_numeric($numaction)) {
3336
+                    $numaction = 0;
3337
+        }
3185 3338
 
3186 3339
         return img_picto($titlealt, 'stcomm' . $numaction . '.png');
3187 3340
     }
@@ -3197,8 +3350,9 @@  discard block
 block discarded – undo
3197 3350
     {
3198 3351
        // global Globals::$conf, Globals::$langs;
3199 3352
 
3200
-        if ($titlealt == 'default')
3201
-            $titlealt = Globals::$langs->trans('Show');
3353
+        if ($titlealt == 'default') {
3354
+                    $titlealt = Globals::$langs->trans('Show');
3355
+        }
3202 3356
 
3203 3357
         return img_picto($titlealt, 'pdf' . $size . '.png');
3204 3358
     }
@@ -3214,8 +3368,9 @@  discard block
 block discarded – undo
3214 3368
     {
3215 3369
        // global Globals::$conf, Globals::$langs;
3216 3370
 
3217
-        if ($titlealt == 'default')
3218
-            $titlealt = Globals::$langs->trans('Add');
3371
+        if ($titlealt == 'default') {
3372
+                    $titlealt = Globals::$langs->trans('Add');
3373
+        }
3219 3374
 
3220 3375
         return img_picto($titlealt, 'edit_add.png', $other);
3221 3376
     }
@@ -3231,8 +3386,9 @@  discard block
 block discarded – undo
3231 3386
     {
3232 3387
        // global Globals::$conf, Globals::$langs;
3233 3388
 
3234
-        if ($titlealt == 'default')
3235
-            $titlealt = Globals::$langs->trans('Remove');
3389
+        if ($titlealt == 'default') {
3390
+                    $titlealt = Globals::$langs->trans('Remove');
3391
+        }
3236 3392
 
3237 3393
         return img_picto($titlealt, 'edit_remove.png', $other);
3238 3394
     }
@@ -3249,8 +3405,9 @@  discard block
 block discarded – undo
3249 3405
     {
3250 3406
        // global Globals::$conf, Globals::$langs;
3251 3407
 
3252
-        if ($titlealt == 'default')
3253
-            $titlealt = Globals::$langs->trans('Modify');
3408
+        if ($titlealt == 'default') {
3409
+                    $titlealt = Globals::$langs->trans('Modify');
3410
+        }
3254 3411
 
3255 3412
         return img_picto($titlealt, 'edit.png', ($float ? 'style="float: ' . (Globals::$langs->tab_translate["DIRECTION"] == 'rtl' ? 'left' : 'right') . '"' : "") . ($other ? ' ' . $other : ''));
3256 3413
     }
@@ -3267,8 +3424,9 @@  discard block
 block discarded – undo
3267 3424
     {
3268 3425
        // global Globals::$conf, Globals::$langs;
3269 3426
 
3270
-        if ($titlealt == 'default')
3271
-            $titlealt = Globals::$langs->trans('View');
3427
+        if ($titlealt == 'default') {
3428
+                    $titlealt = Globals::$langs->trans('View');
3429
+        }
3272 3430
 
3273 3431
         $moreatt = ($float ? 'style="float: right" ' : '') . $other;
3274 3432
 
@@ -3286,8 +3444,9 @@  discard block
 block discarded – undo
3286 3444
     {
3287 3445
        // global Globals::$conf, Globals::$langs;
3288 3446
 
3289
-        if ($titlealt == 'default')
3290
-            $titlealt = Globals::$langs->trans('Delete');
3447
+        if ($titlealt == 'default') {
3448
+                    $titlealt = Globals::$langs->trans('Delete');
3449
+        }
3291 3450
 
3292 3451
         return img_picto($titlealt, 'delete.png', $other);
3293 3452
 //return '<span class="fa fa-trash fa-2x fa-fw" style="font-size: 1.7em;" title="'.$titlealt.'"></span>';
@@ -3303,8 +3462,9 @@  discard block
 block discarded – undo
3303 3462
     static function img_printer($titlealt = "default", $other = '')
3304 3463
     {
3305 3464
        // global Globals::$conf, Globals::$langs;
3306
-        if ($titlealt == "default")
3307
-            $titlealt = Globals::$langs->trans("Print");
3465
+        if ($titlealt == "default") {
3466
+                    $titlealt = Globals::$langs->trans("Print");
3467
+        }
3308 3468
         return img_picto($titlealt, 'printer.png', $other);
3309 3469
     }
3310 3470
 
@@ -3319,8 +3479,9 @@  discard block
 block discarded – undo
3319 3479
     {
3320 3480
        // global Globals::$conf, Globals::$langs;
3321 3481
 
3322
-        if ($titlealt == 'default')
3323
-            $titlealt = Globals::$langs->trans('Split');
3482
+        if ($titlealt == 'default') {
3483
+                    $titlealt = Globals::$langs->trans('Split');
3484
+        }
3324 3485
 
3325 3486
         return img_picto($titlealt, 'split.png', $other);
3326 3487
     }
@@ -3337,10 +3498,11 @@  discard block
 block discarded – undo
3337 3498
        // global Globals::$conf, Globals::$langs;
3338 3499
 
3339 3500
         if ($usealttitle) {
3340
-            if (is_string($usealttitle))
3341
-                $usealttitle = dol_escape_htmltag($usealttitle);
3342
-            else
3343
-                $usealttitle = Globals::$langs->trans('Info');
3501
+            if (is_string($usealttitle)) {
3502
+                            $usealttitle = dol_escape_htmltag($usealttitle);
3503
+            } else {
3504
+                            $usealttitle = Globals::$langs->trans('Info');
3505
+            }
3344 3506
         }
3345 3507
 
3346 3508
         return img_picto($usealttitle, 'info.png', 'style="vertical-align: middle;' . ($usehelpcursor == 1 ? ' cursor: help' : ($usehelpcursor == 2 ? ' cursor: pointer' : '')) . '"');
@@ -3356,8 +3518,9 @@  discard block
 block discarded – undo
3356 3518
     {
3357 3519
        // global Globals::$conf, Globals::$langs;
3358 3520
 
3359
-        if ($titlealt == 'default')
3360
-            $titlealt = Globals::$langs->trans('Informations');
3521
+        if ($titlealt == 'default') {
3522
+                    $titlealt = Globals::$langs->trans('Informations');
3523
+        }
3361 3524
 
3362 3525
         return img_picto($titlealt, 'info.png', 'style="vertical-align: middle;"');
3363 3526
     }
@@ -3373,8 +3536,9 @@  discard block
 block discarded – undo
3373 3536
     {
3374 3537
        // global Globals::$conf, Globals::$langs;
3375 3538
 
3376
-        if ($titlealt == 'default')
3377
-            $titlealt = Globals::$langs->trans('Warning');
3539
+        if ($titlealt == 'default') {
3540
+                    $titlealt = Globals::$langs->trans('Warning');
3541
+        }
3378 3542
 
3379 3543
 //return '<div class="imglatecoin">'.img_picto($titlealt, 'warning_white.png', 'class="pictowarning valignmiddle"'.($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' '.$moreatt): '')).'</div>';
3380 3544
         return img_picto($titlealt, 'warning.png', 'class="pictowarning valignmiddle"' . ($moreatt ? ($moreatt == '1' ? ' style="float: right"' : ' ' . $moreatt) : ''));
@@ -3390,8 +3554,9 @@  discard block
 block discarded – undo
3390 3554
     {
3391 3555
        // global Globals::$conf, Globals::$langs;
3392 3556
 
3393
-        if ($titlealt == 'default')
3394
-            $titlealt = Globals::$langs->trans('Error');
3557
+        if ($titlealt == 'default') {
3558
+                    $titlealt = Globals::$langs->trans('Error');
3559
+        }
3395 3560
 
3396 3561
         return img_picto($titlealt, 'error.png', 'class="valigntextbottom"');
3397 3562
     }
@@ -3407,8 +3572,9 @@  discard block
 block discarded – undo
3407 3572
     {
3408 3573
        // global Globals::$conf, Globals::$langs;
3409 3574
 
3410
-        if ($titlealt == 'default')
3411
-            $titlealt = Globals::$langs->trans('Next');
3575
+        if ($titlealt == 'default') {
3576
+                    $titlealt = Globals::$langs->trans('Next');
3577
+        }
3412 3578
 
3413 3579
 //return img_picto($titlealt, 'next.png', $moreatt);
3414 3580
         return '<span class="fa fa-chevron-right paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
@@ -3425,8 +3591,9 @@  discard block
 block discarded – undo
3425 3591
     {
3426 3592
        // global Globals::$conf, Globals::$langs;
3427 3593
 
3428
-        if ($titlealt == 'default')
3429
-            $titlealt = Globals::$langs->trans('Previous');
3594
+        if ($titlealt == 'default') {
3595
+                    $titlealt = Globals::$langs->trans('Previous');
3596
+        }
3430 3597
 
3431 3598
 //return img_picto($titlealt, 'previous.png', $moreatt);
3432 3599
         return '<span class="fa fa-chevron-left paddingright paddingleft" title="' . dol_escape_htmltag($titlealt) . '"></span>';
@@ -3444,8 +3611,9 @@  discard block
 block discarded – undo
3444 3611
     {
3445 3612
        // global Globals::$conf, Globals::$langs;
3446 3613
 
3447
-        if ($titlealt == 'default')
3448
-            $titlealt = Globals::$langs->trans('Down');
3614
+        if ($titlealt == 'default') {
3615
+                    $titlealt = Globals::$langs->trans('Down');
3616
+        }
3449 3617
 
3450 3618
         return img_picto($titlealt, ($selected ? '1downarrow_selected.png' : '1downarrow.png'), 'class="imgdown' . ($moreclass ? " " . $moreclass : "") . '"');
3451 3619
     }
@@ -3462,8 +3630,9 @@  discard block
 block discarded – undo
3462 3630
     {
3463 3631
        // global Globals::$conf, Globals::$langs;
3464 3632
 
3465
-        if ($titlealt == 'default')
3466
-            $titlealt = Globals::$langs->trans('Up');
3633
+        if ($titlealt == 'default') {
3634
+                    $titlealt = Globals::$langs->trans('Up');
3635
+        }
3467 3636
 
3468 3637
         return img_picto($titlealt, ($selected ? '1uparrow_selected.png' : '1uparrow.png'), 'class="imgup' . ($moreclass ? " " . $moreclass : "") . '"');
3469 3638
     }
@@ -3480,8 +3649,9 @@  discard block
 block discarded – undo
3480 3649
     {
3481 3650
        // global Globals::$conf, Globals::$langs;
3482 3651
 
3483
-        if ($titlealt == 'default')
3484
-            $titlealt = Globals::$langs->trans('Left');
3652
+        if ($titlealt == 'default') {
3653
+                    $titlealt = Globals::$langs->trans('Left');
3654
+        }
3485 3655
 
3486 3656
         return img_picto($titlealt, ($selected ? '1leftarrow_selected.png' : '1leftarrow.png'), $moreatt);
3487 3657
     }
@@ -3498,8 +3668,9 @@  discard block
 block discarded – undo
3498 3668
     {
3499 3669
        // global Globals::$conf, Globals::$langs;
3500 3670
 
3501
-        if ($titlealt == 'default')
3502
-            $titlealt = Globals::$langs->trans('Right');
3671
+        if ($titlealt == 'default') {
3672
+                    $titlealt = Globals::$langs->trans('Right');
3673
+        }
3503 3674
 
3504 3675
         return img_picto($titlealt, ($selected ? '1rightarrow_selected.png' : '1rightarrow.png'), $moreatt);
3505 3676
     }
@@ -3515,11 +3686,13 @@  discard block
 block discarded – undo
3515 3686
     {
3516 3687
        // global Globals::$conf, Globals::$langs;
3517 3688
 
3518
-        if ($titlealt == 'default')
3519
-            $titlealt = Globals::$langs->trans('Active');
3689
+        if ($titlealt == 'default') {
3690
+                    $titlealt = Globals::$langs->trans('Active');
3691
+        }
3520 3692
 
3521
-        if ($allow == 1)
3522
-            return img_picto($titlealt, 'tick.png');
3693
+        if ($allow == 1) {
3694
+                    return img_picto($titlealt, 'tick.png');
3695
+        }
3523 3696
 
3524 3697
         return '-';
3525 3698
     }
@@ -3567,8 +3740,9 @@  discard block
 block discarded – undo
3567 3740
         $mimeimg = dol_mimetype($file, '', 2);
3568 3741
         $mimefa = dol_mimetype($file, '', 4);
3569 3742
 
3570
-        if (empty($titlealt))
3571
-            $titlealt = 'Mime type: ' . $mimetype;
3743
+        if (empty($titlealt)) {
3744
+                    $titlealt = 'Mime type: ' . $mimetype;
3745
+        }
3572 3746
 
3573 3747
 //return img_picto_common($titlealt, 'mime/'.$mimeimg, 'class="'.$morecss.'"');
3574 3748
         return '<i class="fa fa-' . $mimefa . ' paddingright"></i>';
@@ -3590,13 +3764,15 @@  discard block
 block discarded – undo
3590 3764
 
3591 3765
        // global Globals::$conf, Globals::$langs;
3592 3766
 
3593
-        if ($titlealt == 'default')
3594
-            $titlealt = Globals::$langs->trans('Call');
3767
+        if ($titlealt == 'default') {
3768
+                    $titlealt = Globals::$langs->trans('Call');
3769
+        }
3595 3770
 
3596
-        if ($option == 1)
3597
-            $img = 'call';
3598
-        else
3599
-            $img = 'call_out';
3771
+        if ($option == 1) {
3772
+                    $img = 'call';
3773
+        } else {
3774
+                    $img = 'call_out';
3775
+        }
3600 3776
 
3601 3777
         return img_picto($titlealt, $img);
3602 3778
     }
@@ -3612,8 +3788,9 @@  discard block
 block discarded – undo
3612 3788
     {
3613 3789
        // global Globals::$conf, Globals::$langs;
3614 3790
 
3615
-        if ($titlealt == 'default')
3616
-            $titlealt = Globals::$langs->trans('Search');
3791
+        if ($titlealt == 'default') {
3792
+                    $titlealt = Globals::$langs->trans('Search');
3793
+        }
3617 3794
 
3618 3795
         $img = img_picto($titlealt, 'search.png', $other, false, 1);
3619 3796
 
@@ -3634,8 +3811,9 @@  discard block
 block discarded – undo
3634 3811
     {
3635 3812
        // global Globals::$conf, Globals::$langs;
3636 3813
 
3637
-        if ($titlealt == 'default')
3638
-            $titlealt = Globals::$langs->trans('Search');
3814
+        if ($titlealt == 'default') {
3815
+                    $titlealt = Globals::$langs->trans('Search');
3816
+        }
3639 3817
 
3640 3818
         $img = img_picto($titlealt, 'searchclear.png', $other, false, 1);
3641 3819
 
@@ -3697,14 +3875,16 @@  discard block
 block discarded – undo
3697 3875
 
3698 3876
         if ($_SERVER['DOCUMENT_ROOT']) {    // Mode web
3699 3877
             $out .= Globals::$langs->trans("DolibarrHasDetectedError") . ".<br>\n";
3700
-            if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL))
3701
-                $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";
3878
+            if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL)) {
3879
+                            $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";
3880
+            }
3702 3881
             $out .= Globals::$langs->trans("InformationToHelpDiagnose") . ":<br>\n";
3703 3882
 
3704 3883
             $out .= "<b>" . Globals::$langs->trans("Date") . ":</b> " . dol_print_date(time(), 'dayhourlog') . "<br>\n";
3705 3884
             $out .= "<b>" . Globals::$langs->trans("Dolibarr") . ":</b> " . DOL_VERSION . "<br>\n";
3706
-            if (isset(Globals::$conf->global->MAIN_FEATURES_LEVEL))
3707
-                $out .= "<b>" . Globals::$langs->trans("LevelOfFeature") . ":</b> " . Globals::$conf->global->MAIN_FEATURES_LEVEL . "<br>\n";
3885
+            if (isset(Globals::$conf->global->MAIN_FEATURES_LEVEL)) {
3886
+                            $out .= "<b>" . Globals::$langs->trans("LevelOfFeature") . ":</b> " . Globals::$conf->global->MAIN_FEATURES_LEVEL . "<br>\n";
3887
+            }
3708 3888
             if (function_exists("phpversion")) {
3709 3889
                 $out .= "<b>" . Globals::$langs->trans("PHP") . ":</b> " . phpversion() . "<br>\n";
3710 3890
             }
@@ -3747,18 +3927,20 @@  discard block
 block discarded – undo
3747 3927
             Globals::$langs->load("errors");
3748 3928
 
3749 3929
 // Merge all into $errors array
3750
-            if (is_array($error) && is_array($errors))
3751
-                $errors = array_merge($error, $errors);
3752
-            elseif (is_array($error))
3753
-                $errors = $error;
3754
-            elseif (is_array($errors))
3755
-                $errors = array_merge(array($error), $errors);
3756
-            else
3757
-                $errors = array_merge(array($error));
3930
+            if (is_array($error) && is_array($errors)) {
3931
+                            $errors = array_merge($error, $errors);
3932
+            } elseif (is_array($error)) {
3933
+                            $errors = $error;
3934
+            } elseif (is_array($errors)) {
3935
+                            $errors = array_merge(array($error), $errors);
3936
+            } else {
3937
+                            $errors = array_merge(array($error));
3938
+            }
3758 3939
 
3759 3940
             foreach ($errors as $msg) {
3760
-                if (empty($msg))
3761
-                    continue;
3941
+                if (empty($msg)) {
3942
+                                    continue;
3943
+                }
3762 3944
                 if ($_SERVER['DOCUMENT_ROOT']) {  // Mode web
3763 3945
                     $out .= "<b>" . Globals::$langs->trans("Message") . ":</b> " . dol_escape_htmltag($msg) . "<br>\n";
3764 3946
                 } else {                        // Mode CLI
@@ -3776,9 +3958,9 @@  discard block
 block discarded – undo
3776 3958
             $out .= "<br>\n";
3777 3959
         }
3778 3960
 
3779
-        if (empty($dolibarr_main_prod))
3780
-            print $out;
3781
-        else {
3961
+        if (empty($dolibarr_main_prod)) {
3962
+                    print $out;
3963
+        } else {
3782 3964
             print Globals::$langs->trans("DolibarrHasDetectedError") . '. ';
3783 3965
             print Globals::$langs->trans("YouCanSetOptionDolibarrMainProdToZero");
3784 3966
             define("MAIN_CORE_ERROR", 1);
@@ -3801,16 +3983,18 @@  discard block
 block discarded – undo
3801 3983
     {
3802 3984
        // global Globals::$langs, Globals::$conf;
3803 3985
 
3804
-        if (empty($email))
3805
-            $email = Globals::$conf->global->MAIN_INFO_SOCIETE_MAIL;
3986
+        if (empty($email)) {
3987
+                    $email = Globals::$conf->global->MAIN_INFO_SOCIETE_MAIL;
3988
+        }
3806 3989
 
3807 3990
         Globals::$langs->load("errors");
3808 3991
         $now = dol_now();
3809 3992
 
3810 3993
         print '<br><div class="center login_main_message"><div class="' . $morecss . '">';
3811 3994
         print Globals::$langs->trans("ErrorContactEMail", $email, $prefixcode . dol_print_date($now, '%Y%m%d'));
3812
-        if ($errormessage)
3813
-            print '<br><br>' . $errormessage;
3995
+        if ($errormessage) {
3996
+                    print '<br><br>' . $errormessage;
3997
+        }
3814 3998
         if (is_array($errormessages) && count($errormessages)) {
3815 3999
             foreach ($errormessages as $mesgtoshow) {
3816 4000
                 print '<br><br>' . $mesgtoshow;
@@ -4053,12 +4237,15 @@  discard block
 block discarded – undo
4053 4237
         $savtotalnboflines = $totalnboflines;
4054 4238
         $totalnboflines = abs($totalnboflines);
4055 4239
 
4056
-        if ($picto == 'setup')
4057
-            $picto = 'title_setup.png';
4058
-        if ((Globals::$conf->browser->name == 'ie') && $picto == 'title_generic.png')
4059
-            $picto = 'title.gif';
4060
-        if ($limit < 0)
4061
-            $limit = Globals::$conf->liste_limit;
4240
+        if ($picto == 'setup') {
4241
+                    $picto = 'title_setup.png';
4242
+        }
4243
+        if ((Globals::$conf->browser->name == 'ie') && $picto == 'title_generic.png') {
4244
+                    $picto = 'title.gif';
4245
+        }
4246
+        if ($limit < 0) {
4247
+                    $limit = Globals::$conf->liste_limit;
4248
+        }
4062 4249
         if ($savlimit != 0 && (($num > $limit) || ($num == -1) || ($limit == 0))) {
4063 4250
             $nextpage = 1;
4064 4251
         } else {
@@ -4072,11 +4259,13 @@  discard block
 block discarded – undo
4072 4259
 // Left
4073 4260
 //if ($picto && $titre) print '<td class="nobordernopadding hideonsmartphone" width="40" align="left" valign="middle">'.img_picto('', $picto, 'id="pictotitle"', $pictoisfullpath).'</td>';
4074 4261
         print '<td class="nobordernopadding valignmiddle">';
4075
-        if ($picto && $titre)
4076
-            print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4262
+        if ($picto && $titre) {
4263
+                    print img_picto('', $picto, 'class="hideonsmartphone valignmiddle opacityhigh pictotitle widthpictotitle"', $pictoisfullpath);
4264
+        }
4077 4265
         print '<div class="titre inline-block">' . $titre;
4078
-        if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '')
4079
-            print ' (' . $totalnboflines . ')';
4266
+        if (!empty($titre) && $savtotalnboflines >= 0 && (string) $savtotalnboflines != '') {
4267
+                    print ' (' . $totalnboflines . ')';
4268
+        }
4080 4269
         print '</div></td>';
4081 4270
 
4082 4271
 // Center
@@ -4086,21 +4275,24 @@  discard block
 block discarded – undo
4086 4275
 
4087 4276
 // Right
4088 4277
         print '<td class="nobordernopadding valignmiddle" align="right">';
4089
-        if ($sortfield)
4090
-            $options .= "&sortfield=" . urlencode($sortfield);
4091
-        if ($sortorder)
4092
-            $options .= "&sortorder=" . urlencode($sortorder);
4093
-// Show navigation bar
4278
+        if ($sortfield) {
4279
+                    $options .= "&sortfield=" . urlencode($sortfield);
4280
+        }
4281
+        if ($sortorder) {
4282
+                    $options .= "&sortorder=" . urlencode($sortorder);
4283
+        }
4284
+        // Show navigation bar
4094 4285
         $pagelist = '';
4095 4286
         if ($savlimit != 0 && ($page > 0 || $num > $limit)) {
4096 4287
             if ($totalnboflines) { // If we know total nb of lines
4097 4288
 // Define nb of extra page links before and after selected page + ... + first or last
4098 4289
                 $maxnbofpage = (empty(Globals::$conf->dol_optimize_smallscreen) ? 4 : 1);
4099 4290
 
4100
-                if ($limit > 0)
4101
-                    $nbpages = ceil($totalnboflines / $limit);
4102
-                else
4103
-                    $nbpages = 1;
4291
+                if ($limit > 0) {
4292
+                                    $nbpages = ceil($totalnboflines / $limit);
4293
+                } else {
4294
+                                    $nbpages = 1;
4295
+                }
4104 4296
                 $cpt = ($page - $maxnbofpage);
4105 4297
                 if ($cpt < 0) {
4106 4298
                     $cpt = 0;
@@ -4108,10 +4300,11 @@  discard block
 block discarded – undo
4108 4300
 
4109 4301
                 if ($cpt >= 1) {
4110 4302
                     $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=0' . $options . '">1</a></li>';
4111
-                    if ($cpt > 2)
4112
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4113
-                    else if ($cpt == 2)
4114
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4303
+                    if ($cpt > 2) {
4304
+                                            $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4305
+                    } else if ($cpt == 2) {
4306
+                                            $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=1' . $options . '">2</a></li>';
4307
+                    }
4115 4308
                 }
4116 4309
 
4117 4310
                 do {
@@ -4124,14 +4317,14 @@  discard block
 block discarded – undo
4124 4317
                 } while ($cpt < $nbpages && $cpt <= $page + $maxnbofpage);
4125 4318
 
4126 4319
                 if ($cpt < $nbpages) {
4127
-                    if ($cpt < $nbpages - 2)
4128
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4129
-                    else if ($cpt == $nbpages - 2)
4130
-                        $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4320
+                    if ($cpt < $nbpages - 2) {
4321
+                                            $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="inactive"' : '') . '>...</span></li>';
4322
+                    } else if ($cpt == $nbpages - 2) {
4323
+                                            $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 2) . $options . '">' . ($nbpages - 1) . '</a></li>';
4324
+                    }
4131 4325
                     $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><a href="' . $file . '?page=' . ($nbpages - 1) . $options . '">' . $nbpages . '</a></li>';
4132 4326
                 }
4133
-            }
4134
-            else {
4327
+            } else {
4135 4328
                 $pagelist .= '<li' . ((Globals::$conf->dol_use_jmobile != 4) ? ' class="pagination"' : '') . '><span ' . ((Globals::$conf->dol_use_jmobile != 4) ? 'class="active"' : '') . '>' . ($page + 1) . "</li>";
4136 4329
             }
4137 4330
         }
@@ -4167,18 +4360,21 @@  discard block
 block discarded – undo
4167 4360
             $pagesizechoices = '10:10,15:15,20:20,30:30,40:40,50:50,100:100,250:250,500:500,1000:1000,5000:5000';
4168 4361
 //$pagesizechoices.=',0:'.Globals::$langs->trans("All");     // Not yet supported
4169 4362
 //$pagesizechoices.=',2:2';
4170
-            if (!empty(Globals::$conf->global->MAIN_PAGESIZE_CHOICES))
4171
-                $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4363
+            if (!empty(Globals::$conf->global->MAIN_PAGESIZE_CHOICES)) {
4364
+                            $pagesizechoices = Globals::$conf->global->MAIN_PAGESIZE_CHOICES;
4365
+            }
4172 4366
 
4173 4367
             print '<li class="pagination">';
4174 4368
             print '<select class="flat selectlimit" name="limit" title="' . dol_escape_htmltag(Globals::$langs->trans("MaxNbOfRecordPerPage")) . '">';
4175 4369
             $tmpchoice = explode(',', $pagesizechoices);
4176 4370
             $tmpkey = $limit . ':' . $limit;
4177
-            if (!in_array($tmpkey, $tmpchoice))
4178
-                $tmpchoice[] = $tmpkey;
4371
+            if (!in_array($tmpkey, $tmpchoice)) {
4372
+                            $tmpchoice[] = $tmpkey;
4373
+            }
4179 4374
             $tmpkey = Globals::$conf->liste_limit . ':' . Globals::$conf->liste_limit;
4180
-            if (!in_array($tmpkey, $tmpchoice))
4181
-                $tmpchoice[] = $tmpkey;
4375
+            if (!in_array($tmpkey, $tmpchoice)) {
4376
+                            $tmpchoice[] = $tmpkey;
4377
+            }
4182 4378
             asort($tmpchoice, SORT_NUMERIC);
4183 4379
             $found = false;
4184 4380
             foreach ($tmpchoice as $val) {
@@ -4254,14 +4450,15 @@  discard block
 block discarded – undo
4254 4450
         }
4255 4451
 
4256 4452
 // If rate is '9/9/9' we don't change it.  If rate is '9.000' we apply price()
4257
-        if (!preg_match('/\//', $rate))
4258
-            $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4259
-        else {
4453
+        if (!preg_match('/\//', $rate)) {
4454
+                    $ret = price($rate, 0, '', 0, 0) . ($addpercent ? '%' : '');
4455
+        } else {
4260 4456
 // TODO Split on / and output with a price2num to have clean numbers without ton of 000.
4261 4457
             $ret = $rate . ($addpercent ? '%' : '');
4262 4458
         }
4263
-        if (($info_bits & 1) && $usestarfornpr >= 0)
4264
-            $ret .= ' *';
4459
+        if (($info_bits & 1) && $usestarfornpr >= 0) {
4460
+                    $ret .= ' *';
4461
+        }
4265 4462
         $ret .= $morelabel;
4266 4463
         return $ret;
4267 4464
     }
@@ -4285,11 +4482,14 @@  discard block
 block discarded – undo
4285 4482
     {
4286 4483
        // global Globals::$langs, Globals::$conf;
4287 4484
 // Clean parameters
4288
-        if (empty($amount))
4289
-            $amount = 0; // To have a numeric value if amount not defined or = ''
4485
+        if (empty($amount)) {
4486
+                    $amount = 0;
4487
+        }
4488
+        // To have a numeric value if amount not defined or = ''
4290 4489
         $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number)
4291
-        if ($rounding < 0)
4292
-            $rounding = min(Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT, Globals::$conf->global->MAIN_MAX_DECIMALS_TOT);
4490
+        if ($rounding < 0) {
4491
+                    $rounding = min(Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT, Globals::$conf->global->MAIN_MAX_DECIMALS_TOT);
4492
+        }
4293 4493
         $nbdecimal = $rounding;
4294 4494
 
4295 4495
 // Output separators by default (french)
@@ -4297,18 +4497,22 @@  discard block
 block discarded – undo
4297 4497
         $thousand = ' ';
4298 4498
 
4299 4499
 // If $outlangs not forced, we use use language
4300
-        if (!is_object($outlangs))
4301
-            $outlangs = Globals::$langs;
4302
-
4303
-        if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal")
4304
-            $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
4305
-        if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand")
4306
-            $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
4307
-        if ($thousand == 'None')
4308
-            $thousand = '';
4309
-        else if ($thousand == 'Space')
4310
-            $thousand = ' ';
4311
-//print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4500
+        if (!is_object($outlangs)) {
4501
+                    $outlangs = Globals::$langs;
4502
+        }
4503
+
4504
+        if ($outlangs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4505
+                    $dec = $outlangs->transnoentitiesnoconv("SeparatorDecimal");
4506
+        }
4507
+        if ($outlangs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4508
+                    $thousand = $outlangs->transnoentitiesnoconv("SeparatorThousand");
4509
+        }
4510
+        if ($thousand == 'None') {
4511
+                    $thousand = '';
4512
+        } else if ($thousand == 'Space') {
4513
+                    $thousand = ' ';
4514
+        }
4515
+        //print "outlangs=".$outlangs->defaultlang." amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4312 4516
 //print "amount=".$amount."-";
4313 4517
         $amount = str_replace(',', '.', $amount); // should be useless
4314 4518
 //print $amount."-";
@@ -4319,9 +4523,10 @@  discard block
 block discarded – undo
4319 4523
         $end = '';
4320 4524
 
4321 4525
 // We increase nbdecimal if there is more decimal than asked (to not loose information)
4322
-        if (dol_strlen($decpart) > $nbdecimal)
4323
-            $nbdecimal = dol_strlen($decpart);
4324
-// Si on depasse max
4526
+        if (dol_strlen($decpart) > $nbdecimal) {
4527
+                    $nbdecimal = dol_strlen($decpart);
4528
+        }
4529
+        // Si on depasse max
4325 4530
         if ($trunc && $nbdecimal > Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN) {
4326 4531
             $nbdecimal = Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN;
4327 4532
             if (preg_match('/\.\.\./i', Globals::$conf->global->MAIN_MAX_DECIMALS_SHOWN)) {
@@ -4331,8 +4536,9 @@  discard block
 block discarded – undo
4331 4536
         }
4332 4537
 
4333 4538
 // If force rounding
4334
-        if ($forcerounding >= 0)
4335
-            $nbdecimal = $forcerounding;
4539
+        if ($forcerounding >= 0) {
4540
+                    $nbdecimal = $forcerounding;
4541
+        }
4336 4542
 
4337 4543
 // Format number
4338 4544
         $output = number_format($amount, $nbdecimal, $dec, $thousand);
@@ -4343,13 +4549,14 @@  discard block
 block discarded – undo
4343 4549
 // Add symbol of currency if requested
4344 4550
         $cursymbolbefore = $cursymbolafter = '';
4345 4551
         if ($currency_code) {
4346
-            if ($currency_code == 'auto')
4347
-                $currency_code = Globals::$conf->currency;
4552
+            if ($currency_code == 'auto') {
4553
+                            $currency_code = Globals::$conf->currency;
4554
+            }
4348 4555
 
4349 4556
             $listofcurrenciesbefore = array('USD', 'GBP', 'AUD', 'MXN', 'PEN', 'CNY');
4350
-            if (in_array($currency_code, $listofcurrenciesbefore))
4351
-                $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4352
-            else {
4557
+            if (in_array($currency_code, $listofcurrenciesbefore)) {
4558
+                            $cursymbolbefore .= $outlangs->getCurrencySymbol($currency_code);
4559
+            } else {
4353 4560
                 $tmpcur = $outlangs->getCurrencySymbol($currency_code);
4354 4561
                 $cursymbolafter .= ($tmpcur == $currency_code ? ' ' . $tmpcur : $tmpcur);
4355 4562
             }
@@ -4382,15 +4589,18 @@  discard block
 block discarded – undo
4382 4589
 // Decimal delimiter for PHP and database SQL requests must be '.'
4383 4590
         $dec = ',';
4384 4591
         $thousand = ' ';
4385
-        if (Globals::$langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal")
4386
-            $dec = Globals::$langs->transnoentitiesnoconv("SeparatorDecimal");
4387
-        if (Globals::$langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand")
4388
-            $thousand = Globals::$langs->transnoentitiesnoconv("SeparatorThousand");
4389
-        if ($thousand == 'None')
4390
-            $thousand = '';
4391
-        elseif ($thousand == 'Space')
4392
-            $thousand = ' ';
4393
-//print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4592
+        if (Globals::$langs->transnoentitiesnoconv("SeparatorDecimal") != "SeparatorDecimal") {
4593
+                    $dec = Globals::$langs->transnoentitiesnoconv("SeparatorDecimal");
4594
+        }
4595
+        if (Globals::$langs->transnoentitiesnoconv("SeparatorThousand") != "SeparatorThousand") {
4596
+                    $thousand = Globals::$langs->transnoentitiesnoconv("SeparatorThousand");
4597
+        }
4598
+        if ($thousand == 'None') {
4599
+                    $thousand = '';
4600
+        } elseif ($thousand == 'Space') {
4601
+                    $thousand = ' ';
4602
+        }
4603
+        //print "amount=".$amount." html=".$form." trunc=".$trunc." nbdecimal=".$nbdecimal." dec='".$dec."' thousand='".$thousand."'<br>";
4394 4604
 // Convert value to universal number format (no thousand separator, '.' as decimal separator)
4395 4605
         if ($alreadysqlnb != 1) { // If not a PHP number or unknown, we change format
4396 4606
 //print 'PP'.$amount.' - '.$dec.' - '.$thousand.' - '.intval($amount).'<br>';
@@ -4405,8 +4615,10 @@  discard block
 block discarded – undo
4405 4615
             }
4406 4616
 //print "QQ".$amount.'<br>';
4407 4617
 // Now make replace (the main goal of function)
4408
-            if ($thousand != ',' && $thousand != '.')
4409
-                $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4618
+            if ($thousand != ',' && $thousand != '.') {
4619
+                            $amount = str_replace(',', '.', $amount);
4620
+            }
4621
+            // To accept 2 notations for french users
4410 4622
             $amount = str_replace(' ', '', $amount);  // To avoid spaces
4411 4623
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4412 4624
             $amount = str_replace($dec, '.', $amount);
@@ -4415,20 +4627,24 @@  discard block
 block discarded – undo
4415 4627
 // Now, make a rounding if required
4416 4628
         if ($rounding) {
4417 4629
             $nbofdectoround = '';
4418
-            if ($rounding == 'MU')
4419
-                $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT;
4420
-            elseif ($rounding == 'MT')
4421
-                $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_TOT;
4422
-            elseif ($rounding == 'MS')
4423
-                $nbofdectoround = empty(Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK;
4424
-            elseif (is_numeric($rounding))
4425
-                $nbofdectoround = $rounding;
4426
-//print "RR".$amount.' - '.$nbofdectoround.'<br>';
4427
-            if (dol_strlen($nbofdectoround))
4428
-                $amount = round($amount, $nbofdectoround); // $nbofdectoround can be 0.
4429
-            else
4430
-                return 'ErrorBadParameterProvidedToFunction';
4431
-//print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
4630
+            if ($rounding == 'MU') {
4631
+                            $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_UNIT;
4632
+            } elseif ($rounding == 'MT') {
4633
+                            $nbofdectoround = Globals::$conf->global->MAIN_MAX_DECIMALS_TOT;
4634
+            } elseif ($rounding == 'MS') {
4635
+                            $nbofdectoround = empty(Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK) ? 5 : Globals::$conf->global->MAIN_MAX_DECIMALS_STOCK;
4636
+            } elseif (is_numeric($rounding)) {
4637
+                            $nbofdectoround = $rounding;
4638
+            }
4639
+            //print "RR".$amount.' - '.$nbofdectoround.'<br>';
4640
+            if (dol_strlen($nbofdectoround)) {
4641
+                            $amount = round($amount, $nbofdectoround);
4642
+            }
4643
+            // $nbofdectoround can be 0.
4644
+            else {
4645
+                            return 'ErrorBadParameterProvidedToFunction';
4646
+            }
4647
+            //print 'SS'.$amount.' - '.$nbofdec.' - '.$dec.' - '.$thousand.' - '.$nbofdectoround.'<br>';
4432 4648
 // Convert amount to format with dolibarr dec and thousand (this is because PHP convert a number
4433 4649
 // to format defined by LC_NUMERIC after a calculation and we want source format to be defined by Dolibarr setup.
4434 4650
             if (is_numeric($amount)) {
@@ -4441,8 +4657,10 @@  discard block
 block discarded – undo
4441 4657
 //print "TT".$amount.'<br>';
4442 4658
 // Always make replace because each math static function (like round) replace
4443 4659
 // with local values and we want a number that has a SQL string format x.y
4444
-            if ($thousand != ',' && $thousand != '.')
4445
-                $amount = str_replace(',', '.', $amount); // To accept 2 notations for french users
4660
+            if ($thousand != ',' && $thousand != '.') {
4661
+                            $amount = str_replace(',', '.', $amount);
4662
+            }
4663
+            // To accept 2 notations for french users
4446 4664
             $amount = str_replace(' ', '', $amount);  // To avoid spaces
4447 4665
             $amount = str_replace($thousand, '', $amount); // Replace of thousand before replace of dec to avoid pb if thousand is .
4448 4666
             $amount = str_replace($dec, '.', $amount);
@@ -4501,8 +4719,9 @@  discard block
 block discarded – undo
4501 4719
     {
4502 4720
        // global $db, Globals::$conf, $mysoc;
4503 4721
 
4504
-        if (empty($thirdparty_seller) || !is_object($thirdparty_seller))
4505
-            $thirdparty_seller = $mysoc;
4722
+        if (empty($thirdparty_seller) || !is_object($thirdparty_seller)) {
4723
+                    $thirdparty_seller = $mysoc;
4724
+        }
4506 4725
 
4507 4726
         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);
4508 4727
 
@@ -4520,37 +4739,43 @@  discard block
 block discarded – undo
4520 4739
 // Some test to guess with no need to make database access
4521 4740
         if ($mysoc->country_code == 'ES') { // For spain localtaxes 1 and 2, tax is qualified if buyer use local tax
4522 4741
             if ($local == 1) {
4523
-                if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0")
4524
-                    return 0;
4742
+                if (!$mysoc->localtax1_assuj || (string) $vatratecleaned == "0") {
4743
+                                    return 0;
4744
+                }
4525 4745
                 if ($thirdparty_seller->id == $mysoc->id) {
4526
-                    if (!$thirdparty_buyer->localtax1_assuj)
4527
-                        return 0;
4528
-                }
4529
-                else {
4530
-                    if (!$thirdparty_seller->localtax1_assuj)
4531
-                        return 0;
4746
+                    if (!$thirdparty_buyer->localtax1_assuj) {
4747
+                                            return 0;
4748
+                    }
4749
+                } else {
4750
+                    if (!$thirdparty_seller->localtax1_assuj) {
4751
+                                            return 0;
4752
+                    }
4532 4753
                 }
4533 4754
             }
4534 4755
 
4535 4756
             if ($local == 2) {
4536 4757
 //if (! $mysoc->localtax2_assuj || (string) $vatratecleaned == "0") return 0;
4537
-                if (!$mysoc->localtax2_assuj)
4538
-                    return 0;  // If main vat is 0, IRPF may be different than 0.
4758
+                if (!$mysoc->localtax2_assuj) {
4759
+                                    return 0;
4760
+                }
4761
+                // If main vat is 0, IRPF may be different than 0.
4539 4762
                 if ($thirdparty_seller->id == $mysoc->id) {
4540
-                    if (!$thirdparty_buyer->localtax2_assuj)
4541
-                        return 0;
4542
-                }
4543
-                else {
4544
-                    if (!$thirdparty_seller->localtax2_assuj)
4545
-                        return 0;
4763
+                    if (!$thirdparty_buyer->localtax2_assuj) {
4764
+                                            return 0;
4765
+                    }
4766
+                } else {
4767
+                    if (!$thirdparty_seller->localtax2_assuj) {
4768
+                                            return 0;
4769
+                    }
4546 4770
                 }
4547 4771
             }
4548
-        }
4549
-        else {
4550
-            if ($local == 1 && !$thirdparty_seller->localtax1_assuj)
4551
-                return 0;
4552
-            if ($local == 2 && !$thirdparty_seller->localtax2_assuj)
4553
-                return 0;
4772
+        } else {
4773
+            if ($local == 1 && !$thirdparty_seller->localtax1_assuj) {
4774
+                            return 0;
4775
+            }
4776
+            if ($local == 2 && !$thirdparty_seller->localtax2_assuj) {
4777
+                            return 0;
4778
+            }
4554 4779
         }
4555 4780
 
4556 4781
 // For some country MAIN_GET_LOCALTAXES_VALUES_FROM_THIRDPARTY is forced to on.
@@ -4592,19 +4817,23 @@  discard block
 block discarded – undo
4592 4817
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t, " . MAIN_DB_PREFIX . "c_country as c";
4593 4818
         $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $thirdparty_seller->country_code . "'";
4594 4819
         $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4595
-        if ($vatratecode)
4596
-            $sql .= " AND t.code ='" . $vatratecode . "'";  // If we have the code, we use it in priority
4597
-        else
4598
-            $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4820
+        if ($vatratecode) {
4821
+                    $sql .= " AND t.code ='" . $vatratecode . "'";
4822
+        }
4823
+        // If we have the code, we use it in priority
4824
+        else {
4825
+                    $sql .= " AND t.recuperableonly ='" . $vatnpr . "'";
4826
+        }
4599 4827
         dol_syslog("get_localtax", LOG_DEBUG);
4600 4828
         $resql = $db->query($sql);
4601 4829
 
4602 4830
         if ($resql) {
4603 4831
             $obj = $db->fetch_object($resql);
4604
-            if ($local == 1)
4605
-                return $obj->localtax1;
4606
-            elseif ($local == 2)
4607
-                return $obj->localtax2;
4832
+            if ($local == 1) {
4833
+                            return $obj->localtax1;
4834
+            } elseif ($local == 2) {
4835
+                            return $obj->localtax2;
4836
+            }
4608 4837
         }
4609 4838
 
4610 4839
         return 0;
@@ -4650,10 +4879,11 @@  discard block
 block discarded – undo
4650 4879
         $resql = $db->query($sql);
4651 4880
         if ($resql) {
4652 4881
             $obj = $db->fetch_object($resql);
4653
-            if ($local == 1)
4654
-                return $obj->localtax1;
4655
-            elseif ($local == 2)
4656
-                return $obj->localtax2;
4882
+            if ($local == 1) {
4883
+                            return $obj->localtax1;
4884
+            } elseif ($local == 2) {
4885
+                            return $obj->localtax2;
4886
+            }
4657 4887
         }
4658 4888
 
4659 4889
         return 0;
@@ -4679,9 +4909,9 @@  discard block
 block discarded – undo
4679 4909
 // Search local taxes
4680 4910
         $sql = "SELECT t.rowid, t.code, t.taux as rate, t.recuperableonly as npr, t.accountancy_code_sell, t.accountancy_code_buy";
4681 4911
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4682
-        if ($firstparamisid)
4683
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4684
-        else {
4912
+        if ($firstparamisid) {
4913
+                    $sql .= " WHERE t.rowid = " . (int) $vatrate;
4914
+        } else {
4685 4915
             $vatratecleaned = $vatrate;
4686 4916
             $vatratecode = '';
4687 4917
             if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "xx (yy)"
@@ -4694,19 +4924,22 @@  discard block
 block discarded – undo
4694 4924
               else $sql.= " WHERE t.fk_pays = c.rowid AND c.code = '".$seller->country_code."'"; */
4695 4925
             $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4696 4926
             $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4697
-            if ($vatratecode)
4698
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4927
+            if ($vatratecode) {
4928
+                            $sql .= " AND t.code = '" . $vatratecode . "'";
4929
+            }
4699 4930
         }
4700 4931
 
4701 4932
         $resql = $db->query($sql);
4702 4933
         if ($resql) {
4703 4934
             $obj = $db->fetch_object($resql);
4704
-            if ($obj)
4705
-                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);
4706
-            else
4707
-                return array();
4708
-        } else
4709
-            dol_print_error($db);
4935
+            if ($obj) {
4936
+                            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);
4937
+            } else {
4938
+                            return array();
4939
+            }
4940
+        } else {
4941
+                    dol_print_error($db);
4942
+        }
4710 4943
 
4711 4944
         return array();
4712 4945
     }
@@ -4736,9 +4969,9 @@  discard block
 block discarded – undo
4736 4969
 // Search local taxes
4737 4970
         $sql = "SELECT t.localtax1, t.localtax1_type, t.localtax2, t.localtax2_type, t.accountancy_code_sell, t.accountancy_code_buy";
4738 4971
         $sql .= " FROM " . MAIN_DB_PREFIX . "c_tva as t";
4739
-        if ($firstparamisid)
4740
-            $sql .= " WHERE t.rowid = " . (int) $vatrate;
4741
-        else {
4972
+        if ($firstparamisid) {
4973
+                    $sql .= " WHERE t.rowid = " . (int) $vatrate;
4974
+        } else {
4742 4975
             $vatratecleaned = $vatrate;
4743 4976
             $vatratecode = '';
4744 4977
             if (preg_match('/^(.*)\s*\((.*)\)$/', $vatrate, $reg)) {      // If vat is "x.x (yy)"
@@ -4747,13 +4980,17 @@  discard block
 block discarded – undo
4747 4980
             }
4748 4981
 
4749 4982
             $sql .= ", " . MAIN_DB_PREFIX . "c_country as c";
4750
-            if ($mysoc->country_code == 'ES')
4751
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";    // local tax in spain use the buyer country ??
4752
-            else
4753
-                $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4983
+            if ($mysoc->country_code == 'ES') {
4984
+                            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $buyer->country_code . "'";
4985
+            }
4986
+            // local tax in spain use the buyer country ??
4987
+            else {
4988
+                            $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '" . $seller->country_code . "'";
4989
+            }
4754 4990
             $sql .= " AND t.taux = " . ((float) $vatratecleaned) . " AND t.active = 1";
4755
-            if ($vatratecode)
4756
-                $sql .= " AND t.code = '" . $vatratecode . "'";
4991
+            if ($vatratecode) {
4992
+                            $sql .= " AND t.code = '" . $vatratecode . "'";
4993
+            }
4757 4994
         }
4758 4995
 
4759 4996
         $resql = $db->query($sql);
@@ -4799,17 +5036,17 @@  discard block
 block discarded – undo
4799 5036
                 if ($idprodfournprice > 0) {     // We want vat for product for a "supplier" object
4800 5037
                     $product->get_buyprice($idprodfournprice, 0, 0, 0);
4801 5038
                     $ret = $product->vatrate_supplier;
4802
-                    if ($product->default_vat_code)
4803
-                        $ret .= ' (' . $product->default_vat_code . ')';
4804
-                }
4805
-                else {
5039
+                    if ($product->default_vat_code) {
5040
+                                            $ret .= ' (' . $product->default_vat_code . ')';
5041
+                    }
5042
+                } else {
4806 5043
                     $ret = $product->tva_tx;    // Default vat of product we defined
4807
-                    if ($product->default_vat_code)
4808
-                        $ret .= ' (' . $product->default_vat_code . ')';
5044
+                    if ($product->default_vat_code) {
5045
+                                            $ret .= ' (' . $product->default_vat_code . ')';
5046
+                    }
4809 5047
                 }
4810 5048
                 $found = 1;
4811
-            }
4812
-            else {
5049
+            } else {
4813 5050
 // TODO Read default product vat according to countrycode and product. Vat for couple countrycode/product is a feature not implemeted yet.
4814 5051
 // May be usefull/required if hidden option SERVICE_ARE_ECOMMERCE_200238EC is on
4815 5052
             }
@@ -4829,14 +5066,18 @@  discard block
 block discarded – undo
4829 5066
                     $obj = $db->fetch_object($resql);
4830 5067
                     if ($obj) {
4831 5068
                         $ret = $obj->vat_rate;
4832
-                        if ($obj->default_vat_code)
4833
-                            $ret .= ' (' . $obj->default_vat_code . ')';
5069
+                        if ($obj->default_vat_code) {
5070
+                                                    $ret .= ' (' . $obj->default_vat_code . ')';
5071
+                        }
4834 5072
                     }
4835 5073
                     $db->free($sql);
4836
-                } else
4837
-                    dol_print_error($db);
4838
-            } else
4839
-                $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;    // Forced value if autodetect fails
5074
+                } else {
5075
+                                    dol_print_error($db);
5076
+                }
5077
+            } else {
5078
+                            $ret = Globals::$conf->global->MAIN_VAT_DEFAULT_IF_AUTODETECT_FAILS;
5079
+            }
5080
+            // Forced value if autodetect fails
4840 5081
         }
4841 5082
 
4842 5083
         dol_syslog("get_product_vat_for_country: ret=" . $ret);
@@ -4891,13 +5132,15 @@  discard block
 block discarded – undo
4891 5132
             if ($resql) {
4892 5133
                 $obj = $db->fetch_object($resql);
4893 5134
                 if ($obj) {
4894
-                    if ($local == 1)
4895
-                        $ret = $obj->localtax1;
4896
-                    elseif ($local == 2)
4897
-                        $ret = $obj->localtax2;
5135
+                    if ($local == 1) {
5136
+                                            $ret = $obj->localtax1;
5137
+                    } elseif ($local == 2) {
5138
+                                            $ret = $obj->localtax2;
5139
+                    }
4898 5140
                 }
4899
-            } else
4900
-                dol_print_error($db);
5141
+            } else {
5142
+                            dol_print_error($db);
5143
+            }
4901 5144
         }
4902 5145
 
4903 5146
         dol_syslog("get_product_localtax_for_country: ret=" . $ret);
@@ -5000,15 +5243,16 @@  discard block
 block discarded – undo
5000 5243
        // global $db;
5001 5244
 
5002 5245
         if ($idprodfournprice > 0) {
5003
-            if (!class_exists('ProductFournisseur'))
5004
-                require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5246
+            if (!class_exists('ProductFournisseur')) {
5247
+                            require_once DOL_BASE_PATH . '/fourn/class/fournisseur.product.class.php';
5248
+            }
5005 5249
             $prodprice = new ProductFournisseur($db);
5006 5250
             $prodprice->fetch_product_fournisseur_price($idprodfournprice);
5007 5251
             return $prodprice->fourn_tva_npr;
5008
-        }
5009
-        elseif ($idprod > 0) {
5010
-            if (!class_exists('Product'))
5011
-                require_once DOL_BASE_PATH . 'product/class/product.class.php';
5252
+        } elseif ($idprod > 0) {
5253
+            if (!class_exists('Product')) {
5254
+                            require_once DOL_BASE_PATH . 'product/class/product.class.php';
5255
+            }
5012 5256
             $prod = new Product($db);
5013 5257
             $prod->fetch($idprod);
5014 5258
             return $prod->tva_npr;
@@ -5034,30 +5278,35 @@  discard block
 block discarded – undo
5034 5278
     {
5035 5279
        // global $mysoc;
5036 5280
 
5037
-        if (!is_object($thirdparty_seller))
5038
-            return -1;
5039
-        if (!is_object($thirdparty_buyer))
5040
-            return -1;
5281
+        if (!is_object($thirdparty_seller)) {
5282
+                    return -1;
5283
+        }
5284
+        if (!is_object($thirdparty_buyer)) {
5285
+                    return -1;
5286
+        }
5041 5287
 
5042 5288
         if ($local == 1) { // Localtax 1
5043 5289
             if ($mysoc->country_code == 'ES') {
5044
-                if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj)
5045
-                    return 0;
5046
-            }
5047
-            else {
5290
+                if (is_numeric($thirdparty_buyer->localtax1_assuj) && !$thirdparty_buyer->localtax1_assuj) {
5291
+                                    return 0;
5292
+                }
5293
+            } else {
5048 5294
 // Si vendeur non assujeti a Localtax1, localtax1 par default=0
5049
-                if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj)
5050
-                    return 0;
5051
-                if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off')
5052
-                    return 0;
5053
-            }
5054
-        }
5055
-        elseif ($local == 2) { //I Localtax 2
5295
+                if (is_numeric($thirdparty_seller->localtax1_assuj) && !$thirdparty_seller->localtax1_assuj) {
5296
+                                    return 0;
5297
+                }
5298
+                if (!is_numeric($thirdparty_seller->localtax1_assuj) && $thirdparty_seller->localtax1_assuj == 'localtax1off') {
5299
+                                    return 0;
5300
+                }
5301
+            }
5302
+        } elseif ($local == 2) { //I Localtax 2
5056 5303
 // Si vendeur non assujeti a Localtax2, localtax2 par default=0
5057
-            if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj)
5058
-                return 0;
5059
-            if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off')
5060
-                return 0;
5304
+            if (is_numeric($thirdparty_seller->localtax2_assuj) && !$thirdparty_seller->localtax2_assuj) {
5305
+                            return 0;
5306
+            }
5307
+            if (!is_numeric($thirdparty_seller->localtax2_assuj) && $thirdparty_seller->localtax2_assuj == 'localtax2off') {
5308
+                            return 0;
5309
+            }
5061 5310
         }
5062 5311
 
5063 5312
         if ($thirdparty_seller->country_code == $thirdparty_buyer->country_code) {
@@ -5082,31 +5331,38 @@  discard block
 block discarded – undo
5082 5331
         $classname = '';
5083 5332
         if ($yesno == 1 || strtolower($yesno) == 'yes' || strtolower($yesno) == 'true') {  // A mettre avant test sur no a cause du == 0
5084 5333
             $result = Globals::$langs->trans('yes');
5085
-            if ($case == 1 || $case == 3)
5086
-                $result = Globals::$langs->trans("Yes");
5087
-            if ($case == 2)
5088
-                $result = '<input type="checkbox" value="1" checked disabled>';
5089
-            if ($case == 3)
5090
-                $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5334
+            if ($case == 1 || $case == 3) {
5335
+                            $result = Globals::$langs->trans("Yes");
5336
+            }
5337
+            if ($case == 2) {
5338
+                            $result = '<input type="checkbox" value="1" checked disabled>';
5339
+            }
5340
+            if ($case == 3) {
5341
+                            $result = '<input type="checkbox" value="1" checked disabled> ' . $result;
5342
+            }
5091 5343
 
5092 5344
             $classname = 'ok';
5093
-        }
5094
-        elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
5345
+        } elseif ($yesno == 0 || strtolower($yesno) == 'no' || strtolower($yesno) == 'false') {
5095 5346
             $result = Globals::$langs->trans("no");
5096
-            if ($case == 1 || $case == 3)
5097
-                $result = Globals::$langs->trans("No");
5098
-            if ($case == 2)
5099
-                $result = '<input type="checkbox" value="0" disabled>';
5100
-            if ($case == 3)
5101
-                $result = '<input type="checkbox" value="0" disabled> ' . $result;
5102
-
5103
-            if ($color == 2)
5104
-                $classname = 'ok';
5105
-            else
5106
-                $classname = 'error';
5107
-        }
5108
-        if ($color)
5109
-            return '<font class="' . $classname . '">' . $result . '</font>';
5347
+            if ($case == 1 || $case == 3) {
5348
+                            $result = Globals::$langs->trans("No");
5349
+            }
5350
+            if ($case == 2) {
5351
+                            $result = '<input type="checkbox" value="0" disabled>';
5352
+            }
5353
+            if ($case == 3) {
5354
+                            $result = '<input type="checkbox" value="0" disabled> ' . $result;
5355
+            }
5356
+
5357
+            if ($color == 2) {
5358
+                            $classname = 'ok';
5359
+            } else {
5360
+                            $classname = 'error';
5361
+            }
5362
+        }
5363
+        if ($color) {
5364
+                    return '<font class="' . $classname . '">' . $result . '</font>';
5365
+        }
5110 5366
         return $result;
5111 5367
     }
5112 5368
 
@@ -5132,23 +5388,27 @@  discard block
 block discarded – undo
5132 5388
         $path = '';
5133 5389
 
5134 5390
         $arrayforoldpath = array('cheque', 'user', 'category', 'holiday', 'supplier_invoice', 'invoice_supplier', 'mailing', 'supplier_payment');
5135
-        if (!empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
5136
-            $arrayforoldpath[] = 'product';
5391
+        if (!empty(Globals::$conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
5392
+                    $arrayforoldpath[] = 'product';
5393
+        }
5137 5394
         if (!empty($level) && in_array($modulepart, $arrayforoldpath)) {
5138 5395
 // This part should be removed once all code is using "get_exdir" to forge path, with all parameters provided.
5139
-            if (empty($alpha))
5140
-                $num = preg_replace('/([^0-9])/i', '', $num);
5141
-            else
5142
-                $num = preg_replace('/^.*\-/i', '', $num);
5396
+            if (empty($alpha)) {
5397
+                            $num = preg_replace('/([^0-9])/i', '', $num);
5398
+            } else {
5399
+                            $num = preg_replace('/^.*\-/i', '', $num);
5400
+            }
5143 5401
             $num = substr("000" . $num, -$level);
5144
-            if ($level == 1)
5145
-                $path = substr($num, 0, 1);
5146
-            if ($level == 2)
5147
-                $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5148
-            if ($level == 3)
5149
-                $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5150
-        }
5151
-        else {
5402
+            if ($level == 1) {
5403
+                            $path = substr($num, 0, 1);
5404
+            }
5405
+            if ($level == 2) {
5406
+                            $path = substr($num, 1, 1) . '/' . substr($num, 0, 1);
5407
+            }
5408
+            if ($level == 3) {
5409
+                            $path = substr($num, 2, 1) . '/' . substr($num, 1, 1) . '/' . substr($num, 0, 1);
5410
+            }
5411
+        } else {
5152 5412
 // TODO
5153 5413
 // We will enhance here a common way of forging path for document storage
5154 5414
 // Here, object->id, object->ref and modulepart are required.
@@ -5159,8 +5419,9 @@  discard block
 block discarded – undo
5159 5419
             }
5160 5420
         }
5161 5421
 
5162
-        if (empty($withoutslash) && !empty($path))
5163
-            $path .= '/';
5422
+        if (empty($withoutslash) && !empty($path)) {
5423
+                    $path .= '/';
5424
+        }
5164 5425
 
5165 5426
         return $path;
5166 5427
     }
@@ -5180,8 +5441,9 @@  discard block
 block discarded – undo
5180 5441
         dol_syslog("functions.lib::dol_mkdir: dir=" . $dir, LOG_INFO);
5181 5442
 
5182 5443
         $dir_osencoded = dol_osencode($dir);
5183
-        if (@is_dir($dir_osencoded))
5184
-            return 0;
5444
+        if (@is_dir($dir_osencoded)) {
5445
+                    return 0;
5446
+        }
5185 5447
 
5186 5448
         $nberr = 0;
5187 5449
         $nbcreated = 0;
@@ -5196,12 +5458,15 @@  discard block
 block discarded – undo
5196 5458
         $cdir = explode("/", $dir);
5197 5459
         $num = count($cdir);
5198 5460
         for ($i = 0; $i < $num; $i++) {
5199
-            if ($i > 0)
5200
-                $ccdir .= '/' . $cdir[$i];
5201
-            else
5202
-                $ccdir .= $cdir[$i];
5203
-            if (preg_match("/^.:$/", $ccdir, $regs))
5204
-                continue; // Si chemin Windows incomplet, on poursuit par rep suivant
5461
+            if ($i > 0) {
5462
+                            $ccdir .= '/' . $cdir[$i];
5463
+            } else {
5464
+                            $ccdir .= $cdir[$i];
5465
+            }
5466
+            if (preg_match("/^.:$/", $ccdir, $regs)) {
5467
+                            continue;
5468
+            }
5469
+            // Si chemin Windows incomplet, on poursuit par rep suivant
5205 5470
 
5206 5471
 
5207 5472
 
@@ -5293,8 +5558,9 @@  discard block
 block discarded – undo
5293 5558
      */
5294 5559
     static function dol_string_nohtmltag($stringtoclean, $removelinefeed = 1, $pagecodeto = 'UTF-8', $strip_tags = 0)
5295 5560
     {
5296
-        if ($removelinefeed == 2)
5297
-            $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
5561
+        if ($removelinefeed == 2) {
5562
+                    $stringtoclean = preg_replace('/<br[^>]*>\n+/ims', '<br>', $stringtoclean);
5563
+        }
5298 5564
         $temp = preg_replace('/<br[^>]*>/i', "\n", $stringtoclean);
5299 5565
 
5300 5566
         if ($strip_tags) {
@@ -5311,8 +5577,9 @@  discard block
 block discarded – undo
5311 5577
         $temp = dol_html_entity_decode($temp, ENT_COMPAT, $pagecodeto);
5312 5578
 
5313 5579
 // Supprime aussi les retours
5314
-        if ($removelinefeed == 1)
5315
-            $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
5580
+        if ($removelinefeed == 1) {
5581
+                    $temp = str_replace(array("\r\n", "\r", "\n"), " ", $temp);
5582
+        }
5316 5583
 
5317 5584
 // et les espaces doubles
5318 5585
         while (strpos($temp, "  ")) {
@@ -5398,18 +5665,21 @@  discard block
 block discarded – undo
5398 5665
             if ($charset == 'UTF-8') {
5399 5666
                 $pattern = '/(<br[^>]*>)/Uu';
5400 5667
             } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5401
-            else
5402
-                $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5668
+            else {
5669
+                            $pattern = '/(<br[^>]*>)/U';
5670
+            }
5671
+            // /U is to have UNGREEDY regex to limit to one html tag.
5403 5672
             $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5404 5673
 
5405 5674
             $firstline = '';
5406 5675
             $i = 0;
5407 5676
             $nba = count($a); // 2x nb of lines in $a because $a contains also a line for each new line separator
5408 5677
             while (($i < $nba) && ($i < ($nboflines * 2))) {
5409
-                if ($i % 2 == 0)
5410
-                    $firstline .= $a[$i];
5411
-                elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1)))
5412
-                    $firstline .= ($ishtml ? "<br>\n" : "\n");
5678
+                if ($i % 2 == 0) {
5679
+                                    $firstline .= $a[$i];
5680
+                } elseif (($i < (($nboflines * 2) - 1)) && ($i < ($nba - 1))) {
5681
+                                    $firstline .= ($ishtml ? "<br>\n" : "\n");
5682
+                }
5413 5683
                 $i++;
5414 5684
             }
5415 5685
             unset($a);
@@ -5458,15 +5728,18 @@  discard block
 block discarded – undo
5458 5728
         $newstring = $stringtoencode;
5459 5729
         if (dol_textishtml($stringtoencode)) { // Check if text is already HTML or not
5460 5730
             $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.
5461
-            if ($removelasteolbr)
5462
-                $newstring = preg_replace('/<br>$/i', '', $newstring); // Remove last <br> (remove only last one)
5731
+            if ($removelasteolbr) {
5732
+                            $newstring = preg_replace('/<br>$/i', '', $newstring);
5733
+            }
5734
+            // Remove last <br> (remove only last one)
5463 5735
             $newstring = strtr($newstring, array('&' => '__and__', '<' => '__lt__', '>' => '__gt__', '"' => '__dquot__'));
5464 5736
             $newstring = dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom); // Make entity encoding
5465 5737
             $newstring = strtr($newstring, array('__and__' => '&', '__lt__' => '<', '__gt__' => '>', '__dquot__' => '"'));
5466
-        }
5467
-        else {
5468
-            if ($removelasteolbr)
5469
-                $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring); // Remove last \n (may remove several)
5738
+        } else {
5739
+            if ($removelasteolbr) {
5740
+                            $newstring = preg_replace('/(\r\n|\r|\n)$/i', '', $newstring);
5741
+            }
5742
+            // Remove last \n (may remove several)
5470 5743
             $newstring = dol_nl2br(dol_htmlentities($newstring, ENT_COMPAT, $pagecodefrom), $nl2brmode);
5471 5744
         }
5472 5745
 // Other substitutions that htmlentities does not do
@@ -5568,8 +5841,9 @@  discard block
 block discarded – undo
5568 5841
      */
5569 5842
     static function dol_nboflines($s, $maxchar = 0)
5570 5843
     {
5571
-        if ($s == '')
5572
-            return 0;
5844
+        if ($s == '') {
5845
+                    return 0;
5846
+        }
5573 5847
         $arraystring = explode("\n", $s);
5574 5848
         $nb = count($arraystring);
5575 5849
 
@@ -5588,15 +5862,18 @@  discard block
 block discarded – undo
5588 5862
     static function dol_nboflines_bis($text, $maxlinesize = 0, $charset = 'UTF-8')
5589 5863
     {
5590 5864
         $repTable = array("\t" => " ", "\n" => "<br>", "\r" => " ", "\0" => " ", "\x0B" => " ");
5591
-        if (dol_textishtml($text))
5592
-            $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
5865
+        if (dol_textishtml($text)) {
5866
+                    $repTable = array("\t" => " ", "\n" => " ", "\r" => " ", "\0" => " ", "\x0B" => " ");
5867
+        }
5593 5868
 
5594 5869
         $text = strtr($text, $repTable);
5595 5870
         if ($charset == 'UTF-8') {
5596 5871
             $pattern = '/(<br[^>]*>)/Uu';
5597 5872
         } // /U is to have UNGREEDY regex to limit to one html tag. /u is for UTF8 support
5598
-        else
5599
-            $pattern = '/(<br[^>]*>)/U';       // /U is to have UNGREEDY regex to limit to one html tag.
5873
+        else {
5874
+                    $pattern = '/(<br[^>]*>)/U';
5875
+        }
5876
+        // /U is to have UNGREEDY regex to limit to one html tag.
5600 5877
         $a = preg_split($pattern, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
5601 5878
 
5602 5879
         $nblines = (int) floor((count($a) + 1) / 2);
@@ -5643,39 +5920,47 @@  discard block
 block discarded – undo
5643 5920
     static function dol_textishtml($msg, $option = 0)
5644 5921
     {
5645 5922
         if ($option == 1) {
5646
-            if (preg_match('/<html/i', $msg))
5647
-                return true;
5648
-            elseif (preg_match('/<body/i', $msg))
5649
-                return true;
5650
-            elseif (preg_match('/<br/i', $msg))
5651
-                return true;
5923
+            if (preg_match('/<html/i', $msg)) {
5924
+                            return true;
5925
+            } elseif (preg_match('/<body/i', $msg)) {
5926
+                            return true;
5927
+            } elseif (preg_match('/<br/i', $msg)) {
5928
+                            return true;
5929
+            }
5652 5930
             return false;
5653
-        }
5654
-        else {
5655
-            if (preg_match('/<html/i', $msg))
5656
-                return true;
5657
-            elseif (preg_match('/<body/i', $msg))
5658
-                return true;
5659
-            elseif (preg_match('/<(b|em|i|u)>/i', $msg))
5660
-                return true;
5661
-            elseif (preg_match('/<br\/>/i', $msg))
5662
-                return true;
5663
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg))
5664
-                return true;
5665
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg))
5666
-                return true;
5667
-            elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg))
5668
-                return true;
5669
-            elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg))
5670
-                return true; // must accept <img src="http://example.com/aaa.png" />
5671
-            elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg))
5672
-                return true; // must accept <a href="http://example.com/aaa.png" />
5673
-            elseif (preg_match('/<h[0-9]>/i', $msg))
5674
-                return true;
5675
-            elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg))
5676
-                return true;    // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5677
-            elseif (preg_match('/&#[0-9]{2,3};/i', $msg))
5678
-                return true;    // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5931
+        } else {
5932
+            if (preg_match('/<html/i', $msg)) {
5933
+                            return true;
5934
+            } elseif (preg_match('/<body/i', $msg)) {
5935
+                            return true;
5936
+            } elseif (preg_match('/<(b|em|i|u)>/i', $msg)) {
5937
+                            return true;
5938
+            } elseif (preg_match('/<br\/>/i', $msg)) {
5939
+                            return true;
5940
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)>/i', $msg)) {
5941
+                            return true;
5942
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*>/i', $msg)) {
5943
+                            return true;
5944
+            } elseif (preg_match('/<(br|div|font|li|p|span|strong|table)\s+[^<>\/]*\/>/i', $msg)) {
5945
+                            return true;
5946
+            } elseif (preg_match('/<img\s+[^<>]*src[^<>]*>/i', $msg)) {
5947
+                            return true;
5948
+            }
5949
+            // must accept <img src="http://example.com/aaa.png" />
5950
+            elseif (preg_match('/<a\s+[^<>]*href[^<>]*>/i', $msg)) {
5951
+                            return true;
5952
+            }
5953
+            // must accept <a href="http://example.com/aaa.png" />
5954
+            elseif (preg_match('/<h[0-9]>/i', $msg)) {
5955
+                            return true;
5956
+            } elseif (preg_match('/&[A-Z0-9]{1,6};/i', $msg)) {
5957
+                            return true;
5958
+            }
5959
+            // Html entities names (http://www.w3schools.com/tags/ref_entities.asp)
5960
+            elseif (preg_match('/&#[0-9]{2,3};/i', $msg)) {
5961
+                            return true;
5962
+            }
5963
+            // Html entities numbers (http://www.w3schools.com/tags/ref_entities.asp)
5679 5964
 
5680 5965
             return false;
5681 5966
         }
@@ -5827,12 +6112,14 @@  discard block
 block discarded – undo
5827 6112
                 $birthday = dol_print_date($object->birth, 'day');
5828 6113
 
5829 6114
                 $substitutionarray['__MEMBER_ID__'] = $object->id;
5830
-                if (method_exists($object, 'getCivilityLabel'))
5831
-                    $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
6115
+                if (method_exists($object, 'getCivilityLabel')) {
6116
+                                    $substitutionarray['__MEMBER_CIVILITY__'] = $object->getCivilityLabel();
6117
+                }
5832 6118
                 $substitutionarray['__MEMBER_FIRSTNAME__'] = $msgishtml ? dol_htmlentitiesbr($object->firstname) : $object->firstname;
5833 6119
                 $substitutionarray['__MEMBER_LASTNAME__'] = $msgishtml ? dol_htmlentitiesbr($object->lastname) : $object->lastname;
5834
-                if (method_exists($object, 'getFullName'))
5835
-                    $substitutionarray['__MEMBER_FULLNAME__'] = $msgishtml ? dol_htmlentitiesbr($object->getFullName($outputlangs)) : $object->getFullName($outputlangs);
6120
+                if (method_exists($object, 'getFullName')) {
6121
+                                    $substitutionarray['__MEMBER_FULLNAME__'] = $msgishtml ? dol_htmlentitiesbr($object->getFullName($outputlangs)) : $object->getFullName($outputlangs);
6122
+                }
5836 6123
                 $substitutionarray['__MEMBER_COMPANY__'] = $msgishtml ? dol_htmlentitiesbr($object->societe) : $object->societe;
5837 6124
                 $substitutionarray['__MEMBER_ADDRESS__'] = $msgishtml ? dol_htmlentitiesbr($object->address) : $object->address;
5838 6125
                 $substitutionarray['__MEMBER_ZIP__'] = $msgishtml ? dol_htmlentitiesbr($object->zip) : $object->zip;
@@ -5880,10 +6167,12 @@  discard block
 block discarded – undo
5880 6167
                     $dateplannedstart = '';
5881 6168
                     $datenextexpiration = '';
5882 6169
                     foreach ($object->lines as $line) {
5883
-                        if ($line->date_ouverture_prevue > $dateplannedstart)
5884
-                            $dateplannedstart = $line->date_ouverture_prevue;
5885
-                        if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration))
5886
-                            $datenextexpiration = $line->date_fin_prevue;
6170
+                        if ($line->date_ouverture_prevue > $dateplannedstart) {
6171
+                                                    $dateplannedstart = $line->date_ouverture_prevue;
6172
+                        }
6173
+                        if ($line->statut == 4 && $line->date_fin_prevue && (!$datenextexpiration || $line->date_fin_prevue < $datenextexpiration)) {
6174
+                                                    $datenextexpiration = $line->date_fin_prevue;
6175
+                        }
5887 6176
                     }
5888 6177
                     $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATE__'] = dol_print_date($dateplannedstart, 'dayrfc');
5889 6178
                     $substitutionarray['__CONTRACT_HIGHEST_PLANNED_START_DATETIME__'] = dol_print_date($dateplannedstart, 'standard');
@@ -5893,8 +6182,9 @@  discard block
 block discarded – undo
5893 6182
 
5894 6183
 // Create dynamic tags for __EXTRAFIELD_FIELD__
5895 6184
                 if ($object->table_element && $object->id > 0) {
5896
-                    if (!is_object($extrafields))
5897
-                        $extrafields = new ExtraFields($db);
6185
+                    if (!is_object($extrafields)) {
6186
+                                            $extrafields = new ExtraFields($db);
6187
+                    }
5898 6188
                     $extrafields->fetch_name_optionals_label($object->table_element, true);
5899 6189
 
5900 6190
                     if ($object->fetch_optionals() > 0) {
@@ -5915,12 +6205,15 @@  discard block
 block discarded – undo
5915 6205
                     require_once DOL_BASE_PATH . '/core/lib/payments.lib.php';
5916 6206
                     $outputlangs->loadLangs(array('paypal', 'other'));
5917 6207
                     $typeforonlinepayment = 'free';
5918
-                    if (is_object($object) && $object->element == 'commande')
5919
-                        $typeforonlinepayment = 'order';
5920
-                    if (is_object($object) && $object->element == 'facture')
5921
-                        $typeforonlinepayment = 'invoice';
5922
-                    if (is_object($object) && $object->element == 'member')
5923
-                        $typeforonlinepayment = 'member';
6208
+                    if (is_object($object) && $object->element == 'commande') {
6209
+                                            $typeforonlinepayment = 'order';
6210
+                    }
6211
+                    if (is_object($object) && $object->element == 'facture') {
6212
+                                            $typeforonlinepayment = 'invoice';
6213
+                    }
6214
+                    if (is_object($object) && $object->element == 'member') {
6215
+                                            $typeforonlinepayment = 'member';
6216
+                    }
5924 6217
                     $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $substitutionarray['__REF__']);
5925 6218
                     $paymenturl = $url;
5926 6219
                 }
@@ -5930,16 +6223,19 @@  discard block
 block discarded – undo
5930 6223
 
5931 6224
                 if (!empty(Globals::$conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'propal') {
5932 6225
                     $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = $object->getLastMainDocLink($object->element);
5933
-                } else
5934
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
6226
+                } else {
6227
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_PROPOSAL__'] = '';
6228
+                }
5935 6229
                 if (!empty(Globals::$conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'commande') {
5936 6230
                     $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = $object->getLastMainDocLink($object->element);
5937
-                } else
5938
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
6231
+                } else {
6232
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_ORDER__'] = '';
6233
+                }
5939 6234
                 if (!empty(Globals::$conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD) && is_object($object) && $object->element == 'facture') {
5940 6235
                     $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = $object->getLastMainDocLink($object->element);
5941
-                } else
5942
-                    $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
6236
+                } else {
6237
+                                    $substitutionarray['__DIRECTDOWNLOAD_URL_INVOICE__'] = '';
6238
+                }
5943 6239
             }
5944 6240
         }
5945 6241
         if (empty($exclude) || !in_array('objectamount', $exclude)) {
@@ -5949,18 +6245,22 @@  discard block
 block discarded – undo
5949 6245
             $substitutionarray['__AMOUNT__'] = is_object($object) ? $object->total_ttc : '';
5950 6246
             $substitutionarray['__AMOUNT_EXCL_TAX__'] = is_object($object) ? $object->total_ht : '';
5951 6247
             $substitutionarray['__AMOUNT_VAT__'] = is_object($object) ? ($object->total_vat ? $object->total_vat : $object->total_tva) : '';
5952
-            if ($onlykey != 2 || $mysoc->useLocalTax(1))
5953
-                $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
5954
-            if ($onlykey != 2 || $mysoc->useLocalTax(2))
5955
-                $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
6248
+            if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
6249
+                            $substitutionarray['__AMOUNT_TAX2__'] = is_object($object) ? $object->total_localtax1 : '';
6250
+            }
6251
+            if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
6252
+                            $substitutionarray['__AMOUNT_TAX3__'] = is_object($object) ? $object->total_localtax2 : '';
6253
+            }
5956 6254
 
5957 6255
             $substitutionarray['__AMOUNT_FORMATED__'] = is_object($object) ? price($object->total_ttc, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
5958 6256
             $substitutionarray['__AMOUNT_EXCL_TAX_FORMATED__'] = is_object($object) ? price($object->total_ht, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
5959 6257
             $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)) : '';
5960
-            if ($onlykey != 2 || $mysoc->useLocalTax(1))
5961
-                $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
5962
-            if ($onlykey != 2 || $mysoc->useLocalTax(2))
5963
-                $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6258
+            if ($onlykey != 2 || $mysoc->useLocalTax(1)) {
6259
+                            $substitutionarray['__AMOUNT_TAX2_FORMATED__'] = is_object($object) ? price($object->total_localtax1, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6260
+            }
6261
+            if ($onlykey != 2 || $mysoc->useLocalTax(2)) {
6262
+                            $substitutionarray['__AMOUNT_TAX3_FORMATED__'] = is_object($object) ? price($object->total_localtax2, 0, $outputlangs, 0, 0, -1, Globals::$conf->currency) : '';
6263
+            }
5964 6264
 
5965 6265
 // TODO Add keys for foreign multicurrency
5966 6266
 // For backward compatibility
@@ -6030,23 +6330,27 @@  discard block
 block discarded – undo
6030 6330
     {
6031 6331
        // global Globals::$conf, Globals::$langs;
6032 6332
 
6033
-        if (!is_array($substitutionarray))
6034
-            return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
6333
+        if (!is_array($substitutionarray)) {
6334
+                    return 'ErrorBadParameterSubstitutionArrayWhenCalling_make_substitutions';
6335
+        }
6035 6336
 
6036
-        if (empty($outputlangs))
6037
-            $outputlangs = Globals::$langs;
6337
+        if (empty($outputlangs)) {
6338
+                    $outputlangs = Globals::$langs;
6339
+        }
6038 6340
 
6039 6341
 // Make substitution for language keys
6040 6342
         if (is_object($outputlangs)) {
6041 6343
             while (preg_match('/__\(([^\)]+)\)__/', $text, $reg)) {
6042 6344
                 $msgishtml = 0;
6043
-                if (DolUtils::dol_textishtml($text, 1))
6044
-                    $msgishtml = 1;
6345
+                if (DolUtils::dol_textishtml($text, 1)) {
6346
+                                    $msgishtml = 1;
6347
+                }
6045 6348
 
6046 6349
 // If key is __(TranslationKey|langfile)__, then force load of langfile.lang
6047 6350
                 $tmp = explode('|', $reg[1]);
6048
-                if (!empty($tmp[1]))
6049
-                    $outputlangs->load($tmp[1]);
6351
+                if (!empty($tmp[1])) {
6352
+                                    $outputlangs->load($tmp[1]);
6353
+                }
6050 6354
 
6051 6355
                 $text = preg_replace('/__\(' . preg_quote($reg[1], '/') . '\)__/', $msgishtml ? dol_htmlentitiesbr($outputlangs->transnoentitiesnoconv($reg[1])) : $outputlangs->transnoentitiesnoconv($reg[1]), $text);
6052 6356
             }
@@ -6056,23 +6360,29 @@  discard block
 block discarded – undo
6056 6360
 // it is also converted.
6057 6361
         while (preg_match('/__\[([^\]]+)\]__/', $text, $reg)) {
6058 6362
             $msgishtml = 0;
6059
-            if (DolUtils::dol_textishtml($text, 1))
6060
-                $msgishtml = 1;
6363
+            if (DolUtils::dol_textishtml($text, 1)) {
6364
+                            $msgishtml = 1;
6365
+            }
6061 6366
 
6062 6367
             $keyfound = $reg[1];
6063
-            if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound))
6064
-                $newval = '*****forbidden*****';
6065
-            else
6066
-                $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6368
+            if (preg_match('/(_pass|password|secret|_key|key$)/i', $keyfound)) {
6369
+                            $newval = '*****forbidden*****';
6370
+            } else {
6371
+                            $newval = empty(Globals::$conf->global->$keyfound) ? '' : Globals::$conf->global->$keyfound;
6372
+            }
6067 6373
             $text = preg_replace('/__\[' . preg_quote($keyfound, '/') . '\]__/', $msgishtml ? dol_htmlentitiesbr($newval) : $newval, $text);
6068 6374
         }
6069 6375
 
6070 6376
 // Make substitition for array $substitutionarray
6071 6377
         foreach ($substitutionarray as $key => $value) {
6072
-            if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6073
-                $value = '';  // Protection
6074
-            if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN)))
6075
-                $value = ''; // Protection
6378
+            if ($key == '__SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
6379
+                            $value = '';
6380
+            }
6381
+            // Protection
6382
+            if ($key == '__USER_SIGNATURE__' && (!empty(Globals::$conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))) {
6383
+                            $value = '';
6384
+            }
6385
+            // Protection
6076 6386
 
6077 6387
             $text = str_replace("$key", "$value", $text); // We must keep the " to work when value is 123.5 for example
6078 6388
         }
@@ -6118,8 +6428,9 @@  discard block
 block discarded – undo
6118 6428
             $dir = dol_buildpath($reldir, 0);
6119 6429
 
6120 6430
 // Check if directory exists
6121
-            if (!dol_is_dir($dir))
6122
-                continue;
6431
+            if (!dol_is_dir($dir)) {
6432
+                            continue;
6433
+            }
6123 6434
 
6124 6435
             $substitfiles = dol_dir_list($dir, 'files', 0, 'functions_');
6125 6436
             foreach ($substitfiles as $substitfile) {
@@ -6131,8 +6442,9 @@  discard block
 block discarded – undo
6131 6442
                     require_once $dir . $substitfile['name'];
6132 6443
                     // Call the user's function, and only if it is defined
6133 6444
                     $function_name = $module . "_" . $callfunc;
6134
-                    if (function_exists($function_name))
6135
-                        $function_name($substitutionarray, $outputlangs, $object, $parameters);
6445
+                    if (function_exists($function_name)) {
6446
+                                            $function_name($substitutionarray, $outputlangs, $object, $parameters);
6447
+                    }
6136 6448
                 }
6137 6449
             }
6138 6450
         }
@@ -6168,8 +6480,9 @@  discard block
 block discarded – undo
6168 6480
 
6169 6481
         $out = '';
6170 6482
 
6171
-        if (!is_object($outputlangs))
6172
-            $outputlangs = Globals::$langs;
6483
+        if (!is_object($outputlangs)) {
6484
+                    $outputlangs = Globals::$langs;
6485
+        }
6173 6486
 
6174 6487
         if ($date_start && $date_end) {
6175 6488
             $out .= ($withparenthesis ? ' (' : '') . $outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($date_start, $format, false, $outputlangs), dol_print_date($date_end, $format, false, $outputlangs)) . ($withparenthesis ? ')' : '');
@@ -6198,20 +6511,22 @@  discard block
 block discarded – undo
6198 6511
 
6199 6512
         $ret = '';
6200 6513
 // If order not defined, we use the setup
6201
-        if ($nameorder < 0)
6202
-            $nameorder = (empty(Globals::$conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
6514
+        if ($nameorder < 0) {
6515
+                    $nameorder = (empty(Globals::$conf->global->MAIN_FIRSTNAME_NAME_POSITION) ? 1 : 0);
6516
+        }
6203 6517
         if ($nameorder && ((string) $nameorder != '2')) {
6204 6518
             $ret .= $firstname;
6205
-            if ($firstname && $lastname)
6206
-                $ret .= ' ';
6519
+            if ($firstname && $lastname) {
6520
+                            $ret .= ' ';
6521
+            }
6207 6522
             $ret .= $lastname;
6208
-        }
6209
-        else if ($nameorder == 2) {
6523
+        } else if ($nameorder == 2) {
6210 6524
             $ret .= $firstname;
6211 6525
         } else {
6212 6526
             $ret .= $lastname;
6213
-            if ($firstname && $lastname)
6214
-                $ret .= ' ';
6527
+            if ($firstname && $lastname) {
6528
+                            $ret .= ' ';
6529
+            }
6215 6530
             $ret .= $firstname;
6216 6531
         }
6217 6532
         return $ret;
@@ -6231,13 +6546,14 @@  discard block
 block discarded – undo
6231 6546
     {
6232 6547
 //dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);		This is not deprecated, it is used by setEventMessages function
6233 6548
         if (!is_array($mesgs)) {  // If mesgs is a string
6234
-            if ($mesgs)
6235
-                $_SESSION['dol_events'][$style][] = $mesgs;
6236
-        }
6237
-        else {      // If mesgs is an array
6549
+            if ($mesgs) {
6550
+                            $_SESSION['dol_events'][$style][] = $mesgs;
6551
+            }
6552
+        } else {      // If mesgs is an array
6238 6553
             foreach ($mesgs as $mesg) {
6239
-                if ($mesg)
6240
-                    $_SESSION['dol_events'][$style][] = $mesg;
6554
+                if ($mesg) {
6555
+                                    $_SESSION['dol_events'][$style][] = $mesg;
6556
+                }
6241 6557
             }
6242 6558
         }
6243 6559
     }
@@ -6257,13 +6573,16 @@  discard block
 block discarded – undo
6257 6573
         if (empty($mesg) && empty($mesgs)) {
6258 6574
             dol_syslog("Try to add a message in stack with empty message", LOG_WARNING);
6259 6575
         } else {
6260
-            if (!in_array((string) $style, array('mesgs', 'warnings', 'errors')))
6261
-                dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6262
-            if (empty($mesgs))
6263
-                setEventMessage($mesg, $style);
6264
-            else {
6265
-                if (!empty($mesg) && !in_array($mesg, $mesgs))
6266
-                    setEventMessage($mesg, $style); // Add message string if not already into array
6576
+            if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
6577
+                            dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
6578
+            }
6579
+            if (empty($mesgs)) {
6580
+                            setEventMessage($mesg, $style);
6581
+            } else {
6582
+                if (!empty($mesg) && !in_array($mesg, $mesgs)) {
6583
+                                    setEventMessage($mesg, $style);
6584
+                }
6585
+                // Add message string if not already into array
6267 6586
                 setEventMessage($mesgs, $style);
6268 6587
             }
6269 6588
         }
@@ -6282,22 +6601,25 @@  discard block
 block discarded – undo
6282 6601
     {
6283 6602
 // Show mesgs
6284 6603
         if (isset($_SESSION['dol_events']['mesgs'])) {
6285
-            if (empty($disabledoutputofmessages))
6286
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
6604
+            if (empty($disabledoutputofmessages)) {
6605
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['mesgs']);
6606
+            }
6287 6607
             unset($_SESSION['dol_events']['mesgs']);
6288 6608
         }
6289 6609
 
6290 6610
 // Show errors
6291 6611
         if (isset($_SESSION['dol_events']['errors'])) {
6292
-            if (empty($disabledoutputofmessages))
6293
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
6612
+            if (empty($disabledoutputofmessages)) {
6613
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['errors'], 'error');
6614
+            }
6294 6615
             unset($_SESSION['dol_events']['errors']);
6295 6616
         }
6296 6617
 
6297 6618
 // Show warnings
6298 6619
         if (isset($_SESSION['dol_events']['warnings'])) {
6299
-            if (empty($disabledoutputofmessages))
6300
-                dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
6620
+            if (empty($disabledoutputofmessages)) {
6621
+                            dol_htmloutput_mesg('', $_SESSION['dol_events']['warnings'], 'warning');
6622
+            }
6301 6623
             unset($_SESSION['dol_events']['warnings']);
6302 6624
         }
6303 6625
     }
@@ -6338,8 +6660,9 @@  discard block
 block discarded – undo
6338 6660
                 foreach ($mesgarray as $message) {
6339 6661
                     $ret++;
6340 6662
                     $out .= Globals::$langs->trans($message);
6341
-                    if ($ret < count($mesgarray))
6342
-                        $out .= "<br>\n";
6663
+                    if ($ret < count($mesgarray)) {
6664
+                                            $out .= "<br>\n";
6665
+                    }
6343 6666
                 }
6344 6667
             }
6345 6668
             if ($mesgstring) {
@@ -6405,8 +6728,9 @@  discard block
 block discarded – undo
6405 6728
      */
6406 6729
     static function dol_htmloutput_mesg($mesgstring = '', $mesgarray = array(), $style = 'ok', $keepembedded = 0)
6407 6730
     {
6408
-        if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0))
6409
-            return;
6731
+        if (empty($mesgstring) && (!is_array($mesgarray) || count($mesgarray) == 0)) {
6732
+                    return;
6733
+        }
6410 6734
 
6411 6735
         $iserror = 0;
6412 6736
         $iswarning = 0;
@@ -6421,14 +6745,17 @@  discard block
 block discarded – undo
6421 6745
                     break;
6422 6746
                 }
6423 6747
             }
6424
-        } else if ($mesgstring && preg_match('/class="error"/i', $mesgstring))
6425
-            $iserror++;
6426
-        else if ($mesgstring && preg_match('/class="warning"/i', $mesgstring))
6427
-            $iswarning++;
6428
-        if ($style == 'error')
6429
-            $iserror++;
6430
-        if ($style == 'warning')
6431
-            $iswarning++;
6748
+        } else if ($mesgstring && preg_match('/class="error"/i', $mesgstring)) {
6749
+                    $iserror++;
6750
+        } else if ($mesgstring && preg_match('/class="warning"/i', $mesgstring)) {
6751
+                    $iswarning++;
6752
+        }
6753
+        if ($style == 'error') {
6754
+                    $iserror++;
6755
+        }
6756
+        if ($style == 'warning') {
6757
+                    $iswarning++;
6758
+        }
6432 6759
 
6433 6760
         if ($iserror || $iswarning) {
6434 6761
 // Remove div from texts
@@ -6447,8 +6774,9 @@  discard block
 block discarded – undo
6447 6774
                 $mesgarray = $newmesgarray;
6448 6775
             }
6449 6776
             print get_htmloutput_mesg($mesgstring, $mesgarray, ($iserror ? 'error' : 'warning'), $keepembedded);
6450
-        } else
6451
-            print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
6777
+        } else {
6778
+                    print get_htmloutput_mesg($mesgstring, $mesgarray, 'ok', $keepembedded);
6779
+        }
6452 6780
     }
6453 6781
 
6454 6782
     /**
@@ -6489,15 +6817,17 @@  discard block
 block discarded – undo
6489 6817
             $sizearray = count($array);
6490 6818
             if ($sizearray > 0) {
6491 6819
                 $temp = array();
6492
-                foreach (array_keys($array) as $key)
6493
-                    $temp[$key] = $array[$key][$index];
6820
+                foreach (array_keys($array) as $key) {
6821
+                                    $temp[$key] = $array[$key][$index];
6822
+                }
6494 6823
 
6495
-                if (!$natsort)
6496
-                    ($order == 'asc') ? asort($temp) : arsort($temp);
6497
-                else {
6824
+                if (!$natsort) {
6825
+                                    ($order == 'asc') ? asort($temp) : arsort($temp);
6826
+                } else {
6498 6827
                     ($case_sensitive) ? natsort($temp) : natcasesort($temp);
6499
-                    if ($order != 'asc')
6500
-                        $temp = array_reverse($temp, true);
6828
+                    if ($order != 'asc') {
6829
+                                            $temp = array_reverse($temp, true);
6830
+                    }
6501 6831
                 }
6502 6832
 
6503 6833
                 $sorted = array();
@@ -6523,23 +6853,38 @@  discard block
 block discarded – undo
6523 6853
 // We must use here a binary strlen static function (so not dol_strlen)
6524 6854
         $strLength = dol_strlen($str);
6525 6855
         for ($i = 0; $i < $strLength; $i++) {
6526
-            if (ord($str[$i]) < 0x80)
6527
-                continue; // 0bbbbbbb
6528
-            elseif ((ord($str[$i]) & 0xE0) == 0xC0)
6529
-                $n = 1; // 110bbbbb
6530
-            elseif ((ord($str[$i]) & 0xF0) == 0xE0)
6531
-                $n = 2; // 1110bbbb
6532
-            elseif ((ord($str[$i]) & 0xF8) == 0xF0)
6533
-                $n = 3; // 11110bbb
6534
-            elseif ((ord($str[$i]) & 0xFC) == 0xF8)
6535
-                $n = 4; // 111110bb
6536
-            elseif ((ord($str[$i]) & 0xFE) == 0xFC)
6537
-                $n = 5; // 1111110b
6538
-            else
6539
-                return false; // Does not match any model
6856
+            if (ord($str[$i]) < 0x80) {
6857
+                            continue;
6858
+            }
6859
+            // 0bbbbbbb
6860
+            elseif ((ord($str[$i]) & 0xE0) == 0xC0) {
6861
+                            $n = 1;
6862
+            }
6863
+            // 110bbbbb
6864
+            elseif ((ord($str[$i]) & 0xF0) == 0xE0) {
6865
+                            $n = 2;
6866
+            }
6867
+            // 1110bbbb
6868
+            elseif ((ord($str[$i]) & 0xF8) == 0xF0) {
6869
+                            $n = 3;
6870
+            }
6871
+            // 11110bbb
6872
+            elseif ((ord($str[$i]) & 0xFC) == 0xF8) {
6873
+                            $n = 4;
6874
+            }
6875
+            // 111110bb
6876
+            elseif ((ord($str[$i]) & 0xFE) == 0xFC) {
6877
+                            $n = 5;
6878
+            }
6879
+            // 1111110b
6880
+            else {
6881
+                            return false;
6882
+            }
6883
+            // Does not match any model
6540 6884
             for ($j = 0; $j < $n; $j++) { // n bytes matching 10bbbbbb follow ?
6541
-                if (( ++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80))
6542
-                    return false;
6885
+                if (( ++$i == strlen($str)) || ((ord($str[$i]) & 0xC0) != 0x80)) {
6886
+                                    return false;
6887
+                }
6543 6888
             }
6544 6889
         }
6545 6890
         return true;
@@ -6557,15 +6902,21 @@  discard block
 block discarded – undo
6557 6902
        // global Globals::$conf;
6558 6903
 
6559 6904
         $tmp = ini_get("unicode.filesystem_encoding");      // Disponible avec PHP 6.0
6560
-        if (empty($tmp) && !empty($_SERVER["WINDIR"]))
6561
-            $tmp = 'iso-8859-1'; // By default for windows
6562
-        if (empty($tmp))
6563
-            $tmp = 'utf-8';          // By default for other
6564
-        if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING))
6565
-            $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6566
-
6567
-        if ($tmp == 'iso-8859-1')
6568
-            return utf8_decode($str);
6905
+        if (empty($tmp) && !empty($_SERVER["WINDIR"])) {
6906
+                    $tmp = 'iso-8859-1';
6907
+        }
6908
+        // By default for windows
6909
+        if (empty($tmp)) {
6910
+                    $tmp = 'utf-8';
6911
+        }
6912
+        // By default for other
6913
+        if (!empty(Globals::$conf->global->MAIN_FILESYSTEM_ENCODING)) {
6914
+                    $tmp = Globals::$conf->global->MAIN_FILESYSTEM_ENCODING;
6915
+        }
6916
+
6917
+        if ($tmp == 'iso-8859-1') {
6918
+                    return utf8_decode($str);
6919
+        }
6569 6920
         return $str;
6570 6921
     }
6571 6922
 
@@ -6586,8 +6937,9 @@  discard block
 block discarded – undo
6586 6937
     {
6587 6938
        // global $cache_codes;
6588 6939
 // If key empty
6589
-        if ($key == '')
6590
-            return '';
6940
+        if ($key == '') {
6941
+                    return '';
6942
+        }
6591 6943
 
6592 6944
 // Check in cache
6593 6945
         if (isset($cache_codes[$tablename][$key][$fieldid])) { // Can be defined to 0 or ''
@@ -6599,20 +6951,21 @@  discard block
 block discarded – undo
6599 6951
         $sql = "SELECT " . $fieldid . " as valuetoget";
6600 6952
         $sql .= " FROM " . MAIN_DB_PREFIX . $tablename;
6601 6953
         $sql .= " WHERE " . $fieldkey . " = '" . $db->escape($key) . "'";
6602
-        if (!empty($entityfilter))
6603
-            $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6954
+        if (!empty($entityfilter)) {
6955
+                    $sql .= " AND entity IN (" . getEntity($tablename) . ")";
6956
+        }
6604 6957
 
6605 6958
         $resql = $db->query($sql);
6606 6959
         if ($resql) {
6607 6960
             $obj = $db->fetch_object($resql);
6608
-            if ($obj)
6609
-                $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
6610
-            else
6611
-                $cache_codes[$tablename][$key][$fieldid] = '';
6961
+            if ($obj) {
6962
+                            $cache_codes[$tablename][$key][$fieldid] = $obj->valuetoget;
6963
+            } else {
6964
+                            $cache_codes[$tablename][$key][$fieldid] = '';
6965
+            }
6612 6966
             $db->free($resql);
6613 6967
             return $cache_codes[$tablename][$key][$fieldid];
6614
-        }
6615
-        else {
6968
+        } else {
6616 6969
             return -1;
6617 6970
         }
6618 6971
     }
@@ -6658,16 +7011,17 @@  discard block
 block discarded – undo
6658 7011
         // global $soc;       // For backward compatibility
6659 7012
 //print $s."<br>\n";
6660 7013
         if ($returnvalue) {
6661
-            if ($hideerrors)
6662
-                return @eval('return ' . $s . ';');
6663
-            else
6664
-                return eval('return ' . $s . ';');
6665
-        }
6666
-        else {
6667
-            if ($hideerrors)
6668
-                @eval($s);
6669
-            else
6670
-                eval($s);
7014
+            if ($hideerrors) {
7015
+                            return @eval('return ' . $s . ';');
7016
+            } else {
7017
+                            return eval('return ' . $s . ';');
7018
+            }
7019
+        } else {
7020
+            if ($hideerrors) {
7021
+                            @eval($s);
7022
+            } else {
7023
+                            eval($s);
7024
+            }
6671 7025
         }
6672 7026
     }
6673 7027
 
@@ -6693,8 +7047,9 @@  discard block
 block discarded – undo
6693 7047
     {
6694 7048
        // global Globals::$langs;
6695 7049
 
6696
-        if (empty($codelang))
6697
-            return '';
7050
+        if (empty($codelang)) {
7051
+                    return '';
7052
+        }
6698 7053
 
6699 7054
         if ($codelang == 'auto') {
6700 7055
             return '<span class="fa fa-globe"></span>';
@@ -6708,9 +7063,9 @@  discard block
 block discarded – undo
6708 7063
             'sv_SV' => 'se'
6709 7064
         );
6710 7065
 
6711
-        if (isset($langtocountryflag[$codelang]))
6712
-            $flagImage = $langtocountryflag[$codelang];
6713
-        else {
7066
+        if (isset($langtocountryflag[$codelang])) {
7067
+                    $flagImage = $langtocountryflag[$codelang];
7068
+        } else {
6714 7069
             $tmparray = explode('_', $codelang);
6715 7070
             $flagImage = empty($tmparray[1]) ? $tmparray[0] : $tmparray[1];
6716 7071
         }
@@ -6728,15 +7083,20 @@  discard block
 block discarded – undo
6728 7083
     {
6729 7084
        // global $mysoc;
6730 7085
 
6731
-        if (strtoupper($countrycode) == 'MQ')
6732
-            return 'fr_CA';
6733
-        if (strtoupper($countrycode) == 'SE')
6734
-            return 'sv_SE'; // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
7086
+        if (strtoupper($countrycode) == 'MQ') {
7087
+                    return 'fr_CA';
7088
+        }
7089
+        if (strtoupper($countrycode) == 'SE') {
7090
+                    return 'sv_SE';
7091
+        }
7092
+        // se_SE is Sami/Sweden, and we want in priority sv_SE for SE country
6735 7093
         if (strtoupper($countrycode) == 'CH') {
6736
-            if ($mysoc->country_code == 'FR')
6737
-                return 'fr_CH';
6738
-            if ($mysoc->country_code == 'DE')
6739
-                return 'de_CH';
7094
+            if ($mysoc->country_code == 'FR') {
7095
+                            return 'fr_CH';
7096
+            }
7097
+            if ($mysoc->country_code == 'DE') {
7098
+                            return 'de_CH';
7099
+            }
6740 7100
         }
6741 7101
 
6742 7102
 // Locale list taken from:
@@ -6914,8 +7274,9 @@  discard block
 block discarded – undo
6914 7274
         );
6915 7275
 
6916 7276
         $buildprimarykeytotest = strtolower($countrycode) . '-' . strtoupper($countrycode);
6917
-        if (in_array($buildprimarykeytotest, $locales))
6918
-            return strtolower($countrycode) . '_' . strtoupper($countrycode);
7277
+        if (in_array($buildprimarykeytotest, $locales)) {
7278
+                    return strtolower($countrycode) . '_' . strtoupper($countrycode);
7279
+        }
6919 7280
 
6920 7281
         foreach ($locales as $locale) {
6921 7282
             $locale_language = locale_get_primary_language($locale);
@@ -6969,18 +7330,21 @@  discard block
 block discarded – undo
6969 7330
 
6970 7331
                 if ($mode == 'add' && !preg_match('/^\-/', $values[1])) {
6971 7332
                     if (count($values) == 6) {       // new declaration with permissions:  $value='objecttype:+tabname1:Title1:langfile@mymodule:$user->rights->mymodule->read:/mymodule/mynewtab1.php?id=__ID__'
6972
-                        if ($values[0] != $type)
6973
-                            continue;
7333
+                        if ($values[0] != $type) {
7334
+                                                    continue;
7335
+                        }
6974 7336
 
6975 7337
                         if (verifCond($values[4])) {
6976
-                            if ($values[3])
6977
-                                Globals::$langs->load($values[3]);
7338
+                            if ($values[3]) {
7339
+                                                            Globals::$langs->load($values[3]);
7340
+                            }
6978 7341
                             if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
6979 7342
                                 $substitutionarray = array();
6980 7343
                                 complete_substitutions_array($substitutionarray, Globals::$langs, $object, array('needforkey' => $values[2]));
6981 7344
                                 $label = make_substitutions($reg[1], $substitutionarray);
6982
-                            } else
6983
-                                $label = Globals::$langs->trans($values[2]);
7345
+                            } else {
7346
+                                                            $label = Globals::$langs->trans($values[2]);
7347
+                            }
6984 7348
 
6985 7349
                             //$head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]), 1);
6986 7350
                             $head[$h][0] = BASE_URI . preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[5]);
@@ -6988,30 +7352,32 @@  discard block
 block discarded – undo
6988 7352
                             $head[$h][2] = str_replace('+', '', $values[1]);
6989 7353
                             $h++;
6990 7354
                         }
6991
-                    }
6992
-                    else if (count($values) == 5) {       // deprecated
7355
+                    } else if (count($values) == 5) {       // deprecated
6993 7356
                         dol_syslog('Passing 5 values in tabs module_parts is deprecated. Please update to 6 with permissions.', LOG_WARNING);
6994 7357
 
6995
-                        if ($values[0] != $type)
6996
-                            continue;
6997
-                        if ($values[3])
6998
-                            Globals::$langs->load($values[3]);
7358
+                        if ($values[0] != $type) {
7359
+                                                    continue;
7360
+                        }
7361
+                        if ($values[3]) {
7362
+                                                    Globals::$langs->load($values[3]);
7363
+                        }
6999 7364
                         if (preg_match('/SUBSTITUTION_([^_]+)/i', $values[2], $reg)) {
7000 7365
                             $substitutionarray = array();
7001 7366
                             complete_substitutions_array($substitutionarray, Globals::$langs, $object, array('needforkey' => $values[2]));
7002 7367
                             $label = make_substitutions($reg[1], $substitutionarray);
7003
-                        } else
7004
-                            $label = Globals::$langs->trans($values[2]);
7368
+                        } else {
7369
+                                                    $label = Globals::$langs->trans($values[2]);
7370
+                        }
7005 7371
 
7006 7372
                         $head[$h][0] = dol_buildpath(preg_replace('/__ID__/i', ((is_object($object) && !empty($object->id)) ? $object->id : ''), $values[4]), 1);
7007 7373
                         $head[$h][1] = $label;
7008 7374
                         $head[$h][2] = str_replace('+', '', $values[1]);
7009 7375
                         $h++;
7010 7376
                     }
7011
-                }
7012
-                else if ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
7013
-                    if ($values[0] != $type)
7014
-                        continue;
7377
+                } else if ($mode == 'remove' && preg_match('/^\-/', $values[1])) {
7378
+                    if ($values[0] != $type) {
7379
+                                            continue;
7380
+                    }
7015 7381
                     $tabname = str_replace('-', '', $values[1]);
7016 7382
                     foreach ($head as $key => $val) {
7017 7383
                         $condition = (!empty($values[3]) ? verifCond($values[3]) : 1);
@@ -7053,10 +7419,11 @@  discard block
 block discarded – undo
7053 7419
         // global $action;
7054 7420
         // global $micro_start_time;
7055 7421
 
7056
-        if ($zone == 'private')
7057
-            print "\n" . '<!-- Common footer for private page -->' . "\n";
7058
-        else
7059
-            print "\n" . '<!-- Common footer for public page -->' . "\n";
7422
+        if ($zone == 'private') {
7423
+                    print "\n" . '<!-- Common footer for private page -->' . "\n";
7424
+        } else {
7425
+                    print "\n" . '<!-- Common footer for public page -->' . "\n";
7426
+        }
7060 7427
 
7061 7428
 // A div to store page_y POST parameter so we can read it using javascript
7062 7429
         print "\n<!-- A div to store page_y POST paramater -->\n";
@@ -7065,8 +7432,9 @@  discard block
 block discarded – undo
7065 7432
         $parameters = array();
7066 7433
         $reshook = $hookmanager->executeHooks('printCommonFooter', $parameters);    // Note that $action and $object may have been modified by some hooks
7067 7434
         if (empty($reshook)) {
7068
-            if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER))
7069
-                print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7435
+            if (!empty(Globals::$conf->global->MAIN_HTML_FOOTER)) {
7436
+                            print Globals::$conf->global->MAIN_HTML_FOOTER . "\n";
7437
+            }
7070 7438
 
7071 7439
             print "\n";
7072 7440
             if (!empty(Globals::$conf->use_javascript_ajax)) {
@@ -7089,8 +7457,9 @@  discard block
 block discarded – undo
7089 7457
                     print '/* JS CODE TO ENABLE to manage focus and mandatory form fields */' . "\n";
7090 7458
                     $relativepathstring = $_SERVER["PHP_SELF"];
7091 7459
                     // Clean $relativepathstring
7092
-                    if (constant('DOL_BASE_URI'))
7093
-                        $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7460
+                    if (constant('DOL_BASE_URI')) {
7461
+                                            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
7462
+                    }
7094 7463
                     $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
7095 7464
                     $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
7096 7465
                     $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
@@ -7101,14 +7470,17 @@  discard block
 block discarded – undo
7101 7470
                                 $tmpqueryarraytohave = explode('&', $defkey);
7102 7471
                                 $foundintru = 0;
7103 7472
                                 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
7104
-                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
7105
-                                        $foundintru = 1;
7473
+                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
7474
+                                                                            $foundintru = 1;
7475
+                                    }
7106 7476
                                 }
7107
-                                if (!$foundintru)
7108
-                                    $qualified = 1;
7477
+                                if (!$foundintru) {
7478
+                                                                    $qualified = 1;
7479
+                                }
7109 7480
                                 //var_dump($defkey.'-'.$qualified);
7110
-                            } else
7111
-                                $qualified = 1;
7481
+                            } else {
7482
+                                                            $qualified = 1;
7483
+                            }
7112 7484
 
7113 7485
                             if ($qualified) {
7114 7486
                                 foreach ($defval as $paramkey => $paramval) {
@@ -7127,14 +7499,17 @@  discard block
 block discarded – undo
7127 7499
                                 $tmpqueryarraytohave = explode('&', $defkey);
7128 7500
                                 $foundintru = 0;
7129 7501
                                 foreach ($tmpqueryarraytohave as $tmpquerytohave) {
7130
-                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
7131
-                                        $foundintru = 1;
7502
+                                    if (!in_array($tmpquerytohave, $tmpqueryarraywehave)) {
7503
+                                                                            $foundintru = 1;
7504
+                                    }
7132 7505
                                 }
7133
-                                if (!$foundintru)
7134
-                                    $qualified = 1;
7506
+                                if (!$foundintru) {
7507
+                                                                    $qualified = 1;
7508
+                                }
7135 7509
                                 //var_dump($defkey.'-'.$qualified);
7136
-                            } else
7137
-                                $qualified = 1;
7510
+                            } else {
7511
+                                                            $qualified = 1;
7512
+                            }
7138 7513
 
7139 7514
                             if ($qualified) {
7140 7515
                                 foreach ($defval as $paramkey => $paramval) {
@@ -7173,8 +7548,9 @@  discard block
 block discarded – undo
7173 7548
                     print "\n";
7174 7549
                     print "/* JS CODE TO ENABLE to add memory info */\n";
7175 7550
                     print 'window.console && console.log("';
7176
-                    if (!empty(Globals::$conf->global->MEMCACHED_SERVER))
7177
-                        print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7551
+                    if (!empty(Globals::$conf->global->MEMCACHED_SERVER)) {
7552
+                                            print 'MEMCACHED_SERVER=' . Globals::$conf->global->MEMCACHED_SERVER . ' - ';
7553
+                    }
7178 7554
                     print 'MAIN_OPTIMIZE_SPEED=' . (isset(Globals::$conf->global->MAIN_OPTIMIZE_SPEED) ? Globals::$conf->global->MAIN_OPTIMIZE_SPEED : 'off');
7179 7555
                     if (!empty($micro_start_time)) {   // Works only if MAIN_SHOW_TUNING_INFO is defined at $_SERVER level. Not in// global variable.
7180 7556
                         $micro_end_time = microtime(true);
@@ -7304,8 +7680,9 @@  discard block
 block discarded – undo
7304 7680
 
7305 7681
         $crits = explode(' ', $value);
7306 7682
         $res = '';
7307
-        if (!is_array($fields))
7308
-            $fields = array($fields);
7683
+        if (!is_array($fields)) {
7684
+                    $fields = array($fields);
7685
+        }
7309 7686
 
7310 7687
         $nboffields = count($fields);
7311 7688
         $end2 = count($crits);
@@ -7368,8 +7745,9 @@  discard block
 block discarded – undo
7368 7745
                     $tmpcrits = explode('|', $crit);
7369 7746
                     $i3 = 0;
7370 7747
                     foreach ($tmpcrits as $tmpcrit) {
7371
-                        if (empty($tmpcrit))
7372
-                            continue;
7748
+                        if (empty($tmpcrit)) {
7749
+                                                    continue;
7750
+                        }
7373 7751
 
7374 7752
                         $newres .= (($i2 > 0 || $i3 > 0) ? ' OR ' : '');
7375 7753
 
@@ -7405,8 +7783,9 @@  discard block
 block discarded – undo
7405 7783
                 }
7406 7784
                 $i++;
7407 7785
             }
7408
-            if ($newres)
7409
-                $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7786
+            if ($newres) {
7787
+                            $res = $res . ($res ? ' AND ' : '') . ($i2 > 1 ? '(' : '') . $newres . ($i2 > 1 ? ')' : '');
7788
+            }
7410 7789
             $j++;
7411 7790
         }
7412 7791
         $res = ($nofirstand ? "" : " AND ") . "(" . $res . ")";
@@ -7446,29 +7825,37 @@  discard block
 block discarded – undo
7446 7825
     static function getImageFileNameForSize($file, $extName, $extImgTarget = '')
7447 7826
     {
7448 7827
         $dirName = dirname($file);
7449
-        if ($dirName == '.')
7450
-            $dirName = '';
7828
+        if ($dirName == '.') {
7829
+                    $dirName = '';
7830
+        }
7451 7831
 
7452 7832
         $fileName = preg_replace('/(\.gif|\.jpeg|\.jpg|\.png|\.bmp)$/i', '', $file); // We remove extension, whatever is its case
7453 7833
         $fileName = basename($fileName);
7454 7834
 
7455
-        if (empty($extImgTarget))
7456
-            $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
7457
-        if (empty($extImgTarget))
7458
-            $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
7459
-        if (empty($extImgTarget))
7460
-            $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
7461
-        if (empty($extImgTarget))
7462
-            $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
7463
-        if (empty($extImgTarget))
7464
-            $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
7465
-
7466
-        if (!$extImgTarget)
7467
-            return $file;
7835
+        if (empty($extImgTarget)) {
7836
+                    $extImgTarget = (preg_match('/\.jpg$/i', $file) ? '.jpg' : '');
7837
+        }
7838
+        if (empty($extImgTarget)) {
7839
+                    $extImgTarget = (preg_match('/\.jpeg$/i', $file) ? '.jpeg' : '');
7840
+        }
7841
+        if (empty($extImgTarget)) {
7842
+                    $extImgTarget = (preg_match('/\.gif$/i', $file) ? '.gif' : '');
7843
+        }
7844
+        if (empty($extImgTarget)) {
7845
+                    $extImgTarget = (preg_match('/\.png$/i', $file) ? '.png' : '');
7846
+        }
7847
+        if (empty($extImgTarget)) {
7848
+                    $extImgTarget = (preg_match('/\.bmp$/i', $file) ? '.bmp' : '');
7849
+        }
7850
+
7851
+        if (!$extImgTarget) {
7852
+                    return $file;
7853
+        }
7468 7854
 
7469 7855
         $subdir = '';
7470
-        if ($extName)
7471
-            $subdir = 'thumbs/';
7856
+        if ($extName) {
7857
+                    $subdir = 'thumbs/';
7858
+        }
7472 7859
 
7473 7860
         return ($dirName ? $dirName . '/' : '') . $subdir . $fileName . $extName . $extImgTarget; // New filename for thumb
7474 7861
     }
@@ -7486,8 +7873,9 @@  discard block
 block discarded – undo
7486 7873
     {
7487 7874
        // global Globals::$conf, Globals::$langs;
7488 7875
 
7489
-        if (empty(Globals::$conf->use_javascript_ajax))
7490
-            return '';
7876
+        if (empty(Globals::$conf->use_javascript_ajax)) {
7877
+                    return '';
7878
+        }
7491 7879
 
7492 7880
         $mime_preview = array('bmp', 'jpeg', 'png', 'gif', 'tiff', 'pdf', 'plain', 'css', 'svg+xml');
7493 7881
 //$mime_preview[]='vnd.oasis.opendocument.presentation';
@@ -7495,17 +7883,19 @@  discard block
 block discarded – undo
7495 7883
         $num_mime = array_search(dol_mimetype($relativepath, '', 1), $mime_preview);
7496 7884
 
7497 7885
         if ($alldata == 1) {
7498
-            if ($num_mime !== false)
7499
-                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),);
7500
-            else
7501
-                return array();
7886
+            if ($num_mime !== false) {
7887
+                            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),);
7888
+            } else {
7889
+                            return array();
7890
+            }
7502 7891
         }
7503 7892
 
7504 7893
 // old behavior
7505
-        if ($num_mime !== false)
7506
-            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')) . '\')';
7507
-        else
7508
-            return '';
7894
+        if ($num_mime !== false) {
7895
+                    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')) . '\')';
7896
+        } else {
7897
+                    return '';
7898
+        }
7509 7899
     }
7510 7900
 
7511 7901
     /**
@@ -7523,8 +7913,9 @@  discard block
 block discarded – undo
7523 7913
 				    jQuery("#' . $htmlname . '").click(function() { jQuery(this).select(); } );
7524 7914
 				});
7525 7915
 		    </script>';
7526
-        if ($addlink)
7527
-            $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7916
+        if ($addlink) {
7917
+                    $out .= ' <a href="' . $addlink . '" target="_blank">' . Globals::$langs->trans("Link") . '</a>';
7918
+        }
7528 7919
         return $out;
7529 7920
     }
7530 7921
 
@@ -7906,8 +8297,9 @@  discard block
 block discarded – undo
7906 8297
         if (!isset($dictvalues[$tablename])) {
7907 8298
             $dictvalues[$tablename] = array();
7908 8299
             $sql = 'SELECT * FROM ' . $tablename . ' WHERE 1';
7909
-            if ($checkentity)
7910
-                $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
8300
+            if ($checkentity) {
8301
+                            $sql .= ' AND entity IN (0,' . getEntity($tablename) . ')';
8302
+            }
7911 8303
 
7912 8304
             $resql = $db->query($sql);
7913 8305
             if ($resql) {
@@ -7919,11 +8311,14 @@  discard block
 block discarded – undo
7919 8311
             }
7920 8312
         }
7921 8313
 
7922
-        if (!empty($dictvalues[$tablename][$id]))
7923
-            return $dictvalues[$tablename][$id]->{$field}; // Found
8314
+        if (!empty($dictvalues[$tablename][$id])) {
8315
+                    return $dictvalues[$tablename][$id]->{$field};
8316
+        }
8317
+        // Found
7924 8318
         else { // Not found
7925
-            if ($id > 0)
7926
-                return $id;
8319
+            if ($id > 0) {
8320
+                            return $id;
8321
+            }
7927 8322
             return '';
7928 8323
         }
7929 8324
     }
@@ -7953,8 +8348,9 @@  discard block
 block discarded – undo
7953 8348
                 $b = hexdec($hexb);
7954 8349
             }
7955 8350
             $bright = (max($r, $g, $b) + min($r, $g, $b)) / 510.0;    // HSL algorithm
7956
-            if ($bright > 0.6)
7957
-                $res = 1;
8351
+            if ($bright > 0.6) {
8352
+                            $res = 1;
8353
+            }
7958 8354
         }
7959 8355
         return $res;
7960 8356
     }
@@ -7972,8 +8368,10 @@  discard block
 block discarded – undo
7972 8368
        // global Globals::$conf;
7973 8369
 //print 'type_user='.$type_user.' module='.$menuentry['module'].' enabled='.$menuentry['enabled'].' perms='.$menuentry['perms'];
7974 8370
 //print 'ok='.in_array($menuentry['module'], $listofmodulesforexternal);
7975
-        if (empty($menuentry['enabled']))
7976
-            return 0; // Entry disabled by condition
8371
+        if (empty($menuentry['enabled'])) {
8372
+                    return 0;
8373
+        }
8374
+        // Entry disabled by condition
7977 8375
         if ($type_user && $menuentry['module']) {
7978 8376
             $tmploops = explode('|', $menuentry['module']);
7979 8377
             $found = 0;
@@ -7983,15 +8381,23 @@  discard block
 block discarded – undo
7983 8381
                     break;
7984 8382
                 }
7985 8383
             }
7986
-            if (!$found)
7987
-                return 0; // Entry is for menus all excluded to external users
7988
-        }
7989
-        if (!$menuentry['perms'] && $type_user)
7990
-            return 0;            // No permissions and user is external
7991
-        if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED))
7992
-            return 0; // No permissions and option to hide when not allowed, even for internal user, is on
7993
-        if (!$menuentry['perms'])
7994
-            return 2;               // No permissions and user is external
8384
+            if (!$found) {
8385
+                            return 0;
8386
+            }
8387
+            // Entry is for menus all excluded to external users
8388
+        }
8389
+        if (!$menuentry['perms'] && $type_user) {
8390
+                    return 0;
8391
+        }
8392
+        // No permissions and user is external
8393
+        if (!$menuentry['perms'] && !empty(Globals::$conf->global->MAIN_MENU_HIDE_UNAUTHORIZED)) {
8394
+                    return 0;
8395
+        }
8396
+        // No permissions and option to hide when not allowed, even for internal user, is on
8397
+        if (!$menuentry['perms']) {
8398
+                    return 2;
8399
+        }
8400
+        // No permissions and user is external
7995 8401
         return 1;
7996 8402
     }
7997 8403
 
Please login to merge, or discard this patch.
Helpers/EldyLib.php 2 patches
Spacing   +409 added lines, -409 removed lines patch added patch discarded remove patch
@@ -412,14 +412,14 @@  discard block
 block discarded – undo
412 412
                     $param = (isset($tmp[1]) ? $tmp[1] : '');
413 413
 
414 414
                     if (!preg_match('/mainmenu/i', $param) || !preg_match('/leftmenu/i', $param)) {
415
-                        $param .= ($param ? '&' : '') . 'mainmenu=' . $newTabMenu[$i]['mainmenu'] . '&leftmenu=';
415
+                        $param .= ($param ? '&' : '').'mainmenu='.$newTabMenu[$i]['mainmenu'].'&leftmenu=';
416 416
                     }
417 417
 //$url.="idmenu=".$newTabMenu[$i]['rowid'];    // Already done by menuLoad
418
-                    $url = DolUtils::dol_buildpath($url, 1) . ($param ? '?' . $param : '');
418
+                    $url = DolUtils::dol_buildpath($url, 1).($param ? '?'.$param : '');
419 419
 //$shorturl = $shorturl.($param?'?'.$param:'');
420 420
                     $shorturl = $url;
421 421
                     if (BASE_URI) {
422
-                        $shorturl = preg_replace('/^' . preg_quote(BASE_URI, '/') . '/', '', $shorturl);
422
+                        $shorturl = preg_replace('/^'.preg_quote(BASE_URI, '/').'/', '', $shorturl);
423 423
                     }
424 424
                 }
425 425
 
@@ -445,7 +445,7 @@  discard block
 block discarded – undo
445 445
         if (empty($noout)) {
446 446
             foreach ($menu->liste as $menkey => $menuval) {
447 447
                 self::print_start_menu_entry($menuval['idsel'], $menuval['classname'], $menuval['enabled']);
448
-                self::print_text_menu_entry($menuval['titre'], $menuval['enabled'], (($menuval['url'] != '#' && !preg_match('/^(http:\/\/|https:\/\/)/i', $menuval['url'])) ? BASE_URI : '') . $menuval['url'], $menuval['id'], $menuval['idsel'], $menuval['classname'], ($menuval['target'] ? $menuval['target'] : $atarget));
448
+                self::print_text_menu_entry($menuval['titre'], $menuval['enabled'], (($menuval['url'] != '#' && !preg_match('/^(http:\/\/|https:\/\/)/i', $menuval['url'])) ? BASE_URI : '').$menuval['url'], $menuval['id'], $menuval['idsel'], $menuval['classname'], ($menuval['target'] ? $menuval['target'] : $atarget));
449 449
                 self::print_end_menu_entry($menuval['enabled']);
450 450
             }
451 451
         }
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
         global $conf;
471 471
 
472 472
         print '<div class="tmenudiv">';
473
-        print '<ul class="tmenu"' . (empty(Conf::$global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Top menu"') . '>';
473
+        print '<ul class="tmenu"'.(empty(Conf::$global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Top menu"').'>';
474 474
     }
475 475
 
476 476
     /**
@@ -484,7 +484,7 @@  discard block
 block discarded – undo
484 484
     static function print_start_menu_entry($idsel, $classname, $showmode)
485 485
     {
486 486
         if ($showmode) {
487
-            print '<li ' . $classname . ' id="mainmenutd_' . $idsel . '">';
487
+            print '<li '.$classname.' id="mainmenutd_'.$idsel.'">';
488 488
 //print '<div class="tmenuleft tmenusep"></div>';
489 489
             print '<div class="tmenucenter">';
490 490
         }
@@ -507,17 +507,17 @@  discard block
 block discarded – undo
507 507
         // global Globals::$langs;
508 508
 
509 509
         if ($showmode == 1) {
510
-            print '<a class="tmenuimage" tabindex="-1" href="' . $url . '"' . ($atarget ? ' target="' . $atarget . '"' : '') . '>';
511
-            print '<div class="' . $id . ' ' . $idsel . ' topmenuimage"><span class="' . $id . ' tmenuimage" id="mainmenuspan_' . $idsel . '"></span></div>';
510
+            print '<a class="tmenuimage" tabindex="-1" href="'.$url.'"'.($atarget ? ' target="'.$atarget.'"' : '').'>';
511
+            print '<div class="'.$id.' '.$idsel.' topmenuimage"><span class="'.$id.' tmenuimage" id="mainmenuspan_'.$idsel.'"></span></div>';
512 512
             print '</a>';
513
-            print '<a ' . $classname . ' id="mainmenua_' . $idsel . '" href="' . $url . '"' . ($atarget ? ' target="' . $atarget . '"' : '') . '>';
513
+            print '<a '.$classname.' id="mainmenua_'.$idsel.'" href="'.$url.'"'.($atarget ? ' target="'.$atarget.'"' : '').'>';
514 514
             print '<span class="mainmenuaspan">';
515 515
             print $text;
516 516
             print '</span>';
517 517
             print '</a>';
518 518
         } elseif ($showmode == 2) {
519
-            print '<div class="' . $id . ' ' . $idsel . ' topmenuimage tmenudisabled"><span class="' . $id . '" id="mainmenuspan_' . $idsel . '"></span></div>';
520
-            print '<a class="tmenudisabled" id="mainmenua_' . $idsel . '" href="#" title="' . dol_escape_htmltag(Globals::$langs->trans("NotAllowed")) . '">';
519
+            print '<div class="'.$id.' '.$idsel.' topmenuimage tmenudisabled"><span class="'.$id.'" id="mainmenuspan_'.$idsel.'"></span></div>';
520
+            print '<a class="tmenudisabled" id="mainmenua_'.$idsel.'" href="#" title="'.dol_escape_htmltag(Globals::$langs->trans("NotAllowed")).'">';
521 521
             print '<span class="mainmenuaspan">';
522 522
             print $text;
523 523
             print '</span>';
@@ -581,38 +581,38 @@  discard block
 block discarded – undo
581 581
 // Show logo company
582 582
         if (empty(Conf::$global->MAIN_MENU_INVERT) && empty($noout) && !empty(Conf::$global->MAIN_SHOW_LOGO) && empty(Conf::$global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
583 583
             $mysoc->logo_mini = Conf::$global->MAIN_INFO_SOCIETE_LOGO_MINI;
584
-            if (!empty($mysoc->logo_mini) && is_readable($conf->mycompany->dir_output . '/logos/thumbs/' . $mysoc->logo_mini)) {
585
-                $urllogo = DOL_BASE_URI . '/viewimage.php?cache=1&modulepart=mycompany&file=' . urlencode('logos/thumbs/' . $mysoc->logo_mini);
584
+            if (!empty($mysoc->logo_mini) && is_readable($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_mini)) {
585
+                $urllogo = DOL_BASE_URI.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_mini);
586 586
             } else {
587
-                $urllogo = DOL_BASE_URI . '/theme/dolibarr_logo.png';
587
+                $urllogo = DOL_BASE_URI.'/theme/dolibarr_logo.png';
588 588
             }
589 589
             $title = Globals::$langs->trans("GoIntoSetupToChangeLogo");
590
-            print "\n" . '<!-- Show logo on menu -->' . "\n";
591
-            print '<div class="blockvmenuimpair blockvmenulogo">' . "\n";
590
+            print "\n".'<!-- Show logo on menu -->'."\n";
591
+            print '<div class="blockvmenuimpair blockvmenulogo">'."\n";
592 592
             print '<div class="menu_titre" id="menu_titre_logo"></div>';
593 593
             print '<div class="menu_top" id="menu_top_logo"></div>';
594 594
             print '<div class="menu_contenu" id="menu_contenu_logo">';
595
-            print '<div class="center"><img class="mycompany" title="' . dol_escape_htmltag($title) . '" alt="" src="' . $urllogo . '" style="max-width: 70%"></div>' . "\n";
595
+            print '<div class="center"><img class="mycompany" title="'.dol_escape_htmltag($title).'" alt="" src="'.$urllogo.'" style="max-width: 70%"></div>'."\n";
596 596
             print '</div>';
597 597
             print '<div class="menu_end" id="menu_end_logo"></div>';
598
-            print '</div>' . "\n";
598
+            print '</div>'."\n";
599 599
         }
600 600
 
601 601
         if (is_array($moredata) && !empty($moredata['searchform'])) { // searchform can contains select2 code or link to show old search form or link to switch on search page
602 602
             print "\n";
603 603
             print "<!-- Begin SearchForm -->\n";
604
-            print '<div id="blockvmenusearch" class="blockvmenusearch">' . "\n";
604
+            print '<div id="blockvmenusearch" class="blockvmenusearch">'."\n";
605 605
             print $moredata['searchform'];
606
-            print '</div>' . "\n";
606
+            print '</div>'."\n";
607 607
             print "<!-- End SearchForm -->\n";
608 608
         }
609 609
 
610 610
         if (is_array($moredata) && !empty($moredata['bookmarks'])) {
611 611
             print "\n";
612 612
             print "<!-- Begin Bookmarks -->\n";
613
-            print '<div id="blockvmenubookmarks" class="blockvmenubookmarks">' . "\n";
613
+            print '<div id="blockvmenubookmarks" class="blockvmenubookmarks">'."\n";
614 614
             print $moredata['bookmarks'];
615
-            print '</div>' . "\n";
615
+            print '</div>'."\n";
616 616
             print "<!-- End Bookmarks -->\n";
617 617
         }
618 618
 
@@ -629,11 +629,11 @@  discard block
 block discarded – undo
629 629
 
630 630
 // Home - dashboard
631 631
 //$newmenu->add("/index.php?mainmenu=home&leftmenu=home", Globals::$langs->trans("MyDashboard"), 0, 1, '', $mainmenu, 'home', 0, '', '', '', '<i class="fa fa-bar-chart fa-fw paddingright"></i>');
632
-                $newmenu->add(BASE_URI . "?controller=home&method=home&mainmenu=home&leftmenu=home", Globals::$langs->trans("MyDashboard"), 0, 1, '', $mainmenu, 'home', 0, '', '', '', '<i class="fa fa-bar-chart fa-fw paddingright"></i>');
632
+                $newmenu->add(BASE_URI."?controller=home&method=home&mainmenu=home&leftmenu=home", Globals::$langs->trans("MyDashboard"), 0, 1, '', $mainmenu, 'home', 0, '', '', '', '<i class="fa fa-bar-chart fa-fw paddingright"></i>');
633 633
 
634 634
 // Setup
635 635
 //$newmenu->add("/admin/index.php?mainmenu=home&leftmenu=setup", Globals::$langs->trans("Setup"), 0, Globals::$user->admin, '', $mainmenu, 'setup', 0, '', '', '', '<i class="fa fa-wrench fa-fw paddingright"></i>');
636
-                $newmenu->add(BASE_URI . "?controller=admin&method=index&mainmenu=home&leftmenu=setup", Globals::$langs->trans("Setup"), 0, Globals::$user->admin, '', $mainmenu, 'setup', 0, '', '', '', '<i class="fa fa-wrench fa-fw paddingright"></i>');
636
+                $newmenu->add(BASE_URI."?controller=admin&method=index&mainmenu=home&leftmenu=setup", Globals::$langs->trans("Setup"), 0, Globals::$user->admin, '', $mainmenu, 'setup', 0, '', '', '', '<i class="fa fa-wrench fa-fw paddingright"></i>');
637 637
 
638 638
                 if ($usemenuhider || empty($leftmenu) || $leftmenu == "setup") {
639 639
 // Load translation files required by the page
@@ -642,14 +642,14 @@  discard block
 block discarded – undo
642 642
                     $warnpicto = '';
643 643
                     if (empty(Conf::$global->MAIN_INFO_SOCIETE_NOM) || empty(Conf::$global->MAIN_INFO_SOCIETE_COUNTRY)) {
644 644
                         Globals::$langs->load("errors");
645
-                        $warnpicto = ' ' . img_warning(Globals::$langs->trans("WarningMandatorySetupNotComplete"));
645
+                        $warnpicto = ' '.img_warning(Globals::$langs->trans("WarningMandatorySetupNotComplete"));
646 646
                     }
647 647
 //$newmenu->add("/admin/company.php?mainmenu=home", Globals::$langs->trans("MenuCompanySetup") . $warnpicto, 1);
648
-                    $newmenu->add(BASE_URI . "?controller=admin&method=company&mainmenu=home", Globals::$langs->trans("MenuCompanySetup") . $warnpicto, 1);
648
+                    $newmenu->add(BASE_URI."?controller=admin&method=company&mainmenu=home", Globals::$langs->trans("MenuCompanySetup").$warnpicto, 1);
649 649
                     $warnpicto = '';
650 650
                     if (count($conf->modules) <= (empty(Conf::$global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING) ? 1 : Conf::$global->MAIN_MIN_NB_ENABLED_MODULE_FOR_WARNING)) { // If only user module enabled
651 651
                         Globals::$langs->load("errors");
652
-                        $warnpicto = ' ' . img_warning(Globals::$langs->trans("WarningMandatorySetupNotComplete"));
652
+                        $warnpicto = ' '.img_warning(Globals::$langs->trans("WarningMandatorySetupNotComplete"));
653 653
                     }
654 654
                     /*
655 655
                       $newmenu->add("/admin/modules.php?mainmenu=home", Globals::$langs->trans("Modules") . $warnpicto, 1);
@@ -668,42 +668,42 @@  discard block
 block discarded – undo
668 668
                       $newmenu->add("/admin/dict.php?mainmenu=home", Globals::$langs->trans("Dictionary"), 1);
669 669
                       $newmenu->add("/admin/const.php?mainmenu=home", Globals::$langs->trans("OtherSetup"), 1);
670 670
                      */
671
-                    $newmenu->add(BASE_URI . "?controller=admin&method=modules&mainmenu=home", Globals::$langs->trans("Modules") . $warnpicto, 1);
672
-                    $newmenu->add(BASE_URI . "?controller=admin&method=menus&mainmenu=home", Globals::$langs->trans("Menus"), 1);
673
-                    $newmenu->add(BASE_URI . "?controller=admin&method=ihm&mainmenu=home", Globals::$langs->trans("GUISetup"), 1);
674
-
675
-                    $newmenu->add(BASE_URI . "?controller=admin&method=translation&mainmenu=home", Globals::$langs->trans("Translation"), 1);
676
-                    $newmenu->add(BASE_URI . "?controller=admin&method=defaultvalues&mainmenu=home", Globals::$langs->trans("DefaultValues"), 1);
677
-                    $newmenu->add(BASE_URI . "?controller=admin&method=boxes&mainmenu=home", Globals::$langs->trans("Boxes"), 1);
678
-                    $newmenu->add(BASE_URI . "?controller=admin&method=delais&mainmenu=home", Globals::$langs->trans("MenuWarnings"), 1);
679
-                    $newmenu->add(BASE_URI . "?controller=admin&method=security_other&mainmenu=home", Globals::$langs->trans("Security"), 1);
680
-                    $newmenu->add(BASE_URI . "?controller=admin&method=limits&mainmenu=home", Globals::$langs->trans("MenuLimits"), 1);
681
-                    $newmenu->add(BASE_URI . "?controller=admin&method=pdf&mainmenu=home", Globals::$langs->trans("PDF"), 1);
682
-                    $newmenu->add(BASE_URI . "?controller=admin&method=mails&mainmenu=home", Globals::$langs->trans("Emails"), 1);
683
-                    $newmenu->add(BASE_URI . "?controller=admin&method=sms&mainmenu=home", Globals::$langs->trans("SMS"), 1);
684
-                    $newmenu->add(BASE_URI . "?controller=admin&method=dict&mainmenu=home", Globals::$langs->trans("Dictionary"), 1);
685
-                    $newmenu->add(BASE_URI . "?controller=admin&method=const&mainmenu=home", Globals::$langs->trans("OtherSetup"), 1);
671
+                    $newmenu->add(BASE_URI."?controller=admin&method=modules&mainmenu=home", Globals::$langs->trans("Modules").$warnpicto, 1);
672
+                    $newmenu->add(BASE_URI."?controller=admin&method=menus&mainmenu=home", Globals::$langs->trans("Menus"), 1);
673
+                    $newmenu->add(BASE_URI."?controller=admin&method=ihm&mainmenu=home", Globals::$langs->trans("GUISetup"), 1);
674
+
675
+                    $newmenu->add(BASE_URI."?controller=admin&method=translation&mainmenu=home", Globals::$langs->trans("Translation"), 1);
676
+                    $newmenu->add(BASE_URI."?controller=admin&method=defaultvalues&mainmenu=home", Globals::$langs->trans("DefaultValues"), 1);
677
+                    $newmenu->add(BASE_URI."?controller=admin&method=boxes&mainmenu=home", Globals::$langs->trans("Boxes"), 1);
678
+                    $newmenu->add(BASE_URI."?controller=admin&method=delais&mainmenu=home", Globals::$langs->trans("MenuWarnings"), 1);
679
+                    $newmenu->add(BASE_URI."?controller=admin&method=security_other&mainmenu=home", Globals::$langs->trans("Security"), 1);
680
+                    $newmenu->add(BASE_URI."?controller=admin&method=limits&mainmenu=home", Globals::$langs->trans("MenuLimits"), 1);
681
+                    $newmenu->add(BASE_URI."?controller=admin&method=pdf&mainmenu=home", Globals::$langs->trans("PDF"), 1);
682
+                    $newmenu->add(BASE_URI."?controller=admin&method=mails&mainmenu=home", Globals::$langs->trans("Emails"), 1);
683
+                    $newmenu->add(BASE_URI."?controller=admin&method=sms&mainmenu=home", Globals::$langs->trans("SMS"), 1);
684
+                    $newmenu->add(BASE_URI."?controller=admin&method=dict&mainmenu=home", Globals::$langs->trans("Dictionary"), 1);
685
+                    $newmenu->add(BASE_URI."?controller=admin&method=const&mainmenu=home", Globals::$langs->trans("OtherSetup"), 1);
686 686
                 }
687 687
 
688 688
 // System tools
689 689
 //$newmenu->add("/admin/tools/index.php?mainmenu=home&leftmenu=admintools", Globals::$langs->trans("AdminTools"), 0, Globals::$user->admin, '', $mainmenu, 'admintools', 0, '', '', '', '<i class="fa fa-server fa-fw paddingright"></i>');
690
-                $newmenu->add(BASE_URI . "?controller=admin/tools&method=index&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("AdminTools"), 0, Globals::$user->admin, '', $mainmenu, 'admintools', 0, '', '', '', '<i class="fa fa-server fa-fw paddingright"></i>');
690
+                $newmenu->add(BASE_URI."?controller=admin/tools&method=index&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("AdminTools"), 0, Globals::$user->admin, '', $mainmenu, 'admintools', 0, '', '', '', '<i class="fa fa-server fa-fw paddingright"></i>');
691 691
 
692 692
                 if ($usemenuhider || empty($leftmenu) || preg_match('/^admintools/', $leftmenu)) {
693 693
 // Load translation files required by the page
694 694
                     Globals::$langs->loadLangs(array('admin', 'help'));
695 695
 
696 696
 //$newmenu->add('/admin/system/dolibarr.php?mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('InfoDolibarr'), 1);
697
-                    $newmenu->add(BASE_URI . "?controller=admin/system&method=dolibarr&mainmenu=home&leftmenu=admintools_info", Globals::$langs->trans('InfoDolibarr'), 1);
697
+                    $newmenu->add(BASE_URI."?controller=admin/system&method=dolibarr&mainmenu=home&leftmenu=admintools_info", Globals::$langs->trans('InfoDolibarr'), 1);
698 698
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == 'admintools_info') {
699 699
                         /*
700 700
                           $newmenu->add('/admin/system/modules.php?mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Modules'), 2);
701 701
                           $newmenu->add('/admin/triggers.php?mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Triggers'), 2);
702 702
                           $newmenu->add('/admin/system/filecheck.php?mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('FileCheck'), 2);
703 703
                          */
704
-                        $newmenu->add(BASE_URI . '?controller=admin/system&method=modules&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Modules'), 2);
705
-                        $newmenu->add(BASE_URI . '?controller=admin&method=triggers&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Triggers'), 2);
706
-                        $newmenu->add(BASE_URI . '?controller=admin/system&method=filecheck&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('FileCheck'), 2);
704
+                        $newmenu->add(BASE_URI.'?controller=admin/system&method=modules&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Modules'), 2);
705
+                        $newmenu->add(BASE_URI.'?controller=admin&method=triggers&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('Triggers'), 2);
706
+                        $newmenu->add(BASE_URI.'?controller=admin/system&method=filecheck&mainmenu=home&leftmenu=admintools_info', Globals::$langs->trans('FileCheck'), 2);
707 707
                     }
708 708
                     /*
709 709
                       $newmenu->add('/admin/system/browser.php?mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoBrowser'), 1);
@@ -723,33 +723,33 @@  discard block
 block discarded – undo
723 723
                       $newmenu->add("/admin/tools/listsessions.php?mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Sessions"), 1);
724 724
                       $newmenu->add('/admin/system/about.php?mainmenu=home&leftmenu=admintools', Globals::$langs->trans('ExternalResources'), 1);
725 725
                      */
726
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=browser&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoBrowser'), 1);
727
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=os&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoOS'), 1);
728
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=web&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoWebServer'), 1);
729
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=phpinfo&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoPHP'), 1);
726
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=browser&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoBrowser'), 1);
727
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=os&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoOS'), 1);
728
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=web&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoWebServer'), 1);
729
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=phpinfo&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoPHP'), 1);
730 730
 //if (function_exists('xdebug_is_enabled')) $newmenu->add('/admin/system/xdebug.php', Globals::$langs->trans('XDebug'),1);
731
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=database&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoDatabase'), 1);
731
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=database&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('InfoDatabase'), 1);
732 732
                     if (function_exists('eaccelerator_info')) {
733
-                        $newmenu->add(BASE_URI . "?controller=admin/tools&method=eaccelerator&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("EAccelerator"), 1);
733
+                        $newmenu->add(BASE_URI."?controller=admin/tools&method=eaccelerator&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("EAccelerator"), 1);
734 734
                     }
735 735
 //$newmenu->add("/admin/system/perf.php?mainmenu=home&leftmenu=admintools", Globals::$langs->trans("InfoPerf"),1);
736
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=dolibarr_export&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Backup"), 1);
737
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=dolibarr_import&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Restore"), 1);
738
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=update&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("MenuUpgrade"), 1);
739
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=purge&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Purge"), 1);
740
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=listevents&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Audit"), 1);
741
-                    $newmenu->add(BASE_URI . "?controller=admin/tools&method=listsessions&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Sessions"), 1);
742
-                    $newmenu->add(BASE_URI . '?controller=admin/system&method=about&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('ExternalResources'), 1);
736
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=dolibarr_export&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Backup"), 1);
737
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=dolibarr_import&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Restore"), 1);
738
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=update&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("MenuUpgrade"), 1);
739
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=purge&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Purge"), 1);
740
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=listevents&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Audit"), 1);
741
+                    $newmenu->add(BASE_URI."?controller=admin/tools&method=listsessions&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("Sessions"), 1);
742
+                    $newmenu->add(BASE_URI.'?controller=admin/system&method=about&mainmenu=home&leftmenu=admintools', Globals::$langs->trans('ExternalResources'), 1);
743 743
 
744 744
                     if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) {
745 745
                         Globals::$langs->load("products");
746 746
 //$newmenu->add("/product/admin/product_tools.php?mainmenu=home&leftmenu=admintools", Globals::$langs->trans("ProductVatMassChange"), 1, Globals::$user->admin);
747
-                        $newmenu->add(BASE_URI . "?controller=product/admin&method=product_tools&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("ProductVatMassChange"), 1, Globals::$user->admin);
747
+                        $newmenu->add(BASE_URI."?controller=product/admin&method=product_tools&mainmenu=home&leftmenu=admintools", Globals::$langs->trans("ProductVatMassChange"), 1, Globals::$user->admin);
748 748
                     }
749 749
                 }
750 750
 
751 751
 //$newmenu->add("/user/home.php?leftmenu=users", Globals::$langs->trans("MenuUsersAndGroups"), 0, Globals::$user->rights->user->user->lire, '', $mainmenu, 'users', 0, '', '', '', '<i class="fa fa-users fa-fw paddingright"></i>');
752
-                $newmenu->add(BASE_URI . "?controller=user&method=home&leftmenu=users", Globals::$langs->trans("MenuUsersAndGroups"), 0, Globals::$user->rights->user->user->lire, '', $mainmenu, 'users', 0, '', '', '', '<i class="fa fa-users fa-fw paddingright"></i>');
752
+                $newmenu->add(BASE_URI."?controller=user&method=home&leftmenu=users", Globals::$langs->trans("MenuUsersAndGroups"), 0, Globals::$user->rights->user->user->lire, '', $mainmenu, 'users', 0, '', '', '', '<i class="fa fa-users fa-fw paddingright"></i>');
753 753
                 if (Globals::$user->rights->user->user->lire) {
754 754
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "users") {
755 755
                         $newmenu->add("", Globals::$langs->trans("Users"), 1, Globals::$user->rights->user->user->lire || Globals::$user->admin);
@@ -765,16 +765,16 @@  discard block
 block discarded – undo
765 765
                           $newmenu->add("/user/group/card.php?leftmenu=users&action=create", Globals::$langs->trans("NewGroup"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->write : Globals::$user->rights->user->user->creer) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
766 766
                           $newmenu->add("/user/group/list.php?leftmenu=users", Globals::$langs->trans("ListOfGroups"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->read : Globals::$user->rights->user->user->lire) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
767 767
                          */
768
-                        $newmenu->add(BASE_URI . "?controller=user&method=card&leftmenu=users&action=create", Globals::$langs->trans("NewUser"), 2, (Globals::$user->rights->user->user->creer || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE), '', 'home');
769
-                        $newmenu->add(BASE_URI . "?controller=user&method=list&leftmenu=users", Globals::$langs->trans("ListOfUsers"), 2, Globals::$user->rights->user->user->lire || Globals::$user->admin);
770
-                        $newmenu->add(BASE_URI . "?controller=user&method=hierarchy&leftmenu=users", Globals::$langs->trans("HierarchicView"), 2, Globals::$user->rights->user->user->lire || Globals::$user->admin);
768
+                        $newmenu->add(BASE_URI."?controller=user&method=card&leftmenu=users&action=create", Globals::$langs->trans("NewUser"), 2, (Globals::$user->rights->user->user->creer || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE), '', 'home');
769
+                        $newmenu->add(BASE_URI."?controller=user&method=list&leftmenu=users", Globals::$langs->trans("ListOfUsers"), 2, Globals::$user->rights->user->user->lire || Globals::$user->admin);
770
+                        $newmenu->add(BASE_URI."?controller=user&method=hierarchy&leftmenu=users", Globals::$langs->trans("HierarchicView"), 2, Globals::$user->rights->user->user->lire || Globals::$user->admin);
771 771
                         if (!empty($conf->categorie->enabled)) {
772 772
                             Globals::$langs->load("categories");
773
-                            $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=users&type=7", Globals::$langs->trans("UsersCategoriesShort"), 2, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
773
+                            $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=users&type=7", Globals::$langs->trans("UsersCategoriesShort"), 2, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
774 774
                         }
775 775
                         $newmenu->add("", Globals::$langs->trans("Groups"), 1, (Globals::$user->rights->user->user->lire || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
776
-                        $newmenu->add(BASE_URI . "?controller=user/group&method=card&leftmenu=users&action=create", Globals::$langs->trans("NewGroup"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->write : Globals::$user->rights->user->user->creer) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
777
-                        $newmenu->add(BASE_URI . "?controller=user/group&method=list&leftmenu=users", Globals::$langs->trans("ListOfGroups"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->read : Globals::$user->rights->user->user->lire) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
776
+                        $newmenu->add(BASE_URI."?controller=user/group&method=card&leftmenu=users&action=create", Globals::$langs->trans("NewGroup"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->write : Globals::$user->rights->user->user->creer) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
777
+                        $newmenu->add(BASE_URI."?controller=user/group&method=list&leftmenu=users", Globals::$langs->trans("ListOfGroups"), 2, ((Conf::$global->MAIN_USE_ADVANCED_PERMS ? Globals::$user->rights->user->group_advance->read : Globals::$user->rights->user->user->lire) || Globals::$user->admin) && !(!empty($conf->multicompany->enabled) && $conf->entity > 1 && Conf::$global->MULTICOMPANY_TRANSVERSE_MODE));
778 778
                     }
779 779
                 }
780 780
             }
@@ -787,26 +787,26 @@  discard block
 block discarded – undo
787 787
                 if (!empty($conf->societe->enabled)) {
788 788
                     Globals::$langs->load("companies");
789 789
 //$newmenu->add("/societe/index.php?leftmenu=thirdparties", Globals::$langs->trans("ThirdParty"), 0, Globals::$user->rights->societe->lire, '', $mainmenu, 'thirdparties');
790
-                    $newmenu->add(BASE_URI . "?controller=societe&method=index&leftmenu=thirdparties", Globals::$langs->trans("ThirdParty"), 0, Globals::$user->rights->societe->lire, '', $mainmenu, 'thirdparties');
790
+                    $newmenu->add(BASE_URI."?controller=societe&method=index&leftmenu=thirdparties", Globals::$langs->trans("ThirdParty"), 0, Globals::$user->rights->societe->lire, '', $mainmenu, 'thirdparties');
791 791
 
792 792
                     if (Globals::$user->rights->societe->creer) {
793 793
 //$newmenu->add("/societe/card.php?action=create", Globals::$langs->trans("MenuNewThirdParty"), 1);
794
-                        $newmenu->add(BASE_URI . "?controller=societe&method=card&action=create", Globals::$langs->trans("MenuNewThirdParty"), 1);
794
+                        $newmenu->add(BASE_URI."?controller=societe&method=card&action=create", Globals::$langs->trans("MenuNewThirdParty"), 1);
795 795
                         if (!$conf->use_javascript_ajax) {
796 796
 //$newmenu->add("/societe/card.php?action=create&private=1", Globals::$langs->trans("MenuNewPrivateIndividual"), 1);
797
-                            $newmenu->add(BASE_URI . "?controller=societe&method=card&action=create&private=1", Globals::$langs->trans("MenuNewPrivateIndividual"), 1);
797
+                            $newmenu->add(BASE_URI."?controller=societe&method=card&action=create&private=1", Globals::$langs->trans("MenuNewPrivateIndividual"), 1);
798 798
                         }
799 799
                     }
800 800
                 }
801 801
 
802 802
 //$newmenu->add("/societe/list.php?leftmenu=thirdparties", Globals::$langs->trans("List"), 1);
803
-                $newmenu->add(BASE_URI . "?controller=societe&method=list&leftmenu=thirdparties", Globals::$langs->trans("List"), 1);
803
+                $newmenu->add(BASE_URI."?controller=societe&method=list&leftmenu=thirdparties", Globals::$langs->trans("List"), 1);
804 804
 
805 805
 // Prospects
806 806
                 if (!empty($conf->societe->enabled) && empty(Conf::$global->SOCIETE_DISABLE_PROSPECTS)) {
807 807
                     Globals::$langs->load("commercial");
808 808
 //$newmenu->add("/societe/list.php?type=p&leftmenu=prospects", Globals::$langs->trans("ListProspectsShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'prospects');
809
-                    $newmenu->add(BASE_URI . "?controller=societe&method=list&type=p&leftmenu=prospects", Globals::$langs->trans("ListProspectsShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'prospects');
809
+                    $newmenu->add(BASE_URI."?controller=societe&method=list&type=p&leftmenu=prospects", Globals::$langs->trans("ListProspectsShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'prospects');
810 810
                     /* no more required, there is a filter that can do more
811 811
                       if ($usemenuhider || empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=-1", Globals::$langs->trans("LastProspectDoNotContact"), 2, Globals::$user->rights->societe->lire);
812 812
                       if ($usemenuhider || empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=0", Globals::$langs->trans("LastProspectNeverContacted"), 2, Globals::$user->rights->societe->lire);
@@ -815,7 +815,7 @@  discard block
 block discarded – undo
815 815
                       if ($usemenuhider || empty($leftmenu) || $leftmenu=="prospects") $newmenu->add("/societe/list.php?type=p&sortfield=s.datec&sortorder=desc&begin=&search_stcomm=3", Globals::$langs->trans("LastProspectContactDone"), 2, Globals::$user->rights->societe->lire);
816 816
                      */
817 817
 //$newmenu->add("/societe/card.php?leftmenu=prospects&action=create&type=p", Globals::$langs->trans("MenuNewProspect"), 2, Globals::$user->rights->societe->creer);
818
-                    $newmenu->add(BASE_URI . "?controller=societe&method=card&leftmenu=prospects&action=create&type=p", Globals::$langs->trans("MenuNewProspect"), 2, Globals::$user->rights->societe->creer);
818
+                    $newmenu->add(BASE_URI."?controller=societe&method=card&leftmenu=prospects&action=create&type=p", Globals::$langs->trans("MenuNewProspect"), 2, Globals::$user->rights->societe->creer);
819 819
 //$newmenu->add("/contact/list.php?leftmenu=customers&type=p", Globals::$langs->trans("Contacts"), 2, Globals::$user->rights->societe->contact->lire);
820 820
                 }
821 821
 
@@ -823,10 +823,10 @@  discard block
 block discarded – undo
823 823
                 if (!empty($conf->societe->enabled) && empty(Conf::$global->SOCIETE_DISABLE_CUSTOMERS)) {
824 824
                     Globals::$langs->load("commercial");
825 825
 //$newmenu->add("/societe/list.php?type=c&leftmenu=customers", Globals::$langs->trans("ListCustomersShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'customers');
826
-                    $newmenu->add(BASE_URI . "?controller=societe&method=list&type=c&leftmenu=customers", Globals::$langs->trans("ListCustomersShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'customers');
826
+                    $newmenu->add(BASE_URI."?controller=societe&method=list&type=c&leftmenu=customers", Globals::$langs->trans("ListCustomersShort"), 1, Globals::$user->rights->societe->lire, '', $mainmenu, 'customers');
827 827
 
828 828
 //$newmenu->add("/societe/card.php?leftmenu=customers&action=create&type=c", Globals::$langs->trans("MenuNewCustomer"), 2, Globals::$user->rights->societe->creer);
829
-                    $newmenu->add(BASE_URI . "?controller=societe&method=card&leftmenu=customers&action=create&type=c", Globals::$langs->trans("MenuNewCustomer"), 2, Globals::$user->rights->societe->creer);
829
+                    $newmenu->add(BASE_URI."?controller=societe&method=card&leftmenu=customers&action=create&type=c", Globals::$langs->trans("MenuNewCustomer"), 2, Globals::$user->rights->societe->creer);
830 830
 //$newmenu->add("/contact/list.php?leftmenu=customers&type=c", Globals::$langs->trans("Contacts"), 2, Globals::$user->rights->societe->contact->lire);
831 831
                 }
832 832
 
@@ -835,8 +835,8 @@  discard block
 block discarded – undo
835 835
                     Globals::$langs->load("suppliers");
836 836
 //$newmenu->add("/societe/list.php?type=f&leftmenu=suppliers", Globals::$langs->trans("ListSuppliersShort"), 1, (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire), '', $mainmenu, 'suppliers');
837 837
 //$newmenu->add("/societe/card.php?leftmenu=suppliers&action=create&type=f", Globals::$langs->trans("MenuNewSupplier"), 2, Globals::$user->rights->societe->creer && (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire));
838
-                    $newmenu->add(BASE_URI . "?controller=societe&method=list&type=f&leftmenu=suppliers", Globals::$langs->trans("ListSuppliersShort"), 1, (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire), '', $mainmenu, 'suppliers');
839
-                    $newmenu->add(BASE_URI . "?controller=societe&method=card&leftmenu=suppliers&action=create&type=f", Globals::$langs->trans("MenuNewSupplier"), 2, Globals::$user->rights->societe->creer && (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire));
838
+                    $newmenu->add(BASE_URI."?controller=societe&method=list&type=f&leftmenu=suppliers", Globals::$langs->trans("ListSuppliersShort"), 1, (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire), '', $mainmenu, 'suppliers');
839
+                    $newmenu->add(BASE_URI."?controller=societe&method=card&leftmenu=suppliers&action=create&type=f", Globals::$langs->trans("MenuNewSupplier"), 2, Globals::$user->rights->societe->creer && (Globals::$user->rights->fournisseur->lire || Globals::$user->rights->supplier_proposal->lire));
840 840
                 }
841 841
 
842 842
 // Categories
@@ -852,12 +852,12 @@  discard block
 block discarded – undo
852 852
                             $menutoshow = Globals::$langs->trans("ProspectsCategoriesShort");
853 853
                         }
854 854
 //$newmenu->add("/categories/index.php?leftmenu=cat&type=2", $menutoshow, 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
855
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=cat&type=2", $menutoshow, 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
855
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=cat&type=2", $menutoshow, 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
856 856
                     }
857 857
 // Categories suppliers
858 858
                     if (!empty($conf->fournisseur->enabled)) {
859 859
 //$newmenu->add("/categories/index.php?leftmenu=catfournish&type=1", Globals::$langs->trans("SuppliersCategoriesShort"), 1, Globals::$user->rights->categorie->lire);
860
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=catfournish&type=1", Globals::$langs->trans("SuppliersCategoriesShort"), 1, Globals::$user->rights->categorie->lire);
860
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=catfournish&type=1", Globals::$langs->trans("SuppliersCategoriesShort"), 1, Globals::$user->rights->categorie->lire);
861 861
                     }
862 862
                 }
863 863
 
@@ -865,30 +865,30 @@  discard block
 block discarded – undo
865 865
 //$newmenu->add("/societe/index.php?leftmenu=thirdparties", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("Contacts") : Globals::$langs->trans("ContactsAddresses")), 0, Globals::$user->rights->societe->contact->lire, '', $mainmenu, 'contacts');
866 866
 //$newmenu->add("/contact/card.php?leftmenu=contacts&action=create", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("NewContact") : Globals::$langs->trans("NewContactAddress")), 1, Globals::$user->rights->societe->contact->creer);
867 867
 //$newmenu->add("/contact/list.php?leftmenu=contacts", Globals::$langs->trans("List"), 1, Globals::$user->rights->societe->contact->lire);
868
-                $newmenu->add(BASE_URI . "?controller=societe&method=index&leftmenu=thirdparties", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("Contacts") : Globals::$langs->trans("ContactsAddresses")), 0, Globals::$user->rights->societe->contact->lire, '', $mainmenu, 'contacts');
869
-                $newmenu->add(BASE_URI . "?controller=contact&method=card&leftmenu=contacts&action=create", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("NewContact") : Globals::$langs->trans("NewContactAddress")), 1, Globals::$user->rights->societe->contact->creer);
870
-                $newmenu->add(BASE_URI . "?controller=contact&method=list&leftmenu=contacts", Globals::$langs->trans("List"), 1, Globals::$user->rights->societe->contact->lire);
868
+                $newmenu->add(BASE_URI."?controller=societe&method=index&leftmenu=thirdparties", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("Contacts") : Globals::$langs->trans("ContactsAddresses")), 0, Globals::$user->rights->societe->contact->lire, '', $mainmenu, 'contacts');
869
+                $newmenu->add(BASE_URI."?controller=contact&method=card&leftmenu=contacts&action=create", (!empty(Conf::$global->SOCIETE_ADDRESSES_MANAGEMENT) ? Globals::$langs->trans("NewContact") : Globals::$langs->trans("NewContactAddress")), 1, Globals::$user->rights->societe->contact->creer);
870
+                $newmenu->add(BASE_URI."?controller=contact&method=list&leftmenu=contacts", Globals::$langs->trans("List"), 1, Globals::$user->rights->societe->contact->lire);
871 871
                 if (empty(Conf::$global->SOCIETE_DISABLE_PROSPECTS)) {
872 872
 //$newmenu->add("/contact/list.php?leftmenu=contacts&type=p", Globals::$langs->trans("Prospects"), 2, Globals::$user->rights->societe->contact->lire);
873
-                    $newmenu->add(BASE_URI . "?controller=contact&method=list&leftmenu=contacts&type=p", Globals::$langs->trans("Prospects"), 2, Globals::$user->rights->societe->contact->lire);
873
+                    $newmenu->add(BASE_URI."?controller=contact&method=list&leftmenu=contacts&type=p", Globals::$langs->trans("Prospects"), 2, Globals::$user->rights->societe->contact->lire);
874 874
                 }
875 875
                 if (empty(Conf::$global->SOCIETE_DISABLE_CUSTOMERS)) {
876 876
 //$newmenu->add("/contact/list.php?leftmenu=contacts&type=c", Globals::$langs->trans("Customers"), 2, Globals::$user->rights->societe->contact->lire);
877
-                    $newmenu->add(BASE_URI . "?controller=contact&method=list&leftmenu=contacts&type=c", Globals::$langs->trans("Customers"), 2, Globals::$user->rights->societe->contact->lire);
877
+                    $newmenu->add(BASE_URI."?controller=contact&method=list&leftmenu=contacts&type=c", Globals::$langs->trans("Customers"), 2, Globals::$user->rights->societe->contact->lire);
878 878
                 }
879 879
                 if (!empty($conf->fournisseur->enabled)) {
880 880
 //$newmenu->add("/contact/list.php?leftmenu=contacts&type=f", Globals::$langs->trans("Suppliers"), 2, Globals::$user->rights->societe->contact->lire);
881
-                    $newmenu->add(BASE_URI . "?controller=contact&method=list&leftmenu=contacts&type=f", Globals::$langs->trans("Suppliers"), 2, Globals::$user->rights->societe->contact->lire);
881
+                    $newmenu->add(BASE_URI."?controller=contact&method=list&leftmenu=contacts&type=f", Globals::$langs->trans("Suppliers"), 2, Globals::$user->rights->societe->contact->lire);
882 882
                 }
883 883
 //$newmenu->add("/contact/list.php?leftmenu=contacts&type=o", Globals::$langs->trans("ContactOthers"), 2, Globals::$user->rights->societe->contact->lire);
884
-                $newmenu->add(BASE_URI . "?controller=contact&methos=list&leftmenu=contacts&type=o", Globals::$langs->trans("ContactOthers"), 2, Globals::$user->rights->societe->contact->lire);
884
+                $newmenu->add(BASE_URI."?controller=contact&methos=list&leftmenu=contacts&type=o", Globals::$langs->trans("ContactOthers"), 2, Globals::$user->rights->societe->contact->lire);
885 885
 //$newmenu->add("/contact/list.php?userid=Globals::$user->id", Globals::$langs->trans("MyContacts"), 1, Globals::$user->rights->societe->contact->lire);
886 886
 // Categories
887 887
                 if (!empty($conf->categorie->enabled)) {
888 888
                     Globals::$langs->load("categories");
889 889
 // Categories Contact
890 890
 //$newmenu->add("/categories/index.php?leftmenu=catcontact&type=4", Globals::$langs->trans("ContactCategoriesShort"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
891
-                    $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=catcontact&type=4", Globals::$langs->trans("ContactCategoriesShort"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
891
+                    $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=catcontact&type=4", Globals::$langs->trans("ContactCategoriesShort"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
892 892
                 }
893 893
             }
894 894
 
@@ -904,9 +904,9 @@  discard block
 block discarded – undo
904 904
 //$newmenu->add("/comm/propal/index.php?leftmenu=propals", Globals::$langs->trans("Proposals"), 0, Globals::$user->rights->propale->lire, '', $mainmenu, 'propals', 100);
905 905
 //$newmenu->add("/comm/propal/card.php?action=create&leftmenu=propals", Globals::$langs->trans("NewPropal"), 1, Globals::$user->rights->propale->creer);
906 906
 //$newmenu->add("/comm/propal/list.php?leftmenu=propals", Globals::$langs->trans("List"), 1, Globals::$user->rights->propale->lire);
907
-                    $newmenu->add(BASE_URI . "?controller=comm/propal&method=index&leftmenu=propals", Globals::$langs->trans("Proposals"), 0, Globals::$user->rights->propale->lire, '', $mainmenu, 'propals', 100);
908
-                    $newmenu->add(BASE_URI . "?controller=comm/propal&method=card&action=create&leftmenu=propals", Globals::$langs->trans("NewPropal"), 1, Globals::$user->rights->propale->creer);
909
-                    $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals", Globals::$langs->trans("List"), 1, Globals::$user->rights->propale->lire);
907
+                    $newmenu->add(BASE_URI."?controller=comm/propal&method=index&leftmenu=propals", Globals::$langs->trans("Proposals"), 0, Globals::$user->rights->propale->lire, '', $mainmenu, 'propals', 100);
908
+                    $newmenu->add(BASE_URI."?controller=comm/propal&method=card&action=create&leftmenu=propals", Globals::$langs->trans("NewPropal"), 1, Globals::$user->rights->propale->creer);
909
+                    $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals", Globals::$langs->trans("List"), 1, Globals::$user->rights->propale->lire);
910 910
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "propals") {
911 911
                         /*
912 912
                           $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=0", Globals::$langs->trans("PropalsDraft"), 2, Globals::$user->rights->propale->lire);
@@ -915,15 +915,15 @@  discard block
 block discarded – undo
915 915
                           $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=3", Globals::$langs->trans("PropalStatusNotSigned"), 2, Globals::$user->rights->propale->lire);
916 916
                           $newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=4", Globals::$langs->trans("PropalStatusBilled"), 2, Globals::$user->rights->propale->lire);
917 917
                          */
918
-                        $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals&viewstatut=0", Globals::$langs->trans("PropalsDraft"), 2, Globals::$user->rights->propale->lire);
919
-                        $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals&viewstatut=1", Globals::$langs->trans("PropalsOpened"), 2, Globals::$user->rights->propale->lire);
920
-                        $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals&viewstatut=2", Globals::$langs->trans("PropalStatusSigned"), 2, Globals::$user->rights->propale->lire);
921
-                        $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals&viewstatut=3", Globals::$langs->trans("PropalStatusNotSigned"), 2, Globals::$user->rights->propale->lire);
922
-                        $newmenu->add(BASE_URI . "?controller=comm/propal&method=list&leftmenu=propals&viewstatut=4", Globals::$langs->trans("PropalStatusBilled"), 2, Globals::$user->rights->propale->lire);
918
+                        $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals&viewstatut=0", Globals::$langs->trans("PropalsDraft"), 2, Globals::$user->rights->propale->lire);
919
+                        $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals&viewstatut=1", Globals::$langs->trans("PropalsOpened"), 2, Globals::$user->rights->propale->lire);
920
+                        $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals&viewstatut=2", Globals::$langs->trans("PropalStatusSigned"), 2, Globals::$user->rights->propale->lire);
921
+                        $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals&viewstatut=3", Globals::$langs->trans("PropalStatusNotSigned"), 2, Globals::$user->rights->propale->lire);
922
+                        $newmenu->add(BASE_URI."?controller=comm/propal&method=list&leftmenu=propals&viewstatut=4", Globals::$langs->trans("PropalStatusBilled"), 2, Globals::$user->rights->propale->lire);
923 923
 //$newmenu->add("/comm/propal/list.php?leftmenu=propals&viewstatut=2,3,4", Globals::$langs->trans("PropalStatusClosedShort"), 2, Globals::$user->rights->propale->lire);
924 924
                     }
925 925
 //$newmenu->add("/comm/propal/stats/index.php?leftmenu=propals", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->propale->lire);
926
-                    $newmenu->add(BASE_URI . "?controller=comm/propal/stats&method=index&leftmenu=propals", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->propale->lire);
926
+                    $newmenu->add(BASE_URI."?controller=comm/propal/stats&method=index&leftmenu=propals", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->propale->lire);
927 927
                 }
928 928
 
929 929
 // Customers orders
@@ -932,26 +932,26 @@  discard block
 block discarded – undo
932 932
 //$newmenu->add("/commande/index.php?leftmenu=orders", Globals::$langs->trans("CustomersOrders"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders', 200);
933 933
 //$newmenu->add("/commande/card.php?action=create&leftmenu=orders", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->commande->creer);
934 934
 //$newmenu->add("/commande/list.php?leftmenu=orders", Globals::$langs->trans("List"), 1, Globals::$user->rights->commande->lire);
935
-                    $newmenu->add(BASE_URI . "?controller=commande&method=index&leftmenu=orders", Globals::$langs->trans("CustomersOrders"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders', 200);
936
-                    $newmenu->add(BASE_URI . "?controller=commande&method=card&action=create&leftmenu=orders", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->commande->creer);
937
-                    $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders", Globals::$langs->trans("List"), 1, Globals::$user->rights->commande->lire);
935
+                    $newmenu->add(BASE_URI."?controller=commande&method=index&leftmenu=orders", Globals::$langs->trans("CustomersOrders"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders', 200);
936
+                    $newmenu->add(BASE_URI."?controller=commande&method=card&action=create&leftmenu=orders", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->commande->creer);
937
+                    $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders", Globals::$langs->trans("List"), 1, Globals::$user->rights->commande->lire);
938 938
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "orders") {
939 939
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->commande->lire);
940 940
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->commande->lire);
941
-                        $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->commande->lire);
942
-                        $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->commande->lire);
941
+                        $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->commande->lire);
942
+                        $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->commande->lire);
943 943
                         if (!empty($conf->expedition->enabled)) {
944 944
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=2", Globals::$langs->trans("StatusOrderSentShort"), 2, Globals::$user->rights->commande->lire);
945
-                            $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=2", Globals::$langs->trans("StatusOrderSentShort"), 2, Globals::$user->rights->commande->lire);
945
+                            $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=2", Globals::$langs->trans("StatusOrderSentShort"), 2, Globals::$user->rights->commande->lire);
946 946
                         }
947 947
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=3", Globals::$langs->trans("StatusOrderDelivered"), 2, Globals::$user->rights->commande->lire);
948
-                        $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=3", Globals::$langs->trans("StatusOrderDelivered"), 2, Globals::$user->rights->commande->lire);
948
+                        $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=3", Globals::$langs->trans("StatusOrderDelivered"), 2, Globals::$user->rights->commande->lire);
949 949
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=4", Globals::$langs->trans("StatusOrderProcessed"), 2, Globals::$user->rights->commande->lire);
950 950
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=-1", Globals::$langs->trans("StatusOrderCanceledShort"), 2, Globals::$user->rights->commande->lire);
951
-                        $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=-1", Globals::$langs->trans("StatusOrderCanceledShort"), 2, Globals::$user->rights->commande->lire);
951
+                        $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=-1", Globals::$langs->trans("StatusOrderCanceledShort"), 2, Globals::$user->rights->commande->lire);
952 952
                     }
953 953
 //$newmenu->add("/commande/stats/index.php?leftmenu=orders", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->commande->lire);
954
-                    $newmenu->add(BASE_URI . "?controller=commande/stats&method=index&leftmenu=orders", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->commande->lire);
954
+                    $newmenu->add(BASE_URI."?controller=commande/stats&method=index&leftmenu=orders", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->commande->lire);
955 955
                 }
956 956
 
957 957
 // Suppliers orders
@@ -960,16 +960,16 @@  discard block
 block discarded – undo
960 960
 //$newmenu->add("/fourn/commande/index.php?leftmenu=orders_suppliers", Globals::$langs->trans("SuppliersOrders"), 0, Globals::$user->rights->fournisseur->commande->lire, '', $mainmenu, 'orders_suppliers', 400);
961 961
 //$newmenu->add("/fourn/commande/card.php?action=create&leftmenu=orders_suppliers", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->fournisseur->commande->creer);
962 962
 //$newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->commande->lire);
963
-                    $newmenu->add(BASE_URI . "?controller=fourn/commande&method=index&leftmenu=orders_suppliers", Globals::$langs->trans("SuppliersOrders"), 0, Globals::$user->rights->fournisseur->commande->lire, '', $mainmenu, 'orders_suppliers', 400);
964
-                    $newmenu->add(BASE_URI . "?controller=fourn/commande&method=card&action=create&leftmenu=orders_suppliers", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->fournisseur->commande->creer);
965
-                    $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->commande->lire);
963
+                    $newmenu->add(BASE_URI."?controller=fourn/commande&method=index&leftmenu=orders_suppliers", Globals::$langs->trans("SuppliersOrders"), 0, Globals::$user->rights->fournisseur->commande->lire, '', $mainmenu, 'orders_suppliers', 400);
964
+                    $newmenu->add(BASE_URI."?controller=fourn/commande&method=card&action=create&leftmenu=orders_suppliers", Globals::$langs->trans("NewOrder"), 1, Globals::$user->rights->fournisseur->commande->creer);
965
+                    $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->commande->lire);
966 966
 
967 967
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "orders_suppliers") {
968 968
 //$newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
969
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
969
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=0", Globals::$langs->trans("StatusOrderDraftShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
970 970
                         if (empty(Conf::$global->SUPPLIER_ORDER_HIDE_VALIDATED)) {
971 971
 //$newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->fournisseur->commande->lire);
972
-                            $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->fournisseur->commande->lire);
972
+                            $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=1", Globals::$langs->trans("StatusOrderValidated"), 2, Globals::$user->rights->fournisseur->commande->lire);
973 973
                         }
974 974
                         /*
975 975
                           $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=2", Globals::$langs->trans("StatusOrderApprovedShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
@@ -979,16 +979,16 @@  discard block
 block discarded – undo
979 979
                           $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=6,7", Globals::$langs->trans("StatusOrderCanceled"), 2, Globals::$user->rights->fournisseur->commande->lire);
980 980
                           $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&statut=9", Globals::$langs->trans("StatusOrderRefused"), 2, Globals::$user->rights->fournisseur->commande->lire);
981 981
                          */
982
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=2", Globals::$langs->trans("StatusOrderApprovedShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
983
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=3", Globals::$langs->trans("StatusOrderOnProcessShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
984
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=4", Globals::$langs->trans("StatusOrderReceivedPartiallyShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
985
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=5", Globals::$langs->trans("StatusOrderReceivedAll"), 2, Globals::$user->rights->fournisseur->commande->lire);
986
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=6,7", Globals::$langs->trans("StatusOrderCanceled"), 2, Globals::$user->rights->fournisseur->commande->lire);
987
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=9", Globals::$langs->trans("StatusOrderRefused"), 2, Globals::$user->rights->fournisseur->commande->lire);
982
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=2", Globals::$langs->trans("StatusOrderApprovedShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
983
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=3", Globals::$langs->trans("StatusOrderOnProcessShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
984
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=4", Globals::$langs->trans("StatusOrderReceivedPartiallyShort"), 2, Globals::$user->rights->fournisseur->commande->lire);
985
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=5", Globals::$langs->trans("StatusOrderReceivedAll"), 2, Globals::$user->rights->fournisseur->commande->lire);
986
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=6,7", Globals::$langs->trans("StatusOrderCanceled"), 2, Globals::$user->rights->fournisseur->commande->lire);
987
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders_suppliers&statut=9", Globals::$langs->trans("StatusOrderRefused"), 2, Globals::$user->rights->fournisseur->commande->lire);
988 988
                     }
989 989
 // Billed is another field. We should add instead a dedicated filter on list. if ($usemenuhider || empty($leftmenu) || $leftmenu=="orders_suppliers") $newmenu->add("/fourn/commande/list.php?leftmenu=orders_suppliers&billed=1", Globals::$langs->trans("StatusOrderBilled"), 2, Globals::$user->rights->fournisseur->commande->lire);
990 990
 //$newmenu->add("/commande/stats/index.php?leftmenu=orders_suppliers&mode=supplier", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
991
-                    $newmenu->add(BASE_URI . "?controller=commande/stats&method=index&leftmenu=orders_suppliers&mode=supplier", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
991
+                    $newmenu->add(BASE_URI."?controller=commande/stats&method=index&leftmenu=orders_suppliers&mode=supplier", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
992 992
                 }
993 993
 
994 994
 // Contrat
@@ -1000,10 +1000,10 @@  discard block
 block discarded – undo
1000 1000
                       $newmenu->add("/contrat/list.php?leftmenu=contracts", Globals::$langs->trans("List"), 1, Globals::$user->rights->contrat->lire);
1001 1001
                       $newmenu->add("/contrat/services_list.php?leftmenu=contracts", Globals::$langs->trans("MenuServices"), 1, Globals::$user->rights->contrat->lire);
1002 1002
                      */
1003
-                    $newmenu->add(BASE_URI . "?controller=contrat&method=index&leftmenu=contracts", Globals::$langs->trans("ContractsSubscriptions"), 0, Globals::$user->rights->contrat->lire, '', $mainmenu, 'contracts', 2000);
1004
-                    $newmenu->add(BASE_URI . "?controller=contrat&method=card&action=create&leftmenu=contracts", Globals::$langs->trans("NewContractSubscription"), 1, Globals::$user->rights->contrat->creer);
1005
-                    $newmenu->add(BASE_URI . "?controller=contrat&method=list&leftmenu=contracts", Globals::$langs->trans("List"), 1, Globals::$user->rights->contrat->lire);
1006
-                    $newmenu->add(BASE_URI . "?controller=contrat&method=services_list&leftmenu=contracts", Globals::$langs->trans("MenuServices"), 1, Globals::$user->rights->contrat->lire);
1003
+                    $newmenu->add(BASE_URI."?controller=contrat&method=index&leftmenu=contracts", Globals::$langs->trans("ContractsSubscriptions"), 0, Globals::$user->rights->contrat->lire, '', $mainmenu, 'contracts', 2000);
1004
+                    $newmenu->add(BASE_URI."?controller=contrat&method=card&action=create&leftmenu=contracts", Globals::$langs->trans("NewContractSubscription"), 1, Globals::$user->rights->contrat->creer);
1005
+                    $newmenu->add(BASE_URI."?controller=contrat&method=list&leftmenu=contracts", Globals::$langs->trans("List"), 1, Globals::$user->rights->contrat->lire);
1006
+                    $newmenu->add(BASE_URI."?controller=contrat&method=services_list&leftmenu=contracts", Globals::$langs->trans("MenuServices"), 1, Globals::$user->rights->contrat->lire);
1007 1007
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "contracts") {
1008 1008
                         /*
1009 1009
                           $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=0", Globals::$langs->trans("MenuInactiveServices"), 2, Globals::$user->rights->contrat->lire);
@@ -1011,10 +1011,10 @@  discard block
 block discarded – undo
1011 1011
                           $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=4&filter=expired", Globals::$langs->trans("MenuExpiredServices"), 2, Globals::$user->rights->contrat->lire);
1012 1012
                           $newmenu->add("/contrat/services_list.php?leftmenu=contracts&mode=5", Globals::$langs->trans("MenuClosedServices"), 2, Globals::$user->rights->contrat->lire);
1013 1013
                          */
1014
-                        $newmenu->add(BASE_URI . "?controller=contrat&method=services_list&leftmenu=contracts&mode=0", Globals::$langs->trans("MenuInactiveServices"), 2, Globals::$user->rights->contrat->lire);
1015
-                        $newmenu->add(BASE_URI . "?controller=contrat&method=services_list&leftmenu=contracts&mode=4", Globals::$langs->trans("MenuRunningServices"), 2, Globals::$user->rights->contrat->lire);
1016
-                        $newmenu->add(BASE_URI . "?controller=contrat&method=services_list&leftmenu=contracts&mode=4&filter=expired", Globals::$langs->trans("MenuExpiredServices"), 2, Globals::$user->rights->contrat->lire);
1017
-                        $newmenu->add(BASE_URI . "?controller=contrat&method=services_list&leftmenu=contracts&mode=5", Globals::$langs->trans("MenuClosedServices"), 2, Globals::$user->rights->contrat->lire);
1014
+                        $newmenu->add(BASE_URI."?controller=contrat&method=services_list&leftmenu=contracts&mode=0", Globals::$langs->trans("MenuInactiveServices"), 2, Globals::$user->rights->contrat->lire);
1015
+                        $newmenu->add(BASE_URI."?controller=contrat&method=services_list&leftmenu=contracts&mode=4", Globals::$langs->trans("MenuRunningServices"), 2, Globals::$user->rights->contrat->lire);
1016
+                        $newmenu->add(BASE_URI."?controller=contrat&method=services_list&leftmenu=contracts&mode=4&filter=expired", Globals::$langs->trans("MenuExpiredServices"), 2, Globals::$user->rights->contrat->lire);
1017
+                        $newmenu->add(BASE_URI."?controller=contrat&method=services_list&leftmenu=contracts&mode=5", Globals::$langs->trans("MenuClosedServices"), 2, Globals::$user->rights->contrat->lire);
1018 1018
                     }
1019 1019
                 }
1020 1020
 
@@ -1028,11 +1028,11 @@  discard block
 block discarded – undo
1028 1028
                       $newmenu->add("/fichinter/card-red.php?leftmenu=ficheinter", Globals::$langs->trans("ModelList"), 1, Globals::$user->rights->ficheinter->lire, '', '', '', 203);
1029 1029
                       $newmenu->add("/fichinter/stats/index.php?leftmenu=ficheinter", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
1030 1030
                      */
1031
-                    $newmenu->add(BASE_URI . "?controller=fichinter&method=index&leftmenu=ficheinter", Globals::$langs->trans("Interventions"), 0, Globals::$user->rights->ficheinter->lire, '', $mainmenu, 'ficheinter', 2200);
1032
-                    $newmenu->add(BASE_URI . "?controller=fichinter&method=card&action=create&leftmenu=ficheinter", Globals::$langs->trans("NewIntervention"), 1, Globals::$user->rights->ficheinter->creer, '', '', '', 201);
1033
-                    $newmenu->add(BASE_URI . "?controller=fichinter&method=list&leftmenu=ficheinter", Globals::$langs->trans("List"), 1, Globals::$user->rights->ficheinter->lire, '', '', '', 202);
1034
-                    $newmenu->add(BASE_URI . "?controller=fichinter&method=card-red&leftmenu=ficheinter", Globals::$langs->trans("ModelList"), 1, Globals::$user->rights->ficheinter->lire, '', '', '', 203);
1035
-                    $newmenu->add(BASE_URI . "?controller=fichinter/stats&method=index&leftmenu=ficheinter", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
1031
+                    $newmenu->add(BASE_URI."?controller=fichinter&method=index&leftmenu=ficheinter", Globals::$langs->trans("Interventions"), 0, Globals::$user->rights->ficheinter->lire, '', $mainmenu, 'ficheinter', 2200);
1032
+                    $newmenu->add(BASE_URI."?controller=fichinter&method=card&action=create&leftmenu=ficheinter", Globals::$langs->trans("NewIntervention"), 1, Globals::$user->rights->ficheinter->creer, '', '', '', 201);
1033
+                    $newmenu->add(BASE_URI."?controller=fichinter&method=list&leftmenu=ficheinter", Globals::$langs->trans("List"), 1, Globals::$user->rights->ficheinter->lire, '', '', '', 202);
1034
+                    $newmenu->add(BASE_URI."?controller=fichinter&method=card-red&leftmenu=ficheinter", Globals::$langs->trans("ModelList"), 1, Globals::$user->rights->ficheinter->lire, '', '', '', 203);
1035
+                    $newmenu->add(BASE_URI."?controller=fichinter/stats&method=index&leftmenu=ficheinter", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->commande->lire);
1036 1036
                 }
1037 1037
             }
1038 1038
 
@@ -1050,9 +1050,9 @@  discard block
 block discarded – undo
1050 1050
                       $newmenu->add("/compta/facture/card.php?action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->facture->creer);
1051 1051
                       $newmenu->add("/compta/facture/list.php?leftmenu=customers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_list');
1052 1052
                      */
1053
-                    $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills", Globals::$langs->trans("BillsCustomers"), 0, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills');
1054
-                    $newmenu->add(BASE_URI . "?controller=compta/facture&method=card&action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->facture->creer);
1055
-                    $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_list');
1053
+                    $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills", Globals::$langs->trans("BillsCustomers"), 0, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills');
1054
+                    $newmenu->add(BASE_URI."?controller=compta/facture&method=card&action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->facture->creer);
1055
+                    $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_list');
1056 1056
 
1057 1057
                     if ($usemenuhider || empty($leftmenu) || preg_match('/customers_bills(|_draft|_notpaid|_paid|_canceled)$/', $leftmenu)) {
1058 1058
                         /*
@@ -1061,24 +1061,24 @@  discard block
 block discarded – undo
1061 1061
                           $newmenu->add("/compta/facture/list.php?leftmenu=customers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->facture->lire);
1062 1062
                           $newmenu->add("/compta/facture/list.php?leftmenu=customers_bills_canceled&search_status=3", Globals::$langs->trans("BillShortStatusCanceled"), 2, Globals::$user->rights->facture->lire);
1063 1063
                          */
1064
-                        $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills_draft&search_status=0", Globals::$langs->trans("BillShortStatusDraft"), 2, Globals::$user->rights->facture->lire);
1065
-                        $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills_notpaid&search_status=1", Globals::$langs->trans("BillShortStatusNotPaid"), 2, Globals::$user->rights->facture->lire);
1066
-                        $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->facture->lire);
1067
-                        $newmenu->add(BASE_URI . "?controller=compta/facture&method=list&leftmenu=customers_bills_canceled&search_status=3", Globals::$langs->trans("BillShortStatusCanceled"), 2, Globals::$user->rights->facture->lire);
1064
+                        $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills_draft&search_status=0", Globals::$langs->trans("BillShortStatusDraft"), 2, Globals::$user->rights->facture->lire);
1065
+                        $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills_notpaid&search_status=1", Globals::$langs->trans("BillShortStatusNotPaid"), 2, Globals::$user->rights->facture->lire);
1066
+                        $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->facture->lire);
1067
+                        $newmenu->add(BASE_URI."?controller=compta/facture&method=list&leftmenu=customers_bills_canceled&search_status=3", Globals::$langs->trans("BillShortStatusCanceled"), 2, Globals::$user->rights->facture->lire);
1068 1068
                     }
1069 1069
 //$newmenu->add("/compta/facture/invoicetemplate_list.php?leftmenu=customers_bills_templates", Globals::$langs->trans("ListOfTemplates"), 1, Globals::$user->rights->facture->creer, '', $mainmenu, 'customers_bills_templates');    // No need to see recurring invoices, if user has no permission to create invoice.
1070 1070
 //$newmenu->add("/compta/paiement/list.php?leftmenu=customers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_payment');
1071
-                    $newmenu->add(BASE_URI . "?controller=compta/facture&method=invoicetemplate_list&leftmenu=customers_bills_templates", Globals::$langs->trans("ListOfTemplates"), 1, Globals::$user->rights->facture->creer, '', $mainmenu, 'customers_bills_templates');    // No need to see recurring invoices, if user has no permission to create invoice.
1072
-                    $newmenu->add(BASE_URI . "?controller=compta/paiement&method=list&leftmenu=customers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_payment');
1071
+                    $newmenu->add(BASE_URI."?controller=compta/facture&method=invoicetemplate_list&leftmenu=customers_bills_templates", Globals::$langs->trans("ListOfTemplates"), 1, Globals::$user->rights->facture->creer, '', $mainmenu, 'customers_bills_templates'); // No need to see recurring invoices, if user has no permission to create invoice.
1072
+                    $newmenu->add(BASE_URI."?controller=compta/paiement&method=list&leftmenu=customers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_payment');
1073 1073
 
1074 1074
                     if (!empty(Conf::$global->BILL_ADD_PAYMENT_VALIDATION)) {
1075 1075
 //$newmenu->add("/compta/paiement/tovalidate.php?leftmenu=customers_bills_tovalid", Globals::$langs->trans("MenuToValid"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customer_bills_tovalid');
1076
-                        $newmenu->add(BASE_URI . "?controller=compta/paiement&method=tovalidate&leftmenu=customers_bills_tovalid", Globals::$langs->trans("MenuToValid"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customer_bills_tovalid');
1076
+                        $newmenu->add(BASE_URI."?controller=compta/paiement&method=tovalidate&leftmenu=customers_bills_tovalid", Globals::$langs->trans("MenuToValid"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customer_bills_tovalid');
1077 1077
                     }
1078 1078
 //$newmenu->add("/compta/paiement/rapport.php?leftmenu=customers_bills_reports", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_reports');
1079 1079
 //$newmenu->add("/compta/facture/stats/index.php?leftmenu=customers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_stats');
1080
-                    $newmenu->add(BASE_URI . "?controller=compta/paiement&method=rapport&leftmenu=customers_bills_reports", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_reports');
1081
-                    $newmenu->add(BASE_URI . "?controller=compta/facture/stats&method=index&leftmenu=customers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_stats');
1080
+                    $newmenu->add(BASE_URI."?controller=compta/paiement&method=rapport&leftmenu=customers_bills_reports", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_reports');
1081
+                    $newmenu->add(BASE_URI."?controller=compta/facture/stats&method=index&leftmenu=customers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->facture->lire, '', $mainmenu, 'customers_bills_stats');
1082 1082
                 }
1083 1083
 
1084 1084
 // Suppliers invoices
@@ -1087,25 +1087,25 @@  discard block
 block discarded – undo
1087 1087
 //$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills", Globals::$langs->trans("BillsSuppliers"), 0, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
1088 1088
 //$newmenu->add("/fourn/facture/card.php?leftmenu=suppliers_bills&action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->fournisseur->facture->creer, '', $mainmenu, 'suppliers_bills_create');
1089 1089
 //$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_list');
1090
-                    $newmenu->add(BASE_URI . "?controller=fourn/facture&method=list&leftmenu=suppliers_bills", Globals::$langs->trans("BillsSuppliers"), 0, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
1091
-                    $newmenu->add(BASE_URI . "?controller=fourn/facture&method=card&leftmenu=suppliers_bills&action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->fournisseur->facture->creer, '', $mainmenu, 'suppliers_bills_create');
1092
-                    $newmenu->add(BASE_URI . "?controller=fourn/facture&method=list&leftmenu=suppliers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_list');
1090
+                    $newmenu->add(BASE_URI."?controller=fourn/facture&method=list&leftmenu=suppliers_bills", Globals::$langs->trans("BillsSuppliers"), 0, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills');
1091
+                    $newmenu->add(BASE_URI."?controller=fourn/facture&method=card&leftmenu=suppliers_bills&action=create", Globals::$langs->trans("NewBill"), 1, Globals::$user->rights->fournisseur->facture->creer, '', $mainmenu, 'suppliers_bills_create');
1092
+                    $newmenu->add(BASE_URI."?controller=fourn/facture&method=list&leftmenu=suppliers_bills", Globals::$langs->trans("List"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_list');
1093 1093
 
1094 1094
                     if ($usemenuhider || empty($leftmenu) || preg_match('/suppliers_bills/', $leftmenu)) {
1095 1095
 //$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills_draft&search_status=0", Globals::$langs->trans("BillShortStatusDraft"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_draft');
1096 1096
 //$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills_notpaid&search_status=1", Globals::$langs->trans("BillShortStatusNotPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_notpaid');
1097 1097
 //$newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_paid');
1098
-                        $newmenu->add(BASE_URI . "?controller=fourn/facture&method=list&leftmenu=suppliers_bills_draft&search_status=0", Globals::$langs->trans("BillShortStatusDraft"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_draft');
1099
-                        $newmenu->add(BASE_URI . "?controller=fourn/facture&method=list&leftmenu=suppliers_bills_notpaid&search_status=1", Globals::$langs->trans("BillShortStatusNotPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_notpaid');
1100
-                        $newmenu->add(BASE_URI . "?controller=fourn/facture&method=list&leftmenu=suppliers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_paid');
1098
+                        $newmenu->add(BASE_URI."?controller=fourn/facture&method=list&leftmenu=suppliers_bills_draft&search_status=0", Globals::$langs->trans("BillShortStatusDraft"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_draft');
1099
+                        $newmenu->add(BASE_URI."?controller=fourn/facture&method=list&leftmenu=suppliers_bills_notpaid&search_status=1", Globals::$langs->trans("BillShortStatusNotPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_notpaid');
1100
+                        $newmenu->add(BASE_URI."?controller=fourn/facture&method=list&leftmenu=suppliers_bills_paid&search_status=2", Globals::$langs->trans("BillShortStatusPaid"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_paid');
1101 1101
                     }
1102 1102
 
1103 1103
 //$newmenu->add("/fourn/facture/paiement.php?leftmenu=suppliers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_payment');
1104 1104
 //$newmenu->add("/fourn/facture/rapport.php?leftmenu=suppliers_bills_report", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_report');
1105 1105
 //$newmenu->add("/compta/facture/stats/index.php?mode=supplier&leftmenu=suppliers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_stats');
1106
-                    $newmenu->add(BASE_URI . "?controller=fourn/facture&method=paiement&leftmenu=suppliers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_payment');
1107
-                    $newmenu->add(BASE_URI . "?controller=fourn/facture&method=rapport&leftmenu=suppliers_bills_report", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_report');
1108
-                    $newmenu->add(BASE_URI . "?controller=compta/facture/stats&method=index&mode=supplier&leftmenu=suppliers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_stats');
1106
+                    $newmenu->add(BASE_URI."?controller=fourn/facture&method=paiement&leftmenu=suppliers_bills_payment", Globals::$langs->trans("Payments"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_payment');
1107
+                    $newmenu->add(BASE_URI."?controller=fourn/facture&method=rapport&leftmenu=suppliers_bills_report", Globals::$langs->trans("Reportings"), 2, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_report');
1108
+                    $newmenu->add(BASE_URI."?controller=compta/facture/stats&method=index&mode=supplier&leftmenu=suppliers_bills_stats", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_stats');
1109 1109
                 }
1110 1110
 
1111 1111
 // Orders
@@ -1113,7 +1113,7 @@  discard block
 block discarded – undo
1113 1113
                     Globals::$langs->load("orders");
1114 1114
                     if (!empty($conf->facture->enabled)) {
1115 1115
 //$newmenu->add("/commande/list.php?leftmenu=orders&viewstatut=-3&billed=0&contextpage=billableorders", Globals::$langs->trans("MenuOrdersToBill2"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1116
-                        $newmenu->add(BASE_URI . "?controller=commande&method=list&leftmenu=orders&viewstatut=-3&billed=0&contextpage=billableorders", Globals::$langs->trans("MenuOrdersToBill2"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1116
+                        $newmenu->add(BASE_URI."?controller=commande&method=list&leftmenu=orders&viewstatut=-3&billed=0&contextpage=billableorders", Globals::$langs->trans("MenuOrdersToBill2"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1117 1117
                     }
1118 1118
 //                  if ($usemenuhider || empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/", Globals::$langs->trans("StatusOrderToBill"), 1, Globals::$user->rights->commande->lire);
1119 1119
                 }
@@ -1123,7 +1123,7 @@  discard block
 block discarded – undo
1123 1123
                     if (!empty(Conf::$global->SUPPLIER_MENU_ORDER_RECEIVED_INTO_INVOICE)) {
1124 1124
                         Globals::$langs->load("supplier");
1125 1125
 //$newmenu->add("/fourn/commande/list.php?leftmenu=orders&search_status=5&billed=0", Globals::$langs->trans("MenuOrdersSupplierToBill"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1126
-                        $newmenu->add(BASE_URI . "?controller=fourn/commande&method=list&leftmenu=orders&search_status=5&billed=0", Globals::$langs->trans("MenuOrdersSupplierToBill"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1126
+                        $newmenu->add(BASE_URI."?controller=fourn/commande&method=list&leftmenu=orders&search_status=5&billed=0", Globals::$langs->trans("MenuOrdersSupplierToBill"), 0, Globals::$user->rights->commande->lire, '', $mainmenu, 'orders');
1127 1127
 //                  if ($usemenuhider || empty($leftmenu) || $leftmenu=="orders") $newmenu->add("/commande/", Globals::$langs->trans("StatusOrderToBill"), 1, Globals::$user->rights->commande->lire);
1128 1128
                     }
1129 1129
                 }
@@ -1133,12 +1133,12 @@  discard block
 block discarded – undo
1133 1133
                 if (!empty($conf->don->enabled)) {
1134 1134
                     Globals::$langs->load("donations");
1135 1135
 //$newmenu->add("/don/index.php?leftmenu=donations&mainmenu=billing", Globals::$langs->trans("Donations"), 0, Globals::$user->rights->don->lire, '', $mainmenu, 'donations');
1136
-                    $newmenu->add(BASE_URI . "?controller=don&method=index&leftmenu=donations&mainmenu=billing", Globals::$langs->trans("Donations"), 0, Globals::$user->rights->don->lire, '', $mainmenu, 'donations');
1136
+                    $newmenu->add(BASE_URI."?controller=don&method=index&leftmenu=donations&mainmenu=billing", Globals::$langs->trans("Donations"), 0, Globals::$user->rights->don->lire, '', $mainmenu, 'donations');
1137 1137
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "donations") {
1138 1138
 //$newmenu->add("/don/card.php?leftmenu=donations&action=create", Globals::$langs->trans("NewDonation"), 1, Globals::$user->rights->don->creer);
1139 1139
 //$newmenu->add("/don/list.php?leftmenu=donations", Globals::$langs->trans("List"), 1, Globals::$user->rights->don->lire);
1140
-                        $newmenu->add(BASE_URI . "?controller=don&method=card&leftmenu=donations&action=create", Globals::$langs->trans("NewDonation"), 1, Globals::$user->rights->don->creer);
1141
-                        $newmenu->add(BASE_URI . "?controller=don&method=list&leftmenu=donations", Globals::$langs->trans("List"), 1, Globals::$user->rights->don->lire);
1140
+                        $newmenu->add(BASE_URI."?controller=don&method=card&leftmenu=donations&action=create", Globals::$langs->trans("NewDonation"), 1, Globals::$user->rights->don->creer);
1141
+                        $newmenu->add(BASE_URI."?controller=don&method=list&leftmenu=donations", Globals::$langs->trans("List"), 1, Globals::$user->rights->don->lire);
1142 1142
                     }
1143 1143
 // if ($leftmenu=="donations") $newmenu->add("/don/stats/index.php",Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->don->lire);
1144 1144
                 }
@@ -1149,24 +1149,24 @@  discard block
 block discarded – undo
1149 1149
 
1150 1150
                     $permtoshowmenu = ((!empty($conf->tax->enabled) && Globals::$user->rights->tax->charges->lire) || (!empty($conf->salaries->enabled) && !empty(Globals::$user->rights->salaries->read)) || (!empty($conf->loan->enabled) && Globals::$user->rights->loan->read) || (!empty($conf->banque->enabled) && Globals::$user->rights->banque->lire));
1151 1151
 //$newmenu->add("/compta/charges/index.php?leftmenu=tax&mainmenu=billing", Globals::$langs->trans("MenuSpecialExpenses"), 0, $permtoshowmenu, '', $mainmenu, 'tax');
1152
-                    $newmenu->add(BASE_URI . "?controller=compta/charges&method=index&leftmenu=tax&mainmenu=billing", Globals::$langs->trans("MenuSpecialExpenses"), 0, $permtoshowmenu, '', $mainmenu, 'tax');
1152
+                    $newmenu->add(BASE_URI."?controller=compta/charges&method=index&leftmenu=tax&mainmenu=billing", Globals::$langs->trans("MenuSpecialExpenses"), 0, $permtoshowmenu, '', $mainmenu, 'tax');
1153 1153
 
1154 1154
 // Social contributions
1155 1155
                     if (!empty($conf->tax->enabled)) {
1156 1156
 //$newmenu->add("/compta/sociales/list.php?leftmenu=tax_social", Globals::$langs->trans("MenuSocialContributions"), 1, Globals::$user->rights->tax->charges->lire);
1157
-                        $newmenu->add(BASE_URI . "?controller=compta/sociales&method=list&leftmenu=tax_social", Globals::$langs->trans("MenuSocialContributions"), 1, Globals::$user->rights->tax->charges->lire);
1157
+                        $newmenu->add(BASE_URI."?controller=compta/sociales&method=list&leftmenu=tax_social", Globals::$langs->trans("MenuSocialContributions"), 1, Globals::$user->rights->tax->charges->lire);
1158 1158
                         if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_social/i', $leftmenu)) {
1159 1159
 //$newmenu->add("/compta/sociales/card.php?leftmenu=tax_social&action=create", Globals::$langs->trans("MenuNewSocialContribution"), 2, Globals::$user->rights->tax->charges->creer);
1160 1160
 //$newmenu->add("/compta/sociales/list.php?leftmenu=tax_social", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1161 1161
 //$newmenu->add("/compta/sociales/payments.php?leftmenu=tax_social&mainmenu=billing&mode=sconly", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->tax->charges->lire);
1162
-                            $newmenu->add(BASE_URI . "?controller=compta/sociales&method=card&leftmenu=tax_social&action=create", Globals::$langs->trans("MenuNewSocialContribution"), 2, Globals::$user->rights->tax->charges->creer);
1163
-                            $newmenu->add(BASE_URI . "?controller=compta/sociales&method=list&leftmenu=tax_social", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1164
-                            $newmenu->add(BASE_URI . "?controller=compta/sociales&method=payments&leftmenu=tax_social&mainmenu=billing&mode=sconly", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->tax->charges->lire);
1162
+                            $newmenu->add(BASE_URI."?controller=compta/sociales&method=card&leftmenu=tax_social&action=create", Globals::$langs->trans("MenuNewSocialContribution"), 2, Globals::$user->rights->tax->charges->creer);
1163
+                            $newmenu->add(BASE_URI."?controller=compta/sociales&method=list&leftmenu=tax_social", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1164
+                            $newmenu->add(BASE_URI."?controller=compta/sociales&method=payments&leftmenu=tax_social&mainmenu=billing&mode=sconly", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->tax->charges->lire);
1165 1165
                         }
1166 1166
 // VAT
1167 1167
                         if (empty(Conf::$global->TAX_DISABLE_VAT_MENUS)) {
1168 1168
 //$newmenu->add("/compta/tva/list.php?leftmenu=tax_vat&mainmenu=billing", Globals::$langs->transcountry("VAT", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire, '', $mainmenu, 'tax_vat');
1169
-                            $newmenu->add(BASE_URI . "?controller=compta/tva&method=list&leftmenu=tax_vat&mainmenu=billing", Globals::$langs->transcountry("VAT", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire, '', $mainmenu, 'tax_vat');
1169
+                            $newmenu->add(BASE_URI."?controller=compta/tva&method=list&leftmenu=tax_vat&mainmenu=billing", Globals::$langs->transcountry("VAT", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire, '', $mainmenu, 'tax_vat');
1170 1170
                             if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_vat/i', $leftmenu)) {
1171 1171
                                 /*
1172 1172
                                   $newmenu->add("/compta/tva/card.php?leftmenu=tax_vat&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
@@ -1175,18 +1175,18 @@  discard block
 block discarded – undo
1175 1175
                                   $newmenu->add("/compta/tva/clients.php?leftmenu=tax_vat", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1176 1176
                                   $newmenu->add("/compta/tva/quadri_detail.php?leftmenu=tax_vat", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1177 1177
                                  */
1178
-                                $newmenu->add(BASE_URI . "?controller=compta/tva&method=card&leftmenu=tax_vat&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1179
-                                $newmenu->add(BASE_URI . "?controller=compta/tva&method=list&leftmenu=tax_vat", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1180
-                                $newmenu->add(BASE_URI . "?controller=compta/tva&method=index&leftmenu=tax_vat", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1181
-                                $newmenu->add(BASE_URI . "?controller=compta/tva&method=clients&leftmenu=tax_vat", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1182
-                                $newmenu->add(BASE_URI . "?controller=compta/tva&method=quadri_detail&leftmenu=tax_vat", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1178
+                                $newmenu->add(BASE_URI."?controller=compta/tva&method=card&leftmenu=tax_vat&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1179
+                                $newmenu->add(BASE_URI."?controller=compta/tva&method=list&leftmenu=tax_vat", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1180
+                                $newmenu->add(BASE_URI."?controller=compta/tva&method=index&leftmenu=tax_vat", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1181
+                                $newmenu->add(BASE_URI."?controller=compta/tva&method=clients&leftmenu=tax_vat", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1182
+                                $newmenu->add(BASE_URI."?controller=compta/tva&method=quadri_detail&leftmenu=tax_vat", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1183 1183
                             }
1184 1184
                             global $mysoc;
1185 1185
 
1186 1186
 //Local Taxes 1
1187 1187
                             if ($mysoc->useLocalTax(1) && (isset($mysoc->localtax1_assuj) && $mysoc->localtax1_assuj == "1")) {
1188 1188
 //$newmenu->add("/compta/localtax/list.php?leftmenu=tax_1_vat&mainmenu=billing&localTaxType=1", Globals::$langs->transcountry("LT1", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1189
-                                $newmenu->add(BASE_URI . "?controller=compta/localtax&method=list&leftmenu=tax_1_vat&mainmenu=billing&localTaxType=1", Globals::$langs->transcountry("LT1", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1189
+                                $newmenu->add(BASE_URI."?controller=compta/localtax&method=list&leftmenu=tax_1_vat&mainmenu=billing&localTaxType=1", Globals::$langs->transcountry("LT1", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1190 1190
                                 if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_1_vat/i', $leftmenu)) {
1191 1191
                                     /*
1192 1192
                                       $newmenu->add("/compta/localtax/card.php?leftmenu=tax_1_vat&action=create&localTaxType=1", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
@@ -1195,17 +1195,17 @@  discard block
 block discarded – undo
1195 1195
                                       $newmenu->add("/compta/localtax/clients.php?leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1196 1196
                                       $newmenu->add("/compta/localtax/quadri_detail.php?leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1197 1197
                                      */
1198
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=card&leftmenu=tax_1_vat&action=create&localTaxType=1", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1199
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=list&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1200
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=index&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1201
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=clients&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1202
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=quadri_detail&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1198
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=card&leftmenu=tax_1_vat&action=create&localTaxType=1", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1199
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=list&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1200
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=index&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1201
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=clients&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1202
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=quadri_detail&leftmenu=tax_1_vat&localTaxType=1", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1203 1203
                                 }
1204 1204
                             }
1205 1205
 //Local Taxes 2
1206 1206
                             if ($mysoc->useLocalTax(2) && (isset($mysoc->localtax2_assuj) && $mysoc->localtax2_assuj == "1")) {
1207 1207
 //$newmenu->add("/compta/localtax/list.php?leftmenu=tax_2_vat&mainmenu=billing&localTaxType=2", Globals::$langs->transcountry("LT2", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1208
-                                $newmenu->add(BASE_URI . "?controller=compta/localtax&method=list&leftmenu=tax_2_vat&mainmenu=billing&localTaxType=2", Globals::$langs->transcountry("LT2", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1208
+                                $newmenu->add(BASE_URI."?controller=compta/localtax&method=list&leftmenu=tax_2_vat&mainmenu=billing&localTaxType=2", Globals::$langs->transcountry("LT2", $mysoc->country_code), 1, Globals::$user->rights->tax->charges->lire);
1209 1209
                                 if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_2_vat/i', $leftmenu)) {
1210 1210
                                     /*
1211 1211
                                       $newmenu->add("/compta/localtax/card.php?leftmenu=tax_2_vat&action=create&localTaxType=2", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
@@ -1214,11 +1214,11 @@  discard block
 block discarded – undo
1214 1214
                                       $newmenu->add("/compta/localtax/clients.php?leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1215 1215
                                       $newmenu->add("/compta/localtax/quadri_detail.php?leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1216 1216
                                      */
1217
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=card&leftmenu=tax_2_vat&action=create&localTaxType=2", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1218
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=list&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1219
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=index&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1220
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=clients&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1221
-                                    $newmenu->add(BASE_URI . "?controller=compta/localtax&method=quadri_detail&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1217
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=card&leftmenu=tax_2_vat&action=create&localTaxType=2", Globals::$langs->trans("New"), 2, Globals::$user->rights->tax->charges->creer);
1218
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=list&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("List"), 2, Globals::$user->rights->tax->charges->lire);
1219
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=index&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByMonth"), 2, Globals::$user->rights->tax->charges->lire);
1220
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=clients&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByCustomers"), 2, Globals::$user->rights->tax->charges->lire);
1221
+                                    $newmenu->add(BASE_URI."?controller=compta/localtax&method=quadri_detail&leftmenu=tax_2_vat&localTaxType=2", Globals::$langs->trans("ReportByQuarter"), 2, Globals::$user->rights->tax->charges->lire);
1222 1222
                                 }
1223 1223
                             }
1224 1224
                         }
@@ -1228,14 +1228,14 @@  discard block
 block discarded – undo
1228 1228
                     if (!empty($conf->salaries->enabled)) {
1229 1229
                         Globals::$langs->load("salaries");
1230 1230
 //$newmenu->add("/compta/salaries/list.php?leftmenu=tax_salary&mainmenu=billing", Globals::$langs->trans("Salaries"), 1, Globals::$user->rights->salaries->read, '', $mainmenu, 'tax_salary');
1231
-                        $newmenu->add(BASE_URI . "?controller=compta/salaries&method=list&leftmenu=tax_salary&mainmenu=billing", Globals::$langs->trans("Salaries"), 1, Globals::$user->rights->salaries->read, '', $mainmenu, 'tax_salary');
1231
+                        $newmenu->add(BASE_URI."?controller=compta/salaries&method=list&leftmenu=tax_salary&mainmenu=billing", Globals::$langs->trans("Salaries"), 1, Globals::$user->rights->salaries->read, '', $mainmenu, 'tax_salary');
1232 1232
                         if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_salary/i', $leftmenu)) {
1233 1233
 //$newmenu->add("/compta/salaries/card.php?leftmenu=tax_salary&action=create", Globals::$langs->trans("NewPayment"), 2, Globals::$user->rights->salaries->write);
1234 1234
 //$newmenu->add("/compta/salaries/list.php?leftmenu=tax_salary", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->salaries->read);
1235 1235
 //$newmenu->add("/compta/salaries/stats/index.php?leftmenu=tax_salary", Globals::$langs->trans("Statistics"), 2, Globals::$user->rights->salaries->read);
1236
-                            $newmenu->add(BASE_URI . "?controller=compta/salaries&method=card&leftmenu=tax_salary&action=create", Globals::$langs->trans("NewPayment"), 2, Globals::$user->rights->salaries->write);
1237
-                            $newmenu->add(BASE_URI . "?controller=compta/salaries&method=list&leftmenu=tax_salary", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->salaries->read);
1238
-                            $newmenu->add(BASE_URI . "?controller=compta/salaries/stats&method=index&leftmenu=tax_salary", Globals::$langs->trans("Statistics"), 2, Globals::$user->rights->salaries->read);
1236
+                            $newmenu->add(BASE_URI."?controller=compta/salaries&method=card&leftmenu=tax_salary&action=create", Globals::$langs->trans("NewPayment"), 2, Globals::$user->rights->salaries->write);
1237
+                            $newmenu->add(BASE_URI."?controller=compta/salaries&method=list&leftmenu=tax_salary", Globals::$langs->trans("Payments"), 2, Globals::$user->rights->salaries->read);
1238
+                            $newmenu->add(BASE_URI."?controller=compta/salaries/stats&method=index&leftmenu=tax_salary", Globals::$langs->trans("Statistics"), 2, Globals::$user->rights->salaries->read);
1239 1239
                         }
1240 1240
                     }
1241 1241
 
@@ -1243,10 +1243,10 @@  discard block
 block discarded – undo
1243 1243
                     if (!empty($conf->loan->enabled)) {
1244 1244
                         Globals::$langs->load("loan");
1245 1245
 //$newmenu->add("/loan/list.php?leftmenu=tax_loan&mainmenu=billing", Globals::$langs->trans("Loans"), 1, Globals::$user->rights->loan->read, '', $mainmenu, 'tax_loan');
1246
-                        $newmenu->add(BASE_URI . "?controller=loan&method=list&leftmenu=tax_loan&mainmenu=billing", Globals::$langs->trans("Loans"), 1, Globals::$user->rights->loan->read, '', $mainmenu, 'tax_loan');
1246
+                        $newmenu->add(BASE_URI."?controller=loan&method=list&leftmenu=tax_loan&mainmenu=billing", Globals::$langs->trans("Loans"), 1, Globals::$user->rights->loan->read, '', $mainmenu, 'tax_loan');
1247 1247
                         if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_loan/i', $leftmenu)) {
1248 1248
 //$newmenu->add("/loan/card.php?leftmenu=tax_loan&action=create", Globals::$langs->trans("NewLoan"), 2, Globals::$user->rights->loan->write);
1249
-                            $newmenu->add(BASE_URI . "?controller=loan&method=card&leftmenu=tax_loan&action=create", Globals::$langs->trans("NewLoan"), 2, Globals::$user->rights->loan->write);
1249
+                            $newmenu->add(BASE_URI."?controller=loan&method=card&leftmenu=tax_loan&action=create", Globals::$langs->trans("NewLoan"), 2, Globals::$user->rights->loan->write);
1250 1250
 //$newmenu->add("/loan/payment/list.php?leftmenu=tax_loan",Globals::$langs->trans("Payments"),2,Globals::$user->rights->loan->read);
1251 1251
                         }
1252 1252
                     }
@@ -1255,12 +1255,12 @@  discard block
 block discarded – undo
1255 1255
                     if (!empty($conf->banque->enabled) && empty(Conf::$global->BANK_USE_OLD_VARIOUS_PAYMENT)) {
1256 1256
                         Globals::$langs->load("banks");
1257 1257
 //$newmenu->add("/compta/bank/various_payment/list.php?leftmenu=tax_various&mainmenu=billing", Globals::$langs->trans("MenuVariousPayment"), 1, Globals::$user->rights->banque->lire, '', $mainmenu, 'tax_various');
1258
-                        $newmenu->add(BASE_URI . "?controller=compta/bank/various_payment&method=list&leftmenu=tax_various&mainmenu=billing", Globals::$langs->trans("MenuVariousPayment"), 1, Globals::$user->rights->banque->lire, '', $mainmenu, 'tax_various');
1258
+                        $newmenu->add(BASE_URI."?controller=compta/bank/various_payment&method=list&leftmenu=tax_various&mainmenu=billing", Globals::$langs->trans("MenuVariousPayment"), 1, Globals::$user->rights->banque->lire, '', $mainmenu, 'tax_various');
1259 1259
                         if ($usemenuhider || empty($leftmenu) || preg_match('/^tax_various/i', $leftmenu)) {
1260 1260
 //$newmenu->add("/compta/bank/various_payment/card.php?leftmenu=tax_various&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->banque->modifier);
1261 1261
 //$newmenu->add("/compta/bank/various_payment/list.php?leftmenu=tax_various", Globals::$langs->trans("List"), 2, Globals::$user->rights->banque->lire);
1262
-                            $newmenu->add(BASE_URI . "?controller=compta/bank/various_payment&method=card&leftmenu=tax_various&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->banque->modifier);
1263
-                            $newmenu->add(BASE_URI . "?controller=compta/bank/various_payment&method=list&leftmenu=tax_various", Globals::$langs->trans("List"), 2, Globals::$user->rights->banque->lire);
1262
+                            $newmenu->add(BASE_URI."?controller=compta/bank/various_payment&method=card&leftmenu=tax_various&action=create", Globals::$langs->trans("New"), 2, Globals::$user->rights->banque->modifier);
1263
+                            $newmenu->add(BASE_URI."?controller=compta/bank/various_payment&method=list&leftmenu=tax_various", Globals::$langs->trans("List"), 2, Globals::$user->rights->banque->lire);
1264 1264
                         }
1265 1265
                     }
1266 1266
                 }
@@ -1278,11 +1278,11 @@  discard block
 block discarded – undo
1278 1278
 
1279 1279
                     $permtoshowmenu = (!empty($conf->accounting->enabled) || Globals::$user->rights->accounting->bind->write || Globals::$user->rights->compta->resultat->lire);
1280 1280
 //$newmenu->add("/accountancy/index.php?leftmenu=accountancy", Globals::$langs->trans("MenuAccountancy"), 0, $permtoshowmenu, '', $mainmenu, 'accountancy');
1281
-                    $newmenu->add(BASE_URI . "?controller=accountancy&method=index&leftmenu=accountancy", Globals::$langs->trans("MenuAccountancy"), 0, $permtoshowmenu, '', $mainmenu, 'accountancy');
1281
+                    $newmenu->add(BASE_URI."?controller=accountancy&method=index&leftmenu=accountancy", Globals::$langs->trans("MenuAccountancy"), 0, $permtoshowmenu, '', $mainmenu, 'accountancy');
1282 1282
 
1283 1283
 // Chart of account
1284 1284
 //$newmenu->add("/accountancy/index.php?leftmenu=accountancy_admin", Globals::$langs->trans("Setup"), 1, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin', 1);
1285
-                    $newmenu->add(BASE_URI . "?controller=accountancy&method=index&leftmenu=accountancy_admin", Globals::$langs->trans("Setup"), 1, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin', 1);
1285
+                    $newmenu->add(BASE_URI."?controller=accountancy&method=index&leftmenu=accountancy_admin", Globals::$langs->trans("Setup"), 1, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin', 1);
1286 1286
                     if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_admin/', $leftmenu)) {
1287 1287
                         /*
1288 1288
                           $newmenu->add("/accountancy/admin/index.php?mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("General"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_general', 10);
@@ -1292,71 +1292,71 @@  discard block
 block discarded – undo
1292 1292
                           $newmenu->add("/accountancy/admin/categories_list.php?id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("AccountingCategory"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 41);
1293 1293
                           $newmenu->add("/accountancy/admin/defaultaccounts.php?mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuDefaultAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
1294 1294
                          */
1295
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=index&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("General"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_general', 10);
1296
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=journals_list&id=35&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("AccountingJournals"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_journal', 20);
1297
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=accountmodel&id=31&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("Pcg_version"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chartmodel', 30);
1298
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=account&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("Chartofaccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 40);
1299
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=categories_list&id=32&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("AccountingCategory"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 41);
1300
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=defaultaccounts&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuDefaultAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
1295
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=index&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("General"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_general', 10);
1296
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=journals_list&id=35&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("AccountingJournals"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_journal', 20);
1297
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=accountmodel&id=31&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("Pcg_version"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chartmodel', 30);
1298
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=account&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("Chartofaccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 40);
1299
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=categories_list&id=32&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("AccountingCategory"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_chart', 41);
1300
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=defaultaccounts&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuDefaultAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 50);
1301 1301
                         if (!empty($conf->banque->enabled)) {
1302 1302
 //$newmenu->add("/compta/bank/list.php?mainmenu=accountancy&leftmenu=accountancy_admin&search_status=-1", Globals::$langs->trans("MenuBankAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_bank', 51);
1303
-                            $newmenu->add(BASE_URI . "?controller=compta/bank&method=list&mainmenu=accountancy&leftmenu=accountancy_admin&search_status=-1", Globals::$langs->trans("MenuBankAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_bank', 51);
1303
+                            $newmenu->add(BASE_URI."?controller=compta/bank&method=list&mainmenu=accountancy&leftmenu=accountancy_admin&search_status=-1", Globals::$langs->trans("MenuBankAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_bank', 51);
1304 1304
                         }
1305 1305
                         if (!empty($conf->facture->enabled) || !empty($conf->fournisseur->enabled)) {
1306 1306
 //$newmenu->add("/admin/dict.php?id=10&from=accountancy&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuVatAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 52);
1307
-                            $newmenu->add(BASE_URI . "?controller=admin&method=dict&id=10&from=accountancy&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuVatAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 52);
1307
+                            $newmenu->add(BASE_URI."?controller=admin&method=dict&id=10&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuVatAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 52);
1308 1308
                         }
1309 1309
                         if (!empty($conf->tax->enabled)) {
1310 1310
 //$newmenu->add("/admin/dict.php?id=7&from=accountancy&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuTaxAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 53);
1311
-                            $newmenu->add(BASE_URI . "?controller=admin&method=dict&id=7&from=accountancy&search_country_id=" . $mysoc->country_id . "&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuTaxAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 53);
1311
+                            $newmenu->add(BASE_URI."?controller=admin&method=dict&id=7&from=accountancy&search_country_id=".$mysoc->country_id."&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuTaxAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 53);
1312 1312
                         }
1313 1313
                         if (!empty($conf->expensereport->enabled)) {
1314 1314
 //$newmenu->add("/admin/dict.php?id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuExpenseReportAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 54);
1315
-                            $newmenu->add(BASE_URI . "?controller=admin&method=dict&id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuExpenseReportAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 54);
1315
+                            $newmenu->add(BASE_URI."?controller=admin&method=dict&id=17&from=accountancy&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuExpenseReportAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_default', 54);
1316 1316
                         }
1317 1317
 //$newmenu->add("/accountancy/admin/productaccount.php?mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuProductsAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_product', 55);
1318 1318
 //$newmenu->add("/accountancy/admin/export.php?mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("ExportOptions"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_export', 60);
1319
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=productaccount&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuProductsAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_product', 55);
1320
-                        $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=export&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("ExportOptions"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_export', 60);
1319
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=productaccount&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("MenuProductsAccounts"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_product', 55);
1320
+                        $newmenu->add(BASE_URI."?controller=accountancy/admin&method=export&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("ExportOptions"), 2, Globals::$user->rights->accounting->chartofaccount, '', $mainmenu, 'accountancy_admin_export', 60);
1321 1321
 
1322 1322
 // Fiscal year
1323 1323
                         if (Conf::$global->MAIN_FEATURES_LEVEL > 1) {
1324 1324
 // Not yet used. In a future will lock some periods.
1325 1325
 //$newmenu->add("/accountancy/admin/fiscalyear.php?mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("FiscalPeriod"), 2, Globals::$user->rights->accounting->fiscalyear, '', $mainmenu, 'fiscalyear');
1326
-                            $newmenu->add(BASE_URI . "?controller=accountancy/admin&method=fiscalyear&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("FiscalPeriod"), 2, Globals::$user->rights->accounting->fiscalyear, '', $mainmenu, 'fiscalyear');
1326
+                            $newmenu->add(BASE_URI."?controller=accountancy/admin&method=fiscalyear&mainmenu=accountancy&leftmenu=accountancy_admin", Globals::$langs->trans("FiscalPeriod"), 2, Globals::$user->rights->accounting->fiscalyear, '', $mainmenu, 'fiscalyear');
1327 1327
                         }
1328 1328
                     }
1329 1329
 
1330 1330
 // Binding
1331 1331
                     if (!empty($conf->facture->enabled)) {
1332 1332
 //$newmenu->add("/accountancy/customer/index.php?leftmenu=accountancy_dispatch_customer&mainmenu=accountancy", Globals::$langs->trans("CustomersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_customer');
1333
-                        $newmenu->add(BASE_URI . "?controller=accountancy/customer&method=index&leftmenu=accountancy_dispatch_customer&mainmenu=accountancy", Globals::$langs->trans("CustomersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_customer');
1333
+                        $newmenu->add(BASE_URI."?controller=accountancy/customer&method=index&leftmenu=accountancy_dispatch_customer&mainmenu=accountancy", Globals::$langs->trans("CustomersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_customer');
1334 1334
                         if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_dispatch_customer/', $leftmenu)) {
1335 1335
 //$newmenu->add("/accountancy/customer/list.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1336 1336
 //$newmenu->add("/accountancy/customer/lines.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1337
-                            $newmenu->add(BASE_URI . "?controller=accountancy/customer&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1338
-                            $newmenu->add(BASE_URI . "?controller=accountancy/customer&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1337
+                            $newmenu->add(BASE_URI."?controller=accountancy/customer&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1338
+                            $newmenu->add(BASE_URI."?controller=accountancy/customer&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_customer", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1339 1339
                         }
1340 1340
                     }
1341 1341
                     if (!empty($conf->supplier_invoice->enabled)) {
1342 1342
 //$newmenu->add("/accountancy/supplier/index.php?leftmenu=accountancy_dispatch_supplier&mainmenu=accountancy", Globals::$langs->trans("SuppliersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_supplier');
1343
-                        $newmenu->add(BASE_URI . "?controller=accountancy/supplier&method=index&leftmenu=accountancy_dispatch_supplier&mainmenu=accountancy", Globals::$langs->trans("SuppliersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_supplier');
1343
+                        $newmenu->add(BASE_URI."?controller=accountancy/supplier&method=index&leftmenu=accountancy_dispatch_supplier&mainmenu=accountancy", Globals::$langs->trans("SuppliersVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_supplier');
1344 1344
                         if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_dispatch_supplier/', $leftmenu)) {
1345 1345
 //$newmenu->add("/accountancy/supplier/list.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1346 1346
 //$newmenu->add("/accountancy/supplier/lines.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1347
-                            $newmenu->add(BASE_URI . "?controller=accountancy/supplier&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1348
-                            $newmenu->add(BASE_URI . "?controller=accountancy/supplier&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1347
+                            $newmenu->add(BASE_URI."?controller=accountancy/supplier&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1348
+                            $newmenu->add(BASE_URI."?controller=accountancy/supplier&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_supplier", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1349 1349
                         }
1350 1350
                     }
1351 1351
 
1352 1352
                     if (!empty($conf->expensereport->enabled)) {
1353 1353
 //$newmenu->add("/accountancy/expensereport/index.php?leftmenu=accountancy_dispatch_expensereport&mainmenu=accountancy", Globals::$langs->trans("ExpenseReportsVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_expensereport');
1354
-                        $newmenu->add(BASE_URI . "?controller=accountancy/expensereport&method=index&leftmenu=accountancy_dispatch_expensereport&mainmenu=accountancy", Globals::$langs->trans("ExpenseReportsVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_expensereport');
1354
+                        $newmenu->add(BASE_URI."?controller=accountancy/expensereport&method=index&leftmenu=accountancy_dispatch_expensereport&mainmenu=accountancy", Globals::$langs->trans("ExpenseReportsVentilation"), 1, Globals::$user->rights->accounting->bind->write, '', $mainmenu, 'dispatch_expensereport');
1355 1355
                         if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_dispatch_expensereport/', $leftmenu)) {
1356 1356
 //$newmenu->add("/accountancy/expensereport/list.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1357 1357
 //$newmenu->add("/accountancy/expensereport/lines.php?mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1358
-                            $newmenu->add(BASE_URI . "?controller=accountancy/expensereport&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1359
-                            $newmenu->add(BASE_URI . "?controller=accountancy/expensereport&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1358
+                            $newmenu->add(BASE_URI."?controller=accountancy/expensereport&method=list&mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("ToBind"), 2, Globals::$user->rights->accounting->bind->write);
1359
+                            $newmenu->add(BASE_URI."?controller=accountancy/expensereport&method=lines&mainmenu=accountancy&leftmenu=accountancy_dispatch_expensereport", Globals::$langs->trans("Binded"), 2, Globals::$user->rights->accounting->bind->write);
1360 1360
                         }
1361 1361
                     }
1362 1362
 
@@ -1366,8 +1366,8 @@  discard block
 block discarded – undo
1366 1366
 
1367 1367
 // Multi journal
1368 1368
                         $sql = "SELECT rowid, code, label, nature";
1369
-                        $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
1370
-                        $sql .= " WHERE entity = " . $conf->entity;
1369
+                        $sql .= " FROM ".MAIN_DB_PREFIX."accounting_journal";
1370
+                        $sql .= " WHERE entity = ".$conf->entity;
1371 1371
                         $sql .= " AND active = 1";
1372 1372
                         $sql .= " ORDER BY label DESC";
1373 1373
 
@@ -1408,7 +1408,7 @@  discard block
 block discarded – undo
1408 1408
                                         Globals::$langs->load('accountancy');
1409 1409
                                         $journallabel = Globals::$langs->transnoentities($objp->label); // Labels in this table are set by loading llx_accounting_abc.sql. Label can be 'ACCOUNTING_SELL_JOURNAL', 'InventoryJournal', ...
1410 1410
 //$newmenu->add('/accountancy/journal/' . $nature . 'journal.php?mainmenu=accountancy&leftmenu=accountancy_journal&id_journal=' . $objp->rowid, $journallabel, 2, Globals::$user->rights->accounting->comptarapport->lire);
1411
-                                        $newmenu->add(BASE_URI . '?controller=accountancy/journal&method=' . $nature . 'journal&mainmenu=accountancy&leftmenu=accountancy_journal&id_journal=' . $objp->rowid, $journallabel, 2, Globals::$user->rights->accounting->comptarapport->lire);
1411
+                                        $newmenu->add(BASE_URI.'?controller=accountancy/journal&method='.$nature.'journal&mainmenu=accountancy&leftmenu=accountancy_journal&id_journal='.$objp->rowid, $journallabel, 2, Globals::$user->rights->accounting->comptarapport->lire);
1412 1412
                                     }
1413 1413
                                     $i++;
1414 1414
                                 }
@@ -1423,31 +1423,31 @@  discard block
 block discarded – undo
1423 1423
 
1424 1424
 // General Ledger
1425 1425
 //$newmenu->add("/accountancy/bookkeeping/list.php?mainmenu=accountancy&leftmenu=accountancy_generalledger", Globals::$langs->trans("Bookkeeping"), 1, Globals::$user->rights->accounting->mouvements->lire);
1426
-                    $newmenu->add(BASE_URI . "?controller=accountancy/bookkeeping&method=list&mainmenu=accountancy&leftmenu=accountancy_generalledger", Globals::$langs->trans("Bookkeeping"), 1, Globals::$user->rights->accounting->mouvements->lire);
1426
+                    $newmenu->add(BASE_URI."?controller=accountancy/bookkeeping&method=list&mainmenu=accountancy&leftmenu=accountancy_generalledger", Globals::$langs->trans("Bookkeeping"), 1, Globals::$user->rights->accounting->mouvements->lire);
1427 1427
 
1428 1428
 // Balance
1429 1429
 //$newmenu->add("/accountancy/bookkeeping/balance.php?mainmenu=accountancy&leftmenu=accountancy_balance", Globals::$langs->trans("AccountBalance"), 1, Globals::$user->rights->accounting->mouvements->lire);
1430
-                    $newmenu->add(BASE_URI . "?controller=accountancy/bookkeeping&method=balance&mainmenu=accountancy&leftmenu=accountancy_balance", Globals::$langs->trans("AccountBalance"), 1, Globals::$user->rights->accounting->mouvements->lire);
1430
+                    $newmenu->add(BASE_URI."?controller=accountancy/bookkeeping&method=balance&mainmenu=accountancy&leftmenu=accountancy_balance", Globals::$langs->trans("AccountBalance"), 1, Globals::$user->rights->accounting->mouvements->lire);
1431 1431
 
1432 1432
 // Files
1433 1433
                     if (!empty(Conf::$global->MAIN_FEATURES_LEVEL) && Conf::$global->MAIN_FEATURES_LEVEL > 2) {
1434 1434
 //$newmenu->add("/compta/compta-files.php?mainmenu=accountancy&leftmenu=accountancy_files", Globals::$langs->trans("AccountantFiles"), 1, Globals::$user->rights->accounting->mouvements->lire);
1435
-                        $newmenu->add(BASE_URI . "?controller=compta&method=compta-files&mainmenu=accountancy&leftmenu=accountancy_files", Globals::$langs->trans("AccountantFiles"), 1, Globals::$user->rights->accounting->mouvements->lire);
1435
+                        $newmenu->add(BASE_URI."?controller=compta&method=compta-files&mainmenu=accountancy&leftmenu=accountancy_files", Globals::$langs->trans("AccountantFiles"), 1, Globals::$user->rights->accounting->mouvements->lire);
1436 1436
                     }
1437 1437
 
1438 1438
 // Reports
1439 1439
                     Globals::$langs->load("compta");
1440 1440
 
1441 1441
 //$newmenu->add("/compta/resultat/index.php?mainmenu=accountancy&leftmenu=accountancy_report", Globals::$langs->trans("Reportings"), 1, Globals::$user->rights->accounting->comptarapport->lire, '', $mainmenu, 'ca');
1442
-                    $newmenu->add(BASE_URI . "?controller=compta/resultat&method=index&mainmenu=accountancy&leftmenu=accountancy_report", Globals::$langs->trans("Reportings"), 1, Globals::$user->rights->accounting->comptarapport->lire, '', $mainmenu, 'ca');
1442
+                    $newmenu->add(BASE_URI."?controller=compta/resultat&method=index&mainmenu=accountancy&leftmenu=accountancy_report", Globals::$langs->trans("Reportings"), 1, Globals::$user->rights->accounting->comptarapport->lire, '', $mainmenu, 'ca');
1443 1443
 
1444 1444
                     if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_report/', $leftmenu)) {
1445 1445
 //$newmenu->add("/compta/resultat/index.php?leftmenu=accountancy_report", Globals::$langs->trans("MenuReportInOut"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1446 1446
 //$newmenu->add("/compta/resultat/clientfourn.php?leftmenu=accountancy_report", Globals::$langs->trans("ByPredefinedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1447 1447
 //$newmenu->add("/compta/resultat/result.php?leftmenu=accountancy_report", Globals::$langs->trans("ByPersonalizedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1448
-                        $newmenu->add(BASE_URI . "?controller=compta/resultat&method=index&leftmenu=accountancy_report", Globals::$langs->trans("MenuReportInOut"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1449
-                        $newmenu->add(BASE_URI . "?controller=compta/resultat&method=clientfourn&leftmenu=accountancy_report", Globals::$langs->trans("ByPredefinedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1450
-                        $newmenu->add(BASE_URI . "?controller=compta/resultat&method=result&leftmenu=accountancy_report", Globals::$langs->trans("ByPersonalizedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1448
+                        $newmenu->add(BASE_URI."?controller=compta/resultat&method=index&leftmenu=accountancy_report", Globals::$langs->trans("MenuReportInOut"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1449
+                        $newmenu->add(BASE_URI."?controller=compta/resultat&method=clientfourn&leftmenu=accountancy_report", Globals::$langs->trans("ByPredefinedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1450
+                        $newmenu->add(BASE_URI."?controller=compta/resultat&method=result&leftmenu=accountancy_report", Globals::$langs->trans("ByPersonalizedAccountGroups"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1451 1451
                     }
1452 1452
 
1453 1453
                     $modecompta = 'CREANCES-DETTES';
@@ -1462,11 +1462,11 @@  discard block
 block discarded – undo
1462 1462
                               $newmenu->add("/compta/stats/cabyprodserv.php?leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByProductsAndServices"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1463 1463
                               $newmenu->add("/compta/stats/byratecountry.php?leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByVatRate"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1464 1464
                              */
1465
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=index&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ReportTurnover"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1466
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=casoc&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByCompanies"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1467
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=cabyuser&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByUsers"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1468
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=cabyprodserv&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByProductsAndServices"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1469
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=byratecountry&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByVatRate"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1465
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=index&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ReportTurnover"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1466
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=casoc&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByCompanies"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1467
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=cabyuser&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByUsers"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1468
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=cabyprodserv&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByProductsAndServices"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1469
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=byratecountry&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByVatRate"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1470 1470
                         }
1471 1471
                     }
1472 1472
 
@@ -1477,9 +1477,9 @@  discard block
 block discarded – undo
1477 1477
 //$newmenu->add("/compta/stats/index.php?leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ReportTurnoverCollected"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1478 1478
 //$newmenu->add("/compta/stats/casoc.php?leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByCompanies"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1479 1479
 //$newmenu->add("/compta/stats/cabyuser.php?leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByUsers"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1480
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=index&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ReportTurnoverCollected"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1481
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=casoc&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByCompanies"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1482
-                            $newmenu->add(BASE_URI . "?controller=compta/stats&method=cabyuser&leftmenu=accountancy_report&modecompta = " . $modecompta, Globals::$langs->trans("ByUsers"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1480
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=index&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ReportTurnoverCollected"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1481
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=casoc&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByCompanies"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1482
+                            $newmenu->add(BASE_URI."?controller=compta/stats&method=cabyuser&leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByUsers"), 3, Globals::$user->rights->accounting->comptarapport->lire);
1483 1483
 //$newmenu->add("/compta/stats/cabyprodserv.php?leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByProductsAndServices"),3,Globals::$user->rights->accounting->comptarapport->lire);
1484 1484
 //$newmenu->add("/compta/stats/byratecountry.php?leftmenu=accountancy_report&modecompta = ".$modecompta, Globals::$langs->trans("ByVatRate"),3,Globals::$user->rights->accounting->comptarapport->lire);
1485 1485
                         }
@@ -1492,19 +1492,19 @@  discard block
 block discarded – undo
1492 1492
 
1493 1493
 // Bilan, resultats
1494 1494
 //$newmenu->add("/compta/resultat/index.php?leftmenu=report&mainmenu=accountancy", Globals::$langs->trans("Reportings"), 0, Globals::$user->rights->compta->resultat->lire, '', $mainmenu, 'ca');
1495
-                    $newmenu->add(BASE_URI . "?controller=compta/resultat&method=index&leftmenu=report&mainmenu=accountancy", Globals::$langs->trans("Reportings"), 0, Globals::$user->rights->compta->resultat->lire, '', $mainmenu, 'ca');
1495
+                    $newmenu->add(BASE_URI."?controller=compta/resultat&method=index&leftmenu=report&mainmenu=accountancy", Globals::$langs->trans("Reportings"), 0, Globals::$user->rights->compta->resultat->lire, '', $mainmenu, 'ca');
1496 1496
 
1497 1497
                     if ($usemenuhider || empty($leftmenu) || preg_match('/report/', $leftmenu)) {
1498 1498
 //$newmenu->add("/compta/resultat/index.php?leftmenu=report", Globals::$langs->trans("MenuReportInOut"), 1, Globals::$user->rights->compta->resultat->lire);
1499 1499
 //$newmenu->add("/compta/resultat/clientfourn.php?leftmenu=report", Globals::$langs->trans("ByCompanies"), 2, Globals::$user->rights->compta->resultat->lire);
1500
-                        $newmenu->add(BASE_URI . "?controller=compta/resultat&method=index&leftmenu=report", Globals::$langs->trans("MenuReportInOut"), 1, Globals::$user->rights->compta->resultat->lire);
1501
-                        $newmenu->add(BASE_URI . "?controller=compta/resultat&method=clientfourn&leftmenu=report", Globals::$langs->trans("ByCompanies"), 2, Globals::$user->rights->compta->resultat->lire);
1500
+                        $newmenu->add(BASE_URI."?controller=compta/resultat&method=index&leftmenu=report", Globals::$langs->trans("MenuReportInOut"), 1, Globals::$user->rights->compta->resultat->lire);
1501
+                        $newmenu->add(BASE_URI."?controller=compta/resultat&method=clientfourn&leftmenu=report", Globals::$langs->trans("ByCompanies"), 2, Globals::$user->rights->compta->resultat->lire);
1502 1502
                         /* On verra ca avec module compabilite expert
1503 1503
                           $newmenu->add("/compta/resultat/compteres.php?leftmenu=report","Compte de resultat",2,Globals::$user->rights->compta->resultat->lire);
1504 1504
                           $newmenu->add("/compta/resultat/bilan.php?leftmenu=report","Bilan",2,Globals::$user->rights->compta->resultat->lire);
1505 1505
                          */
1506 1506
 //$newmenu->add("/compta/stats/index.php?leftmenu=report", Globals::$langs->trans("ReportTurnover"), 1, Globals::$user->rights->compta->resultat->lire);
1507
-                        $newmenu->add(BASE_URI . "?controller=compta/stats&method=index&leftmenu=report", Globals::$langs->trans("ReportTurnover"), 1, Globals::$user->rights->compta->resultat->lire);
1507
+                        $newmenu->add(BASE_URI."?controller=compta/stats&method=index&leftmenu=report", Globals::$langs->trans("ReportTurnover"), 1, Globals::$user->rights->compta->resultat->lire);
1508 1508
 
1509 1509
                         /*
1510 1510
                           $newmenu->add("/compta/stats/cumul.php?leftmenu=report","Cumule",2,Globals::$user->rights->compta->resultat->lire);
@@ -1517,16 +1517,16 @@  discard block
 block discarded – undo
1517 1517
 //$newmenu->add("/compta/stats/cabyuser.php?leftmenu=report", Globals::$langs->trans("ByUsers"), 2, Globals::$user->rights->compta->resultat->lire);
1518 1518
 //$newmenu->add("/compta/stats/cabyprodserv.php?leftmenu=report", Globals::$langs->trans("ByProductsAndServices"), 2, Globals::$user->rights->compta->resultat->lire);
1519 1519
 //$newmenu->add("/compta/stats/byratecountry.php?leftmenu=report", Globals::$langs->trans("ByVatRate"), 2, Globals::$user->rights->compta->resultat->lire);
1520
-                        $newmenu->add(BASE_URI . "?controller=compta/stats&method=casoc&leftmenu=report", Globals::$langs->trans("ByCompanies"), 2, Globals::$user->rights->compta->resultat->lire);
1521
-                        $newmenu->add(BASE_URI . "?controller=compta/stats&method=cabyuser&leftmenu=report", Globals::$langs->trans("ByUsers"), 2, Globals::$user->rights->compta->resultat->lire);
1522
-                        $newmenu->add(BASE_URI . "?controller=compta/stats&method=cabyprodserv&leftmenu=report", Globals::$langs->trans("ByProductsAndServices"), 2, Globals::$user->rights->compta->resultat->lire);
1523
-                        $newmenu->add(BASE_URI . "?controller=compta/stats&method=byratecountry&leftmenu=report", Globals::$langs->trans("ByVatRate"), 2, Globals::$user->rights->compta->resultat->lire);
1520
+                        $newmenu->add(BASE_URI."?controller=compta/stats&method=casoc&leftmenu=report", Globals::$langs->trans("ByCompanies"), 2, Globals::$user->rights->compta->resultat->lire);
1521
+                        $newmenu->add(BASE_URI."?controller=compta/stats&method=cabyuser&leftmenu=report", Globals::$langs->trans("ByUsers"), 2, Globals::$user->rights->compta->resultat->lire);
1522
+                        $newmenu->add(BASE_URI."?controller=compta/stats&method=cabyprodserv&leftmenu=report", Globals::$langs->trans("ByProductsAndServices"), 2, Globals::$user->rights->compta->resultat->lire);
1523
+                        $newmenu->add(BASE_URI."?controller=compta/stats&method=byratecountry&leftmenu=report", Globals::$langs->trans("ByVatRate"), 2, Globals::$user->rights->compta->resultat->lire);
1524 1524
 
1525 1525
 // Journaux
1526 1526
 //$newmenu->add("/compta/journal/sellsjournal.php?leftmenu=report", Globals::$langs->trans("SellsJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 50);
1527 1527
 //$newmenu->add("/compta/journal/purchasesjournal.php?leftmenu=report", Globals::$langs->trans("PurchasesJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 51);
1528
-                        $newmenu->add(BASE_URI . "?controller=compta/journal&method=sellsjournal&leftmenu=report", Globals::$langs->trans("SellsJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 50);
1529
-                        $newmenu->add(BASE_URI . "?controller=compta/journal&method=purchasesjournal&leftmenu=report", Globals::$langs->trans("PurchasesJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 51);
1528
+                        $newmenu->add(BASE_URI."?controller=compta/journal&method=sellsjournal&leftmenu=report", Globals::$langs->trans("SellsJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 50);
1529
+                        $newmenu->add(BASE_URI."?controller=compta/journal&method=purchasesjournal&leftmenu=report", Globals::$langs->trans("PurchasesJournal"), 1, Globals::$user->rights->compta->resultat->lire, '', '', '', 51);
1530 1530
                     }
1531 1531
 //if ($leftmenu=="ca") $newmenu->add("/compta/journaux/index.php?leftmenu=ca",Globals::$langs->trans("Journaux"),1,Globals::$user->rights->compta->resultat->lire||Globals::$user->rights->accounting->comptarapport->lire);
1532 1532
                 }
@@ -1538,15 +1538,15 @@  discard block
 block discarded – undo
1538 1538
 //$newmenu->add("/asset/card.php?action=create", Globals::$langs->trans("MenuNewAsset"), 1, Globals::$user->rights->asset->write);
1539 1539
 //$newmenu->add("/asset/list.php?leftmenu=asset&mainmenu=accountancy", Globals::$langs->trans("MenuListAssets"), 1, Globals::$user->rights->asset->read);
1540 1540
 //$newmenu->add("/asset/type.php?leftmenu=asset_type", Globals::$langs->trans("MenuTypeAssets"), 1, Globals::$user->rights->asset->read, '', $mainmenu, 'asset_type');
1541
-                    $newmenu->add(BASE_URI . "?controller=asset&method=list&leftmenu=asset&mainmenu=accountancy", Globals::$langs->trans("MenuAssets"), 0, Globals::$user->rights->asset->read, '', $mainmenu, 'asset');
1542
-                    $newmenu->add(BASE_URI . "?controller=asset&method=card&action=create", Globals::$langs->trans("MenuNewAsset"), 1, Globals::$user->rights->asset->write);
1543
-                    $newmenu->add(BASE_URI . "?controller=asset&method=list&leftmenu=asset&mainmenu=accountancy", Globals::$langs->trans("MenuListAssets"), 1, Globals::$user->rights->asset->read);
1544
-                    $newmenu->add(BASE_URI . "?controller=asset&method=type&leftmenu=asset_type", Globals::$langs->trans("MenuTypeAssets"), 1, Globals::$user->rights->asset->read, '', $mainmenu, 'asset_type');
1541
+                    $newmenu->add(BASE_URI."?controller=asset&method=list&leftmenu=asset&mainmenu=accountancy", Globals::$langs->trans("MenuAssets"), 0, Globals::$user->rights->asset->read, '', $mainmenu, 'asset');
1542
+                    $newmenu->add(BASE_URI."?controller=asset&method=card&action=create", Globals::$langs->trans("MenuNewAsset"), 1, Globals::$user->rights->asset->write);
1543
+                    $newmenu->add(BASE_URI."?controller=asset&method=list&leftmenu=asset&mainmenu=accountancy", Globals::$langs->trans("MenuListAssets"), 1, Globals::$user->rights->asset->read);
1544
+                    $newmenu->add(BASE_URI."?controller=asset&method=type&leftmenu=asset_type", Globals::$langs->trans("MenuTypeAssets"), 1, Globals::$user->rights->asset->read, '', $mainmenu, 'asset_type');
1545 1545
                     if ($usemenuhider || empty($leftmenu) || preg_match('/asset_type/', $leftmenu)) {
1546 1546
 //$newmenu->add("/asset/type.php?leftmenu=asset_type&action=create", Globals::$langs->trans("MenuNewTypeAssets"), 2, Globals::$user->rights->asset->write);
1547 1547
 //$newmenu->add("/asset/type.php?leftmenu=asset_type", Globals::$langs->trans("MenuListTypeAssets"), 2, Globals::$user->rights->asset->read);
1548
-                        $newmenu->add(BASE_URI . "?controller=asset&method=type&leftmenu=asset_type&action=create", Globals::$langs->trans("MenuNewTypeAssets"), 2, Globals::$user->rights->asset->write);
1549
-                        $newmenu->add(BASE_URI . "?controller=asset&mtehod=type&leftmenu=asset_type", Globals::$langs->trans("MenuListTypeAssets"), 2, Globals::$user->rights->asset->read);
1548
+                        $newmenu->add(BASE_URI."?controller=asset&method=type&leftmenu=asset_type&action=create", Globals::$langs->trans("MenuNewTypeAssets"), 2, Globals::$user->rights->asset->write);
1549
+                        $newmenu->add(BASE_URI."?controller=asset&mtehod=type&leftmenu=asset_type", Globals::$langs->trans("MenuListTypeAssets"), 2, Globals::$user->rights->asset->read);
1550 1550
                     }
1551 1551
                 }
1552 1552
             }
@@ -1571,28 +1571,28 @@  discard block
 block discarded – undo
1571 1571
 
1572 1572
                       $newmenu->add("/compta/bank/transfer.php", Globals::$langs->trans("MenuBankInternalTransfer"), 1, Globals::$user->rights->banque->transfer);
1573 1573
                      */
1574
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=list&leftmenu=bank&mainmenu=bank", Globals::$langs->trans("MenuBankCash"), 0, Globals::$user->rights->banque->lire, '', $mainmenu, 'bank');
1574
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=list&leftmenu=bank&mainmenu=bank", Globals::$langs->trans("MenuBankCash"), 0, Globals::$user->rights->banque->lire, '', $mainmenu, 'bank');
1575 1575
 
1576
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=card&action=create", Globals::$langs->trans("MenuNewFinancialAccount"), 1, Globals::$user->rights->banque->configurer);
1577
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=list&leftmenu=bank&mainmenu=bank", Globals::$langs->trans("List"), 1, Globals::$user->rights->banque->lire, '', $mainmenu, 'bank');
1578
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=bankentries_list", Globals::$langs->trans("ListTransactions"), 1, Globals::$user->rights->banque->lire);
1579
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=budget", Globals::$langs->trans("ListTransactionsByCategory"), 1, Globals::$user->rights->banque->lire);
1576
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=card&action=create", Globals::$langs->trans("MenuNewFinancialAccount"), 1, Globals::$user->rights->banque->configurer);
1577
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=list&leftmenu=bank&mainmenu=bank", Globals::$langs->trans("List"), 1, Globals::$user->rights->banque->lire, '', $mainmenu, 'bank');
1578
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=bankentries_list", Globals::$langs->trans("ListTransactions"), 1, Globals::$user->rights->banque->lire);
1579
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=budget", Globals::$langs->trans("ListTransactionsByCategory"), 1, Globals::$user->rights->banque->lire);
1580 1580
 
1581
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=transfer", Globals::$langs->trans("MenuBankInternalTransfer"), 1, Globals::$user->rights->banque->transfer);
1581
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=transfer", Globals::$langs->trans("MenuBankInternalTransfer"), 1, Globals::$user->rights->banque->transfer);
1582 1582
                 }
1583 1583
 
1584 1584
                 if (!empty($conf->categorie->enabled)) {
1585 1585
                     Globals::$langs->load("categories");
1586 1586
 //$newmenu->add("/categories/index.php?type = 5", Globals::$langs->trans("Rubriques"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1587 1587
 //$newmenu->add("/compta/bank/categ.php", Globals::$langs->trans("RubriquesTransactions"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1588
-                    $newmenu->add(BASE_URI . "?controller=categories&method=index&type=5", Globals::$langs->trans("Rubriques"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1589
-                    $newmenu->add(BASE_URI . "?controller=compta/bank&method=categ", Globals::$langs->trans("RubriquesTransactions"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1588
+                    $newmenu->add(BASE_URI."?controller=categories&method=index&type=5", Globals::$langs->trans("Rubriques"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1589
+                    $newmenu->add(BASE_URI."?controller=compta/bank&method=categ", Globals::$langs->trans("RubriquesTransactions"), 1, Globals::$user->rights->categorie->creer, '', $mainmenu, 'tags');
1590 1590
                 }
1591 1591
 
1592 1592
 // Prelevements
1593 1593
                 if (!empty($conf->prelevement->enabled)) {
1594 1594
 //$newmenu->add("/compta/prelevement/index.php?leftmenu=withdraw&mainmenu=bank", Globals::$langs->trans("StandingOrders"), 0, Globals::$user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
1595
-                    $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=index&leftmenu=withdraw&mainmenu=bank", Globals::$langs->trans("StandingOrders"), 0, Globals::$user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
1595
+                    $newmenu->add(BASE_URI."?controller=compta/prelevement&method=index&leftmenu=withdraw&mainmenu=bank", Globals::$langs->trans("StandingOrders"), 0, Globals::$user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
1596 1596
 
1597 1597
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "withdraw") {
1598 1598
 //$newmenu->add("/compta/prelevement/demandes.php?status = 0&mainmenu=bank",Globals::$langs->trans("StandingOrderToProcess"),1,Globals::$user->rights->prelevement->bons->lire);
@@ -1605,12 +1605,12 @@  discard block
 block discarded – undo
1605 1605
                           $newmenu->add("/compta/prelevement/rejets.php?mainmenu=bank", Globals::$langs->trans("Rejects"), 1, Globals::$user->rights->prelevement->bons->lire);
1606 1606
                           $newmenu->add("/compta/prelevement/stats.php?mainmenu=bank", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->prelevement->bons->lire);
1607 1607
                          */
1608
-                        $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=create&mainmenu=bank", Globals::$langs->trans("NewStandingOrder"), 1, Globals::$user->rights->prelevement->bons->creer);
1608
+                        $newmenu->add(BASE_URI."?controller=compta/prelevement&method=create&mainmenu=bank", Globals::$langs->trans("NewStandingOrder"), 1, Globals::$user->rights->prelevement->bons->creer);
1609 1609
 
1610
-                        $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=bons&mainmenu=bank", Globals::$langs->trans("WithdrawalsReceipts"), 1, Globals::$user->rights->prelevement->bons->lire);
1611
-                        $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=list&mainmenu=bank", Globals::$langs->trans("WithdrawalsLines"), 1, Globals::$user->rights->prelevement->bons->lire);
1612
-                        $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=rejets&mainmenu=bank", Globals::$langs->trans("Rejects"), 1, Globals::$user->rights->prelevement->bons->lire);
1613
-                        $newmenu->add(BASE_URI . "?controller=compta/prelevement&method=stats&mainmenu=bank", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->prelevement->bons->lire);
1610
+                        $newmenu->add(BASE_URI."?controller=compta/prelevement&method=bons&mainmenu=bank", Globals::$langs->trans("WithdrawalsReceipts"), 1, Globals::$user->rights->prelevement->bons->lire);
1611
+                        $newmenu->add(BASE_URI."?controller=compta/prelevement&method=list&mainmenu=bank", Globals::$langs->trans("WithdrawalsLines"), 1, Globals::$user->rights->prelevement->bons->lire);
1612
+                        $newmenu->add(BASE_URI."?controller=compta/prelevement&method=rejets&mainmenu=bank", Globals::$langs->trans("Rejects"), 1, Globals::$user->rights->prelevement->bons->lire);
1613
+                        $newmenu->add(BASE_URI."?controller=compta/prelevement&method=stats&mainmenu=bank", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->prelevement->bons->lire);
1614 1614
 
1615 1615
 //$newmenu->add("/compta/prelevement/config.php",Globals::$langs->trans("Setup"),1,Globals::$user->rights->prelevement->bons->configurer);
1616 1616
                     }
@@ -1619,12 +1619,12 @@  discard block
 block discarded – undo
1619 1619
 // Gestion cheques
1620 1620
                 if (empty(Conf::$global->BANK_DISABLE_CHECK_DEPOSIT) && !empty($conf->banque->enabled) && (!empty($conf->facture->enabled) || !empty(Conf::$global->MAIN_MENU_CHEQUE_DEPOSIT_ON))) {
1621 1621
 //$newmenu->add("/compta/paiement/cheque/index.php?leftmenu=checks&mainmenu=bank", Globals::$langs->trans("MenuChequeDeposits"), 0, Globals::$user->rights->banque->cheque, '', $mainmenu, 'checks');
1622
-                    $newmenu->add(BASE_URI . "?controller=compta/paiement/cheque&method=index&leftmenu=checks&mainmenu=bank", Globals::$langs->trans("MenuChequeDeposits"), 0, Globals::$user->rights->banque->cheque, '', $mainmenu, 'checks');
1622
+                    $newmenu->add(BASE_URI."?controller=compta/paiement/cheque&method=index&leftmenu=checks&mainmenu=bank", Globals::$langs->trans("MenuChequeDeposits"), 0, Globals::$user->rights->banque->cheque, '', $mainmenu, 'checks');
1623 1623
                     if (preg_match('/checks/', $leftmenu)) {
1624 1624
 //$newmenu->add("/compta/paiement/cheque/card.php?leftmenu=checks_bis&action=new&mainmenu=bank", Globals::$langs->trans("NewChequeDeposit"), 1, Globals::$user->rights->banque->cheque);
1625 1625
 //$newmenu->add("/compta/paiement/cheque/list.php?leftmenu=checks_bis&mainmenu=bank", Globals::$langs->trans("List"), 1, Globals::$user->rights->banque->cheque);
1626
-                        $newmenu->add(BASE_URI . "?controller=compta/paiement/cheque&method=card&leftmenu=checks_bis&action=new&mainmenu=bank", Globals::$langs->trans("NewChequeDeposit"), 1, Globals::$user->rights->banque->cheque);
1627
-                        $newmenu->add(BASE_URI . "?controller=compta/paiement/cheque&method=list&leftmenu=checks_bis&mainmenu=bank", Globals::$langs->trans("List"), 1, Globals::$user->rights->banque->cheque);
1626
+                        $newmenu->add(BASE_URI."?controller=compta/paiement/cheque&method=card&leftmenu=checks_bis&action=new&mainmenu=bank", Globals::$langs->trans("NewChequeDeposit"), 1, Globals::$user->rights->banque->cheque);
1627
+                        $newmenu->add(BASE_URI."?controller=compta/paiement/cheque&method=list&leftmenu=checks_bis&mainmenu=bank", Globals::$langs->trans("List"), 1, Globals::$user->rights->banque->cheque);
1628 1628
                     }
1629 1629
                 }
1630 1630
 
@@ -1634,9 +1634,9 @@  discard block
 block discarded – undo
1634 1634
 //$newmenu->add("/compta/cashcontrol/cashcontrol_list.php?action=list", Globals::$langs->trans("POS"), 0, $permtomakecashfence, '', $mainmenu, 'cashcontrol');
1635 1635
 //$newmenu->add("/compta/cashcontrol/cashcontrol_card.php?action=create", Globals::$langs->trans("NewCashFence"), 1, $permtomakecashfence);
1636 1636
 //$newmenu->add("/compta/cashcontrol/cashcontrol_list.php?action=list", Globals::$langs->trans("List"), 1, $permtomakecashfence);
1637
-                    $newmenu->add(BASE_URI . "?controller=compta/cashcontrol&method=cashcontrol_list&action=list", Globals::$langs->trans("POS"), 0, $permtomakecashfence, '', $mainmenu, 'cashcontrol');
1638
-                    $newmenu->add(BASE_URI . "?controller=compta/cashcontrol&method=cashcontrol_card&action=create", Globals::$langs->trans("NewCashFence"), 1, $permtomakecashfence);
1639
-                    $newmenu->add(BASE_URI . "?controller=compta/cashcontrol&method=cashcontrol_list&action=list", Globals::$langs->trans("List"), 1, $permtomakecashfence);
1637
+                    $newmenu->add(BASE_URI."?controller=compta/cashcontrol&method=cashcontrol_list&action=list", Globals::$langs->trans("POS"), 0, $permtomakecashfence, '', $mainmenu, 'cashcontrol');
1638
+                    $newmenu->add(BASE_URI."?controller=compta/cashcontrol&method=cashcontrol_card&action=create", Globals::$langs->trans("NewCashFence"), 1, $permtomakecashfence);
1639
+                    $newmenu->add(BASE_URI."?controller=compta/cashcontrol&method=cashcontrol_list&action=list", Globals::$langs->trans("List"), 1, $permtomakecashfence);
1640 1640
                 }
1641 1641
             }
1642 1642
 
@@ -1649,34 +1649,34 @@  discard block
 block discarded – undo
1649 1649
 //$newmenu->add("/product/index.php?leftmenu=product&type=0", Globals::$langs->trans("Products"), 0, Globals::$user->rights->produit->lire, '', $mainmenu, 'product');
1650 1650
 //$newmenu->add("/product/card.php?leftmenu=product&action=create&type=0", Globals::$langs->trans("NewProduct"), 1, Globals::$user->rights->produit->creer);
1651 1651
 //$newmenu->add("/product/list.php?leftmenu=product&type=0", Globals::$langs->trans("List"), 1, Globals::$user->rights->produit->lire);
1652
-                    $newmenu->add(BASE_URI . "?controller=product&method=index&leftmenu=product&type=0", Globals::$langs->trans("Products"), 0, Globals::$user->rights->produit->lire, '', $mainmenu, 'product');
1653
-                    $newmenu->add(BASE_URI . "?controller=product&method=card&leftmenu=product&action=create&type=0", Globals::$langs->trans("NewProduct"), 1, Globals::$user->rights->produit->creer);
1654
-                    $newmenu->add(BASE_URI . "?controller=product&method=list&leftmenu=product&type=0", Globals::$langs->trans("List"), 1, Globals::$user->rights->produit->lire);
1652
+                    $newmenu->add(BASE_URI."?controller=product&method=index&leftmenu=product&type=0", Globals::$langs->trans("Products"), 0, Globals::$user->rights->produit->lire, '', $mainmenu, 'product');
1653
+                    $newmenu->add(BASE_URI."?controller=product&method=card&leftmenu=product&action=create&type=0", Globals::$langs->trans("NewProduct"), 1, Globals::$user->rights->produit->creer);
1654
+                    $newmenu->add(BASE_URI."?controller=product&method=list&leftmenu=product&type=0", Globals::$langs->trans("List"), 1, Globals::$user->rights->produit->lire);
1655 1655
                     if (!empty($conf->stock->enabled)) {
1656 1656
 //$newmenu->add("/product/reassort.php?type = 0", Globals::$langs->trans("Stocks"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1657
-                        $newmenu->add(BASE_URI . "?controller=product&method=reassort&type=0", Globals::$langs->trans("Stocks"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1657
+                        $newmenu->add(BASE_URI."?controller=product&method=reassort&type=0", Globals::$langs->trans("Stocks"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1658 1658
                     }
1659 1659
                     if (!empty($conf->productbatch->enabled)) {
1660 1660
                         Globals::$langs->load("stocks");
1661 1661
 //$newmenu->add("/product/reassortlot.php?type = 0", Globals::$langs->trans("StocksByLotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1662 1662
 //$newmenu->add("/product/stock/productlot_list.php", Globals::$langs->trans("LotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1663
-                        $newmenu->add(BASE_URI . "?controller=product&method=reassortlot&type=0", Globals::$langs->trans("StocksByLotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1664
-                        $newmenu->add(BASE_URI . "?controller=product/stock&method=productlot_list", Globals::$langs->trans("LotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1663
+                        $newmenu->add(BASE_URI."?controller=product&method=reassortlot&type=0", Globals::$langs->trans("StocksByLotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1664
+                        $newmenu->add(BASE_URI."?controller=product/stock&method=productlot_list", Globals::$langs->trans("LotSerial"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->stock->lire);
1665 1665
                     }
1666 1666
                     if (!empty($conf->variants->enabled)) {
1667 1667
 //$newmenu->add("/variants/list.php", Globals::$langs->trans("VariantAttributes"), 1, Globals::$user->rights->produit->lire);
1668
-                        $newmenu->add(BASE_URI . "?controller=variants&method=list", Globals::$langs->trans("VariantAttributes"), 1, Globals::$user->rights->produit->lire);
1668
+                        $newmenu->add(BASE_URI."?controller=variants&method=list", Globals::$langs->trans("VariantAttributes"), 1, Globals::$user->rights->produit->lire);
1669 1669
                     }
1670 1670
                     if (!empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->facture->enabled) || !empty($conf->fournisseur->enabled) || !empty($conf->supplier_proposal->enabled)) {
1671 1671
 // $newmenu->add("/product/stats/card.php?id = all&leftmenu=stats&type=0", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->propale->lire);
1672
-                        $newmenu->add(BASE_URI . "?controller=product/stats&method=card&id=all&leftmenu=stats&type=0", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->propale->lire);
1672
+                        $newmenu->add(BASE_URI."?controller=product/stats&method=card&id=all&leftmenu=stats&type=0", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->produit->lire && Globals::$user->rights->propale->lire);
1673 1673
                     }
1674 1674
 
1675 1675
 // Categories
1676 1676
                     if (!empty($conf->categorie->enabled)) {
1677 1677
                         Globals::$langs->load("categories");
1678 1678
 //$newmenu->add("/categories/index.php?leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1679
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1679
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1680 1680
                         //if ($usemenuhider || empty($leftmenu) || $leftmenu=="cat") $newmenu->add("/categories/list.php", Globals::$langs->trans("List"), 1, Globals::$user->rights->categorie->lire);
1681 1681
                     }
1682 1682
                 }
@@ -1686,18 +1686,18 @@  discard block
 block discarded – undo
1686 1686
                     //$newmenu->add("/product/index.php?leftmenu=service&type=1", Globals::$langs->trans("Services"), 0, Globals::$user->rights->service->lire, '', $mainmenu, 'service');
1687 1687
                     //$newmenu->add("/product/card.php?leftmenu=service&action=create&type=1", Globals::$langs->trans("NewService"), 1, Globals::$user->rights->service->creer);
1688 1688
                     //$newmenu->add("/product/list.php?leftmenu=service&type=1", Globals::$langs->trans("List"), 1, Globals::$user->rights->service->lire);
1689
-                    $newmenu->add(BASE_URI . "?controller=product&method=index&leftmenu=service&type=1", Globals::$langs->trans("Services"), 0, Globals::$user->rights->service->lire, '', $mainmenu, 'service');
1690
-                    $newmenu->add(BASE_URI . "?controller=product&method=card&leftmenu=service&action=create&type=1", Globals::$langs->trans("NewService"), 1, Globals::$user->rights->service->creer);
1691
-                    $newmenu->add(BASE_URI . "?controller=product&method=list&leftmenu=service&type=1", Globals::$langs->trans("List"), 1, Globals::$user->rights->service->lire);
1689
+                    $newmenu->add(BASE_URI."?controller=product&method=index&leftmenu=service&type=1", Globals::$langs->trans("Services"), 0, Globals::$user->rights->service->lire, '', $mainmenu, 'service');
1690
+                    $newmenu->add(BASE_URI."?controller=product&method=card&leftmenu=service&action=create&type=1", Globals::$langs->trans("NewService"), 1, Globals::$user->rights->service->creer);
1691
+                    $newmenu->add(BASE_URI."?controller=product&method=list&leftmenu=service&type=1", Globals::$langs->trans("List"), 1, Globals::$user->rights->service->lire);
1692 1692
                     if (!empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->facture->enabled) || !empty($conf->fournisseur->enabled) || !empty($conf->supplier_proposal->enabled)) {
1693 1693
                         //$newmenu->add("/product/stats/card.php?id = all&leftmenu=stats&type=1", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->service->lire && Globals::$user->rights->propale->lire);
1694
-                        $newmenu->add(BASE_URI . "?controller=product/stats&method=card&id=all&leftmenu=stats&type=1", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->service->lire && Globals::$user->rights->propale->lire);
1694
+                        $newmenu->add(BASE_URI."?controller=product/stats&method=card&id=all&leftmenu=stats&type=1", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->service->lire && Globals::$user->rights->propale->lire);
1695 1695
                     }
1696 1696
                     // Categories
1697 1697
                     if (!empty($conf->categorie->enabled)) {
1698 1698
                         Globals::$langs->load("categories");
1699 1699
                         //$newmenu->add("/categories/index.php?leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1700
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1700
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=cat&type=0", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1701 1701
                         //if ($usemenuhider || empty($leftmenu) || $leftmenu=="cat") $newmenu->add("/categories/list.php", Globals::$langs->trans("List"), 1, Globals::$user->rights->categorie->lire);
1702 1702
                     }
1703 1703
                 }
@@ -1713,15 +1713,15 @@  discard block
 block discarded – undo
1713 1713
 
1714 1714
                       $newmenu->add("/product/stock/massstockmove.php", Globals::$langs->trans("MassStockTransferShort"), 1, Globals::$user->rights->stock->mouvement->creer);
1715 1715
                      */
1716
-                    $newmenu->add(BASE_URI . "?controller=product/stock&method=index&leftmenu=stock", Globals::$langs->trans("Warehouses"), 0, Globals::$user->rights->stock->lire, '', $mainmenu, 'stock');
1717
-                    $newmenu->add(BASE_URI . "?controller=product/stock&method=card&action=create", Globals::$langs->trans("MenuNewWarehouse"), 1, Globals::$user->rights->stock->creer);
1718
-                    $newmenu->add(BASE_URI . "?controller=product/stock&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->lire);
1719
-                    $newmenu->add(BASE_URI . "?controller=product/stock&method=movement_list", Globals::$langs->trans("Movements"), 1, Globals::$user->rights->stock->mouvement->lire);
1716
+                    $newmenu->add(BASE_URI."?controller=product/stock&method=index&leftmenu=stock", Globals::$langs->trans("Warehouses"), 0, Globals::$user->rights->stock->lire, '', $mainmenu, 'stock');
1717
+                    $newmenu->add(BASE_URI."?controller=product/stock&method=card&action=create", Globals::$langs->trans("MenuNewWarehouse"), 1, Globals::$user->rights->stock->creer);
1718
+                    $newmenu->add(BASE_URI."?controller=product/stock&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->lire);
1719
+                    $newmenu->add(BASE_URI."?controller=product/stock&method=movement_list", Globals::$langs->trans("Movements"), 1, Globals::$user->rights->stock->mouvement->lire);
1720 1720
 
1721
-                    $newmenu->add(BASE_URI . "?controller=product/stock&method=massstockmove", Globals::$langs->trans("MassStockTransferShort"), 1, Globals::$user->rights->stock->mouvement->creer);
1721
+                    $newmenu->add(BASE_URI."?controller=product/stock&method=massstockmove", Globals::$langs->trans("MassStockTransferShort"), 1, Globals::$user->rights->stock->mouvement->creer);
1722 1722
                     if ($conf->supplier_order->enabled) {
1723 1723
                         //$newmenu->add("/product/stock/replenish.php", Globals::$langs->trans("Replenishment"), 1, Globals::$user->rights->stock->mouvement->creer && Globals::$user->rights->fournisseur->lire);
1724
-                        $newmenu->add(BASE_URI . "?controller=product/stock&method=replenish", Globals::$langs->trans("Replenishment"), 1, Globals::$user->rights->stock->mouvement->creer && Globals::$user->rights->fournisseur->lire);
1724
+                        $newmenu->add(BASE_URI."?controller=product/stock&method=replenish", Globals::$langs->trans("Replenishment"), 1, Globals::$user->rights->stock->mouvement->creer && Globals::$user->rights->fournisseur->lire);
1725 1725
                     }
1726 1726
                 }
1727 1727
 
@@ -1733,16 +1733,16 @@  discard block
 block discarded – undo
1733 1733
                             //$newmenu->add("/product/inventory/list.php?leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->lire, '', $mainmenu, 'stock');
1734 1734
                             //$newmenu->add("/product/inventory/card.php?action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->creer);
1735 1735
                             //$newmenu->add("/product/inventory/list.php", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->lire);
1736
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=list&leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->lire, '', $mainmenu, 'stock');
1737
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=card&action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->creer);
1738
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->lire);
1736
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=list&leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->lire, '', $mainmenu, 'stock');
1737
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=card&action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->creer);
1738
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->lire);
1739 1739
                         } else {
1740 1740
                             //$newmenu->add("/product/inventory/list.php?leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->inventory_advance->read, '', $mainmenu, 'stock');
1741 1741
                             //$newmenu->add("/product/inventory/card.php?action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->inventory_advance->write);
1742 1742
                             //$newmenu->add("/product/inventory/list.php", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->inventory_advance->read);
1743
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=list&leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->inventory_advance->read, '', $mainmenu, 'stock');
1744
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=card&action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->inventory_advance->write);
1745
-                            $newmenu->add(BASE_URI . "?controller=product/inventory&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->inventory_advance->read);
1743
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=list&leftmenu=stock", Globals::$langs->trans("Inventory"), 0, Globals::$user->rights->stock->inventory_advance->read, '', $mainmenu, 'stock');
1744
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=card&action=create", Globals::$langs->trans("NewInventory"), 1, Globals::$user->rights->stock->inventory_advance->write);
1745
+                            $newmenu->add(BASE_URI."?controller=product/inventory&method=list", Globals::$langs->trans("List"), 1, Globals::$user->rights->stock->inventory_advance->read);
1746 1746
                         }
1747 1747
                     }
1748 1748
                 }
@@ -1753,19 +1753,19 @@  discard block
 block discarded – undo
1753 1753
                     //$newmenu->add("/expedition/index.php?leftmenu=sendings", Globals::$langs->trans("Shipments"), 0, Globals::$user->rights->expedition->lire, '', $mainmenu, 'sendings');
1754 1754
                     //$newmenu->add("/expedition/card.php?action=create2&leftmenu=sendings", Globals::$langs->trans("NewSending"), 1, Globals::$user->rights->expedition->creer);
1755 1755
                     //$newmenu->add("/expedition/list.php?leftmenu=sendings", Globals::$langs->trans("List"), 1, Globals::$user->rights->expedition->lire);
1756
-                    $newmenu->add(BASE_URI . "?controller=expedition&method=index&leftmenu=sendings", Globals::$langs->trans("Shipments"), 0, Globals::$user->rights->expedition->lire, '', $mainmenu, 'sendings');
1757
-                    $newmenu->add(BASE_URI . "?controller=expedition&method=card&action=create2&leftmenu=sendings", Globals::$langs->trans("NewSending"), 1, Globals::$user->rights->expedition->creer);
1758
-                    $newmenu->add(BASE_URI . "?controller=expedition&method=list&leftmenu=sendings", Globals::$langs->trans("List"), 1, Globals::$user->rights->expedition->lire);
1756
+                    $newmenu->add(BASE_URI."?controller=expedition&method=index&leftmenu=sendings", Globals::$langs->trans("Shipments"), 0, Globals::$user->rights->expedition->lire, '', $mainmenu, 'sendings');
1757
+                    $newmenu->add(BASE_URI."?controller=expedition&method=card&action=create2&leftmenu=sendings", Globals::$langs->trans("NewSending"), 1, Globals::$user->rights->expedition->creer);
1758
+                    $newmenu->add(BASE_URI."?controller=expedition&method=list&leftmenu=sendings", Globals::$langs->trans("List"), 1, Globals::$user->rights->expedition->lire);
1759 1759
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "sendings") {
1760 1760
                         //$newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=0", Globals::$langs->trans("StatusSendingDraftShort"), 2, Globals::$user->rights->expedition->lire);
1761 1761
                         //$newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=1", Globals::$langs->trans("StatusSendingValidatedShort"), 2, Globals::$user->rights->expedition->lire);
1762 1762
                         //$newmenu->add("/expedition/list.php?leftmenu=sendings&viewstatut=2", Globals::$langs->trans("StatusSendingProcessedShort"), 2, Globals::$user->rights->expedition->lire);
1763
-                        $newmenu->add(BASE_URI . "?controller=expedition&method=list&leftmenu=sendings&viewstatut=0", Globals::$langs->trans("StatusSendingDraftShort"), 2, Globals::$user->rights->expedition->lire);
1764
-                        $newmenu->add(BASE_URI . "?controller=expedition&method=list&leftmenu=sendings&viewstatut=1", Globals::$langs->trans("StatusSendingValidatedShort"), 2, Globals::$user->rights->expedition->lire);
1765
-                        $newmenu->add(BASE_URI . "?controller=expedition&method=list&leftmenu=sendings&viewstatut=2", Globals::$langs->trans("StatusSendingProcessedShort"), 2, Globals::$user->rights->expedition->lire);
1763
+                        $newmenu->add(BASE_URI."?controller=expedition&method=list&leftmenu=sendings&viewstatut=0", Globals::$langs->trans("StatusSendingDraftShort"), 2, Globals::$user->rights->expedition->lire);
1764
+                        $newmenu->add(BASE_URI."?controller=expedition&method=list&leftmenu=sendings&viewstatut=1", Globals::$langs->trans("StatusSendingValidatedShort"), 2, Globals::$user->rights->expedition->lire);
1765
+                        $newmenu->add(BASE_URI."?controller=expedition&method=list&leftmenu=sendings&viewstatut=2", Globals::$langs->trans("StatusSendingProcessedShort"), 2, Globals::$user->rights->expedition->lire);
1766 1766
                     }
1767 1767
                     //$newmenu->add("/expedition/stats/index.php?leftmenu=sendings", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expedition->lire);
1768
-                    $newmenu->add(BASE_URI . "?controller=expedition/stats&method=index&leftmenu=sendings", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expedition->lire);
1768
+                    $newmenu->add(BASE_URI."?controller=expedition/stats&method=index&leftmenu=sendings", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expedition->lire);
1769 1769
                 }
1770 1770
 
1771 1771
                 // Receptions
@@ -1774,23 +1774,23 @@  discard block
 block discarded – undo
1774 1774
                     //$newmenu->add("/reception/index.php?leftmenu=receptions", Globals::$langs->trans("Receptions"), 0, Globals::$user->rights->reception->lire, '', $mainmenu, 'receptions');
1775 1775
                     //$newmenu->add("/reception/card.php?action=create2&leftmenu=receptions", Globals::$langs->trans("NewReception"), 1, Globals::$user->rights->reception->creer);
1776 1776
                     //$newmenu->add("/reception/list.php?leftmenu=receptions", Globals::$langs->trans("List"), 1, Globals::$user->rights->reception->lire);
1777
-                    $newmenu->add(BASE_URI . "?controller=reception&method=index&leftmenu=receptions", Globals::$langs->trans("Receptions"), 0, Globals::$user->rights->reception->lire, '', $mainmenu, 'receptions');
1778
-                    $newmenu->add(BASE_URI . "?controller=reception&method=card&action=create2&leftmenu=receptions", Globals::$langs->trans("NewReception"), 1, Globals::$user->rights->reception->creer);
1779
-                    $newmenu->add(BASE_URI . "?controller=reception&method=list&leftmenu=receptions", Globals::$langs->trans("List"), 1, Globals::$user->rights->reception->lire);
1777
+                    $newmenu->add(BASE_URI."?controller=reception&method=index&leftmenu=receptions", Globals::$langs->trans("Receptions"), 0, Globals::$user->rights->reception->lire, '', $mainmenu, 'receptions');
1778
+                    $newmenu->add(BASE_URI."?controller=reception&method=card&action=create2&leftmenu=receptions", Globals::$langs->trans("NewReception"), 1, Globals::$user->rights->reception->creer);
1779
+                    $newmenu->add(BASE_URI."?controller=reception&method=list&leftmenu=receptions", Globals::$langs->trans("List"), 1, Globals::$user->rights->reception->lire);
1780 1780
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "receptions") {
1781 1781
                         //$newmenu->add("/reception/list.php?leftmenu=receptions&viewstatut=0", Globals::$langs->trans("StatusReceptionDraftShort"), 2, Globals::$user->rights->reception->lire);
1782
-                        $newmenu->add(BASE_URI . "?controller=reception&method=list&leftmenu=receptions&viewstatut=0", Globals::$langs->trans("StatusReceptionDraftShort"), 2, Globals::$user->rights->reception->lire);
1782
+                        $newmenu->add(BASE_URI."?controller=reception&method=list&leftmenu=receptions&viewstatut=0", Globals::$langs->trans("StatusReceptionDraftShort"), 2, Globals::$user->rights->reception->lire);
1783 1783
                     }
1784 1784
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "receptions") {
1785 1785
                         //$newmenu->add("/reception/list.php?leftmenu=receptions&viewstatut=1", Globals::$langs->trans("StatusReceptionValidatedShort"), 2, Globals::$user->rights->reception->lire);
1786
-                        $newmenu->add(BASE_URI . "?controller=reception&method=list&leftmenu=receptions&viewstatut=1", Globals::$langs->trans("StatusReceptionValidatedShort"), 2, Globals::$user->rights->reception->lire);
1786
+                        $newmenu->add(BASE_URI."?controller=reception&method=list&leftmenu=receptions&viewstatut=1", Globals::$langs->trans("StatusReceptionValidatedShort"), 2, Globals::$user->rights->reception->lire);
1787 1787
                     }
1788 1788
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "receptions") {
1789 1789
                         //$newmenu->add("/reception/list.php?leftmenu=receptions&viewstatut=2", Globals::$langs->trans("StatusReceptionProcessedShort"), 2, Globals::$user->rights->reception->lire);
1790
-                        $newmenu->add(BASE_URI . "?controller=reception&method=list&leftmenu=receptions&viewstatut=2", Globals::$langs->trans("StatusReceptionProcessedShort"), 2, Globals::$user->rights->reception->lire);
1790
+                        $newmenu->add(BASE_URI."?controller=reception&method=list&leftmenu=receptions&viewstatut=2", Globals::$langs->trans("StatusReceptionProcessedShort"), 2, Globals::$user->rights->reception->lire);
1791 1791
                     }
1792 1792
                     //$newmenu->add("/reception/stats/index.php?leftmenu=receptions", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->reception->lire);
1793
-                    $newmenu->add(BASE_URI . "?controller=reception/stats&method=index&leftmenu=receptions", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->reception->lire);
1793
+                    $newmenu->add(BASE_URI."?controller=reception/stats&method=index&leftmenu=receptions", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->reception->lire);
1794 1794
                 }
1795 1795
             }
1796 1796
 
@@ -1824,32 +1824,32 @@  discard block
 block discarded – undo
1824 1824
                     // Project assigned to user
1825 1825
                     //$newmenu->add("/projet/index.php?leftmenu=projects" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), $titleboth, 0, Globals::$user->rights->projet->lire, '', $mainmenu, 'projects');
1826 1826
                     //$newmenu->add("/projet/card.php?leftmenu=projects&action=create" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), $titlenew, 1, Globals::$user->rights->projet->creer);
1827
-                    $newmenu->add(BASE_URI . "?controller=projet&method=index&leftmenu=projects" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), $titleboth, 0, Globals::$user->rights->projet->lire, '', $mainmenu, 'projects');
1828
-                    $newmenu->add(BASE_URI . "?controller=projet&method=card&leftmenu=projects&action=create" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), $titlenew, 1, Globals::$user->rights->projet->creer);
1827
+                    $newmenu->add(BASE_URI."?controller=projet&method=index&leftmenu=projects".($search_project_user ? '&search_project_user='.$search_project_user : ''), $titleboth, 0, Globals::$user->rights->projet->lire, '', $mainmenu, 'projects');
1828
+                    $newmenu->add(BASE_URI."?controller=projet&method=card&leftmenu=projects&action=create".($search_project_user ? '&search_project_user='.$search_project_user : ''), $titlenew, 1, Globals::$user->rights->projet->creer);
1829 1829
 
1830 1830
                     if (Conf::$global->PROJECT_USE_OPPORTUNITIES == 0) {
1831 1831
                         //$newmenu->add("/projet/list.php?leftmenu=projets" . ($search_project_user ? '&search_project_user=' . $search_project_user : '') . '&search_status=99', Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1832
-                        $newmenu->add(BASE_URI . "?controller=projet&method=list&leftmenu=projets" . ($search_project_user ? '&search_project_user=' . $search_project_user : '') . '&search_status=99', Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1832
+                        $newmenu->add(BASE_URI."?controller=projet&method=list&leftmenu=projets".($search_project_user ? '&search_project_user='.$search_project_user : '').'&search_status=99', Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1833 1833
                     } elseif (Conf::$global->PROJECT_USE_OPPORTUNITIES == 1) {
1834 1834
                         //$newmenu->add("/projet/list.php?leftmenu=projets" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1835 1835
                         //$newmenu->add('/projet/list.php?mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99&contextpage=lead', Globals::$langs->trans("ListOpenLeads"), 2, $showmode);
1836 1836
                         //$newmenu->add('/projet/list.php?mainmenu=project&leftmenu=list&search_opp_status=notopenedopp&search_status=99&contextpage=project', Globals::$langs->trans("ListOpenProjects"), 2, $showmode);
1837
-                        $newmenu->add(BASE_URI . "?controller=projet&method=list&leftmenu=projets" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1838
-                        $newmenu->add(BASE_URI . '?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99&contextpage=lead', Globals::$langs->trans("ListOpenLeads"), 2, $showmode);
1839
-                        $newmenu->add(BASE_URI . '?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=notopenedopp&search_status=99&contextpage=project', Globals::$langs->trans("ListOpenProjects"), 2, $showmode);
1837
+                        $newmenu->add(BASE_URI."?controller=projet&method=list&leftmenu=projets".($search_project_user ? '&search_project_user='.$search_project_user : ''), Globals::$langs->trans("List"), 1, $showmode, '', 'project', 'list');
1838
+                        $newmenu->add(BASE_URI.'?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99&contextpage=lead', Globals::$langs->trans("ListOpenLeads"), 2, $showmode);
1839
+                        $newmenu->add(BASE_URI.'?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=notopenedopp&search_status=99&contextpage=project', Globals::$langs->trans("ListOpenProjects"), 2, $showmode);
1840 1840
                     } elseif (Conf::$global->PROJECT_USE_OPPORTUNITIES == 2) { // 2 = leads only
1841 1841
                         //$newmenu->add('/projet/list.php?mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99', Globals::$langs->trans("List"), 2, $showmode);
1842
-                        $newmenu->add(BASE_URI . '?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99', Globals::$langs->trans("List"), 2, $showmode);
1842
+                        $newmenu->add(BASE_URI.'?controller=projet&method=list&mainmenu=project&leftmenu=list&search_opp_status=openedopp&search_status=99', Globals::$langs->trans("List"), 2, $showmode);
1843 1843
                     }
1844 1844
 
1845 1845
                     //$newmenu->add("/projet/stats/index.php?leftmenu=projects", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->projet->lire);
1846
-                    $newmenu->add(BASE_URI . "?controller=projet/stats&method=index&leftmenu=projects", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->projet->lire);
1846
+                    $newmenu->add(BASE_URI."?controller=projet/stats&method=index&leftmenu=projects", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->projet->lire);
1847 1847
 
1848 1848
                     // Categories
1849 1849
                     if (!empty($conf->categorie->enabled)) {
1850 1850
                         Globals::$langs->load("categories");
1851 1851
                         //$newmenu->add("/categories/index.php?leftmenu=cat&type=6", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1852
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=cat&type=6", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1852
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=cat&type=6", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
1853 1853
                     }
1854 1854
 
1855 1855
                     if (empty(Conf::$global->PROJECT_HIDE_TASKS)) {
@@ -1862,12 +1862,12 @@  discard block
 block discarded – undo
1862 1862
 
1863 1863
                           $newmenu->add("/projet/activity/perweek.php?leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1864 1864
                          */
1865
-                        $newmenu->add(BASE_URI . "?controller=projet/activity&method=index&leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("Activities"), 0, Globals::$user->rights->projet->lire);
1866
-                        $newmenu->add(BASE_URI . "?controller=projet&method=tasks&leftmenu=tasks&action=create", Globals::$langs->trans("NewTask"), 1, Globals::$user->rights->projet->creer);
1867
-                        $newmenu->add(BASE_URI . "?controller=projet/tasks&method=list&leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("List"), 1, Globals::$user->rights->projet->lire);
1868
-                        $newmenu->add(BASE_URI . "?controller=projet/tasks/stats&method=index&leftmenu=projects", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->projet->lire);
1865
+                        $newmenu->add(BASE_URI."?controller=projet/activity&method=index&leftmenu=tasks".($search_project_user ? '&search_project_user='.$search_project_user : ''), Globals::$langs->trans("Activities"), 0, Globals::$user->rights->projet->lire);
1866
+                        $newmenu->add(BASE_URI."?controller=projet&method=tasks&leftmenu=tasks&action=create", Globals::$langs->trans("NewTask"), 1, Globals::$user->rights->projet->creer);
1867
+                        $newmenu->add(BASE_URI."?controller=projet/tasks&method=list&leftmenu=tasks".($search_project_user ? '&search_project_user='.$search_project_user : ''), Globals::$langs->trans("List"), 1, Globals::$user->rights->projet->lire);
1868
+                        $newmenu->add(BASE_URI."?controller=projet/tasks/stats&method=index&leftmenu=projects", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->projet->lire);
1869 1869
 
1870
-                        $newmenu->add(BASE_URI . "?controller=projet/activity&method=perweek&leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1870
+                        $newmenu->add(BASE_URI."?controller=projet/activity&method=perweek&leftmenu=tasks".($search_project_user ? '&search_project_user='.$search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1871 1871
                     }
1872 1872
                 }
1873 1873
             }
@@ -1883,9 +1883,9 @@  discard block
 block discarded – undo
1883 1883
                     //$newmenu->add("/user/list.php?leftmenu=hrm&mode=employee", Globals::$langs->trans("Employees"), 0, Globals::$user->rights->hrm->employee->read, '', $mainmenu, 'hrm');
1884 1884
                     //$newmenu->add("/user/card.php?action=create&employee = 1", Globals::$langs->trans("NewEmployee"), 1, Globals::$user->rights->hrm->employee->write);
1885 1885
                     //$newmenu->add("/user/list.php?leftmenu=hrm&mode=employee&contextpage = employeelist", Globals::$langs->trans("List"), 1, Globals::$user->rights->hrm->employee->read);
1886
-                    $newmenu->add(BASE_URI . "?controller=user&method=list&leftmenu=hrm&mode=employee", Globals::$langs->trans("Employees"), 0, Globals::$user->rights->hrm->employee->read, '', $mainmenu, 'hrm');
1887
-                    $newmenu->add(BASE_URI . "?controller=user&method=card&action=create&employee = 1", Globals::$langs->trans("NewEmployee"), 1, Globals::$user->rights->hrm->employee->write);
1888
-                    $newmenu->add(BASE_URI . "?controller=user&method=list&leftmenu=hrm&mode=employee&contextpage = employeelist", Globals::$langs->trans("List"), 1, Globals::$user->rights->hrm->employee->read);
1886
+                    $newmenu->add(BASE_URI."?controller=user&method=list&leftmenu=hrm&mode=employee", Globals::$langs->trans("Employees"), 0, Globals::$user->rights->hrm->employee->read, '', $mainmenu, 'hrm');
1887
+                    $newmenu->add(BASE_URI."?controller=user&method=card&action=create&employee = 1", Globals::$langs->trans("NewEmployee"), 1, Globals::$user->rights->hrm->employee->write);
1888
+                    $newmenu->add(BASE_URI."?controller=user&method=list&leftmenu=hrm&mode=employee&contextpage = employeelist", Globals::$langs->trans("List"), 1, Globals::$user->rights->hrm->employee->read);
1889 1889
                 }
1890 1890
 
1891 1891
                 // Leave/Holiday/Vacation module
@@ -1896,9 +1896,9 @@  discard block
 block discarded – undo
1896 1896
                     //$newmenu->add("/holiday/list.php?leftmenu=hrm", Globals::$langs->trans("CPTitreMenu"), 0, Globals::$user->rights->holiday->read, '', $mainmenu, 'hrm');
1897 1897
                     //$newmenu->add("/holiday/card.php?action=request", Globals::$langs->trans("New"), 1, Globals::$user->rights->holiday->write);
1898 1898
                     //$newmenu->add("/holiday/list.php?leftmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->holiday->read);
1899
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=list&leftmenu=hrm", Globals::$langs->trans("CPTitreMenu"), 0, Globals::$user->rights->holiday->read, '', $mainmenu, 'hrm');
1900
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=card&action=request", Globals::$langs->trans("New"), 1, Globals::$user->rights->holiday->write);
1901
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=list&leftmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->holiday->read);
1899
+                    $newmenu->add(BASE_URI."?controller=holiday&method=list&leftmenu=hrm", Globals::$langs->trans("CPTitreMenu"), 0, Globals::$user->rights->holiday->read, '', $mainmenu, 'hrm');
1900
+                    $newmenu->add(BASE_URI."?controller=holiday&method=card&action=request", Globals::$langs->trans("New"), 1, Globals::$user->rights->holiday->write);
1901
+                    $newmenu->add(BASE_URI."?controller=holiday&method=list&leftmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->holiday->read);
1902 1902
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "hrm") {
1903 1903
                         /*
1904 1904
                           $newmenu->add("/holiday/list.php?search_statut = 1&leftmenu=hrm", Globals::$langs->trans("DraftCP"), 2, Globals::$user->rights->holiday->read);
@@ -1907,18 +1907,18 @@  discard block
 block discarded – undo
1907 1907
                           $newmenu->add("/holiday/list.php?search_statut = 4&leftmenu=hrm", Globals::$langs->trans("CancelCP"), 2, Globals::$user->rights->holiday->read);
1908 1908
                           $newmenu->add("/holiday/list.php?search_statut = 5&leftmenu=hrm", Globals::$langs->trans("RefuseCP"), 2, Globals::$user->rights->holiday->read);
1909 1909
                          */
1910
-                        $newmenu->add(BASE_URI . "?controller=holiday&method=list&search_statut=1&leftmenu=hrm", Globals::$langs->trans("DraftCP"), 2, Globals::$user->rights->holiday->read);
1911
-                        $newmenu->add(BASE_URI . "?controller=holiday&method=list&search_statut=2&leftmenu=hrm", Globals::$langs->trans("ToReviewCP"), 2, Globals::$user->rights->holiday->read);
1912
-                        $newmenu->add(BASE_URI . "?controller=holiday&method=list&search_statut=3&leftmenu=hrm", Globals::$langs->trans("ApprovedCP"), 2, Globals::$user->rights->holiday->read);
1913
-                        $newmenu->add(BASE_URI . "?controller=holiday&method=list&search_statut=4&leftmenu=hrm", Globals::$langs->trans("CancelCP"), 2, Globals::$user->rights->holiday->read);
1914
-                        $newmenu->add(BASE_URI . "?controller=holiday&method=list&search_statut=5&leftmenu=hrm", Globals::$langs->trans("RefuseCP"), 2, Globals::$user->rights->holiday->read);
1910
+                        $newmenu->add(BASE_URI."?controller=holiday&method=list&search_statut=1&leftmenu=hrm", Globals::$langs->trans("DraftCP"), 2, Globals::$user->rights->holiday->read);
1911
+                        $newmenu->add(BASE_URI."?controller=holiday&method=list&search_statut=2&leftmenu=hrm", Globals::$langs->trans("ToReviewCP"), 2, Globals::$user->rights->holiday->read);
1912
+                        $newmenu->add(BASE_URI."?controller=holiday&method=list&search_statut=3&leftmenu=hrm", Globals::$langs->trans("ApprovedCP"), 2, Globals::$user->rights->holiday->read);
1913
+                        $newmenu->add(BASE_URI."?controller=holiday&method=list&search_statut=4&leftmenu=hrm", Globals::$langs->trans("CancelCP"), 2, Globals::$user->rights->holiday->read);
1914
+                        $newmenu->add(BASE_URI."?controller=holiday&method=list&search_statut=5&leftmenu=hrm", Globals::$langs->trans("RefuseCP"), 2, Globals::$user->rights->holiday->read);
1915 1915
                     }
1916 1916
                     //$newmenu->add("/holiday/define_holiday.php?action=request", Globals::$langs->trans("MenuConfCP"), 1, Globals::$user->rights->holiday->read);
1917 1917
                     //$newmenu->add("/holiday/month_report.php", Globals::$langs->trans("MenuReportMonth"), 1, Globals::$user->rights->holiday->read_all);
1918 1918
                     //$newmenu->add("/holiday/view_log.php?action=request", Globals::$langs->trans("MenuLogCP"), 1, Globals::$user->rights->holiday->define_holiday);
1919
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=define_holiday&action=request", Globals::$langs->trans("MenuConfCP"), 1, Globals::$user->rights->holiday->read);
1920
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=month_report", Globals::$langs->trans("MenuReportMonth"), 1, Globals::$user->rights->holiday->read_all);
1921
-                    $newmenu->add(BASE_URI . "?controller=holiday&method=view_log&action=request", Globals::$langs->trans("MenuLogCP"), 1, Globals::$user->rights->holiday->define_holiday);
1919
+                    $newmenu->add(BASE_URI."?controller=holiday&method=define_holiday&action=request", Globals::$langs->trans("MenuConfCP"), 1, Globals::$user->rights->holiday->read);
1920
+                    $newmenu->add(BASE_URI."?controller=holiday&method=month_report", Globals::$langs->trans("MenuReportMonth"), 1, Globals::$user->rights->holiday->read_all);
1921
+                    $newmenu->add(BASE_URI."?controller=holiday&method=view_log&action=request", Globals::$langs->trans("MenuLogCP"), 1, Globals::$user->rights->holiday->define_holiday);
1922 1922
                 }
1923 1923
 
1924 1924
                 // Trips and expenses (old module)
@@ -1930,10 +1930,10 @@  discard block
 block discarded – undo
1930 1930
                       $newmenu->add("/compta/deplacement/list.php?leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->deplacement->lire);
1931 1931
                       $newmenu->add("/compta/deplacement/stats/index.php?leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->deplacement->lire);
1932 1932
                      */
1933
-                    $newmenu->add(BASE_URI . "?controller=compta/deplacement&method=index&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("TripsAndExpenses"), 0, Globals::$user->rights->deplacement->lire, '', $mainmenu, 'tripsandexpenses');
1934
-                    $newmenu->add(BASE_URI . "?controller=compta/deplacement&method=card&action=create&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("New"), 1, Globals::$user->rights->deplacement->creer);
1935
-                    $newmenu->add(BASE_URI . "?controller=compta/deplacement&method=list&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->deplacement->lire);
1936
-                    $newmenu->add(BASE_URI . "?controller=compta/deplacement/stats&method=index&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->deplacement->lire);
1933
+                    $newmenu->add(BASE_URI."?controller=compta/deplacement&method=index&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("TripsAndExpenses"), 0, Globals::$user->rights->deplacement->lire, '', $mainmenu, 'tripsandexpenses');
1934
+                    $newmenu->add(BASE_URI."?controller=compta/deplacement&method=card&action=create&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("New"), 1, Globals::$user->rights->deplacement->creer);
1935
+                    $newmenu->add(BASE_URI."?controller=compta/deplacement&method=list&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->deplacement->lire);
1936
+                    $newmenu->add(BASE_URI."?controller=compta/deplacement/stats&method=index&leftmenu=tripsandexpenses&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->deplacement->lire);
1937 1937
                 }
1938 1938
 
1939 1939
                 // Expense report
@@ -1953,18 +1953,18 @@  discard block
 block discarded – undo
1953 1953
                       }
1954 1954
                       $newmenu->add("/expensereport/stats/index.php?leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expensereport->lire);
1955 1955
                      */
1956
-                    $newmenu->add(BASE_URI . "?controller=expensereport&method=index&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("TripsAndExpenses"), 0, Globals::$user->rights->expensereport->lire, '', $mainmenu, 'expensereport');
1957
-                    $newmenu->add(BASE_URI . "?controller=expensereport&method=card&action=create&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("New"), 1, Globals::$user->rights->expensereport->creer);
1958
-                    $newmenu->add(BASE_URI . "?controller=expensereport&method=list&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->expensereport->lire);
1956
+                    $newmenu->add(BASE_URI."?controller=expensereport&method=index&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("TripsAndExpenses"), 0, Globals::$user->rights->expensereport->lire, '', $mainmenu, 'expensereport');
1957
+                    $newmenu->add(BASE_URI."?controller=expensereport&method=card&action=create&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("New"), 1, Globals::$user->rights->expensereport->creer);
1958
+                    $newmenu->add(BASE_URI."?controller=expensereport&method=list&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("List"), 1, Globals::$user->rights->expensereport->lire);
1959 1959
                     if ($usemenuhider || empty($leftmenu) || $leftmenu == "expensereport") {
1960
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=0&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Draft"), 2, Globals::$user->rights->expensereport->lire);
1961
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=2&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Validated"), 2, Globals::$user->rights->expensereport->lire);
1962
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=5&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Approved"), 2, Globals::$user->rights->expensereport->lire);
1963
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=6&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Paid"), 2, Globals::$user->rights->expensereport->lire);
1964
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=4&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Canceled"), 2, Globals::$user->rights->expensereport->lire);
1965
-                        $newmenu->add(BASE_URI . "?controller=expensereport&method=list&search_status=99&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Refused"), 2, Globals::$user->rights->expensereport->lire);
1966
-                    }
1967
-                    $newmenu->add(BASE_URI . "?controller=expensereport/stats&method=index&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expensereport->lire);
1960
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=0&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Draft"), 2, Globals::$user->rights->expensereport->lire);
1961
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=2&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Validated"), 2, Globals::$user->rights->expensereport->lire);
1962
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=5&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Approved"), 2, Globals::$user->rights->expensereport->lire);
1963
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=6&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Paid"), 2, Globals::$user->rights->expensereport->lire);
1964
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=4&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Canceled"), 2, Globals::$user->rights->expensereport->lire);
1965
+                        $newmenu->add(BASE_URI."?controller=expensereport&method=list&search_status=99&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Refused"), 2, Globals::$user->rights->expensereport->lire);
1966
+                    }
1967
+                    $newmenu->add(BASE_URI."?controller=expensereport/stats&method=index&leftmenu=expensereport&mainmenu=hrm", Globals::$langs->trans("Statistics"), 1, Globals::$user->rights->expensereport->lire);
1968 1968
                 }
1969 1969
 
1970 1970
                 if (!empty($conf->projet->enabled)) {
@@ -1974,7 +1974,7 @@  discard block
 block discarded – undo
1974 1974
                         $search_project_user = DolUtils::GETPOST('search_project_user', 'int');
1975 1975
 
1976 1976
                         //$newmenu->add("/projet/activity/perweek.php?leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1977
-                        $newmenu->add(BASE_URI . "?controller=projet/activity&method=perweek&leftmenu=tasks" . ($search_project_user ? '&search_project_user=' . $search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1977
+                        $newmenu->add(BASE_URI."?controller=projet/activity&method=perweek&leftmenu=tasks".($search_project_user ? '&search_project_user='.$search_project_user : ''), Globals::$langs->trans("NewTimeSpent"), 0, Globals::$user->rights->projet->lire);
1978 1978
                     }
1979 1979
                 }
1980 1980
             }
@@ -1987,24 +1987,24 @@  discard block
 block discarded – undo
1987 1987
                 if (empty(Globals::$user->socid)) { // limit to internal users
1988 1988
                     Globals::$langs->load("mails");
1989 1989
                     //$newmenu->add("/admin/mails_templates.php?leftmenu=email_templates", Globals::$langs->trans("EMailTemplates"), 0, 1, '', $mainmenu, 'email_templates');
1990
-                    $newmenu->add(BASE_URI . "?controller=admin&method=mails_templates&leftmenu=email_templates", Globals::$langs->trans("EMailTemplates"), 0, 1, '', $mainmenu, 'email_templates');
1990
+                    $newmenu->add(BASE_URI."?controller=admin&method=mails_templates&leftmenu=email_templates", Globals::$langs->trans("EMailTemplates"), 0, 1, '', $mainmenu, 'email_templates');
1991 1991
                 }
1992 1992
 
1993 1993
                 if (!empty($conf->mailing->enabled)) {
1994 1994
                     //$newmenu->add("/comm/mailing/index.php?leftmenu=mailing", Globals::$langs->trans("EMailings"), 0, Globals::$user->rights->mailing->lire, '', $mainmenu, 'mailing');
1995 1995
                     //$newmenu->add("/comm/mailing/card.php?leftmenu=mailing&action=create", Globals::$langs->trans("NewMailing"), 1, Globals::$user->rights->mailing->creer);
1996 1996
                     //$newmenu->add("/comm/mailing/list.php?leftmenu=mailing", Globals::$langs->trans("List"), 1, Globals::$user->rights->mailing->lire);
1997
-                    $newmenu->add(BASE_URI . "?controller=comm/mailing&method=index&leftmenu=mailing", Globals::$langs->trans("EMailings"), 0, Globals::$user->rights->mailing->lire, '', $mainmenu, 'mailing');
1998
-                    $newmenu->add(BASE_URI . "?controller=comm/mailing&method=card&leftmenu=mailing&action=create", Globals::$langs->trans("NewMailing"), 1, Globals::$user->rights->mailing->creer);
1999
-                    $newmenu->add(BASE_URI . "?controller=comm/mailing&method=list&leftmenu=mailing", Globals::$langs->trans("List"), 1, Globals::$user->rights->mailing->lire);
1997
+                    $newmenu->add(BASE_URI."?controller=comm/mailing&method=index&leftmenu=mailing", Globals::$langs->trans("EMailings"), 0, Globals::$user->rights->mailing->lire, '', $mainmenu, 'mailing');
1998
+                    $newmenu->add(BASE_URI."?controller=comm/mailing&method=card&leftmenu=mailing&action=create", Globals::$langs->trans("NewMailing"), 1, Globals::$user->rights->mailing->creer);
1999
+                    $newmenu->add(BASE_URI."?controller=comm/mailing&method=list&leftmenu=mailing", Globals::$langs->trans("List"), 1, Globals::$user->rights->mailing->lire);
2000 2000
                 }
2001 2001
 
2002 2002
                 if (!empty($conf->export->enabled)) {
2003 2003
                     Globals::$langs->load("exports");
2004 2004
                     //$newmenu->add("/exports/index.php?leftmenu=export", Globals::$langs->trans("FormatedExport"), 0, Globals::$user->rights->export->lire, '', $mainmenu, 'export');
2005 2005
                     //$newmenu->add("/exports/export.php?leftmenu=export", Globals::$langs->trans("NewExport"), 1, Globals::$user->rights->export->creer);
2006
-                    $newmenu->add(BASE_URI . "?controller=exports&methodindex&leftmenu=export", Globals::$langs->trans("FormatedExport"), 0, Globals::$user->rights->export->lire, '', $mainmenu, 'export');
2007
-                    $newmenu->add(BASE_URI . "?controller=exports&method=export&leftmenu=export", Globals::$langs->trans("NewExport"), 1, Globals::$user->rights->export->creer);
2006
+                    $newmenu->add(BASE_URI."?controller=exports&methodindex&leftmenu=export", Globals::$langs->trans("FormatedExport"), 0, Globals::$user->rights->export->lire, '', $mainmenu, 'export');
2007
+                    $newmenu->add(BASE_URI."?controller=exports&method=export&leftmenu=export", Globals::$langs->trans("NewExport"), 1, Globals::$user->rights->export->creer);
2008 2008
                     //$newmenu->add("/exports/export.php?leftmenu=export",Globals::$langs->trans("List"),1, Globals::$user->rights->export->lire);
2009 2009
                 }
2010 2010
 
@@ -2012,8 +2012,8 @@  discard block
 block discarded – undo
2012 2012
                     Globals::$langs->load("exports");
2013 2013
                     //$newmenu->add("/imports/index.php?leftmenu=import", Globals::$langs->trans("FormatedImport"), 0, Globals::$user->rights->import->run, '', $mainmenu, 'import');
2014 2014
                     //$newmenu->add("/imports/import.php?leftmenu=import", Globals::$langs->trans("NewImport"), 1, Globals::$user->rights->import->run);
2015
-                    $newmenu->add(BASE_URI . "?controller=imports&method=index&leftmenu=import", Globals::$langs->trans("FormatedImport"), 0, Globals::$user->rights->import->run, '', $mainmenu, 'import');
2016
-                    $newmenu->add(BASE_URI . "?controller=imports&method=import&leftmenu=import", Globals::$langs->trans("NewImport"), 1, Globals::$user->rights->import->run);
2015
+                    $newmenu->add(BASE_URI."?controller=imports&method=index&leftmenu=import", Globals::$langs->trans("FormatedImport"), 0, Globals::$user->rights->import->run, '', $mainmenu, 'import');
2016
+                    $newmenu->add(BASE_URI."?controller=imports&method=import&leftmenu=import", Globals::$langs->trans("NewImport"), 1, Globals::$user->rights->import->run);
2017 2017
                 }
2018 2018
             }
2019 2019
 
@@ -2056,30 +2056,30 @@  discard block
 block discarded – undo
2056 2056
                       $newmenu->add("/adherents/type.php?leftmenu=setup&mainmenu=members&action=create", Globals::$langs->trans("New"), 1, Globals::$user->rights->adherent->configurer);
2057 2057
                       $newmenu->add("/adherents/type.php?leftmenu=setup&mainmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->configurer);
2058 2058
                      */
2059
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=index&leftmenu=members&mainmenu=members", Globals::$langs->trans("Members"), 0, Globals::$user->rights->adherent->lire, '', $mainmenu, 'members');
2060
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=card&leftmenu=members&action=create", Globals::$langs->trans("NewMember"), 1, Globals::$user->rights->adherent->creer);
2061
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->lire);
2062
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members&statut=-1", Globals::$langs->trans("MenuMembersToValidate"), 2, Globals::$user->rights->adherent->lire);
2063
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members&statut=1", Globals::$langs->trans("MenuMembersValidated"), 2, Globals::$user->rights->adherent->lire);
2064
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members&statut=1&filter = uptodate", Globals::$langs->trans("MenuMembersUpToDate"), 2, Globals::$user->rights->adherent->lire);
2065
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members&statut=1&filter = outofdate", Globals::$langs->trans("MenuMembersNotUpToDate"), 2, Globals::$user->rights->adherent->lire);
2066
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=list&leftmenu=members&statut=0", Globals::$langs->trans("MenuMembersResiliated"), 2, Globals::$user->rights->adherent->lire);
2067
-                    $newmenu->add(BASE_URI . "?controller=adherents/stats&method=index&leftmenu=members", Globals::$langs->trans("MenuMembersStats"), 1, Globals::$user->rights->adherent->lire);
2068
-                    $newmenu->add(BASE_URI . "?controller=adherents/cartes&method=carte&leftmenu=export", Globals::$langs->trans("MembersCards"), 1, Globals::$user->rights->adherent->export);
2059
+                    $newmenu->add(BASE_URI."?controller=adherents&method=index&leftmenu=members&mainmenu=members", Globals::$langs->trans("Members"), 0, Globals::$user->rights->adherent->lire, '', $mainmenu, 'members');
2060
+                    $newmenu->add(BASE_URI."?controller=adherents&method=card&leftmenu=members&action=create", Globals::$langs->trans("NewMember"), 1, Globals::$user->rights->adherent->creer);
2061
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->lire);
2062
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members&statut=-1", Globals::$langs->trans("MenuMembersToValidate"), 2, Globals::$user->rights->adherent->lire);
2063
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members&statut=1", Globals::$langs->trans("MenuMembersValidated"), 2, Globals::$user->rights->adherent->lire);
2064
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members&statut=1&filter = uptodate", Globals::$langs->trans("MenuMembersUpToDate"), 2, Globals::$user->rights->adherent->lire);
2065
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members&statut=1&filter = outofdate", Globals::$langs->trans("MenuMembersNotUpToDate"), 2, Globals::$user->rights->adherent->lire);
2066
+                    $newmenu->add(BASE_URI."?controller=adherents&method=list&leftmenu=members&statut=0", Globals::$langs->trans("MenuMembersResiliated"), 2, Globals::$user->rights->adherent->lire);
2067
+                    $newmenu->add(BASE_URI."?controller=adherents/stats&method=index&leftmenu=members", Globals::$langs->trans("MenuMembersStats"), 1, Globals::$user->rights->adherent->lire);
2068
+                    $newmenu->add(BASE_URI."?controller=adherents/cartes&method=carte&leftmenu=export", Globals::$langs->trans("MembersCards"), 1, Globals::$user->rights->adherent->export);
2069 2069
                     if (!empty(Conf::$global->MEMBER_LINK_TO_HTPASSWDFILE) && ($usemenuhider || empty($leftmenu) || $leftmenu == 'none' || $leftmenu == "members" || $leftmenu == "export")) {
2070
-                        $newmenu->add(BASE_URI . "?controller=adherents&method=htpasswd&leftmenu=export", Globals::$langs->trans("Filehtpasswd"), 1, Globals::$user->rights->adherent->export);
2070
+                        $newmenu->add(BASE_URI."?controller=adherents&method=htpasswd&leftmenu=export", Globals::$langs->trans("Filehtpasswd"), 1, Globals::$user->rights->adherent->export);
2071 2071
                     }
2072 2072
                     if (!empty($conf->categorie->enabled)) {
2073 2073
                         Globals::$langs->load("categories");
2074
-                        $newmenu->add(BASE_URI . "?controller=categories&method=index&leftmenu=cat&type=3", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
2075
-                    }
2076
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=index&leftmenu=members&mainmenu=members", Globals::$langs->trans("Subscriptions"), 0, Globals::$user->rights->adherent->cotisation->lire);
2077
-                    $newmenu->add(BASE_URI . "?controller=adherents&methodlist&leftmenu=members&statut=-1,1&mainmenu=members", Globals::$langs->trans("NewSubscription"), 1, Globals::$user->rights->adherent->cotisation->creer);
2078
-                    $newmenu->add(BASE_URI . "?controller=adherents/subscription&method=list&leftmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->cotisation->lire);
2079
-                    $newmenu->add(BASE_URI . "?controller=adherents/stats&method=index&leftmenu=members", Globals::$langs->trans("MenuMembersStats"), 1, Globals::$user->rights->adherent->lire);
2080
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=type&leftmenu=setup&mainmenu=members", Globals::$langs->trans("MembersTypes"), 0, Globals::$user->rights->adherent->configurer, '', $mainmenu, 'setup');
2081
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=type&leftmenu=setup&mainmenu=members&action=create", Globals::$langs->trans("New"), 1, Globals::$user->rights->adherent->configurer);
2082
-                    $newmenu->add(BASE_URI . "?controller=adherents&method=type&leftmenu=setup&mainmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->configurer);
2074
+                        $newmenu->add(BASE_URI."?controller=categories&method=index&leftmenu=cat&type=3", Globals::$langs->trans("Categories"), 1, Globals::$user->rights->categorie->lire, '', $mainmenu, 'cat');
2075
+                    }
2076
+                    $newmenu->add(BASE_URI."?controller=adherents&method=index&leftmenu=members&mainmenu=members", Globals::$langs->trans("Subscriptions"), 0, Globals::$user->rights->adherent->cotisation->lire);
2077
+                    $newmenu->add(BASE_URI."?controller=adherents&methodlist&leftmenu=members&statut=-1,1&mainmenu=members", Globals::$langs->trans("NewSubscription"), 1, Globals::$user->rights->adherent->cotisation->creer);
2078
+                    $newmenu->add(BASE_URI."?controller=adherents/subscription&method=list&leftmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->cotisation->lire);
2079
+                    $newmenu->add(BASE_URI."?controller=adherents/stats&method=index&leftmenu=members", Globals::$langs->trans("MenuMembersStats"), 1, Globals::$user->rights->adherent->lire);
2080
+                    $newmenu->add(BASE_URI."?controller=adherents&method=type&leftmenu=setup&mainmenu=members", Globals::$langs->trans("MembersTypes"), 0, Globals::$user->rights->adherent->configurer, '', $mainmenu, 'setup');
2081
+                    $newmenu->add(BASE_URI."?controller=adherents&method=type&leftmenu=setup&mainmenu=members&action=create", Globals::$langs->trans("New"), 1, Globals::$user->rights->adherent->configurer);
2082
+                    $newmenu->add(BASE_URI."?controller=adherents&method=type&leftmenu=setup&mainmenu=members", Globals::$langs->trans("List"), 1, Globals::$user->rights->adherent->configurer);
2083 2083
                 }
2084 2084
             }
2085 2085
 
@@ -2090,11 +2090,11 @@  discard block
 block discarded – undo
2090 2090
             //var_dump($newmenu->liste);    //
2091 2091
             // We update newmenu for special dynamic menus
2092 2092
             if (!empty(Globals::$user->rights->banque->lire) && $mainmenu == 'bank') { // Entry for each bank account
2093
-                require_once DOL_DOCUMENT_ROOT . '/compta/bank/class/account.class.php';
2093
+                require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
2094 2094
 
2095 2095
                 $sql = "SELECT rowid, label, courant, rappro";
2096
-                $sql .= " FROM " . MAIN_DB_PREFIX . "bank_account";
2097
-                $sql .= " WHERE entity = " . $conf->entity;
2096
+                $sql .= " FROM ".MAIN_DB_PREFIX."bank_account";
2097
+                $sql .= " WHERE entity = ".$conf->entity;
2098 2098
                 $sql .= " AND clos = 0";
2099 2099
                 $sql .= " ORDER BY label";
2100 2100
 
@@ -2105,16 +2105,16 @@  discard block
 block discarded – undo
2105 2105
 
2106 2106
                     if ($numr > 0) {
2107 2107
                         //$newmenu->add('/compta/bank/list.php', Globals::$langs->trans("BankAccounts"), 0, Globals::$user->rights->banque->lire);
2108
-                        $newmenu->add(BASE_URI . '?controller=compta/bank?method=list', Globals::$langs->trans("BankAccounts"), 0, Globals::$user->rights->banque->lire);
2108
+                        $newmenu->add(BASE_URI.'?controller=compta/bank?method=list', Globals::$langs->trans("BankAccounts"), 0, Globals::$user->rights->banque->lire);
2109 2109
                     }
2110 2110
 
2111 2111
                     while ($i < $numr) {
2112 2112
                         $objp = Config::$dbEngine->fetch_object($resql);
2113 2113
 //$newmenu->add('/compta/bank/card.php?id=' . $objp->rowid, $objp->label, 1, Globals::$user->rights->banque->lire);
2114
-                        $newmenu->add(BASE_URI . '?controller=compta/bank&method=card&id=' . $objp->rowid, $objp->label, 1, Globals::$user->rights->banque->lire);
2114
+                        $newmenu->add(BASE_URI.'?controller=compta/bank&method=card&id='.$objp->rowid, $objp->label, 1, Globals::$user->rights->banque->lire);
2115 2115
                         if ($objp->rappro && $objp->courant != Account::TYPE_CASH && empty($objp->clos)) {  // If not cash account and not closed and can be reconciliate
2116 2116
                             //$newmenu->add('/compta/bank/bankentries_list.php?action=reconcile&contextpage=banktransactionlist-' . $objp->rowid . '&account=' . $objp->rowid . '&id=' . $objp->rowid . '&search_conciliated=0', Globals::$langs->trans("Conciliate"), 2, Globals::$user->rights->banque->consolidate);
2117
-                            $newmenu->add(BASE_URI . '?controller=compta/bank&method=bankentries_list&action=reconcile&contextpage=banktransactionlist-' . $objp->rowid . '&account=' . $objp->rowid . '&id=' . $objp->rowid . '&search_conciliated=0', Globals::$langs->trans("Conciliate"), 2, Globals::$user->rights->banque->consolidate);
2117
+                            $newmenu->add(BASE_URI.'?controller=compta/bank&method=bankentries_list&action=reconcile&contextpage=banktransactionlist-'.$objp->rowid.'&account='.$objp->rowid.'&id='.$objp->rowid.'&search_conciliated=0', Globals::$langs->trans("Conciliate"), 2, Globals::$user->rights->banque->consolidate);
2118 2118
                         }
2119 2119
                         $i++;
2120 2120
                     }
@@ -2128,11 +2128,11 @@  discard block
 block discarded – undo
2128 2128
                 $MAXFTP = 20;
2129 2129
                 $i = 1;
2130 2130
                 while ($i <= $MAXFTP) {
2131
-                    $paramkey = 'FTP_NAME_' . $i;
2131
+                    $paramkey = 'FTP_NAME_'.$i;
2132 2132
                     //print $paramkey;
2133 2133
                     if (!empty(Conf::$global->$paramkey)) {
2134 2134
                         //$link = "/ftp/index.php?idmenu = " . $_SESSION["idmenu"] . "&numero_ftp = " . $i;
2135
-                        $link = BASE_URI . "?controller=ftp&method=index&idmenu=" . $_SESSION["idmenu"] . "&numero_ftp=" . $i;
2135
+                        $link = BASE_URI."?controller=ftp&method=index&idmenu=".$_SESSION["idmenu"]."&numero_ftp=".$i;
2136 2136
 
2137 2137
                         $newmenu->add($link, dol_trunc(Conf::$global->$paramkey, 24));
2138 2138
                     }
@@ -2193,9 +2193,9 @@  discard block
 block discarded – undo
2193 2193
                         }
2194 2194
                     }
2195 2195
                     if ($altok % 2 == 0) {
2196
-                        print '<div class="blockvmenu blockvmenuimpair' . $invert . ($lastopened ? ' blockvmenulast' : '') . ($altok == 1 ? ' blockvmenufirst' : '') . '">' . "\n";
2196
+                        print '<div class="blockvmenu blockvmenuimpair'.$invert.($lastopened ? ' blockvmenulast' : '').($altok == 1 ? ' blockvmenufirst' : '').'">'."\n";
2197 2197
                     } else {
2198
-                        print '<div class="blockvmenu blockvmenupair' . $invert . ($lastopened ? ' blockvmenulast' : '') . ($altok == 1 ? ' blockvmenufirst' : '') . '">' . "\n";
2198
+                        print '<div class="blockvmenu blockvmenupair'.$invert.($lastopened ? ' blockvmenulast' : '').($altok == 1 ? ' blockvmenufirst' : '').'">'."\n";
2199 2199
                     }
2200 2200
                 }
2201 2201
 
@@ -2217,48 +2217,48 @@  discard block
 block discarded – undo
2217 2217
                 if (!preg_match("/^(http:\/\/|https:\/\/)/i", $menu_array[$i]['url'])) {
2218 2218
                     $tmp = explode('?', $menu_array[$i]['url'], 2);
2219 2219
                     $url = $shorturl = $tmp[0];
2220
-                    $param = (isset($tmp[1]) ? $tmp[1] : '');    // params in url of the menu link
2220
+                    $param = (isset($tmp[1]) ? $tmp[1] : ''); // params in url of the menu link
2221 2221
                     // Complete param to force leftmenu to '' to close open menu when we click on a link with no leftmenu defined.
2222 2222
                     if ((!preg_match('/mainmenu/i', $param)) && (!preg_match('/leftmenu/i', $param)) && !empty($menu_array[$i]['mainmenu'])) {
2223
-                        $param .= ($param ? '&' : '') . 'mainmenu=' . $menu_array[$i]['mainmenu'] . '&leftmenu=';
2223
+                        $param .= ($param ? '&' : '').'mainmenu='.$menu_array[$i]['mainmenu'].'&leftmenu=';
2224 2224
                     }
2225 2225
                     if ((!preg_match('/mainmenu/i', $param)) && (!preg_match('/leftmenu/i', $param)) && empty($menu_array[$i]['mainmenu'])) {
2226
-                        $param .= ($param ? '&' : '') . 'leftmenu=';
2226
+                        $param .= ($param ? '&' : '').'leftmenu=';
2227 2227
                     }
2228 2228
                     //$url.="idmenu = ".$menu_array[$i]['rowid'];    // Already done by menuLoad
2229
-                    $url = DolUtils::dol_buildpath($url, 1) . ($param ? '?' . $param : '');
2229
+                    $url = DolUtils::dol_buildpath($url, 1).($param ? '?'.$param : '');
2230 2230
                     $shorturlwithoutparam = $shorturl;
2231
-                    $shorturl = $shorturl . ($param ? '?' . $param : '');
2231
+                    $shorturl = $shorturl.($param ? '?'.$param : '');
2232 2232
                 }
2233 2233
 
2234 2234
 
2235
-                print '<!-- Process menu entry with mainmenu=' . $menu_array[$i]['mainmenu'] . ', leftmenu=' . $menu_array[$i]['leftmenu'] . ', level=' . $menu_array[$i]['level'] . ' enabled=' . $menu_array[$i]['enabled'] . ', position=' . $menu_array[$i]['position'] . ' -->' . "\n";
2235
+                print '<!-- Process menu entry with mainmenu='.$menu_array[$i]['mainmenu'].', leftmenu='.$menu_array[$i]['leftmenu'].', level='.$menu_array[$i]['level'].' enabled='.$menu_array[$i]['enabled'].', position='.$menu_array[$i]['position'].' -->'."\n";
2236 2236
 
2237 2237
                 // Menu level 0
2238 2238
                 if ($menu_array[$i]['level'] == 0) {
2239 2239
                     if ($menu_array[$i]['enabled']) {     // Enabled so visible
2240
-                        print '<div class="menu_titre">' . $tabstring;
2240
+                        print '<div class="menu_titre">'.$tabstring;
2241 2241
                         if ($shorturlwithoutparam) {
2242
-                            print '<a class="vmenu" href="' . $url . '"' . ($menu_array[$i]['target'] ? ' target="' . $menu_array[$i]['target'] . '"' : '') . '>';
2242
+                            print '<a class="vmenu" href="'.$url.'"'.($menu_array[$i]['target'] ? ' target="'.$menu_array[$i]['target'].'"' : '').'>';
2243 2243
                         } else {
2244 2244
                             print '<span class="vmenu">';
2245 2245
                         }
2246
-                        print ($menu_array[$i]['prefix'] ? $menu_array[$i]['prefix'] : '') . $menu_array[$i]['titre'];
2246
+                        print ($menu_array[$i]['prefix'] ? $menu_array[$i]['prefix'] : '').$menu_array[$i]['titre'];
2247 2247
                         if ($shorturlwithoutparam) {
2248 2248
                             print '</a>';
2249 2249
                         } else {
2250 2250
                             print '</span>';
2251 2251
                         }
2252
-                        print '</div>' . "\n";
2252
+                        print '</div>'."\n";
2253 2253
                         $lastlevel0 = 'enabled';
2254 2254
                     } else if ($showmenu) {                 // Not enabled but visible (so greyed)
2255
-                        print '<div class="menu_titre">' . $tabstring . '<font class="vmenudisabled">' . $menu_array[$i]['titre'] . '</font></div>' . "\n";
2255
+                        print '<div class="menu_titre">'.$tabstring.'<font class="vmenudisabled">'.$menu_array[$i]['titre'].'</font></div>'."\n";
2256 2256
                         $lastlevel0 = 'greyed';
2257 2257
                     } else {
2258 2258
                         $lastlevel0 = 'hidden';
2259 2259
                     }
2260 2260
                     if ($showmenu) {
2261
-                        print '<div class="menu_top"></div>' . "\n";
2261
+                        print '<div class="menu_top"></div>'."\n";
2262 2262
                     }
2263 2263
                 }
2264 2264
 
@@ -2266,13 +2266,13 @@  discard block
 block discarded – undo
2266 2266
                 if ($menu_array[$i]['level'] > 0) {
2267 2267
                     $cssmenu = '';
2268 2268
                     if ($menu_array[$i]['url']) {
2269
-                        $cssmenu = ' menu_contenu' . dol_string_nospecial(preg_replace('/\.php.*$/', '', $menu_array[$i]['url']));
2269
+                        $cssmenu = ' menu_contenu'.dol_string_nospecial(preg_replace('/\.php.*$/', '', $menu_array[$i]['url']));
2270 2270
                     }
2271 2271
 
2272 2272
                     if ($menu_array[$i]['enabled'] && $lastlevel0 == 'enabled') {     // Enabled so visible, except if parent was not enabled.
2273
-                        print '<div class="menu_contenu' . $cssmenu . '">' . $tabstring;
2273
+                        print '<div class="menu_contenu'.$cssmenu.'">'.$tabstring;
2274 2274
                         if ($shorturlwithoutparam) {
2275
-                            print '<a class="vsmenu" href="' . $url . '"' . ($menu_array[$i]['target'] ? ' target="' . $menu_array[$i]['target'] . '"' : '') . '>';
2275
+                            print '<a class="vsmenu" href="'.$url.'"'.($menu_array[$i]['target'] ? ' target="'.$menu_array[$i]['target'].'"' : '').'>';
2276 2276
                         } else {
2277 2277
                             print '<span class="vsmenu">';
2278 2278
                         }
@@ -2286,26 +2286,26 @@  discard block
 block discarded – undo
2286 2286
                         if (!strstr($menu_array[$i]['titre'], '<table')) {
2287 2287
                             print '<br>';
2288 2288
                         }
2289
-                        print '</div>' . "\n";
2289
+                        print '</div>'."\n";
2290 2290
                     } else if ($showmenu && $lastlevel0 == 'enabled') {       // Not enabled but visible (so greyed), except if parent was not enabled.
2291
-                        print '<div class="menu_contenu' . $cssmenu . '">' . $tabstring . '<font class="vsmenudisabled vsmenudisabledmargin">' . $menu_array[$i]['titre'] . '</font><br></div>' . "\n";
2291
+                        print '<div class="menu_contenu'.$cssmenu.'">'.$tabstring.'<font class="vsmenudisabled vsmenudisabledmargin">'.$menu_array[$i]['titre'].'</font><br></div>'."\n";
2292 2292
                     }
2293 2293
                 }
2294 2294
 
2295 2295
                 // If next is a new block or if there is nothing after
2296 2296
                 if (empty($menu_array[$i + 1]['level'])) {               // End menu block
2297 2297
                     if ($showmenu) {
2298
-                        print '<div class="menu_end"></div>' . "\n";
2298
+                        print '<div class="menu_end"></div>'."\n";
2299 2299
                     }
2300 2300
                     if ($blockvmenuopened) {
2301
-                        print '</div>' . "\n";
2301
+                        print '</div>'."\n";
2302 2302
                         $blockvmenuopened = false;
2303 2303
                     }
2304 2304
                 }
2305 2305
             }
2306 2306
 
2307 2307
             if ($altok) {
2308
-                print '<div class="blockvmenuend"></div>';    // End menu block
2308
+                print '<div class="blockvmenuend"></div>'; // End menu block
2309 2309
             }
2310 2310
         }
2311 2311
 
Please login to merge, or discard this patch.
Braces   +34 added lines, -22 removed lines patch added patch discarded remove patch
@@ -303,8 +303,9 @@  discard block
 block discarded – undo
303 303
             if ($_SESSION["mainmenu"] && $_SESSION["mainmenu"] == "bank") {
304 304
                 $classname = 'class="tmenusel"';
305 305
                 $_SESSION['idmenu'] = '';
306
-            } else
307
-                $classname = 'class="tmenu"';
306
+            } else {
307
+                            $classname = 'class="tmenu"';
308
+            }
308 309
             $idsel = 'bank';
309 310
 
310 311
 //$menu->add('/compta/bank/list.php?mainmenu=bank&leftmenu=', Globals::$langs->trans("MenuBankCash"), 0, $showmode, $atarget, "bank", '', 52, $id, $idsel, $classname);
@@ -1383,25 +1384,33 @@  discard block
 block discarded – undo
1383 1384
                                     $nature = '';
1384 1385
 
1385 1386
 // Must match array $sourceList defined into journals_list.php
1386
-                                    if ($objp->nature == 2 && !empty($conf->facture->enabled))
1387
-                                        $nature = "sells";
1388
-                                    if ($objp->nature == 3 && !empty($conf->fournisseur->enabled))
1389
-                                        $nature = "purchases";
1390
-                                    if ($objp->nature == 4 && !empty($conf->banque->enabled))
1391
-                                        $nature = "bank";
1392
-                                    if ($objp->nature == 5 && !empty($conf->expensereport->enabled))
1393
-                                        $nature = "expensereports";
1394
-                                    if ($objp->nature == 1)
1395
-                                        $nature = "various";
1396
-                                    if ($objp->nature == 8)
1397
-                                        $nature = "inventory";
1398
-                                    if ($objp->nature == 9)
1399
-                                        $nature = "hasnew";
1387
+                                    if ($objp->nature == 2 && !empty($conf->facture->enabled)) {
1388
+                                                                            $nature = "sells";
1389
+                                    }
1390
+                                    if ($objp->nature == 3 && !empty($conf->fournisseur->enabled)) {
1391
+                                                                            $nature = "purchases";
1392
+                                    }
1393
+                                    if ($objp->nature == 4 && !empty($conf->banque->enabled)) {
1394
+                                                                            $nature = "bank";
1395
+                                    }
1396
+                                    if ($objp->nature == 5 && !empty($conf->expensereport->enabled)) {
1397
+                                                                            $nature = "expensereports";
1398
+                                    }
1399
+                                    if ($objp->nature == 1) {
1400
+                                                                            $nature = "various";
1401
+                                    }
1402
+                                    if ($objp->nature == 8) {
1403
+                                                                            $nature = "inventory";
1404
+                                    }
1405
+                                    if ($objp->nature == 9) {
1406
+                                                                            $nature = "hasnew";
1407
+                                    }
1400 1408
 
1401 1409
 // To enable when page exists
1402 1410
                                     if (empty(Conf::$global->ACCOUNTANCY_SHOW_DEVELOP_JOURNAL)) {
1403
-                                        if ($nature == 'various' || $nature == 'hasnew' || $nature == 'inventory')
1404
-                                            $nature = '';
1411
+                                        if ($nature == 'various' || $nature == 'hasnew' || $nature == 'inventory') {
1412
+                                                                                    $nature = '';
1413
+                                        }
1405 1414
                                     }
1406 1415
 
1407 1416
                                     if ($nature) {
@@ -1416,8 +1425,9 @@  discard block
 block discarded – undo
1416 1425
 // Should not happend. Entries are added
1417 1426
                                 $newmenu->add('', Globals::$langs->trans("NoJournalDefined"), 2, Globals::$user->rights->accounting->comptarapport->lire);
1418 1427
                             }
1419
-                        } else
1420
-                            dol_print_error(Config::$dbEngine);
1428
+                        } else {
1429
+                                                    dol_print_error(Config::$dbEngine);
1430
+                        }
1421 1431
                         Config::$dbEngine->free($resql);
1422 1432
                     }
1423 1433
 
@@ -1451,8 +1461,10 @@  discard block
 block discarded – undo
1451 1461
                     }
1452 1462
 
1453 1463
                     $modecompta = 'CREANCES-DETTES';
1454
-                    if (!empty($conf->accounting->enabled) && !empty(Globals::$user->rights->accounting->comptarapport->lire) && $mainmenu == 'accountancy')
1455
-                        $modecompta = 'BOOKKEEPING'; // Not yet implemented. Should be BOOKKEEPINGCOLLECTED
1464
+                    if (!empty($conf->accounting->enabled) && !empty(Globals::$user->rights->accounting->comptarapport->lire) && $mainmenu == 'accountancy') {
1465
+                                            $modecompta = 'BOOKKEEPING';
1466
+                    }
1467
+                    // Not yet implemented. Should be BOOKKEEPINGCOLLECTED
1456 1468
                     if ($modecompta) {
1457 1469
                         if ($usemenuhider || empty($leftmenu) || preg_match('/accountancy_report/', $leftmenu)) {
1458 1470
                             /*
Please login to merge, or discard this patch.
Base/MenuManager.php 1 patch
Spacing   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -38,8 +38,8 @@  discard block
 block discarded – undo
38 38
      * @var DoliDB Database handler.
39 39
      */
40 40
     // public $db;
41
-    var $type_user;         // Put 0 for internal users, 1 for external users
42
-    var $atarget = "";                                // To store default target to use onto links
41
+    var $type_user; // Put 0 for internal users, 1 for external users
42
+    var $atarget = ""; // To store default target to use onto links
43 43
     var $name = "eldy";
44 44
     var $menu_array;
45 45
     var $menu_array_after;
@@ -163,16 +163,16 @@  discard block
 block discarded – undo
163 163
 
164 164
         if ($mode == 'topnb') {
165 165
             //print_eldy_menu($this->db, $this->atarget, $this->type_user, $this->tabMenu, $this->menu, 1, $mode);  // no output
166
-            EldyLib::print_eldy_menu(Config::$dbEngine, $this->atarget, $this->type_user, $this->tabMenu, $this->menu, 1, $mode);  // no output
166
+            EldyLib::print_eldy_menu(Config::$dbEngine, $this->atarget, $this->type_user, $this->tabMenu, $this->menu, 1, $mode); // no output
167 167
             return $this->menu->getNbOfVisibleMenuEntries();
168 168
         }
169 169
 
170 170
         if ($mode == 'jmobile') {     // Used to get menu in xml ul/li
171
-            EldyLib::print_eldy_menu($this->db, $this->atarget, $this->type_user, $this->tabMenu, $this->menu, 1, $mode);      // Fill this->menu that is empty with top menu
171
+            EldyLib::print_eldy_menu($this->db, $this->atarget, $this->type_user, $this->tabMenu, $this->menu, 1, $mode); // Fill this->menu that is empty with top menu
172 172
             // $this->menu->liste is top menu
173 173
             //var_dump($this->menu->liste);exit;
174 174
             $lastlevel = array();
175
-            print '<!-- Generate menu list from menu handler ' . $this->name . ' -->' . "\n";
175
+            print '<!-- Generate menu list from menu handler '.$this->name.' -->'."\n";
176 176
             foreach ($this->menu->liste as $key => $val) {  // $val['url','titre','level','enabled'=0|1|2,'target','mainmenu','leftmenu'
177 177
                 print '<ul class="ulmenu" data-inset="true">';
178 178
                 print '<li class="lilevel0">';
@@ -193,13 +193,13 @@  discard block
 block discarded – undo
193 193
                     }
194 194
 
195 195
                     print $val['titre'];
196
-                    print '</a>' . "\n";
196
+                    print '</a>'."\n";
197 197
 
198 198
                     // Search submenu fot this mainmenu entry
199 199
                     $tmpmainmenu = $val['mainmenu'];
200 200
                     $tmpleftmenu = 'all';
201 201
                     $submenu = new Menu();
202
-                    print_left_eldy_menu($this->db, $this->menu_array, $this->menu_array_after, $this->tabMenu, $submenu, 1, $tmpmainmenu, $tmpleftmenu);       // Fill $submenu (example with tmpmainmenu='home' tmpleftmenu='all', return left menu tree of Home)
202
+                    print_left_eldy_menu($this->db, $this->menu_array, $this->menu_array_after, $this->tabMenu, $submenu, 1, $tmpmainmenu, $tmpleftmenu); // Fill $submenu (example with tmpmainmenu='home' tmpleftmenu='all', return left menu tree of Home)
203 203
                     // Note: $submenu contains menu entry with substitution not yet done
204 204
                     //if ($tmpmainmenu.'-'.$tmpleftmenu == 'home-all') { var_dump($submenu); exit; }
205 205
                     //if ($tmpmainmenu=='accountancy') { var_dump($submenu->liste); exit; }
@@ -209,21 +209,21 @@  discard block
 block discarded – undo
209 209
                     $canonnexturl = preg_replace('/\?.*$/', '', $nexturl);
210 210
                     //var_dump($canonrelurl);
211 211
                     //var_dump($canonnexturl);
212
-                    print '<ul>' . "\n";
212
+                    print '<ul>'."\n";
213 213
                     if (($canonrelurl != $canonnexturl && !in_array($val['mainmenu'], array('tools'))) || (strpos($canonrelurl, '/product/index.php') !== false || strpos($canonrelurl, '/compta/bank/list.php') !== false)) {
214 214
                         // We add sub entry
215
-                        print str_pad('', 1) . '<li class="lilevel1 ui-btn-icon-right ui-btn">';  // ui-btn to highlight on clic
216
-                        print '<a href="' . $relurl . '">';
217
-                        if ($langs->trans(ucfirst($val['mainmenu']) . "Dashboard") == ucfirst($val['mainmenu']) . "Dashboard") {  // No translation
215
+                        print str_pad('', 1).'<li class="lilevel1 ui-btn-icon-right ui-btn">'; // ui-btn to highlight on clic
216
+                        print '<a href="'.$relurl.'">';
217
+                        if ($langs->trans(ucfirst($val['mainmenu'])."Dashboard") == ucfirst($val['mainmenu'])."Dashboard") {  // No translation
218 218
                             if (in_array($val['mainmenu'], array('cashdesk', 'externalsite', 'website', 'collab'))) {
219 219
                                 print $langs->trans("Access");
220 220
                             } else {
221 221
                                 print $langs->trans("Dashboard");
222 222
                             }
223 223
                         } else
224
-                            print $langs->trans(ucfirst($val['mainmenu']) . "Dashboard");
224
+                            print $langs->trans(ucfirst($val['mainmenu'])."Dashboard");
225 225
                         print '</a>';
226
-                        print '</li>' . "\n";
226
+                        print '</li>'."\n";
227 227
                     }
228 228
 
229 229
                     if ($val['level'] == 0) {
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
                         if ($showmenu) {  // Visible (option to hide when not allowed is off or allowed)
258 258
                             $substitarray = array('__LOGIN__' => $user->login, '__USER_ID__' => $user->id, '__USER_SUPERVISOR_ID__' => $user->fk_user);
259 259
                             $substitarray['__USERID__'] = $user->id; // For backward compatibility
260
-                            $val2['url'] = make_substitutions($val2['url'], $substitarray);  // Make also substitution of __(XXX)__ and __[XXX]__
260
+                            $val2['url'] = make_substitutions($val2['url'], $substitarray); // Make also substitution of __(XXX)__ and __[XXX]__
261 261
 
262 262
                             if (!preg_match("/^(http:\/\/|https:\/\/)/i", $val2['url'])) {
263 263
                                 $relurl2 = dol_buildpath($val2['url'], 1);
@@ -276,14 +276,14 @@  discard block
 block discarded – undo
276 276
                             }
277 277
 
278 278
                             print str_pad('', $val2['level'] + 1);
279
-                            print '<li class="lilevel' . ($val2['level'] + 1);
279
+                            print '<li class="lilevel'.($val2['level'] + 1);
280 280
                             if ($val2['level'] == 0) {
281
-                                print ' ui-btn-icon-right ui-btn';  // ui-btn to highlight on clic
281
+                                print ' ui-btn-icon-right ui-btn'; // ui-btn to highlight on clic
282 282
                             }
283
-                            print $disabled . '">';  // ui-btn to highlight on clic
283
+                            print $disabled.'">'; // ui-btn to highlight on clic
284 284
                             if ($relurl2) {
285 285
                                 if ($val2['enabled']) { // Allowed
286
-                                    print '<a href="' . $relurl2 . '"';
286
+                                    print '<a href="'.$relurl2.'"';
287 287
                                     //print ' data-ajax="false"';
288 288
                                     print '>';
289 289
                                     $lastlevel2[$val2['level']] = 'enabled';
@@ -307,17 +307,17 @@  discard block
 block discarded – undo
307 307
                                 else
308 308
                                     print '</a>';
309 309
                             }
310
-                            print '</li>' . "\n";
310
+                            print '</li>'."\n";
311 311
                         }
312 312
                     }
313 313
                     //var_dump($submenu);
314 314
                     print '</ul>';
315 315
                 }
316 316
                 if ($val['enabled'] == 2) {
317
-                    print '<font class="vsmenudisabled">' . $val['titre'] . '</font>';
317
+                    print '<font class="vsmenudisabled">'.$val['titre'].'</font>';
318 318
                 }
319 319
                 print '</li>';
320
-                print '</ul>' . "\n";
320
+                print '</ul>'."\n";
321 321
             }
322 322
         }
323 323
 
Please login to merge, or discard this patch.
Base/AlixarView.php 2 patches
Spacing   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -116,7 +116,7 @@  discard block
 block discarded – undo
116 116
 // html header
117 117
         $this->top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss);
118 118
 
119
-        print '<body id="mainbody"' . ($morecssonbody ? ' class="' . $morecssonbody . '"' : '') . '>' . "\n";
119
+        print '<body id="mainbody"'.($morecssonbody ? ' class="'.$morecssonbody.'"' : '').'>'."\n";
120 120
 
121 121
 // top menu and left menu area
122 122
         if (empty(Globals::$conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) {
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
         }
125 125
 
126 126
         if (empty(Globals::$conf->dol_hide_leftmenu)) {
127
-            $this->left_menu('', $help_url, '', '', 1, $title, 1);  // $menumanager is retreived with a global $menumanager inside this function
127
+            $this->left_menu('', $help_url, '', '', 1, $title, 1); // $menumanager is retreived with a global $menumanager inside this function
128 128
         }
129 129
 
130 130
 // main area
@@ -175,13 +175,13 @@  discard block
 block discarded – undo
175 175
          * Top menu
176 176
          */
177 177
         if ((empty(Globals::$conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
178
-            print "\n" . '<!-- Start top horizontal -->' . "\n";
178
+            print "\n".'<!-- Start top horizontal -->'."\n";
179 179
 
180
-            print '<div class="side-nav-vert' . (DolUtils::GETPOST('dol_invisible_topmenu', 'int') ? ' hidden' : '') . '"><div id="id-top">';  // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
180
+            print '<div class="side-nav-vert'.(DolUtils::GETPOST('dol_invisible_topmenu', 'int') ? ' hidden' : '').'"><div id="id-top">'; // dol_invisible_topmenu differs from dol_hide_topmenu: dol_invisible_topmenu means we output menu but we make it invisible.
181 181
 // Show menu entries
182
-            print '<div id="tmenu_tooltip' . (empty(Globals::$conf->global->MAIN_MENU_INVERT) ? '' : 'invert') . '" class="tmenu">' . "\n";
182
+            print '<div id="tmenu_tooltip'.(empty(Globals::$conf->global->MAIN_MENU_INVERT) ? '' : 'invert').'" class="tmenu">'."\n";
183 183
             $this->menumanager->atarget = $target;
184
-            $this->menumanager->showmenu('top', array('searchform' => $searchform, 'bookmarks' => $bookmarks));      // This contains a \n
184
+            $this->menumanager->showmenu('top', array('searchform' => $searchform, 'bookmarks' => $bookmarks)); // This contains a \n
185 185
             print "</div>\n";
186 186
 
187 187
 // Define link to login card
@@ -189,36 +189,36 @@  discard block
 block discarded – undo
189 189
             if (!empty(Globals::$conf->global->MAIN_APPLICATION_TITLE)) {
190 190
                 $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
191 191
                 if (preg_match('/\d\.\d/', $appli)) {
192
-                    if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli))
193
-                        $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
192
+                    if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli))
193
+                        $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
194 194
                 } else
195
-                    $appli .= " " . DOL_VERSION;
195
+                    $appli .= " ".DOL_VERSION;
196 196
             } else
197
-                $appli .= " " . DOL_VERSION;
197
+                $appli .= " ".DOL_VERSION;
198 198
 
199 199
             if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL))
200
-                $appli .= "<br>" . Globals::$langs->trans("LevelOfFeature") . ': ' . Globals::$conf->global->MAIN_FEATURES_LEVEL;
200
+                $appli .= "<br>".Globals::$langs->trans("LevelOfFeature").': '.Globals::$conf->global->MAIN_FEATURES_LEVEL;
201 201
 
202 202
             $logouttext = '';
203 203
             if (empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
204 204
 //$logouthtmltext=$appli.'<br>';
205 205
                 $logouthtmltext = '';
206 206
                 if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { {
207
-                        $logouthtmltext .= Globals::$langs->trans("Logout") . '<br>';
207
+                        $logouthtmltext .= Globals::$langs->trans("Logout").'<br>';
208 208
                     }
209 209
 
210 210
 //$logouttext .='<a accesskey="l" href="'.DOL_BASE_URI.'/user/logout.php">';
211
-                    $logouttext .= '<a accesskey="l" href="' . BASE_URI . '?controller=user&method=logout">';
211
+                    $logouttext .= '<a accesskey="l" href="'.BASE_URI.'?controller=user&method=logout">';
212 212
 //$logouttext .= img_picto(Globals::$langs->trans('Logout').":".Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
213 213
                     $logouttext .= '<span class="fa fa-sign-out atoplogin"></span>';
214 214
                     $logouttext .= '</a>';
215 215
                 } else {
216 216
                     $logouthtmltext .= Globals::$langs->trans("NoLogoutProcessWithAuthMode", $_SESSION["dol_authmode"]);
217
-                    $logouttext .= img_picto(Globals::$langs->trans('Logout') . ":" . Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
217
+                    $logouttext .= img_picto(Globals::$langs->trans('Logout').":".Globals::$langs->trans('Logout'), 'logout_top.png', 'class="login"', 0, 0, 1);
218 218
                 }
219 219
             }
220 220
 
221
-            print '<div class="login_block">' . "\n";
221
+            print '<div class="login_block">'."\n";
222 222
 
223 223
 // Add login user link
224 224
             $toprightmenu .= '<div class="login_block_user">';
@@ -229,18 +229,18 @@  discard block
 block discarded – undo
229 229
             $toprightmenu .= Globals::$user->getNomUrl($mode, '', 1, 0, 11, 0, (Globals::$user->firstname ? 'firstname' : -1), 'atoplogin');
230 230
             $toprightmenu .= '</div></div>';
231 231
 
232
-            $toprightmenu .= '</div>' . "\n";
232
+            $toprightmenu .= '</div>'."\n";
233 233
 
234 234
             $toprightmenu .= '<div class="login_block_other">';
235 235
 
236 236
 // Execute hook printTopRightMenu (hooks should output string like '<div class="login"><a href="">mylink</a></div>')
237 237
             $parameters = array();
238
-            $result = Globals::$hookManager->executeHooks('printTopRightMenu', $parameters);    // Note that $action and $object may have been modified by some hooks
238
+            $result = Globals::$hookManager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks
239 239
             if (is_numeric($result)) {
240 240
                 if ($result == 0)
241
-                    $toprightmenu .= Globals::$hookManager->resPrint;  // add
241
+                    $toprightmenu .= Globals::$hookManager->resPrint; // add
242 242
                 else
243
-                    $toprightmenu = Globals::$hookManager->resPrint;      // replace
243
+                    $toprightmenu = Globals::$hookManager->resPrint; // replace
244 244
             }
245 245
             else {
246 246
                 $toprightmenu .= $result; // For backward compatibility
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 // Link to module builder
250 250
             if (!empty(Globals::$conf->modulebuilder->enabled)) {
251 251
 //$text = '<a href="' . DOL_BASE_URI . '/modulebuilder/index.php?mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
252
-                $text = '<a href="' . BASE_URI . '?controller=modulebuilder&method=index&mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
252
+                $text = '<a href="'.BASE_URI.'?controller=modulebuilder&method=index&mainmenu=home&leftmenu=admintools" target="_modulebuilder">';
253 253
 //$text.= img_picto(":".Globals::$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"');
254 254
                 $text .= '<span class="fa fa-bug atoplogin"></span>';
255 255
                 $text .= '</a>';
@@ -263,12 +263,12 @@  discard block
 block discarded – undo
263 263
                 if (is_array($_POST)) {
264 264
                     foreach ($_POST as $key => $value) {
265 265
                         if ($key !== 'action' && $key !== 'password' && !is_array($value)) {
266
-                            $qs .= '&' . $key . '=' . urlencode($value);
266
+                            $qs .= '&'.$key.'='.urlencode($value);
267 267
                         }
268 268
                     }
269 269
                 }
270
-                $qs .= (($qs && $morequerystring) ? '&' : '') . $morequerystring;
271
-                $text = '<a href="' . dol_escape_htmltag($_SERVER["PHP_SELF"]) . '?' . $qs . ($qs ? '&' : '') . 'optioncss=print" target="_blank">';
270
+                $qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring;
271
+                $text = '<a href="'.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.$qs.($qs ? '&' : '').'optioncss=print" target="_blank">';
272 272
 //$text.= img_picto(":".Globals::$langs->trans("PrintContentArea"), 'printer_top.png', 'class="printer"');
273 273
                 $text .= '<span class="fa fa-print atoplogin"></span>';
274 274
                 $text .= '</a>';
@@ -297,12 +297,12 @@  discard block
 block discarded – undo
297 297
                     $text = '';
298 298
                     if (!empty(Globals::$conf->global->MAIN_SHOWDATABASENAMEINHELPPAGESLINK)) {
299 299
                         Globals::$langs->load('admin');
300
-                        $appli .= '<br>' . Globals::$langs->trans("Database") . ': ' . $db->database_name;
300
+                        $appli .= '<br>'.Globals::$langs->trans("Database").': '.$db->database_name;
301 301
                     }
302
-                    $title = $appli . '<br>';
302
+                    $title = $appli.'<br>';
303 303
                     $title .= Globals::$langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage');
304 304
                     if ($mode == 'wiki') {
305
-                        $title .= ' - ' . Globals::$langs->trans("PageWiki") . ' &quot;' . dol_escape_htmltag(strtr($helppage, '_', ' ')) . '&quot;';
305
+                        $title .= ' - '.Globals::$langs->trans("PageWiki").' &quot;'.dol_escape_htmltag(strtr($helppage, '_', ' ')).'&quot;';
306 306
                     }
307 307
                     $text .= '<a class="help" target="_blank" rel="noopener" href="';
308 308
                     if ($mode == 'wiki') {
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
 
329 329
             print $toprightmenu;
330 330
 
331
-            print "</div>\n";  // end div class="login_block"
331
+            print "</div>\n"; // end div class="login_block"
332 332
 
333 333
             print '</div></div>';
334 334
 
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
         }
338 338
 
339 339
         if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile))
340
-            print '<!-- Begin div id-container --><div id="id-container" class="id-container' . ($morecss ? ' ' . $morecss : '') . '">';
340
+            print '<!-- Begin div id-container --><div id="id-container" class="id-container'.($morecss ? ' '.$morecss : '').'">';
341 341
     }
342 342
 
343 343
     /**
@@ -369,7 +369,7 @@  discard block
 block discarded – undo
369 369
 // Instantiate hooks of thirdparty module
370 370
             Globals::$hookManager->initHooks(array('searchform', 'leftblock'));
371 371
 
372
-            print "\n" . '<!-- Begin side-nav id-left -->' . "\n" . '<div class="side-nav"><div id="id-left">' . "\n";
372
+            print "\n".'<!-- Begin side-nav id-left -->'."\n".'<div class="side-nav"><div id="id-left">'."\n";
373 373
 
374 374
             if (Globals::$conf->browser->layout == 'phone')
375 375
                 Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
@@ -381,7 +381,7 @@  discard block
 block discarded – undo
381 381
             }
382 382
             $selected = -1;
383 383
             $usedbyinclude = 1;
384
-            include_once DOL_BASE_PATH . '/core/ajax/selectsearchbox.php'; // This set $arrayresult
384
+            include_once DOL_BASE_PATH.'/core/ajax/selectsearchbox.php'; // This set $arrayresult
385 385
 
386 386
             if (Globals::$conf->use_javascript_ajax && empty(Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM)) {
387 387
 //$searchform.=$form->selectArrayAjax('searchselectcombo', DOL_BASE_URI.'/core/ajax/selectsearchbox.php', $selected, '', '', 0, 1, 'vmenusearchselectcombo', 1, Globals::$langs->trans("Search"), 1);
@@ -396,7 +396,7 @@  discard block
 block discarded – undo
396 396
 // Execute hook printSearchForm
397 397
             $parameters = array('searchform' => $searchform);
398 398
 
399
-            $reshook = Globals::$hookManager->executeHooks('printSearchForm', $parameters);    // Note that $action and $object may have been modified by some hooks
399
+            $reshook = Globals::$hookManager->executeHooks('printSearchForm', $parameters); // Note that $action and $object may have been modified by some hooks
400 400
             if (empty($reshook)) {
401 401
                 $searchform .= Globals::$hookManager->resPrint;
402 402
             } else
@@ -404,10 +404,10 @@  discard block
 block discarded – undo
404 404
 
405 405
 // Force special value for $searchform
406 406
             if (!empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty(Globals::$conf->use_javascript_ajax)) {
407
-                $urltosearch = DOL_BASE_URI . '/core/search_page.php?showtitlebefore=1';
408
-                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="' . $urltosearch . '" alt="' . dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")) . '">' . Globals::$langs->trans("Search") . '...</a></div></div>';
407
+                $urltosearch = DOL_BASE_URI.'/core/search_page.php?showtitlebefore=1';
408
+                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="'.$urltosearch.'" alt="'.dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")).'">'.Globals::$langs->trans("Search").'...</a></div></div>';
409 409
             } elseif (Globals::$conf->use_javascript_ajax && !empty(Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM)) {
410
-                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="' . dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")) . '">' . Globals::$langs->trans("Search") . '...</a></div><div id="divsearchforms2" style="display: none">' . $searchform . '</div>';
410
+                $searchform = '<div class="blockvmenuimpair blockvmenusearchphone"><div id="divsearchforms1"><a href="#" alt="'.dol_escape_htmltag(Globals::$langs->trans("ShowSearchFields")).'">'.Globals::$langs->trans("Search").'...</a></div><div id="divsearchforms2" style="display: none">'.$searchform.'</div>';
411 411
                 $searchform .= '<script type="text/javascript">
412 412
             	jQuery(document).ready(function () {
413 413
             		jQuery("#divsearchforms1").click(function(){
@@ -420,16 +420,16 @@  discard block
 block discarded – undo
420 420
 
421 421
 // Define $bookmarks
422 422
             if (!empty(Globals::$conf->bookmark->enabled) && Globals::$user->rights->bookmark->lire) {
423
-                include_once DOL_BASE_PATH . '/bookmarks/bookmarks.lib.php';
423
+                include_once DOL_BASE_PATH.'/bookmarks/bookmarks.lib.php';
424 424
                 Globals::$langs->load("bookmarks");
425 425
 
426 426
                 $bookmarks = printBookmarksList($db, Globals::$langs);
427 427
             }
428 428
 
429 429
 // Left column
430
-            print '<!-- Begin left menu -->' . "\n";
430
+            print '<!-- Begin left menu -->'."\n";
431 431
 
432
-            print '<div class="vmenu"' . (empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"') . '>' . "\n\n";
432
+            print '<div class="vmenu"'.(empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' title="Left menu"').'>'."\n\n";
433 433
 
434 434
 // Show left menu with other forms
435 435
             $this->menumanager->menu_array = $menu_array_before;
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 // Dolibarr version + help + bug report link
439 439
             print "\n";
440 440
             print "<!-- Begin Help Block-->\n";
441
-            print '<div id="blockvmenuhelp" class="blockvmenuhelp">' . "\n";
441
+            print '<div id="blockvmenuhelp" class="blockvmenuhelp">'."\n";
442 442
 
443 443
 // Version
444 444
             if (empty(Globals::$conf->global->MAIN_HIDE_VERSION)) {    // Version is already on help picto and on login page.
@@ -460,15 +460,15 @@  discard block
 block discarded – undo
460 460
                     $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
461 461
                     $doliurl = '';
462 462
                     if (preg_match('/\d\.\d/', $appli)) {
463
-                        if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli))
464
-                            $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
463
+                        if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli))
464
+                            $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core
465 465
                     } else
466
-                        $appli .= " " . DOL_VERSION;
466
+                        $appli .= " ".DOL_VERSION;
467 467
                 } else
468
-                    $appli .= " " . DOL_VERSION;
468
+                    $appli .= " ".DOL_VERSION;
469 469
                 print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
470 470
                 if ($doliurl)
471
-                    print '<a class="help" target="_blank" rel="noopener" href="' . $doliurl . '">';
471
+                    print '<a class="help" target="_blank" rel="noopener" href="'.$doliurl.'">';
472 472
                 else
473 473
                     print '<span class="help">';
474 474
                 print $appli;
@@ -476,12 +476,12 @@  discard block
 block discarded – undo
476 476
                     print '</a>';
477 477
                 else
478 478
                     print '</span>';
479
-                print '</div>' . "\n";
479
+                print '</div>'."\n";
480 480
             }
481 481
 
482 482
 // Link to bugtrack
483 483
             if (!empty(Globals::$conf->global->MAIN_BUGTRACK_ENABLELINK)) {
484
-                require_once DOL_BASE_PATH . '/core/lib/functions2.lib.php';
484
+                require_once DOL_BASE_PATH.'/core/lib/functions2.lib.php';
485 485
 
486 486
                 $bugbaseurl = 'https://github.com/Dolibarr/dolibarr/issues/new';
487 487
                 $bugbaseurl .= '?title=';
@@ -490,16 +490,16 @@  discard block
 block discarded – undo
490 490
                 $bugbaseurl .= urlencode("# Bug\n");
491 491
                 $bugbaseurl .= urlencode("\n");
492 492
                 $bugbaseurl .= urlencode("## Environment\n");
493
-                $bugbaseurl .= urlencode("- **Version**: " . DOL_VERSION . "\n");
494
-                $bugbaseurl .= urlencode("- **OS**: " . php_uname('s') . "\n");
495
-                $bugbaseurl .= urlencode("- **Web server**: " . $_SERVER["SERVER_SOFTWARE"] . "\n");
496
-                $bugbaseurl .= urlencode("- **PHP**: " . php_sapi_name() . ' ' . phpversion() . "\n");
497
-                $bugbaseurl .= urlencode("- **Database**: " . $db::LABEL . ' ' . $db->getVersion() . "\n");
498
-                $bugbaseurl .= urlencode("- **URL**: " . $_SERVER["REQUEST_URI"] . "\n");
493
+                $bugbaseurl .= urlencode("- **Version**: ".DOL_VERSION."\n");
494
+                $bugbaseurl .= urlencode("- **OS**: ".php_uname('s')."\n");
495
+                $bugbaseurl .= urlencode("- **Web server**: ".$_SERVER["SERVER_SOFTWARE"]."\n");
496
+                $bugbaseurl .= urlencode("- **PHP**: ".php_sapi_name().' '.phpversion()."\n");
497
+                $bugbaseurl .= urlencode("- **Database**: ".$db::LABEL.' '.$db->getVersion()."\n");
498
+                $bugbaseurl .= urlencode("- **URL**: ".$_SERVER["REQUEST_URI"]."\n");
499 499
                 $bugbaseurl .= urlencode("\n");
500 500
                 $bugbaseurl .= urlencode("## Report\n");
501 501
                 print '<div id="blockvmenuhelpbugreport" class="blockvmenuhelp">';
502
-                print '<a class="help" target="_blank" rel="noopener" href="' . $bugbaseurl . '">' . Globals::$langs->trans("FindBug") . '</a>';
502
+                print '<a class="help" target="_blank" rel="noopener" href="'.$bugbaseurl.'">'.Globals::$langs->trans("FindBug").'</a>';
503 503
                 print '</div>';
504 504
             }
505 505
 
@@ -513,14 +513,14 @@  discard block
 block discarded – undo
513 513
 
514 514
 // Execute hook printLeftBlock
515 515
             $parameters = array();
516
-            $reshook = Globals::$hookManager->executeHooks('printLeftBlock', $parameters);    // Note that $action and $object may have been modified by some hooks
516
+            $reshook = Globals::$hookManager->executeHooks('printLeftBlock', $parameters); // Note that $action and $object may have been modified by some hooks
517 517
             print Globals::$hookManager->resPrint;
518 518
 
519 519
             print '</div></div> <!-- End side-nav id-left -->'; // End div id="side-nav" div id="id-left"
520 520
         }
521 521
 
522 522
         print "\n";
523
-        print '<!-- Begin right area -->' . "\n";
523
+        print '<!-- Begin right area -->'."\n";
524 524
 
525 525
         if (empty($leftmenuwithoutmainarea))
526 526
             main_area($title);
@@ -541,7 +541,7 @@  discard block
 block discarded – undo
541 541
 
542 542
         print "\n";
543 543
 
544
-        print '<!-- Begin div class="fiche" -->' . "\n" . '<div class="fiche">' . "\n";
544
+        print '<!-- Begin div class="fiche" -->'."\n".'<div class="fiche">'."\n";
545 545
 
546 546
         if (!empty(Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED))
547 547
             print info_admin(Globals::$langs->trans("WarningYouAreInMaintenanceMode", Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
@@ -607,17 +607,17 @@  discard block
 block discarded – undo
607 607
         // global Globals::$conf, Globals::$langs, Globals::$user;
608 608
 
609 609
         $ret = '';
610
-        $ret .= '<form action="' . $urlaction . '" method="post" class="searchform">';
611
-        $ret .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
610
+        $ret .= '<form action="'.$urlaction.'" method="post" class="searchform">';
611
+        $ret .= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
612 612
         $ret .= '<input type="hidden" name="mode" value="search">';
613
-        $ret .= '<input type="hidden" name="savelogin" value="' . dol_escape_htmltag(Globals::$user->login) . '">';
613
+        $ret .= '<input type="hidden" name="savelogin" value="'.dol_escape_htmltag(Globals::$user->login).'">';
614 614
         if ($showtitlebefore)
615
-            $ret .= $title . ' ';
616
-        $ret .= '<input type="text" class="flat ' . $htmlmorecss . '"';
617
-        $ret .= ' style="text-indent: 22px; background-image: url(\'' . $img . '\'); background-repeat: no-repeat; background-position: 3px;"';
618
-        $ret .= ($accesskey ? ' accesskey="' . $accesskey . '"' : '');
619
-        $ret .= ' placeholder="' . strip_tags($title) . '"';
620
-        $ret .= ' name="' . $htmlinputname . '" id="' . $prefhtmlinputname . $htmlinputname . '" />';
615
+            $ret .= $title.' ';
616
+        $ret .= '<input type="text" class="flat '.$htmlmorecss.'"';
617
+        $ret .= ' style="text-indent: 22px; background-image: url(\''.$img.'\'); background-repeat: no-repeat; background-position: 3px;"';
618
+        $ret .= ($accesskey ? ' accesskey="'.$accesskey.'"' : '');
619
+        $ret .= ' placeholder="'.strip_tags($title).'"';
620
+        $ret .= ' name="'.$htmlinputname.'" id="'.$prefhtmlinputname.$htmlinputname.'" />';
621 621
 //$ret.='<input type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px" value="'.Globals::$langs->trans("Go").'">';
622 622
         $ret .= '<button type="submit" class="button" style="padding-top: 4px; padding-bottom: 4px; padding-left: 6px; padding-right: 6px">';
623 623
         $ret .= '<span class="fa fa-search"></span>';
@@ -642,7 +642,7 @@  discard block
 block discarded – undo
642 642
         // global $delayedhtmlcontent;
643 643
         // global $contextpage, $page, $limit;
644 644
 
645
-        $ext = 'layout=' . Globals::$conf->browser->layout . '&version=' . urlencode(DOL_VERSION);
645
+        $ext = 'layout='.Globals::$conf->browser->layout.'&version='.urlencode(DOL_VERSION);
646 646
 
647 647
 // Global html output events ($mesgs, $errors, $warnings)
648 648
         dol_htmloutput_events($disabledoutputofmessages);
@@ -652,15 +652,15 @@  discard block
 block discarded – undo
652 652
         if (is_object(Globals::$user) && !empty(Globals::$user->lastsearch_values_tmp) && is_array(Globals::$user->lastsearch_values_tmp)) {
653 653
 // Clean and save data
654 654
             foreach (Globals::$user->lastsearch_values_tmp as $key => $val) {
655
-                unset($_SESSION['lastsearch_values_tmp_' . $key]);   // Clean array to rebuild it just after
655
+                unset($_SESSION['lastsearch_values_tmp_'.$key]); // Clean array to rebuild it just after
656 656
                 if (count($val) && empty($_POST['button_removefilter'])) { // If there is search criteria to save and we did not click on 'Clear filter' button
657 657
                     if (empty($val['sortfield']))
658 658
                         unset($val['sortfield']);
659 659
                     if (empty($val['sortorder']))
660 660
                         unset($val['sortorder']);
661
-                    dol_syslog('Save lastsearch_values_tmp_' . $key . '=' . json_encode($val, 0) . " (systematic recording of last search criterias)");
662
-                    $_SESSION['lastsearch_values_tmp_' . $key] = json_encode($val);
663
-                    unset($_SESSION['lastsearch_values_' . $key]);
661
+                    dol_syslog('Save lastsearch_values_tmp_'.$key.'='.json_encode($val, 0)." (systematic recording of last search criterias)");
662
+                    $_SESSION['lastsearch_values_tmp_'.$key] = json_encode($val);
663
+                    unset($_SESSION['lastsearch_values_'.$key]);
664 664
                 }
665 665
             }
666 666
         }
@@ -669,37 +669,37 @@  discard block
 block discarded – undo
669 669
         $relativepathstring = $_SERVER["PHP_SELF"];
670 670
 // Clean $relativepathstring
671 671
         if (constant('DOL_BASE_URI'))
672
-            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
672
+            $relativepathstring = preg_replace('/^'.preg_quote(constant('DOL_BASE_URI'), '/').'/', '', $relativepathstring);
673 673
         $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
674 674
         $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
675 675
         if (preg_match('/list\.php$/', $relativepathstring)) {
676
-            unset($_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring]);
677
-            unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
678
-            unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
676
+            unset($_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring]);
677
+            unset($_SESSION['lastsearch_page_tmp_'.$relativepathstring]);
678
+            unset($_SESSION['lastsearch_limit_tmp_'.$relativepathstring]);
679 679
 
680 680
             if (!empty($contextpage))
681
-                $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring] = $contextpage;
681
+                $_SESSION['lastsearch_contextpage_tmp_'.$relativepathstring] = $contextpage;
682 682
             if (!empty($page) && $page > 1)
683
-                $_SESSION['lastsearch_page_tmp_' . $relativepathstring] = $page;
683
+                $_SESSION['lastsearch_page_tmp_'.$relativepathstring] = $page;
684 684
             if (!empty($limit) && $limit != Globals::$conf->limit)
685
-                $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] = $limit;
685
+                $_SESSION['lastsearch_limit_tmp_'.$relativepathstring] = $limit;
686 686
 
687
-            unset($_SESSION['lastsearch_contextpage_' . $relativepathstring]);
688
-            unset($_SESSION['lastsearch_page_' . $relativepathstring]);
689
-            unset($_SESSION['lastsearch_limit_' . $relativepathstring]);
687
+            unset($_SESSION['lastsearch_contextpage_'.$relativepathstring]);
688
+            unset($_SESSION['lastsearch_page_'.$relativepathstring]);
689
+            unset($_SESSION['lastsearch_limit_'.$relativepathstring]);
690 690
         }
691 691
 
692 692
 // Core error message
693 693
         if (!empty(Globals::$conf->global->MAIN_CORE_ERROR)) {
694 694
 // Ajax version
695 695
             if (Globals::$conf->use_javascript_ajax) {
696
-                $title = img_warning() . ' ' . Globals::$langs->trans('CoreErrorTitle');
696
+                $title = img_warning().' '.Globals::$langs->trans('CoreErrorTitle');
697 697
                 print ajax_dialog($title, Globals::$langs->trans('CoreErrorMessage'));
698 698
             }
699 699
 // html version
700 700
             else {
701
-                $msg = img_warning() . ' ' . Globals::$langs->trans('CoreErrorMessage');
702
-                print '<div class="error">' . $msg . '</div>';
701
+                $msg = img_warning().' '.Globals::$langs->trans('CoreErrorMessage');
702
+                print '<div class="error">'.$msg.'</div>';
703 703
             }
704 704
 
705 705
 //define("MAIN_CORE_ERROR",0);      // Constant was defined and we can't change value of a constant
@@ -707,17 +707,17 @@  discard block
 block discarded – undo
707 707
 
708 708
         print "\n\n";
709 709
 
710
-        print '</div> <!-- End div class="fiche" -->' . "\n"; // End div fiche
710
+        print '</div> <!-- End div class="fiche" -->'."\n"; // End div fiche
711 711
 
712 712
         if (empty(Globals::$conf->dol_hide_leftmenu))
713
-            print '</div> <!-- End div id-right -->' . "\n"; // End div id-right
713
+            print '</div> <!-- End div id-right -->'."\n"; // End div id-right
714 714
 
715 715
         if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile))
716
-            print '</div> <!-- End div id-container -->' . "\n"; // End div container
716
+            print '</div> <!-- End div id-container -->'."\n"; // End div container
717 717
 
718 718
         print "\n";
719 719
         if ($comment)
720
-            print '<!-- ' . $comment . ' -->' . "\n";
720
+            print '<!-- '.$comment.' -->'."\n";
721 721
 
722 722
         printCommonFooter($zone);
723 723
 
@@ -725,8 +725,8 @@  discard block
 block discarded – undo
725 725
             print $delayedhtmlcontent;
726 726
 
727 727
         if (!empty(Globals::$conf->use_javascript_ajax)) {
728
-            print "\n" . '<!-- Includes JS Footer of Dolibarr -->' . "\n";
729
-            print '<script type="text/javascript" src="' . BASE_URI . '?controller=core/js/&method=lib_foot.js&lang=' . Globals::$langs->defaultlang . ($ext ? '&' . $ext : '') . '"></script>' . "\n";
728
+            print "\n".'<!-- Includes JS Footer of Dolibarr -->'."\n";
729
+            print '<script type="text/javascript" src="'.BASE_URI.'?controller=core/js/&method=lib_foot.js&lang='.Globals::$langs->defaultlang.($ext ? '&'.$ext : '').'"></script>'."\n";
730 730
         }
731 731
 
732 732
 // Wrapper to add log when clicking on download or preview
@@ -738,7 +738,7 @@  discard block
 block discarded – undo
738 738
                 <script type="text/javascript">
739 739
                     jQuery(document).ready(function () {
740 740
                         $('a.documentpreview').click(function () {
741
-                            $.post('<?php echo DOL_BASE_URI . "/blockedlog/ajax/block-add.php" ?>'
741
+                            $.post('<?php echo DOL_BASE_URI."/blockedlog/ajax/block-add.php" ?>'
742 742
                                     , {
743 743
                                         id:<?php echo $object->id; ?>
744 744
                                         , element: '<?php echo $object->element ?>'
@@ -747,7 +747,7 @@  discard block
 block discarded – undo
747 747
                             );
748 748
                         });
749 749
                         $('a.documentdownload').click(function () {
750
-                            $.post('<?php echo DOL_BASE_URI . "/blockedlog/ajax/block-add.php" ?>'
750
+                            $.post('<?php echo DOL_BASE_URI."/blockedlog/ajax/block-add.php" ?>'
751 751
                                     , {
752 752
                                         id:<?php echo $object->id; ?>
753 753
                                         , element: '<?php echo $object->element ?>'
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
 
764 764
 // A div for the address popup
765 765
         print "\n<!-- A div to allow dialog popup -->\n";
766
-        print '<div id="dialogforpopup" style="display: none;"></div>' . "\n";
766
+        print '<div id="dialogforpopup" style="display: none;"></div>'."\n";
767 767
 
768 768
         print "</body>\n";
769 769
 
Please login to merge, or discard this patch.
Braces   +123 added lines, -80 removed lines patch added patch discarded remove patch
@@ -189,15 +189,20 @@  discard block
 block discarded – undo
189 189
             if (!empty(Globals::$conf->global->MAIN_APPLICATION_TITLE)) {
190 190
                 $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
191 191
                 if (preg_match('/\d\.\d/', $appli)) {
192
-                    if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli))
193
-                        $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
194
-                } else
195
-                    $appli .= " " . DOL_VERSION;
196
-            } else
197
-                $appli .= " " . DOL_VERSION;
192
+                    if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
193
+                                            $appli .= " (" . DOL_VERSION . ")";
194
+                    }
195
+                    // If new title contains a version that is different than core
196
+                } else {
197
+                                    $appli .= " " . DOL_VERSION;
198
+                }
199
+            } else {
200
+                            $appli .= " " . DOL_VERSION;
201
+            }
198 202
 
199
-            if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL))
200
-                $appli .= "<br>" . Globals::$langs->trans("LevelOfFeature") . ': ' . Globals::$conf->global->MAIN_FEATURES_LEVEL;
203
+            if (!empty(Globals::$conf->global->MAIN_FEATURES_LEVEL)) {
204
+                            $appli .= "<br>" . Globals::$langs->trans("LevelOfFeature") . ': ' . Globals::$conf->global->MAIN_FEATURES_LEVEL;
205
+            }
201 206
 
202 207
             $logouttext = '';
203 208
             if (empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
@@ -237,12 +242,15 @@  discard block
 block discarded – undo
237 242
             $parameters = array();
238 243
             $result = Globals::$hookManager->executeHooks('printTopRightMenu', $parameters);    // Note that $action and $object may have been modified by some hooks
239 244
             if (is_numeric($result)) {
240
-                if ($result == 0)
241
-                    $toprightmenu .= Globals::$hookManager->resPrint;  // add
242
-                else
243
-                    $toprightmenu = Globals::$hookManager->resPrint;      // replace
244
-            }
245
-            else {
245
+                if ($result == 0) {
246
+                                    $toprightmenu .= Globals::$hookManager->resPrint;
247
+                }
248
+                // add
249
+                else {
250
+                                    $toprightmenu = Globals::$hookManager->resPrint;
251
+                }
252
+                // replace
253
+            } else {
246 254
                 $toprightmenu .= $result; // For backward compatibility
247 255
             }
248 256
 
@@ -336,8 +344,9 @@  discard block
 block discarded – undo
336 344
             print "<!-- End top horizontal menu -->\n\n";
337 345
         }
338 346
 
339
-        if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile))
340
-            print '<!-- Begin div id-container --><div id="id-container" class="id-container' . ($morecss ? ' ' . $morecss : '') . '">';
347
+        if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile)) {
348
+                    print '<!-- Begin div id-container --><div id="id-container" class="id-container' . ($morecss ? ' ' . $morecss : '') . '">';
349
+        }
341 350
     }
342 351
 
343 352
     /**
@@ -362,8 +371,9 @@  discard block
 block discarded – undo
362 371
         $searchform = '';
363 372
         $bookmarks = '';
364 373
 
365
-        if (!empty($menu_array_before))
366
-            dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
374
+        if (!empty($menu_array_before)) {
375
+                    dol_syslog("Deprecated parameter menu_array_before was used when calling main::left_menu function. Menu entries of module should now be defined into module descriptor and not provided when calling left_menu.", LOG_WARNING);
376
+        }
367 377
 
368 378
         if (empty(Globals::$conf->dol_hide_leftmenu) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) {
369 379
 // Instantiate hooks of thirdparty module
@@ -371,8 +381,10 @@  discard block
 block discarded – undo
371 381
 
372 382
             print "\n" . '<!-- Begin side-nav id-left -->' . "\n" . '<div class="side-nav"><div id="id-left">' . "\n";
373 383
 
374
-            if (Globals::$conf->browser->layout == 'phone')
375
-                Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM = 1; // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
384
+            if (Globals::$conf->browser->layout == 'phone') {
385
+                            Globals::$conf->global->MAIN_USE_OLD_SEARCH_FORM = 1;
386
+            }
387
+            // Select into select2 is awfull on smartphone. TODO Is this still true with select2 v4 ?
376 388
 
377 389
             print "\n";
378 390
 
@@ -399,8 +411,9 @@  discard block
 block discarded – undo
399 411
             $reshook = Globals::$hookManager->executeHooks('printSearchForm', $parameters);    // Note that $action and $object may have been modified by some hooks
400 412
             if (empty($reshook)) {
401 413
                 $searchform .= Globals::$hookManager->resPrint;
402
-            } else
403
-                $searchform = Globals::$hookManager->resPrint;
414
+            } else {
415
+                            $searchform = Globals::$hookManager->resPrint;
416
+            }
404 417
 
405 418
 // Force special value for $searchform
406 419
             if (!empty(Globals::$conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) || empty(Globals::$conf->use_javascript_ajax)) {
@@ -444,38 +457,49 @@  discard block
 block discarded – undo
444 457
             if (empty(Globals::$conf->global->MAIN_HIDE_VERSION)) {    // Version is already on help picto and on login page.
445 458
                 $doliurl = 'https://www.dolibarr.org';
446 459
 //local communities
447
-                if (preg_match('/fr/i', Globals::$langs->defaultlang))
448
-                    $doliurl = 'https://www.dolibarr.fr';
449
-                if (preg_match('/es/i', Globals::$langs->defaultlang))
450
-                    $doliurl = 'https://www.dolibarr.es';
451
-                if (preg_match('/de/i', Globals::$langs->defaultlang))
452
-                    $doliurl = 'https://www.dolibarr.de';
453
-                if (preg_match('/it/i', Globals::$langs->defaultlang))
454
-                    $doliurl = 'https://www.dolibarr.it';
455
-                if (preg_match('/gr/i', Globals::$langs->defaultlang))
456
-                    $doliurl = 'https://www.dolibarr.gr';
460
+                if (preg_match('/fr/i', Globals::$langs->defaultlang)) {
461
+                                    $doliurl = 'https://www.dolibarr.fr';
462
+                }
463
+                if (preg_match('/es/i', Globals::$langs->defaultlang)) {
464
+                                    $doliurl = 'https://www.dolibarr.es';
465
+                }
466
+                if (preg_match('/de/i', Globals::$langs->defaultlang)) {
467
+                                    $doliurl = 'https://www.dolibarr.de';
468
+                }
469
+                if (preg_match('/it/i', Globals::$langs->defaultlang)) {
470
+                                    $doliurl = 'https://www.dolibarr.it';
471
+                }
472
+                if (preg_match('/gr/i', Globals::$langs->defaultlang)) {
473
+                                    $doliurl = 'https://www.dolibarr.gr';
474
+                }
457 475
 
458 476
                 $appli = constant('DOL_APPLICATION_TITLE');
459 477
                 if (!empty(Globals::$conf->global->MAIN_APPLICATION_TITLE)) {
460 478
                     $appli = Globals::$conf->global->MAIN_APPLICATION_TITLE;
461 479
                     $doliurl = '';
462 480
                     if (preg_match('/\d\.\d/', $appli)) {
463
-                        if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli))
464
-                            $appli .= " (" . DOL_VERSION . ")"; // If new title contains a version that is different than core
465
-                    } else
466
-                        $appli .= " " . DOL_VERSION;
467
-                } else
468
-                    $appli .= " " . DOL_VERSION;
481
+                        if (!preg_match('/' . preg_quote(DOL_VERSION) . '/', $appli)) {
482
+                                                    $appli .= " (" . DOL_VERSION . ")";
483
+                        }
484
+                        // If new title contains a version that is different than core
485
+                    } else {
486
+                                            $appli .= " " . DOL_VERSION;
487
+                    }
488
+                } else {
489
+                                    $appli .= " " . DOL_VERSION;
490
+                }
469 491
                 print '<div id="blockvmenuhelpapp" class="blockvmenuhelp">';
470
-                if ($doliurl)
471
-                    print '<a class="help" target="_blank" rel="noopener" href="' . $doliurl . '">';
472
-                else
473
-                    print '<span class="help">';
492
+                if ($doliurl) {
493
+                                    print '<a class="help" target="_blank" rel="noopener" href="' . $doliurl . '">';
494
+                } else {
495
+                                    print '<span class="help">';
496
+                }
474 497
                 print $appli;
475
-                if ($doliurl)
476
-                    print '</a>';
477
-                else
478
-                    print '</span>';
498
+                if ($doliurl) {
499
+                                    print '</a>';
500
+                } else {
501
+                                    print '</span>';
502
+                }
479 503
                 print '</div>' . "\n";
480 504
             }
481 505
 
@@ -522,8 +546,9 @@  discard block
 block discarded – undo
522 546
         print "\n";
523 547
         print '<!-- Begin right area -->' . "\n";
524 548
 
525
-        if (empty($leftmenuwithoutmainarea))
526
-            main_area($title);
549
+        if (empty($leftmenuwithoutmainarea)) {
550
+                    main_area($title);
551
+        }
527 552
     }
528 553
 
529 554
     /**
@@ -536,15 +561,17 @@  discard block
 block discarded – undo
536 561
     {
537 562
 // global Globals::$conf, Globals::$langs;
538 563
 
539
-        if (empty(Globals::$conf->dol_hide_leftmenu))
540
-            print '<div id="id-right">';
564
+        if (empty(Globals::$conf->dol_hide_leftmenu)) {
565
+                    print '<div id="id-right">';
566
+        }
541 567
 
542 568
         print "\n";
543 569
 
544 570
         print '<!-- Begin div class="fiche" -->' . "\n" . '<div class="fiche">' . "\n";
545 571
 
546
-        if (!empty(Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED))
547
-            print info_admin(Globals::$langs->trans("WarningYouAreInMaintenanceMode", Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
572
+        if (!empty(Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED)) {
573
+                    print info_admin(Globals::$langs->trans("WarningYouAreInMaintenanceMode", Globals::$conf->global->MAIN_ONLY_LOGIN_ALLOWED));
574
+        }
548 575
     }
549 576
 
550 577
     /**
@@ -569,18 +596,21 @@  discard block
 block discarded – undo
569 596
 // If WIKI URL
570 597
             if (preg_match('/^es/i', Globals::$langs->defaultlang)) {
571 598
                 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
572
-                if (preg_match('/ES:([^|]+)/i', $helppagename, $reg))
573
-                    $helppage = $reg[1];
599
+                if (preg_match('/ES:([^|]+)/i', $helppagename, $reg)) {
600
+                                    $helppage = $reg[1];
601
+                }
574 602
             }
575 603
             if (preg_match('/^fr/i', Globals::$langs->defaultlang)) {
576 604
                 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
577
-                if (preg_match('/FR:([^|]+)/i', $helppagename, $reg))
578
-                    $helppage = $reg[1];
605
+                if (preg_match('/FR:([^|]+)/i', $helppagename, $reg)) {
606
+                                    $helppage = $reg[1];
607
+                }
579 608
             }
580 609
             if (empty($helppage)) { // If help page not already found
581 610
                 $helpbaseurl = 'http://wiki.dolibarr.org/index.php/%s';
582
-                if (preg_match('/EN:([^|]+)/i', $helppagename, $reg))
583
-                    $helppage = $reg[1];
611
+                if (preg_match('/EN:([^|]+)/i', $helppagename, $reg)) {
612
+                                    $helppage = $reg[1];
613
+                }
584 614
             }
585 615
             $mode = 'wiki';
586 616
         }
@@ -611,8 +641,9 @@  discard block
 block discarded – undo
611 641
         $ret .= '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
612 642
         $ret .= '<input type="hidden" name="mode" value="search">';
613 643
         $ret .= '<input type="hidden" name="savelogin" value="' . dol_escape_htmltag(Globals::$user->login) . '">';
614
-        if ($showtitlebefore)
615
-            $ret .= $title . ' ';
644
+        if ($showtitlebefore) {
645
+                    $ret .= $title . ' ';
646
+        }
616 647
         $ret .= '<input type="text" class="flat ' . $htmlmorecss . '"';
617 648
         $ret .= ' style="text-indent: 22px; background-image: url(\'' . $img . '\'); background-repeat: no-repeat; background-position: 3px;"';
618 649
         $ret .= ($accesskey ? ' accesskey="' . $accesskey . '"' : '');
@@ -654,10 +685,12 @@  discard block
 block discarded – undo
654 685
             foreach (Globals::$user->lastsearch_values_tmp as $key => $val) {
655 686
                 unset($_SESSION['lastsearch_values_tmp_' . $key]);   // Clean array to rebuild it just after
656 687
                 if (count($val) && empty($_POST['button_removefilter'])) { // If there is search criteria to save and we did not click on 'Clear filter' button
657
-                    if (empty($val['sortfield']))
658
-                        unset($val['sortfield']);
659
-                    if (empty($val['sortorder']))
660
-                        unset($val['sortorder']);
688
+                    if (empty($val['sortfield'])) {
689
+                                            unset($val['sortfield']);
690
+                    }
691
+                    if (empty($val['sortorder'])) {
692
+                                            unset($val['sortorder']);
693
+                    }
661 694
                     dol_syslog('Save lastsearch_values_tmp_' . $key . '=' . json_encode($val, 0) . " (systematic recording of last search criterias)");
662 695
                     $_SESSION['lastsearch_values_tmp_' . $key] = json_encode($val);
663 696
                     unset($_SESSION['lastsearch_values_' . $key]);
@@ -668,8 +701,9 @@  discard block
 block discarded – undo
668 701
 
669 702
         $relativepathstring = $_SERVER["PHP_SELF"];
670 703
 // Clean $relativepathstring
671
-        if (constant('DOL_BASE_URI'))
672
-            $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
704
+        if (constant('DOL_BASE_URI')) {
705
+                    $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
706
+        }
673 707
         $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
674 708
         $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
675 709
         if (preg_match('/list\.php$/', $relativepathstring)) {
@@ -677,12 +711,15 @@  discard block
 block discarded – undo
677 711
             unset($_SESSION['lastsearch_page_tmp_' . $relativepathstring]);
678 712
             unset($_SESSION['lastsearch_limit_tmp_' . $relativepathstring]);
679 713
 
680
-            if (!empty($contextpage))
681
-                $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring] = $contextpage;
682
-            if (!empty($page) && $page > 1)
683
-                $_SESSION['lastsearch_page_tmp_' . $relativepathstring] = $page;
684
-            if (!empty($limit) && $limit != Globals::$conf->limit)
685
-                $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] = $limit;
714
+            if (!empty($contextpage)) {
715
+                            $_SESSION['lastsearch_contextpage_tmp_' . $relativepathstring] = $contextpage;
716
+            }
717
+            if (!empty($page) && $page > 1) {
718
+                            $_SESSION['lastsearch_page_tmp_' . $relativepathstring] = $page;
719
+            }
720
+            if (!empty($limit) && $limit != Globals::$conf->limit) {
721
+                            $_SESSION['lastsearch_limit_tmp_' . $relativepathstring] = $limit;
722
+            }
686 723
 
687 724
             unset($_SESSION['lastsearch_contextpage_' . $relativepathstring]);
688 725
             unset($_SESSION['lastsearch_page_' . $relativepathstring]);
@@ -709,20 +746,26 @@  discard block
 block discarded – undo
709 746
 
710 747
         print '</div> <!-- End div class="fiche" -->' . "\n"; // End div fiche
711 748
 
712
-        if (empty(Globals::$conf->dol_hide_leftmenu))
713
-            print '</div> <!-- End div id-right -->' . "\n"; // End div id-right
749
+        if (empty(Globals::$conf->dol_hide_leftmenu)) {
750
+                    print '</div> <!-- End div id-right -->' . "\n";
751
+        }
752
+        // End div id-right
714 753
 
715
-        if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile))
716
-            print '</div> <!-- End div id-container -->' . "\n"; // End div container
754
+        if (empty(Globals::$conf->dol_hide_leftmenu) && empty(Globals::$conf->dol_use_jmobile)) {
755
+                    print '</div> <!-- End div id-container -->' . "\n";
756
+        }
757
+        // End div container
717 758
 
718 759
         print "\n";
719
-        if ($comment)
720
-            print '<!-- ' . $comment . ' -->' . "\n";
760
+        if ($comment) {
761
+                    print '<!-- ' . $comment . ' -->' . "\n";
762
+        }
721 763
 
722 764
         printCommonFooter($zone);
723 765
 
724
-        if (!empty($delayedhtmlcontent))
725
-            print $delayedhtmlcontent;
766
+        if (!empty($delayedhtmlcontent)) {
767
+                    print $delayedhtmlcontent;
768
+        }
726 769
 
727 770
         if (!empty(Globals::$conf->use_javascript_ajax)) {
728 771
             print "\n" . '<!-- Includes JS Footer of Dolibarr -->' . "\n";
Please login to merge, or discard this patch.
Base/User.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -2963,7 +2963,7 @@
 block discarded – undo
2963 2963
     function load_state_board()
2964 2964
     {
2965 2965
 // phpcs:enable
2966
-       // global $conf;
2966
+        // global $conf;
2967 2967
 
2968 2968
         $this->nb = array();
2969 2969
 
Please login to merge, or discard this patch.
Spacing   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
     public $skype;
56 56
     public $twitter;
57 57
     public $facebook;
58
-    public $job;   // job position
58
+    public $job; // job position
59 59
     public $signature;
60 60
 
61 61
     /**
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
     public $address;
65 65
     public $zip;
66 66
     public $town;
67
-    public $state_id;  // The state/department
67
+    public $state_id; // The state/department
68 68
     public $state_code;
69 69
     public $state;
70 70
     public $office_phone;
@@ -118,26 +118,26 @@  discard block
 block discarded – undo
118 118
     public $datepreviouslogin;
119 119
     public $photo;
120 120
     public $lang;
121
-    public $rights;                        // Array of permissions user->rights->permx
122
-    public $all_permissions_are_loaded;    // All permission are loaded
123
-    public $nb_rights;              // Number of rights granted to the user
124
-    private $_tab_loaded = array();     // Cache array of already loaded permissions
125
-    public $conf;             // To store personal config
126
-    public $default_values;         // To store default values for user
127
-    public $lastsearch_values_tmp;  // To store current search criterias for user
128
-    public $lastsearch_values;      // To store last saved search criterias for user
129
-    public $users = array();  // To store all tree of users hierarchy
130
-    public $parentof;    // To store an array of all parents for all ids.
121
+    public $rights; // Array of permissions user->rights->permx
122
+    public $all_permissions_are_loaded; // All permission are loaded
123
+    public $nb_rights; // Number of rights granted to the user
124
+    private $_tab_loaded = array(); // Cache array of already loaded permissions
125
+    public $conf; // To store personal config
126
+    public $default_values; // To store default values for user
127
+    public $lastsearch_values_tmp; // To store current search criterias for user
128
+    public $lastsearch_values; // To store last saved search criterias for user
129
+    public $users = array(); // To store all tree of users hierarchy
130
+    public $parentof; // To store an array of all parents for all ids.
131 131
     private $cache_childids;
132
-    public $accountancy_code;   // Accountancy code in prevision of the complete accountancy module
133
-    public $thm;     // Average cost of employee - Used for valuation of time spent
134
-    public $tjm;     // Average cost of employee
135
-    public $salary;     // Monthly salary       - Denormalized value from llx_user_employment
136
-    public $salaryextra;    // Monthly salary extra - Denormalized value from llx_user_employment
137
-    public $weeklyhours;    // Weekly hours         - Denormalized value from llx_user_employment
138
-    public $color;      // Define background color for user in agenda
139
-    public $dateemployment;   // Define date of employment by company
140
-    public $dateemploymentend;  // Define date of employment end by company
132
+    public $accountancy_code; // Accountancy code in prevision of the complete accountancy module
133
+    public $thm; // Average cost of employee - Used for valuation of time spent
134
+    public $tjm; // Average cost of employee
135
+    public $salary; // Monthly salary       - Denormalized value from llx_user_employment
136
+    public $salaryextra; // Monthly salary extra - Denormalized value from llx_user_employment
137
+    public $weeklyhours; // Weekly hours         - Denormalized value from llx_user_employment
138
+    public $color; // Define background color for user in agenda
139
+    public $dateemployment; // Define date of employment by company
140
+    public $dateemploymentend; // Define date of employment end by company
141 141
     public $default_c_exp_tax_cat;
142 142
     public $default_range;
143 143
     public $fields = array(
@@ -212,37 +212,37 @@  discard block
 block discarded – undo
212 212
         $sql .= " u.color,";
213 213
         $sql .= " u.dateemployment, u.dateemploymentend,";
214 214
         $sql .= " u.ref_int, u.ref_ext,";
215
-        $sql .= " u.default_range, u.default_c_exp_tax_cat,";   // Expense report default mode
215
+        $sql .= " u.default_range, u.default_c_exp_tax_cat,"; // Expense report default mode
216 216
         $sql .= " c.code as country_code, c.label as country,";
217 217
         $sql .= " d.code_departement as state_code, d.nom as state";
218
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
219
-        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_country as c ON u.fk_country = c.rowid";
220
-        $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "c_departements as d ON u.fk_state = d.rowid";
218
+        $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
219
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON u.fk_country = c.rowid";
220
+        $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as d ON u.fk_state = d.rowid";
221 221
 
222 222
         if ($entity < 0) {
223 223
             if ((empty($conf->multicompany->enabled) || empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) && (!empty(Globals::$user->entity))) {
224
-                $sql .= " WHERE u.entity IN (0," . Globals::$conf->entity . ")";
224
+                $sql .= " WHERE u.entity IN (0,".Globals::$conf->entity.")";
225 225
             } else {
226
-                $sql .= " WHERE u.entity IS NOT NULL";    // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
226
+                $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
227 227
             }
228 228
         } else {  // The fetch was forced on an entity
229 229
             if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
230
-                $sql .= " WHERE u.entity IS NOT NULL";    // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
230
+                $sql .= " WHERE u.entity IS NOT NULL"; // multicompany is on in transverse mode or user making fetch is on entity 0, so user is allowed to fetch anywhere into database
231 231
             } else {
232
-                $sql .= " WHERE u.entity IN (0, " . (($entity != '' && $entity >= 0) ? $entity : Globals::$conf->entity) . ")";   // search in entity provided in parameter
232
+                $sql .= " WHERE u.entity IN (0, ".(($entity != '' && $entity >= 0) ? $entity : Globals::$conf->entity).")"; // search in entity provided in parameter
233 233
             }
234 234
         }
235 235
 
236 236
         if ($sid) {    // permet une recherche du user par son SID ActiveDirectory ou Samba
237 237
 //$sql .= " AND (u.ldap_sid = '" . Config::$dbEngine->escape($sid) . "' OR u.login = '" . Config::$dbEngine->escape($login) . "') LIMIT 1";
238
-            $sql .= " AND (u.ldap_sid = '" . $sid . "' OR u.login = '" . Config::$dbEngine->escape($login) . "') LIMIT 1";
238
+            $sql .= " AND (u.ldap_sid = '".$sid."' OR u.login = '".Config::$dbEngine->escape($login)."') LIMIT 1";
239 239
         } else if ($login) {
240 240
 // $sql .= " AND u.login = '" . Config::$dbEngine->escape($login) . "'";
241
-            $sql .= " AND u.login = '" . $login . "'";
241
+            $sql .= " AND u.login = '".$login."'";
242 242
         } else {
243
-            $sql .= " AND u.rowid = " . $id;
243
+            $sql .= " AND u.rowid = ".$id;
244 244
         }
245
-        $sql .= " ORDER BY u.entity ASC";    // Avoid random result when there is 2 login in 2 different entities
245
+        $sql .= " ORDER BY u.entity ASC"; // Avoid random result when there is 2 login in 2 different entities
246 246
 
247 247
         $result = Config::$dbEngine->select($sql);
248 248
 // echo "<p>SQL in 2477 of User: '$sql'</p>";
@@ -328,7 +328,7 @@  discard block
 block discarded – undo
328 328
                 $this->datelastlogin = $obj->datel;
329 329
                 $this->datepreviouslogin = $obj->datep;
330 330
 
331
-                $this->societe_id = $obj->fk_soc;  // deprecated
331
+                $this->societe_id = $obj->fk_soc; // deprecated
332 332
                 $this->contact_id = $obj->fk_socpeople; // deprecated
333 333
                 $this->socid = $obj->fk_soc;
334 334
                 $this->contactid = $obj->fk_socpeople;
@@ -349,7 +349,7 @@  discard block
 block discarded – undo
349 349
                 $this->fetch_optionals();
350 350
             } else {
351 351
                 $this->error = "USERNOTFOUND";
352
-                DolUtils::dol_syslog(get_class($this) . "::fetch user not found", LOG_DEBUG);
352
+                DolUtils::dol_syslog(get_class($this)."::fetch user not found", LOG_DEBUG);
353 353
                 return 0;
354 354
             }
355 355
         } else {
@@ -360,9 +360,9 @@  discard block
 block discarded – undo
360 360
 // To get back the global configuration unique to the user
361 361
         if ($loadpersonalconf) {
362 362
 // Load user->conf for user
363
-            $sql = "SELECT param, value FROM " . MAIN_DB_PREFIX . "user_param";
364
-            $sql .= " WHERE fk_user = " . $this->id;
365
-            $sql .= " AND entity = " . Globals::$conf->entity;
363
+            $sql = "SELECT param, value FROM ".MAIN_DB_PREFIX."user_param";
364
+            $sql .= " WHERE fk_user = ".$this->id;
365
+            $sql .= " AND entity = ".Globals::$conf->entity;
366 366
 //DolUtils::dol_syslog(get_class($this).'::fetch load personalized conf', LOG_DEBUG);
367 367
             $resql = Config::$dbEngine->select($sql);
368 368
             if (is_array($resql)) {
@@ -400,9 +400,9 @@  discard block
 block discarded – undo
400 400
 // global $conf;
401 401
 // Load user->default_values for user. TODO Save this in memcached ?
402 402
         $sql = "SELECT rowid, entity, type, page, param, value";
403
-        $sql .= " FROM " . MAIN_DB_PREFIX . "default_values";
404
-        $sql .= " WHERE entity IN (" . ($this->entity > 0 ? $this->entity . ", " : "") . Globals::$conf->entity . ")"; // Entity of user (if defined) + current entity
405
-        $sql .= " AND user_id IN (0" . ($this->id > 0 ? ", " . $this->id : "") . ")";       // User 0 (all) + me (if defined)
403
+        $sql .= " FROM ".MAIN_DB_PREFIX."default_values";
404
+        $sql .= " WHERE entity IN (".($this->entity > 0 ? $this->entity.", " : "").Globals::$conf->entity.")"; // Entity of user (if defined) + current entity
405
+        $sql .= " AND user_id IN (0".($this->id > 0 ? ", ".$this->id : "").")"; // User 0 (all) + me (if defined)
406 406
         $resql = Config::$dbEngine->select($sql);
407 407
         if (is_array($resql)) {
408 408
             foreach ($resql as $array) {
@@ -450,7 +450,7 @@  discard block
 block discarded – undo
450 450
 
451 451
         $entity = (!empty($entity) ? $entity : Globals::$conf->entity);
452 452
 
453
-        DolUtils::dol_syslog(get_class($this) . "::addrights $rid, $allmodule, $allperms, $entity");
453
+        DolUtils::dol_syslog(get_class($this)."::addrights $rid, $allmodule, $allperms, $entity");
454 454
         $error = 0;
455 455
         $whereforadd = '';
456 456
 
@@ -460,9 +460,9 @@  discard block
 block discarded – undo
460 460
 // Si on a demande ajout d'un droit en particulier, on recupere
461 461
 // les caracteristiques (module, perms et subperms) de ce droit.
462 462
             $sql = "SELECT module, perms, subperms";
463
-            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
464
-            $sql .= " WHERE id = '" . Config::$dbEngine->escape($rid) . "'";
465
-            $sql .= " AND entity = " . $entity;
463
+            $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
464
+            $sql .= " WHERE id = '".Config::$dbEngine->escape($rid)."'";
465
+            $sql .= " AND entity = ".$entity;
466 466
 
467 467
             $result = Config::$dbEngine->query($sql);
468 468
             if ($result) {
@@ -476,7 +476,7 @@  discard block
 block discarded – undo
476 476
             }
477 477
 
478 478
 // Where pour la liste des droits a ajouter
479
-            $whereforadd = "id=" . Config::$dbEngine->escape($rid);
479
+            $whereforadd = "id=".Config::$dbEngine->escape($rid);
480 480
 // Ajout des droits induits
481 481
             if (!empty($subperms)) {
482 482
                 $whereforadd .= " OR (module='$module' AND perms='$perms' AND (subperms='lire' OR subperms='read'))";
@@ -493,9 +493,9 @@  discard block
 block discarded – undo
493 493
                 if ($allmodule == 'allmodules') {
494 494
                     $whereforadd = 'allmodules';
495 495
                 } else {
496
-                    $whereforadd = "module='" . Config::$dbEngine->escape($allmodule) . "'";
496
+                    $whereforadd = "module='".Config::$dbEngine->escape($allmodule)."'";
497 497
                     if (!empty($allperms)) {
498
-                        $whereforadd .= " AND perms='" . Config::$dbEngine->escape($allperms) . "'";
498
+                        $whereforadd .= " AND perms='".Config::$dbEngine->escape($allperms)."'";
499 499
                     }
500 500
                 }
501 501
             }
@@ -505,10 +505,10 @@  discard block
 block discarded – undo
505 505
         if (!empty($whereforadd)) {
506 506
 //print "$module-$perms-$subperms";
507 507
             $sql = "SELECT id";
508
-            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
509
-            $sql .= " WHERE entity = " . $entity;
508
+            $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
509
+            $sql .= " WHERE entity = ".$entity;
510 510
             if (!empty($whereforadd) && $whereforadd != 'allmodules') {
511
-                $sql .= " AND " . $whereforadd;
511
+                $sql .= " AND ".$whereforadd;
512 512
             }
513 513
 
514 514
             $result = Config::$dbEngine->query($sql);
@@ -519,10 +519,10 @@  discard block
 block discarded – undo
519 519
                     $obj = Config::$dbEngine->fetch_object($result);
520 520
                     $nid = $obj->id;
521 521
 
522
-                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id . " AND fk_id=" . $nid . " AND entity = " . $entity;
522
+                    $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id." AND fk_id=".$nid." AND entity = ".$entity;
523 523
                     if (!Config::$dbEngine->query($sql))
524 524
                         $error++;
525
-                    $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (entity, fk_user, fk_id) VALUES (" . $entity . ", " . $this->id . ", " . $nid . ")";
525
+                    $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (entity, fk_user, fk_id) VALUES (".$entity.", ".$this->id.", ".$nid.")";
526 526
                     if (!Config::$dbEngine->query($sql))
527 527
                         $error++;
528 528
 
@@ -537,7 +537,7 @@  discard block
 block discarded – undo
537 537
 
538 538
         if (!$error && !$notrigger) {
539 539
             Globals::$langs->load("other");
540
-            $this->context = array('audit' => Globals::$langs->trans("PermissionsAdd") . ($rid ? ' (id=' . $rid . ')' : ''));
540
+            $this->context = array('audit' => Globals::$langs->trans("PermissionsAdd").($rid ? ' (id='.$rid.')' : ''));
541 541
 
542 542
 // Call trigger
543 543
             $result = $this->call_trigger('USER_MODIFY', Globals::$user);
@@ -581,9 +581,9 @@  discard block
 block discarded – undo
581 581
 // Si on a demande supression d'un droit en particulier, on recupere
582 582
 // les caracteristiques module, perms et subperms de ce droit.
583 583
             $sql = "SELECT module, perms, subperms";
584
-            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
585
-            $sql .= " WHERE id = '" . Config::$dbEngine->escape($rid) . "'";
586
-            $sql .= " AND entity = " . $entity;
584
+            $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
585
+            $sql .= " WHERE id = '".Config::$dbEngine->escape($rid)."'";
586
+            $sql .= " AND entity = ".$entity;
587 587
 
588 588
             $result = Config::$dbEngine->query($sql);
589 589
             if ($result) {
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
             }
598 598
 
599 599
 // Where pour la liste des droits a supprimer
600
-            $wherefordel = "id=" . Config::$dbEngine->escape($rid);
600
+            $wherefordel = "id=".Config::$dbEngine->escape($rid);
601 601
 // Suppression des droits induits
602 602
             if ($subperms == 'lire' || $subperms == 'read') {
603 603
                 $wherefordel .= " OR (module='$module' AND perms='$perms' AND subperms IS NOT NULL)";
@@ -612,9 +612,9 @@  discard block
 block discarded – undo
612 612
                 if ($allmodule == 'allmodules') {
613 613
                     $wherefordel = 'allmodules';
614 614
                 } else {
615
-                    $wherefordel = "module='" . Config::$dbEngine->escape($allmodule) . "'";
615
+                    $wherefordel = "module='".Config::$dbEngine->escape($allmodule)."'";
616 616
                     if (!empty($allperms)) {
617
-                        $whereforadd .= " AND perms='" . Config::$dbEngine->escape($allperms) . "'";
617
+                        $whereforadd .= " AND perms='".Config::$dbEngine->escape($allperms)."'";
618 618
                     }
619 619
                 }
620 620
             }
@@ -624,10 +624,10 @@  discard block
 block discarded – undo
624 624
         if (!empty($wherefordel)) {
625 625
 //print "$module-$perms-$subperms";
626 626
             $sql = "SELECT id";
627
-            $sql .= " FROM " . MAIN_DB_PREFIX . "rights_def";
628
-            $sql .= " WHERE entity = " . $entity;
627
+            $sql .= " FROM ".MAIN_DB_PREFIX."rights_def";
628
+            $sql .= " WHERE entity = ".$entity;
629 629
             if (!empty($wherefordel) && $wherefordel != 'allmodules') {
630
-                $sql .= " AND " . $wherefordel;
630
+                $sql .= " AND ".$wherefordel;
631 631
             }
632 632
 
633 633
             $result = Config::$dbEngine->query($sql);
@@ -638,9 +638,9 @@  discard block
 block discarded – undo
638 638
                     $obj = Config::$dbEngine->fetch_object($result);
639 639
                     $nid = $obj->id;
640 640
 
641
-                    $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights";
642
-                    $sql .= " WHERE fk_user = " . $this->id . " AND fk_id=" . $nid;
643
-                    $sql .= " AND entity = " . $entity;
641
+                    $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights";
642
+                    $sql .= " WHERE fk_user = ".$this->id." AND fk_id=".$nid;
643
+                    $sql .= " AND entity = ".$entity;
644 644
                     if (!Config::$dbEngine->query($sql)) {
645 645
                         $error++;
646 646
                     }
@@ -655,7 +655,7 @@  discard block
 block discarded – undo
655 655
 
656 656
         if (!$error && !$notrigger) {
657 657
             Globals::$langs->load("other");
658
-            $this->context = array('audit' => Globals::$langs->trans("PermissionsDelete") . ($rid ? ' (id=' . $rid . ')' : ''));
658
+            $this->context = array('audit' => Globals::$langs->trans("PermissionsDelete").($rid ? ' (id='.$rid.')' : ''));
659 659
 
660 660
 // Call trigger
661 661
             $result = $this->call_trigger('USER_MODIFY', Globals::$user);
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
      */
683 683
     function clearrights()
684 684
     {
685
-        DolUtils::dol_syslog(get_class($this) . "::clearrights reset user->rights");
685
+        DolUtils::dol_syslog(get_class($this)."::clearrights reset user->rights");
686 686
         $this->rights = '';
687 687
         $this->all_permissions_are_loaded = false;
688 688
         $this->_tab_loaded = array();
@@ -715,19 +715,19 @@  discard block
 block discarded – undo
715 715
 // Recuperation des droits utilisateurs + recuperation des droits groupes
716 716
 // D'abord les droits utilisateurs
717 717
         $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
718
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user_rights as ur";
719
-        $sql .= ", " . MAIN_DB_PREFIX . "rights_def as r";
718
+        $sql .= " FROM ".MAIN_DB_PREFIX."user_rights as ur";
719
+        $sql .= ", ".MAIN_DB_PREFIX."rights_def as r";
720 720
         $sql .= " WHERE r.id = ur.fk_id";
721 721
         if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
722
-            $sql .= " AND r.entity IN (0," . (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "") . Globals::$conf->entity . ")";
722
+            $sql .= " AND r.entity IN (0,".(!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE) ? "1," : "").Globals::$conf->entity.")";
723 723
         } else {
724
-            $sql .= " AND ur.entity = " . Globals::$conf->entity;
724
+            $sql .= " AND ur.entity = ".Globals::$conf->entity;
725 725
         }
726
-        $sql .= " AND ur.fk_user= " . $this->id;
726
+        $sql .= " AND ur.fk_user= ".$this->id;
727 727
         $sql .= " AND r.perms IS NOT NULL";
728 728
         if ($moduletag) {
729 729
 // $sql .= " AND r.module = '" . Config::$dbEngine->escape($moduletag) . "'";
730
-            $sql .= " AND r.module = '" . $moduletag . "'";
730
+            $sql .= " AND r.module = '".$moduletag."'";
731 731
         }
732 732
 
733 733
         $resql = Config::$dbEngine->select($sql);
@@ -768,25 +768,25 @@  discard block
 block discarded – undo
768 768
 
769 769
 // Maintenant les droits groupes
770 770
         $sql = "SELECT DISTINCT r.module, r.perms, r.subperms";
771
-        $sql .= " FROM " . MAIN_DB_PREFIX . "usergroup_rights as gr,";
772
-        $sql .= " " . MAIN_DB_PREFIX . "usergroup_user as gu,";
773
-        $sql .= " " . MAIN_DB_PREFIX . "rights_def as r";
771
+        $sql .= " FROM ".MAIN_DB_PREFIX."usergroup_rights as gr,";
772
+        $sql .= " ".MAIN_DB_PREFIX."usergroup_user as gu,";
773
+        $sql .= " ".MAIN_DB_PREFIX."rights_def as r";
774 774
         $sql .= " WHERE r.id = gr.fk_id";
775 775
         if (!empty($conf->global->MULTICOMPANY_BACKWARD_COMPATIBILITY)) {
776 776
             if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
777
-                $sql .= " AND gu.entity IN (0," . Globals::$conf->entity . ")";
777
+                $sql .= " AND gu.entity IN (0,".Globals::$conf->entity.")";
778 778
             } else {
779
-                $sql .= " AND r.entity = " . Globals::$conf->entity;
779
+                $sql .= " AND r.entity = ".Globals::$conf->entity;
780 780
             }
781 781
         } else {
782
-            $sql .= " AND gr.entity = " . Globals::$conf->entity;
783
-            $sql .= " AND r.entity = " . Globals::$conf->entity;
782
+            $sql .= " AND gr.entity = ".Globals::$conf->entity;
783
+            $sql .= " AND r.entity = ".Globals::$conf->entity;
784 784
         }
785 785
         $sql .= " AND gr.fk_usergroup = gu.fk_usergroup";
786
-        $sql .= " AND gu.fk_user = " . $this->id;
786
+        $sql .= " AND gu.fk_user = ".$this->id;
787 787
         $sql .= " AND r.perms IS NOT NULL";
788 788
         if ($moduletag) {
789
-            $sql .= " AND r.module = '" . $moduletag . "'";
789
+            $sql .= " AND r.module = '".$moduletag."'";
790 790
         }
791 791
 
792 792
         $resql = Config::$dbEngine->select($sql);
@@ -866,12 +866,12 @@  discard block
 block discarded – undo
866 866
         Config::$dbEngine->begin();
867 867
 
868 868
 // Deactivate user
869
-        $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
870
-        $sql .= " SET statut = " . $this->statut;
871
-        $sql .= " WHERE rowid = " . $this->id;
869
+        $sql = "UPDATE ".MAIN_DB_PREFIX."user";
870
+        $sql .= " SET statut = ".$this->statut;
871
+        $sql .= " WHERE rowid = ".$this->id;
872 872
         $result = Config::$dbEngine->query($sql);
873 873
 
874
-        DolUtils::dol_syslog(get_class($this) . "::setstatus", LOG_DEBUG);
874
+        DolUtils::dol_syslog(get_class($this)."::setstatus", LOG_DEBUG);
875 875
         if ($result) {
876 876
 // Call trigger
877 877
             $result = $this->call_trigger('USER_ENABLEDISABLE', Globals::$user);
@@ -908,7 +908,7 @@  discard block
 block discarded – undo
908 908
         }
909 909
 
910 910
 // Get current categories
911
-        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
911
+        require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
912 912
         $c = new Categorie(Config::$dbEngine);
913 913
         $existing = $c->containing($this->id, Categorie::TYPE_USER, 'id');
914 914
 
@@ -951,10 +951,10 @@  discard block
 block discarded – undo
951 951
 
952 952
         $this->fetch($this->id);
953 953
 
954
-        DolUtils::dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
954
+        DolUtils::dol_syslog(get_class($this)."::delete", LOG_DEBUG);
955 955
 
956 956
 // Remove rights
957
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id;
957
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = ".$this->id;
958 958
 
959 959
         if (!$error && !Config::$dbEngine->query($sql)) {
960 960
             $error++;
@@ -962,7 +962,7 @@  discard block
 block discarded – undo
962 962
         }
963 963
 
964 964
 // Remove group
965
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user WHERE fk_user  = " . $this->id;
965
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user WHERE fk_user  = ".$this->id;
966 966
         if (!$error && !Config::$dbEngine->query($sql)) {
967 967
             $error++;
968 968
             $this->error = Config::$dbEngine->lasterror();
@@ -970,7 +970,7 @@  discard block
 block discarded – undo
970 970
 
971 971
 // If contact, remove link
972 972
         if ($this->contact_id) {
973
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "socpeople SET fk_user_creat = null WHERE rowid = " . $this->contact_id;
973
+            $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET fk_user_creat = null WHERE rowid = ".$this->contact_id;
974 974
             if (!$error && !Config::$dbEngine->query($sql)) {
975 975
                 $error++;
976 976
                 $this->error = Config::$dbEngine->lasterror();
@@ -982,14 +982,14 @@  discard block
 block discarded – undo
982 982
             $result = $this->deleteExtraFields();
983 983
             if ($result < 0) {
984 984
                 $error++;
985
-                DolUtils::dol_syslog(get_class($this) . "::delete error -4 " . $this->error, LOG_ERR);
985
+                DolUtils::dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
986 986
             }
987 987
         }
988 988
 
989 989
 // Remove user
990 990
         if (!$error) {
991
-            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user WHERE rowid = " . $this->id;
992
-            DolUtils::dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
991
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."user WHERE rowid = ".$this->id;
992
+            DolUtils::dol_syslog(get_class($this)."::delete", LOG_DEBUG);
993 993
             if (!Config::$dbEngine->query($sql)) {
994 994
                 $error++;
995 995
                 $this->error = Config::$dbEngine->lasterror();
@@ -1030,7 +1030,7 @@  discard block
 block discarded – undo
1030 1030
         if (!isset($this->entity)) {
1031 1031
             $this->entity = Globals::$conf->entity; // If not defined, we use default value
1032 1032
         }
1033
-        DolUtils::dol_syslog(get_class($this) . "::create login=" . $this->login . ", user=" . (is_object(Globals::$user) ? Globals::$user->id : ''), LOG_DEBUG);
1033
+        DolUtils::dol_syslog(get_class($this)."::create login=".$this->login.", user=".(is_object(Globals::$user) ? Globals::$user->id : ''), LOG_DEBUG);
1034 1034
 
1035 1035
 // Check parameters
1036 1036
         if (!empty($conf->global->USER_MAIL_REQUIRED) && !isValidEMail($this->email)) {
@@ -1049,11 +1049,11 @@  discard block
 block discarded – undo
1049 1049
         $error = 0;
1050 1050
         Config::$dbEngine->begin();
1051 1051
 
1052
-        $sql = "SELECT login FROM " . MAIN_DB_PREFIX . "user";
1053
-        $sql .= " WHERE login ='" . Config::$dbEngine->escape($this->login) . "'";
1054
-        $sql .= " AND entity IN (0," . Config::$dbEngine->escape($conf->entity) . ")";
1052
+        $sql = "SELECT login FROM ".MAIN_DB_PREFIX."user";
1053
+        $sql .= " WHERE login ='".Config::$dbEngine->escape($this->login)."'";
1054
+        $sql .= " AND entity IN (0,".Config::$dbEngine->escape($conf->entity).")";
1055 1055
 
1056
-        DolUtils::dol_syslog(get_class($this) . "::create", LOG_DEBUG);
1056
+        DolUtils::dol_syslog(get_class($this)."::create", LOG_DEBUG);
1057 1057
         $resql = Config::$dbEngine->query($sql);
1058 1058
         if ($resql) {
1059 1059
             $num = Config::$dbEngine->num_rows($resql);
@@ -1061,17 +1061,17 @@  discard block
 block discarded – undo
1061 1061
 
1062 1062
             if ($num) {
1063 1063
                 $this->error = 'ErrorLoginAlreadyExists';
1064
-                DolUtils::dol_syslog(get_class($this) . "::create " . $this->error, LOG_WARNING);
1064
+                DolUtils::dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
1065 1065
                 Config::$dbEngine->rollback();
1066 1066
                 return -6;
1067 1067
             } else {
1068
-                $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user (datec,login,ldap_sid,entity)";
1069
-                $sql .= " VALUES('" . Config::$dbEngine->idate($this->datec) . "','" . Config::$dbEngine->escape($this->login) . "','" . Config::$dbEngine->escape($this->ldap_sid) . "'," . Config::$dbEngine->escape($this->entity) . ")";
1068
+                $sql = "INSERT INTO ".MAIN_DB_PREFIX."user (datec,login,ldap_sid,entity)";
1069
+                $sql .= " VALUES('".Config::$dbEngine->idate($this->datec)."','".Config::$dbEngine->escape($this->login)."','".Config::$dbEngine->escape($this->ldap_sid)."',".Config::$dbEngine->escape($this->entity).")";
1070 1070
                 $result = Config::$dbEngine->query($sql);
1071 1071
 
1072
-                DolUtils::dol_syslog(get_class($this) . "::create", LOG_DEBUG);
1072
+                DolUtils::dol_syslog(get_class($this)."::create", LOG_DEBUG);
1073 1073
                 if ($result) {
1074
-                    $this->id = Config::$dbEngine->last_insert_id(MAIN_DB_PREFIX . "user");
1074
+                    $this->id = Config::$dbEngine->last_insert_id(MAIN_DB_PREFIX."user");
1075 1075
 
1076 1076
 // Set default rights
1077 1077
                     if ($this->set_default_rights() < 0) {
@@ -1088,7 +1088,7 @@  discard block
 block discarded – undo
1088 1088
                     }
1089 1089
 
1090 1090
                     if (!empty($conf->global->STOCK_USERSTOCK_AUTOCREATE)) {
1091
-                        require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
1091
+                        require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
1092 1092
                         Globals::$langs->load("stocks");
1093 1093
                         $entrepot = new Entrepot(Config::$dbEngine);
1094 1094
                         $entrepot->libelle = Globals::$langs->trans("PersonalStock", $this->getFullName(Globals::$langs));
@@ -1112,7 +1112,7 @@  discard block
 block discarded – undo
1112 1112
                         return $this->id;
1113 1113
                     } else {
1114 1114
 //$this->error=$interface->error;
1115
-                        DolUtils::dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
1115
+                        DolUtils::dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
1116 1116
                         Config::$dbEngine->rollback();
1117 1117
                         return -3;
1118 1118
                     }
@@ -1165,7 +1165,7 @@  discard block
 block discarded – undo
1165 1165
         $this->employee = 0;
1166 1166
 
1167 1167
         if (empty($login)) {
1168
-            $login = strtolower(substr($contact->firstname, 0, 4)) . strtolower(substr($contact->lastname, 0, 4));
1168
+            $login = strtolower(substr($contact->firstname, 0, 4)).strtolower(substr($contact->lastname, 0, 4));
1169 1169
         }
1170 1170
         $this->login = $login;
1171 1171
 
@@ -1174,15 +1174,15 @@  discard block
 block discarded – undo
1174 1174
 // Cree et positionne $this->id
1175 1175
         $result = $this->create(Globals::$user);
1176 1176
         if ($result > 0) {
1177
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1178
-            $sql .= " SET fk_socpeople=" . $contact->id;
1177
+            $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1178
+            $sql .= " SET fk_socpeople=".$contact->id;
1179 1179
             if ($contact->socid) {
1180
-                $sql .= ", fk_soc=" . $contact->socid;
1180
+                $sql .= ", fk_soc=".$contact->socid;
1181 1181
             }
1182
-            $sql .= " WHERE rowid=" . $this->id;
1182
+            $sql .= " WHERE rowid=".$this->id;
1183 1183
             $resql = Config::$dbEngine->query($sql);
1184 1184
 
1185
-            DolUtils::dol_syslog(get_class($this) . "::create_from_contact", LOG_DEBUG);
1185
+            DolUtils::dol_syslog(get_class($this)."::create_from_contact", LOG_DEBUG);
1186 1186
             if ($resql) {
1187 1187
                 $this->context['createfromcontact'] = 'createfromcontact';
1188 1188
 
@@ -1205,7 +1205,7 @@  discard block
 block discarded – undo
1205 1205
             }
1206 1206
         } else {
1207 1207
 // $this->error deja positionne
1208
-            DolUtils::dol_syslog(get_class($this) . "::create_from_contact - 0");
1208
+            DolUtils::dol_syslog(get_class($this)."::create_from_contact - 0");
1209 1209
 
1210 1210
             Config::$dbEngine->rollback();
1211 1211
             return $result;
@@ -1239,7 +1239,7 @@  discard block
 block discarded – undo
1239 1239
         $this->country_id = $member->country_id;
1240 1240
 
1241 1241
         if (empty($login)) {
1242
-            $login = strtolower(substr($member->firstname, 0, 4)) . strtolower(substr($member->lastname, 0, 4));
1242
+            $login = strtolower(substr($member->firstname, 0, 4)).strtolower(substr($member->lastname, 0, 4));
1243 1243
         }
1244 1244
         $this->login = $login;
1245 1245
 
@@ -1254,11 +1254,11 @@  discard block
 block discarded – undo
1254 1254
             }
1255 1255
 
1256 1256
             if ($result > 0 && $member->fk_soc) { // If member is linked to a thirdparty
1257
-                $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1258
-                $sql .= " SET fk_soc=" . $member->fk_soc;
1259
-                $sql .= " WHERE rowid=" . $this->id;
1257
+                $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1258
+                $sql .= " SET fk_soc=".$member->fk_soc;
1259
+                $sql .= " WHERE rowid=".$this->id;
1260 1260
 
1261
-                DolUtils::dol_syslog(get_class($this) . "::create_from_member", LOG_DEBUG);
1261
+                DolUtils::dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
1262 1262
                 $resql = Config::$dbEngine->query($sql);
1263 1263
                 if ($resql) {
1264 1264
                     Config::$dbEngine->commit();
@@ -1293,9 +1293,9 @@  discard block
 block discarded – undo
1293 1293
 // phpcs:enable
1294 1294
         global $conf;
1295 1295
 
1296
-        $sql = "SELECT id FROM " . MAIN_DB_PREFIX . "rights_def";
1296
+        $sql = "SELECT id FROM ".MAIN_DB_PREFIX."rights_def";
1297 1297
         $sql .= " WHERE bydefault = 1";
1298
-        $sql .= " AND entity = " . Globals::$conf->entity;
1298
+        $sql .= " AND entity = ".Globals::$conf->entity;
1299 1299
 
1300 1300
         $resql = Config::$dbEngine->query($sql);
1301 1301
         if ($resql) {
@@ -1312,10 +1312,10 @@  discard block
 block discarded – undo
1312 1312
         $i = 0;
1313 1313
         while ($i < $num) {
1314 1314
 
1315
-            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1315
+            $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_rights WHERE fk_user = $this->id AND fk_id=$rd[$i]";
1316 1316
             $result = Config::$dbEngine->query($sql);
1317 1317
 
1318
-            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1318
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_rights (fk_user, fk_id) VALUES ($this->id, $rd[$i])";
1319 1319
             $result = Config::$dbEngine->query($sql);
1320 1320
             if (!$result) {
1321 1321
                 return -1;
@@ -1343,7 +1343,7 @@  discard block
 block discarded – undo
1343 1343
         $nbrowsaffected = 0;
1344 1344
         $error = 0;
1345 1345
 
1346
-        DolUtils::dol_syslog(get_class($this) . "::update notrigger=" . $notrigger . ", nosyncmember=" . $nosyncmember . ", nosyncmemberpass=" . $nosyncmemberpass);
1346
+        DolUtils::dol_syslog(get_class($this)."::update notrigger=".$notrigger.", nosyncmember=".$nosyncmember.", nosyncmemberpass=".$nosyncmemberpass);
1347 1347
 
1348 1348
 // Clean parameters
1349 1349
         $this->lastname = trim($this->lastname);
@@ -1371,7 +1371,7 @@  discard block
 block discarded – undo
1371 1371
         $this->job = trim($this->job);
1372 1372
         $this->signature = trim($this->signature);
1373 1373
         $this->note = trim($this->note);
1374
-        $this->openid = trim(empty($this->openid) ? '' : $this->openid);    // Avoid warning
1374
+        $this->openid = trim(empty($this->openid) ? '' : $this->openid); // Avoid warning
1375 1375
         $this->admin = $this->admin ? $this->admin : 0;
1376 1376
         $this->address = empty($this->address) ? '' : $this->address;
1377 1377
         $this->zip = empty($this->zip) ? '' : $this->zip;
@@ -1396,59 +1396,59 @@  discard block
 block discarded – undo
1396 1396
         Config::$dbEngine->begin();
1397 1397
 
1398 1398
 // Update datas
1399
-        $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET";
1400
-        $sql .= " lastname = '" . Config::$dbEngine->escape($this->lastname) . "'";
1401
-        $sql .= ", firstname = '" . Config::$dbEngine->escape($this->firstname) . "'";
1402
-        $sql .= ", employee = " . $this->employee;
1403
-        $sql .= ", login = '" . Config::$dbEngine->escape($this->login) . "'";
1404
-        $sql .= ", api_key = " . ($this->api_key ? "'" . Config::$dbEngine->escape($this->api_key) . "'" : "null");
1405
-        $sql .= ", gender = " . ($this->gender != -1 ? "'" . Config::$dbEngine->escape($this->gender) . "'" : "null"); // 'man' or 'woman'
1406
-        $sql .= ", birth=" . (strval($this->birth) != '' ? "'" . Config::$dbEngine->idate($this->birth) . "'" : 'null');
1399
+        $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
1400
+        $sql .= " lastname = '".Config::$dbEngine->escape($this->lastname)."'";
1401
+        $sql .= ", firstname = '".Config::$dbEngine->escape($this->firstname)."'";
1402
+        $sql .= ", employee = ".$this->employee;
1403
+        $sql .= ", login = '".Config::$dbEngine->escape($this->login)."'";
1404
+        $sql .= ", api_key = ".($this->api_key ? "'".Config::$dbEngine->escape($this->api_key)."'" : "null");
1405
+        $sql .= ", gender = ".($this->gender != -1 ? "'".Config::$dbEngine->escape($this->gender)."'" : "null"); // 'man' or 'woman'
1406
+        $sql .= ", birth=".(strval($this->birth) != '' ? "'".Config::$dbEngine->idate($this->birth)."'" : 'null');
1407 1407
         if (!empty(Globals::$user->admin)) {
1408
-            $sql .= ", admin = " . $this->admin; // admin flag can be set/unset only by an admin user
1409
-        }
1410
-        $sql .= ", address = '" . Config::$dbEngine->escape($this->address) . "'";
1411
-        $sql .= ", zip = '" . Config::$dbEngine->escape($this->zip) . "'";
1412
-        $sql .= ", town = '" . Config::$dbEngine->escape($this->town) . "'";
1413
-        $sql .= ", fk_state = " . ((!empty($this->state_id) && $this->state_id > 0) ? "'" . Config::$dbEngine->escape($this->state_id) . "'" : "null");
1414
-        $sql .= ", fk_country = " . ((!empty($this->country_id) && $this->country_id > 0) ? "'" . Config::$dbEngine->escape($this->country_id) . "'" : "null");
1415
-        $sql .= ", office_phone = '" . Config::$dbEngine->escape($this->office_phone) . "'";
1416
-        $sql .= ", office_fax = '" . Config::$dbEngine->escape($this->office_fax) . "'";
1417
-        $sql .= ", user_mobile = '" . Config::$dbEngine->escape($this->user_mobile) . "'";
1418
-        $sql .= ", email = '" . Config::$dbEngine->escape($this->email) . "'";
1419
-        $sql .= ", skype = '" . Config::$dbEngine->escape($this->skype) . "'";
1420
-        $sql .= ", twitter = '" . Config::$dbEngine->escape($this->twitter) . "'";
1421
-        $sql .= ", facebook = '" . Config::$dbEngine->escape($this->facebook) . "'";
1422
-        $sql .= ", job = '" . Config::$dbEngine->escape($this->job) . "'";
1423
-        $sql .= ", signature = '" . Config::$dbEngine->escape($this->signature) . "'";
1424
-        $sql .= ", accountancy_code = '" . Config::$dbEngine->escape($this->accountancy_code) . "'";
1425
-        $sql .= ", color = '" . Config::$dbEngine->escape($this->color) . "'";
1426
-        $sql .= ", dateemployment=" . (strval($this->dateemployment) != '' ? "'" . Config::$dbEngine->idate($this->dateemployment) . "'" : 'null');
1427
-        $sql .= ", dateemploymentend=" . (strval($this->dateemploymentend) != '' ? "'" . Config::$dbEngine->idate($this->dateemploymentend) . "'" : 'null');
1428
-        $sql .= ", note = '" . Config::$dbEngine->escape($this->note) . "'";
1429
-        $sql .= ", photo = " . ($this->photo ? "'" . Config::$dbEngine->escape($this->photo) . "'" : "null");
1430
-        $sql .= ", openid = " . ($this->openid ? "'" . Config::$dbEngine->escape($this->openid) . "'" : "null");
1431
-        $sql .= ", fk_user = " . ($this->fk_user > 0 ? "'" . Config::$dbEngine->escape($this->fk_user) . "'" : "null");
1408
+            $sql .= ", admin = ".$this->admin; // admin flag can be set/unset only by an admin user
1409
+        }
1410
+        $sql .= ", address = '".Config::$dbEngine->escape($this->address)."'";
1411
+        $sql .= ", zip = '".Config::$dbEngine->escape($this->zip)."'";
1412
+        $sql .= ", town = '".Config::$dbEngine->escape($this->town)."'";
1413
+        $sql .= ", fk_state = ".((!empty($this->state_id) && $this->state_id > 0) ? "'".Config::$dbEngine->escape($this->state_id)."'" : "null");
1414
+        $sql .= ", fk_country = ".((!empty($this->country_id) && $this->country_id > 0) ? "'".Config::$dbEngine->escape($this->country_id)."'" : "null");
1415
+        $sql .= ", office_phone = '".Config::$dbEngine->escape($this->office_phone)."'";
1416
+        $sql .= ", office_fax = '".Config::$dbEngine->escape($this->office_fax)."'";
1417
+        $sql .= ", user_mobile = '".Config::$dbEngine->escape($this->user_mobile)."'";
1418
+        $sql .= ", email = '".Config::$dbEngine->escape($this->email)."'";
1419
+        $sql .= ", skype = '".Config::$dbEngine->escape($this->skype)."'";
1420
+        $sql .= ", twitter = '".Config::$dbEngine->escape($this->twitter)."'";
1421
+        $sql .= ", facebook = '".Config::$dbEngine->escape($this->facebook)."'";
1422
+        $sql .= ", job = '".Config::$dbEngine->escape($this->job)."'";
1423
+        $sql .= ", signature = '".Config::$dbEngine->escape($this->signature)."'";
1424
+        $sql .= ", accountancy_code = '".Config::$dbEngine->escape($this->accountancy_code)."'";
1425
+        $sql .= ", color = '".Config::$dbEngine->escape($this->color)."'";
1426
+        $sql .= ", dateemployment=".(strval($this->dateemployment) != '' ? "'".Config::$dbEngine->idate($this->dateemployment)."'" : 'null');
1427
+        $sql .= ", dateemploymentend=".(strval($this->dateemploymentend) != '' ? "'".Config::$dbEngine->idate($this->dateemploymentend)."'" : 'null');
1428
+        $sql .= ", note = '".Config::$dbEngine->escape($this->note)."'";
1429
+        $sql .= ", photo = ".($this->photo ? "'".Config::$dbEngine->escape($this->photo)."'" : "null");
1430
+        $sql .= ", openid = ".($this->openid ? "'".Config::$dbEngine->escape($this->openid)."'" : "null");
1431
+        $sql .= ", fk_user = ".($this->fk_user > 0 ? "'".Config::$dbEngine->escape($this->fk_user)."'" : "null");
1432 1432
         if (isset($this->thm) || $this->thm != '') {
1433
-            $sql .= ", thm= " . ($this->thm != '' ? "'" . Config::$dbEngine->escape($this->thm) . "'" : "null");
1433
+            $sql .= ", thm= ".($this->thm != '' ? "'".Config::$dbEngine->escape($this->thm)."'" : "null");
1434 1434
         }
1435 1435
         if (isset($this->tjm) || $this->tjm != '') {
1436
-            $sql .= ", tjm= " . ($this->tjm != '' ? "'" . Config::$dbEngine->escape($this->tjm) . "'" : "null");
1436
+            $sql .= ", tjm= ".($this->tjm != '' ? "'".Config::$dbEngine->escape($this->tjm)."'" : "null");
1437 1437
         }
1438 1438
         if (isset($this->salary) || $this->salary != '') {
1439
-            $sql .= ", salary= " . ($this->salary != '' ? "'" . Config::$dbEngine->escape($this->salary) . "'" : "null");
1439
+            $sql .= ", salary= ".($this->salary != '' ? "'".Config::$dbEngine->escape($this->salary)."'" : "null");
1440 1440
         }
1441 1441
         if (isset($this->salaryextra) || $this->salaryextra != '') {
1442
-            $sql .= ", salaryextra= " . ($this->salaryextra != '' ? "'" . Config::$dbEngine->escape($this->salaryextra) . "'" : "null");
1442
+            $sql .= ", salaryextra= ".($this->salaryextra != '' ? "'".Config::$dbEngine->escape($this->salaryextra)."'" : "null");
1443 1443
         }
1444
-        $sql .= ", weeklyhours= " . ($this->weeklyhours != '' ? "'" . Config::$dbEngine->escape($this->weeklyhours) . "'" : "null");
1445
-        $sql .= ", entity = '" . Config::$dbEngine->escape($this->entity) . "'";
1446
-        $sql .= ", default_range = " . ($this->default_range > 0 ? $this->default_range : 'null');
1447
-        $sql .= ", default_c_exp_tax_cat = " . ($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
1444
+        $sql .= ", weeklyhours= ".($this->weeklyhours != '' ? "'".Config::$dbEngine->escape($this->weeklyhours)."'" : "null");
1445
+        $sql .= ", entity = '".Config::$dbEngine->escape($this->entity)."'";
1446
+        $sql .= ", default_range = ".($this->default_range > 0 ? $this->default_range : 'null');
1447
+        $sql .= ", default_c_exp_tax_cat = ".($this->default_c_exp_tax_cat > 0 ? $this->default_c_exp_tax_cat : 'null');
1448 1448
 
1449
-        $sql .= " WHERE rowid = " . $this->id;
1449
+        $sql .= " WHERE rowid = ".$this->id;
1450 1450
 
1451
-        DolUtils::dol_syslog(get_class($this) . "::update", LOG_DEBUG);
1451
+        DolUtils::dol_syslog(get_class($this)."::update", LOG_DEBUG);
1452 1452
         $resql = Config::$dbEngine->query($sql);
1453 1453
         if ($resql) {
1454 1454
             $nbrowsaffected += Config::$dbEngine->affected_rows($resql);
@@ -1466,8 +1466,8 @@  discard block
 block discarded – undo
1466 1466
 
1467 1467
 // If user is linked to a member, remove old link to this member
1468 1468
             if ($this->fk_member > 0) {
1469
-                DolUtils::dol_syslog(get_class($this) . "::update remove link with member. We will recreate it later", LOG_DEBUG);
1470
-                $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member = NULL where fk_member = " . $this->fk_member;
1469
+                DolUtils::dol_syslog(get_class($this)."::update remove link with member. We will recreate it later", LOG_DEBUG);
1470
+                $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member = NULL where fk_member = ".$this->fk_member;
1471 1471
                 $resql = Config::$dbEngine->query($sql);
1472 1472
                 if (!$resql) {
1473 1473
                     $this->error = Config::$dbEngine->error();
@@ -1476,8 +1476,8 @@  discard block
 block discarded – undo
1476 1476
                 }
1477 1477
             }
1478 1478
 // Set link to user
1479
-            DolUtils::dol_syslog(get_class($this) . "::update set link with member", LOG_DEBUG);
1480
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET fk_member =" . ($this->fk_member > 0 ? $this->fk_member : 'null') . " where rowid = " . $this->id;
1479
+            DolUtils::dol_syslog(get_class($this)."::update set link with member", LOG_DEBUG);
1480
+            $sql = "UPDATE ".MAIN_DB_PREFIX."user SET fk_member =".($this->fk_member > 0 ? $this->fk_member : 'null')." where rowid = ".$this->id;
1481 1481
             $resql = Config::$dbEngine->query($sql);
1482 1482
             if (!$resql) {
1483 1483
                 $this->error = Config::$dbEngine->error();
@@ -1487,9 +1487,9 @@  discard block
 block discarded – undo
1487 1487
 
1488 1488
             if ($nbrowsaffected) { // If something has changed in data
1489 1489
                 if ($this->fk_member > 0 && !$nosyncmember) {
1490
-                    DolUtils::dol_syslog(get_class($this) . "::update user is linked with a member. We try to update member too.", LOG_DEBUG);
1490
+                    DolUtils::dol_syslog(get_class($this)."::update user is linked with a member. We try to update member too.", LOG_DEBUG);
1491 1491
 
1492
-                    require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
1492
+                    require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1493 1493
 
1494 1494
 // This user is linked with a member, so we also update member information
1495 1495
 // if this is an update.
@@ -1529,7 +1529,7 @@  discard block
 block discarded – undo
1529 1529
                         if ($result < 0) {
1530 1530
                             $this->error = $adh->error;
1531 1531
                             $this->errors = $adh->errors;
1532
-                            DolUtils::dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
1532
+                            DolUtils::dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
1533 1533
                             $error++;
1534 1534
                         }
1535 1535
                     } else {
@@ -1540,9 +1540,9 @@  discard block
 block discarded – undo
1540 1540
                 }
1541 1541
 
1542 1542
                 if ($this->contact_id > 0 && !$nosynccontact) {
1543
-                    DolUtils::dol_syslog(get_class($this) . "::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
1543
+                    DolUtils::dol_syslog(get_class($this)."::update user is linked with a contact. We try to update contact too.", LOG_DEBUG);
1544 1544
 
1545
-                    require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
1545
+                    require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1546 1546
 
1547 1547
 // This user is linked with a contact, so we also update contact information
1548 1548
 // if this is an update.
@@ -1582,7 +1582,7 @@  discard block
 block discarded – undo
1582 1582
                         if ($result < 0) {
1583 1583
                             $this->error = $tmpobj->error;
1584 1584
                             $this->errors = $tmpobj->errors;
1585
-                            DolUtils::dol_syslog(get_class($this) . "::update error after calling adh->update to sync it with user: " . $this->error, LOG_ERR);
1585
+                            DolUtils::dol_syslog(get_class($this)."::update error after calling adh->update to sync it with user: ".$this->error, LOG_ERR);
1586 1586
                             $error++;
1587 1587
                         }
1588 1588
                     } else {
@@ -1616,7 +1616,7 @@  discard block
 block discarded – undo
1616 1616
                 Config::$dbEngine->commit();
1617 1617
                 return $nbrowsaffected;
1618 1618
             } else {
1619
-                DolUtils::dol_syslog(get_class($this) . "::update error=" . $this->error, LOG_ERR);
1619
+                DolUtils::dol_syslog(get_class($this)."::update error=".$this->error, LOG_ERR);
1620 1620
                 Config::$dbEngine->rollback();
1621 1621
                 return -1;
1622 1622
             }
@@ -1639,20 +1639,20 @@  discard block
 block discarded – undo
1639 1639
 // phpcs:enable
1640 1640
         $now = dol_now();
1641 1641
 
1642
-        $sql = "UPDATE " . MAIN_DB_PREFIX . "user SET";
1642
+        $sql = "UPDATE ".MAIN_DB_PREFIX."user SET";
1643 1643
         $sql .= " datepreviouslogin = datelastlogin,";
1644
-        $sql .= " datelastlogin = '" . Config::$dbEngine->idate($now) . "',";
1645
-        $sql .= " tms = tms";    // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
1646
-        $sql .= " WHERE rowid = " . $this->id;
1644
+        $sql .= " datelastlogin = '".Config::$dbEngine->idate($now)."',";
1645
+        $sql .= " tms = tms"; // La date de derniere modif doit changer sauf pour la mise a jour de date de derniere connexion
1646
+        $sql .= " WHERE rowid = ".$this->id;
1647 1647
 
1648
-        DolUtils::dol_syslog(get_class($this) . "::update_last_login_date user->id=" . $this->id . " " . $sql, LOG_DEBUG);
1648
+        DolUtils::dol_syslog(get_class($this)."::update_last_login_date user->id=".$this->id." ".$sql, LOG_DEBUG);
1649 1649
         $resql = Config::$dbEngine->query($sql);
1650 1650
         if ($resql) {
1651 1651
             $this->datepreviouslogin = $this->datelastlogin;
1652 1652
             $this->datelastlogin = $now;
1653 1653
             return 1;
1654 1654
         } else {
1655
-            $this->error = Config::$dbEngine->lasterror() . ' sql=' . $sql;
1655
+            $this->error = Config::$dbEngine->lasterror().' sql='.$sql;
1656 1656
             return -1;
1657 1657
         }
1658 1658
     }
@@ -1670,11 +1670,11 @@  discard block
 block discarded – undo
1670 1670
     function setPassword($user, $password = '', $changelater = 0, $notrigger = 0, $nosyncmember = 0)
1671 1671
     {
1672 1672
 //global $conf, Globals::$langs;
1673
-        require_once DOL_DOCUMENT_ROOT . '/core/lib/security2.lib.php';
1673
+        require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1674 1674
 
1675 1675
         $error = 0;
1676 1676
 
1677
-        DolUtils::dol_syslog(get_class($this) . "::setPassword user=" . Globals::$user->id . " password=" . preg_replace('/./i', '*', $password) . " changelater=" . $changelater . " notrigger=" . $notrigger . " nosyncmember=" . $nosyncmember, LOG_DEBUG);
1677
+        DolUtils::dol_syslog(get_class($this)."::setPassword user=".Globals::$user->id." password=".preg_replace('/./i', '*', $password)." changelater=".$changelater." notrigger=".$notrigger." nosyncmember=".$nosyncmember, LOG_DEBUG);
1678 1678
 
1679 1679
 // If new password not provided, we generate one
1680 1680
         if (!$password) {
@@ -1692,17 +1692,17 @@  discard block
 block discarded – undo
1692 1692
 
1693 1693
             Config::$dbEngine->begin();
1694 1694
 
1695
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1696
-            $sql .= " SET pass_crypted = '" . Config::$dbEngine->escape($password_crypted) . "',";
1695
+            $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1696
+            $sql .= " SET pass_crypted = '".Config::$dbEngine->escape($password_crypted)."',";
1697 1697
             $sql .= " pass_temp = null";
1698 1698
             if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) {
1699 1699
                 $sql .= ", pass = null";
1700 1700
             } else {
1701
-                $sql .= ", pass = '" . Config::$dbEngine->escape($password) . "'";
1701
+                $sql .= ", pass = '".Config::$dbEngine->escape($password)."'";
1702 1702
             }
1703
-            $sql .= " WHERE rowid = " . $this->id;
1703
+            $sql .= " WHERE rowid = ".$this->id;
1704 1704
 
1705
-            DolUtils::dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG);
1705
+            DolUtils::dol_syslog(get_class($this)."::setPassword", LOG_DEBUG);
1706 1706
             $result = Config::$dbEngine->query($sql);
1707 1707
             if ($result) {
1708 1708
                 if (Config::$dbEngine->affected_rows($result)) {
@@ -1711,7 +1711,7 @@  discard block
 block discarded – undo
1711 1711
                     $this->pass_indatabase_crypted = $password_crypted;
1712 1712
 
1713 1713
                     if ($this->fk_member && !$nosyncmember) {
1714
-                        require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherent.class.php';
1714
+                        require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
1715 1715
 
1716 1716
 // This user is linked with a member, so we also update members informations
1717 1717
 // if this is an update.
@@ -1722,7 +1722,7 @@  discard block
 block discarded – undo
1722 1722
                             $result = $adh->setPassword(Globals::$user, $this->pass, (empty($conf->global->DATABASE_PWD_ENCRYPTED) ? 0 : 1), 1); // Cryptage non gere dans module adherent
1723 1723
                             if ($result < 0) {
1724 1724
                                 $this->error = $adh->error;
1725
-                                DolUtils::dol_syslog(get_class($this) . "::setPassword " . $this->error, LOG_ERR);
1725
+                                DolUtils::dol_syslog(get_class($this)."::setPassword ".$this->error, LOG_ERR);
1726 1726
                                 $error++;
1727 1727
                             }
1728 1728
                         } else {
@@ -1731,7 +1731,7 @@  discard block
 block discarded – undo
1731 1731
                         }
1732 1732
                     }
1733 1733
 
1734
-                    DolUtils::dol_syslog(get_class($this) . "::setPassword notrigger=" . $notrigger . " error=" . $error, LOG_DEBUG);
1734
+                    DolUtils::dol_syslog(get_class($this)."::setPassword notrigger=".$notrigger." error=".$error, LOG_DEBUG);
1735 1735
 
1736 1736
                     if (!$error && !$notrigger) {
1737 1737
 // Call trigger
@@ -1758,11 +1758,11 @@  discard block
 block discarded – undo
1758 1758
         } else {
1759 1759
 // We store clear password in password temporary field.
1760 1760
 // After receiving confirmation link, we will crypt it and store it in pass_crypted
1761
-            $sql = "UPDATE " . MAIN_DB_PREFIX . "user";
1762
-            $sql .= " SET pass_temp = '" . Config::$dbEngine->escape($password) . "'";
1763
-            $sql .= " WHERE rowid = " . $this->id;
1761
+            $sql = "UPDATE ".MAIN_DB_PREFIX."user";
1762
+            $sql .= " SET pass_temp = '".Config::$dbEngine->escape($password)."'";
1763
+            $sql .= " WHERE rowid = ".$this->id;
1764 1764
 
1765
-            DolUtils::dol_syslog(get_class($this) . "::setPassword", LOG_DEBUG); // No log
1765
+            DolUtils::dol_syslog(get_class($this)."::setPassword", LOG_DEBUG); // No log
1766 1766
             $result = Config::$dbEngine->query($sql);
1767 1767
             if ($result) {
1768 1768
                 return $password;
@@ -1788,7 +1788,7 @@  discard block
 block discarded – undo
1788 1788
 //global $conf, Globals::$langs;
1789 1789
 //global $dolibarr_main_url_root;
1790 1790
 
1791
-        require_once DOL_DOCUMENT_ROOT . '/core/class/CMailFile.class.php';
1791
+        require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
1792 1792
 
1793 1793
         $msgishtml = 0;
1794 1794
 
@@ -1813,36 +1813,36 @@  discard block
 block discarded – undo
1813 1813
         $subject = $outputlangs->transnoentitiesnoconv("SubjectNewPassword", $appli);
1814 1814
 
1815 1815
 // Define $urlwithroot
1816
-        $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_URL_ROOT, '/') . '$/i', '', trim($dolibarr_main_url_root));
1817
-        $urlwithroot = $urlwithouturlroot . DOL_URL_ROOT;  // This is to use external domain name found into config file
1816
+        $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
1817
+        $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
1818 1818
 
1819 1819
         if (!$changelater) {
1820
-            $url = $urlwithroot . '/';
1820
+            $url = $urlwithroot.'/';
1821 1821
 
1822
-            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . ".\n";
1823
-            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs") . " :\n\n";
1824
-            $mesg .= $outputlangs->transnoentitiesnoconv("Login") . " = " . $this->login . "\n";
1825
-            $mesg .= $outputlangs->transnoentitiesnoconv("Password") . " = " . $password . "\n\n";
1822
+            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived").".\n";
1823
+            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyIs")." :\n\n";
1824
+            $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
1825
+            $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
1826 1826
             $mesg .= "\n";
1827 1827
 
1828
-            $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli) . ': ' . $url . "\n\n";
1828
+            $mesg .= $outputlangs->transnoentitiesnoconv("ClickHereToGoTo", $appli).': '.$url."\n\n";
1829 1829
             $mesg .= "--\n";
1830 1830
             $mesg .= Globals::$user->getFullName($outputlangs); // Username that make then sending
1831 1831
 
1832
-            DolUtils::dol_syslog(get_class($this) . "::send_password changelater is off, url=" . $url);
1832
+            DolUtils::dol_syslog(get_class($this)."::send_password changelater is off, url=".$url);
1833 1833
         } else {
1834
-            $url = $urlwithroot . '/user/passwordforgotten.php?action=validatenewpassword&username=' . $this->login . "&passwordhash=" . dol_hash($password);
1834
+            $url = $urlwithroot.'/user/passwordforgotten.php?action=validatenewpassword&username='.$this->login."&passwordhash=".dol_hash($password);
1835 1835
 
1836
-            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived") . "\n";
1837
-            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe") . " :\n\n";
1838
-            $mesg .= $outputlangs->transnoentitiesnoconv("Login") . " = " . $this->login . "\n";
1839
-            $mesg .= $outputlangs->transnoentitiesnoconv("Password") . " = " . $password . "\n\n";
1836
+            $mesg .= $outputlangs->transnoentitiesnoconv("RequestToResetPasswordReceived")."\n";
1837
+            $mesg .= $outputlangs->transnoentitiesnoconv("NewKeyWillBe")." :\n\n";
1838
+            $mesg .= $outputlangs->transnoentitiesnoconv("Login")." = ".$this->login."\n";
1839
+            $mesg .= $outputlangs->transnoentitiesnoconv("Password")." = ".$password."\n\n";
1840 1840
             $mesg .= "\n";
1841
-            $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange") . " :\n";
1842
-            $mesg .= $url . "\n\n";
1843
-            $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing") . "\n\n";
1841
+            $mesg .= $outputlangs->transnoentitiesnoconv("YouMustClickToChange")." :\n";
1842
+            $mesg .= $url."\n\n";
1843
+            $mesg .= $outputlangs->transnoentitiesnoconv("ForgetIfNothing")."\n\n";
1844 1844
 
1845
-            DolUtils::dol_syslog(get_class($this) . "::send_password changelater is on, url=" . $url);
1845
+            DolUtils::dol_syslog(get_class($this)."::send_password changelater is on, url=".$url);
1846 1846
         }
1847 1847
 
1848 1848
         $mailfile = new CMailFile(
@@ -1853,7 +1853,7 @@  discard block
 block discarded – undo
1853 1853
             return 1;
1854 1854
         } else {
1855 1855
             Globals::$langs->trans("errors");
1856
-            $this->error = Globals::$langs->trans("ErrorFailedToSendPassword") . ' ' . $mailfile->error;
1856
+            $this->error = Globals::$langs->trans("ErrorFailedToSendPassword").' '.$mailfile->error;
1857 1857
             return -1;
1858 1858
         }
1859 1859
     }
@@ -1878,8 +1878,8 @@  discard block
 block discarded – undo
1878 1878
     {
1879 1879
 // phpcs:enable
1880 1880
         $sql = "SELECT url, login, pass, poste ";
1881
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user_clicktodial as u";
1882
-        $sql .= " WHERE u.fk_user = " . $this->id;
1881
+        $sql .= " FROM ".MAIN_DB_PREFIX."user_clicktodial as u";
1882
+        $sql .= " WHERE u.fk_user = ".$this->id;
1883 1883
 
1884 1884
         $resql = Config::$dbEngine->query($sql);
1885 1885
         if ($resql) {
@@ -1913,21 +1913,21 @@  discard block
 block discarded – undo
1913 1913
 // phpcs:enable
1914 1914
         Config::$dbEngine->begin();
1915 1915
 
1916
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_clicktodial";
1917
-        $sql .= " WHERE fk_user = " . $this->id;
1916
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_clicktodial";
1917
+        $sql .= " WHERE fk_user = ".$this->id;
1918 1918
 
1919
-        DolUtils::dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
1919
+        DolUtils::dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
1920 1920
         $result = Config::$dbEngine->query($sql);
1921 1921
 
1922
-        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_clicktodial";
1922
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_clicktodial";
1923 1923
         $sql .= " (fk_user,url,login,pass,poste)";
1924
-        $sql .= " VALUES (" . $this->id;
1925
-        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_url) . "'";
1926
-        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_login) . "'";
1927
-        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_password) . "'";
1928
-        $sql .= ", '" . Config::$dbEngine->escape($this->clicktodial_poste) . "')";
1924
+        $sql .= " VALUES (".$this->id;
1925
+        $sql .= ", '".Config::$dbEngine->escape($this->clicktodial_url)."'";
1926
+        $sql .= ", '".Config::$dbEngine->escape($this->clicktodial_login)."'";
1927
+        $sql .= ", '".Config::$dbEngine->escape($this->clicktodial_password)."'";
1928
+        $sql .= ", '".Config::$dbEngine->escape($this->clicktodial_poste)."')";
1929 1929
 
1930
-        DolUtils::dol_syslog(get_class($this) . '::update_clicktodial', LOG_DEBUG);
1930
+        DolUtils::dol_syslog(get_class($this).'::update_clicktodial', LOG_DEBUG);
1931 1931
         $result = Config::$dbEngine->query($sql);
1932 1932
         if ($result) {
1933 1933
             Config::$dbEngine->commit();
@@ -1957,20 +1957,20 @@  discard block
 block discarded – undo
1957 1957
 
1958 1958
         Config::$dbEngine->begin();
1959 1959
 
1960
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
1961
-        $sql .= " WHERE fk_user  = " . $this->id;
1962
-        $sql .= " AND fk_usergroup = " . $group;
1963
-        $sql .= " AND entity = " . $entity;
1960
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
1961
+        $sql .= " WHERE fk_user  = ".$this->id;
1962
+        $sql .= " AND fk_usergroup = ".$group;
1963
+        $sql .= " AND entity = ".$entity;
1964 1964
 
1965 1965
         $result = Config::$dbEngine->query($sql);
1966 1966
 
1967
-        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "usergroup_user (entity, fk_user, fk_usergroup)";
1968
-        $sql .= " VALUES (" . $entity . "," . $this->id . "," . $group . ")";
1967
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."usergroup_user (entity, fk_user, fk_usergroup)";
1968
+        $sql .= " VALUES (".$entity.",".$this->id.",".$group.")";
1969 1969
 
1970 1970
         $result = Config::$dbEngine->query($sql);
1971 1971
         if ($result) {
1972 1972
             if (!$error && !$notrigger) {
1973
-                $this->newgroupid = $group;    // deprecated. Remove this.
1973
+                $this->newgroupid = $group; // deprecated. Remove this.
1974 1974
                 $this->context = array('audit' => Globals::$langs->trans("UserSetInGroup"), 'newgroupid' => $group);
1975 1975
 
1976 1976
 // Call trigger
@@ -1985,7 +1985,7 @@  discard block
 block discarded – undo
1985 1985
                 Config::$dbEngine->commit();
1986 1986
                 return 1;
1987 1987
             } else {
1988
-                DolUtils::dol_syslog(get_class($this) . "::SetInGroup " . $this->error, LOG_ERR);
1988
+                DolUtils::dol_syslog(get_class($this)."::SetInGroup ".$this->error, LOG_ERR);
1989 1989
                 Config::$dbEngine->rollback();
1990 1990
                 return -2;
1991 1991
             }
@@ -2014,15 +2014,15 @@  discard block
 block discarded – undo
2014 2014
 
2015 2015
         Config::$dbEngine->begin();
2016 2016
 
2017
-        $sql = "DELETE FROM " . MAIN_DB_PREFIX . "usergroup_user";
2018
-        $sql .= " WHERE fk_user  = " . $this->id;
2019
-        $sql .= " AND fk_usergroup = " . $group;
2020
-        $sql .= " AND entity = " . $entity;
2017
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."usergroup_user";
2018
+        $sql .= " WHERE fk_user  = ".$this->id;
2019
+        $sql .= " AND fk_usergroup = ".$group;
2020
+        $sql .= " AND entity = ".$entity;
2021 2021
 
2022 2022
         $result = Config::$dbEngine->query($sql);
2023 2023
         if ($result) {
2024 2024
             if (!$error && !$notrigger) {
2025
-                $this->oldgroupid = $group;    // deprecated. Remove this.
2025
+                $this->oldgroupid = $group; // deprecated. Remove this.
2026 2026
                 $this->context = array('audit' => Globals::$langs->trans("UserRemovedFromGroup"), 'oldgroupid' => $group);
2027 2027
 
2028 2028
 // Call trigger
@@ -2038,7 +2038,7 @@  discard block
 block discarded – undo
2038 2038
                 return 1;
2039 2039
             } else {
2040 2040
                 $this->error = $interface->error;
2041
-                DolUtils::dol_syslog(get_class($this) . "::RemoveFromGroup " . $this->error, LOG_ERR);
2041
+                DolUtils::dol_syslog(get_class($this)."::RemoveFromGroup ".$this->error, LOG_ERR);
2042 2042
                 Config::$dbEngine->rollback();
2043 2043
                 return -2;
2044 2044
             }
@@ -2062,7 +2062,7 @@  discard block
 block discarded – undo
2062 2062
     function getPhotoUrl($width, $height, $cssclass = '', $imagesize = '')
2063 2063
     {
2064 2064
 // $result = '<a href="' . DOL_URL_ROOT . '/user/card.php?id=' . $this->id . '">';
2065
-        $result = '<a href="' . BASE_URI . '?controller=user&method=card&id=' . $this->id . '">';
2065
+        $result = '<a href="'.BASE_URI.'?controller=user&method=card&id='.$this->id.'">';
2066 2066
         $result .= Form::showphoto('userphoto', $this, $width, $height, 0, $cssclass, $imagesize);
2067 2067
         $result .= '</a>';
2068 2068
 
@@ -2112,49 +2112,49 @@  discard block
 block discarded – undo
2112 2112
 
2113 2113
 // Info Login
2114 2114
         $label .= '<div class="centpercent">';
2115
-        $label .= '<u>' . Globals::$langs->trans("User") . '</u><br>';
2116
-        $label .= '<b>' . Globals::$langs->trans('Name') . ':</b> ' . $this->getFullName(Globals::$langs, '');
2115
+        $label .= '<u>'.Globals::$langs->trans("User").'</u><br>';
2116
+        $label .= '<b>'.Globals::$langs->trans('Name').':</b> '.$this->getFullName(Globals::$langs, '');
2117 2117
         if (!empty($this->login)) {
2118
-            $label .= '<br><b>' . Globals::$langs->trans('Login') . ':</b> ' . $this->login;
2118
+            $label .= '<br><b>'.Globals::$langs->trans('Login').':</b> '.$this->login;
2119 2119
         }
2120
-        $label .= '<br><b>' . Globals::$langs->trans("EMail") . ':</b> ' . $this->email;
2120
+        $label .= '<br><b>'.Globals::$langs->trans("EMail").':</b> '.$this->email;
2121 2121
         if (!empty($this->admin)) {
2122
-            $label .= '<br><b>' . Globals::$langs->trans("Administrator") . '</b>: ' . DolUtils::yn($this->admin);
2122
+            $label .= '<br><b>'.Globals::$langs->trans("Administrator").'</b>: '.DolUtils::yn($this->admin);
2123 2123
         }
2124 2124
         if (!empty($this->socid)) { // Add thirdparty for external users
2125 2125
             $thirdpartystatic = new Societe($db);
2126 2126
             $thirdpartystatic->fetch($this->socid);
2127 2127
             if (empty($hidethirdpartylogo)) {
2128
-                $companylink = ' ' . $thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2128
+                $companylink = ' '.$thirdpartystatic->getNomUrl(2, (($option == 'nolink') ? 'nolink' : '')); // picto only of company
2129 2129
             }
2130
-            $company = ' (' . Globals::$langs->trans("Company") . ': ' . $thirdpartystatic->name . ')';
2130
+            $company = ' ('.Globals::$langs->trans("Company").': '.$thirdpartystatic->name.')';
2131 2131
         }
2132
-        $type = ($this->socid ? Globals::$langs->trans("External") . $company : Globals::$langs->trans("Internal"));
2133
-        $label .= '<br><b>' . Globals::$langs->trans("Type") . ':</b> ' . $type;
2134
-        $label .= '<br><b>' . Globals::$langs->trans("Status") . '</b>: ' . $this->getLibStatut(0);
2132
+        $type = ($this->socid ? Globals::$langs->trans("External").$company : Globals::$langs->trans("Internal"));
2133
+        $label .= '<br><b>'.Globals::$langs->trans("Type").':</b> '.$type;
2134
+        $label .= '<br><b>'.Globals::$langs->trans("Status").'</b>: '.$this->getLibStatut(0);
2135 2135
         $label .= '</div>';
2136 2136
         if ($infologin > 0) {
2137 2137
             $label .= '<br>';
2138
-            $label .= '<br><u>' . Globals::$langs->trans("Connection") . '</u>';
2139
-            $label .= '<br><b>' . Globals::$langs->trans("IPAddress") . '</b>: ' . $_SERVER["REMOTE_ADDR"];
2138
+            $label .= '<br><u>'.Globals::$langs->trans("Connection").'</u>';
2139
+            $label .= '<br><b>'.Globals::$langs->trans("IPAddress").'</b>: '.$_SERVER["REMOTE_ADDR"];
2140 2140
             if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) {
2141
-                $label .= '<br><b>' . Globals::$langs->trans("ConnectedOnMultiCompany") . ':</b> ' . Globals::$conf->entity . ' (user entity ' . $this->entity . ')';
2141
+                $label .= '<br><b>'.Globals::$langs->trans("ConnectedOnMultiCompany").':</b> '.Globals::$conf->entity.' (user entity '.$this->entity.')';
2142 2142
             }
2143
-            $label .= '<br><b>' . Globals::$langs->trans("AuthenticationMode") . ':</b> ' . $_SESSION["dol_authmode"] . (empty($dolibarr_main_demo) ? '' : ' (demo)');
2144
-            $label .= '<br><b>' . Globals::$langs->trans("ConnectedSince") . ':</b> ' . dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2145
-            $label .= '<br><b>' . Globals::$langs->trans("PreviousConnexion") . ':</b> ' . dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2146
-            $label .= '<br><b>' . Globals::$langs->trans("CurrentTheme") . ':</b> ' . Globals::$conf->theme;
2147
-            $label .= '<br><b>' . Globals::$langs->trans("CurrentMenuManager") . ':</b> ' . $menumanager->name;
2143
+            $label .= '<br><b>'.Globals::$langs->trans("AuthenticationMode").':</b> '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)');
2144
+            $label .= '<br><b>'.Globals::$langs->trans("ConnectedSince").':</b> '.dol_print_date($this->datelastlogin, "dayhour", 'tzuser');
2145
+            $label .= '<br><b>'.Globals::$langs->trans("PreviousConnexion").':</b> '.dol_print_date($this->datepreviouslogin, "dayhour", 'tzuser');
2146
+            $label .= '<br><b>'.Globals::$langs->trans("CurrentTheme").':</b> '.Globals::$conf->theme;
2147
+            $label .= '<br><b>'.Globals::$langs->trans("CurrentMenuManager").':</b> '.$menumanager->name;
2148 2148
             $s = picto_from_langcode(Globals::$langs->getDefaultLang());
2149
-            $label .= '<br><b>' . Globals::$langs->trans("CurrentUserLanguage") . ':</b> ' . ($s ? $s . ' ' : '') . Globals::$langs->getDefaultLang();
2150
-            $label .= '<br><b>' . Globals::$langs->trans("Browser") . ':</b> ' . Globals::$conf->browser->name . ($conf->browser->version ? ' ' . Globals::$conf->browser->version : '') . ' (' . $_SERVER['HTTP_USER_AGENT'] . ')';
2151
-            $label .= '<br><b>' . Globals::$langs->trans("Layout") . ':</b> ' . Globals::$conf->browser->layout;
2152
-            $label .= '<br><b>' . Globals::$langs->trans("Screen") . ':</b> ' . $_SESSION['dol_screenwidth'] . ' x ' . $_SESSION['dol_screenheight'];
2149
+            $label .= '<br><b>'.Globals::$langs->trans("CurrentUserLanguage").':</b> '.($s ? $s.' ' : '').Globals::$langs->getDefaultLang();
2150
+            $label .= '<br><b>'.Globals::$langs->trans("Browser").':</b> '.Globals::$conf->browser->name.($conf->browser->version ? ' '.Globals::$conf->browser->version : '').' ('.$_SERVER['HTTP_USER_AGENT'].')';
2151
+            $label .= '<br><b>'.Globals::$langs->trans("Layout").':</b> '.Globals::$conf->browser->layout;
2152
+            $label .= '<br><b>'.Globals::$langs->trans("Screen").':</b> '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight'];
2153 2153
             if ($conf->browser->layout == 'phone') {
2154
-                $label .= '<br><b>' . Globals::$langs->trans("Phone") . ':</b> ' . Globals::$langs->trans("Yes");
2154
+                $label .= '<br><b>'.Globals::$langs->trans("Phone").':</b> '.Globals::$langs->trans("Yes");
2155 2155
             }
2156 2156
             if (!empty($_SESSION["disablemodules"])) {
2157
-                $label .= '<br><b>' . Globals::$langs->trans("DisabledModules") . ':</b> <br>' . join(', ', explode(',', $_SESSION["disablemodules"]));
2157
+                $label .= '<br><b>'.Globals::$langs->trans("DisabledModules").':</b> <br>'.join(', ', explode(',', $_SESSION["disablemodules"]));
2158 2158
             }
2159 2159
         }
2160 2160
         if ($infologin < 0) {
@@ -2162,10 +2162,10 @@  discard block
 block discarded – undo
2162 2162
         }
2163 2163
 
2164 2164
 // $url = DOL_URL_ROOT . '/user/card.php?id=' . $this->id;
2165
-        $url = BASE_URI . '?controller=user&method=card&id=' . $this->id;
2165
+        $url = BASE_URI.'?controller=user&method=card&id='.$this->id;
2166 2166
         if ($option == 'leave') {
2167 2167
 //$url = DOL_URL_ROOT . '/holiday/list.php?id=' . $this->id;
2168
-            $url = BASE_URI . '?controller=holiday&method=list&id=' . $this->id;
2168
+            $url = BASE_URI.'?controller=holiday&method=list&id='.$this->id;
2169 2169
         }
2170 2170
         if ($option != 'nolink') {
2171 2171
 // Add param to save lastsearch_values or not
@@ -2178,16 +2178,16 @@  discard block
 block discarded – undo
2178 2178
             }
2179 2179
         }
2180 2180
 
2181
-        $linkstart = '<a href="' . $url . '"';
2181
+        $linkstart = '<a href="'.$url.'"';
2182 2182
         $linkclose = "";
2183 2183
         if (empty($notooltip)) {
2184 2184
             if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2185 2185
                 Globals::$langs->load("users");
2186 2186
                 $label = Globals::$langs->trans("ShowUser");
2187
-                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
2187
+                $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
2188 2188
             }
2189
-            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
2190
-            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
2189
+            $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
2190
+            $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
2191 2191
 
2192 2192
             /*
2193 2193
               $hookmanager->initHooks(array('userdao'));
@@ -2197,7 +2197,7 @@  discard block
 block discarded – undo
2197 2197
              */
2198 2198
         }
2199 2199
 
2200
-        $linkstart .= $linkclose . '>';
2200
+        $linkstart .= $linkclose.'>';
2201 2201
         $linkend = '</a>';
2202 2202
 
2203 2203
 //if ($withpictoimg == -1) $result.='<div class="nowrap">';
@@ -2209,15 +2209,15 @@  discard block
 block discarded – undo
2209 2209
             }
2210 2210
 // Only picto
2211 2211
             if ($withpictoimg > 0) {
2212
-                $picto = '<!-- picto user --><div class="inline-block nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '">' . img_object('', 'user', $paddafterimage . ' ' . ($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1) . '</div>';
2212
+                $picto = '<!-- picto user --><div class="inline-block nopadding userimg'.($morecss ? ' '.$morecss : '').'">'.img_object('', 'user', $paddafterimage.' '.($notooltip ? '' : 'class="classfortooltip"'), 0, 0, $notooltip ? 0 : 1).'</div>';
2213 2213
             } else { // Picto must be a photo
2214
-                $picto = '<!-- picto photo user --><div class="inline-block nopadding userimg' . ($morecss ? ' ' . $morecss : '') . '"' . ($paddafterimage ? ' ' . $paddafterimage : '') . '>' . Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto' . ($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1) . '</div>';
2214
+                $picto = '<!-- picto photo user --><div class="inline-block nopadding userimg'.($morecss ? ' '.$morecss : '').'"'.($paddafterimage ? ' '.$paddafterimage : '').'>'.Form::showphoto('userphoto', $this, 0, 0, 0, 'userphoto'.($withpictoimg == -3 ? 'small' : ''), 'mini', 0, 1).'</div>';
2215 2215
             }
2216 2216
             $result .= $picto;
2217 2217
         }
2218 2218
         if ($withpictoimg > -2 && $withpictoimg != 2) {
2219 2219
             if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2220
-                $result .= '<div class="inline-block nopadding valignmiddle usertext' . ((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled') . ($morecss ? ' ' . $morecss : '') . '">';
2220
+                $result .= '<div class="inline-block nopadding valignmiddle usertext'.((!isset($this->statut) || $this->statut) ? '' : ' strikefordisabled').($morecss ? ' '.$morecss : '').'">';
2221 2221
             }
2222 2222
             if ($mode == 'login') {
2223 2223
                 $result .= dol_trunc($this->login, $maxlen);
@@ -2235,7 +2235,7 @@  discard block
 block discarded – undo
2235 2235
         global $action;
2236 2236
         $hookmanager->initHooks(array('userdao'));
2237 2237
         $parameters = array('id' => $this->id, 'getnomurl' => $result);
2238
-        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
2238
+        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2239 2239
         if ($reshook > 0) {
2240 2240
             $result = $hookmanager->resPrint;
2241 2241
         } else {
@@ -2259,7 +2259,7 @@  discard block
 block discarded – undo
2259 2259
         $result = '';
2260 2260
 
2261 2261
 // $linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2262
-        $linkstart = '<a href="' . BASE_URI . '?controller=user&method=card&id=' . $this->id . '">';
2262
+        $linkstart = '<a href="'.BASE_URI.'?controller=user&method=card&id='.$this->id.'">';
2263 2263
         $linkend = '</a>';
2264 2264
 
2265 2265
 //Check user's rights to see an other user
@@ -2269,7 +2269,7 @@  discard block
 block discarded – undo
2269 2269
 
2270 2270
         if ($option == 'xxx') {
2271 2271
 //$linkstart = '<a href="'.DOL_URL_ROOT.'/user/card.php?id='.$this->id.'">';
2272
-            $linkstart = '<a href="' . BASE_URI . '?controller=user&method=card.php&id=' . $this->id . '">';
2272
+            $linkstart = '<a href="'.BASE_URI.'?controller=user&method=card.php&id='.$this->id.'">';
2273 2273
             $linkend = '</a>';
2274 2274
         }
2275 2275
 
@@ -2326,9 +2326,9 @@  discard block
 block discarded – undo
2326 2326
             }
2327 2327
         } elseif ($mode == 2) {
2328 2328
             if ($statut == 1) {
2329
-                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Enabled');
2329
+                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"').' '.Globals::$langs->trans('Enabled');
2330 2330
             } elseif ($statut == 0) {
2331
-                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Disabled');
2331
+                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"').' '.Globals::$langs->trans('Disabled');
2332 2332
             }
2333 2333
         } elseif ($mode == 3) {
2334 2334
             if ($statut == 1) {
@@ -2338,15 +2338,15 @@  discard block
 block discarded – undo
2338 2338
             }
2339 2339
         } elseif ($mode == 4) {
2340 2340
             if ($statut == 1) {
2341
-                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Enabled');
2341
+                return img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"').' '.Globals::$langs->trans('Enabled');
2342 2342
             } elseif ($statut == 0) {
2343
-                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"') . ' ' . Globals::$langs->trans('Disabled');
2343
+                return img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"').' '.Globals::$langs->trans('Disabled');
2344 2344
             }
2345 2345
         } elseif ($mode == 5) {
2346 2346
             if ($statut == 1) {
2347
-                return Globals::$langs->trans('Enabled') . ' ' . img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"');
2347
+                return Globals::$langs->trans('Enabled').' '.img_picto(Globals::$langs->trans('Enabled'), 'statut4', 'class="pictostatus"');
2348 2348
             } elseif ($statut == 0) {
2349
-                return Globals::$langs->trans('Disabled') . ' ' . img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"');
2349
+                return Globals::$langs->trans('Disabled').' '.img_picto(Globals::$langs->trans('Disabled'), 'statut5', 'class="pictostatus"');
2350 2350
             }
2351 2351
         }
2352 2352
     }
@@ -2367,11 +2367,11 @@  discard block
 block discarded – undo
2367 2367
         global $conf;
2368 2368
         $dn = '';
2369 2369
         if ($mode == 0) {
2370
-            $dn = Globals::$conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS] . "," . Globals::$conf->global->LDAP_USER_DN;
2370
+            $dn = Globals::$conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS].",".Globals::$conf->global->LDAP_USER_DN;
2371 2371
         } elseif ($mode == 1) {
2372 2372
             $dn = Globals::$conf->global->LDAP_USER_DN;
2373 2373
         } elseif ($mode == 2) {
2374
-            $dn = Globals::$conf->global->LDAP_KEY_USERS . "=" . $info[$conf->global->LDAP_KEY_USERS];
2374
+            $dn = Globals::$conf->global->LDAP_KEY_USERS."=".$info[$conf->global->LDAP_KEY_USERS];
2375 2375
         }
2376 2376
         return $dn;
2377 2377
     }
@@ -2569,8 +2569,8 @@  discard block
 block discarded – undo
2569 2569
     {
2570 2570
         $sql = "SELECT u.rowid, u.login as ref, u.datec,";
2571 2571
         $sql .= " u.tms as date_modification, u.entity";
2572
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2573
-        $sql .= " WHERE u.rowid = " . $id;
2572
+        $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2573
+        $sql .= " WHERE u.rowid = ".$id;
2574 2574
 
2575 2575
         $result = Config::$dbEngine->query($sql);
2576 2576
         if ($result) {
@@ -2599,9 +2599,9 @@  discard block
 block discarded – undo
2599 2599
     function getNbOfEMailings()
2600 2600
     {
2601 2601
         $sql = "SELECT count(mc.email) as nb";
2602
-        $sql .= " FROM " . MAIN_DB_PREFIX . "mailing_cibles as mc";
2603
-        $sql .= " WHERE mc.email = '" . Config::$dbEngine->escape($this->email) . "'";
2604
-        $sql .= " AND mc.statut NOT IN (-1,0)";      // -1 erreur, 0 non envoye, 1 envoye avec succes
2602
+        $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
2603
+        $sql .= " WHERE mc.email = '".Config::$dbEngine->escape($this->email)."'";
2604
+        $sql .= " AND mc.statut NOT IN (-1,0)"; // -1 erreur, 0 non envoye, 1 envoye avec succes
2605 2605
 
2606 2606
         $resql = Config::$dbEngine->query($sql);
2607 2607
         if ($resql) {
@@ -2629,19 +2629,19 @@  discard block
 block discarded – undo
2629 2629
         global $conf;
2630 2630
 
2631 2631
         $sql = "SELECT count(rowid) as nb";
2632
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
2632
+        $sql .= " FROM ".MAIN_DB_PREFIX."user";
2633 2633
         if ($option == 'superadmin') {
2634 2634
             $sql .= " WHERE entity = 0";
2635 2635
             if ($admin >= 0) {
2636
-                $sql .= " AND admin = " . $admin;
2636
+                $sql .= " AND admin = ".$admin;
2637 2637
             }
2638 2638
         } else {
2639
-            $sql .= " WHERE entity IN (" . getEntity('user', 0) . ")";
2639
+            $sql .= " WHERE entity IN (".getEntity('user', 0).")";
2640 2640
             if ($limitTo == 'active') {
2641 2641
                 $sql .= " AND statut = 1";
2642 2642
             }
2643 2643
             if ($admin >= 0) {
2644
-                $sql .= " AND admin = " . $admin;
2644
+                $sql .= " AND admin = ".$admin;
2645 2645
             }
2646 2646
         }
2647 2647
 
@@ -2692,7 +2692,7 @@  discard block
 block discarded – undo
2692 2692
 
2693 2693
         $result = $this->update(Globals::$user);
2694 2694
 
2695
-        DolUtils::dol_syslog(get_class($this) . "::update_ldap2dolibarr result=" . $result, LOG_DEBUG);
2695
+        DolUtils::dol_syslog(get_class($this)."::update_ldap2dolibarr result=".$result, LOG_DEBUG);
2696 2696
 
2697 2697
         return $result;
2698 2698
     }
@@ -2707,10 +2707,10 @@  discard block
 block discarded – undo
2707 2707
     function get_children()
2708 2708
     {
2709 2709
 // phpcs:enable
2710
-        $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "user";
2711
-        $sql .= " WHERE fk_user = " . $this->id;
2710
+        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."user";
2711
+        $sql .= " WHERE fk_user = ".$this->id;
2712 2712
 
2713
-        DolUtils::dol_syslog(get_class($this) . "::get_children result=" . $result, LOG_DEBUG);
2713
+        DolUtils::dol_syslog(get_class($this)."::get_children result=".$result, LOG_DEBUG);
2714 2714
         $res = Config::$dbEngine->query($sql);
2715 2715
         if ($res) {
2716 2716
             $this->users = array();
@@ -2739,11 +2739,11 @@  discard block
 block discarded – undo
2739 2739
 
2740 2740
 // Load array[child]=parent
2741 2741
         $sql = "SELECT fk_user as id_parent, rowid as id_son";
2742
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
2742
+        $sql .= " FROM ".MAIN_DB_PREFIX."user";
2743 2743
         $sql .= " WHERE fk_user <> 0";
2744
-        $sql .= " AND entity IN (" . getEntity('user') . ")";
2744
+        $sql .= " AND entity IN (".getEntity('user').")";
2745 2745
 
2746
-        DolUtils::dol_syslog(get_class($this) . "::loadParentOf", LOG_DEBUG);
2746
+        DolUtils::dol_syslog(get_class($this)."::loadParentOf", LOG_DEBUG);
2747 2747
         $resql = Config::$dbEngine->query($sql);
2748 2748
         if ($resql) {
2749 2749
             while ($obj = Config::$dbEngine->fetch_object($resql)) {
@@ -2785,20 +2785,20 @@  discard block
 block discarded – undo
2785 2785
 
2786 2786
 // Init $this->users array
2787 2787
         $sql = "SELECT DISTINCT u.rowid, u.firstname, u.lastname, u.fk_user, u.fk_soc, u.login, u.email, u.gender, u.admin, u.statut, u.photo, u.entity"; // Distinct reduce pb with old tables with duplicates
2788
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2788
+        $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2789 2789
 // Add fields from hooks
2790 2790
         $parameters = array();
2791
-        $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters);    // Note that $action and $object may have been modified by hook
2791
+        $reshook = $hookmanager->executeHooks('printUserListWhere', $parameters); // Note that $action and $object may have been modified by hook
2792 2792
         if ($reshook > 0) {
2793 2793
             $sql .= $hookmanager->resPrint;
2794 2794
         } else {
2795
-            $sql .= " WHERE u.entity IN (" . getEntity('user') . ")";
2795
+            $sql .= " WHERE u.entity IN (".getEntity('user').")";
2796 2796
         }
2797 2797
         if ($filter) {
2798
-            $sql .= " AND " . $filter;
2798
+            $sql .= " AND ".$filter;
2799 2799
         }
2800 2800
 
2801
-        DolUtils::dol_syslog(get_class($this) . "::get_full_tree get user list", LOG_DEBUG);
2801
+        DolUtils::dol_syslog(get_class($this)."::get_full_tree get user list", LOG_DEBUG);
2802 2802
         $resql = Config::$dbEngine->query($sql);
2803 2803
         if ($resql) {
2804 2804
             $i = 0;
@@ -2824,7 +2824,7 @@  discard block
 block discarded – undo
2824 2824
         }
2825 2825
 
2826 2826
 // We add the fullpath property to each elements of first level (no parent exists)
2827
-        DolUtils::dol_syslog(get_class($this) . "::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
2827
+        DolUtils::dol_syslog(get_class($this)."::get_full_tree call to build_path_from_id_user", LOG_DEBUG);
2828 2828
         foreach ($this->users as $key => $val) {
2829 2829
             $result = $this->build_path_from_id_user($key, 0); // Process a branch from the root user key (this user has no parent)
2830 2830
             if ($result < 0) {
@@ -2836,18 +2836,18 @@  discard block
 block discarded – undo
2836 2836
 // Exclude leaf including $deleteafterid from tree
2837 2837
         if ($deleteafterid) {
2838 2838
 //print "Look to discard user ".$deleteafterid."\n";
2839
-            $keyfilter1 = '^' . $deleteafterid . '$';
2840
-            $keyfilter2 = '_' . $deleteafterid . '$';
2841
-            $keyfilter3 = '^' . $deleteafterid . '_';
2842
-            $keyfilter4 = '_' . $deleteafterid . '_';
2839
+            $keyfilter1 = '^'.$deleteafterid.'$';
2840
+            $keyfilter2 = '_'.$deleteafterid.'$';
2841
+            $keyfilter3 = '^'.$deleteafterid.'_';
2842
+            $keyfilter4 = '_'.$deleteafterid.'_';
2843 2843
             foreach ($this->users as $key => $val) {
2844
-                if (preg_match('/' . $keyfilter1 . '/', $val['fullpath']) || preg_match('/' . $keyfilter2 . '/', $val['fullpath']) || preg_match('/' . $keyfilter3 . '/', $val['fullpath']) || preg_match('/' . $keyfilter4 . '/', $val['fullpath'])) {
2844
+                if (preg_match('/'.$keyfilter1.'/', $val['fullpath']) || preg_match('/'.$keyfilter2.'/', $val['fullpath']) || preg_match('/'.$keyfilter3.'/', $val['fullpath']) || preg_match('/'.$keyfilter4.'/', $val['fullpath'])) {
2845 2845
                     unset($this->users[$key]);
2846 2846
                 }
2847 2847
             }
2848 2848
         }
2849 2849
 
2850
-        DolUtils::dol_syslog(get_class($this) . "::get_full_tree dol_sort_array", LOG_DEBUG);
2850
+        DolUtils::dol_syslog(get_class($this)."::get_full_tree dol_sort_array", LOG_DEBUG);
2851 2851
         $this->users = dol_sort_array($this->users, 'fullname', 'asc', true, false);
2852 2852
 
2853 2853
 //var_dump($this->users);
@@ -2875,10 +2875,10 @@  discard block
 block discarded – undo
2875 2875
 
2876 2876
             $idtoscan = $this->id;
2877 2877
 
2878
-            DolUtils::dol_syslog("Build childid for id = " . $idtoscan);
2878
+            DolUtils::dol_syslog("Build childid for id = ".$idtoscan);
2879 2879
             foreach ($this->users as $id => $val) {
2880 2880
 //var_dump($val['fullpath']);
2881
-                if (preg_match('/_' . $idtoscan . '_/', $val['fullpath'])) {
2881
+                if (preg_match('/_'.$idtoscan.'_/', $val['fullpath'])) {
2882 2882
                     $childids[$val['id']] = $val['id'];
2883 2883
                 }
2884 2884
             }
@@ -2904,16 +2904,16 @@  discard block
 block discarded – undo
2904 2904
     function build_path_from_id_user($id_user, $protection = 0)
2905 2905
     {
2906 2906
 // phpcs:enable
2907
-        DolUtils::dol_syslog(get_class($this) . "::build_path_from_id_user id_user=" . $id_user . " protection=" . $protection, LOG_DEBUG);
2907
+        DolUtils::dol_syslog(get_class($this)."::build_path_from_id_user id_user=".$id_user." protection=".$protection, LOG_DEBUG);
2908 2908
 
2909 2909
         if (!empty($this->users[$id_user]['fullpath'])) {
2910 2910
 // Already defined
2911
-            DolUtils::dol_syslog(get_class($this) . "::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
2911
+            DolUtils::dol_syslog(get_class($this)."::build_path_from_id_user fullpath and fullname already defined", LOG_WARNING);
2912 2912
             return 0;
2913 2913
         }
2914 2914
 
2915 2915
 // Define fullpath and fullname
2916
-        $this->users[$id_user]['fullpath'] = '_' . $id_user;
2916
+        $this->users[$id_user]['fullpath'] = '_'.$id_user;
2917 2917
         $this->users[$id_user]['fullname'] = $this->users[$id_user]['lastname'];
2918 2918
         $i = 0;
2919 2919
         $cursor_user = $id_user;
@@ -2922,11 +2922,11 @@  discard block
 block discarded – undo
2922 2922
         while (!empty($this->parentof[$cursor_user])) {
2923 2923
             if (in_array($this->parentof[$cursor_user], Globals::$useridfound)) {
2924 2924
                 DolUtils::dol_syslog("The hierarchy of user has a recursive loop", LOG_WARNING);
2925
-                return -1;     // Should not happen. Protection against looping hierarchy
2925
+                return -1; // Should not happen. Protection against looping hierarchy
2926 2926
             }
2927 2927
             Globals::$useridfound[] = $this->parentof[$cursor_user];
2928
-            $this->users[$id_user]['fullpath'] = '_' . $this->parentof[$cursor_user] . $this->users[$id_user]['fullpath'];
2929
-            $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'] . ' >> ' . $this->users[$id_user]['fullname'];
2928
+            $this->users[$id_user]['fullpath'] = '_'.$this->parentof[$cursor_user].$this->users[$id_user]['fullpath'];
2929
+            $this->users[$id_user]['fullname'] = $this->users[$this->parentof[$cursor_user]]['lastname'].' >> '.$this->users[$id_user]['fullname'];
2930 2930
             $i++;
2931 2931
             $cursor_user = $this->parentof[$cursor_user];
2932 2932
         }
@@ -2968,10 +2968,10 @@  discard block
 block discarded – undo
2968 2968
         $this->nb = array();
2969 2969
 
2970 2970
         $sql = "SELECT count(u.rowid) as nb";
2971
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user as u";
2971
+        $sql .= " FROM ".MAIN_DB_PREFIX."user as u";
2972 2972
         $sql .= " WHERE u.statut > 0";
2973 2973
 //$sql.= " AND employee != 0";
2974
-        $sql .= " AND u.entity IN (" . getEntity('user') . ")";
2974
+        $sql .= " AND u.entity IN (".getEntity('user').")";
2975 2975
 
2976 2976
         $resql = Config::$dbEngine->query($sql);
2977 2977
         if ($resql) {
@@ -3036,8 +3036,8 @@  discard block
 block discarded – undo
3036 3036
         }
3037 3037
 
3038 3038
         $sql = "SELECT rowid, email, user_mobile, civility, lastname, firstname";
3039
-        $sql .= " FROM " . MAIN_DB_PREFIX . "user";
3040
-        $sql .= " WHERE rowid = '" . $rowid . "'";
3039
+        $sql .= " FROM ".MAIN_DB_PREFIX."user";
3040
+        $sql .= " WHERE rowid = '".$rowid."'";
3041 3041
 
3042 3042
         $resql = Config::$dbEngine->query($sql);
3043 3043
         if ($resql) {
@@ -3047,7 +3047,7 @@  discard block
 block discarded – undo
3047 3047
                 $obj = Config::$dbEngine->fetch_object($resql);
3048 3048
 
3049 3049
                 if ($mode == 'email') {
3050
-                    $this->user_property = dolGetFirstLastname($obj->firstname, $obj->lastname) . " <" . $obj->email . ">";
3050
+                    $this->user_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
3051 3051
                 } else if ($mode == 'mobile') {
3052 3052
                     $this->user_property = $obj->user_mobile;
3053 3053
                 }
@@ -3074,7 +3074,7 @@  discard block
 block discarded – undo
3074 3074
         global $conf;
3075 3075
 
3076 3076
         $sql = "SELECT t.rowid";
3077
-        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t ';
3077
+        $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t ';
3078 3078
         $sql .= " WHERE 1";
3079 3079
 
3080 3080
 // Manage filter
@@ -3082,25 +3082,25 @@  discard block
 block discarded – undo
3082 3082
         if (!empty($filter)) {
3083 3083
             foreach ($filter as $key => $value) {
3084 3084
                 if ($key == 't.rowid') {
3085
-                    $sqlwhere[] = $key . '=' . $value;
3085
+                    $sqlwhere[] = $key.'='.$value;
3086 3086
                 } elseif (strpos($key, 'date') !== false) {
3087
-                    $sqlwhere[] = $key . ' = \'' . Config::$dbEngine->idate($value) . '\'';
3087
+                    $sqlwhere[] = $key.' = \''.Config::$dbEngine->idate($value).'\'';
3088 3088
                 } elseif ($key == 'customsql') {
3089 3089
                     $sqlwhere[] = $value;
3090 3090
                 } else {
3091
-                    $sqlwhere[] = $key . ' LIKE \'%' . Config::$dbEngine->escape($value) . '%\'';
3091
+                    $sqlwhere[] = $key.' LIKE \'%'.Config::$dbEngine->escape($value).'%\'';
3092 3092
                 }
3093 3093
             }
3094 3094
         }
3095 3095
         if (count($sqlwhere) > 0) {
3096
-            $sql .= ' AND (' . implode(' ' . $filtermode . ' ', $sqlwhere) . ')';
3096
+            $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
3097 3097
         }
3098 3098
         $sql .= Config::$dbEngine->order($sortfield, $sortorder);
3099 3099
         if ($limit) {
3100 3100
             $sql .= Config::$dbEngine->plimit($limit + 1, $offset);
3101 3101
         }
3102 3102
 
3103
-        DolUtils::dol_syslog(get_class($this) . "::" . __METHOD__, LOG_DEBUG);
3103
+        DolUtils::dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
3104 3104
 
3105 3105
         $resql = Config::$dbEngine->query($sql);
3106 3106
         if ($resql) {
Please login to merge, or discard this patch.
Braces   +10 added lines, -8 removed lines patch added patch discarded remove patch
@@ -520,16 +520,17 @@  discard block
 block discarded – undo
520 520
                     $nid = $obj->id;
521 521
 
522 522
                     $sql = "DELETE FROM " . MAIN_DB_PREFIX . "user_rights WHERE fk_user = " . $this->id . " AND fk_id=" . $nid . " AND entity = " . $entity;
523
-                    if (!Config::$dbEngine->query($sql))
524
-                        $error++;
523
+                    if (!Config::$dbEngine->query($sql)) {
524
+                                            $error++;
525
+                    }
525 526
                     $sql = "INSERT INTO " . MAIN_DB_PREFIX . "user_rights (entity, fk_user, fk_id) VALUES (" . $entity . ", " . $this->id . ", " . $nid . ")";
526
-                    if (!Config::$dbEngine->query($sql))
527
-                        $error++;
527
+                    if (!Config::$dbEngine->query($sql)) {
528
+                                            $error++;
529
+                    }
528 530
 
529 531
                     $i++;
530 532
                 }
531
-            }
532
-            else {
533
+            } else {
533 534
                 $error++;
534 535
                 dol_print_error(Config::$dbEngine);
535 536
             }
@@ -2224,8 +2225,9 @@  discard block
 block discarded – undo
2224 2225
             } else {
2225 2226
                 $result .= $this->getFullName(Globals::$langs, '', ($mode == 'firstname' ? 2 : -1), $maxlen);
2226 2227
             }
2227
-            if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
2228
-                $result .= '</div>';
2228
+            if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
2229
+                            $result .= '</div>';
2230
+            }
2229 2231
         }
2230 2232
         $result .= (($option == 'nolink') ? '' : $linkend);
2231 2233
 //if ($withpictoimg == -1) $result.='</div>';
Please login to merge, or discard this patch.
Base/Conf.php 2 patches
Spacing   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
     //! Used to store current currency (ISO code like 'USD', 'EUR', ...)
37 37
     public $currency;
38 38
     //! Used to store current css (from theme)
39
-    public $theme;        // Contains current theme ("eldy", "auguria", ...)
40
-    public $css;          // Contains full path of css page ("/theme/eldy/style.css.php", ...)
39
+    public $theme; // Contains current theme ("eldy", "auguria", ...)
40
+    public $css; // Contains full path of css page ("/theme/eldy/style.css.php", ...)
41 41
     //! Used to store current menu handler
42 42
     public $standard_menu;
43 43
     public $modules = array(); // List of activated modules
@@ -54,11 +54,11 @@  discard block
 block discarded – undo
54 54
     public $entity = 1;
55 55
     //! Used to store list of entities to use for each element
56 56
     public $entities = array();
57
-    public $dol_hide_topmenu;   // Set if we force param dol_hide_topmenu into login url
58
-    public $dol_hide_leftmenu;   // Set if we force param dol_hide_leftmenu into login url
57
+    public $dol_hide_topmenu; // Set if we force param dol_hide_topmenu into login url
58
+    public $dol_hide_leftmenu; // Set if we force param dol_hide_leftmenu into login url
59 59
     public $dol_optimize_smallscreen; // Set if we force param dol_optimize_smallscreen into login url or if browser is smartphone
60
-    public $dol_no_mouse_hover;   // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone
61
-    public $dol_use_jmobile;   // Set if we force param dol_use_jmobile into login url
60
+    public $dol_no_mouse_hover; // Set if we force param dol_no_mouse_hover into login url or if browser is smartphone
61
+    public $dol_use_jmobile; // Set if we force param dol_use_jmobile into login url
62 62
 
63 63
     /**
64 64
      * Constructor
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
         $this->multicompany = new \stdClass();
80 80
 
81 81
         //! Charset for HTML output and for storing data in memory
82
-        $this->file->character_set_client = 'UTF-8';   // UTF-8, ISO-8859-1
82
+        $this->file->character_set_client = 'UTF-8'; // UTF-8, ISO-8859-1
83 83
         // First level object
84 84
         // TODO Remove this part.
85 85
         $this->expedition_bon = new \stdClass();
@@ -113,13 +113,13 @@  discard block
 block discarded – undo
113 113
     {
114 114
         global $conf;
115 115
 
116
-        dol_syslog(get_class($this) . "::setValues");
116
+        dol_syslog(get_class($this)."::setValues");
117 117
 
118 118
         //Define all global constants into Conf::$global->key=value
119
-        $sql = "SELECT " . $db->decrypt('name') . " as name,";
120
-        $sql .= " " . $db->decrypt('value') . " as value, entity";
121
-        $sql .= " FROM " . MAIN_DB_PREFIX . "const";
122
-        $sql .= " WHERE entity IN (0," . $this->entity . ")";
119
+        $sql = "SELECT ".$db->decrypt('name')." as name,";
120
+        $sql .= " ".$db->decrypt('value')." as value, entity";
121
+        $sql .= " FROM ".MAIN_DB_PREFIX."const";
122
+        $sql .= " WHERE entity IN (0,".$this->entity.")";
123 123
         $sql .= " ORDER BY entity"; // This is to have entity 0 first, then entity 1 that overwrite.
124 124
 
125 125
         $resql = $db->query($sql);
@@ -159,13 +159,13 @@  discard block
 block discarded – undo
159 159
                             if (is_array($arrValue) && !empty($arrValue))
160 160
                                 $value = $arrValue;
161 161
                             else if (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl')))
162
-                                $value = '/' . $modulename . '/core/' . $partname . '/';
162
+                                $value = '/'.$modulename.'/core/'.$partname.'/';
163 163
                             else if (in_array($partname, array('models', 'theme')))
164
-                                $value = '/' . $modulename . '/';
164
+                                $value = '/'.$modulename.'/';
165 165
                             else if (in_array($partname, array('sms')))
166
-                                $value = '/' . $modulename . '/';
166
+                                $value = '/'.$modulename.'/';
167 167
                             else if ($value == 1)
168
-                                $value = '/' . $modulename . '/core/modules/' . $partname . '/'; // ex: partname = societe
168
+                                $value = '/'.$modulename.'/core/modules/'.$partname.'/'; // ex: partname = societe
169 169
                             $this->modules_parts[$partname] = array_merge($this->modules_parts[$partname], array($modulename => $value)); // $value may be a string or an array
170 170
                         }
171 171
                         // If this is a module constant (must be at end)
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
                             if (!isset($this->$modulename) || !is_object($this->$modulename))
179 179
                                 $this->$modulename = new \stdClass();
180 180
                             $this->$modulename->enabled = true;
181
-                            $this->modules[] = $modulename;              // Add this module in list of enabled modules
181
+                            $this->modules[] = $modulename; // Add this module in list of enabled modules
182 182
                         }
183 183
                     }
184 184
                 }
@@ -193,7 +193,7 @@  discard block
 block discarded – undo
193 193
             $filesList = explode(":", Conf::$global->LOCAL_CONSTS_FILES);
194 194
             foreach ($filesList as $file) {
195 195
                 $file = dol_sanitizeFileName($file);
196
-                include_once DOL_DOCUMENT_ROOT . "/" . $file . "/" . $file . "_consts.php";
196
+                include_once DOL_DOCUMENT_ROOT."/".$file."/".$file."_consts.php";
197 197
                 foreach ($file2bddconsts as $key => $value) {
198 198
                     Conf::$global->$key = $value;
199 199
                 }
@@ -209,7 +209,7 @@  discard block
 block discarded – undo
209 209
             try {
210 210
                 date_default_timezone_set(Conf::$global->MAIN_SERVER_TZ);
211 211
             } catch (Exception $e) {
212
-                dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=" . Conf::$global->MAIN_SERVER_TZ, LOG_ERR);
212
+                dol_syslog("Error: Bad value for parameter MAIN_SERVER_TZ=".Conf::$global->MAIN_SERVER_TZ, LOG_ERR);
213 213
             }
214 214
         }
215 215
 
@@ -269,18 +269,18 @@  discard block
 block discarded – undo
269 269
         $rootforuser = DOL_DATA_ROOT;
270 270
         // If multicompany module is enabled, we redefine the root of data
271 271
         if (!empty($this->multicompany->enabled) && !empty($this->entity) && $this->entity > 1) {
272
-            $rootfordata .= '/' . $this->entity;
272
+            $rootfordata .= '/'.$this->entity;
273 273
         }
274 274
 
275 275
         // Define default dir_output and dir_temp for directories of modules
276 276
         foreach ($this->modules as $module) {
277 277
             //var_dump($module);
278 278
             // For multicompany sharings
279
-            $this->$module->multidir_output = array($this->entity => $rootfordata . "/" . $module);
280
-            $this->$module->multidir_temp = array($this->entity => $rootfordata . "/" . $module . "/temp");
279
+            $this->$module->multidir_output = array($this->entity => $rootfordata."/".$module);
280
+            $this->$module->multidir_temp = array($this->entity => $rootfordata."/".$module."/temp");
281 281
             // For backward compatibility
282
-            $this->$module->dir_output = $rootfordata . "/" . $module;
283
-            $this->$module->dir_temp = $rootfordata . "/" . $module . "/temp";
282
+            $this->$module->dir_output = $rootfordata."/".$module;
283
+            $this->$module->dir_temp = $rootfordata."/".$module."/temp";
284 284
         }
285 285
 
286 286
         // External modules storage
@@ -290,45 +290,45 @@  discard block
 block discarded – undo
290 290
                     foreach ($dirs as $type => $name) {
291 291
                         $subdir = ($type == 'temp' ? '/temp' : '');
292 292
                         // For multicompany sharings
293
-                        $varname = 'multidir_' . $type;
294
-                        $this->$module->$varname = array($this->entity => $rootfordata . "/" . $name . $subdir);
293
+                        $varname = 'multidir_'.$type;
294
+                        $this->$module->$varname = array($this->entity => $rootfordata."/".$name.$subdir);
295 295
                         // For backward compatibility
296
-                        $varname = 'dir_' . $type;
297
-                        $this->$module->$varname = $rootfordata . "/" . $name . $subdir;
296
+                        $varname = 'dir_'.$type;
297
+                        $this->$module->$varname = $rootfordata."/".$name.$subdir;
298 298
                     }
299 299
                 }
300 300
             }
301 301
         }
302 302
 
303 303
         // For mycompany storage
304
-        $this->mycompany->dir_output = $rootfordata . "/mycompany";
305
-        $this->mycompany->dir_temp = $rootfordata . "/mycompany/temp";
304
+        $this->mycompany->dir_output = $rootfordata."/mycompany";
305
+        $this->mycompany->dir_temp = $rootfordata."/mycompany/temp";
306 306
 
307 307
         // For admin storage
308
-        $this->admin->dir_output = $rootfordata . '/admin';
309
-        $this->admin->dir_temp = $rootfordata . '/admin/temp';
308
+        $this->admin->dir_output = $rootfordata.'/admin';
309
+        $this->admin->dir_temp = $rootfordata.'/admin/temp';
310 310
 
311 311
         // For user storage
312
-        $this->user->multidir_output = array($this->entity => $rootfordata . "/users");
313
-        $this->user->multidir_temp = array($this->entity => $rootfordata . "/users/temp");
312
+        $this->user->multidir_output = array($this->entity => $rootfordata."/users");
313
+        $this->user->multidir_temp = array($this->entity => $rootfordata."/users/temp");
314 314
         // For backward compatibility
315
-        $this->user->dir_output = $rootforuser . "/users";
316
-        $this->user->dir_temp = $rootforuser . "/users/temp";
315
+        $this->user->dir_output = $rootforuser."/users";
316
+        $this->user->dir_temp = $rootforuser."/users/temp";
317 317
 
318 318
         // For usergroup storage
319
-        $this->usergroup->dir_output = $rootforuser . "/usergroups";
320
-        $this->usergroup->dir_temp = $rootforuser . "/usergroups/temp";
319
+        $this->usergroup->dir_output = $rootforuser."/usergroups";
320
+        $this->usergroup->dir_temp = $rootforuser."/usergroups/temp";
321 321
 
322 322
         // For proposal storage
323
-        $this->propal->multidir_output = array($this->entity => $rootfordata . "/propale");
324
-        $this->propal->multidir_temp = array($this->entity => $rootfordata . "/propale/temp");
323
+        $this->propal->multidir_output = array($this->entity => $rootfordata."/propale");
324
+        $this->propal->multidir_temp = array($this->entity => $rootfordata."/propale/temp");
325 325
         // For backward compatibility
326
-        $this->propal->dir_output = $rootfordata . "/propale";
327
-        $this->propal->dir_temp = $rootfordata . "/propale/temp";
326
+        $this->propal->dir_output = $rootfordata."/propale";
327
+        $this->propal->dir_temp = $rootfordata."/propale/temp";
328 328
 
329 329
         // For medias storage
330
-        $this->medias->multidir_output = array($this->entity => $rootfordata . "/medias");
331
-        $this->medias->multidir_temp = array($this->entity => $rootfordata . "/medias/temp");
330
+        $this->medias->multidir_output = array($this->entity => $rootfordata."/medias");
331
+        $this->medias->multidir_temp = array($this->entity => $rootfordata."/medias/temp");
332 332
 
333 333
         // Exception: Some dir are not the name of module. So we keep exception here for backward compatibility.
334 334
         // Sous module bons d'expedition
@@ -339,72 +339,72 @@  discard block
 block discarded – undo
339 339
         // Module fournisseur
340 340
         if (!empty($this->fournisseur)) {
341 341
             $this->fournisseur->commande = new \stdClass();
342
-            $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata . "/fournisseur/commande");
343
-            $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/commande/temp");
344
-            $this->fournisseur->commande->dir_output = $rootfordata . "/fournisseur/commande";  // For backward compatibility
345
-            $this->fournisseur->commande->dir_temp = $rootfordata . "/fournisseur/commande/temp"; // For backward compatibility
342
+            $this->fournisseur->commande->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande");
343
+            $this->fournisseur->commande->multidir_temp = array($this->entity => $rootfordata."/fournisseur/commande/temp");
344
+            $this->fournisseur->commande->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility
345
+            $this->fournisseur->commande->dir_temp = $rootfordata."/fournisseur/commande/temp"; // For backward compatibility
346 346
             $this->fournisseur->facture = new \stdClass();
347
-            $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata . "/fournisseur/facture");
348
-            $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/facture/temp");
349
-            $this->fournisseur->facture->dir_output = $rootfordata . "/fournisseur/facture";  // For backward compatibility
350
-            $this->fournisseur->facture->dir_temp = $rootfordata . "/fournisseur/facture/temp"; // For backward compatibility
347
+            $this->fournisseur->facture->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture");
348
+            $this->fournisseur->facture->multidir_temp = array($this->entity => $rootfordata."/fournisseur/facture/temp");
349
+            $this->fournisseur->facture->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility
350
+            $this->fournisseur->facture->dir_temp = $rootfordata."/fournisseur/facture/temp"; // For backward compatibility
351 351
             $this->supplierproposal = new \stdClass();
352
-            $this->supplierproposal->multidir_output = array($this->entity => $rootfordata . "/supplier_proposal");
353
-            $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata . "/supplier_proposal/temp");
354
-            $this->supplierproposal->dir_output = $rootfordata . "/supplier_proposal";    // For backward compatibility
355
-            $this->supplierproposal->dir_temp = $rootfordata . "/supplier_proposal/temp";   // For backward compatibility
352
+            $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal");
353
+            $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata."/supplier_proposal/temp");
354
+            $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility
355
+            $this->supplierproposal->dir_temp = $rootfordata."/supplier_proposal/temp"; // For backward compatibility
356 356
             $this->fournisseur->payment = new \stdClass();
357
-            $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata . "/fournisseur/payment");
358
-            $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/payment/temp");
359
-            $this->fournisseur->payment->dir_output = $rootfordata . "/fournisseur/payment";  // For backward compatibility
360
-            $this->fournisseur->payment->dir_temp = $rootfordata . "/fournisseur/payment/temp"; // For backward compatibility
357
+            $this->fournisseur->payment->multidir_output = array($this->entity => $rootfordata."/fournisseur/payment");
358
+            $this->fournisseur->payment->multidir_temp = array($this->entity => $rootfordata."/fournisseur/payment/temp");
359
+            $this->fournisseur->payment->dir_output = $rootfordata."/fournisseur/payment"; // For backward compatibility
360
+            $this->fournisseur->payment->dir_temp = $rootfordata."/fournisseur/payment/temp"; // For backward compatibility
361 361
             // To prepare split of module fournisseur into fournisseur + supplier_order + supplier_invoice
362 362
             if (!empty($this->fournisseur->enabled) && empty(Conf::$global->MAIN_USE_NEW_SUPPLIERMOD)) {  // By default, if module supplier is on, we set new properties
363 363
                 $this->supplier_order = new \stdClass();
364 364
                 $this->supplier_order->enabled = 1;
365
-                $this->supplier_order->multidir_output = array($this->entity => $rootfordata . "/fournisseur/commande");
366
-                $this->supplier_order->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/commande/temp");
367
-                $this->supplier_order->dir_output = $rootfordata . "/fournisseur/commande";   // For backward compatibility
368
-                $this->supplier_order->dir_temp = $rootfordata . "/fournisseur/commande/temp";  // For backward compatibility
365
+                $this->supplier_order->multidir_output = array($this->entity => $rootfordata."/fournisseur/commande");
366
+                $this->supplier_order->multidir_temp = array($this->entity => $rootfordata."/fournisseur/commande/temp");
367
+                $this->supplier_order->dir_output = $rootfordata."/fournisseur/commande"; // For backward compatibility
368
+                $this->supplier_order->dir_temp = $rootfordata."/fournisseur/commande/temp"; // For backward compatibility
369 369
                 $this->supplier_invoice = new \stdClass();
370 370
                 $this->supplier_invoice->enabled = 1;
371
-                $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata . "/fournisseur/facture");
372
-                $this->supplier_invoice->multidir_temp = array($this->entity => $rootfordata . "/fournisseur/facture/temp");
373
-                $this->supplier_invoice->dir_output = $rootfordata . "/fournisseur/facture";  // For backward compatibility
374
-                $this->supplier_invoice->dir_temp = $rootfordata . "/fournisseur/facture/temp";  // For backward compatibility
371
+                $this->supplier_invoice->multidir_output = array($this->entity => $rootfordata."/fournisseur/facture");
372
+                $this->supplier_invoice->multidir_temp = array($this->entity => $rootfordata."/fournisseur/facture/temp");
373
+                $this->supplier_invoice->dir_output = $rootfordata."/fournisseur/facture"; // For backward compatibility
374
+                $this->supplier_invoice->dir_temp = $rootfordata."/fournisseur/facture/temp"; // For backward compatibility
375 375
                 $this->supplierproposal = new \stdClass();
376
-                $this->supplierproposal->multidir_output = array($this->entity => $rootfordata . "/supplier_proposal");
377
-                $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata . "/supplier_proposal/temp");
378
-                $this->supplierproposal->dir_output = $rootfordata . "/supplier_proposal";   // For backward compatibility
379
-                $this->supplierproposal->dir_temp = $rootfordata . "/supplier_proposal/temp";  // For backward compatibility
376
+                $this->supplierproposal->multidir_output = array($this->entity => $rootfordata."/supplier_proposal");
377
+                $this->supplierproposal->multidir_temp = array($this->entity => $rootfordata."/supplier_proposal/temp");
378
+                $this->supplierproposal->dir_output = $rootfordata."/supplier_proposal"; // For backward compatibility
379
+                $this->supplierproposal->dir_temp = $rootfordata."/supplier_proposal/temp"; // For backward compatibility
380 380
             }
381 381
         }
382 382
 
383 383
         // Module product/service
384
-        $this->product->multidir_output = array($this->entity => $rootfordata . "/produit");
385
-        $this->product->multidir_temp = array($this->entity => $rootfordata . "/produit/temp");
386
-        $this->service->multidir_output = array($this->entity => $rootfordata . "/produit");
387
-        $this->service->multidir_temp = array($this->entity => $rootfordata . "/produit/temp");
384
+        $this->product->multidir_output = array($this->entity => $rootfordata."/produit");
385
+        $this->product->multidir_temp = array($this->entity => $rootfordata."/produit/temp");
386
+        $this->service->multidir_output = array($this->entity => $rootfordata."/produit");
387
+        $this->service->multidir_temp = array($this->entity => $rootfordata."/produit/temp");
388 388
         // For backward compatibility
389
-        $this->product->dir_output = $rootfordata . "/produit";
390
-        $this->product->dir_temp = $rootfordata . "/produit/temp";
391
-        $this->service->dir_output = $rootfordata . "/produit";
392
-        $this->service->dir_temp = $rootfordata . "/produit/temp";
389
+        $this->product->dir_output = $rootfordata."/produit";
390
+        $this->product->dir_temp = $rootfordata."/produit/temp";
391
+        $this->service->dir_output = $rootfordata."/produit";
392
+        $this->service->dir_temp = $rootfordata."/produit/temp";
393 393
 
394 394
         // Module productbatch
395
-        $this->productbatch->multidir_output = array($this->entity => $rootfordata . "/produitlot");
396
-        $this->productbatch->multidir_temp = array($this->entity => $rootfordata . "/produitlot/temp");
395
+        $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot");
396
+        $this->productbatch->multidir_temp = array($this->entity => $rootfordata."/produitlot/temp");
397 397
 
398 398
         // Module contrat
399
-        $this->contrat->multidir_output = array($this->entity => $rootfordata . "/contract");
400
-        $this->contrat->multidir_temp = array($this->entity => $rootfordata . "/contract/temp");
399
+        $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract");
400
+        $this->contrat->multidir_temp = array($this->entity => $rootfordata."/contract/temp");
401 401
         // For backward compatibility
402
-        $this->contrat->dir_output = $rootfordata . "/contract";
403
-        $this->contrat->dir_temp = $rootfordata . "/contract/temp";
402
+        $this->contrat->dir_output = $rootfordata."/contract";
403
+        $this->contrat->dir_temp = $rootfordata."/contract/temp";
404 404
 
405 405
         // Module bank
406
-        $this->bank->dir_output = $rootfordata . "/bank";
407
-        $this->bank->dir_temp = $rootfordata . "/bank/temp";
406
+        $this->bank->dir_output = $rootfordata."/bank";
407
+        $this->bank->dir_temp = $rootfordata."/bank/temp";
408 408
 
409 409
 
410 410
         // Set some default values
@@ -427,7 +427,7 @@  discard block
 block discarded – undo
427 427
         if (empty(Conf::$global->USER_PASSWORD_GENERATED))
428 428
             Conf::$global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator
429 429
         if (empty(Conf::$global->MAIN_UMASK))
430
-            Conf::$global->MAIN_UMASK = '0664';         // Default mask
430
+            Conf::$global->MAIN_UMASK = '0664'; // Default mask
431 431
 
432 432
 
433 433
 
@@ -466,7 +466,7 @@  discard block
 block discarded – undo
466 466
         $this->currency = Conf::$global->MAIN_MONNAIE;
467 467
 
468 468
         if (empty(Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY))
469
-            Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30;   // Less than 1 minutes to be sure
469
+            Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30; // Less than 1 minutes to be sure
470 470
 
471 471
 
472 472
 
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 
475 475
             // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...)
476 476
         if (empty(Conf::$global->ACCOUNTING_MODE))
477
-            Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES';  // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
477
+            Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES'; // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
478 478
 
479 479
 
480 480
 
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
             Conf::$global->MAIN_THEME = Conf::$global->MAIN_FORCETHEME;
505 505
         $this->theme = Conf::$global->MAIN_THEME;
506 506
         //$this->css  = "/theme/".$this->theme."/style.css.php";
507
-        $this->css = '?controller=theme/' . $this->theme . '&method=style.css';
507
+        $this->css = '?controller=theme/'.$this->theme.'&method=style.css';
508 508
 
509 509
         // conf->email_from = email pour envoi par dolibarr des mails automatiques
510 510
         $this->email_from = "[email protected]";
@@ -524,8 +524,8 @@  discard block
 block discarded – undo
524 524
             Conf::$global->MAIN_EMAIL_ADD_TRACK_ID = 1;
525 525
 
526 526
         // Format for date (used by default when not found or not searched in lang)
527
-        $this->format_date_short = "%d/%m/%Y";            // Format of day with PHP/C tags (strftime functions)
528
-        $this->format_date_short_java = "dd/MM/yyyy";     // Format of day with Java tags
527
+        $this->format_date_short = "%d/%m/%Y"; // Format of day with PHP/C tags (strftime functions)
528
+        $this->format_date_short_java = "dd/MM/yyyy"; // Format of day with Java tags
529 529
         $this->format_hour_short = "%H:%M";
530 530
         $this->format_hour_short_duration = "%H:%M";
531 531
         $this->format_date_text_short = "%d %b %Y";
@@ -549,9 +549,9 @@  discard block
 block discarded – undo
549 549
 
550 550
         // Default pdf option
551 551
         if (!isset(Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES))
552
-            Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1;    // use dash between lines
552
+            Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1; // use dash between lines
553 553
         if (!isset(Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
554
-            Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1;  // allow html content into free footer text
554
+            Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1; // allow html content into free footer text
555 555
 
556 556
 
557 557
 
@@ -566,7 +566,7 @@  discard block
 block discarded – undo
566 566
 
567 567
         // By default, we propagate contacts
568 568
         if (!isset(Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
569
-            Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*';  // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
569
+            Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*'; // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
570 570
 
571 571
 
572 572
 
@@ -589,7 +589,7 @@  discard block
 block discarded – undo
589 589
             Conf::$global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later.
590 590
         if (!empty($this->modules_parts['moduleforexternal'])) {  // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list
591 591
             foreach ($this->modules_parts['moduleforexternal'] as $key => $value)
592
-                Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= "," . $key;
592
+                Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= ",".$key;
593 593
         }
594 594
 
595 595
         // Enable select2
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
 
683 683
         // Save inconsistent option
684 684
         if (empty(Conf::$global->AGENDA_USE_EVENT_TYPE) && (!isset(Conf::$global->AGENDA_DEFAULT_FILTER_TYPE) || Conf::$global->AGENDA_DEFAULT_FILTER_TYPE == 'AC_NON_AUTO')) {
685
-            Conf::$global->AGENDA_DEFAULT_FILTER_TYPE = '0';    // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on.
685
+            Conf::$global->AGENDA_DEFAULT_FILTER_TYPE = '0'; // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on.
686 686
         }
687 687
 
688 688
         if (!isset(Conf::$global->MAIN_EXTRAFIELDS_IN_ONE_TD))
@@ -723,7 +723,7 @@  discard block
 block discarded – undo
723 723
                 $dir = dol_buildpath($reldir, 0);
724 724
                 $newdir = dol_osencode($dir);
725 725
                 if (is_dir($newdir)) {
726
-                    $file = $newdir . $handler . '.php';
726
+                    $file = $newdir.$handler.'.php';
727 727
                     if (file_exists($file)) {
728 728
                         $handler_files[] = $file;
729 729
                     }
@@ -731,7 +731,7 @@  discard block
 block discarded – undo
731 731
             }
732 732
 
733 733
             if (empty($handler_files)) {
734
-                throw new Exception('Missing log handler file ' . $handler . '.php');
734
+                throw new Exception('Missing log handler file '.$handler.'.php');
735 735
             }
736 736
 
737 737
             require_once $handler_files[0];
Please login to merge, or discard this patch.
Braces   +229 added lines, -151 removed lines patch added patch discarded remove patch
@@ -156,27 +156,32 @@  discard block
 block discarded – undo
156 156
                                 $this->modules_parts[$partname] = array();
157 157
                             }
158 158
                             $arrValue = json_decode($value, true);
159
-                            if (is_array($arrValue) && !empty($arrValue))
160
-                                $value = $arrValue;
161
-                            else if (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl')))
162
-                                $value = '/' . $modulename . '/core/' . $partname . '/';
163
-                            else if (in_array($partname, array('models', 'theme')))
164
-                                $value = '/' . $modulename . '/';
165
-                            else if (in_array($partname, array('sms')))
166
-                                $value = '/' . $modulename . '/';
167
-                            else if ($value == 1)
168
-                                $value = '/' . $modulename . '/core/modules/' . $partname . '/'; // ex: partname = societe
159
+                            if (is_array($arrValue) && !empty($arrValue)) {
160
+                                                            $value = $arrValue;
161
+                            } else if (in_array($partname, array('login', 'menus', 'substitutions', 'triggers', 'tpl'))) {
162
+                                                            $value = '/' . $modulename . '/core/' . $partname . '/';
163
+                            } else if (in_array($partname, array('models', 'theme'))) {
164
+                                                            $value = '/' . $modulename . '/';
165
+                            } else if (in_array($partname, array('sms'))) {
166
+                                                            $value = '/' . $modulename . '/';
167
+                            } else if ($value == 1) {
168
+                                                            $value = '/' . $modulename . '/core/modules/' . $partname . '/';
169
+                            }
170
+                            // ex: partname = societe
169 171
                             $this->modules_parts[$partname] = array_merge($this->modules_parts[$partname], array($modulename => $value)); // $value may be a string or an array
170 172
                         }
171 173
                         // If this is a module constant (must be at end)
172 174
                         elseif (preg_match('/^MAIN_MODULE_([0-9A-Z_]+)$/i', $key, $reg)) {
173 175
                             $modulename = strtolower($reg[1]);
174
-                            if ($modulename == 'propale')
175
-                                $modulename = 'propal';
176
-                            if ($modulename == 'supplierproposal')
177
-                                $modulename = 'supplier_proposal';
178
-                            if (!isset($this->$modulename) || !is_object($this->$modulename))
179
-                                $this->$modulename = new \stdClass();
176
+                            if ($modulename == 'propale') {
177
+                                                            $modulename = 'propal';
178
+                            }
179
+                            if ($modulename == 'supplierproposal') {
180
+                                                            $modulename = 'supplier_proposal';
181
+                            }
182
+                            if (!isset($this->$modulename) || !is_object($this->$modulename)) {
183
+                                                            $this->$modulename = new \stdClass();
184
+                            }
180 185
                             $this->$modulename->enabled = true;
181 186
                             $this->modules[] = $modulename;              // Add this module in list of enabled modules
182 187
                         }
@@ -224,46 +229,60 @@  discard block
 block discarded – undo
224 229
         }
225 230
 
226 231
         // Clean some variables
227
-        if (empty(Conf::$global->MAIN_MENU_STANDARD))
228
-            Conf::$global->MAIN_MENU_STANDARD = "eldy_menu.php";
229
-        if (empty(Conf::$global->MAIN_MENUFRONT_STANDARD))
230
-            Conf::$global->MAIN_MENUFRONT_STANDARD = "eldy_menu.php";
231
-        if (empty(Conf::$global->MAIN_MENU_SMARTPHONE))
232
-            Conf::$global->MAIN_MENU_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones
233
-        if (empty(Conf::$global->MAIN_MENUFRONT_SMARTPHONE))
234
-            Conf::$global->MAIN_MENUFRONT_SMARTPHONE = "eldy_menu.php"; // Use eldy by default because smartphone does not work on all phones
232
+        if (empty(Conf::$global->MAIN_MENU_STANDARD)) {
233
+                    Conf::$global->MAIN_MENU_STANDARD = "eldy_menu.php";
234
+        }
235
+        if (empty(Conf::$global->MAIN_MENUFRONT_STANDARD)) {
236
+                    Conf::$global->MAIN_MENUFRONT_STANDARD = "eldy_menu.php";
237
+        }
238
+        if (empty(Conf::$global->MAIN_MENU_SMARTPHONE)) {
239
+                    Conf::$global->MAIN_MENU_SMARTPHONE = "eldy_menu.php";
240
+        }
241
+        // Use eldy by default because smartphone does not work on all phones
242
+        if (empty(Conf::$global->MAIN_MENUFRONT_SMARTPHONE)) {
243
+                    Conf::$global->MAIN_MENUFRONT_SMARTPHONE = "eldy_menu.php";
244
+        }
245
+        // Use eldy by default because smartphone does not work on all phones
235 246
 
236 247
 
237 248
 
238 249
 
239 250
             // Clean var use vat for company
240
-        if (!isset(Conf::$global->FACTURE_TVAOPTION))
241
-            Conf::$global->FACTURE_TVAOPTION = 1;
242
-        else if (!empty(Conf::$global->FACTURE_TVAOPTION) && !is_numeric(Conf::$global->FACTURE_TVAOPTION)) {
251
+        if (!isset(Conf::$global->FACTURE_TVAOPTION)) {
252
+                    Conf::$global->FACTURE_TVAOPTION = 1;
253
+        } else if (!empty(Conf::$global->FACTURE_TVAOPTION) && !is_numeric(Conf::$global->FACTURE_TVAOPTION)) {
243 254
             // Old value of option, we clean to use new value (0 or 1)
244
-            if (Conf::$global->FACTURE_TVAOPTION != "franchise")
245
-                Conf::$global->FACTURE_TVAOPTION = 1;
246
-            else
247
-                Conf::$global->FACTURE_TVAOPTION = 0;
255
+            if (Conf::$global->FACTURE_TVAOPTION != "franchise") {
256
+                            Conf::$global->FACTURE_TVAOPTION = 1;
257
+            } else {
258
+                            Conf::$global->FACTURE_TVAOPTION = 0;
259
+            }
248 260
         }
249 261
 
250 262
         // Variable globales LDAP
251
-        if (empty(Conf::$global->LDAP_FIELD_FULLNAME))
252
-            Conf::$global->LDAP_FIELD_FULLNAME = '';
253
-        if (!isset(Conf::$global->LDAP_KEY_USERS))
254
-            Conf::$global->LDAP_KEY_USERS = Conf::$global->LDAP_FIELD_FULLNAME;
255
-        if (!isset(Conf::$global->LDAP_KEY_GROUPS))
256
-            Conf::$global->LDAP_KEY_GROUPS = Conf::$global->LDAP_FIELD_FULLNAME;
257
-        if (!isset(Conf::$global->LDAP_KEY_CONTACTS))
258
-            Conf::$global->LDAP_KEY_CONTACTS = Conf::$global->LDAP_FIELD_FULLNAME;
259
-        if (!isset(Conf::$global->LDAP_KEY_MEMBERS))
260
-            Conf::$global->LDAP_KEY_MEMBERS = Conf::$global->LDAP_FIELD_FULLNAME;
261
-        if (!isset(Conf::$global->LDAP_KEY_MEMBERS_TYPES))
262
-            Conf::$global->LDAP_KEY_MEMBERS_TYPES = Conf::$global->LDAP_FIELD_FULLNAME;
263
+        if (empty(Conf::$global->LDAP_FIELD_FULLNAME)) {
264
+                    Conf::$global->LDAP_FIELD_FULLNAME = '';
265
+        }
266
+        if (!isset(Conf::$global->LDAP_KEY_USERS)) {
267
+                    Conf::$global->LDAP_KEY_USERS = Conf::$global->LDAP_FIELD_FULLNAME;
268
+        }
269
+        if (!isset(Conf::$global->LDAP_KEY_GROUPS)) {
270
+                    Conf::$global->LDAP_KEY_GROUPS = Conf::$global->LDAP_FIELD_FULLNAME;
271
+        }
272
+        if (!isset(Conf::$global->LDAP_KEY_CONTACTS)) {
273
+                    Conf::$global->LDAP_KEY_CONTACTS = Conf::$global->LDAP_FIELD_FULLNAME;
274
+        }
275
+        if (!isset(Conf::$global->LDAP_KEY_MEMBERS)) {
276
+                    Conf::$global->LDAP_KEY_MEMBERS = Conf::$global->LDAP_FIELD_FULLNAME;
277
+        }
278
+        if (!isset(Conf::$global->LDAP_KEY_MEMBERS_TYPES)) {
279
+                    Conf::$global->LDAP_KEY_MEMBERS_TYPES = Conf::$global->LDAP_FIELD_FULLNAME;
280
+        }
263 281
 
264 282
         // Load translation object with current language
265
-        if (empty(Conf::$global->MAIN_LANG_DEFAULT))
266
-            Conf::$global->MAIN_LANG_DEFAULT = "en_US";
283
+        if (empty(Conf::$global->MAIN_LANG_DEFAULT)) {
284
+                    Conf::$global->MAIN_LANG_DEFAULT = "en_US";
285
+        }
267 286
 
268 287
         $rootfordata = DOL_DATA_ROOT;
269 288
         $rootforuser = DOL_DATA_ROOT;
@@ -413,21 +432,29 @@  discard block
 block discarded – undo
413 432
         Conf::$global->MAIN_MAIL_USE_MULTI_PART = 1;
414 433
 
415 434
         // societe
416
-        if (empty(Conf::$global->SOCIETE_CODECLIENT_ADDON))
417
-            Conf::$global->SOCIETE_CODECLIENT_ADDON = "mod_codeclient_leopard";
418
-        if (empty(Conf::$global->SOCIETE_CODECOMPTA_ADDON))
419
-            Conf::$global->SOCIETE_CODECOMPTA_ADDON = "mod_codecompta_panicum";
420
-
421
-        if (empty(Conf::$global->CHEQUERECEIPTS_ADDON))
422
-            Conf::$global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint';
423
-        if (empty($conf->global->TICKETSUP_ADDON))
424
-            Conf::$global->TICKETSUP_ADDON = 'mod_ticket_simple';
435
+        if (empty(Conf::$global->SOCIETE_CODECLIENT_ADDON)) {
436
+                    Conf::$global->SOCIETE_CODECLIENT_ADDON = "mod_codeclient_leopard";
437
+        }
438
+        if (empty(Conf::$global->SOCIETE_CODECOMPTA_ADDON)) {
439
+                    Conf::$global->SOCIETE_CODECOMPTA_ADDON = "mod_codecompta_panicum";
440
+        }
441
+
442
+        if (empty(Conf::$global->CHEQUERECEIPTS_ADDON)) {
443
+                    Conf::$global->CHEQUERECEIPTS_ADDON = 'mod_chequereceipt_mint';
444
+        }
445
+        if (empty($conf->global->TICKETSUP_ADDON)) {
446
+                    Conf::$global->TICKETSUP_ADDON = 'mod_ticket_simple';
447
+        }
425 448
 
426 449
         // Security
427
-        if (empty(Conf::$global->USER_PASSWORD_GENERATED))
428
-            Conf::$global->USER_PASSWORD_GENERATED = 'standard'; // Default password generator
429
-        if (empty(Conf::$global->MAIN_UMASK))
430
-            Conf::$global->MAIN_UMASK = '0664';         // Default mask
450
+        if (empty(Conf::$global->USER_PASSWORD_GENERATED)) {
451
+                    Conf::$global->USER_PASSWORD_GENERATED = 'standard';
452
+        }
453
+        // Default password generator
454
+        if (empty(Conf::$global->MAIN_UMASK)) {
455
+                    Conf::$global->MAIN_UMASK = '0664';
456
+        }
457
+        // Default mask
431 458
 
432 459
 
433 460
 
@@ -435,8 +462,9 @@  discard block
 block discarded – undo
435 462
 
436 463
             // conf->use_javascript_ajax
437 464
         $this->use_javascript_ajax = 1;
438
-        if (isset(Conf::$global->MAIN_DISABLE_JAVASCRIPT))
439
-            $this->use_javascript_ajax = !Conf::$global->MAIN_DISABLE_JAVASCRIPT;
465
+        if (isset(Conf::$global->MAIN_DISABLE_JAVASCRIPT)) {
466
+                    $this->use_javascript_ajax = !Conf::$global->MAIN_DISABLE_JAVASCRIPT;
467
+        }
440 468
         // If no javascript_ajax, Ajax features are disabled.
441 469
         if (empty($this->use_javascript_ajax)) {
442 470
             unset(Conf::$global->PRODUIT_USE_SEARCH_TO_SELECT);
@@ -452,29 +480,34 @@  discard block
 block discarded – undo
452 480
             Conf::$global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE = 0;
453 481
             Conf::$global->STOCK_CALCULATE_ON_SUPPLIER_BILL = 0;
454 482
             Conf::$global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER = 0;
455
-            if (empty($this->reception->enabled))
456
-                Conf::$global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER = 1;
457
-            else {
483
+            if (empty($this->reception->enabled)) {
484
+                            Conf::$global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER = 1;
485
+            } else {
458 486
                 Conf::$global->STOCK_CALCULATE_ON_RECEPTION = 1;
459 487
                 Conf::$global->STOCK_CALCULATE_ON_RECEPTION_CLOSE = 0;
460 488
             }
461 489
         }
462 490
 
463 491
         // conf->currency
464
-        if (empty(Conf::$global->MAIN_MONNAIE))
465
-            Conf::$global->MAIN_MONNAIE = 'EUR';
492
+        if (empty(Conf::$global->MAIN_MONNAIE)) {
493
+                    Conf::$global->MAIN_MONNAIE = 'EUR';
494
+        }
466 495
         $this->currency = Conf::$global->MAIN_MONNAIE;
467 496
 
468
-        if (empty(Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY))
469
-            Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30;   // Less than 1 minutes to be sure
497
+        if (empty(Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY)) {
498
+                    Conf::$global->MAIN_BROWSER_NOTIFICATION_FREQUENCY = 30;
499
+        }
500
+        // Less than 1 minutes to be sure
470 501
 
471 502
 
472 503
 
473 504
 
474 505
 
475 506
             // conf->global->ACCOUNTING_MODE = Option des modules Comptabilites (simple ou expert). Defini le mode de calcul des etats comptables (CA,...)
476
-        if (empty(Conf::$global->ACCOUNTING_MODE))
477
-            Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES';  // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
507
+        if (empty(Conf::$global->ACCOUNTING_MODE)) {
508
+                    Conf::$global->ACCOUNTING_MODE = 'RECETTES-DEPENSES';
509
+        }
510
+        // By default. Can be 'RECETTES-DEPENSES' ou 'CREANCES-DETTES'
478 511
 
479 512
 
480 513
 
@@ -484,44 +517,53 @@  discard block
 block discarded – undo
484 517
         Conf::$global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS = 1;
485 518
 
486 519
         // MAIN_HTML_TITLE
487
-        if (!isset(Conf::$global->MAIN_HTML_TITLE))
488
-            Conf::$global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly';
520
+        if (!isset(Conf::$global->MAIN_HTML_TITLE)) {
521
+                    Conf::$global->MAIN_HTML_TITLE = 'noapp,thirdpartynameonly,contactnameonly,projectnameonly';
522
+        }
489 523
 
490 524
         // conf->liste_limit = constante de taille maximale des listes
491
-        if (empty(Conf::$global->MAIN_SIZE_LISTE_LIMIT))
492
-            Conf::$global->MAIN_SIZE_LISTE_LIMIT = 25;
525
+        if (empty(Conf::$global->MAIN_SIZE_LISTE_LIMIT)) {
526
+                    Conf::$global->MAIN_SIZE_LISTE_LIMIT = 25;
527
+        }
493 528
         $this->liste_limit = Conf::$global->MAIN_SIZE_LISTE_LIMIT;
494 529
 
495 530
         // conf->product->limit_size = constante de taille maximale des select de produit
496
-        if (!isset(Conf::$global->PRODUIT_LIMIT_SIZE))
497
-            Conf::$global->PRODUIT_LIMIT_SIZE = 1000;
531
+        if (!isset(Conf::$global->PRODUIT_LIMIT_SIZE)) {
532
+                    Conf::$global->PRODUIT_LIMIT_SIZE = 1000;
533
+        }
498 534
         $this->product->limit_size = Conf::$global->PRODUIT_LIMIT_SIZE;
499 535
 
500 536
         // conf->theme et $this->css
501
-        if (empty(Conf::$global->MAIN_THEME))
502
-            Conf::$global->MAIN_THEME = "eldy";
503
-        if (!empty(Conf::$global->MAIN_FORCETHEME))
504
-            Conf::$global->MAIN_THEME = Conf::$global->MAIN_FORCETHEME;
537
+        if (empty(Conf::$global->MAIN_THEME)) {
538
+                    Conf::$global->MAIN_THEME = "eldy";
539
+        }
540
+        if (!empty(Conf::$global->MAIN_FORCETHEME)) {
541
+                    Conf::$global->MAIN_THEME = Conf::$global->MAIN_FORCETHEME;
542
+        }
505 543
         $this->theme = Conf::$global->MAIN_THEME;
506 544
         //$this->css  = "/theme/".$this->theme."/style.css.php";
507 545
         $this->css = '?controller=theme/' . $this->theme . '&method=style.css';
508 546
 
509 547
         // conf->email_from = email pour envoi par dolibarr des mails automatiques
510 548
         $this->email_from = "[email protected]";
511
-        if (!empty(Conf::$global->MAIN_MAIL_EMAIL_FROM))
512
-            $this->email_from = Conf::$global->MAIN_MAIL_EMAIL_FROM;
549
+        if (!empty(Conf::$global->MAIN_MAIL_EMAIL_FROM)) {
550
+                    $this->email_from = Conf::$global->MAIN_MAIL_EMAIL_FROM;
551
+        }
513 552
 
514 553
         // conf->notification->email_from = email pour envoi par Dolibarr des notifications
515 554
         $this->notification->email_from = $this->email_from;
516
-        if (!empty(Conf::$global->NOTIFICATION_EMAIL_FROM))
517
-            $this->notification->email_from = Conf::$global->NOTIFICATION_EMAIL_FROM;
555
+        if (!empty(Conf::$global->NOTIFICATION_EMAIL_FROM)) {
556
+                    $this->notification->email_from = Conf::$global->NOTIFICATION_EMAIL_FROM;
557
+        }
518 558
 
519 559
         // conf->mailing->email_from = email pour envoi par Dolibarr des mailings
520 560
         $this->mailing->email_from = $this->email_from;
521
-        if (!empty(Conf::$global->MAILING_EMAIL_FROM))
522
-            $this->mailing->email_from = Conf::$global->MAILING_EMAIL_FROM;
523
-        if (!isset(Conf::$global->MAIN_EMAIL_ADD_TRACK_ID))
524
-            Conf::$global->MAIN_EMAIL_ADD_TRACK_ID = 1;
561
+        if (!empty(Conf::$global->MAILING_EMAIL_FROM)) {
562
+                    $this->mailing->email_from = Conf::$global->MAILING_EMAIL_FROM;
563
+        }
564
+        if (!isset(Conf::$global->MAIN_EMAIL_ADD_TRACK_ID)) {
565
+                    Conf::$global->MAIN_EMAIL_ADD_TRACK_ID = 1;
566
+        }
525 567
 
526 568
         // Format for date (used by default when not found or not searched in lang)
527 569
         $this->format_date_short = "%d/%m/%Y";            // Format of day with PHP/C tags (strftime functions)
@@ -536,81 +578,105 @@  discard block
 block discarded – undo
536 578
         $this->format_date_hour_text = "%d %B %Y %H:%M";
537 579
 
538 580
         // Duration of workday
539
-        if (!isset(Conf::$global->MAIN_DURATION_OF_WORKDAY))
540
-            Conf::$global->MAIN_DURATION_OF_WORKDAY = 86400;
581
+        if (!isset(Conf::$global->MAIN_DURATION_OF_WORKDAY)) {
582
+                    Conf::$global->MAIN_DURATION_OF_WORKDAY = 86400;
583
+        }
541 584
 
542 585
         // Limites decimales si non definie (peuvent etre egale a 0)
543
-        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_UNIT))
544
-            Conf::$global->MAIN_MAX_DECIMALS_UNIT = 5;
545
-        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_TOT))
546
-            Conf::$global->MAIN_MAX_DECIMALS_TOT = 2;
547
-        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_SHOWN))
548
-            Conf::$global->MAIN_MAX_DECIMALS_SHOWN = 8;
586
+        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_UNIT)) {
587
+                    Conf::$global->MAIN_MAX_DECIMALS_UNIT = 5;
588
+        }
589
+        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_TOT)) {
590
+                    Conf::$global->MAIN_MAX_DECIMALS_TOT = 2;
591
+        }
592
+        if (!isset(Conf::$global->MAIN_MAX_DECIMALS_SHOWN)) {
593
+                    Conf::$global->MAIN_MAX_DECIMALS_SHOWN = 8;
594
+        }
549 595
 
550 596
         // Default pdf option
551
-        if (!isset(Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES))
552
-            Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1;    // use dash between lines
553
-        if (!isset(Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT))
554
-            Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1;  // allow html content into free footer text
597
+        if (!isset(Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES)) {
598
+                    Conf::$global->MAIN_PDF_DASH_BETWEEN_LINES = 1;
599
+        }
600
+        // use dash between lines
601
+        if (!isset(Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) {
602
+                    Conf::$global->PDF_ALLOW_HTML_FOR_FREE_TEXT = 1;
603
+        }
604
+        // allow html content into free footer text
555 605
 
556 606
 
557 607
 
558 608
 
559 609
 
560 610
             // Set default value to MAIN_SHOW_LOGO
561
-        if (!isset(Conf::$global->MAIN_SHOW_LOGO))
562
-            Conf::$global->MAIN_SHOW_LOGO = 1;
611
+        if (!isset(Conf::$global->MAIN_SHOW_LOGO)) {
612
+                    Conf::$global->MAIN_SHOW_LOGO = 1;
613
+        }
563 614
 
564 615
         // Default max file size for upload
565 616
         $this->maxfilesize = (empty(Conf::$global->MAIN_UPLOAD_DOC) ? 0 : (int) Conf::$global->MAIN_UPLOAD_DOC * 1024);
566 617
 
567 618
         // By default, we propagate contacts
568
-        if (!isset(Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN))
569
-            Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*';  // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
619
+        if (!isset(Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) {
620
+                    Conf::$global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN = '*';
621
+        }
622
+        // Can be also '*' or '^(BILLING|SHIPPING|CUSTOMER|.*)$' (regex not yet implemented)
570 623
 
571 624
 
572 625
 
573 626
 
574 627
 
575 628
             // By default, we do not use the zip town table but the table of third parties
576
-        if (!isset(Conf::$global->MAIN_USE_ZIPTOWN_DICTIONNARY))
577
-            Conf::$global->MAIN_USE_ZIPTOWN_DICTIONNARY = 0;
629
+        if (!isset(Conf::$global->MAIN_USE_ZIPTOWN_DICTIONNARY)) {
630
+                    Conf::$global->MAIN_USE_ZIPTOWN_DICTIONNARY = 0;
631
+        }
578 632
 
579 633
         // By default, we open card if one found
580
-        if (!isset(Conf::$global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE))
581
-            Conf::$global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE = 1;
634
+        if (!isset(Conf::$global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE)) {
635
+                    Conf::$global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE = 1;
636
+        }
582 637
 
583 638
         // By default, we show state code in combo list
584
-        if (!isset(Conf::$global->MAIN_SHOW_STATE_CODE))
585
-            Conf::$global->MAIN_SHOW_STATE_CODE = 1;
639
+        if (!isset(Conf::$global->MAIN_SHOW_STATE_CODE)) {
640
+                    Conf::$global->MAIN_SHOW_STATE_CODE = 1;
641
+        }
586 642
 
587 643
         // Define list of limited modules (value must be key found for "name" property of module, so for example 'supplierproposal' for Module "Supplier Proposal"
588
-        if (!isset(Conf::$global->MAIN_MODULES_FOR_EXTERNAL))
589
-            Conf::$global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog'; // '' means 'all'. Note that contact is added here as it should be a module later.
644
+        if (!isset(Conf::$global->MAIN_MODULES_FOR_EXTERNAL)) {
645
+                    Conf::$global->MAIN_MODULES_FOR_EXTERNAL = 'user,societe,propal,commande,facture,categorie,supplierproposal,fournisseur,contact,projet,contrat,ficheinter,expedition,agenda,resource,adherent,blockedlog';
646
+        }
647
+        // '' means 'all'. Note that contact is added here as it should be a module later.
590 648
         if (!empty($this->modules_parts['moduleforexternal'])) {  // Module part to include an external module into the MAIN_MODULES_FOR_EXTERNAL list
591
-            foreach ($this->modules_parts['moduleforexternal'] as $key => $value)
592
-                Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= "," . $key;
649
+            foreach ($this->modules_parts['moduleforexternal'] as $key => $value) {
650
+                            Conf::$global->MAIN_MODULES_FOR_EXTERNAL .= "," . $key;
651
+            }
593 652
         }
594 653
 
595 654
         // Enable select2
596
-        if (empty(Conf::$global->MAIN_USE_JQUERY_MULTISELECT) || Conf::$global->MAIN_USE_JQUERY_MULTISELECT == '1')
597
-            Conf::$global->MAIN_USE_JQUERY_MULTISELECT = 'select2';
655
+        if (empty(Conf::$global->MAIN_USE_JQUERY_MULTISELECT) || Conf::$global->MAIN_USE_JQUERY_MULTISELECT == '1') {
656
+                    Conf::$global->MAIN_USE_JQUERY_MULTISELECT = 'select2';
657
+        }
598 658
 
599 659
         // Timeouts
600
-        if (empty(Conf::$global->MAIN_USE_CONNECT_TIMEOUT))
601
-            Conf::$global->MAIN_USE_CONNECT_TIMEOUT = 10;
602
-        if (empty(Conf::$global->MAIN_USE_RESPONSE_TIMEOUT))
603
-            Conf::$global->MAIN_USE_RESPONSE_TIMEOUT = 30;
660
+        if (empty(Conf::$global->MAIN_USE_CONNECT_TIMEOUT)) {
661
+                    Conf::$global->MAIN_USE_CONNECT_TIMEOUT = 10;
662
+        }
663
+        if (empty(Conf::$global->MAIN_USE_RESPONSE_TIMEOUT)) {
664
+                    Conf::$global->MAIN_USE_RESPONSE_TIMEOUT = 30;
665
+        }
604 666
 
605 667
         // Set default variable to calculate VAT as if option tax_mode was 0 (standard)
606
-        if (empty(Conf::$global->TAX_MODE_SELL_PRODUCT))
607
-            Conf::$global->TAX_MODE_SELL_PRODUCT = 'invoice';
608
-        if (empty(Conf::$global->TAX_MODE_BUY_PRODUCT))
609
-            Conf::$global->TAX_MODE_BUY_PRODUCT = 'invoice';
610
-        if (empty(Conf::$global->TAX_MODE_SELL_SERVICE))
611
-            Conf::$global->TAX_MODE_SELL_SERVICE = 'payment';
612
-        if (empty(Conf::$global->TAX_MODE_BUY_SERVICE))
613
-            Conf::$global->TAX_MODE_BUY_SERVICE = 'payment';
668
+        if (empty(Conf::$global->TAX_MODE_SELL_PRODUCT)) {
669
+                    Conf::$global->TAX_MODE_SELL_PRODUCT = 'invoice';
670
+        }
671
+        if (empty(Conf::$global->TAX_MODE_BUY_PRODUCT)) {
672
+                    Conf::$global->TAX_MODE_BUY_PRODUCT = 'invoice';
673
+        }
674
+        if (empty(Conf::$global->TAX_MODE_SELL_SERVICE)) {
675
+                    Conf::$global->TAX_MODE_SELL_SERVICE = 'payment';
676
+        }
677
+        if (empty(Conf::$global->TAX_MODE_BUY_SERVICE)) {
678
+                    Conf::$global->TAX_MODE_BUY_SERVICE = 'payment';
679
+        }
614 680
 
615 681
         // Delay before warnings
616 682
         // Avoid strict errors. TODO: Replace xxx->warning_delay with a property ->warning_delay_xxx
@@ -618,8 +684,9 @@  discard block
 block discarded – undo
618 684
             $this->adherent->subscription = new \stdClass();
619 685
             $this->adherent->subscription->warning_delay = (isset(Conf::$global->MAIN_DELAY_MEMBERS) ? Conf::$global->MAIN_DELAY_MEMBERS : 0) * 24 * 60 * 60;
620 686
         }
621
-        if (isset($this->agenda))
622
-            $this->agenda->warning_delay = (isset(Conf::$global->MAIN_DELAY_ACTIONS_TODO) ? Conf::$global->MAIN_DELAY_ACTIONS_TODO : 7) * 24 * 60 * 60;
687
+        if (isset($this->agenda)) {
688
+                    $this->agenda->warning_delay = (isset(Conf::$global->MAIN_DELAY_ACTIONS_TODO) ? Conf::$global->MAIN_DELAY_ACTIONS_TODO : 7) * 24 * 60 * 60;
689
+        }
623 690
         if (isset($this->projet)) {
624 691
             $this->projet->warning_delay = (isset(Conf::$global->MAIN_DELAY_PROJECT_TO_CLOSE) ? Conf::$global->MAIN_DELAY_PROJECT_TO_CLOSE : 7) * 24 * 60 * 60;
625 692
             $this->projet->task = new StdClass();
@@ -669,44 +736,55 @@  discard block
 block discarded – undo
669 736
         }
670 737
 
671 738
         // For modules that want to disable top or left menu
672
-        if (!empty(Conf::$global->MAIN_HIDE_TOP_MENU))
673
-            $this->dol_hide_topmenu = Conf::$global->MAIN_HIDE_TOP_MENU;
674
-        if (!empty(Conf::$global->MAIN_HIDE_LEFT_MENU))
675
-            $this->dol_hide_leftmenu = Conf::$global->MAIN_HIDE_LEFT_MENU;
739
+        if (!empty(Conf::$global->MAIN_HIDE_TOP_MENU)) {
740
+                    $this->dol_hide_topmenu = Conf::$global->MAIN_HIDE_TOP_MENU;
741
+        }
742
+        if (!empty(Conf::$global->MAIN_HIDE_LEFT_MENU)) {
743
+                    $this->dol_hide_leftmenu = Conf::$global->MAIN_HIDE_LEFT_MENU;
744
+        }
676 745
 
677
-        if (empty(Conf::$global->MAIN_SIZE_SHORTLIST_LIMIT))
678
-            Conf::$global->MAIN_SIZE_SHORTLIST_LIMIT = 3;
746
+        if (empty(Conf::$global->MAIN_SIZE_SHORTLIST_LIMIT)) {
747
+                    Conf::$global->MAIN_SIZE_SHORTLIST_LIMIT = 3;
748
+        }
679 749
 
680
-        if (!isset(Conf::$global->THEME_HIDE_BORDER_ON_INPUT))
681
-            Conf::$global->THEME_HIDE_BORDER_ON_INPUT = 0;
750
+        if (!isset(Conf::$global->THEME_HIDE_BORDER_ON_INPUT)) {
751
+                    Conf::$global->THEME_HIDE_BORDER_ON_INPUT = 0;
752
+        }
682 753
 
683 754
         // Save inconsistent option
684 755
         if (empty(Conf::$global->AGENDA_USE_EVENT_TYPE) && (!isset(Conf::$global->AGENDA_DEFAULT_FILTER_TYPE) || Conf::$global->AGENDA_DEFAULT_FILTER_TYPE == 'AC_NON_AUTO')) {
685 756
             Conf::$global->AGENDA_DEFAULT_FILTER_TYPE = '0';    // 'AC_NON_AUTO' does not exists when AGENDA_DEFAULT_FILTER_TYPE is not on.
686 757
         }
687 758
 
688
-        if (!isset(Conf::$global->MAIN_EXTRAFIELDS_IN_ONE_TD))
689
-            Conf::$global->MAIN_EXTRAFIELDS_IN_ONE_TD = 1;
759
+        if (!isset(Conf::$global->MAIN_EXTRAFIELDS_IN_ONE_TD)) {
760
+                    Conf::$global->MAIN_EXTRAFIELDS_IN_ONE_TD = 1;
761
+        }
690 762
 
691 763
         Conf::$global->MAIN_MODULE_DOLISTORE_API_SRV = 'https://www.dolistore.com';
692 764
         Conf::$global->MAIN_MODULE_DOLISTORE_API_KEY = 'dolistorecatalogpublickey1234567';
693 765
 
694 766
         // For backward compatibility
695
-        if (isset($this->product))
696
-            $this->produit = $this->product;
697
-        if (isset($this->facture))
698
-            $this->invoice = $this->facture;
699
-        if (isset($this->commande))
700
-            $this->order = $this->commande;
701
-        if (isset($this->contrat))
702
-            $this->contract = $this->contrat;
703
-        if (isset($this->categorie))
704
-            $this->category = $this->categorie;
767
+        if (isset($this->product)) {
768
+                    $this->produit = $this->product;
769
+        }
770
+        if (isset($this->facture)) {
771
+                    $this->invoice = $this->facture;
772
+        }
773
+        if (isset($this->commande)) {
774
+                    $this->order = $this->commande;
775
+        }
776
+        if (isset($this->contrat)) {
777
+                    $this->contract = $this->contrat;
778
+        }
779
+        if (isset($this->categorie)) {
780
+                    $this->category = $this->categorie;
781
+        }
705 782
 
706 783
         // Object $mc
707 784
         if (!defined('NOREQUIREMC') && !empty($this->multicompany->enabled)) {
708
-            if (is_object($mc))
709
-                $mc->setValues($this);
785
+            if (is_object($mc)) {
786
+                            $mc->setValues($this);
787
+            }
710 788
         }
711 789
 
712 790
         // We init log handlers
Please login to merge, or discard this patch.
Base/Menu.php 3 patches
Indentation   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -33,11 +33,11 @@  discard block
 block discarded – undo
33 33
     var $liste;
34 34
 
35 35
     /**
36
-	 *	Constructor
36
+     *	Constructor
37 37
      */
38 38
     function __construct()
39 39
     {
40
-      	$this->liste = array();
40
+            $this->liste = array();
41 41
     }
42 42
 
43 43
     /**
@@ -69,7 +69,7 @@  discard block
 block discarded – undo
69 69
      */
70 70
     function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
71 71
     {
72
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
72
+        $this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
73 73
     }
74 74
 
75 75
     /**
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -67,9 +67,9 @@  discard block
 block discarded – undo
67 67
      * @param	string	$prefix		Prefix to title (image or picto)
68 68
      * @return	void
69 69
      */
70
-    function add($url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
70
+    function add($url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
71 71
     {
72
-    	$this->liste[]=array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
72
+    	$this->liste[] = array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix);
73 73
     }
74 74
 
75 75
     /**
@@ -90,12 +90,12 @@  discard block
 block discarded – undo
90 90
      * @param	string	$prefix		Prefix to title (image or picto)
91 91
      * @return	void
92 92
      */
93
-    function insert($idafter, $url, $titre, $level=0, $enabled=1, $target='',$mainmenu='',$leftmenu='',$position=0, $id='', $idsel='', $classname='', $prefix='')
93
+    function insert($idafter, $url, $titre, $level = 0, $enabled = 1, $target = '', $mainmenu = '', $leftmenu = '', $position = 0, $id = '', $idsel = '', $classname = '', $prefix = '')
94 94
     {
95
-        $array_start = array_slice($this->liste,0,($idafter+1));
96
-        $array_new   = array(0=>array('url'=>$url,'titre'=>$titre,'level'=>$level,'enabled'=>$enabled,'target'=>$target,'mainmenu'=>$mainmenu,'leftmenu'=>$leftmenu,'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
97
-        $array_end   = array_slice($this->liste,($idafter+1));
98
-        $this->liste=array_merge($array_start,$array_new,$array_end);
95
+        $array_start = array_slice($this->liste, 0, ($idafter + 1));
96
+        $array_new   = array(0=>array('url'=>$url, 'titre'=>$titre, 'level'=>$level, 'enabled'=>$enabled, 'target'=>$target, 'mainmenu'=>$mainmenu, 'leftmenu'=>$leftmenu, 'position'=>$position, 'id'=>$id, 'idsel'=>$idsel, 'classname'=>$classname, 'prefix'=>$prefix));
97
+        $array_end   = array_slice($this->liste, ($idafter + 1));
98
+        $this->liste = array_merge($array_start, $array_new, $array_end);
99 99
     }
100 100
 
101 101
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -119,10 +119,10 @@  discard block
 block discarded – undo
119 119
      */
120 120
     function getNbOfVisibleMenuEntries()
121 121
     {
122
-        $nb=0;
123
-        foreach($this->liste as $val)
122
+        $nb = 0;
123
+        foreach ($this->liste as $val)
124 124
         {
125
-            if (! empty($val['enabled'])) $nb++;
125
+            if (!empty($val['enabled'])) $nb++;
126 126
         }
127 127
         return $nb;
128 128
     }
Please login to merge, or discard this patch.
Braces   +3 added lines, -1 removed lines patch added patch discarded remove patch
@@ -122,7 +122,9 @@
 block discarded – undo
122 122
         $nb=0;
123 123
         foreach($this->liste as $val)
124 124
         {
125
-            if (! empty($val['enabled'])) $nb++;
125
+            if (! empty($val['enabled'])) {
126
+                $nb++;
127
+            }
126 128
         }
127 129
         return $nb;
128 130
     }
Please login to merge, or discard this patch.
Base/CommonObject.php 3 patches
Indentation   +7078 added lines, -7078 removed lines patch added patch discarded remove patch
@@ -21,7382 +21,7382 @@
 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;
30
+     * @var string 		Error string
31
+     * @see             errors
32
+     */
33
+    public $error;
202 34
 
203
-	/**
204
-	 * @var int
205
-	 * @see getFullAddress(), state
206
-	 */
207
-	public $state_id;
35
+    /**
36
+     * @var string[]	Array of error strings
37
+     */
38
+    public $errors=array();
208 39
 
209
-	/**
210
-	 * @var string
211
-	 * @see getFullAddress(), state
212
-	 */
213
-    public $state_code;
40
+    /**
41
+     * @var string ID to identify managed object
42
+     */
43
+    public $element;
214 44
 
215 45
     /**
216
-	 * @var string
217
-	 * @see getFullAddress(), region
218
-	 */
219
-	public $region;
46
+     * @var string Name of table without prefix where object is stored
47
+     */
48
+    public $table_element;
220 49
 
221
-	/**
222
-	 * @var string
223
-	 * @see getFullAddress(), region
224
-	 */
225
-    public $region_code;
50
+    /**
51
+     * @var int    Name of subtable line
52
+     */
53
+    public $table_element_line='';
226 54
 
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) $sql.= " AND entity = ".$conf->entity;
413
-
414
-		dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
415
-		$resql = $db->query($sql);
416
-		if ($resql)
417
-		{
418
-			$num=$db->num_rows($resql);
419
-			if ($num > 0) return 1;
420
-			else return 0;
421
-		}
422
-		return -1;
423
-	}
424
-
425
-	/**
426
-	 * Method to output saved errors
427
-	 *
428
-	 * @return	string		String with errors
429
-	 */
430
-	function errorsToString()
431
-	{
432
-		return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
433
-	}
434
-
435
-	/**
436
-	 *	Return full name (civility+' '+name+' '+lastname)
437
-	 *
438
-	 *	@param	Translate	$langs			Language object for translation of civility (used only if option is 1)
439
-	 *	@param	int			$option			0=No option, 1=Add civility
440
-	 * 	@param	int			$nameorder		-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
441
-	 * 	@param	int			$maxlen			Maximum length
442
-	 * 	@return	string						String with full name
443
-	 */
444
-	function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
445
-	{
446
-		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
447
-		$lastname=$this->lastname;
448
-		$firstname=$this->firstname;
449
-		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:'')))));
450
-
451
-		$ret='';
452
-		if ($option && $this->civility_id)
453
-		{
454
-			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
455
-			else $ret.=$this->civility_id.' ';
456
-		}
457
-
458
-		$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;
459 59
 
460
-        return DolUtils::dol_trunc($ret, $maxlen);
461
-    }
60
+    /**
61
+     * @var mixed		Contains data to manage extrafields
62
+     */
63
+    public $array_options=array();
462 64
 
463
-	/**
464
-	 * 	Return full address of contact
465
-	 *
466
-	 * 	@param		int			$withcountry		1=Add country into address string
467
-	 *  @param		string		$sep				Separator to use to build string
468
-	 *  @param		int		    $withregion			1=Add region into address string
469
-	 *	@return		string							Full address string
470
-	 */
471
-	function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
472
-	{
473
-		if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
474
-		{
475
-			require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
476
-			$tmparray=getCountry($this->country_id,'all');
477
-			$this->country_code=$tmparray['code'];
478
-			$this->country     =$tmparray['label'];
479
-		}
65
+    /**
66
+     * @var int[][]		Array of linked objects ids. Loaded by ->fetchObjectLinked
67
+     */
68
+    public $linkedObjectsIds;
480 69
 
481
-        if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
482
-    	{
483
-    		require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
484
-    		$tmparray=getState($this->state_id,'all',0,1);
485
-			$this->state_code   =$tmparray['code'];
486
-			$this->state        =$tmparray['label'];
487
-			$this->region_code  =$tmparray['region_code'];
488
-			$this->region       =$tmparray['region'];
489
-        }
490
-
491
-		return dol_format_address($this, $withcountry, $sep);
492
-	}
493
-
494
-
495
-	/**
496
-	 * 	Return full address for banner
497
-	 *
498
-	 * 	@param		string		$htmlkey            HTML id to make banner content unique
499
-	 *  @param      Object      $object				Object (thirdparty, thirdparty of contact for contact, null for a member)
500
-	 *	@return		string							Full address string
501
-	 */
502
-	function getBannerAddress($htmlkey, $object)
503
-	{
504
-		global $conf, $langs;
505
-
506
-		$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
507
-
508
-		$contactid=0;
509
-		$thirdpartyid=0;
510
-		if ($this->element == 'societe')
511
-		{
512
-			$thirdpartyid=$this->id;
513
-		}
514
-		if ($this->element == 'contact')
515
-		{
516
-			$contactid=$this->id;
517
-			$thirdpartyid=$object->fk_soc;
518
-		}
519
-		if ($this->element == 'user')
520
-		{
521
-			$contactid=$this->contact_id;
522
-			$thirdpartyid=$object->fk_soc;
523
-		}
524
-
525
-		$out='<!-- BEGIN part to show address block -->';
526
-
527
-		$outdone=0;
528
-		$coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
529
-		if ($coords)
530
-		{
531
-			if (! empty($conf->use_javascript_ajax))
532
-			{
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($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
544
-				&& empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
545
-		{
546
-            if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
547
-                $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
548
-            }
549
-            else {
550
-                $out.=($outdone?' - ':'').$this->state;
551
-            }
552
-			$outdone++;
553
-		}
554
-
555
-		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>':'');
556
-		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
557
-			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
558
-		}
559
-		if (! empty($this->phone_pro)) {
560
-			$out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
561
-		}
562
-		if (! empty($this->phone_mobile)) {
563
-			$out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
564
-		}
565
-		if (! empty($this->phone_perso)) {
566
-			$out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
567
-		}
568
-		if (! empty($this->office_phone)) {
569
-			$out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
570
-		}
571
-		if (! empty($this->user_mobile)) {
572
-			$out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
573
-		}
574
-		if (! empty($this->fax)) {
575
-			$out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
576
-		}
577
-		if (! empty($this->office_fax)) {
578
-			$out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
579
-		}
580
-
581
-		$out.='<div style="clear: both;"></div>';
582
-		$outdone=0;
583
-		if (! empty($this->email))
584
-		{
585
-			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
586
-			$outdone++;
587
-		}
588
-		if (! empty($this->url))
589
-		{
590
-			$out.=dol_print_url($this->url,'_goout',0,1);
591
-			$outdone++;
592
-		}
593
-		$out.='<div style="clear: both;">';
594
-		if (! empty($conf->socialnetworks->enabled))
595
-		{
596
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
597
-			$outdone++;
598
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
599
-			$outdone++;
600
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
601
-			$outdone++;
602
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
603
-			$outdone++;
604
-		}
605
-		$out.='</div>';
606
-
607
-		$out.='<!-- END Part to show address block -->';
608
-
609
-		return $out;
610
-	}
611
-
612
-	/**
613
-	 * Return the link of last main doc file for direct public download.
614
-	 *
615
-	 * @param	string	$modulepart			Module related to document
616
-	 * @param	int		$initsharekey		Init the share key if it was not yet defined
617
-	 * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
618
-	 * @return	string						Link or empty string if there is no download link
619
-	 */
620
-	function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
621
-	{
622
-		global $user, $dolibarr_main_url_root;
623
-
624
-		if (empty($this->last_main_doc))
625
-		{
626
-			return '';		// No way to known which document name to use
627
-		}
628
-
629
-		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
630
-		$ecmfile=new EcmFiles($this->db);
631
-		$result = $ecmfile->fetch(0, '', $this->last_main_doc);
632
-		if ($result < 0)
633
-		{
634
-			$this->error = $ecmfile->error;
635
-			$this->errors = $ecmfile->errors;
636
-			return -1;
637
-		}
638
-
639
-		if (empty($ecmfile->id))
640
-		{
641
-			// Add entry into index
642
-			if ($initsharekey)
643
-			{
644
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
645
-				// TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
646
-				/*
647
-				$ecmfile->filepath = $rel_dir;
648
-				$ecmfile->filename = $filename;
649
-				$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
650
-				$ecmfile->fullpath_orig = '';
651
-				$ecmfile->gen_or_uploaded = 'generated';
652
-				$ecmfile->description = '';    // indexed content
653
-				$ecmfile->keyword = '';        // keyword content
654
-				$ecmfile->share = getRandomPassword(true);
655
-				$result = $ecmfile->create($user);
656
-				if ($result < 0)
657
-				{
658
-					$this->error = $ecmfile->error;
659
-					$this->errors = $ecmfile->errors;
660
-				}
661
-				*/
662
-			}
663
-			else return '';
664
-		}
665
-		elseif (empty($ecmfile->share))
666
-		{
667
-			// Add entry into index
668
-			if ($initsharekey)
669
-			{
670
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
671
-				$ecmfile->share = getRandomPassword(true);
672
-				$ecmfile->update($user);
673
-			}
674
-			else return '';
675
-		}
676
-
677
-		// Define $urlwithroot
678
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
679
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
680
-		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
681
-
682
-		$forcedownload=0;
683
-
684
-		$paramlink='';
685
-		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
686
-		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
687
-		//$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
688
-		if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
689
-		if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
690
-
691
-		if ($relativelink)
692
-		{
693
-			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
694
-		}
695
-		else
696
-		{
697
-			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
698
-		}
699
-
700
-		// Here $ecmfile->share is defined
701
-		return $linktoreturn;
702
-	}
70
+    /**
71
+     * @var mixed		Array of linked objects. Loaded by ->fetchObjectLinked
72
+     */
73
+    public $linkedObjects;
703 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;
704 79
 
705
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
706
-	/**
707
-	 *  Add a link between element $this->element and a contact
708
-	 *
709
-	 *  @param	int		$fk_socpeople       Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
710
-	 *  @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
711
-	 *  @param  string	$source             external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
712
-	 *  @param  int		$notrigger			Disable all triggers
713
-	 *  @return int                 		<0 if KO, >0 if OK
714
-	 */
715
-	function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
716
-	{
717
-        // phpcs:enable
718
-		global $user,$langs;
719
-
720
-
721
-		dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
722
-
723
-		// Check parameters
724
-		if ($fk_socpeople <= 0)
725
-		{
726
-			$langs->load("errors");
727
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","1");
728
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
729
-			return -1;
730
-		}
731
-		if (! $type_contact)
732
-		{
733
-			$langs->load("errors");
734
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","2");
735
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
736
-			return -2;
737
-		}
738
-
739
-		$id_type_contact=0;
740
-		if (is_numeric($type_contact))
741
-		{
742
-			$id_type_contact=$type_contact;
743
-		}
744
-		else
745
-		{
746
-			// We look for id type_contact
747
-			$sql = "SELECT tc.rowid";
748
-			$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
749
-			$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
750
-			$sql.= " AND tc.source='".$this->db->escape($source)."'";
751
-			$sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
752
-			//print $sql;
753
-			$resql=$this->db->query($sql);
754
-			if ($resql)
755
-			{
756
-				$obj = $this->db->fetch_object($resql);
757
-				if ($obj) $id_type_contact=$obj->rowid;
758
-			}
759
-		}
760
-
761
-		if ($id_type_contact == 0)
762
-		{
763
-			$this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
764
-			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");
765
-			return -3;
766
-		}
767
-
768
-		$datecreate = dol_now();
769
-
770
-		// Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
771
-		$TListeContacts=$this->liste_contact(-1, $source);
772
-		$already_added=false;
773
-		if(!empty($TListeContacts)) {
774
-			foreach($TListeContacts as $array_contact) {
775
-				if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
776
-					$already_added=true;
777
-					break;
778
-				}
779
-			}
780
-		}
80
+    /**
81
+     * @var string		Column name of the ref field.
82
+     */
83
+    protected $table_ref_field = '';
781 84
 
782
-		if(!$already_added) {
783 85
 
784
-			$this->db->begin();
785 86
 
786
-			// Insert into database
787
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
788
-			$sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
789
-			$sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
790
-			$sql.= "'".$this->db->idate($datecreate)."'";
791
-			$sql.= ", 4, ". $id_type_contact;
792
-			$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.
793 88
 
794
-			$resql=$this->db->query($sql);
795
-			if ($resql)
796
-			{
797
-				if (! $notrigger)
798
-				{
799
-					$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
800
-					if ($result < 0)
801
-					{
802
-						$this->db->rollback();
803
-						return -1;
804
-					}
805
-				}
89
+    /**
90
+     * @var array<string,mixed>		Can be used to pass information when only object is provided to method
91
+     */
92
+    public $context=array();
806 93
 
807
-				$this->db->commit();
808
-				return 1;
809
-			}
810
-			else
811
-			{
812
-				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
813
-				{
814
-					$this->error=$this->db->errno();
815
-					$this->db->rollback();
816
-					echo 'err rollback';
817
-					return -2;
818
-				}
819
-				else
820
-				{
821
-					$this->error=$this->db->error();
822
-					$this->db->rollback();
823
-					return -1;
824
-				}
825
-			}
826
-		} else return 0;
827
-	}
94
+    /**
95
+     * @var string		Contains canvas name if record is an alternative canvas record
96
+     */
97
+    public $canvas;
828 98
 
829
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
830
-	/**
831
-	 *    Copy contact from one element to current
832
-	 *
833
-	 *    @param    CommonObject    $objFrom    Source element
834
-	 *    @param    string          $source     Nature of contact ('internal' or 'external')
835
-	 *    @return   int                         >0 if OK, <0 if KO
836
-	 */
837
-	function copy_linked_contact($objFrom, $source='internal')
838
-	{
839
-        // phpcs:enable
840
-		$contacts = $objFrom->liste_contact(-1, $source);
841
-		foreach($contacts as $contact)
842
-		{
843
-			if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
844
-			{
845
-				$this->error=$this->db->lasterror();
846
-				return -1;
847
-			}
848
-		}
849
-		return 1;
850
-	}
99
+    /**
100
+     * @var Project The related project
101
+     * @see fetch_projet()
102
+     */
103
+    public $project;
851 104
 
852
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
853
-	/**
854
-	 *      Update a link to contact line
855
-	 *
856
-	 *      @param	int		$rowid              Id of line contact-element
857
-	 * 		@param	int		$statut	            New status of link
858
-	 *      @param  int		$type_contact_id    Id of contact type (not modified if 0)
859
-	 *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
860
-	 *      @return int                 		<0 if KO, >= 0 if OK
861
-	 */
862
-	function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
863
-	{
864
-        // phpcs:enable
865
-		// Insert into database
866
-		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
867
-		$sql.= " statut = ".$statut;
868
-		if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
869
-		if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
870
-		$sql.= " where rowid = ".$rowid;
871
-		$resql=$this->db->query($sql);
872
-		if ($resql)
873
-		{
874
-			return 0;
875
-		}
876
-		else
877
-		{
878
-			$this->error=$this->db->lasterror();
879
-			return -1;
880
-		}
881
-	}
105
+    /**
106
+     * @var int The related project ID
107
+     * @see setProject(), project
108
+     */
109
+    public $fk_project;
882 110
 
883
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
884
-	/**
885
-	 *    Delete a link to contact line
886
-	 *
887
-	 *    @param	int		$rowid			Id of contact link line to delete
888
-	 *    @param	int		$notrigger		Disable all triggers
889
-	 *    @return   int						>0 if OK, <0 if KO
890
-	 */
891
-	function delete_contact($rowid, $notrigger=0)
892
-	{
893
-        // phpcs:enable
894
-		global $user;
111
+    /**
112
+     * @deprecated
113
+     * @see project
114
+     */
115
+    public $projet;
895 116
 
117
+    /**
118
+     * @var Contact a related contact
119
+     * @see fetch_contact()
120
+     */
121
+    public $contact;
896 122
 
897
-		$this->db->begin();
123
+    /**
124
+     * @var int The related contact ID
125
+     * @see fetch_contact()
126
+     */
127
+    public $contact_id;
898 128
 
899
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
900
-		$sql.= " WHERE rowid =".$rowid;
129
+    /**
130
+     * @var Societe A related thirdparty
131
+     * @see fetch_thirdparty()
132
+     */
133
+    public $thirdparty;
901 134
 
902
-		dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
903
-		if ($this->db->query($sql))
904
-		{
905
-			if (! $notrigger)
906
-			{
907
-				$result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
908
-				if ($result < 0) { $this->db->rollback(); return -1; }
909
-			}
910
-
911
-			$this->db->commit();
912
-			return 1;
913
-		}
914
-		else
915
-		{
916
-			$this->error=$this->db->lasterror();
917
-			$this->db->rollback();
918
-			return -1;
919
-		}
920
-	}
135
+    /**
136
+     * @var User A related user
137
+     * @see fetch_user()
138
+     */
139
+    public $user;
921 140
 
922
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
923
-	/**
924
-	 *    Delete all links between an object $this and all its contacts
925
-	 *
926
-	 *	  @param	string	$source		'' or 'internal' or 'external'
927
-	 *	  @param	string	$code		Type of contact (code or id)
928
-	 *    @return   int					>0 if OK, <0 if KO
929
-	 */
930
-	function delete_linked_contact($source='',$code='')
931
-	{
932
-        // phpcs:enable
933
-		$temp = array();
934
-		$typeContact = $this->liste_type_contact($source,'',0,0,$code);
935
-
936
-		foreach($typeContact as $key => $value)
937
-		{
938
-			array_push($temp,$key);
939
-		}
940
-		$listId = implode(",", $temp);
941
-
942
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
943
-		$sql.= " WHERE element_id = ".$this->id;
944
-		if ($listId)
945
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
946
-
947
-		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
948
-		if ($this->db->query($sql))
949
-		{
950
-			return 1;
951
-		}
952
-		else
953
-		{
954
-			$this->error=$this->db->lasterror();
955
-			return -1;
956
-		}
957
-	}
141
+    /**
142
+     * @var string 	The type of originating object ('commande', 'facture', ...)
143
+     * @see fetch_origin()
144
+     */
145
+    public $origin;
958 146
 
959
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
960
-	/**
961
-	 *    Get array of all contacts for an object
962
-	 *
963
-	 *    @param	int			$statut		Status of links to get (-1=all)
964
-	 *    @param	string		$source		Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
965
-	 *    @param	int         $list       0:Return array contains all properties, 1:Return array contains just id
966
-	 *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
967
-	 *    @return	array|int		        Array of contacts, -1 if error
968
-	 */
969
-	function liste_contact($statut=-1,$source='external',$list=0,$code='')
970
-	{
971
-        // phpcs:enable
972
-		global $langs;
973
-
974
-		$tab=array();
975
-
976
-		$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
977
-		if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
978
-		if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
979
-		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
980
-		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
981
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
982
-		$sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
983
-		if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
984
-		if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
985
-		$sql.= " WHERE ec.element_id =".$this->id;
986
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
987
-		$sql.= " AND tc.element='".$this->db->escape($this->element)."'";
988
-		if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
989
-		if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
990
-		if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
991
-		$sql.= " AND tc.active=1";
992
-		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
993
-		$sql.=" ORDER BY t.lastname ASC";
994
-
995
-		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
996
-		$resql=$this->db->query($sql);
997
-		if ($resql)
998
-		{
999
-			$num=$this->db->num_rows($resql);
1000
-			$i=0;
1001
-			while ($i < $num)
1002
-			{
1003
-				$obj = $this->db->fetch_object($resql);
147
+    /**
148
+     * @var int 	The id of originating object
149
+     * @see fetch_origin()
150
+     */
151
+    public $origin_id;
1004 152
 
1005
-				if (! $list)
1006
-				{
1007
-					$transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1008
-					$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1009
-					$tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
1010
-								   'nom'=>$obj->lastname,      // For backward compatibility
1011
-								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1012
-								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1013
-				}
1014
-				else
1015
-				{
1016
-					$tab[$i]=$obj->id;
1017
-				}
153
+    /**
154
+     * @var string The object's reference
155
+     */
156
+    public $ref;
1018 157
 
1019
-				$i++;
1020
-			}
1021
-
1022
-			return $tab;
1023
-		}
1024
-		else
1025
-		{
1026
-			$this->error=$this->db->lasterror();
1027
-			dol_print_error($this->db);
1028
-			return -1;
1029
-		}
1030
-	}
1031
-
1032
-
1033
-	/**
1034
-	 * 		Update status of a contact linked to object
1035
-	 *
1036
-	 * 		@param	int		$rowid		Id of link between object and contact
1037
-	 * 		@return	int					<0 if KO, >=0 if OK
1038
-	 */
1039
-	function swapContactStatus($rowid)
1040
-	{
1041
-		$sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1042
-		$sql.= " tc.code, tc.libelle";
1043
-		//$sql.= ", s.fk_soc";
1044
-		$sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1045
-		//$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
1046
-		$sql.= " WHERE ec.rowid =".$rowid;
1047
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
1048
-		$sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
1049
-
1050
-		dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1051
-		$resql=$this->db->query($sql);
1052
-		if ($resql)
1053
-		{
1054
-			$obj = $this->db->fetch_object($resql);
1055
-			$newstatut = ($obj->statut == 4) ? 5 : 4;
1056
-			$result = $this->update_contact($rowid, $newstatut);
1057
-			$this->db->free($resql);
1058
-			return $result;
1059
-		}
1060
-		else
1061
-		{
1062
-			$this->error=$this->db->error();
1063
-			dol_print_error($this->db);
1064
-			return -1;
1065
-		}
1066
-	}
158
+    /**
159
+     * @var string The object's previous reference
160
+     */
161
+    public $ref_previous;
1067 162
 
1068
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1069
-	/**
1070
-	 *      Return array with list of possible values for type of contacts
1071
-	 *
1072
-	 *      @param	string	$source     'internal', 'external' or 'all'
1073
-	 *      @param	string	$order		Sort order by : 'position', 'code', 'rowid'...
1074
-	 *      @param  int		$option     0=Return array id->label, 1=Return array code->label
1075
-	 *      @param  int		$activeonly 0=all status of contact, 1=only the active
1076
-	 *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1077
-	 *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1078
-	 */
1079
-	function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1080
-	{
1081
-        // phpcs:enable
1082
-		global $langs;
1083
-
1084
-		if (empty($order)) $order='position';
1085
-		if ($order == 'position') $order.=',code';
1086
-
1087
-		$tab = array();
1088
-		$sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1089
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1090
-		$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
1091
-		if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
1092
-		if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
1093
-		if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
1094
-		$sql.= $this->db->order($order,'ASC');
1095
-
1096
-		//print "sql=".$sql;
1097
-		$resql=$this->db->query($sql);
1098
-		if ($resql)
1099
-		{
1100
-			$num=$this->db->num_rows($resql);
1101
-			$i=0;
1102
-			while ($i < $num)
1103
-			{
1104
-				$obj = $this->db->fetch_object($resql);
1105
-
1106
-				$transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1107
-				$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1108
-				if (empty($option)) $tab[$obj->rowid]=$libelle_type;
1109
-				else $tab[$obj->code]=$libelle_type;
1110
-				$i++;
1111
-			}
1112
-			return $tab;
1113
-		}
1114
-		else
1115
-		{
1116
-			$this->error=$this->db->lasterror();
1117
-			//dol_print_error($this->db);
1118
-			return null;
1119
-		}
1120
-	}
1121
-
1122
-	/**
1123
-	 *      Return id of contacts for a source and a contact code.
1124
-	 *      Example: contact client de facturation ('external', 'BILLING')
1125
-	 *      Example: contact client de livraison ('external', 'SHIPPING')
1126
-	 *      Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
1127
-	 *
1128
-	 *		@param	string	$source		'external' or 'internal'
1129
-	 *		@param	string	$code		'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
1130
-	 *		@param	int		$status		limited to a certain status
1131
-	 *      @return array       		List of id for such contacts
1132
-	 */
1133
-	function getIdContact($source,$code,$status=0)
1134
-	{
1135
-		global $conf;
1136
-
1137
-		$result=array();
1138
-		$i=0;
1139
-		//cas particulier pour les expeditions
1140
-		if($this->element=='shipping' && $this->origin_id != 0) {
1141
-			$id=$this->origin_id;
1142
-			$element='commande';
1143
-        } else if($this->element=='reception' && $this->origin_id != 0) {
1144
-            $id=$this->origin_id;
1145
-            $element='order_supplier';
1146
-		} else {
1147
-			$id=$this->id;
1148
-			$element=$this->element;
1149
-		}
1150
-
1151
-		$sql = "SELECT ec.fk_socpeople";
1152
-		$sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1153
-		if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
1154
-		if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1155
-		$sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1156
-		$sql.= " WHERE ec.element_id = ".$id;
1157
-		$sql.= " AND ec.fk_socpeople = c.rowid";
1158
-		if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
1159
-		if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
1160
-		$sql.= " AND ec.fk_c_type_contact = tc.rowid";
1161
-		$sql.= " AND tc.element = '".$element."'";
1162
-		$sql.= " AND tc.source = '".$source."'";
1163
-		$sql.= " AND tc.code = '".$code."'";
1164
-		$sql.= " AND tc.active = 1";
1165
-		if ($status) $sql.= " AND ec.statut = ".$status;
1166
-
1167
-		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1168
-		$resql=$this->db->query($sql);
1169
-		if ($resql)
1170
-		{
1171
-			while ($obj = $this->db->fetch_object($resql))
1172
-			{
1173
-				$result[$i]=$obj->fk_socpeople;
1174
-				$i++;
1175
-			}
1176
-		}
1177
-		else
1178
-		{
1179
-			$this->error=$this->db->error();
1180
-			return null;
1181
-		}
1182
-
1183
-		return $result;
1184
-	}
163
+    /**
164
+     * @var string The object's next reference
165
+     */
166
+    public $ref_next;
1185 167
 
1186
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1187
-	/**
1188
-	 *		Load object contact with id=$this->contactid into $this->contact
1189
-	 *
1190
-	 *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1191
-	 *		@return	int						<0 if KO, >0 if OK
1192
-	 */
1193
-	function fetch_contact($contactid=null)
1194
-	{
1195
-        // phpcs:enable
1196
-		if (empty($contactid)) $contactid=$this->contactid;
168
+    /**
169
+     * @var string An external reference for the object
170
+     */
171
+    public $ref_ext;
1197 172
 
1198
-		if (empty($contactid)) return 0;
173
+    /**
174
+     * @var int The object's status
175
+     * @see setStatut()
176
+     */
177
+    public $statut;
1199 178
 
1200
-		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1201
-		$contact = new Contact($this->db);
1202
-		$result=$contact->fetch($contactid);
1203
-		$this->contact = $contact;
1204
-		return $result;
1205
-	}
179
+    /**
180
+     * @var string
181
+     * @see getFullAddress()
182
+     */
183
+    public $country;
1206 184
 
1207
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1208
-	/**
1209
-	 *    	Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
1210
-	 *
1211
-	 *		@param		int		$force_thirdparty_id	Force thirdparty id
1212
-	 *		@return		int								<0 if KO, >0 if OK
1213
-	 */
1214
-	function fetch_thirdparty($force_thirdparty_id=0)
1215
-	{
1216
-        // phpcs:enable
1217
-		global $conf;
185
+    /**
186
+     * @var int
187
+     * @see getFullAddress(), country
188
+     */
189
+    public $country_id;
1218 190
 
1219
-		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1220
-			return 0;
191
+    /**
192
+     * @var string
193
+     * @see getFullAddress(), isInEEC(), country
194
+     */
195
+    public $country_code;
1221 196
 
1222
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
197
+    /**
198
+     * @var string
199
+     * @see getFullAddress()
200
+     */
201
+    public $state;
1223 202
 
1224
-		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1225
-		if ($force_thirdparty_id)
1226
-			$idtofetch = $force_thirdparty_id;
203
+    /**
204
+     * @var int
205
+     * @see getFullAddress(), state
206
+     */
207
+    public $state_id;
1227 208
 
1228
-		if ($idtofetch) {
1229
-			$thirdparty = new Societe($this->db);
1230
-			$result = $thirdparty->fetch($idtofetch);
1231
-			$this->thirdparty = $thirdparty;
209
+    /**
210
+     * @var string
211
+     * @see getFullAddress(), state
212
+     */
213
+    public $state_code;
1232 214
 
1233
-			// Use first price level if level not defined for third party
1234
-			if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1235
-				$this->thirdparty->price_level = 1;
1236
-			}
215
+    /**
216
+     * @var string
217
+     * @see getFullAddress(), region
218
+     */
219
+    public $region;
1237 220
 
1238
-			return $result;
1239
-		} else
1240
-			return -1;
1241
-	}
221
+    /**
222
+     * @var string
223
+     * @see getFullAddress(), region
224
+     */
225
+    public $region_code;
1242 226
 
227
+    /**
228
+     * @var int
229
+     * @see fetch_barcode()
230
+     */
231
+    public $barcode_type;
1243 232
 
1244
-	/**
1245
-	 * Looks for an object with ref matching the wildcard provided
1246
-	 * It does only work when $this->table_ref_field is set
1247
-	 *
1248
-	 * @param string $ref Wildcard
1249
-	 * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
1250
-	 */
1251
-	public function fetchOneLike($ref)
1252
-	{
1253
-		if (!$this->table_ref_field) {
1254
-			return 0;
1255
-		}
233
+    /**
234
+     * @var string
235
+     * @see fetch_barcode(), barcode_type
236
+     */
237
+    public $barcode_type_code;
1256 238
 
1257
-		$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;
1258 244
 
1259
-		$query = $this->db->query($sql);
245
+    /**
246
+     * @var string
247
+     * @see fetch_barcode(), barcode_type
248
+     */
249
+    public $barcode_type_coder;
1260 250
 
1261
-		if (!$this->db->num_rows($query)) {
1262
-			return 0;
1263
-		}
251
+    /**
252
+     * @var int Payment method ID (cheque, cash, ...)
253
+     * @see setPaymentMethods()
254
+     */
255
+    public $mode_reglement_id;
1264 256
 
1265
-		$result = $this->db->fetch_object($query);
257
+    /**
258
+     * @var int Payment terms ID
259
+     * @see setPaymentTerms()
260
+     */
261
+    public $cond_reglement_id;
1266 262
 
1267
-		return $this->fetch($result->rowid);
1268
-	}
263
+    /**
264
+     * @var int Payment terms ID
265
+     * @deprecated Kept for compatibility
266
+     * @see cond_reglement_id;
267
+     */
268
+    public $cond_reglement;
1269 269
 
1270
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1271
-	/**
1272
-	 *	Load data for barcode into properties ->barcode_type*
1273
-	 *	Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
1274
-	 *  if it is not defined, ->element must be defined to know default barcode type.
1275
-	 *
1276
-	 *	@return		int			<0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
1277
-	 */
1278
-	function fetch_barcode()
1279
-	{
1280
-        // phpcs:enable
1281
-		global $conf;
270
+    /**
271
+     * @var int Delivery address ID
272
+     * @deprecated
273
+     * @see setDeliveryAddress()
274
+     */
275
+    public $fk_delivery_address;
1282 276
 
1283
-		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;
1284 282
 
1285
-		$idtype=$this->barcode_type;
1286
-		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
1287
-		{
1288
-			if ($this->element == 'product')      $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1289
-			else if ($this->element == 'societe') $idtype = $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 = ".$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($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($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
-				if (! empty($user->admin) && empty($user->entity) && $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($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($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
-				if (! empty($user->admin) && empty($user->entity) && $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) $sql.= " AND entity = ".$conf->entity;
1905 413
 
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;
414
+        dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
415
+        $resql = $db->query($sql);
416
+        if ($resql)
417
+        {
418
+            $num=$db->num_rows($resql);
419
+            if ($num > 0) return 1;
420
+            else return 0;
421
+        }
422
+        return -1;
423
+    }
2007 424
 
2008
-        if (empty($userused)) $userused=$user;
425
+    /**
426
+     * Method to output saved errors
427
+     *
428
+     * @return	string		String with errors
429
+     */
430
+    function errorsToString()
431
+    {
432
+        return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
433
+    }
2009 434
 
2010
-        $error = 0;
435
+    /**
436
+     *	Return full name (civility+' '+name+' '+lastname)
437
+     *
438
+     *	@param	Translate	$langs			Language object for translation of civility (used only if option is 1)
439
+     *	@param	int			$option			0=No option, 1=Add civility
440
+     * 	@param	int			$nameorder		-1=Auto, 0=Lastname+Firstname, 1=Firstname+Lastname, 2=Firstname
441
+     * 	@param	int			$maxlen			Maximum length
442
+     * 	@return	string						String with full name
443
+     */
444
+    function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
445
+    {
446
+        //print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
447
+        $lastname=$this->lastname;
448
+        $firstname=$this->firstname;
449
+        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 450
 
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
-		}
451
+        $ret='';
452
+        if ($option && $this->civility_id)
453
+        {
454
+            if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
455
+            else $ret.=$this->civility_id.' ';
456
+        }
2016 457
 
2017
-        $this->db->begin();
458
+        $ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
2018 459
 
2019
-		if ($shipping_method_id<0) $shipping_method_id='NULL';
2020
-		dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
460
+        return DolUtils::dol_trunc($ret, $maxlen);
461
+    }
2021 462
 
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)
463
+    /**
464
+     * 	Return full address of contact
465
+     *
466
+     * 	@param		int			$withcountry		1=Add country into address string
467
+     *  @param		string		$sep				Separator to use to build string
468
+     *  @param		int		    $withregion			1=Add region into address string
469
+     *	@return		string							Full address string
470
+     */
471
+    function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
472
+    {
473
+        if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
474
+        {
475
+            require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
476
+            $tmparray=getCountry($this->country_id,'all');
477
+            $this->country_code=$tmparray['code'];
478
+            $this->country     =$tmparray['label'];
479
+        }
480
+
481
+        if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
482
+        {
483
+            require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
484
+            $tmparray=getState($this->state_id,'all',0,1);
485
+            $this->state_code   =$tmparray['code'];
486
+            $this->state        =$tmparray['label'];
487
+            $this->region_code  =$tmparray['region_code'];
488
+            $this->region       =$tmparray['region'];
489
+        }
490
+
491
+        return dol_format_address($this, $withcountry, $sep);
492
+    }
493
+
494
+
495
+    /**
496
+     * 	Return full address for banner
497
+     *
498
+     * 	@param		string		$htmlkey            HTML id to make banner content unique
499
+     *  @param      Object      $object				Object (thirdparty, thirdparty of contact for contact, null for a member)
500
+     *	@return		string							Full address string
501
+     */
502
+    function getBannerAddress($htmlkey, $object)
503
+    {
504
+        global $conf, $langs;
505
+
506
+        $countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
507
+
508
+        $contactid=0;
509
+        $thirdpartyid=0;
510
+        if ($this->element == 'societe')
511
+        {
512
+            $thirdpartyid=$this->id;
513
+        }
514
+        if ($this->element == 'contact')
515
+        {
516
+            $contactid=$this->id;
517
+            $thirdpartyid=$object->fk_soc;
518
+        }
519
+        if ($this->element == 'user')
520
+        {
521
+            $contactid=$this->contact_id;
522
+            $thirdpartyid=$object->fk_soc;
523
+        }
524
+
525
+        $out='<!-- BEGIN part to show address block -->';
526
+
527
+        $outdone=0;
528
+        $coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
529
+        if ($coords)
530
+        {
531
+            if (! empty($conf->use_javascript_ajax))
2032 532
             {
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
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> ';
2038 538
             }
539
+            $out.=dol_print_address($coords, 'address_'.$htmlkey.'_'.$this->id, $this->element, $this->id, 1, ', '); $outdone++;
540
+            $outdone++;
2039 541
         }
2040
-        if ($error)
542
+
543
+        if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
544
+                && empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
2041 545
         {
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;
546
+            if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
547
+                $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
548
+            }
549
+            else {
550
+                $out.=($outdone?' - ':'').$this->state;
551
+            }
552
+            $outdone++;
2048 553
         }
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 554
 
2132
-        if (empty($userused)) $userused=$user;
555
+        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>':'');
556
+        if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
557
+            $out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
558
+        }
559
+        if (! empty($this->phone_pro)) {
560
+            $out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
561
+        }
562
+        if (! empty($this->phone_mobile)) {
563
+            $out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
564
+        }
565
+        if (! empty($this->phone_perso)) {
566
+            $out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
567
+        }
568
+        if (! empty($this->office_phone)) {
569
+            $out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
570
+        }
571
+        if (! empty($this->user_mobile)) {
572
+            $out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
573
+        }
574
+        if (! empty($this->fax)) {
575
+            $out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
576
+        }
577
+        if (! empty($this->office_fax)) {
578
+            $out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
579
+        }
2133 580
 
2134
-        $error = 0;
581
+        $out.='<div style="clear: both;"></div>';
582
+        $outdone=0;
583
+        if (! empty($this->email))
584
+        {
585
+            $out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
586
+            $outdone++;
587
+        }
588
+        if (! empty($this->url))
589
+        {
590
+            $out.=dol_print_url($this->url,'_goout',0,1);
591
+            $outdone++;
592
+        }
593
+        $out.='<div style="clear: both;">';
594
+        if (! empty($conf->socialnetworks->enabled))
595
+        {
596
+            if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
597
+            $outdone++;
598
+            if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
599
+            $outdone++;
600
+            if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
601
+            $outdone++;
602
+            if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
603
+            $outdone++;
604
+        }
605
+        $out.='</div>';
2135 606
 
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();
607
+        $out.='<!-- END Part to show address block -->';
608
+
609
+        return $out;
610
+    }
2141 611
 
2142
-		if ($fk_account<0) $fk_account='NULL';
2143
-		dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
612
+    /**
613
+     * Return the link of last main doc file for direct public download.
614
+     *
615
+     * @param	string	$modulepart			Module related to document
616
+     * @param	int		$initsharekey		Init the share key if it was not yet defined
617
+     * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
618
+     * @return	string						Link or empty string if there is no download link
619
+     */
620
+    function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
621
+    {
622
+        global $user, $dolibarr_main_url_root;
2144 623
 
2145
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
2146
-		$sql.= " SET fk_account = ".$fk_account;
2147
-		$sql.= " WHERE rowid=".$this->id;
624
+        if (empty($this->last_main_doc))
625
+        {
626
+            return '';		// No way to known which document name to use
627
+        }
2148 628
 
2149
-        $resql = $this->db->query($sql);
2150
-        if (! $resql)
629
+        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
630
+        $ecmfile=new EcmFiles($this->db);
631
+        $result = $ecmfile->fetch(0, '', $this->last_main_doc);
632
+        if ($result < 0)
2151 633
         {
2152
-            dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153
-            $this->error = $this->db->lasterror();
2154
-            $error++;
634
+            $this->error = $ecmfile->error;
635
+            $this->errors = $ecmfile->errors;
636
+            return -1;
2155 637
         }
2156
-        else
638
+
639
+        if (empty($ecmfile->id))
2157 640
         {
2158
-            if (!$notrigger)
641
+            // Add entry into index
642
+            if ($initsharekey)
2159 643
             {
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
644
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
645
+                // TODO We can't, we dont' have full path of file, only last_main_doc adn ->element, so we must rebuild full path first
646
+                /*
647
+				$ecmfile->filepath = $rel_dir;
648
+				$ecmfile->filename = $filename;
649
+				$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
650
+				$ecmfile->fullpath_orig = '';
651
+				$ecmfile->gen_or_uploaded = 'generated';
652
+				$ecmfile->description = '';    // indexed content
653
+				$ecmfile->keyword = '';        // keyword content
654
+				$ecmfile->share = getRandomPassword(true);
655
+				$result = $ecmfile->create($user);
656
+				if ($result < 0)
657
+				{
658
+					$this->error = $ecmfile->error;
659
+					$this->errors = $ecmfile->errors;
660
+				}
661
+				*/
2165 662
             }
663
+            else return '';
2166 664
         }
2167
-        if ($error)
665
+        elseif (empty($ecmfile->share))
2168 666
         {
2169
-            $this->db->rollback();
2170
-            return -1;
667
+            // Add entry into index
668
+            if ($initsharekey)
669
+            {
670
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
671
+                $ecmfile->share = getRandomPassword(true);
672
+                $ecmfile->update($user);
673
+            }
674
+            else return '';
675
+        }
676
+
677
+        // Define $urlwithroot
678
+        $urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
679
+        $urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
680
+        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
681
+
682
+        $forcedownload=0;
683
+
684
+        $paramlink='';
685
+        //if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
686
+        //if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
687
+        //$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
688
+        if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
689
+        if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
690
+
691
+        if ($relativelink)
692
+        {
693
+            $linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
2171 694
         }
2172 695
         else
2173 696
         {
2174
-            $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2175
-            $this->db->commit();
2176
-            return 1;
697
+            $linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
2177 698
         }
2178
-    }
2179 699
 
700
+        // Here $ecmfile->share is defined
701
+        return $linktoreturn;
702
+    }
2180 703
 
2181
-	// TODO: Move line related operations to CommonObjectLine?
2182 704
 
2183 705
     // 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
-	{
706
+    /**
707
+     *  Add a link between element $this->element and a contact
708
+     *
709
+     *  @param	int		$fk_socpeople       Id of thirdparty contact (if source = 'external') or id of user (if souce = 'internal') to link
710
+     *  @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
711
+     *  @param  string	$source             external=Contact extern (llx_socpeople), internal=Contact intern (llx_user)
712
+     *  @param  int		$notrigger			Disable all triggers
713
+     *  @return int                 		<0 if KO, >0 if OK
714
+     */
715
+    function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
716
+    {
2195 717
         // 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
-				}
718
+        global $user,$langs;
2254 719
 
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 720
 
2301
-		return $rows;
2302
-	}
721
+        dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
2303 722
 
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);
723
+        // Check parameters
724
+        if ($fk_socpeople <= 0)
725
+        {
726
+            $langs->load("errors");
727
+            $this->error=$langs->trans("ErrorWrongValueForParameterX","1");
728
+            dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
729
+            return -1;
730
+        }
731
+        if (! $type_contact)
732
+        {
733
+            $langs->load("errors");
734
+            $this->error=$langs->trans("ErrorWrongValueForParameterX","2");
735
+            dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
736
+            return -2;
737
+        }
2316 738
 
2317
-		// Get rang of line
2318
-		$rang = $this->getRangOfLine($rowid);
739
+        $id_type_contact=0;
740
+        if (is_numeric($type_contact))
741
+        {
742
+            $id_type_contact=$type_contact;
743
+        }
744
+        else
745
+        {
746
+            // We look for id type_contact
747
+            $sql = "SELECT tc.rowid";
748
+            $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
749
+            $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
750
+            $sql.= " AND tc.source='".$this->db->escape($source)."'";
751
+            $sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
752
+            //print $sql;
753
+            $resql=$this->db->query($sql);
754
+            if ($resql)
755
+            {
756
+                $obj = $this->db->fetch_object($resql);
757
+                if ($obj) $id_type_contact=$obj->rowid;
758
+            }
759
+        }
2319 760
 
2320
-		// Update position of line
2321
-		$this->updateLineUp($rowid, $rang);
2322
-	}
761
+        if ($id_type_contact == 0)
762
+        {
763
+            $this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
764
+            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");
765
+            return -3;
766
+        }
2323 767
 
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
-	}
768
+        $datecreate = dol_now();
769
+
770
+        // Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
771
+        $TListeContacts=$this->liste_contact(-1, $source);
772
+        $already_added=false;
773
+        if(!empty($TListeContacts)) {
774
+            foreach($TListeContacts as $array_contact) {
775
+                if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
776
+                    $already_added=true;
777
+                    break;
778
+                }
779
+            }
780
+        }
2368 781
 
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
-	}
782
+        if(!$already_added) {
2491 783
 
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
-	}
784
+            $this->db->begin();
2539 785
 
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
-	}
786
+            // Insert into database
787
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
788
+            $sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
789
+            $sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
790
+            $sql.= "'".$this->db->idate($datecreate)."'";
791
+            $sql.= ", 4, ". $id_type_contact;
792
+            $sql.= ")";
793
+
794
+            $resql=$this->db->query($sql);
795
+            if ($resql)
796
+            {
797
+                if (! $notrigger)
798
+                {
799
+                    $result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
800
+                    if ($result < 0)
801
+                    {
802
+                        $this->db->rollback();
803
+                        return -1;
804
+                    }
805
+                }
806
+
807
+                $this->db->commit();
808
+                return 1;
809
+            }
810
+            else
811
+            {
812
+                if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
813
+                {
814
+                    $this->error=$this->db->errno();
815
+                    $this->db->rollback();
816
+                    echo 'err rollback';
817
+                    return -2;
818
+                }
819
+                else
820
+                {
821
+                    $this->error=$this->db->error();
822
+                    $this->db->rollback();
823
+                    return -1;
824
+                }
825
+            }
826
+        } else return 0;
827
+    }
2572 828
 
2573 829
     // 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
-	{
830
+    /**
831
+     *    Copy contact from one element to current
832
+     *
833
+     *    @param    CommonObject    $objFrom    Source element
834
+     *    @param    string          $source     Nature of contact ('internal' or 'external')
835
+     *    @return   int                         >0 if OK, <0 if KO
836
+     */
837
+    function copy_linked_contact($objFrom, $source='internal')
838
+    {
2583 839
         // 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
-	}
840
+        $contacts = $objFrom->liste_contact(-1, $source);
841
+        foreach($contacts as $contact)
842
+        {
843
+            if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
844
+            {
845
+                $this->error=$this->db->lasterror();
846
+                return -1;
847
+            }
848
+        }
849
+        return 1;
850
+    }
2625 851
 
2626 852
     // 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
-	{
853
+    /**
854
+     *      Update a link to contact line
855
+     *
856
+     *      @param	int		$rowid              Id of line contact-element
857
+     * 		@param	int		$statut	            New status of link
858
+     *      @param  int		$type_contact_id    Id of contact type (not modified if 0)
859
+     *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
860
+     *      @return int                 		<0 if KO, >= 0 if OK
861
+     */
862
+    function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
863
+    {
2637 864
         // phpcs:enable
2638
-		return $this->update_note($note,'_public');
2639
-	}
865
+        // Insert into database
866
+        $sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
867
+        $sql.= " statut = ".$statut;
868
+        if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
869
+        if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
870
+        $sql.= " where rowid = ".$rowid;
871
+        $resql=$this->db->query($sql);
872
+        if ($resql)
873
+        {
874
+            return 0;
875
+        }
876
+        else
877
+        {
878
+            $this->error=$this->db->lasterror();
879
+            return -1;
880
+        }
881
+    }
2640 882
 
2641 883
     // 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
-	{
884
+    /**
885
+     *    Delete a link to contact line
886
+     *
887
+     *    @param	int		$rowid			Id of contact link line to delete
888
+     *    @param	int		$notrigger		Disable all triggers
889
+     *    @return   int						>0 if OK, <0 if KO
890
+     */
891
+    function delete_contact($rowid, $notrigger=0)
892
+    {
2654 893
         // 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($conf->global->$MODULE)) {
2674
-				$modsactivated = explode(',', $conf->global->$MODULE);
2675
-				foreach ($modsactivated as $mod) {
2676
-					if ($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($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2688
-		elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2689
-
2690
-		$error=0;
2691
-
2692
-		$multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2693
-
2694
-		// Define constants to find lines to sum
2695
-		$fieldtva='total_tva';
2696
-		$fieldlocaltax1='total_localtax1';
2697
-		$fieldlocaltax2='total_localtax2';
2698
-		$fieldup='subprice';
2699
-		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2700
-		{
2701
-			$fieldtva='tva';
2702
-			$fieldup='pu_ht';
2703
-		}
2704
-		if ($this->element == 'expensereport')
2705
-		{
2706
-			$fieldup='value_unit';
2707
-		}
2708
-
2709
-		$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,';
2710
-		$sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2711
-			if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
2712
-			$sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2713
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2714
-		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2715
-		if ($exclspec)
2716
-		{
2717
-			$product_field='product_type';
2718
-			if ($this->table_element_line == 'contratdet') $product_field='';    // contratdet table has no product_type field
2719
-			if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
2720
-		}
2721
-		$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
-
2723
-		dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2724
-		$resql = $this->db->query($sql);
2725
-		if ($resql)
2726
-		{
2727
-			$this->total_ht  = 0;
2728
-			$this->total_tva = 0;
2729
-			$this->total_localtax1 = 0;
2730
-			$this->total_localtax2 = 0;
2731
-			$this->total_ttc = 0;
2732
-			$total_ht_by_vats  = array();
2733
-			$total_tva_by_vats = array();
2734
-			$total_ttc_by_vats = array();
2735
-			$this->multicurrency_total_ht	= 0;
2736
-			$this->multicurrency_total_tva	= 0;
2737
-			$this->multicurrency_total_ttc	= 0;
2738
-
2739
-			$num = $this->db->num_rows($resql);
2740
-			$i = 0;
2741
-			while ($i < $num)
2742
-			{
2743
-				$obj = $this->db->fetch_object($resql);
2744
-
2745
-				// Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2746
-				$parameters=array('fk_element' => $obj->rowid);
2747
-				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2748
-
2749
-				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'
2750
-				{
2751
-					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2752
-					$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);
2753
-					$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2754
-					if ($diff)
2755
-					{
2756
-						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2757
-						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);
2758
-								$resqlfix=$this->db->query($sqlfix);
2759
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2760
-								$obj->total_tva = $tmpcal[1];
2761
-								$obj->total_ttc = $tmpcal[2];
2762
-						//
2763
-					}
2764
-				}
894
+        global $user;
2765 895
 
2766
-				$this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2767
-				$this->total_tva       += $obj->total_tva;
2768
-				$this->total_localtax1 += $obj->total_localtax1;
2769
-				$this->total_localtax2 += $obj->total_localtax2;
2770
-				$this->total_ttc       += $obj->total_ttc;
2771
-				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2772
-				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2773
-				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2774
-
2775
-				if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
2776
-				if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
2777
-				if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
2778
-				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2779
-				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2780
-				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2781
-
2782
-				if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2783
-				{
2784
-					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2785
-					$diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2786
-					//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";
2787
-					if ($diff)
2788
-					{
2789
-						if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
2790
-						$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
-						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);
2792
-								$resqlfix=$this->db->query($sqlfix);
2793
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2794
-								$this->total_tva -= $diff;
2795
-								$this->total_ttc -= $diff;
2796
-								$total_tva_by_vats[$obj->vatrate] -= $diff;
2797
-								$total_ttc_by_vats[$obj->vatrate] -= $diff;
2798
-					}
2799
-				}
2800 896
 
2801
-				$i++;
2802
-			}
897
+        $this->db->begin();
2803 898
 
2804
-			// Add revenue stamp to total
2805
-			$this->total_ttc       			+= isset($this->revenuestamp)?$this->revenuestamp:0;
2806
-			$this->multicurrency_total_ttc  += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0;
899
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
900
+        $sql.= " WHERE rowid =".$rowid;
2807 901
 
2808
-			// Situations totals
2809
-			if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE )
2810
-			{
2811
-				$prev_sits = $this->get_prev_sits();
2812
-
2813
-				foreach ($prev_sits as $sit) {				// $sit is an object Facture loaded with a fetch.
2814
-					$this->total_ht -= $sit->total_ht;
2815
-					$this->total_tva -= $sit->total_tva;
2816
-					$this->total_localtax1 -= $sit->total_localtax1;
2817
-					$this->total_localtax2 -= $sit->total_localtax2;
2818
-					$this->total_ttc -= $sit->total_ttc;
2819
-					$this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
2820
-					$this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
2821
-					$this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
2822
-				}
2823
-			}
2824
-
2825
-			$this->db->free($resql);
2826
-
2827
-			// Now update global field total_ht, total_ttc and tva
2828
-			$fieldht='total_ht';
2829
-			$fieldtva='tva';
2830
-			$fieldlocaltax1='localtax1';
2831
-			$fieldlocaltax2='localtax2';
2832
-			$fieldttc='total_ttc';
2833
-			// Specific code for backward compatibility with old field names
2834
-			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht='total';
2835
-			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
2836
-			if ($this->element == 'propal')                                                $fieldttc='total';
2837
-			if ($this->element == 'expensereport')                                         $fieldtva='total_tva';
2838
-			if ($this->element == 'supplier_proposal')                                     $fieldttc='total';
2839
-
2840
-			if (empty($nodatabaseupdate))
2841
-			{
2842
-				$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
2843
-				$sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
2844
-				$sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
2845
-				$sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
2846
-				$sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
2847
-				$sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
2848
-						$sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
2849
-						$sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
2850
-						$sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
2851
-				$sql .= ' WHERE rowid = '.$this->id;
2852
-
2853
-
2854
-				dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2855
-				$resql=$this->db->query($sql);
2856
-				if (! $resql)
2857
-				{
2858
-					$error++;
2859
-					$this->error=$this->db->lasterror();
2860
-					$this->errors[]=$this->db->lasterror();
2861
-				}
2862
-			}
902
+        dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
903
+        if ($this->db->query($sql))
904
+        {
905
+            if (! $notrigger)
906
+            {
907
+                $result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
908
+                if ($result < 0) { $this->db->rollback(); return -1; }
909
+            }
2863 910
 
2864
-			if (! $error)
2865
-			{
2866
-				return 1;
2867
-			}
2868
-			else
2869
-			{
2870
-				return -1;
2871
-			}
2872
-		}
2873
-		else
2874
-		{
2875
-			dol_print_error($this->db,'Bad request in update_price');
2876
-			return -1;
2877
-		}
2878
-	}
911
+            $this->db->commit();
912
+            return 1;
913
+        }
914
+        else
915
+        {
916
+            $this->error=$this->db->lasterror();
917
+            $this->db->rollback();
918
+            return -1;
919
+        }
920
+    }
2879 921
 
2880 922
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2881
-	/**
2882
-	 *	Add objects linked in llx_element_element.
2883
-	 *
2884
-	 *	@param		string	$origin		Linked element type
2885
-	 *	@param		int		$origin_id	Linked element id
2886
-	 *	@return		int					<=0 if KO, >0 if OK
2887
-	 *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2888
-	 */
2889
-	function add_object_linked($origin=null, $origin_id=null)
2890
-	{
923
+    /**
924
+     *    Delete all links between an object $this and all its contacts
925
+     *
926
+     *	  @param	string	$source		'' or 'internal' or 'external'
927
+     *	  @param	string	$code		Type of contact (code or id)
928
+     *    @return   int					>0 if OK, <0 if KO
929
+     */
930
+    function delete_linked_contact($source='',$code='')
931
+    {
2891 932
         // phpcs:enable
2892
-		$origin = (! empty($origin) ? $origin : $this->origin);
2893
-		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2894
-
2895
-		// Special case
2896
-		if ($origin == 'order') $origin='commande';
2897
-		if ($origin == 'invoice') $origin='facture';
2898
-		if ($origin == 'invoice_template') $origin='facturerec';
2899
-    	if ($origin == 'supplierorder') $origin='order_supplier';
2900
-		$this->db->begin();
2901
-
2902
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2903
-		$sql.= "fk_source";
2904
-		$sql.= ", sourcetype";
2905
-		$sql.= ", fk_target";
2906
-		$sql.= ", targettype";
2907
-		$sql.= ") VALUES (";
2908
-		$sql.= $origin_id;
2909
-		$sql.= ", '".$this->db->escape($origin)."'";
2910
-		$sql.= ", ".$this->id;
2911
-		$sql.= ", '".$this->db->escape($this->element)."'";
2912
-		$sql.= ")";
2913
-
2914
-		dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2915
-		if ($this->db->query($sql))
2916
-	  	{
2917
-	  		$this->db->commit();
2918
-	  		return 1;
2919
-	  	}
2920
-	  	else
2921
-	  	{
2922
-	  		$this->error=$this->db->lasterror();
2923
-	  		$this->db->rollback();
2924
-	  		return 0;
2925
-	  	}
2926
-	}
2927
-
2928
-	/**
2929
-	 *	Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
2930
-	 *		this->linkedObjectsIds array and
2931
-	 *		this->linkedObjects array if $loadalsoobjects = 1
2932
-	 *  Possible usage for parameters:
2933
-	 *  - all parameters empty -> we look all link to current object (current object can be source or target)
2934
-	 *  - source id+type -> will get target list linked to source
2935
-	 *  - target id+type -> will get source list linked to target
2936
-	 *  - source id+type + target type -> will get target list of the type
2937
-	 *  - target id+type + target source -> will get source list of the type
2938
-	 *
2939
-	 *	@param	int		$sourceid			Object source id (if not defined, id of object)
2940
-	 *	@param  string	$sourcetype			Object source type (if not defined, element name of object)
2941
-	 *	@param  int		$targetid			Object target id (if not defined, id of object)
2942
-	 *	@param  string	$targettype			Object target type (if not defined, elemennt name of object)
2943
-	 *	@param  string	$clause				'OR' or 'AND' clause used when both source id and target id are provided
2944
-	 *  @param  int		$alsosametype		0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
2945
-	 *  @param  string	$orderby			SQL 'ORDER BY' clause
2946
-	 *  @param	int		$loadalsoobjects	Load also array this->linkedObjects (Use 0 to increase performances)
2947
-	 *	@return int							<0 if KO, >0 if OK
2948
-	 *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2949
-	 */
2950
-	function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2951
-	{
2952
-		global $conf;
2953
-
2954
-		$this->linkedObjectsIds=array();
2955
-		$this->linkedObjects=array();
2956
-
2957
-		$justsource=false;
2958
-		$justtarget=false;
2959
-		$withtargettype=false;
2960
-		$withsourcetype=false;
2961
-
2962
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2963
-		{
2964
-			$justsource=true;  // the source (id and type) is a search criteria
2965
-			if (! empty($targettype)) $withtargettype=true;
2966
-		}
2967
-		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2968
-		{
2969
-			$justtarget=true;  // the target (id and type) is a search criteria
2970
-			if (! empty($sourcetype)) $withsourcetype=true;
2971
-		}
2972
-
2973
-		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
2974
-		$targetid = (! empty($targetid) ? $targetid : $this->id);
2975
-		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
2976
-		$targettype = (! empty($targettype) ? $targettype : $this->element);
2977
-
2978
-		/*if (empty($sourceid) && empty($targetid))
2979
-		 {
2980
-		 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
2981
-		 return -1;
2982
-		 }*/
933
+        $temp = array();
934
+        $typeContact = $this->liste_type_contact($source,'',0,0,$code);
2983 935
 
2984
-		// Links between objects are stored in table element_element
2985
-		$sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2986
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2987
-		$sql.= " WHERE ";
2988
-		if ($justsource || $justtarget)
2989
-		{
2990
-			if ($justsource)
2991
-			{
2992
-				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2993
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2994
-			}
2995
-			else if ($justtarget)
2996
-			{
2997
-				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2998
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
2999
-			}
3000
-		}
3001
-		else
3002
-		{
3003
-			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3004
-			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3005
-		}
3006
-		$sql .= ' ORDER BY '.$orderby;
3007
-
3008
-		dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3009
-		$resql = $this->db->query($sql);
3010
-		if ($resql)
3011
-		{
3012
-			$num = $this->db->num_rows($resql);
3013
-			$i = 0;
3014
-			while ($i < $num)
3015
-			{
3016
-				$obj = $this->db->fetch_object($resql);
3017
-				if ($justsource || $justtarget)
3018
-				{
3019
-					if ($justsource)
3020
-					{
3021
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3022
-					}
3023
-					else if ($justtarget)
3024
-					{
3025
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3026
-					}
3027
-				}
3028
-				else
3029
-				{
3030
-					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3031
-					{
3032
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3033
-					}
3034
-					if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3035
-					{
3036
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3037
-					}
3038
-				}
3039
-				$i++;
3040
-			}
936
+        foreach($typeContact as $key => $value)
937
+        {
938
+            array_push($temp,$key);
939
+        }
940
+        $listId = implode(",", $temp);
3041 941
 
3042
-			if (! empty($this->linkedObjectsIds))
3043
-			{
3044
-				$tmparray = $this->linkedObjectsIds;
3045
-				foreach($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3046
-				{
3047
-					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3048
-					$module = $element = $subelement = $objecttype;
3049
-					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3050
-						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3051
-					{
3052
-						$module = $element = $regs[1];
3053
-						$subelement = $regs[2];
3054
-					}
3055
-
3056
-					$classpath = $element.'/class';
3057
-					// To work with non standard classpath or module name
3058
-					if ($objecttype == 'facture')			{
3059
-						$classpath = 'compta/facture/class';
3060
-					}
3061
-					else if ($objecttype == 'facturerec')			{
3062
-						$classpath = 'compta/facture/class'; $module = 'facture';
3063
-					}
3064
-					else if ($objecttype == 'propal')			{
3065
-						$classpath = 'comm/propal/class';
3066
-					}
3067
-					else if ($objecttype == 'supplier_proposal')			{
3068
-						$classpath = 'supplier_proposal/class';
3069
-					}
3070
-					else if ($objecttype == 'shipping')			{
3071
-						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3072
-					}
3073
-					else if ($objecttype == 'delivery')			{
3074
-						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3075
-					}
3076
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3077
-						$classpath = 'fourn/class'; $module = 'fournisseur';
3078
-					}
3079
-					else if ($objecttype == 'fichinter')			{
3080
-						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3081
-					}
3082
-					else if ($objecttype == 'subscription')			{
3083
-						$classpath = 'adherents/class'; $module = 'adherent';
3084
-					}
3085
-
3086
-					// Set classfile
3087
-					$classfile = strtolower($subelement); $classname = ucfirst($subelement);
3088
-
3089
-					if ($objecttype == 'order') {
3090
-						$classfile = 'commande'; $classname = 'Commande';
3091
-					}
3092
-					else if ($objecttype == 'invoice_supplier') {
3093
-						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3094
-					}
3095
-					else if ($objecttype == 'order_supplier')   {
3096
-						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3097
-					}
3098
-					else if ($objecttype == 'supplier_proposal')   {
3099
-						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3100
-					}
3101
-					else if ($objecttype == 'facturerec')   {
3102
-						$classfile = 'facture-rec'; $classname = 'FactureRec';
3103
-					}
3104
-					else if ($objecttype == 'subscription')   {
3105
-						$classfile = 'subscription'; $classname = 'Subscription';
3106
-					}
3107
-
3108
-					// Here $module, $classfile and $classname are set
3109
-					if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
3110
-					{
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
-			}
942
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
943
+        $sql.= " WHERE element_id = ".$this->id;
944
+        if ($listId)
945
+            $sql.= " AND fk_c_type_contact IN (".$listId.")";
3314 946
 
3315
-			if (! $error)
3316
-			{
3317
-				$this->db->commit();
947
+        dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
948
+        if ($this->db->query($sql))
949
+        {
950
+            return 1;
951
+        }
952
+        else
953
+        {
954
+            $this->error=$this->db->lasterror();
955
+            return -1;
956
+        }
957
+    }
3318 958
 
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
-				}
959
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
960
+    /**
961
+     *    Get array of all contacts for an object
962
+     *
963
+     *    @param	int			$statut		Status of links to get (-1=all)
964
+     *    @param	string		$source		Source of contact: external or thirdparty (llx_socpeople) or internal (llx_user)
965
+     *    @param	int         $list       0:Return array contains all properties, 1:Return array contains just id
966
+     *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
967
+     *    @return	array|int		        Array of contacts, -1 if error
968
+     */
969
+    function liste_contact($statut=-1,$source='external',$list=0,$code='')
970
+    {
971
+        // phpcs:enable
972
+        global $langs;
973
+
974
+        $tab=array();
975
+
976
+        $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
977
+        if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
978
+        if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
979
+        $sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
980
+        $sql.= ", tc.source, tc.element, tc.code, tc.libelle";
981
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
982
+        $sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
983
+        if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
984
+        if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
985
+        $sql.= " WHERE ec.element_id =".$this->id;
986
+        $sql.= " AND ec.fk_c_type_contact=tc.rowid";
987
+        $sql.= " AND tc.element='".$this->db->escape($this->element)."'";
988
+        if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
989
+        if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
990
+        if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
991
+        $sql.= " AND tc.active=1";
992
+        if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
993
+        $sql.=" ORDER BY t.lastname ASC";
994
+
995
+        dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
996
+        $resql=$this->db->query($sql);
997
+        if ($resql)
998
+        {
999
+            $num=$this->db->num_rows($resql);
1000
+            $i=0;
1001
+            while ($i < $num)
1002
+            {
1003
+                $obj = $this->db->fetch_object($resql);
1004
+
1005
+                if (! $list)
1006
+                {
1007
+                    $transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1008
+                    $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1009
+                    $tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
1010
+                                    'nom'=>$obj->lastname,      // For backward compatibility
1011
+                                    'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1012
+                                    'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1013
+                }
1014
+                else
1015
+                {
1016
+                    $tab[$i]=$obj->id;
1017
+                }
1018
+
1019
+                $i++;
1020
+            }
3324 1021
 
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($conf->global->MAIN_DISABLE_CANVAS)) return 0;    // To increase speed. Not enabled by default.
3356
-
3357
-		// Clean parameters
3358
-		$ref = trim($ref);
3359
-
3360
-		$sql = "SELECT rowid, canvas";
3361
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3362
-		$sql.= " WHERE entity IN (".getEntity($this->element).")";
3363
-		if (! empty($id))  $sql.= " AND rowid = ".$id;
3364
-		if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
3365
-
3366
-		$resql = $this->db->query($sql);
3367
-		if ($resql)
3368
-		{
3369
-			$obj = $this->db->fetch_object($resql);
3370
-			if ($obj)
3371
-			{
3372
-				$this->canvas   = $obj->canvas;
3373
-				return 1;
3374
-			}
3375
-			else return 0;
3376
-		}
3377
-		else
3378
-		{
3379
-			dol_print_error($this->db);
3380
-			return -1;
3381
-		}
3382
-	}
3383
-
3384
-
3385
-	/**
3386
-	 * 	Get special code of a line
3387
-	 *
3388
-	 * 	@param	int		$lineid		Id of line
3389
-	 * 	@return	int					Special code
3390
-	 */
3391
-	function getSpecialCode($lineid)
3392
-	{
3393
-		$sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3394
-		$sql.= ' WHERE rowid = '.$lineid;
3395
-		$resql = $this->db->query($sql);
3396
-		if ($resql)
3397
-		{
3398
-			$row = $this->db->fetch_row($resql);
3399
-			return $row[0];
3400
-		}
3401
-	}
3402
-
3403
-	/**
3404
-	 *  Function to check if an object is used by others.
3405
-	 *  Check is done into this->childtables. There is no check into llx_element_element.
3406
-	 *
3407
-	 *  @param	int		$id			Force id of object
3408
-	 *  @return	int					<0 if KO, 0 if not used, >0 if already used
3409
-	 */
3410
-	function isObjectUsed($id=0)
3411
-	{
3412
-		global $langs;
3413
-
3414
-		if (empty($id)) $id=$this->id;
3415
-
3416
-		// Check parameters
3417
-		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3418
-		{
3419
-			dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3420
-			return -1;
3421
-		}
3422
-
3423
-		$arraytoscan = $this->childtables;
3424
-		// For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3425
-		$tmparray=array_keys($this->childtables);
3426
-		if (is_numeric($tmparray[0]))
3427
-		{
3428
-			$arraytoscan = array_flip($this->childtables);
3429
-		}
3430
-
3431
-		// Test if child exists
3432
-		$haschild=0;
3433
-		foreach($arraytoscan as $table => $elementname)
3434
-		{
3435
-			//print $id.'-'.$table.'-'.$elementname.'<br>';
3436
-			// Check if third party can be deleted
3437
-			$sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3438
-			$sql.= " WHERE ".$this->fk_element." = ".$id;
3439
-			$resql=$this->db->query($sql);
3440
-			if ($resql)
3441
-			{
3442
-				$obj=$this->db->fetch_object($resql);
3443
-				if ($obj->nb > 0)
3444
-				{
3445
-					$langs->load("errors");
3446
-					//print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3447
-					$haschild += $obj->nb;
3448
-					if (is_numeric($elementname))	// old usage
3449
-					{
3450
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3451
-					}
3452
-					else	// new usage: $elementname=Translation key
3453
-					{
3454
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3455
-					}
3456
-					break;    // We found at least one, we stop here
3457
-				}
3458
-			}
3459
-			else
3460
-			{
3461
-				$this->errors[]=$this->db->lasterror();
3462
-				return -1;
3463
-			}
3464
-		}
3465
-		if ($haschild > 0)
3466
-		{
3467
-			$this->errors[]="ErrorRecordHasChildren";
3468
-			return $haschild;
3469
-		}
3470
-		else return 0;
3471
-	}
3472
-
3473
-	/**
3474
-	 *  Function to say how many lines object contains
3475
-	 *
3476
-	 *	@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
3477
-	 *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3478
-	 */
3479
-	function hasProductsOrServices($predefined=-1)
3480
-	{
3481
-		$nb=0;
3482
-
3483
-		foreach($this->lines as $key => $val)
3484
-		{
3485
-			$qualified=0;
3486
-			if ($predefined == -1) $qualified=1;
3487
-			if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
3488
-			if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
3489
-			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
3490
-			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
3491
-			if ($qualified) $nb++;
3492
-		}
3493
-		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3494
-		return $nb;
3495
-	}
3496
-
3497
-	/**
3498
-	 * Function that returns the total amount HT of discounts applied for all lines.
3499
-	 *
3500
-	 * @return 	float
3501
-	 */
3502
-	function getTotalDiscount()
3503
-	{
3504
-		$total_discount=0.00;
3505
-
3506
-		$sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
3507
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3508
-		$sql.= " WHERE ".$this->fk_element." = ".$this->id;
3509
-
3510
-		dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3511
-		$resql = $this->db->query($sql);
3512
-		if ($resql)
3513
-		{
3514
-			$num=$this->db->num_rows($resql);
3515
-			$i=0;
3516
-			while ($i < $num)
3517
-			{
3518
-				$obj = $this->db->fetch_object($resql);
3519
-
3520
-				$pu_ht = $obj->pu_ht;
3521
-				$qty= $obj->qty;
3522
-				$total_ht = $obj->total_ht;
3523
-
3524
-				$total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
3525
-				$total_discount += $total_discount_line;
3526
-
3527
-				$i++;
3528
-			}
3529
-		}
3530
-
3531
-		//print $total_discount; exit;
3532
-		return price2num($total_discount);
3533
-	}
3534
-
3535
-
3536
-	/**
3537
-	 * Return into unit=0, the calculated total of weight and volume of all lines * qty
3538
-	 * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
3539
-	 *
3540
-	 * @return  array                           array('weight'=>...,'volume'=>...)
3541
-	 */
3542
-	function getTotalWeightVolume()
3543
-	{
3544
-		$totalWeight = 0;
3545
-		$totalVolume = 0;
3546
-		// defined for shipment only
3547
-		$totalOrdered = '';
3548
-		// defined for shipment only
3549
-		$totalToShip = '';
3550
-
3551
-		foreach ($this->lines as $line)
3552
-		{
3553
-			if (isset($line->qty_asked))
3554
-			{
3555
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3556
-				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3557
-			}
3558
-			if (isset($line->qty_shipped))
3559
-			{
3560
-				if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3561
-				$totalToShip+=$line->qty_shipped;   // defined for shipment only
3562
-            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
1022
+            return $tab;
1023
+        }
1024
+        else
1025
+        {
1026
+            $this->error=$this->db->lasterror();
1027
+            dol_print_error($this->db);
1028
+            return -1;
1029
+        }
1030
+    }
1031
+
1032
+
1033
+    /**
1034
+     * 		Update status of a contact linked to object
1035
+     *
1036
+     * 		@param	int		$rowid		Id of link between object and contact
1037
+     * 		@return	int					<0 if KO, >=0 if OK
1038
+     */
1039
+    function swapContactStatus($rowid)
1040
+    {
1041
+        $sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1042
+        $sql.= " tc.code, tc.libelle";
1043
+        //$sql.= ", s.fk_soc";
1044
+        $sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1045
+        //$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
1046
+        $sql.= " WHERE ec.rowid =".$rowid;
1047
+        $sql.= " AND ec.fk_c_type_contact=tc.rowid";
1048
+        $sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
1049
+
1050
+        dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1051
+        $resql=$this->db->query($sql);
1052
+        if ($resql)
1053
+        {
1054
+            $obj = $this->db->fetch_object($resql);
1055
+            $newstatut = ($obj->statut == 4) ? 5 : 4;
1056
+            $result = $this->update_contact($rowid, $newstatut);
1057
+            $this->db->free($resql);
1058
+            return $result;
1059
+        }
1060
+        else
1061
+        {
1062
+            $this->error=$this->db->error();
1063
+            dol_print_error($this->db);
1064
+            return -1;
1065
+        }
1066
+    }
1067
+
1068
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1069
+    /**
1070
+     *      Return array with list of possible values for type of contacts
1071
+     *
1072
+     *      @param	string	$source     'internal', 'external' or 'all'
1073
+     *      @param	string	$order		Sort order by : 'position', 'code', 'rowid'...
1074
+     *      @param  int		$option     0=Return array id->label, 1=Return array code->label
1075
+     *      @param  int		$activeonly 0=all status of contact, 1=only the active
1076
+     *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1077
+     *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1078
+     */
1079
+    function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1080
+    {
1081
+        // phpcs:enable
1082
+        global $langs;
1083
+
1084
+        if (empty($order)) $order='position';
1085
+        if ($order == 'position') $order.=',code';
1086
+
1087
+        $tab = array();
1088
+        $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1089
+        $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1090
+        $sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
1091
+        if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
1092
+        if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
1093
+        if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
1094
+        $sql.= $this->db->order($order,'ASC');
1095
+
1096
+        //print "sql=".$sql;
1097
+        $resql=$this->db->query($sql);
1098
+        if ($resql)
1099
+        {
1100
+            $num=$this->db->num_rows($resql);
1101
+            $i=0;
1102
+            while ($i < $num)
3563 1103
             {
3564
-                if (empty($totalToShip)) $totalToShip=0;
3565
-                $totalToShip+=$line->qty;   // defined for reception only
3566
-			}
3567
-
3568
-			// Define qty, weight, volume, weight_units, volume_units
3569
-			if ($this->element == 'shipping') {
3570
-				// for shipments
3571
-				$qty = $line->qty_shipped ? $line->qty_shipped : 0;
3572
-			}
3573
-			else {
3574
-				$qty = $line->qty ? $line->qty : 0;
3575
-			}
3576
-
3577
-			$weight = $line->weight ? $line->weight : 0;
3578
-            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3579
-			$volume = $line->volume ? $line->volume : 0;
3580
-			($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
1104
+                $obj = $this->db->fetch_object($resql);
3581 1105
 
3582
-			$weight_units=$line->weight_units;
3583
-			($weight_units==0 && !empty($line->product->weight_units))? $weight_units=$line->product->weight_units: 0;
3584
-			$volume_units=$line->volume_units;
3585
-			($volume_units==0 && !empty($line->product->volume_units))? $volume_units=$line->product->volume_units: 0;
1106
+                $transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1107
+                $libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1108
+                if (empty($option)) $tab[$obj->rowid]=$libelle_type;
1109
+                else $tab[$obj->code]=$libelle_type;
1110
+                $i++;
1111
+            }
1112
+            return $tab;
1113
+        }
1114
+        else
1115
+        {
1116
+            $this->error=$this->db->lasterror();
1117
+            //dol_print_error($this->db);
1118
+            return null;
1119
+        }
1120
+    }
3586 1121
 
3587
-			$weightUnit=0;
3588
-			$volumeUnit=0;
3589
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3590
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
1122
+    /**
1123
+     *      Return id of contacts for a source and a contact code.
1124
+     *      Example: contact client de facturation ('external', 'BILLING')
1125
+     *      Example: contact client de livraison ('external', 'SHIPPING')
1126
+     *      Example: contact interne suivi paiement ('internal', 'SALESREPFOLL')
1127
+     *
1128
+     *		@param	string	$source		'external' or 'internal'
1129
+     *		@param	string	$code		'BILLING', 'SHIPPING', 'SALESREPFOLL', ...
1130
+     *		@param	int		$status		limited to a certain status
1131
+     *      @return array       		List of id for such contacts
1132
+     */
1133
+    function getIdContact($source,$code,$status=0)
1134
+    {
1135
+        global $conf;
3591 1136
 
3592
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3593
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
1137
+        $result=array();
1138
+        $i=0;
1139
+        //cas particulier pour les expeditions
1140
+        if($this->element=='shipping' && $this->origin_id != 0) {
1141
+            $id=$this->origin_id;
1142
+            $element='commande';
1143
+        } else if($this->element=='reception' && $this->origin_id != 0) {
1144
+            $id=$this->origin_id;
1145
+            $element='order_supplier';
1146
+        } else {
1147
+            $id=$this->id;
1148
+            $element=$this->element;
1149
+        }
3594 1150
 
3595
-			//var_dump($line->volume_units);
3596
-			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3597
-			{
3598
-				$trueWeightUnit=pow(10, $weightUnit);
3599
-				$totalWeight += $weight * $qty * $trueWeightUnit;
3600
-			}
3601
-			else {
3602
-		if ($weight_units == 99) {
3603
-			// conversion 1 Pound = 0.45359237 KG
3604
-			$trueWeightUnit = 0.45359237;
3605
-			$totalWeight += $weight * $qty * $trueWeightUnit;
3606
-		} elseif ($weight_units == 98) {
3607
-			// conversion 1 Ounce = 0.0283495 KG
3608
-			$trueWeightUnit = 0.0283495;
3609
-			$totalWeight += $weight * $qty * $trueWeightUnit;
3610
-		}
3611
-		else
3612
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3613
-			}
3614
-			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3615
-			{
3616
-				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3617
-				$trueVolumeUnit=pow(10, $volumeUnit);
3618
-				//print $line->volume;
3619
-				$totalVolume += $volume * $qty * $trueVolumeUnit;
3620
-			}
3621
-			else
3622
-			{
3623
-				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3624
-			}
3625
-		}
3626
-
3627
-		return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
3628
-	}
3629
-
3630
-
3631
-	/**
3632
-	 *	Set extra parameters
3633
-	 *
3634
-	 *	@return	int      <0 if KO, >0 if OK
3635
-	 */
3636
-	function setExtraParameters()
3637
-	{
3638
-		$this->db->begin();
3639
-
3640
-		$extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3641
-
3642
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3643
-		$sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3644
-		$sql.= " WHERE rowid = ".$this->id;
3645
-
3646
-		dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3647
-		$resql = $this->db->query($sql);
3648
-		if (! $resql)
3649
-		{
3650
-			$this->error=$this->db->lasterror();
3651
-			$this->db->rollback();
3652
-			return -1;
3653
-		}
3654
-		else
3655
-		{
3656
-			$this->db->commit();
3657
-			return 1;
3658
-		}
3659
-	}
1151
+        $sql = "SELECT ec.fk_socpeople";
1152
+        $sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1153
+        if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
1154
+        if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1155
+        $sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1156
+        $sql.= " WHERE ec.element_id = ".$id;
1157
+        $sql.= " AND ec.fk_socpeople = c.rowid";
1158
+        if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
1159
+        if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
1160
+        $sql.= " AND ec.fk_c_type_contact = tc.rowid";
1161
+        $sql.= " AND tc.element = '".$element."'";
1162
+        $sql.= " AND tc.source = '".$source."'";
1163
+        $sql.= " AND tc.code = '".$code."'";
1164
+        $sql.= " AND tc.active = 1";
1165
+        if ($status) $sql.= " AND ec.statut = ".$status;
1166
+
1167
+        dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1168
+        $resql=$this->db->query($sql);
1169
+        if ($resql)
1170
+        {
1171
+            while ($obj = $this->db->fetch_object($resql))
1172
+            {
1173
+                $result[$i]=$obj->fk_socpeople;
1174
+                $i++;
1175
+            }
1176
+        }
1177
+        else
1178
+        {
1179
+            $this->error=$this->db->error();
1180
+            return null;
1181
+        }
3660 1182
 
1183
+        return $result;
1184
+    }
3661 1185
 
3662 1186
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3663
-	/**
3664
-	 *    Return incoterms informations
3665
-	 *    TODO Use a cache for label get
3666
-	 *
3667
-	 *    @return	string	incoterms info
3668
-	 */
3669
-	function display_incoterms()
3670
-	{
1187
+    /**
1188
+     *		Load object contact with id=$this->contactid into $this->contact
1189
+     *
1190
+     *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1191
+     *		@return	int						<0 if KO, >0 if OK
1192
+     */
1193
+    function fetch_contact($contactid=null)
1194
+    {
3671 1195
         // phpcs:enable
3672
-		$out = '';
3673
-		$this->libelle_incoterms = '';
3674
-		if (!empty($this->fk_incoterms))
3675
-		{
3676
-			$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3677
-			$result = $this->db->query($sql);
3678
-			if ($result)
3679
-			{
3680
-				$res = $this->db->fetch_object($result);
3681
-				$out .= $res->code;
3682
-			}
3683
-		}
3684
-
3685
-		$out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3686
-
3687
-		return $out;
3688
-	}
3689
-
3690
-	/**
3691
-	 *    Return incoterms informations for pdf display
3692
-	 *
3693
-	 *    @return	string		incoterms info
3694
-	 */
3695
-	function getIncotermsForPDF()
3696
-	{
3697
-		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3698
-		$resql = $this->db->query($sql);
3699
-		if ($resql)
3700
-		{
3701
-			$num = $this->db->num_rows($resql);
3702
-			if ($num > 0)
3703
-			{
3704
-				$res = $this->db->fetch_object($resql);
3705
-				return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3706
-			}
3707
-			else
3708
-			{
3709
-				return '';
3710
-			}
3711
-		}
3712
-		else
3713
-		{
3714
-			$this->errors[] = $this->db->lasterror();
3715
-			return false;
3716
-		}
3717
-	}
3718
-
3719
-	/**
3720
-	 *    Define incoterms values of current object
3721
-	 *
3722
-	 *    @param	int		$id_incoterm     Id of incoterm to set or '' to remove
3723
-	 * 	  @param 	string  $location		 location of incoterm
3724
-	 *    @return	int     		<0 if KO, >0 if OK
3725
-	 */
3726
-	function setIncoterms($id_incoterm, $location)
3727
-	{
3728
-		if ($this->id && $this->table_element)
3729
-		{
3730
-			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3731
-			$sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3732
-			$sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3733
-			$sql.= " WHERE rowid = " . $this->id;
3734
-			dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3735
-			$resql=$this->db->query($sql);
3736
-			if ($resql)
3737
-			{
3738
-				$this->fk_incoterms = $id_incoterm;
3739
-				$this->location_incoterms = $location;
1196
+        if (empty($contactid)) $contactid=$this->contactid;
3740 1197
 
3741
-				$sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3742
-				$res = $this->db->query($sql);
3743
-				if ($res)
3744
-				{
3745
-					$obj = $this->db->fetch_object($res);
3746
-					$this->libelle_incoterms = $obj->libelle;
3747
-				}
3748
-				return 1;
3749
-			}
3750
-			else
3751
-			{
3752
-				$this->errors[] = $this->db->lasterror();
3753
-				return -1;
3754
-			}
3755
-		}
3756
-		else return -1;
3757
-	}
3758
-
3759
-
3760
-	// --------------------
3761
-	// TODO: All functions here must be redesigned and moved as they are not business functions but output functions
3762
-	// --------------------
3763
-
3764
-	/* This is to show add lines */
3765
-
3766
-	/**
3767
-	 *	Show add free and predefined products/services form
3768
-	 *
3769
-	 *  @param	int		        $dateSelector       1=Show also date range input fields
3770
-	 *  @param	Societe			$seller				Object thirdparty who sell
3771
-	 *  @param	Societe			$buyer				Object thirdparty who buy
3772
-	 *	@return	void
3773
-	 */
3774
-	function formAddObjectLine($dateSelector, $seller, $buyer)
3775
-	{
3776
-		global $conf,$user,$langs,$object,$hookmanager;
3777
-		global $form,$bcnd,$var;
3778
-
3779
-		// Line extrafield
3780
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3781
-		$extrafieldsline = new ExtraFields($this->db);
3782
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3783
-
3784
-		// Output template part (modules that overwrite templates must declare this into descriptor)
3785
-		// Use global variables + $dateSelector + $seller and $buyer
3786
-		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
3787
-		foreach($dirtpls as $reldir)
3788
-		{
3789
-			$tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3790
-			if (empty($conf->file->strict_mode)) {
3791
-				$res=@include $tpl;
3792
-			} else {
3793
-				$res=include $tpl; // for debug
3794
-			}
3795
-			if ($res) break;
3796
-		}
3797
-	}
3798
-
3799
-
3800
-
3801
-	/* This is to show array of line of details */
3802
-
3803
-
3804
-	/**
3805
-	 *	Return HTML table for object lines
3806
-	 *	TODO Move this into an output class file (htmlline.class.php)
3807
-	 *	If lines are into a template, title must also be into a template
3808
-	 *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
3809
-	 *
3810
-	 *	@param	string		$action				Action code
3811
-	 *	@param  string		$seller            	Object of seller third party
3812
-	 *	@param  string  	$buyer             	Object of buyer third party
3813
-	 *	@param	int			$selected		   	Object line selected
3814
-	 *	@param  int	    	$dateSelector      	1=Show also date range input fields
3815
-	 *	@return	void
3816
-	 */
3817
-	function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3818
-	{
3819
-		global $conf, $hookmanager, $langs, $user;
3820
-		// TODO We should not use global var for this !
3821
-		global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3822
-
3823
-		// Define usemargins
3824
-		$usemargins=0;
3825
-		if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
3826
-
3827
-		$num = count($this->lines);
3828
-
3829
-		// Line extrafield
3830
-		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3831
-		$extrafieldsline = new ExtraFields($this->db);
3832
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3833
-
3834
-		$parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3835
-		$reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3836
-		if (empty($reshook))
3837
-		{
3838
-			// Title line
3839
-		    print "<thead>\n";
3840
-
3841
-			print '<tr class="liste_titre nodrag nodrop">';
3842
-
3843
-			// Adds a line numbering column
3844
-			if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
3845
-
3846
-			// Description
3847
-			print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
3848
-
3849
-			if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier')
3850
-			{
3851
-				print '<td class="linerefsupplier"><span id="title_fourn_ref">'.$langs->trans("SupplierRef").'</span></td>';
3852
-			}
1198
+        if (empty($contactid)) return 0;
3853 1199
 
3854
-			// VAT
3855
-			print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
1200
+        require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1201
+        $contact = new Contact($this->db);
1202
+        $result=$contact->fetch($contactid);
1203
+        $this->contact = $contact;
1204
+        return $result;
1205
+    }
3856 1206
 
3857
-			// Price HT
3858
-			print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
1207
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1208
+    /**
1209
+     *    	Load the third party of object, from id $this->socid or $this->fk_soc, into this->thirdparty
1210
+     *
1211
+     *		@param		int		$force_thirdparty_id	Force thirdparty id
1212
+     *		@return		int								<0 if KO, >0 if OK
1213
+     */
1214
+    function fetch_thirdparty($force_thirdparty_id=0)
1215
+    {
1216
+        // phpcs:enable
1217
+        global $conf;
3859 1218
 
3860
-			// Multicurrency
3861
-			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
1219
+        if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1220
+            return 0;
3862 1221
 
3863
-			if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
1222
+        require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
3864 1223
 
3865
-			// Qty
3866
-			print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
1224
+        $idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1225
+        if ($force_thirdparty_id)
1226
+            $idtofetch = $force_thirdparty_id;
3867 1227
 
3868
-			if($conf->global->PRODUCT_USE_UNITS)
3869
-			{
3870
-				print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
3871
-			}
1228
+        if ($idtofetch) {
1229
+            $thirdparty = new Societe($this->db);
1230
+            $result = $thirdparty->fetch($idtofetch);
1231
+            $this->thirdparty = $thirdparty;
3872 1232
 
3873
-			// Reduction short
3874
-			print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
1233
+            // Use first price level if level not defined for third party
1234
+            if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->thirdparty->price_level)) {
1235
+                $this->thirdparty->price_level = 1;
1236
+            }
3875 1237
 
3876
-			if ($this->situation_cycle_ref) {
3877
-				print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3878
-			}
1238
+            return $result;
1239
+        } else
1240
+            return -1;
1241
+    }
3879 1242
 
3880
-			if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
3881
-			{
3882
-				if (!empty($user->rights->margins->creer))
3883
-				{
3884
-					if ($conf->global->MARGIN_TYPE == "1")
3885
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3886
-					else
3887
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
3888
-				}
3889 1243
 
3890
-				if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3891
-					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3892
-				if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3893
-					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
3894
-			}
1244
+    /**
1245
+     * Looks for an object with ref matching the wildcard provided
1246
+     * It does only work when $this->table_ref_field is set
1247
+     *
1248
+     * @param string $ref Wildcard
1249
+     * @return int >1 = OK, 0 = Not found or table_ref_field not defined, <0 = KO
1250
+     */
1251
+    public function fetchOneLike($ref)
1252
+    {
1253
+        if (!$this->table_ref_field) {
1254
+            return 0;
1255
+        }
3895 1256
 
3896
-			// Total HT
3897
-			print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
1257
+        $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE '.$this->table_ref_field.' LIKE "'.$this->db->escape($ref).'" LIMIT 1';
3898 1258
 
3899
-			// Multicurrency
3900
-			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
1259
+        $query = $this->db->query($sql);
3901 1260
 
3902
-			if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
1261
+        if (!$this->db->num_rows($query)) {
1262
+            return 0;
1263
+        }
3903 1264
 
3904
-			print '<td class="linecoledit"></td>';  // No width to allow autodim
1265
+        $result = $this->db->fetch_object($query);
3905 1266
 
3906
-			print '<td class="linecoldelete" width="10"></td>';
1267
+        return $this->fetch($result->rowid);
1268
+    }
3907 1269
 
3908
-			print '<td class="linecolmove" width="10"></td>';
1270
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
1271
+    /**
1272
+     *	Load data for barcode into properties ->barcode_type*
1273
+     *	Properties ->barcode_type that is id of barcode. Type is used to find other properties, but
1274
+     *  if it is not defined, ->element must be defined to know default barcode type.
1275
+     *
1276
+     *	@return		int			<0 if KO, 0 if can't guess type of barcode (ISBN, EAN13...), >0 if OK (all barcode properties loaded)
1277
+     */
1278
+    function fetch_barcode()
1279
+    {
1280
+        // phpcs:enable
1281
+        global $conf;
3909 1282
 
3910
-			if($action == 'selectlines')
3911
-			{
3912
-			    print '<td class="linecolcheckall" align="center">';
3913
-			    print '<input type="checkbox" class="linecheckboxtoggle" />';
3914
-			    print '<script type="text/javascript">$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
3915
-			    print '</td>';
3916
-			}
3917
-
3918
-			print "</tr>\n";
3919
-			print "</thead>\n";
3920
-		}
3921
-
3922
-		$var = true;
3923
-		$i	 = 0;
3924
-
3925
-		print "<tbody>\n";
3926
-		foreach ($this->lines as $line)
3927
-		{
3928
-			//Line extrafield
3929
-			$line->fetch_optionals();
3930
-
3931
-			//if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3932
-			if (is_object($hookmanager))   // Old code is commented on preceding line.
3933
-			{
3934
-				if (empty($line->fk_parent_line))
3935
-				{
3936
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3937
-					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3938
-				}
3939
-				else
3940
-				{
3941
-					$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);
3942
-					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3943
-				}
3944
-			}
3945
-			if (empty($reshook))
3946
-			{
3947
-				$this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3948
-			}
3949
-
3950
-			$i++;
3951
-		}
3952
-		print "</tbody>\n";
3953
-	}
3954
-
3955
-	/**
3956
-	 *	Return HTML content of a detail line
3957
-	 *	TODO Move this into an output class file (htmlline.class.php)
3958
-	 *
3959
-	 *	@param	string		$action				GET/POST action
3960
-	 *	@param CommonObjectLine $line		       	Selected object line to output
3961
-	 *	@param  string	    $var               	Is it a an odd line (true)
3962
-	 *	@param  int		    $num               	Number of line (0)
3963
-	 *	@param  int		    $i					I
3964
-	 *	@param  int		    $dateSelector      	1=Show also date range input fields
3965
-	 *	@param  string	    $seller            	Object of seller third party
3966
-	 *	@param  string	    $buyer             	Object of buyer third party
3967
-	 *	@param	int			$selected		   	Object line selected
3968
-	 *  @param  int			$extrafieldsline	Object of extrafield line attribute
3969
-	 *	@return	void
3970
-	 */
3971
-	function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
3972
-	{
3973
-		global $conf,$langs,$user,$object,$hookmanager;
3974
-		global $form,$bc,$bcdd;
3975
-		global $object_rights, $disableedit, $disablemove, $disableremove;   // TODO We should not use global var for this !
3976
-
3977
-		$object_rights = $this->getRights();
3978
-
3979
-		$element=$this->element;
3980
-
3981
-		$text=''; $description=''; $type=0;
3982
-
3983
-		// Show product and description
3984
-		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3985
-		// Try to enhance type detection using date_start and date_end for free lines where type was not saved.
3986
-		if (! empty($line->date_start)) $type=1; // deprecated
3987
-		if (! empty($line->date_end)) $type=1; // deprecated
3988
-
3989
-		// Ligne en mode visu
3990
-		if ($action != 'editline' || $selected != $line->id)
3991
-		{
3992
-			// Product
3993
-			if ($line->fk_product > 0)
3994
-			{
3995
-				$product_static = new Product($this->db);
3996
-				$product_static->fetch($line->fk_product);
1283
+        dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
3997 1284
 
3998
-				$product_static->ref = $line->ref; //can change ref in hook
3999
-				$product_static->label = $line->label; //can change label in hook
4000
-				$text=$product_static->getNomUrl(1);
1285
+        $idtype=$this->barcode_type;
1286
+        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
1287
+        {
1288
+            if ($this->element == 'product')      $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1289
+            else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1290
+            else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1291
+        }
4001 1292
 
4002
-				// Define output language and label
4003
-				if (! empty($conf->global->MAIN_MULTILANGS))
4004
-				{
4005
-					if (! is_object($this->thirdparty))
4006
-					{
4007
-						dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4008
-						return;
4009
-					}
4010
-
4011
-					$prod = new Product($this->db);
4012
-					$prod->fetch($line->fk_product);
4013
-
4014
-					$outputlangs = $langs;
4015
-					$newlang='';
4016
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
4017
-					if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang;		// For language to language of customer
4018
-					if (! empty($newlang))
4019
-					{
4020
-						$outputlangs = new Translate("",$conf);
4021
-						$outputlangs->setDefaultLang($newlang);
4022
-					}
4023
-
4024
-					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4025
-				}
4026
-				else
4027
-				{
4028
-					$label = $line->product_label;
4029
-				}
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
+    }
4030 1320
 
4031
-				$text.= ' - '.(! empty($line->label)?$line->label:$label);
4032
-				$description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description));	// Description is what to show on popup. We shown nothing if already into desc.
4033
-			}
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';
4034 1331
 
4035
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
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;
4036 1334
 
4037
-			// Output template part (modules that overwrite templates must declare this into descriptor)
4038
-			// Use global variables + $dateSelector + $seller and $buyer
4039
-			$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4040
-			foreach($dirtpls as $reldir)
4041
-			{
4042
-				$tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4043
-				if (empty($conf->file->strict_mode)) {
4044
-					$res=@include $tpl;
4045
-				} else {
4046
-					$res=include $tpl; // for debug
4047
-				}
4048
-				if ($res) break;
4049
-			}
4050
-		}
4051
-
4052
-		// Ligne en mode update
4053
-		if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4054
-		{
4055
-			$label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4056
-			$placeholder=' placeholder="'.$langs->trans("Label").'"';
4057
-
4058
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4059
-
4060
-			// Output template part (modules that overwrite templates must declare this into descriptor)
4061
-			// Use global variables + $dateSelector + $seller and $buyer
4062
-			$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4063
-			foreach($dirtpls as $reldir)
4064
-			{
4065
-				$tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4066
-				if (empty($conf->file->strict_mode)) {
4067
-					$res=@include $tpl;
4068
-				} else {
4069
-					$res=include $tpl; // for debug
4070
-				}
4071
-				if ($res) break;
4072
-			}
4073
-		}
4074
-	}
4075
-
4076
-
4077
-	/* This is to show array of line of details of source object */
4078
-
4079
-
4080
-	/**
4081
-	 * 	Return HTML table table of source object lines
4082
-	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
4083
-	 *  If lines are into a template, title must also be into a template
4084
-	 *  But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
4085
-	 *
4086
-	 *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4087
-	 *  @return	void
4088
-	 */
4089
-	function printOriginLinesList($restrictlist='')
4090
-	{
4091
-		global $langs, $hookmanager, $conf;
4092
-
4093
-		print '<tr class="liste_titre">';
4094
-		print '<td>'.$langs->trans('Ref').'</td>';
4095
-		print '<td>'.$langs->trans('Description').'</td>';
4096
-		print '<td align="right">'.$langs->trans('VATRate').'</td>';
4097
-		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4098
-		if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4099
-		print '<td align="right">'.$langs->trans('Qty').'</td>';
4100
-		if($conf->global->PRODUCT_USE_UNITS)
4101
-		{
4102
-			print '<td align="left">'.$langs->trans('Unit').'</td>';
4103
-		}
4104
-		print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
4105
-
4106
-		$var = true;
4107
-		$i	 = 0;
4108
-
4109
-		if (! empty($this->lines))
4110
-		{
4111
-			foreach ($this->lines as $line)
4112
-			{
4113
-				if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4114
-				{
4115
-					if (empty($line->fk_parent_line))
4116
-					{
4117
-						$parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
4118
-						$action='';
4119
-						$hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4120
-					}
4121
-				}
4122
-				else
4123
-				{
4124
-					$this->printOriginLine($line, $var, $restrictlist);
4125
-				}
1335
+        $project = new Project($this->db);
1336
+        $result = $project->fetch($this->fk_project);
4126 1337
 
4127
-				$i++;
4128
-			}
4129
-		}
4130
-	}
4131
-
4132
-	/**
4133
-	 * 	Return HTML with a line of table array of source object lines
4134
-	 *  TODO Move this and previous function into output html class file (htmlline.class.php).
4135
-	 *  If lines are into a template, title must also be into a template
4136
-	 *  But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
4137
-	 *
4138
-	 * 	@param	CommonObjectLine	$line				Line
4139
-	 * 	@param	string				$var				Var
4140
-	 *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4141
-	 * 	@return	void
4142
-	 */
4143
-	function printOriginLine($line, $var, $restrictlist='')
4144
-	{
4145
-		global $langs, $conf;
4146
-
4147
-		//var_dump($line);
4148
-		if (!empty($line->date_start))
4149
-		{
4150
-			$date_start=$line->date_start;
4151
-		}
4152
-		else
4153
-		{
4154
-			$date_start=$line->date_debut_prevue;
4155
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4156
-		}
4157
-		if (!empty($line->date_end))
4158
-		{
4159
-			$date_end=$line->date_end;
4160
-		}
4161
-		else
4162
-		{
4163
-			$date_end=$line->date_fin_prevue;
4164
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4165
-		}
4166
-
4167
-		$this->tpl['label'] = '';
4168
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4169
-
4170
-		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4171
-		{
4172
-			$discount=new DiscountAbsolute($this->db);
4173
-			$discount->fk_soc = $this->socid;
4174
-			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4175
-		}
4176
-		else if (! empty($line->fk_product))
4177
-		{
4178
-			$productstatic = new Product($this->db);
4179
-			$productstatic->id = $line->fk_product;
4180
-			$productstatic->ref = $line->ref;
4181
-			$productstatic->type = $line->fk_product_type;
4182
-            if(empty($productstatic->ref)){
4183
-				$line->fetch_product();
4184
-				$productstatic = $line->product;
4185
-			}
4186
-			
4187
-			$this->tpl['label'].= $productstatic->getNomUrl(1);
4188
-			$this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4189
-			// Dates
4190
-			if ($line->product_type == 1 && ($date_start || $date_end))
4191
-			{
4192
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4193
-			}
4194
-		}
4195
-		else
4196
-		{
4197
-			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4198
-			if (!empty($line->desc)) {
4199
-				$this->tpl['label'].=$line->desc;
4200
-			}else {
4201
-				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4202
-			}
4203
-			
4204
-			// Dates
4205
-			if ($line->product_type == 1 && ($date_start || $date_end))
4206
-			{
4207
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4208
-			}
4209
-		}
1338
+        $this->projet = $project;	// deprecated
1339
+        $this->project = $project;
1340
+        return $result;
1341
+    }
4210 1342
 
4211
-		if (! empty($line->desc))
4212
-		{
4213
-			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4214
-			{
4215
-				$discount=new DiscountAbsolute($this->db);
4216
-				$discount->fetch($line->fk_remise_except);
4217
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4218
-			}
4219
-			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4220
-			{
4221
-				$discount=new DiscountAbsolute($this->db);
4222
-				$discount->fetch($line->fk_remise_except);
4223
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4224
-			}
4225
-			elseif ($line->desc == '(EXCESS RECEIVED)')
4226
-			{
4227
-				$discount=new DiscountAbsolute($this->db);
4228
-				$discount->fetch($line->fk_remise_except);
4229
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4230
-			}
4231
-			elseif ($line->desc == '(EXCESS PAID)')
4232
-			{
4233
-				$discount=new DiscountAbsolute($this->db);
4234
-				$discount->fetch($line->fk_remise_except);
4235
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4236
-			}
4237
-			else
4238
-			{
4239
-				$this->tpl['description'] = dol_trunc($line->desc,60);
4240
-			}
4241
-		}
4242
-		else
4243
-		{
4244
-			$this->tpl['description'] = '&nbsp;';
4245
-		}
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';
4246 1353
 
4247
-        // VAT Rate
4248
-        $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4249
-        $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
4250
-        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
1354
+        if (empty($this->fk_product)) return 0;
4251 1355
 
4252
-		$this->tpl['price'] = price($line->subprice);
4253
-		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4254
-		$this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4255
-		if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4256
-		$this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4257
-
4258
-		// Is the line strike or not
4259
-		$this->tpl['strike']=0;
4260
-		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4261
-
4262
-		// Output template part (modules that overwrite templates must declare this into descriptor)
4263
-		// Use global variables + $dateSelector + $seller and $buyer
4264
-		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4265
-		foreach($dirtpls as $reldir)
4266
-		{
4267
-			$tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4268
-			if (empty($conf->file->strict_mode)) {
4269
-				$res=@include $tpl;
4270
-			} else {
4271
-				$res=include $tpl; // for debug
4272
-			}
4273
-			if ($res) break;
4274
-		}
4275
-	}
1356
+        $product = new Product($this->db);
1357
+        $result = $product->fetch($this->fk_product);
4276 1358
 
1359
+        $this->product = $product;
1360
+        return $result;
1361
+    }
4277 1362
 
4278 1363
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4279
-	/**
4280
-	 *	Add resources to the current object : add entry into llx_element_resources
4281
-	 *	Need $this->element & $this->id
4282
-	 *
4283
-	 *	@param		int		$resource_id		Resource id
4284
-	 *	@param		string	$resource_type		'resource'
4285
-	 *	@param		int		$busy				Busy or not
4286
-	 *	@param		int		$mandatory			Mandatory or not
4287
-	 *	@return		int							<=0 if KO, >0 if OK
4288
-	 */
4289
-	function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4290
-	{
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
+    {
4291 1372
         // phpcs:enable
4292
-		$this->db->begin();
4293
-
4294
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
4295
-		$sql.= "resource_id";
4296
-		$sql.= ", resource_type";
4297
-		$sql.= ", element_id";
4298
-		$sql.= ", element_type";
4299
-		$sql.= ", busy";
4300
-		$sql.= ", mandatory";
4301
-		$sql.= ") VALUES (";
4302
-		$sql.= $resource_id;
4303
-		$sql.= ", '".$this->db->escape($resource_type)."'";
4304
-		$sql.= ", '".$this->db->escape($this->id)."'";
4305
-		$sql.= ", '".$this->db->escape($this->element)."'";
4306
-		$sql.= ", '".$this->db->escape($busy)."'";
4307
-		$sql.= ", '".$this->db->escape($mandatory)."'";
4308
-		$sql.= ")";
4309
-
4310
-		dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4311
-		if ($this->db->query($sql))
4312
-		{
4313
-			$this->db->commit();
4314
-			return 1;
4315
-		}
4316
-		else
4317
-		{
4318
-			$this->error=$this->db->lasterror();
4319
-			$this->db->rollback();
4320
-			return  0;
4321
-		}
4322
-	}
1373
+        $user = new User($this->db);
1374
+        $result=$user->fetch($userid);
1375
+        $this->user = $user;
1376
+        return $result;
1377
+    }
4323 1378
 
4324 1379
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4325
-	/**
4326
-	 *    Delete a link to resource line
4327
-	 *
4328
-	 *    @param	int		$rowid			Id of resource line to delete
4329
-	 *    @param	int		$element		element name (for trigger) TODO: use $this->element into commonobject class
4330
-	 *    @param	int		$notrigger		Disable all triggers
4331
-	 *    @return   int						>0 if OK, <0 if KO
4332
-	 */
4333
-	function delete_resource($rowid, $element, $notrigger=0)
4334
-	{
1380
+    /**
1381
+     *	Read linked origin object
1382
+     *
1383
+     *	@return		void
1384
+     */
1385
+    function fetch_origin()
1386
+    {
4335 1387
         // phpcs:enable
4336
-		global $user;
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';
4337 1391
 
4338
-		$this->db->begin();
1392
+        $origin = $this->origin;
4339 1393
 
4340
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4341
-		$sql.= " WHERE rowid=".$rowid;
1394
+        $classname = ucfirst($origin);
1395
+        $this->$origin = new $classname($this->db);
1396
+        $this->$origin->fetch($this->origin_id);
1397
+    }
4342 1398
 
4343
-		dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
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;
4344 1411
 
4345
-		$resql=$this->db->query($sql);
4346
-		if (! $resql)
4347
-		{
4348
-			$this->error=$this->db->lasterror();
4349
-			$this->db->rollback();
4350
-			return -1;
4351
-		}
4352
-		else
4353
-		{
4354
-			if (! $notrigger)
4355
-			{
4356
-				$result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4357
-				if ($result < 0) { $this->db->rollback(); return -1; }
4358
-			}
4359
-			$this->db->commit();
4360
-			return 1;
4361
-		}
4362
-	}
4363
-
4364
-
4365
-	/**
4366
-	 * Overwrite magic function to solve problem of cloning object that are kept as references
4367
-	 *
4368
-	 * @return void
4369
-	 */
4370
-	function __clone()
4371
-	{
4372
-		// Force a copy of this->lines, otherwise it will point to same object.
4373
-		if (isset($this->lines) && is_array($this->lines))
4374
-		{
4375
-			$nboflines=count($this->lines);
4376
-			for($i=0; $i < $nboflines; $i++)
4377
-			{
4378
-				$this->lines[$i] = clone $this->lines[$i];
4379
-			}
4380
-		}
4381
-	}
4382
-
4383
-	/**
4384
-	 * Common function for all objects extending CommonObject for generating documents
4385
-	 *
4386
-	 * @param 	string 		$modelspath 	Relative folder where generators are placed
4387
-	 * @param 	string 		$modele 		Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
4388
-	 * @param 	Translate 	$outputlangs 	Output language to use
4389
-	 * @param 	int 		$hidedetails 	1 to hide details. 0 by default
4390
-	 * @param 	int 		$hidedesc 		1 to hide product description. 0 by default
4391
-	 * @param 	int 		$hideref 		1 to hide product reference. 0 by default
4392
-	 * @param   null|array  $moreparams     Array to provide more information
4393
-	 * @return 	int 						>0 if OK, <0 if KO
4394
-	 * @see	addFileIntoDatabaseIndex
4395
-	 */
4396
-	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4397
-	{
4398
-		global $conf, $langs, $user;
4399
-
4400
-		$srctemplatepath='';
4401
-
4402
-		// Increase limit for PDF build
4403
-		$err=error_reporting();
4404
-		error_reporting(0);
4405
-		@set_time_limit(120);
4406
-		error_reporting($err);
4407
-
4408
-		// If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4409
-		$tmp=explode(':',$modele,2);
4410
-		if (! empty($tmp[1]))
4411
-		{
4412
-			$modele=$tmp[0];
4413
-			$srctemplatepath=$tmp[1];
4414
-		}
4415
-
4416
-		// Search template files
4417
-		$file=''; $classname=''; $filefound=0;
4418
-		$dirmodels=array('/');
4419
-		if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
4420
-		foreach($dirmodels as $reldir)
4421
-		{
4422
-			foreach(array('doc','pdf') as $prefix)
4423
-			{
4424
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4425
-				else $file = $prefix."_".$modele.".modules.php";
1412
+        $result=false;
4426 1413
 
4427
-				// On verifie l'emplacement du modele
4428
-				$file=dol_buildpath($reldir.$modelspath.$file,0);
4429
-				if (file_exists($file))
4430
-				{
4431
-					$filefound=1;
4432
-					$classname=$prefix.'_'.$modele;
4433
-					break;
4434
-				}
4435
-			}
4436
-			if ($filefound) break;
4437
-		}
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 = ".$conf->entity;
1420
+        }
4438 1421
 
4439
-		// If generator was found
4440
-		if ($filefound)
4441
-		{
4442
-			global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
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
+        }
4443 1432
 
4444
-			require_once $file;
1433
+        return $result;
1434
+    }
4445 1435
 
4446
-			$obj = new $classname($this->db);
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
+    }
4447 1461
 
4448
-			// If generator is ODT, we must have srctemplatepath defined, if not we set it.
4449
-			if ($obj->type == 'odt' && empty($srctemplatepath))
4450
-			{
4451
-				$varfortemplatedir=$obj->scandir;
4452
-				if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
4453
-				{
4454
-					$dirtoscan=$conf->global->$varfortemplatedir;
4455
-
4456
-					$listoffiles=array();
4457
-
4458
-					// Now we add first model found in directories scanned
4459
-					$listofdir=explode(',',$dirtoscan);
4460
-					foreach($listofdir as $key => $tmpdir)
4461
-					{
4462
-						$tmpdir=trim($tmpdir);
4463
-						$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4464
-						if (! $tmpdir) { unset($listofdir[$key]); continue; }
4465
-						if (is_dir($tmpdir))
4466
-						{
4467
-							$tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4468
-							if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4469
-						}
4470
-					}
4471
-
4472
-					if (count($listoffiles))
4473
-					{
4474
-						foreach($listoffiles as $record)
4475
-						{
4476
-							$srctemplatepath=$record['fullname'];
4477
-							break;
4478
-						}
4479
-					}
4480
-				}
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;
4481 1481
 
4482
-				if (empty($srctemplatepath))
4483
-				{
4484
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4485
-					return -1;
4486
-				}
4487
-			}
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';
4488 1486
 
4489
-			if ($obj->type == 'odt' && ! empty($srctemplatepath))
4490
-			{
4491
-				if (! dol_is_file($srctemplatepath))
4492
-				{
4493
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4494
-					return -1;
4495
-				}
4496
-			}
1487
+        $error=0;
4497 1488
 
4498
-			// We save charset_output to restore it because write_file can change it if needed for
4499
-			// output format that does not support UTF8.
4500
-			$sav_charset_output=$outputlangs->charset_output;
1489
+        $this->db->begin();
4501 1490
 
4502
-			if (in_array(get_class($this), array('Adherent')))
4503
-			{
4504
-				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4505
-				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4506
-			}
4507
-			else
4508
-			{
4509
-				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4510
-			}
4511
-			// After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
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';
4512 1494
 
4513
-			if ($resultwritefile > 0)
4514
-			{
4515
-				$outputlangs->charset_output=$sav_charset_output;
4516
-
4517
-				// We delete old preview
4518
-				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4519
-				dol_delete_preview($this);
4520
-
4521
-				// Index file in database
4522
-				if (! empty($obj->result['fullpath']))
4523
-				{
4524
-					$destfull = $obj->result['fullpath'];
4525
-					$upload_dir = dirname($destfull);
4526
-					$destfile = basename($destfull);
4527
-					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4528
-
4529
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4530
-					{
4531
-						$filename = basename($destfile);
4532
-						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4533
-						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4534
-
4535
-						include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
4536
-						$ecmfile=new EcmFiles($this->db);
4537
-						$result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename);
4538
-
4539
-						// Set the public "share" key
4540
-						$setsharekey = false;
4541
-						if ($this->element == 'propal')
4542
-						{
4543
-							$useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL;	// Replace this with 1 when feature to make online signature is ok
4544
-							if ($useonlinesignature) $setsharekey=true;
4545
-							if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4546
-						}
4547
-						if ($this->element == 'commande'     && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))        $setsharekey=true;
4548
-						if ($this->element == 'facture'      && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))      $setsharekey=true;
4549
-						if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4550
-
4551
-						if ($setsharekey)
4552
-						{
4553
-							if (empty($ecmfile->share))	// Because object not found or share not set yet
4554
-							{
4555
-								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4556
-								$ecmfile->share = getRandomPassword(true);
4557
-							}
4558
-						}
1495
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
4559 1496
 
4560
-						if ($result > 0)
4561
-						{
4562
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4563
-							$ecmfile->fullpath_orig = '';
4564
-							$ecmfile->gen_or_uploaded = 'generated';
4565
-							$ecmfile->description = '';    // indexed content
4566
-							$ecmfile->keyword = '';        // keyword content
4567
-							$result = $ecmfile->update($user);
4568
-							if ($result < 0)
4569
-							{
4570
-								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4571
-							}
4572
-						}
4573
-						else
4574
-						{
4575
-							$ecmfile->entity = $conf->entity;
4576
-							$ecmfile->filepath = $rel_dir;
4577
-							$ecmfile->filename = $filename;
4578
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4579
-							$ecmfile->fullpath_orig = '';
4580
-							$ecmfile->gen_or_uploaded = 'generated';
4581
-							$ecmfile->description = '';    // indexed content
4582
-							$ecmfile->keyword = '';        // keyword content
4583
-							$ecmfile->src_object_type = $this->table_element;
4584
-							$ecmfile->src_object_id   = $this->id;
4585
-
4586
-							$result = $ecmfile->create($user);
4587
-							if ($result < 0)
4588
-							{
4589
-								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4590
-							}
4591
-						}
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");
4592 1500
 
4593
-						/*$this->result['fullname']=$destfull;
4594
-						$this->result['filepath']=$ecmfile->filepath;
4595
-						$this->result['filename']=$ecmfile->filename;*/
4596
-						//var_dump($obj->update_main_doc_field);exit;
4597
-
4598
-						// Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4599
-						$update_main_doc_field=0;
4600
-						if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4601
-						if ($update_main_doc_field && ! empty($this->table_element))
4602
-						{
4603
-							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4604
-							$sql.= ' WHERE rowid = '.$this->id;
4605
-							$resql = $this->db->query($sql);
4606
-							if (! $resql) dol_print_error($this->db);
4607
-						}
4608
-					}
4609
-				}
4610
-				else
4611
-				{
4612
-					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);
4613
-				}
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
+        }
4614 1506
 
4615
-				// Success in building document. We build meta file.
4616
-				dol_meta_create($this);
1507
+        $sql.= " WHERE ".$id_field." = ".$id;
4617 1508
 
4618
-				return 1;
4619
-			}
4620
-			else
4621
-			{
4622
-				$outputlangs->charset_output=$sav_charset_output;
4623
-				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4624
-				return -1;
4625
-			}
4626
-		}
4627
-		else
4628
-		{
4629
-			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4630
-			dol_print_error('',$this->error);
4631
-			return -1;
4632
-		}
4633
-	}
4634
-
4635
-	/**
4636
-	 *  Build thumb
4637
-	 *  @TODO Move this into files.lib.php
4638
-	 *
4639
-	 *  @param      string	$file           Path file in UTF8 to original file to create thumbs from.
4640
-	 *	@return		void
4641
-	 */
4642
-	function addThumbs($file)
4643
-	{
4644
-		global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4645
-
4646
-		require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4647
-
4648
-		$file_osencoded=dol_osencode($file);
4649
-		if (file_exists($file_osencoded))
4650
-		{
4651
-			// Create small thumbs for company (Ratio is near 16/9)
4652
-			// Used on logon for example
4653
-			vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
4654
-
4655
-			// Create mini thumbs for company (Ratio is near 16/9)
4656
-			// Used on menu or for setup page for example
4657
-			vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
4658
-		}
4659
-	}
4660
-
4661
-
4662
-	/* Functions common to commonobject and commonobjectline */
4663
-
4664
-	/* For default values */
4665
-
4666
-	/**
4667
-	 * Return the default value to use for a field when showing the create form of object.
4668
-	 * Return values in this order:
4669
-	 * 1) If parameter is available into POST, we return it first.
4670
-	 * 2) If not but an alternate value was provided as parameter of function, we return it.
4671
-	 * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
4672
-	 * 4) Return value found into database (TODO No yet implemented)
4673
-	 *
4674
-	 * @param   string              $fieldname          Name of field
4675
-	 * @param   string              $alternatevalue     Alternate value to use
4676
-	 * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4677
-	 **/
4678
-	function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4679
-	{
4680
-		global $conf, $_POST;
4681
-
4682
-		// If param here has been posted, we use this value first.
4683
-		if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
4684
-
4685
-		if (isset($alternatevalue)) return $alternatevalue;
4686
-
4687
-		$newelement=$this->element;
4688
-		if ($newelement == 'facture') $newelement='invoice';
4689
-		if ($newelement == 'commande') $newelement='order';
4690
-		if (empty($newelement))
4691
-		{
4692
-			dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
4693
-			return '';
4694
-		}
4695
-
4696
-		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4697
-		//var_dump($keyforfieldname);
4698
-		if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
4699
-
4700
-		// TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4701
-	}
4702
-
4703
-
4704
-	/* 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
+            }
4705 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
+    }
4706 1547
 
4707 1548
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4708
-	/**
4709
-	 * Call trigger based on this instance.
4710
-	 * Some context information may also be provided into array property this->context.
4711
-	 * NB:  Error from trigger are stacked in interface->errors
4712
-	 * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
4713
-	 *
4714
-	 * @param   string    $trigger_name   trigger's name to execute
4715
-	 * @param   User      $user           Object user
4716
-	 * @return  int                       Result of run_triggers
4717
-	 */
4718
-	function call_trigger($trigger_name, $user)
4719
-	{
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
+    {
4720 1559
         // phpcs:enable
4721
-		global $langs,$conf;
1560
+        global $conf, $user;
4722 1561
 
4723
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
4724
-		$interface=new Interfaces($this->db);
4725
-		$result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
4726
-
4727
-		if ($result < 0)
4728
-		{
4729
-			if (!empty($this->errors))
4730
-			{
4731
-				$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.
4732
-			}
4733
-			else
4734
-			{
4735
-				$this->errors=$interface->errors;
4736
-			}
4737
-		}
4738
-		return $result;
4739
-	}
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;
4740 1568
 
1569
+        // Security on socid
1570
+        $socid = 0;
1571
+        if ($user->societe_id > 0) $socid = $user->societe_id;
4741 1572
 
4742
-	/* Functions for extrafields */
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';
4743 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($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($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
+                if (! empty($user->admin) && empty($user->entity) && $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>";
4744 1613
 
4745
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4746
-	/**
4747
-	 *  Function to get extra fields of an object into $this->array_options
4748
-	 *  This method is in most cases called by method fetch of objects but you can call it separately.
4749
-	 *
4750
-	 *  @param	int		$rowid			Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
4751
-	 *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
4752
-	 *  @return	int						<0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
4753
-	 */
4754
-	function fetch_optionals($rowid=null, $optionsArray=null)
4755
-	{
4756
-        // phpcs:enable
4757
-		if (empty($rowid)) $rowid=$this->id;
4758
-
4759
-		// To avoid SQL errors. Probably not the better solution though
4760
-		if (!$this->table_element) {
4761
-			return 0;
4762
-		}
4763
-
4764
-		$this->array_options=array();
4765
-
4766
-		if (! is_array($optionsArray))
4767
-		{
4768
-			// If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4769
-			// TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
4770
-			// global $extrafields;
4771
-			//if (! is_object($extrafields))
4772
-			//{
4773
-				// require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4774
-            $extrafields = new ExtraFields();
4775
-            //}
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];
4776 1622
 
4777
-			// Load array of extrafields for elementype = $this->table_element
4778
-			if (empty($extrafields->attributes[$this->table_element]['loaded']))
4779
-			{
4780
-				$extrafields->fetch_name_optionals_label($this->table_element);
4781
-			}
4782
-			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4783
-		}
4784
-		else
4785
-		{
4786
-			global $extrafields;
4787
-			dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4788
-		}
4789
-
4790
-		$table_element = $this->table_element;
4791
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4792
-
4793
-		// Request to get complementary values
4794
-		if (is_array($optionsArray) && count($optionsArray) > 0)
4795
-		{
4796
-			$sql = "SELECT rowid";
4797
-			foreach ($optionsArray as $name => $label)
4798
-			{
4799
-				if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4800
-				{
4801
-					$sql.= ", ".$name;
4802
-				}
4803
-			}
4804
-			$sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4805
-			$sql.= " WHERE fk_object = ".$rowid;
4806 1623
 
4807
-			//dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4808
-			$resql=$this->db->query($sql);
4809
-			if ($resql)
4810
-			{
4811
-				$this->array_options = array();
4812
-				$numrows=$this->db->num_rows($resql);
4813
-				if ($numrows)
4814
-				{
4815
-					$tab = $this->db->fetch_array($resql);
4816
-
4817
-					foreach ($tab as $key => $value)
4818
-					{
4819
-						// 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)
4820
-						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4821
-						{
4822
-							// we can add this attribute to object
4823
-							if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4824
-							{
4825
-								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4826
-								$this->array_options["options_".$key]=$this->db->jdate($value);
4827
-							}
4828
-							else
4829
-							{
4830
-								$this->array_options["options_".$key]=$value;
4831
-							}
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($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($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
+                if (! empty($user->admin) && empty($user->entity) && $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];
4832 1669
 
4833
-							//var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
4834
-						}
4835
-					}
4836
-				}
1670
+        return 1;
1671
+    }
4837 1672
 
4838
-				$this->db->free($resql);
4839 1673
 
4840
-				if ($numrows) return $numrows;
4841
-				else return 0;
4842
-			}
4843
-			else
4844
-			{
4845
-				dol_print_error($this->db);
4846
-				return -1;
4847
-			}
4848
-		}
4849
-		return 0;
4850
-	}
4851
-
4852
-	/**
4853
-	 *	Delete all extra fields values for the current object.
4854
-	 *
4855
-	 *  @return	int		<0 if KO, >0 if OK
4856
-	 */
4857
-	function deleteExtraFields()
4858
-	{
4859
-		$this->db->begin();
4860
-
4861
-		$table_element = $this->table_element;
4862
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4863
-
4864
-		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4865
-		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4866
-		$resql=$this->db->query($sql_del);
4867
-		if (! $resql)
4868
-		{
4869
-			$this->error=$this->db->lasterror();
4870
-			$this->db->rollback();
4871
-			return -1;
4872
-		}
4873
-		else
4874
-		{
4875
-			$this->db->commit();
4876
-			return 1;
4877
-		}
4878
-	}
4879
-
4880
-	/**
4881
-	 *	Add/Update all extra fields values for the current object.
4882
-	 *  Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
4883
-	 *  This function delete record with all extrafields and insert them again from the array $this->array_options.
4884
-	 *
4885
-	 *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
4886
-	 *  @param	User		$userused		Object user
4887
-	 *  @return int 						-1=error, O=did nothing, 1=OK
4888
-	 *  @see updateExtraField, setValueFrom
4889
-	 */
4890
-	function insertExtraFields($trigger='', $userused=null)
4891
-	{
4892
-		global $conf,$langs,$user;
4893
-
4894
-		if (empty($userused)) $userused=$user;
4895
-
4896
-		$error=0;
4897
-
4898
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
4899
-
4900
-		if (! empty($this->array_options))
4901
-		{
4902
-			// Check parameters
4903
-			$langs->load('admin');
4904
-			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4905
-			$extrafields = new ExtraFields($this->db);
4906
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4907
-
4908
-			//Eliminate copied source object extra_fields that do not exist in target object
4909
-			$new_array_options=array();
4910
-			foreach ($this->array_options as $key => $value) {
4911
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4912
-					$new_array_options[$key] = $value;
4913
-				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4914
-					$new_array_options['options_'.$key] = $value;
4915
-			}
4916
-
4917
-			foreach($new_array_options as $key => $value)
4918
-			{
4919
-			   	$attributeKey      = substr($key,8);   // Remove 'options_' prefix
4920
-			   	$attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4921
-			   	$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4922
-			   	$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
4923
-			   	$attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
4924
-
4925
-			   	if ($attributeRequired)
4926
-			   	{
4927
-			   		$mandatorypb=false;
4928
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4929
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
4930
-			   		if ($mandatorypb)
4931
-			   		{
4932
-			   			dol_syslog($this->error);
4933
-			   			$this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4934
-			   			return -1;
4935
-			   		}
4936
-			   	}
4937
-
4938
-				//dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
4939
-				//dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
4940
-
4941
-			   	switch ($attributeType)
4942
-			   	{
4943
-			   		case 'int':
4944
-			  			if (!is_numeric($value) && $value!='')
4945
-			   			{
4946
-			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4947
-			   				return -1;
4948
-			  			}
4949
-			   			elseif ($value=='')
4950
-			   			{
4951
-			   				$new_array_options[$key] = null;
4952
-			   			}
4953
-			 			break;
4954
-					case 'double':
4955
-						$value = price2num($value);
4956
-						if (!is_numeric($value) && $value!='')
4957
-						{
4958
-							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4959
-							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4960
-							return -1;
4961
-						}
4962
-						elseif ($value=='')
4963
-						{
4964
-							$new_array_options[$key] = null;
4965
-						}
4966
-						//dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
4967
-						$new_array_options[$key] = $value;
4968
-						break;
4969
-			 		/*case 'select':	// Not required, we chosed value='0' for undefined values
4970
-             			if ($value=='-1')
4971
-             			{
4972
-             				$this->array_options[$key] = null;
4973
-             			}
4974
-             			break;*/
4975
-			   		case 'password':
4976
-			   			$algo='';
4977
-			   			if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4978
-			   			{
4979
-			   				// If there is an encryption choice, we use it to crypt data before insert
4980
-			   				$tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4981
-			   				$algo=reset($tmparrays);
4982
-			   				if ($algo != '')
4983
-			   				{
4984
-			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
4985
-			   					//var_dump($action);
4986
-			   					//var_dump($this->oldcopy);exit;
4987
-			   					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
4988
-			   					{
4989
-			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
4990
-				   					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.
4991
-				   					{
4992
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
4993
-				   					}
4994
-									else
4995
-									{
4996
-										// var_dump($algo);
4997
-										$newvalue = dol_hash($this->array_options[$key], $algo);
4998
-										$new_array_options[$key] = $newvalue;
4999
-									}
5000
-			   					}
5001
-			   					else
5002
-			   					{
5003
-			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5004
-			   					}
5005
-			   				}
5006
-			   			}
5007
-			   			else	// Common usage
5008
-			   			{
5009
-			   				$new_array_options[$key] = $this->array_options[$key];
5010
-			   			}
5011
-			   			break;
5012
-			   		case 'price':
5013
-						$new_array_options[$key] = price2num($this->array_options[$key]);
5014
-						break;
5015
-					case 'date':
5016
-						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5017
-						break;
5018
-					case 'datetime':
5019
-						// If data is a string instead of a timestamp, we convert it
5020
-						if (! is_int($this->array_options[$key])) {
5021
-							$this->array_options[$key] = strtotime($this->array_options[$key]);
5022
-						}
5023
-						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5024
-						break;
5025
-		   			case 'link':
5026
-						$param_list=array_keys($attributeParam['options']);
5027
-						// 0 : ObjectName
5028
-						// 1 : classPath
5029
-						$InfoFieldList = explode(":", $param_list[0]);
5030
-						dol_include_once($InfoFieldList[1]);
5031
-						if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5032
-						{
5033
-							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5034
-							{
5035
-								$new_array_options[$key]='';
5036
-							}
5037
-							elseif ($value)
5038
-							{
5039
-								$object = new $InfoFieldList[0]($this->db);
5040
-								if (is_numeric($value)) $res=$object->fetch($value);
5041
-								else $res=$object->fetch('',$value);
5042
-
5043
-								if ($res > 0) $new_array_options[$key]=$object->id;
5044
-								else
5045
-								{
5046
-									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5047
-									$this->db->rollback();
5048
-									return -1;
5049
-								}
5050
-							}
5051
-						}
5052
-						else
5053
-						{
5054
-							dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5055
-						}
5056
-						break;
5057
-			   	}
5058
-			}
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
+    }
5059 1695
 
5060
-			$this->db->begin();
5061 1696
 
5062
-			$table_element = $this->table_element;
5063
-			if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
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
+        }
5064 1710
 
5065
-			$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5066
-			dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
5067
-			$this->db->query($sql_del);
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
+        }
5068 1724
 
5069
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5070
-			foreach($new_array_options as $key => $value)
5071
-			{
5072
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5073
-				// Add field of attribut
5074
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5075
-					$sql.=",".$attributeKey;
5076
-			}
5077
-			$sql .= ") VALUES (".$this->id;
5078
-
5079
-			foreach($new_array_options as $key => $value)
5080
-			{
5081
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5082
-				// Add field of attribute
5083
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5084
-				{
5085
-					if ($new_array_options[$key] != '')
5086
-					{
5087
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5088
-					}
5089
-					else
5090
-					{
5091
-						$sql.=",null";
5092
-					}
5093
-				}
5094
-			}
5095
-			$sql.=")";
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
+    }
5096 1737
 
5097
-			dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5098
-			$resql = $this->db->query($sql);
5099
-			if (! $resql)
5100
-			{
5101
-				$this->error=$this->db->lasterror();
5102
-				$error++;
5103
-			}
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';
5104 1753
 
5105
-			if (! $error && $trigger)
5106
-			{
5107
-				// Call trigger
5108
-				$this->context=array('extrafieldaddupdate'=>1);
5109
-				$result=$this->call_trigger($trigger, $userused);
5110
-				if ($result < 0) $error++;
5111
-				// End call trigger
5112
-			}
5113
-
5114
-			if ($error)
5115
-			{
5116
-				$this->db->rollback();
5117
-				return -1;
5118
-			}
5119
-			else
5120
-			{
5121
-				$this->db->commit();
5122
-				return 1;
5123
-			}
5124
-		}
5125
-		else return 0;
5126
-	}
5127
-
5128
-	/**
5129
-	 *	Update an extra field value for the current object.
5130
-	 *  Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
5131
-	 *
5132
-	 *  @param  string      $key    		Key of the extrafield (without starting 'options_')
5133
-	 *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
5134
-	 *  @param	User		$userused		Object user
5135
-	 *  @return int                 		-1=error, O=did nothing, 1=OK
5136
-	 *  @see setValueFrom, insertExtraFields
5137
-	 */
5138
-	function updateExtraField($key, $trigger=null, $userused=null)
5139
-	{
5140
-		global $conf,$langs,$user;
5141
-
5142
-		if (empty($userused)) $userused=$user;
5143
-
5144
-		$error=0;
5145
-
5146
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
5147
-
5148
-		if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5149
-		{
5150
-			// Check parameters
5151
-			$langs->load('admin');
5152
-			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5153
-			$extrafields = new ExtraFields($this->db);
5154
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5155
-
5156
-			$value=$this->array_options["options_".$key];
5157
-
5158
-			$attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5159
-			$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
5160
-			$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$key];
5161
-			$attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
5162
-
5163
-			//dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
5164
-			//dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
5165
-
5166
-			switch ($attributeType)
5167
-			{
5168
-				case 'int':
5169
-					if (!is_numeric($value) && $value!='')
5170
-					{
5171
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5172
-						return -1;
5173
-					}
5174
-					elseif ($value=='')
5175
-					{
5176
-						$this->array_options["options_".$key] = null;
5177
-					}
5178
-					break;
5179
-				case 'double':
5180
-					$value = price2num($value);
5181
-					if (!is_numeric($value) && $value!='')
5182
-					{
5183
-						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5184
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5185
-						return -1;
5186
-					}
5187
-					elseif ($value=='')
5188
-					{
5189
-						$this->array_options["options_".$key] = null;
5190
-					}
5191
-					//dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
5192
-					$this->array_options["options_".$key] = $value;
5193
-					break;
5194
-			 	/*case 'select':	// Not required, we chosed value='0' for undefined values
5195
-             		if ($value=='-1')
5196
-             		{
5197
-             			$this->array_options[$key] = null;
5198
-             		}
5199
-             		break;*/
5200
-				case 'price':
5201
-					$this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5202
-					break;
5203
-				case 'date':
5204
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5205
-					break;
5206
-				case 'datetime':
5207
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5208
-					break;
5209
-				case 'link':
5210
-					$param_list=array_keys($attributeParam['options']);
5211
-					// 0 : ObjectName
5212
-					// 1 : classPath
5213
-					$InfoFieldList = explode(":", $param_list[0]);
5214
-					dol_include_once($InfoFieldList[1]);
5215
-					if ($value)
5216
-					{
5217
-						$object = new $InfoFieldList[0]($this->db);
5218
-						$object->fetch(0,$value);
5219
-						$this->array_options["options_".$key]=$object->id;
5220
-					}
5221
-					break;
5222
-			}
5223
-
5224
-			$this->db->begin();
5225
-			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5226
-			$sql .= " WHERE fk_object = ".$this->id;
5227
-			$resql = $this->db->query($sql);
5228
-			if (! $resql)
5229
-			{
5230
-				$error++;
5231
-				$this->error=$this->db->lasterror();
5232
-			}
1754
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1755
+            $sql .= ' SET '.$fieldname.' = '.$id;
1756
+            $sql .= ' WHERE rowid='.$this->id;
5233 1757
 
5234
-			if (! $error && $trigger)
5235
-			{
5236
-				// Call trigger
5237
-				$this->context=array('extrafieldupdate'=>1);
5238
-				$result=$this->call_trigger($trigger, $userused);
5239
-				if ($result < 0) $error++;
5240
-				// End call trigger
5241
-			}
5242
-
5243
-			if ($error)
5244
-			{
5245
-				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5246
-				$this->db->rollback();
5247
-				return -1;
5248
-			}
5249
-			else
5250
-			{
5251
-				$this->db->commit();
5252
-				return 1;
5253
-			}
5254
-		}
5255
-		else return 0;
5256
-	}
5257
-
5258
-
5259
-	/**
5260
-	 * Return HTML string to put an input field into a page
5261
-	 * Code very similar with showInputField of extra fields
5262
-	 *
5263
-	 * @param  array   		$val	       Array of properties for field to show
5264
-	 * @param  string  		$key           Key of attribute
5265
-	 * @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)
5266
-	 * @param  string  		$moreparam     To add more parameters on html input tag
5267
-	 * @param  string  		$keysuffix     Prefix string to add into name and id of field (can be used to avoid duplicate names)
5268
-	 * @param  string  		$keyprefix     Suffix string to add into name and id of field (can be used to avoid duplicate names)
5269
-	 * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5270
-	 * @return string
5271
-	 */
5272
-	function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5273
-	{
5274
-		global $conf,$langs,$form;
5275
-
5276
-		if (! is_object($form))
5277
-		{
5278
-			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5279
-			$form=new Form($this->db);
5280
-		}
5281
-
5282
-		$val=$this->fields[$key];
5283
-
5284
-		$out='';
5285
-        $type='';
5286
-        $param = array();
5287
-        $param['options']=array();
5288
-        $size =$this->fields[$key]['size'];
5289
-        // Because we work on extrafields
5290
-        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5291
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5292
-            $type ='link';
5293
-        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5294
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5295
-            $type ='link';
5296
-        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5297
-            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5298
-            $type ='sellist';
5299
-        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5300
-            $param['options']=array();
5301
-            $type ='varchar';
5302
-            $size=$reg[1];
5303
-        } elseif(preg_match('/varchar/', $val['type'])) {
5304
-            $param['options']=array();
5305
-            $type ='varchar';
5306
-        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5307
-            $param['options']=$this->fields[$key]['arrayofkeyval'];
5308
-            $type ='select';
5309
-        } else {
5310
-            $param['options']=array();
5311
-            $type =$this->fields[$key]['type'];
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
+            }
5312 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
+    }
5313 1779
 
5314
-		$label=$this->fields[$key]['label'];
5315
-		//$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5316
-		$default=$this->fields[$key]['default'];
5317
-		$computed=$this->fields[$key]['computed'];
5318
-		$unique=$this->fields[$key]['unique'];
5319
-		$required=$this->fields[$key]['required'];
5320
-
5321
-		$langfile=$this->fields[$key]['langfile'];
5322
-		$list=$this->fields[$key]['list'];
5323
-		$hidden=abs($this->fields[$key]['visible'])!=1?1:0;
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';
5324 1792
 
5325
-		$objectid = $this->id;
1793
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1794
+            $sql .= ' SET '.$fieldname." = '".$this->db->escape($code)."'";
1795
+            $sql .= ' WHERE rowid='.$this->id;
5326 1796
 
1797
+            if ($this->db->query($sql))
1798
+            {
1799
+                $this->multicurrency_code = $code;
5327 1800
 
5328
-		if ($computed)
5329
-		{
5330
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5331
-			else return '';
5332
-		}
1801
+                list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
+                if ($rate) $this->setMulticurrencyRate($rate,2);
5333 1803
 
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
+    }
5334 1820
 
5335
-		// Use in priority showsize from parameters, then $val['css'] then autodefine
5336
-		if (empty($morecss) && ! empty($val['css']))
5337
-		{
5338
-			$showsize = $val['css'];
5339
-		}
5340
-		if (empty($morecss))
5341
-		{
5342
-			if ($type == 'date')
5343
-			{
5344
-				$morecss = 'minwidth100imp';
5345
-			}
5346
-			elseif ($type == 'datetime')
5347
-			{
5348
-				$morecss = 'minwidth200imp';
5349
-			}
5350
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5351
-			{
5352
-				$morecss = 'maxwidth75';
5353
-                        }elseif ($type == 'url')
5354
-			{
5355
-				$morecss='minwidth400';
5356
-			}
5357
-			elseif ($type == 'boolean')
5358
-			{
5359
-				$morecss='';
5360
-			}
5361
-			else
5362
-			{
5363
-				if (round($size) < 12)
5364
-				{
5365
-					$morecss = 'minwidth100';
5366
-				}
5367
-				else if (round($size) <= 48)
5368
-				{
5369
-					$morecss = 'minwidth200';
5370
-				}
5371
-				else
5372
-				{
5373
-					$morecss = 'minwidth400';
5374
-				}
5375
-			}
5376
-		}
5377
-
5378
-		if (in_array($type,array('date','datetime')))
5379
-		{
5380
-			$tmp=explode(',',$size);
5381
-			$newsize=$tmp[0];
5382
-
5383
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5384
-
5385
-			// Do not show current date when field not required (see selectDate() method)
5386
-			if (!$required && $value == '') $value = '-1';
5387
-
5388
-			// TODO Must also support $moreparam
5389
-			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5390
-		}
5391
-		elseif (in_array($type,array('int','integer')))
5392
-		{
5393
-			$tmp=explode(',',$size);
5394
-			$newsize=$tmp[0];
5395
-			$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:'').'>';
5396
-		}
5397
-		elseif (preg_match('/varchar/', $type))
5398
-		{
5399
-			$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:'').'>';
5400
-		}
5401
-		elseif (in_array($type, array('mail', 'phone', 'url')))
5402
-		{
5403
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5404
-		}
5405
-		elseif ($type == 'text')
5406
-		{
5407
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5408
-			{
5409
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5410
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5411
-				$out=$doleditor->Create(1);
5412
-			}
5413
-			else
5414
-			{
5415
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5416
-			}
5417
-		}
5418
-		elseif ($type == 'html')
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,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,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 == 'boolean')
5432
-		{
5433
-			$checked='';
5434
-			if (!empty($value)) {
5435
-				$checked=' checked value="1" ';
5436
-			} else {
5437
-				$checked=' value="1" ';
5438
-			}
5439
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5440
-		}
5441
-		elseif ($type == 'price')
5442
-		{
5443
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5444
-				$value=price($value);
5445
-			}
5446
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
5447
-		}
5448
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5449
-		{
5450
-			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5451
-				$value=price($value);
5452
-			}
5453
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5454
-		}
5455
-		elseif ($type == 'select')
5456
-		{
5457
-			$out = '';
5458
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5459
-			{
5460
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5461
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5462
-			}
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';
5463 1834
 
5464
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5465
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5466
-			foreach ($param['options'] as $key => $val)
5467
-			{
5468
-				if ((string) $key == '') continue;
5469
-				list($val, $parent) = explode('|', $val);
5470
-				$out.='<option value="'.$key.'"';
5471
-				$out.= (((string) $value == (string) $key)?' selected':'');
5472
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5473
-				$out.='>'.$val.'</option>';
5474
-			}
5475
-			$out.='</select>';
5476
-		}
5477
-		elseif ($type == 'sellist')
5478
-		{
5479
-			$out = '';
5480
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5481
-			{
5482
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5483
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5484
-			}
1835
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1836
+            $sql .= ' SET '.$fieldname.' = '.$rate;
1837
+            $sql .= ' WHERE rowid='.$this->id;
5485 1838
 
5486
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5487
-			if (is_array($param['options']))
5488
-			{
5489
-				$param_list=array_keys($param['options']);
5490
-				$InfoFieldList = explode(":", $param_list[0]);
5491
-				$parentName='';
5492
-				$parentField='';
5493
-				// 0 : tableName
5494
-				// 1 : label field name
5495
-				// 2 : key fields name (if differ of rowid)
5496
-				// 3 : key field parent (for dependent lists)
5497
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5498
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5499
-
5500
-
5501
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5502
-				{
5503
-					if (strpos($InfoFieldList[4], 'extra.') !== false)
5504
-					{
5505
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
5506
-					} else {
5507
-						$keyList=$InfoFieldList[2].' as rowid';
5508
-					}
5509
-				}
5510
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5511
-				{
5512
-					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5513
-					$keyList.= ', '.$parentField;
5514
-				}
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
+                        }
1851
+
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
+                }
1905
+
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
+    }
5515 1922
 
5516
-				$fields_label = explode('|',$InfoFieldList[1]);
5517
-				if (is_array($fields_label))
5518
-				{
5519
-					$keyList .=', ';
5520
-					$keyList .= implode(', ', $fields_label);
5521
-				}
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';
5522 1938
 
5523
-				$sqlwhere='';
5524
-				$sql = 'SELECT '.$keyList;
5525
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5526
-				if (!empty($InfoFieldList[4]))
5527
-				{
5528
-					// can use SELECT request
5529
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5530
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5531
-					}
5532
-
5533
-					// current object id can be use into filter
5534
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5535
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5536
-					} else {
5537
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5538
-					}
5539
-					//We have to join on extrafield table
5540
-					if (strpos($InfoFieldList[4], 'extra')!==false)
5541
-					{
5542
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5543
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5544
-					}
5545
-					else
5546
-					{
5547
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5548
-					}
5549
-				}
5550
-				else
5551
-				{
5552
-					$sqlwhere.= ' WHERE 1=1';
5553
-				}
5554
-				// Some tables may have field, some other not. For the moment we disable it.
5555
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
5556
-				{
5557
-					$sqlwhere.= ' AND entity = '.$conf->entity;
5558
-				}
5559
-				$sql.=$sqlwhere;
5560
-				//print $sql;
1939
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1940
+            $sql .= ' SET '.$fieldname.' = '.$id;
1941
+            $sql .= ' WHERE rowid='.$this->id;
5561 1942
 
5562
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
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
+    }
5563 1965
 
5564
-				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5565
-				$resql = $this->db->query($sql);
5566
-				if ($resql)
5567
-				{
5568
-					$out.='<option value="0">&nbsp;</option>';
5569
-					$num = $this->db->num_rows($resql);
5570
-					$i = 0;
5571
-					while ($i < $num)
5572
-					{
5573
-						$labeltoshow='';
5574
-						$obj = $this->db->fetch_object($resql);
5575
-
5576
-						// Several field into label (eq table:code|libelle:rowid)
5577
-						$notrans = false;
5578
-						$fields_label = explode('|',$InfoFieldList[1]);
5579
-						if (is_array($fields_label))
5580
-						{
5581
-							$notrans = true;
5582
-							foreach ($fields_label as $field_toshow)
5583
-							{
5584
-								$labeltoshow.= $obj->$field_toshow.' ';
5585
-							}
5586
-						}
5587
-						else
5588
-						{
5589
-							$labeltoshow=$obj->{$InfoFieldList[1]};
5590
-						}
5591
-						$labeltoshow=dol_trunc($labeltoshow,45);
5592
-
5593
-						if ($value == $obj->rowid)
5594
-						{
5595
-							foreach ($fields_label as $field_toshow)
5596
-							{
5597
-								$translabel=$langs->trans($obj->$field_toshow);
5598
-								if ($translabel!=$obj->$field_toshow) {
5599
-									$labeltoshow=dol_trunc($translabel,18).' ';
5600
-								}else {
5601
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5602
-								}
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;
2007
+
2008
+        if (empty($userused)) $userused=$user;
2009
+
2010
+        $error = 0;
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);
2014
+            return -1;
2015
+        }
2016
+
2017
+        $this->db->begin();
2018
+
2019
+        if ($shipping_method_id<0) $shipping_method_id='NULL';
2020
+        dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2021
+
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
+    }
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
+
2132
+        if (empty($userused)) $userused=$user;
2133
+
2134
+        $error = 0;
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);
2138
+            return -1;
2139
+        }
2140
+        $this->db->begin();
2141
+
2142
+        if ($fk_account<0) $fk_account='NULL';
2143
+        dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2144
+
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($conf->global->$MODULE)) {
2674
+                $modsactivated = explode(',', $conf->global->$MODULE);
2675
+                foreach ($modsactivated as $mod) {
2676
+                    if ($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($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2688
+        elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2689
+
2690
+        $error=0;
2691
+
2692
+        $multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2693
+
2694
+        // Define constants to find lines to sum
2695
+        $fieldtva='total_tva';
2696
+        $fieldlocaltax1='total_localtax1';
2697
+        $fieldlocaltax2='total_localtax2';
2698
+        $fieldup='subprice';
2699
+        if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2700
+        {
2701
+            $fieldtva='tva';
2702
+            $fieldup='pu_ht';
2703
+        }
2704
+        if ($this->element == 'expensereport')
2705
+        {
2706
+            $fieldup='value_unit';
2707
+        }
2708
+
2709
+        $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,';
2710
+        $sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2711
+            if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
2712
+            $sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2713
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2714
+        $sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2715
+        if ($exclspec)
2716
+        {
2717
+            $product_field='product_type';
2718
+            if ($this->table_element_line == 'contratdet') $product_field='';    // contratdet table has no product_type field
2719
+            if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
2720
+        }
2721
+        $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
+
2723
+        dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2724
+        $resql = $this->db->query($sql);
2725
+        if ($resql)
2726
+        {
2727
+            $this->total_ht  = 0;
2728
+            $this->total_tva = 0;
2729
+            $this->total_localtax1 = 0;
2730
+            $this->total_localtax2 = 0;
2731
+            $this->total_ttc = 0;
2732
+            $total_ht_by_vats  = array();
2733
+            $total_tva_by_vats = array();
2734
+            $total_ttc_by_vats = array();
2735
+            $this->multicurrency_total_ht	= 0;
2736
+            $this->multicurrency_total_tva	= 0;
2737
+            $this->multicurrency_total_ttc	= 0;
2738
+
2739
+            $num = $this->db->num_rows($resql);
2740
+            $i = 0;
2741
+            while ($i < $num)
2742
+            {
2743
+                $obj = $this->db->fetch_object($resql);
2744
+
2745
+                // Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2746
+                $parameters=array('fk_element' => $obj->rowid);
2747
+                $reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2748
+
2749
+                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'
2750
+                {
2751
+                    $localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2752
+                    $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);
2753
+                    $diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2754
+                    if ($diff)
2755
+                    {
2756
+                        $sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2757
+                        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);
2758
+                                $resqlfix=$this->db->query($sqlfix);
2759
+                                if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2760
+                                $obj->total_tva = $tmpcal[1];
2761
+                                $obj->total_ttc = $tmpcal[2];
2762
+                        //
2763
+                    }
2764
+                }
2765
+
2766
+                $this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2767
+                $this->total_tva       += $obj->total_tva;
2768
+                $this->total_localtax1 += $obj->total_localtax1;
2769
+                $this->total_localtax2 += $obj->total_localtax2;
2770
+                $this->total_ttc       += $obj->total_ttc;
2771
+                $this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2772
+                $this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2773
+                $this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2774
+
2775
+                if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
2776
+                if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
2777
+                if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
2778
+                $total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2779
+                $total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2780
+                $total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2781
+
2782
+                if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2783
+                {
2784
+                    $tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2785
+                    $diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2786
+                    //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";
2787
+                    if ($diff)
2788
+                    {
2789
+                        if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
2790
+                        $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
+                        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);
2792
+                                $resqlfix=$this->db->query($sqlfix);
2793
+                                if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2794
+                                $this->total_tva -= $diff;
2795
+                                $this->total_ttc -= $diff;
2796
+                                $total_tva_by_vats[$obj->vatrate] -= $diff;
2797
+                                $total_ttc_by_vats[$obj->vatrate] -= $diff;
2798
+                    }
2799
+                }
2800
+
2801
+                $i++;
2802
+            }
2803
+
2804
+            // Add revenue stamp to total
2805
+            $this->total_ttc       			+= isset($this->revenuestamp)?$this->revenuestamp:0;
2806
+            $this->multicurrency_total_ttc  += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0;
2807
+
2808
+            // Situations totals
2809
+            if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE )
2810
+            {
2811
+                $prev_sits = $this->get_prev_sits();
2812
+
2813
+                foreach ($prev_sits as $sit) {				// $sit is an object Facture loaded with a fetch.
2814
+                    $this->total_ht -= $sit->total_ht;
2815
+                    $this->total_tva -= $sit->total_tva;
2816
+                    $this->total_localtax1 -= $sit->total_localtax1;
2817
+                    $this->total_localtax2 -= $sit->total_localtax2;
2818
+                    $this->total_ttc -= $sit->total_ttc;
2819
+                    $this->multicurrency_total_ht -= $sit->multicurrency_total_ht;
2820
+                    $this->multicurrency_total_tva -= $sit->multicurrency_total_tva;
2821
+                    $this->multicurrency_total_ttc -= $sit->multicurrency_total_ttc;
2822
+                }
2823
+            }
2824
+
2825
+            $this->db->free($resql);
2826
+
2827
+            // Now update global field total_ht, total_ttc and tva
2828
+            $fieldht='total_ht';
2829
+            $fieldtva='tva';
2830
+            $fieldlocaltax1='localtax1';
2831
+            $fieldlocaltax2='localtax2';
2832
+            $fieldttc='total_ttc';
2833
+            // Specific code for backward compatibility with old field names
2834
+            if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht='total';
2835
+            if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
2836
+            if ($this->element == 'propal')                                                $fieldttc='total';
2837
+            if ($this->element == 'expensereport')                                         $fieldtva='total_tva';
2838
+            if ($this->element == 'supplier_proposal')                                     $fieldttc='total';
2839
+
2840
+            if (empty($nodatabaseupdate))
2841
+            {
2842
+                $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET';
2843
+                $sql .= " ".$fieldht."='".price2num($this->total_ht)."',";
2844
+                $sql .= " ".$fieldtva."='".price2num($this->total_tva)."',";
2845
+                $sql .= " ".$fieldlocaltax1."='".price2num($this->total_localtax1)."',";
2846
+                $sql .= " ".$fieldlocaltax2."='".price2num($this->total_localtax2)."',";
2847
+                $sql .= " ".$fieldttc."='".price2num($this->total_ttc)."'";
2848
+                        $sql .= ", multicurrency_total_ht='".price2num($this->multicurrency_total_ht, 'MT', 1)."'";
2849
+                        $sql .= ", multicurrency_total_tva='".price2num($this->multicurrency_total_tva, 'MT', 1)."'";
2850
+                        $sql .= ", multicurrency_total_ttc='".price2num($this->multicurrency_total_ttc, 'MT', 1)."'";
2851
+                $sql .= ' WHERE rowid = '.$this->id;
2852
+
2853
+
2854
+                dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2855
+                $resql=$this->db->query($sql);
2856
+                if (! $resql)
2857
+                {
2858
+                    $error++;
2859
+                    $this->error=$this->db->lasterror();
2860
+                    $this->errors[]=$this->db->lasterror();
2861
+                }
2862
+            }
2863
+
2864
+            if (! $error)
2865
+            {
2866
+                return 1;
2867
+            }
2868
+            else
2869
+            {
2870
+                return -1;
2871
+            }
2872
+        }
2873
+        else
2874
+        {
2875
+            dol_print_error($this->db,'Bad request in update_price');
2876
+            return -1;
2877
+        }
2878
+    }
2879
+
2880
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
2881
+    /**
2882
+     *	Add objects linked in llx_element_element.
2883
+     *
2884
+     *	@param		string	$origin		Linked element type
2885
+     *	@param		int		$origin_id	Linked element id
2886
+     *	@return		int					<=0 if KO, >0 if OK
2887
+     *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2888
+     */
2889
+    function add_object_linked($origin=null, $origin_id=null)
2890
+    {
2891
+        // phpcs:enable
2892
+        $origin = (! empty($origin) ? $origin : $this->origin);
2893
+        $origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2894
+
2895
+        // Special case
2896
+        if ($origin == 'order') $origin='commande';
2897
+        if ($origin == 'invoice') $origin='facture';
2898
+        if ($origin == 'invoice_template') $origin='facturerec';
2899
+        if ($origin == 'supplierorder') $origin='order_supplier';
2900
+        $this->db->begin();
2901
+
2902
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2903
+        $sql.= "fk_source";
2904
+        $sql.= ", sourcetype";
2905
+        $sql.= ", fk_target";
2906
+        $sql.= ", targettype";
2907
+        $sql.= ") VALUES (";
2908
+        $sql.= $origin_id;
2909
+        $sql.= ", '".$this->db->escape($origin)."'";
2910
+        $sql.= ", ".$this->id;
2911
+        $sql.= ", '".$this->db->escape($this->element)."'";
2912
+        $sql.= ")";
2913
+
2914
+        dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2915
+        if ($this->db->query($sql))
2916
+            {
2917
+                $this->db->commit();
2918
+                return 1;
2919
+            }
2920
+            else
2921
+            {
2922
+                $this->error=$this->db->lasterror();
2923
+                $this->db->rollback();
2924
+                return 0;
2925
+            }
2926
+    }
2927
+
2928
+    /**
2929
+     *	Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
2930
+     *		this->linkedObjectsIds array and
2931
+     *		this->linkedObjects array if $loadalsoobjects = 1
2932
+     *  Possible usage for parameters:
2933
+     *  - all parameters empty -> we look all link to current object (current object can be source or target)
2934
+     *  - source id+type -> will get target list linked to source
2935
+     *  - target id+type -> will get source list linked to target
2936
+     *  - source id+type + target type -> will get target list of the type
2937
+     *  - target id+type + target source -> will get source list of the type
2938
+     *
2939
+     *	@param	int		$sourceid			Object source id (if not defined, id of object)
2940
+     *	@param  string	$sourcetype			Object source type (if not defined, element name of object)
2941
+     *	@param  int		$targetid			Object target id (if not defined, id of object)
2942
+     *	@param  string	$targettype			Object target type (if not defined, elemennt name of object)
2943
+     *	@param  string	$clause				'OR' or 'AND' clause used when both source id and target id are provided
2944
+     *  @param  int		$alsosametype		0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
2945
+     *  @param  string	$orderby			SQL 'ORDER BY' clause
2946
+     *  @param	int		$loadalsoobjects	Load also array this->linkedObjects (Use 0 to increase performances)
2947
+     *	@return int							<0 if KO, >0 if OK
2948
+     *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2949
+     */
2950
+    function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2951
+    {
2952
+        global $conf;
2953
+
2954
+        $this->linkedObjectsIds=array();
2955
+        $this->linkedObjects=array();
2956
+
2957
+        $justsource=false;
2958
+        $justtarget=false;
2959
+        $withtargettype=false;
2960
+        $withsourcetype=false;
2961
+
2962
+        if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2963
+        {
2964
+            $justsource=true;  // the source (id and type) is a search criteria
2965
+            if (! empty($targettype)) $withtargettype=true;
2966
+        }
2967
+        if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2968
+        {
2969
+            $justtarget=true;  // the target (id and type) is a search criteria
2970
+            if (! empty($sourcetype)) $withsourcetype=true;
2971
+        }
2972
+
2973
+        $sourceid = (! empty($sourceid) ? $sourceid : $this->id);
2974
+        $targetid = (! empty($targetid) ? $targetid : $this->id);
2975
+        $sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
2976
+        $targettype = (! empty($targettype) ? $targettype : $this->element);
2977
+
2978
+        /*if (empty($sourceid) && empty($targetid))
2979
+		 {
2980
+		 dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
2981
+		 return -1;
2982
+		 }*/
2983
+
2984
+        // Links between objects are stored in table element_element
2985
+        $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2986
+        $sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2987
+        $sql.= " WHERE ";
2988
+        if ($justsource || $justtarget)
2989
+        {
2990
+            if ($justsource)
2991
+            {
2992
+                $sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2993
+                if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2994
+            }
2995
+            else if ($justtarget)
2996
+            {
2997
+                $sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2998
+                if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
2999
+            }
3000
+        }
3001
+        else
3002
+        {
3003
+            $sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3004
+            $sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3005
+        }
3006
+        $sql .= ' ORDER BY '.$orderby;
3007
+
3008
+        dol_syslog(get_class($this)."::fetchObjectLink", LOG_DEBUG);
3009
+        $resql = $this->db->query($sql);
3010
+        if ($resql)
3011
+        {
3012
+            $num = $this->db->num_rows($resql);
3013
+            $i = 0;
3014
+            while ($i < $num)
3015
+            {
3016
+                $obj = $this->db->fetch_object($resql);
3017
+                if ($justsource || $justtarget)
3018
+                {
3019
+                    if ($justsource)
3020
+                    {
3021
+                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3022
+                    }
3023
+                    else if ($justtarget)
3024
+                    {
3025
+                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3026
+                    }
3027
+                }
3028
+                else
3029
+                {
3030
+                    if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3031
+                    {
3032
+                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3033
+                    }
3034
+                    if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3035
+                    {
3036
+                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3037
+                    }
3038
+                }
3039
+                $i++;
3040
+            }
3041
+
3042
+            if (! empty($this->linkedObjectsIds))
3043
+            {
3044
+                $tmparray = $this->linkedObjectsIds;
3045
+                foreach($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3046
+                {
3047
+                    // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3048
+                    $module = $element = $subelement = $objecttype;
3049
+                    if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3050
+                        && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3051
+                    {
3052
+                        $module = $element = $regs[1];
3053
+                        $subelement = $regs[2];
3054
+                    }
3055
+
3056
+                    $classpath = $element.'/class';
3057
+                    // To work with non standard classpath or module name
3058
+                    if ($objecttype == 'facture')			{
3059
+                        $classpath = 'compta/facture/class';
3060
+                    }
3061
+                    else if ($objecttype == 'facturerec')			{
3062
+                        $classpath = 'compta/facture/class'; $module = 'facture';
3063
+                    }
3064
+                    else if ($objecttype == 'propal')			{
3065
+                        $classpath = 'comm/propal/class';
3066
+                    }
3067
+                    else if ($objecttype == 'supplier_proposal')			{
3068
+                        $classpath = 'supplier_proposal/class';
3069
+                    }
3070
+                    else if ($objecttype == 'shipping')			{
3071
+                        $classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3072
+                    }
3073
+                    else if ($objecttype == 'delivery')			{
3074
+                        $classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3075
+                    }
3076
+                    else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3077
+                        $classpath = 'fourn/class'; $module = 'fournisseur';
3078
+                    }
3079
+                    else if ($objecttype == 'fichinter')			{
3080
+                        $classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3081
+                    }
3082
+                    else if ($objecttype == 'subscription')			{
3083
+                        $classpath = 'adherents/class'; $module = 'adherent';
3084
+                    }
3085
+
3086
+                    // Set classfile
3087
+                    $classfile = strtolower($subelement); $classname = ucfirst($subelement);
3088
+
3089
+                    if ($objecttype == 'order') {
3090
+                        $classfile = 'commande'; $classname = 'Commande';
3091
+                    }
3092
+                    else if ($objecttype == 'invoice_supplier') {
3093
+                        $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3094
+                    }
3095
+                    else if ($objecttype == 'order_supplier')   {
3096
+                        $classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3097
+                    }
3098
+                    else if ($objecttype == 'supplier_proposal')   {
3099
+                        $classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3100
+                    }
3101
+                    else if ($objecttype == 'facturerec')   {
3102
+                        $classfile = 'facture-rec'; $classname = 'FactureRec';
3103
+                    }
3104
+                    else if ($objecttype == 'subscription')   {
3105
+                        $classfile = 'subscription'; $classname = 'Subscription';
3106
+                    }
3107
+
3108
+                    // Here $module, $classfile and $classname are set
3109
+                    if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
3110
+                    {
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($conf->global->MAIN_DISABLE_CANVAS)) return 0;    // To increase speed. Not enabled by default.
3356
+
3357
+        // Clean parameters
3358
+        $ref = trim($ref);
3359
+
3360
+        $sql = "SELECT rowid, canvas";
3361
+        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3362
+        $sql.= " WHERE entity IN (".getEntity($this->element).")";
3363
+        if (! empty($id))  $sql.= " AND rowid = ".$id;
3364
+        if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
3365
+
3366
+        $resql = $this->db->query($sql);
3367
+        if ($resql)
3368
+        {
3369
+            $obj = $this->db->fetch_object($resql);
3370
+            if ($obj)
3371
+            {
3372
+                $this->canvas   = $obj->canvas;
3373
+                return 1;
3374
+            }
3375
+            else return 0;
3376
+        }
3377
+        else
3378
+        {
3379
+            dol_print_error($this->db);
3380
+            return -1;
3381
+        }
3382
+    }
3383
+
3384
+
3385
+    /**
3386
+     * 	Get special code of a line
3387
+     *
3388
+     * 	@param	int		$lineid		Id of line
3389
+     * 	@return	int					Special code
3390
+     */
3391
+    function getSpecialCode($lineid)
3392
+    {
3393
+        $sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3394
+        $sql.= ' WHERE rowid = '.$lineid;
3395
+        $resql = $this->db->query($sql);
3396
+        if ($resql)
3397
+        {
3398
+            $row = $this->db->fetch_row($resql);
3399
+            return $row[0];
3400
+        }
3401
+    }
3402
+
3403
+    /**
3404
+     *  Function to check if an object is used by others.
3405
+     *  Check is done into this->childtables. There is no check into llx_element_element.
3406
+     *
3407
+     *  @param	int		$id			Force id of object
3408
+     *  @return	int					<0 if KO, 0 if not used, >0 if already used
3409
+     */
3410
+    function isObjectUsed($id=0)
3411
+    {
3412
+        global $langs;
3413
+
3414
+        if (empty($id)) $id=$this->id;
3415
+
3416
+        // Check parameters
3417
+        if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3418
+        {
3419
+            dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3420
+            return -1;
3421
+        }
3422
+
3423
+        $arraytoscan = $this->childtables;
3424
+        // For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3425
+        $tmparray=array_keys($this->childtables);
3426
+        if (is_numeric($tmparray[0]))
3427
+        {
3428
+            $arraytoscan = array_flip($this->childtables);
3429
+        }
3430
+
3431
+        // Test if child exists
3432
+        $haschild=0;
3433
+        foreach($arraytoscan as $table => $elementname)
3434
+        {
3435
+            //print $id.'-'.$table.'-'.$elementname.'<br>';
3436
+            // Check if third party can be deleted
3437
+            $sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3438
+            $sql.= " WHERE ".$this->fk_element." = ".$id;
3439
+            $resql=$this->db->query($sql);
3440
+            if ($resql)
3441
+            {
3442
+                $obj=$this->db->fetch_object($resql);
3443
+                if ($obj->nb > 0)
3444
+                {
3445
+                    $langs->load("errors");
3446
+                    //print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3447
+                    $haschild += $obj->nb;
3448
+                    if (is_numeric($elementname))	// old usage
3449
+                    {
3450
+                        $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3451
+                    }
3452
+                    else	// new usage: $elementname=Translation key
3453
+                    {
3454
+                        $this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3455
+                    }
3456
+                    break;    // We found at least one, we stop here
3457
+                }
3458
+            }
3459
+            else
3460
+            {
3461
+                $this->errors[]=$this->db->lasterror();
3462
+                return -1;
3463
+            }
3464
+        }
3465
+        if ($haschild > 0)
3466
+        {
3467
+            $this->errors[]="ErrorRecordHasChildren";
3468
+            return $haschild;
3469
+        }
3470
+        else return 0;
3471
+    }
3472
+
3473
+    /**
3474
+     *  Function to say how many lines object contains
3475
+     *
3476
+     *	@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
3477
+     *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3478
+     */
3479
+    function hasProductsOrServices($predefined=-1)
3480
+    {
3481
+        $nb=0;
3482
+
3483
+        foreach($this->lines as $key => $val)
3484
+        {
3485
+            $qualified=0;
3486
+            if ($predefined == -1) $qualified=1;
3487
+            if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
3488
+            if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
3489
+            if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
3490
+            if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
3491
+            if ($qualified) $nb++;
3492
+        }
3493
+        dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3494
+        return $nb;
3495
+    }
3496
+
3497
+    /**
3498
+     * Function that returns the total amount HT of discounts applied for all lines.
3499
+     *
3500
+     * @return 	float
3501
+     */
3502
+    function getTotalDiscount()
3503
+    {
3504
+        $total_discount=0.00;
3505
+
3506
+        $sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
3507
+        $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3508
+        $sql.= " WHERE ".$this->fk_element." = ".$this->id;
3509
+
3510
+        dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3511
+        $resql = $this->db->query($sql);
3512
+        if ($resql)
3513
+        {
3514
+            $num=$this->db->num_rows($resql);
3515
+            $i=0;
3516
+            while ($i < $num)
3517
+            {
3518
+                $obj = $this->db->fetch_object($resql);
3519
+
3520
+                $pu_ht = $obj->pu_ht;
3521
+                $qty= $obj->qty;
3522
+                $total_ht = $obj->total_ht;
3523
+
3524
+                $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
3525
+                $total_discount += $total_discount_line;
3526
+
3527
+                $i++;
3528
+            }
3529
+        }
3530
+
3531
+        //print $total_discount; exit;
3532
+        return price2num($total_discount);
3533
+    }
3534
+
3535
+
3536
+    /**
3537
+     * Return into unit=0, the calculated total of weight and volume of all lines * qty
3538
+     * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
3539
+     *
3540
+     * @return  array                           array('weight'=>...,'volume'=>...)
3541
+     */
3542
+    function getTotalWeightVolume()
3543
+    {
3544
+        $totalWeight = 0;
3545
+        $totalVolume = 0;
3546
+        // defined for shipment only
3547
+        $totalOrdered = '';
3548
+        // defined for shipment only
3549
+        $totalToShip = '';
3550
+
3551
+        foreach ($this->lines as $line)
3552
+        {
3553
+            if (isset($line->qty_asked))
3554
+            {
3555
+                if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3556
+                $totalOrdered+=$line->qty_asked;    // defined for shipment only
3557
+            }
3558
+            if (isset($line->qty_shipped))
3559
+            {
3560
+                if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3561
+                $totalToShip+=$line->qty_shipped;   // defined for shipment only
3562
+            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3563
+            {
3564
+                if (empty($totalToShip)) $totalToShip=0;
3565
+                $totalToShip+=$line->qty;   // defined for reception only
3566
+            }
3567
+
3568
+            // Define qty, weight, volume, weight_units, volume_units
3569
+            if ($this->element == 'shipping') {
3570
+                // for shipments
3571
+                $qty = $line->qty_shipped ? $line->qty_shipped : 0;
3572
+            }
3573
+            else {
3574
+                $qty = $line->qty ? $line->qty : 0;
3575
+            }
3576
+
3577
+            $weight = $line->weight ? $line->weight : 0;
3578
+            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3579
+            $volume = $line->volume ? $line->volume : 0;
3580
+            ($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
3581
+
3582
+            $weight_units=$line->weight_units;
3583
+            ($weight_units==0 && !empty($line->product->weight_units))? $weight_units=$line->product->weight_units: 0;
3584
+            $volume_units=$line->volume_units;
3585
+            ($volume_units==0 && !empty($line->product->volume_units))? $volume_units=$line->product->volume_units: 0;
3586
+
3587
+            $weightUnit=0;
3588
+            $volumeUnit=0;
3589
+            if (! empty($weight_units)) $weightUnit = $weight_units;
3590
+            if (! empty($volume_units)) $volumeUnit = $volume_units;
3591
+
3592
+            if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3593
+            if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3594
+
3595
+            //var_dump($line->volume_units);
3596
+            if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3597
+            {
3598
+                $trueWeightUnit=pow(10, $weightUnit);
3599
+                $totalWeight += $weight * $qty * $trueWeightUnit;
3600
+            }
3601
+            else {
3602
+        if ($weight_units == 99) {
3603
+            // conversion 1 Pound = 0.45359237 KG
3604
+            $trueWeightUnit = 0.45359237;
3605
+            $totalWeight += $weight * $qty * $trueWeightUnit;
3606
+        } elseif ($weight_units == 98) {
3607
+            // conversion 1 Ounce = 0.0283495 KG
3608
+            $trueWeightUnit = 0.0283495;
3609
+            $totalWeight += $weight * $qty * $trueWeightUnit;
3610
+        }
3611
+        else
3612
+                    $totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3613
+            }
3614
+            if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3615
+            {
3616
+                //print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3617
+                $trueVolumeUnit=pow(10, $volumeUnit);
3618
+                //print $line->volume;
3619
+                $totalVolume += $volume * $qty * $trueVolumeUnit;
3620
+            }
3621
+            else
3622
+            {
3623
+                $totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3624
+            }
3625
+        }
3626
+
3627
+        return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
3628
+    }
3629
+
3630
+
3631
+    /**
3632
+     *	Set extra parameters
3633
+     *
3634
+     *	@return	int      <0 if KO, >0 if OK
3635
+     */
3636
+    function setExtraParameters()
3637
+    {
3638
+        $this->db->begin();
3639
+
3640
+        $extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3641
+
3642
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3643
+        $sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3644
+        $sql.= " WHERE rowid = ".$this->id;
3645
+
3646
+        dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3647
+        $resql = $this->db->query($sql);
3648
+        if (! $resql)
3649
+        {
3650
+            $this->error=$this->db->lasterror();
3651
+            $this->db->rollback();
3652
+            return -1;
3653
+        }
3654
+        else
3655
+        {
3656
+            $this->db->commit();
3657
+            return 1;
3658
+        }
3659
+    }
3660
+
3661
+
3662
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
3663
+    /**
3664
+     *    Return incoterms informations
3665
+     *    TODO Use a cache for label get
3666
+     *
3667
+     *    @return	string	incoterms info
3668
+     */
3669
+    function display_incoterms()
3670
+    {
3671
+        // phpcs:enable
3672
+        $out = '';
3673
+        $this->libelle_incoterms = '';
3674
+        if (!empty($this->fk_incoterms))
3675
+        {
3676
+            $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3677
+            $result = $this->db->query($sql);
3678
+            if ($result)
3679
+            {
3680
+                $res = $this->db->fetch_object($result);
3681
+                $out .= $res->code;
3682
+            }
3683
+        }
3684
+
3685
+        $out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3686
+
3687
+        return $out;
3688
+    }
3689
+
3690
+    /**
3691
+     *    Return incoterms informations for pdf display
3692
+     *
3693
+     *    @return	string		incoterms info
3694
+     */
3695
+    function getIncotermsForPDF()
3696
+    {
3697
+        $sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3698
+        $resql = $this->db->query($sql);
3699
+        if ($resql)
3700
+        {
3701
+            $num = $this->db->num_rows($resql);
3702
+            if ($num > 0)
3703
+            {
3704
+                $res = $this->db->fetch_object($resql);
3705
+                return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3706
+            }
3707
+            else
3708
+            {
3709
+                return '';
3710
+            }
3711
+        }
3712
+        else
3713
+        {
3714
+            $this->errors[] = $this->db->lasterror();
3715
+            return false;
3716
+        }
3717
+    }
3718
+
3719
+    /**
3720
+     *    Define incoterms values of current object
3721
+     *
3722
+     *    @param	int		$id_incoterm     Id of incoterm to set or '' to remove
3723
+     * 	  @param 	string  $location		 location of incoterm
3724
+     *    @return	int     		<0 if KO, >0 if OK
3725
+     */
3726
+    function setIncoterms($id_incoterm, $location)
3727
+    {
3728
+        if ($this->id && $this->table_element)
3729
+        {
3730
+            $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3731
+            $sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3732
+            $sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3733
+            $sql.= " WHERE rowid = " . $this->id;
3734
+            dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3735
+            $resql=$this->db->query($sql);
3736
+            if ($resql)
3737
+            {
3738
+                $this->fk_incoterms = $id_incoterm;
3739
+                $this->location_incoterms = $location;
3740
+
3741
+                $sql = 'SELECT libelle FROM '.MAIN_DB_PREFIX.'c_incoterms WHERE rowid = '.(int) $this->fk_incoterms;
3742
+                $res = $this->db->query($sql);
3743
+                if ($res)
3744
+                {
3745
+                    $obj = $this->db->fetch_object($res);
3746
+                    $this->libelle_incoterms = $obj->libelle;
3747
+                }
3748
+                return 1;
3749
+            }
3750
+            else
3751
+            {
3752
+                $this->errors[] = $this->db->lasterror();
3753
+                return -1;
3754
+            }
3755
+        }
3756
+        else return -1;
3757
+    }
3758
+
3759
+
3760
+    // --------------------
3761
+    // TODO: All functions here must be redesigned and moved as they are not business functions but output functions
3762
+    // --------------------
3763
+
3764
+    /* This is to show add lines */
3765
+
3766
+    /**
3767
+     *	Show add free and predefined products/services form
3768
+     *
3769
+     *  @param	int		        $dateSelector       1=Show also date range input fields
3770
+     *  @param	Societe			$seller				Object thirdparty who sell
3771
+     *  @param	Societe			$buyer				Object thirdparty who buy
3772
+     *	@return	void
3773
+     */
3774
+    function formAddObjectLine($dateSelector, $seller, $buyer)
3775
+    {
3776
+        global $conf,$user,$langs,$object,$hookmanager;
3777
+        global $form,$bcnd,$var;
3778
+
3779
+        // Line extrafield
3780
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3781
+        $extrafieldsline = new ExtraFields($this->db);
3782
+        $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3783
+
3784
+        // Output template part (modules that overwrite templates must declare this into descriptor)
3785
+        // Use global variables + $dateSelector + $seller and $buyer
3786
+        $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
3787
+        foreach($dirtpls as $reldir)
3788
+        {
3789
+            $tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3790
+            if (empty($conf->file->strict_mode)) {
3791
+                $res=@include $tpl;
3792
+            } else {
3793
+                $res=include $tpl; // for debug
3794
+            }
3795
+            if ($res) break;
3796
+        }
3797
+    }
3798
+
3799
+
3800
+
3801
+    /* This is to show array of line of details */
3802
+
3803
+
3804
+    /**
3805
+     *	Return HTML table for object lines
3806
+     *	TODO Move this into an output class file (htmlline.class.php)
3807
+     *	If lines are into a template, title must also be into a template
3808
+     *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
3809
+     *
3810
+     *	@param	string		$action				Action code
3811
+     *	@param  string		$seller            	Object of seller third party
3812
+     *	@param  string  	$buyer             	Object of buyer third party
3813
+     *	@param	int			$selected		   	Object line selected
3814
+     *	@param  int	    	$dateSelector      	1=Show also date range input fields
3815
+     *	@return	void
3816
+     */
3817
+    function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3818
+    {
3819
+        global $conf, $hookmanager, $langs, $user;
3820
+        // TODO We should not use global var for this !
3821
+        global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3822
+
3823
+        // Define usemargins
3824
+        $usemargins=0;
3825
+        if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
3826
+
3827
+        $num = count($this->lines);
3828
+
3829
+        // Line extrafield
3830
+        require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3831
+        $extrafieldsline = new ExtraFields($this->db);
3832
+        $extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3833
+
3834
+        $parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3835
+        $reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3836
+        if (empty($reshook))
3837
+        {
3838
+            // Title line
3839
+            print "<thead>\n";
3840
+
3841
+            print '<tr class="liste_titre nodrag nodrop">';
3842
+
3843
+            // Adds a line numbering column
3844
+            if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
3845
+
3846
+            // Description
3847
+            print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
3848
+
3849
+            if ($this->element == 'supplier_proposal' || $this->element == 'order_supplier' || $this->element == 'invoice_supplier')
3850
+            {
3851
+                print '<td class="linerefsupplier"><span id="title_fourn_ref">'.$langs->trans("SupplierRef").'</span></td>';
3852
+            }
3853
+
3854
+            // VAT
3855
+            print '<td class="linecolvat" align="right" width="80">'.$langs->trans('VAT').'</td>';
3856
+
3857
+            // Price HT
3858
+            print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
3859
+
3860
+            // Multicurrency
3861
+            if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
3862
+
3863
+            if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
3864
+
3865
+            // Qty
3866
+            print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
3867
+
3868
+            if($conf->global->PRODUCT_USE_UNITS)
3869
+            {
3870
+                print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
3871
+            }
3872
+
3873
+            // Reduction short
3874
+            print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
3875
+
3876
+            if ($this->situation_cycle_ref) {
3877
+                print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3878
+            }
3879
+
3880
+            if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
3881
+            {
3882
+                if (!empty($user->rights->margins->creer))
3883
+                {
3884
+                    if ($conf->global->MARGIN_TYPE == "1")
3885
+                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3886
+                    else
3887
+                        print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
3888
+                }
3889
+
3890
+                if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3891
+                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3892
+                if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3893
+                    print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
3894
+            }
3895
+
3896
+            // Total HT
3897
+            print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
3898
+
3899
+            // Multicurrency
3900
+            if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
3901
+
3902
+            if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
3903
+
3904
+            print '<td class="linecoledit"></td>';  // No width to allow autodim
3905
+
3906
+            print '<td class="linecoldelete" width="10"></td>';
3907
+
3908
+            print '<td class="linecolmove" width="10"></td>';
3909
+
3910
+            if($action == 'selectlines')
3911
+            {
3912
+                print '<td class="linecolcheckall" align="center">';
3913
+                print '<input type="checkbox" class="linecheckboxtoggle" />';
3914
+                print '<script type="text/javascript">$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
3915
+                print '</td>';
3916
+            }
3917
+
3918
+            print "</tr>\n";
3919
+            print "</thead>\n";
3920
+        }
3921
+
3922
+        $var = true;
3923
+        $i	 = 0;
3924
+
3925
+        print "<tbody>\n";
3926
+        foreach ($this->lines as $line)
3927
+        {
3928
+            //Line extrafield
3929
+            $line->fetch_optionals();
3930
+
3931
+            //if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3932
+            if (is_object($hookmanager))   // Old code is commented on preceding line.
3933
+            {
3934
+                if (empty($line->fk_parent_line))
3935
+                {
3936
+                    $parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3937
+                    $reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3938
+                }
3939
+                else
3940
+                {
3941
+                    $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);
3942
+                    $reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3943
+                }
3944
+            }
3945
+            if (empty($reshook))
3946
+            {
3947
+                $this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3948
+            }
3949
+
3950
+            $i++;
3951
+        }
3952
+        print "</tbody>\n";
3953
+    }
3954
+
3955
+    /**
3956
+     *	Return HTML content of a detail line
3957
+     *	TODO Move this into an output class file (htmlline.class.php)
3958
+     *
3959
+     *	@param	string		$action				GET/POST action
3960
+     *	@param CommonObjectLine $line		       	Selected object line to output
3961
+     *	@param  string	    $var               	Is it a an odd line (true)
3962
+     *	@param  int		    $num               	Number of line (0)
3963
+     *	@param  int		    $i					I
3964
+     *	@param  int		    $dateSelector      	1=Show also date range input fields
3965
+     *	@param  string	    $seller            	Object of seller third party
3966
+     *	@param  string	    $buyer             	Object of buyer third party
3967
+     *	@param	int			$selected		   	Object line selected
3968
+     *  @param  int			$extrafieldsline	Object of extrafield line attribute
3969
+     *	@return	void
3970
+     */
3971
+    function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
3972
+    {
3973
+        global $conf,$langs,$user,$object,$hookmanager;
3974
+        global $form,$bc,$bcdd;
3975
+        global $object_rights, $disableedit, $disablemove, $disableremove;   // TODO We should not use global var for this !
3976
+
3977
+        $object_rights = $this->getRights();
3978
+
3979
+        $element=$this->element;
3980
+
3981
+        $text=''; $description=''; $type=0;
3982
+
3983
+        // Show product and description
3984
+        $type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3985
+        // Try to enhance type detection using date_start and date_end for free lines where type was not saved.
3986
+        if (! empty($line->date_start)) $type=1; // deprecated
3987
+        if (! empty($line->date_end)) $type=1; // deprecated
3988
+
3989
+        // Ligne en mode visu
3990
+        if ($action != 'editline' || $selected != $line->id)
3991
+        {
3992
+            // Product
3993
+            if ($line->fk_product > 0)
3994
+            {
3995
+                $product_static = new Product($this->db);
3996
+                $product_static->fetch($line->fk_product);
3997
+
3998
+                $product_static->ref = $line->ref; //can change ref in hook
3999
+                $product_static->label = $line->label; //can change label in hook
4000
+                $text=$product_static->getNomUrl(1);
4001
+
4002
+                // Define output language and label
4003
+                if (! empty($conf->global->MAIN_MULTILANGS))
4004
+                {
4005
+                    if (! is_object($this->thirdparty))
4006
+                    {
4007
+                        dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4008
+                        return;
4009
+                    }
4010
+
4011
+                    $prod = new Product($this->db);
4012
+                    $prod->fetch($line->fk_product);
4013
+
4014
+                    $outputlangs = $langs;
4015
+                    $newlang='';
4016
+                    if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
4017
+                    if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang;		// For language to language of customer
4018
+                    if (! empty($newlang))
4019
+                    {
4020
+                        $outputlangs = new Translate("",$conf);
4021
+                        $outputlangs->setDefaultLang($newlang);
4022
+                    }
4023
+
4024
+                    $label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4025
+                }
4026
+                else
4027
+                {
4028
+                    $label = $line->product_label;
4029
+                }
4030
+
4031
+                $text.= ' - '.(! empty($line->label)?$line->label:$label);
4032
+                $description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description));	// Description is what to show on popup. We shown nothing if already into desc.
4033
+            }
4034
+
4035
+            $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4036
+
4037
+            // Output template part (modules that overwrite templates must declare this into descriptor)
4038
+            // Use global variables + $dateSelector + $seller and $buyer
4039
+            $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4040
+            foreach($dirtpls as $reldir)
4041
+            {
4042
+                $tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4043
+                if (empty($conf->file->strict_mode)) {
4044
+                    $res=@include $tpl;
4045
+                } else {
4046
+                    $res=include $tpl; // for debug
4047
+                }
4048
+                if ($res) break;
4049
+            }
4050
+        }
4051
+
4052
+        // Ligne en mode update
4053
+        if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4054
+        {
4055
+            $label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4056
+            $placeholder=' placeholder="'.$langs->trans("Label").'"';
4057
+
4058
+            $line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4059
+
4060
+            // Output template part (modules that overwrite templates must declare this into descriptor)
4061
+            // Use global variables + $dateSelector + $seller and $buyer
4062
+            $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4063
+            foreach($dirtpls as $reldir)
4064
+            {
4065
+                $tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4066
+                if (empty($conf->file->strict_mode)) {
4067
+                    $res=@include $tpl;
4068
+                } else {
4069
+                    $res=include $tpl; // for debug
4070
+                }
4071
+                if ($res) break;
4072
+            }
4073
+        }
4074
+    }
4075
+
4076
+
4077
+    /* This is to show array of line of details of source object */
4078
+
4079
+
4080
+    /**
4081
+     * 	Return HTML table table of source object lines
4082
+     *  TODO Move this and previous function into output html class file (htmlline.class.php).
4083
+     *  If lines are into a template, title must also be into a template
4084
+     *  But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
4085
+     *
4086
+     *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4087
+     *  @return	void
4088
+     */
4089
+    function printOriginLinesList($restrictlist='')
4090
+    {
4091
+        global $langs, $hookmanager, $conf;
4092
+
4093
+        print '<tr class="liste_titre">';
4094
+        print '<td>'.$langs->trans('Ref').'</td>';
4095
+        print '<td>'.$langs->trans('Description').'</td>';
4096
+        print '<td align="right">'.$langs->trans('VATRate').'</td>';
4097
+        print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4098
+        if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4099
+        print '<td align="right">'.$langs->trans('Qty').'</td>';
4100
+        if($conf->global->PRODUCT_USE_UNITS)
4101
+        {
4102
+            print '<td align="left">'.$langs->trans('Unit').'</td>';
4103
+        }
4104
+        print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
4105
+
4106
+        $var = true;
4107
+        $i	 = 0;
4108
+
4109
+        if (! empty($this->lines))
4110
+        {
4111
+            foreach ($this->lines as $line)
4112
+            {
4113
+                if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4114
+                {
4115
+                    if (empty($line->fk_parent_line))
4116
+                    {
4117
+                        $parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
4118
+                        $action='';
4119
+                        $hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4120
+                    }
4121
+                }
4122
+                else
4123
+                {
4124
+                    $this->printOriginLine($line, $var, $restrictlist);
4125
+                }
4126
+
4127
+                $i++;
4128
+            }
4129
+        }
4130
+    }
4131
+
4132
+    /**
4133
+     * 	Return HTML with a line of table array of source object lines
4134
+     *  TODO Move this and previous function into output html class file (htmlline.class.php).
4135
+     *  If lines are into a template, title must also be into a template
4136
+     *  But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
4137
+     *
4138
+     * 	@param	CommonObjectLine	$line				Line
4139
+     * 	@param	string				$var				Var
4140
+     *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4141
+     * 	@return	void
4142
+     */
4143
+    function printOriginLine($line, $var, $restrictlist='')
4144
+    {
4145
+        global $langs, $conf;
4146
+
4147
+        //var_dump($line);
4148
+        if (!empty($line->date_start))
4149
+        {
4150
+            $date_start=$line->date_start;
4151
+        }
4152
+        else
4153
+        {
4154
+            $date_start=$line->date_debut_prevue;
4155
+            if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4156
+        }
4157
+        if (!empty($line->date_end))
4158
+        {
4159
+            $date_end=$line->date_end;
4160
+        }
4161
+        else
4162
+        {
4163
+            $date_end=$line->date_fin_prevue;
4164
+            if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4165
+        }
4166
+
4167
+        $this->tpl['label'] = '';
4168
+        if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4169
+
4170
+        if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4171
+        {
4172
+            $discount=new DiscountAbsolute($this->db);
4173
+            $discount->fk_soc = $this->socid;
4174
+            $this->tpl['label'].= $discount->getNomUrl(0,'discount');
4175
+        }
4176
+        else if (! empty($line->fk_product))
4177
+        {
4178
+            $productstatic = new Product($this->db);
4179
+            $productstatic->id = $line->fk_product;
4180
+            $productstatic->ref = $line->ref;
4181
+            $productstatic->type = $line->fk_product_type;
4182
+            if(empty($productstatic->ref)){
4183
+                $line->fetch_product();
4184
+                $productstatic = $line->product;
4185
+            }
4186
+			
4187
+            $this->tpl['label'].= $productstatic->getNomUrl(1);
4188
+            $this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4189
+            // Dates
4190
+            if ($line->product_type == 1 && ($date_start || $date_end))
4191
+            {
4192
+                $this->tpl['label'].= get_date_range($date_start,$date_end);
4193
+            }
4194
+        }
4195
+        else
4196
+        {
4197
+            $this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4198
+            if (!empty($line->desc)) {
4199
+                $this->tpl['label'].=$line->desc;
4200
+            }else {
4201
+                $this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4202
+            }
4203
+			
4204
+            // Dates
4205
+            if ($line->product_type == 1 && ($date_start || $date_end))
4206
+            {
4207
+                $this->tpl['label'].= get_date_range($date_start,$date_end);
4208
+            }
4209
+        }
4210
+
4211
+        if (! empty($line->desc))
4212
+        {
4213
+            if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4214
+            {
4215
+                $discount=new DiscountAbsolute($this->db);
4216
+                $discount->fetch($line->fk_remise_except);
4217
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4218
+            }
4219
+            elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4220
+            {
4221
+                $discount=new DiscountAbsolute($this->db);
4222
+                $discount->fetch($line->fk_remise_except);
4223
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4224
+            }
4225
+            elseif ($line->desc == '(EXCESS RECEIVED)')
4226
+            {
4227
+                $discount=new DiscountAbsolute($this->db);
4228
+                $discount->fetch($line->fk_remise_except);
4229
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4230
+            }
4231
+            elseif ($line->desc == '(EXCESS PAID)')
4232
+            {
4233
+                $discount=new DiscountAbsolute($this->db);
4234
+                $discount->fetch($line->fk_remise_except);
4235
+                $this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4236
+            }
4237
+            else
4238
+            {
4239
+                $this->tpl['description'] = dol_trunc($line->desc,60);
4240
+            }
4241
+        }
4242
+        else
4243
+        {
4244
+            $this->tpl['description'] = '&nbsp;';
4245
+        }
4246
+
4247
+        // VAT Rate
4248
+        $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4249
+        $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
4250
+        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4251
+
4252
+        $this->tpl['price'] = price($line->subprice);
4253
+        $this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4254
+        $this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4255
+        if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4256
+        $this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4257
+
4258
+        // Is the line strike or not
4259
+        $this->tpl['strike']=0;
4260
+        if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4261
+
4262
+        // Output template part (modules that overwrite templates must declare this into descriptor)
4263
+        // Use global variables + $dateSelector + $seller and $buyer
4264
+        $dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4265
+        foreach($dirtpls as $reldir)
4266
+        {
4267
+            $tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4268
+            if (empty($conf->file->strict_mode)) {
4269
+                $res=@include $tpl;
4270
+            } else {
4271
+                $res=include $tpl; // for debug
4272
+            }
4273
+            if ($res) break;
4274
+        }
4275
+    }
4276
+
4277
+
4278
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4279
+    /**
4280
+     *	Add resources to the current object : add entry into llx_element_resources
4281
+     *	Need $this->element & $this->id
4282
+     *
4283
+     *	@param		int		$resource_id		Resource id
4284
+     *	@param		string	$resource_type		'resource'
4285
+     *	@param		int		$busy				Busy or not
4286
+     *	@param		int		$mandatory			Mandatory or not
4287
+     *	@return		int							<=0 if KO, >0 if OK
4288
+     */
4289
+    function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4290
+    {
4291
+        // phpcs:enable
4292
+        $this->db->begin();
4293
+
4294
+        $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
4295
+        $sql.= "resource_id";
4296
+        $sql.= ", resource_type";
4297
+        $sql.= ", element_id";
4298
+        $sql.= ", element_type";
4299
+        $sql.= ", busy";
4300
+        $sql.= ", mandatory";
4301
+        $sql.= ") VALUES (";
4302
+        $sql.= $resource_id;
4303
+        $sql.= ", '".$this->db->escape($resource_type)."'";
4304
+        $sql.= ", '".$this->db->escape($this->id)."'";
4305
+        $sql.= ", '".$this->db->escape($this->element)."'";
4306
+        $sql.= ", '".$this->db->escape($busy)."'";
4307
+        $sql.= ", '".$this->db->escape($mandatory)."'";
4308
+        $sql.= ")";
4309
+
4310
+        dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4311
+        if ($this->db->query($sql))
4312
+        {
4313
+            $this->db->commit();
4314
+            return 1;
4315
+        }
4316
+        else
4317
+        {
4318
+            $this->error=$this->db->lasterror();
4319
+            $this->db->rollback();
4320
+            return  0;
4321
+        }
4322
+    }
4323
+
4324
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4325
+    /**
4326
+     *    Delete a link to resource line
4327
+     *
4328
+     *    @param	int		$rowid			Id of resource line to delete
4329
+     *    @param	int		$element		element name (for trigger) TODO: use $this->element into commonobject class
4330
+     *    @param	int		$notrigger		Disable all triggers
4331
+     *    @return   int						>0 if OK, <0 if KO
4332
+     */
4333
+    function delete_resource($rowid, $element, $notrigger=0)
4334
+    {
4335
+        // phpcs:enable
4336
+        global $user;
4337
+
4338
+        $this->db->begin();
4339
+
4340
+        $sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4341
+        $sql.= " WHERE rowid=".$rowid;
4342
+
4343
+        dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
4344
+
4345
+        $resql=$this->db->query($sql);
4346
+        if (! $resql)
4347
+        {
4348
+            $this->error=$this->db->lasterror();
4349
+            $this->db->rollback();
4350
+            return -1;
4351
+        }
4352
+        else
4353
+        {
4354
+            if (! $notrigger)
4355
+            {
4356
+                $result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4357
+                if ($result < 0) { $this->db->rollback(); return -1; }
4358
+            }
4359
+            $this->db->commit();
4360
+            return 1;
4361
+        }
4362
+    }
4363
+
4364
+
4365
+    /**
4366
+     * Overwrite magic function to solve problem of cloning object that are kept as references
4367
+     *
4368
+     * @return void
4369
+     */
4370
+    function __clone()
4371
+    {
4372
+        // Force a copy of this->lines, otherwise it will point to same object.
4373
+        if (isset($this->lines) && is_array($this->lines))
4374
+        {
4375
+            $nboflines=count($this->lines);
4376
+            for($i=0; $i < $nboflines; $i++)
4377
+            {
4378
+                $this->lines[$i] = clone $this->lines[$i];
4379
+            }
4380
+        }
4381
+    }
4382
+
4383
+    /**
4384
+     * Common function for all objects extending CommonObject for generating documents
4385
+     *
4386
+     * @param 	string 		$modelspath 	Relative folder where generators are placed
4387
+     * @param 	string 		$modele 		Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
4388
+     * @param 	Translate 	$outputlangs 	Output language to use
4389
+     * @param 	int 		$hidedetails 	1 to hide details. 0 by default
4390
+     * @param 	int 		$hidedesc 		1 to hide product description. 0 by default
4391
+     * @param 	int 		$hideref 		1 to hide product reference. 0 by default
4392
+     * @param   null|array  $moreparams     Array to provide more information
4393
+     * @return 	int 						>0 if OK, <0 if KO
4394
+     * @see	addFileIntoDatabaseIndex
4395
+     */
4396
+    protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4397
+    {
4398
+        global $conf, $langs, $user;
4399
+
4400
+        $srctemplatepath='';
4401
+
4402
+        // Increase limit for PDF build
4403
+        $err=error_reporting();
4404
+        error_reporting(0);
4405
+        @set_time_limit(120);
4406
+        error_reporting($err);
4407
+
4408
+        // If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4409
+        $tmp=explode(':',$modele,2);
4410
+        if (! empty($tmp[1]))
4411
+        {
4412
+            $modele=$tmp[0];
4413
+            $srctemplatepath=$tmp[1];
4414
+        }
4415
+
4416
+        // Search template files
4417
+        $file=''; $classname=''; $filefound=0;
4418
+        $dirmodels=array('/');
4419
+        if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
4420
+        foreach($dirmodels as $reldir)
4421
+        {
4422
+            foreach(array('doc','pdf') as $prefix)
4423
+            {
4424
+                if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4425
+                else $file = $prefix."_".$modele.".modules.php";
4426
+
4427
+                // On verifie l'emplacement du modele
4428
+                $file=dol_buildpath($reldir.$modelspath.$file,0);
4429
+                if (file_exists($file))
4430
+                {
4431
+                    $filefound=1;
4432
+                    $classname=$prefix.'_'.$modele;
4433
+                    break;
4434
+                }
4435
+            }
4436
+            if ($filefound) break;
4437
+        }
4438
+
4439
+        // If generator was found
4440
+        if ($filefound)
4441
+        {
4442
+            global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4443
+
4444
+            require_once $file;
4445
+
4446
+            $obj = new $classname($this->db);
4447
+
4448
+            // If generator is ODT, we must have srctemplatepath defined, if not we set it.
4449
+            if ($obj->type == 'odt' && empty($srctemplatepath))
4450
+            {
4451
+                $varfortemplatedir=$obj->scandir;
4452
+                if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
4453
+                {
4454
+                    $dirtoscan=$conf->global->$varfortemplatedir;
4455
+
4456
+                    $listoffiles=array();
4457
+
4458
+                    // Now we add first model found in directories scanned
4459
+                    $listofdir=explode(',',$dirtoscan);
4460
+                    foreach($listofdir as $key => $tmpdir)
4461
+                    {
4462
+                        $tmpdir=trim($tmpdir);
4463
+                        $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4464
+                        if (! $tmpdir) { unset($listofdir[$key]); continue; }
4465
+                        if (is_dir($tmpdir))
4466
+                        {
4467
+                            $tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4468
+                            if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4469
+                        }
4470
+                    }
4471
+
4472
+                    if (count($listoffiles))
4473
+                    {
4474
+                        foreach($listoffiles as $record)
4475
+                        {
4476
+                            $srctemplatepath=$record['fullname'];
4477
+                            break;
4478
+                        }
4479
+                    }
4480
+                }
4481
+
4482
+                if (empty($srctemplatepath))
4483
+                {
4484
+                    $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4485
+                    return -1;
4486
+                }
4487
+            }
4488
+
4489
+            if ($obj->type == 'odt' && ! empty($srctemplatepath))
4490
+            {
4491
+                if (! dol_is_file($srctemplatepath))
4492
+                {
4493
+                    $this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4494
+                    return -1;
4495
+                }
4496
+            }
4497
+
4498
+            // We save charset_output to restore it because write_file can change it if needed for
4499
+            // output format that does not support UTF8.
4500
+            $sav_charset_output=$outputlangs->charset_output;
4501
+
4502
+            if (in_array(get_class($this), array('Adherent')))
4503
+            {
4504
+                $arrayofrecords = array();   // The write_file of templates of adherent class need this var
4505
+                $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4506
+            }
4507
+            else
4508
+            {
4509
+                $resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4510
+            }
4511
+            // After call of write_file $obj->result['fullpath'] is set with generated file. It will be used to update the ECM database index.
4512
+
4513
+            if ($resultwritefile > 0)
4514
+            {
4515
+                $outputlangs->charset_output=$sav_charset_output;
4516
+
4517
+                // We delete old preview
4518
+                require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4519
+                dol_delete_preview($this);
4520
+
4521
+                // Index file in database
4522
+                if (! empty($obj->result['fullpath']))
4523
+                {
4524
+                    $destfull = $obj->result['fullpath'];
4525
+                    $upload_dir = dirname($destfull);
4526
+                    $destfile = basename($destfull);
4527
+                    $rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4528
+
4529
+                    if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4530
+                    {
4531
+                        $filename = basename($destfile);
4532
+                        $rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4533
+                        $rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4534
+
4535
+                        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
4536
+                        $ecmfile=new EcmFiles($this->db);
4537
+                        $result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename);
4538
+
4539
+                        // Set the public "share" key
4540
+                        $setsharekey = false;
4541
+                        if ($this->element == 'propal')
4542
+                        {
4543
+                            $useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL;	// Replace this with 1 when feature to make online signature is ok
4544
+                            if ($useonlinesignature) $setsharekey=true;
4545
+                            if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4546
+                        }
4547
+                        if ($this->element == 'commande'     && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))        $setsharekey=true;
4548
+                        if ($this->element == 'facture'      && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))      $setsharekey=true;
4549
+                        if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4550
+
4551
+                        if ($setsharekey)
4552
+                        {
4553
+                            if (empty($ecmfile->share))	// Because object not found or share not set yet
4554
+                            {
4555
+                                require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4556
+                                $ecmfile->share = getRandomPassword(true);
4557
+                            }
4558
+                        }
4559
+
4560
+                        if ($result > 0)
4561
+                        {
4562
+                            $ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4563
+                            $ecmfile->fullpath_orig = '';
4564
+                            $ecmfile->gen_or_uploaded = 'generated';
4565
+                            $ecmfile->description = '';    // indexed content
4566
+                            $ecmfile->keyword = '';        // keyword content
4567
+                            $result = $ecmfile->update($user);
4568
+                            if ($result < 0)
4569
+                            {
4570
+                                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4571
+                            }
4572
+                        }
4573
+                        else
4574
+                        {
4575
+                            $ecmfile->entity = $conf->entity;
4576
+                            $ecmfile->filepath = $rel_dir;
4577
+                            $ecmfile->filename = $filename;
4578
+                            $ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4579
+                            $ecmfile->fullpath_orig = '';
4580
+                            $ecmfile->gen_or_uploaded = 'generated';
4581
+                            $ecmfile->description = '';    // indexed content
4582
+                            $ecmfile->keyword = '';        // keyword content
4583
+                            $ecmfile->src_object_type = $this->table_element;
4584
+                            $ecmfile->src_object_id   = $this->id;
4585
+
4586
+                            $result = $ecmfile->create($user);
4587
+                            if ($result < 0)
4588
+                            {
4589
+                                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4590
+                            }
4591
+                        }
4592
+
4593
+                        /*$this->result['fullname']=$destfull;
4594
+						$this->result['filepath']=$ecmfile->filepath;
4595
+						$this->result['filename']=$ecmfile->filename;*/
4596
+                        //var_dump($obj->update_main_doc_field);exit;
4597
+
4598
+                        // Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4599
+                        $update_main_doc_field=0;
4600
+                        if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4601
+                        if ($update_main_doc_field && ! empty($this->table_element))
4602
+                        {
4603
+                            $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4604
+                            $sql.= ' WHERE rowid = '.$this->id;
4605
+                            $resql = $this->db->query($sql);
4606
+                            if (! $resql) dol_print_error($this->db);
4607
+                        }
4608
+                    }
4609
+                }
4610
+                else
4611
+                {
4612
+                    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);
4613
+                }
4614
+
4615
+                // Success in building document. We build meta file.
4616
+                dol_meta_create($this);
4617
+
4618
+                return 1;
4619
+            }
4620
+            else
4621
+            {
4622
+                $outputlangs->charset_output=$sav_charset_output;
4623
+                dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4624
+                return -1;
4625
+            }
4626
+        }
4627
+        else
4628
+        {
4629
+            $this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4630
+            dol_print_error('',$this->error);
4631
+            return -1;
4632
+        }
4633
+    }
4634
+
4635
+    /**
4636
+     *  Build thumb
4637
+     *  @TODO Move this into files.lib.php
4638
+     *
4639
+     *  @param      string	$file           Path file in UTF8 to original file to create thumbs from.
4640
+     *	@return		void
4641
+     */
4642
+    function addThumbs($file)
4643
+    {
4644
+        global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4645
+
4646
+        require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4647
+
4648
+        $file_osencoded=dol_osencode($file);
4649
+        if (file_exists($file_osencoded))
4650
+        {
4651
+            // Create small thumbs for company (Ratio is near 16/9)
4652
+            // Used on logon for example
4653
+            vignette($file_osencoded, $maxwidthsmall, $maxheightsmall, '_small', $quality);
4654
+
4655
+            // Create mini thumbs for company (Ratio is near 16/9)
4656
+            // Used on menu or for setup page for example
4657
+            vignette($file_osencoded, $maxwidthmini, $maxheightmini, '_mini', $quality);
4658
+        }
4659
+    }
4660
+
4661
+
4662
+    /* Functions common to commonobject and commonobjectline */
4663
+
4664
+    /* For default values */
4665
+
4666
+    /**
4667
+     * Return the default value to use for a field when showing the create form of object.
4668
+     * Return values in this order:
4669
+     * 1) If parameter is available into POST, we return it first.
4670
+     * 2) If not but an alternate value was provided as parameter of function, we return it.
4671
+     * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
4672
+     * 4) Return value found into database (TODO No yet implemented)
4673
+     *
4674
+     * @param   string              $fieldname          Name of field
4675
+     * @param   string              $alternatevalue     Alternate value to use
4676
+     * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4677
+     **/
4678
+    function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4679
+    {
4680
+        global $conf, $_POST;
4681
+
4682
+        // If param here has been posted, we use this value first.
4683
+        if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
4684
+
4685
+        if (isset($alternatevalue)) return $alternatevalue;
4686
+
4687
+        $newelement=$this->element;
4688
+        if ($newelement == 'facture') $newelement='invoice';
4689
+        if ($newelement == 'commande') $newelement='order';
4690
+        if (empty($newelement))
4691
+        {
4692
+            dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
4693
+            return '';
4694
+        }
4695
+
4696
+        $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4697
+        //var_dump($keyforfieldname);
4698
+        if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
4699
+
4700
+        // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4701
+    }
4702
+
4703
+
4704
+    /* For triggers */
4705
+
4706
+
4707
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4708
+    /**
4709
+     * Call trigger based on this instance.
4710
+     * Some context information may also be provided into array property this->context.
4711
+     * NB:  Error from trigger are stacked in interface->errors
4712
+     * NB2: If return code of triggers are < 0, action calling trigger should cancel all transaction.
4713
+     *
4714
+     * @param   string    $trigger_name   trigger's name to execute
4715
+     * @param   User      $user           Object user
4716
+     * @return  int                       Result of run_triggers
4717
+     */
4718
+    function call_trigger($trigger_name, $user)
4719
+    {
4720
+        // phpcs:enable
4721
+        global $langs,$conf;
4722
+
4723
+        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
4724
+        $interface=new Interfaces($this->db);
4725
+        $result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
4726
+
4727
+        if ($result < 0)
4728
+        {
4729
+            if (!empty($this->errors))
4730
+            {
4731
+                $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.
4732
+            }
4733
+            else
4734
+            {
4735
+                $this->errors=$interface->errors;
4736
+            }
4737
+        }
4738
+        return $result;
4739
+    }
4740
+
4741
+
4742
+    /* Functions for extrafields */
4743
+
4744
+
4745
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
4746
+    /**
4747
+     *  Function to get extra fields of an object into $this->array_options
4748
+     *  This method is in most cases called by method fetch of objects but you can call it separately.
4749
+     *
4750
+     *  @param	int		$rowid			Id of line. Use the id of object if not defined. Deprecated. Function must be called without parameters.
4751
+     *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
4752
+     *  @return	int						<0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
4753
+     */
4754
+    function fetch_optionals($rowid=null, $optionsArray=null)
4755
+    {
4756
+        // phpcs:enable
4757
+        if (empty($rowid)) $rowid=$this->id;
4758
+
4759
+        // To avoid SQL errors. Probably not the better solution though
4760
+        if (!$this->table_element) {
4761
+            return 0;
4762
+        }
4763
+
4764
+        $this->array_options=array();
4765
+
4766
+        if (! is_array($optionsArray))
4767
+        {
4768
+            // If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4769
+            // TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
4770
+            // global $extrafields;
4771
+            //if (! is_object($extrafields))
4772
+            //{
4773
+                // require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4774
+            $extrafields = new ExtraFields();
4775
+            //}
4776
+
4777
+            // Load array of extrafields for elementype = $this->table_element
4778
+            if (empty($extrafields->attributes[$this->table_element]['loaded']))
4779
+            {
4780
+                $extrafields->fetch_name_optionals_label($this->table_element);
4781
+            }
4782
+            $optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4783
+        }
4784
+        else
4785
+        {
4786
+            global $extrafields;
4787
+            dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4788
+        }
4789
+
4790
+        $table_element = $this->table_element;
4791
+        if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4792
+
4793
+        // Request to get complementary values
4794
+        if (is_array($optionsArray) && count($optionsArray) > 0)
4795
+        {
4796
+            $sql = "SELECT rowid";
4797
+            foreach ($optionsArray as $name => $label)
4798
+            {
4799
+                if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4800
+                {
4801
+                    $sql.= ", ".$name;
4802
+                }
4803
+            }
4804
+            $sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4805
+            $sql.= " WHERE fk_object = ".$rowid;
4806
+
4807
+            //dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4808
+            $resql=$this->db->query($sql);
4809
+            if ($resql)
4810
+            {
4811
+                $this->array_options = array();
4812
+                $numrows=$this->db->num_rows($resql);
4813
+                if ($numrows)
4814
+                {
4815
+                    $tab = $this->db->fetch_array($resql);
4816
+
4817
+                    foreach ($tab as $key => $value)
4818
+                    {
4819
+                        // 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)
4820
+                        if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4821
+                        {
4822
+                            // we can add this attribute to object
4823
+                            if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4824
+                            {
4825
+                                //var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4826
+                                $this->array_options["options_".$key]=$this->db->jdate($value);
4827
+                            }
4828
+                            else
4829
+                            {
4830
+                                $this->array_options["options_".$key]=$value;
4831
+                            }
4832
+
4833
+                            //var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
4834
+                        }
4835
+                    }
4836
+                }
4837
+
4838
+                $this->db->free($resql);
4839
+
4840
+                if ($numrows) return $numrows;
4841
+                else return 0;
4842
+            }
4843
+            else
4844
+            {
4845
+                dol_print_error($this->db);
4846
+                return -1;
4847
+            }
4848
+        }
4849
+        return 0;
4850
+    }
4851
+
4852
+    /**
4853
+     *	Delete all extra fields values for the current object.
4854
+     *
4855
+     *  @return	int		<0 if KO, >0 if OK
4856
+     */
4857
+    function deleteExtraFields()
4858
+    {
4859
+        $this->db->begin();
4860
+
4861
+        $table_element = $this->table_element;
4862
+        if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
4863
+
4864
+        $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4865
+        dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4866
+        $resql=$this->db->query($sql_del);
4867
+        if (! $resql)
4868
+        {
4869
+            $this->error=$this->db->lasterror();
4870
+            $this->db->rollback();
4871
+            return -1;
4872
+        }
4873
+        else
4874
+        {
4875
+            $this->db->commit();
4876
+            return 1;
4877
+        }
4878
+    }
4879
+
4880
+    /**
4881
+     *	Add/Update all extra fields values for the current object.
4882
+     *  Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
4883
+     *  This function delete record with all extrafields and insert them again from the array $this->array_options.
4884
+     *
4885
+     *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
4886
+     *  @param	User		$userused		Object user
4887
+     *  @return int 						-1=error, O=did nothing, 1=OK
4888
+     *  @see updateExtraField, setValueFrom
4889
+     */
4890
+    function insertExtraFields($trigger='', $userused=null)
4891
+    {
4892
+        global $conf,$langs,$user;
4893
+
4894
+        if (empty($userused)) $userused=$user;
4895
+
4896
+        $error=0;
4897
+
4898
+        if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
4899
+
4900
+        if (! empty($this->array_options))
4901
+        {
4902
+            // Check parameters
4903
+            $langs->load('admin');
4904
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4905
+            $extrafields = new ExtraFields($this->db);
4906
+            $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4907
+
4908
+            //Eliminate copied source object extra_fields that do not exist in target object
4909
+            $new_array_options=array();
4910
+            foreach ($this->array_options as $key => $value) {
4911
+                if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4912
+                    $new_array_options[$key] = $value;
4913
+                elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4914
+                    $new_array_options['options_'.$key] = $value;
4915
+            }
4916
+
4917
+            foreach($new_array_options as $key => $value)
4918
+            {
4919
+                    $attributeKey      = substr($key,8);   // Remove 'options_' prefix
4920
+                    $attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4921
+                    $attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4922
+                    $attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
4923
+                    $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$attributeKey];
4924
+
4925
+                    if ($attributeRequired)
4926
+                    {
4927
+                        $mandatorypb=false;
4928
+                        if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4929
+                        if ($this->array_options[$key] === '') $mandatorypb=true;
4930
+                        if ($mandatorypb)
4931
+                        {
4932
+                            dol_syslog($this->error);
4933
+                            $this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4934
+                            return -1;
4935
+                        }
4936
+                    }
4937
+
4938
+                //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
4939
+                //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
4940
+
4941
+                    switch ($attributeType)
4942
+                    {
4943
+                        case 'int':
4944
+                          if (!is_numeric($value) && $value!='')
4945
+                            {
4946
+                                $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4947
+                                return -1;
4948
+                            }
4949
+                            elseif ($value=='')
4950
+                            {
4951
+                                $new_array_options[$key] = null;
4952
+                            }
4953
+                            break;
4954
+                    case 'double':
4955
+                        $value = price2num($value);
4956
+                        if (!is_numeric($value) && $value!='')
4957
+                        {
4958
+                            dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4959
+                            $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4960
+                            return -1;
4961
+                        }
4962
+                        elseif ($value=='')
4963
+                        {
4964
+                            $new_array_options[$key] = null;
4965
+                        }
4966
+                        //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
4967
+                        $new_array_options[$key] = $value;
4968
+                        break;
4969
+                        /*case 'select':	// Not required, we chosed value='0' for undefined values
4970
+             			if ($value=='-1')
4971
+             			{
4972
+             				$this->array_options[$key] = null;
4973
+             			}
4974
+             			break;*/
4975
+                        case 'password':
4976
+                           $algo='';
4977
+                            if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4978
+                            {
4979
+                                // If there is an encryption choice, we use it to crypt data before insert
4980
+                                $tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4981
+                                $algo=reset($tmparrays);
4982
+                                if ($algo != '')
4983
+                                {
4984
+                                    //global $action;		// $action may be 'create', 'update', 'update_extras'...
4985
+                                    //var_dump($action);
4986
+                                    //var_dump($this->oldcopy);exit;
4987
+                                    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
4988
+                                    {
4989
+                                        //var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
4990
+                                        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.
4991
+                                        {
4992
+                                            $new_array_options[$key] = $this->array_options[$key];	// Value is kept
4993
+                                        }
4994
+                                    else
4995
+                                    {
4996
+                                        // var_dump($algo);
4997
+                                        $newvalue = dol_hash($this->array_options[$key], $algo);
4998
+                                        $new_array_options[$key] = $newvalue;
4999
+                                    }
5000
+                                    }
5001
+                                    else
5002
+                                    {
5003
+                                        $new_array_options[$key] = $this->array_options[$key];	// Value is kept
5004
+                                    }
5005
+                                }
5006
+                            }
5007
+                            else	// Common usage
5008
+                            {
5009
+                                $new_array_options[$key] = $this->array_options[$key];
5010
+                            }
5011
+                            break;
5012
+                        case 'price':
5013
+                        $new_array_options[$key] = price2num($this->array_options[$key]);
5014
+                        break;
5015
+                    case 'date':
5016
+                        $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5017
+                        break;
5018
+                    case 'datetime':
5019
+                        // If data is a string instead of a timestamp, we convert it
5020
+                        if (! is_int($this->array_options[$key])) {
5021
+                            $this->array_options[$key] = strtotime($this->array_options[$key]);
5022
+                        }
5023
+                        $new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5024
+                        break;
5025
+                        case 'link':
5026
+                        $param_list=array_keys($attributeParam['options']);
5027
+                        // 0 : ObjectName
5028
+                        // 1 : classPath
5029
+                        $InfoFieldList = explode(":", $param_list[0]);
5030
+                        dol_include_once($InfoFieldList[1]);
5031
+                        if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5032
+                        {
5033
+                            if ($value == '-1')	// -1 is key for no defined in combo list of objects
5034
+                            {
5035
+                                $new_array_options[$key]='';
5036
+                            }
5037
+                            elseif ($value)
5038
+                            {
5039
+                                $object = new $InfoFieldList[0]($this->db);
5040
+                                if (is_numeric($value)) $res=$object->fetch($value);
5041
+                                else $res=$object->fetch('',$value);
5042
+
5043
+                                if ($res > 0) $new_array_options[$key]=$object->id;
5044
+                                else
5045
+                                {
5046
+                                    $this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5047
+                                    $this->db->rollback();
5048
+                                    return -1;
5049
+                                }
5050
+                            }
5051
+                        }
5052
+                        else
5053
+                        {
5054
+                            dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5055
+                        }
5056
+                        break;
5057
+                    }
5058
+            }
5059
+
5060
+            $this->db->begin();
5061
+
5062
+            $table_element = $this->table_element;
5063
+            if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5064
+
5065
+            $sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5066
+            dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
5067
+            $this->db->query($sql_del);
5068
+
5069
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5070
+            foreach($new_array_options as $key => $value)
5071
+            {
5072
+                $attributeKey = substr($key,8);   // Remove 'options_' prefix
5073
+                // Add field of attribut
5074
+                if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5075
+                    $sql.=",".$attributeKey;
5076
+            }
5077
+            $sql .= ") VALUES (".$this->id;
5078
+
5079
+            foreach($new_array_options as $key => $value)
5080
+            {
5081
+                $attributeKey = substr($key,8);   // Remove 'options_' prefix
5082
+                // Add field of attribute
5083
+                if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5084
+                {
5085
+                    if ($new_array_options[$key] != '')
5086
+                    {
5087
+                        $sql.=",'".$this->db->escape($new_array_options[$key])."'";
5088
+                    }
5089
+                    else
5090
+                    {
5091
+                        $sql.=",null";
5092
+                    }
5093
+                }
5094
+            }
5095
+            $sql.=")";
5096
+
5097
+            dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5098
+            $resql = $this->db->query($sql);
5099
+            if (! $resql)
5100
+            {
5101
+                $this->error=$this->db->lasterror();
5102
+                $error++;
5103
+            }
5104
+
5105
+            if (! $error && $trigger)
5106
+            {
5107
+                // Call trigger
5108
+                $this->context=array('extrafieldaddupdate'=>1);
5109
+                $result=$this->call_trigger($trigger, $userused);
5110
+                if ($result < 0) $error++;
5111
+                // End call trigger
5112
+            }
5113
+
5114
+            if ($error)
5115
+            {
5116
+                $this->db->rollback();
5117
+                return -1;
5118
+            }
5119
+            else
5120
+            {
5121
+                $this->db->commit();
5122
+                return 1;
5123
+            }
5124
+        }
5125
+        else return 0;
5126
+    }
5127
+
5128
+    /**
5129
+     *	Update an extra field value for the current object.
5130
+     *  Data to describe values to update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
5131
+     *
5132
+     *  @param  string      $key    		Key of the extrafield (without starting 'options_')
5133
+     *  @param	string		$trigger		If defined, call also the trigger (for example COMPANY_MODIFY)
5134
+     *  @param	User		$userused		Object user
5135
+     *  @return int                 		-1=error, O=did nothing, 1=OK
5136
+     *  @see setValueFrom, insertExtraFields
5137
+     */
5138
+    function updateExtraField($key, $trigger=null, $userused=null)
5139
+    {
5140
+        global $conf,$langs,$user;
5141
+
5142
+        if (empty($userused)) $userused=$user;
5143
+
5144
+        $error=0;
5145
+
5146
+        if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
5147
+
5148
+        if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5149
+        {
5150
+            // Check parameters
5151
+            $langs->load('admin');
5152
+            require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5153
+            $extrafields = new ExtraFields($this->db);
5154
+            $target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5155
+
5156
+            $value=$this->array_options["options_".$key];
5157
+
5158
+            $attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5159
+            $attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
5160
+            $attributeParam    = $extrafields->attributes[$this->table_element]['param'][$key];
5161
+            $attributeRequired = $extrafields->attributes[$this->table_element]['required'][$key];
5162
+
5163
+            //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG);
5164
+            //dol_syslog("attributeType=".$attributeType, LOG_DEBUG);
5165
+
5166
+            switch ($attributeType)
5167
+            {
5168
+                case 'int':
5169
+                    if (!is_numeric($value) && $value!='')
5170
+                    {
5171
+                        $this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5172
+                        return -1;
5173
+                    }
5174
+                    elseif ($value=='')
5175
+                    {
5176
+                        $this->array_options["options_".$key] = null;
5177
+                    }
5178
+                    break;
5179
+                case 'double':
5180
+                    $value = price2num($value);
5181
+                    if (!is_numeric($value) && $value!='')
5182
+                    {
5183
+                        dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5184
+                        $this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5185
+                        return -1;
5186
+                    }
5187
+                    elseif ($value=='')
5188
+                    {
5189
+                        $this->array_options["options_".$key] = null;
5190
+                    }
5191
+                    //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG);
5192
+                    $this->array_options["options_".$key] = $value;
5193
+                    break;
5194
+                    /*case 'select':	// Not required, we chosed value='0' for undefined values
5195
+             		if ($value=='-1')
5196
+             		{
5197
+             			$this->array_options[$key] = null;
5198
+             		}
5199
+             		break;*/
5200
+                case 'price':
5201
+                    $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5202
+                    break;
5203
+                case 'date':
5204
+                    $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5205
+                    break;
5206
+                case 'datetime':
5207
+                    $this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5208
+                    break;
5209
+                case 'link':
5210
+                    $param_list=array_keys($attributeParam['options']);
5211
+                    // 0 : ObjectName
5212
+                    // 1 : classPath
5213
+                    $InfoFieldList = explode(":", $param_list[0]);
5214
+                    dol_include_once($InfoFieldList[1]);
5215
+                    if ($value)
5216
+                    {
5217
+                        $object = new $InfoFieldList[0]($this->db);
5218
+                        $object->fetch(0,$value);
5219
+                        $this->array_options["options_".$key]=$object->id;
5220
+                    }
5221
+                    break;
5222
+            }
5223
+
5224
+            $this->db->begin();
5225
+            $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5226
+            $sql .= " WHERE fk_object = ".$this->id;
5227
+            $resql = $this->db->query($sql);
5228
+            if (! $resql)
5229
+            {
5230
+                $error++;
5231
+                $this->error=$this->db->lasterror();
5232
+            }
5233
+
5234
+            if (! $error && $trigger)
5235
+            {
5236
+                // Call trigger
5237
+                $this->context=array('extrafieldupdate'=>1);
5238
+                $result=$this->call_trigger($trigger, $userused);
5239
+                if ($result < 0) $error++;
5240
+                // End call trigger
5241
+            }
5242
+
5243
+            if ($error)
5244
+            {
5245
+                dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5246
+                $this->db->rollback();
5247
+                return -1;
5248
+            }
5249
+            else
5250
+            {
5251
+                $this->db->commit();
5252
+                return 1;
5253
+            }
5254
+        }
5255
+        else return 0;
5256
+    }
5257
+
5258
+
5259
+    /**
5260
+     * Return HTML string to put an input field into a page
5261
+     * Code very similar with showInputField of extra fields
5262
+     *
5263
+     * @param  array   		$val	       Array of properties for field to show
5264
+     * @param  string  		$key           Key of attribute
5265
+     * @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)
5266
+     * @param  string  		$moreparam     To add more parameters on html input tag
5267
+     * @param  string  		$keysuffix     Prefix string to add into name and id of field (can be used to avoid duplicate names)
5268
+     * @param  string  		$keyprefix     Suffix string to add into name and id of field (can be used to avoid duplicate names)
5269
+     * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5270
+     * @return string
5271
+     */
5272
+    function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5273
+    {
5274
+        global $conf,$langs,$form;
5275
+
5276
+        if (! is_object($form))
5277
+        {
5278
+            require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5279
+            $form=new Form($this->db);
5280
+        }
5281
+
5282
+        $val=$this->fields[$key];
5283
+
5284
+        $out='';
5285
+        $type='';
5286
+        $param = array();
5287
+        $param['options']=array();
5288
+        $size =$this->fields[$key]['size'];
5289
+        // Because we work on extrafields
5290
+        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5291
+            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5292
+            $type ='link';
5293
+        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5294
+            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5295
+            $type ='link';
5296
+        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5297
+            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5298
+            $type ='sellist';
5299
+        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5300
+            $param['options']=array();
5301
+            $type ='varchar';
5302
+            $size=$reg[1];
5303
+        } elseif(preg_match('/varchar/', $val['type'])) {
5304
+            $param['options']=array();
5305
+            $type ='varchar';
5306
+        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5307
+            $param['options']=$this->fields[$key]['arrayofkeyval'];
5308
+            $type ='select';
5309
+        } else {
5310
+            $param['options']=array();
5311
+            $type =$this->fields[$key]['type'];
5312
+        }
5313
+
5314
+        $label=$this->fields[$key]['label'];
5315
+        //$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5316
+        $default=$this->fields[$key]['default'];
5317
+        $computed=$this->fields[$key]['computed'];
5318
+        $unique=$this->fields[$key]['unique'];
5319
+        $required=$this->fields[$key]['required'];
5320
+
5321
+        $langfile=$this->fields[$key]['langfile'];
5322
+        $list=$this->fields[$key]['list'];
5323
+        $hidden=abs($this->fields[$key]['visible'])!=1?1:0;
5324
+
5325
+        $objectid = $this->id;
5326
+
5327
+
5328
+        if ($computed)
5329
+        {
5330
+            if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5331
+            else return '';
5332
+        }
5333
+
5334
+
5335
+        // Use in priority showsize from parameters, then $val['css'] then autodefine
5336
+        if (empty($morecss) && ! empty($val['css']))
5337
+        {
5338
+            $showsize = $val['css'];
5339
+        }
5340
+        if (empty($morecss))
5341
+        {
5342
+            if ($type == 'date')
5343
+            {
5344
+                $morecss = 'minwidth100imp';
5345
+            }
5346
+            elseif ($type == 'datetime')
5347
+            {
5348
+                $morecss = 'minwidth200imp';
5349
+            }
5350
+            elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5351
+            {
5352
+                $morecss = 'maxwidth75';
5353
+                        }elseif ($type == 'url')
5354
+            {
5355
+                $morecss='minwidth400';
5356
+            }
5357
+            elseif ($type == 'boolean')
5358
+            {
5359
+                $morecss='';
5360
+            }
5361
+            else
5362
+            {
5363
+                if (round($size) < 12)
5364
+                {
5365
+                    $morecss = 'minwidth100';
5366
+                }
5367
+                else if (round($size) <= 48)
5368
+                {
5369
+                    $morecss = 'minwidth200';
5370
+                }
5371
+                else
5372
+                {
5373
+                    $morecss = 'minwidth400';
5374
+                }
5375
+            }
5376
+        }
5377
+
5378
+        if (in_array($type,array('date','datetime')))
5379
+        {
5380
+            $tmp=explode(',',$size);
5381
+            $newsize=$tmp[0];
5382
+
5383
+            $showtime = in_array($type,array('datetime')) ? 1 : 0;
5384
+
5385
+            // Do not show current date when field not required (see selectDate() method)
5386
+            if (!$required && $value == '') $value = '-1';
5387
+
5388
+            // TODO Must also support $moreparam
5389
+            $out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5390
+        }
5391
+        elseif (in_array($type,array('int','integer')))
5392
+        {
5393
+            $tmp=explode(',',$size);
5394
+            $newsize=$tmp[0];
5395
+            $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:'').'>';
5396
+        }
5397
+        elseif (preg_match('/varchar/', $type))
5398
+        {
5399
+            $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:'').'>';
5400
+        }
5401
+        elseif (in_array($type, array('mail', 'phone', 'url')))
5402
+        {
5403
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5404
+        }
5405
+        elseif ($type == 'text')
5406
+        {
5407
+            if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5408
+            {
5409
+                require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5410
+                $doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5411
+                $out=$doleditor->Create(1);
5412
+            }
5413
+            else
5414
+            {
5415
+                $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5416
+            }
5417
+        }
5418
+        elseif ($type == 'html')
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,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,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 == 'boolean')
5432
+        {
5433
+            $checked='';
5434
+            if (!empty($value)) {
5435
+                $checked=' checked value="1" ';
5436
+            } else {
5437
+                $checked=' value="1" ';
5438
+            }
5439
+            $out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5440
+        }
5441
+        elseif ($type == 'price')
5442
+        {
5443
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5444
+                $value=price($value);
5445
+            }
5446
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
5447
+        }
5448
+        elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5449
+        {
5450
+            if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5451
+                $value=price($value);
5452
+            }
5453
+            $out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5454
+        }
5455
+        elseif ($type == 'select')
5456
+        {
5457
+            $out = '';
5458
+            if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5459
+            {
5460
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5461
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5462
+            }
5463
+
5464
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5465
+                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5466
+            foreach ($param['options'] as $key => $val)
5467
+            {
5468
+                if ((string) $key == '') continue;
5469
+                list($val, $parent) = explode('|', $val);
5470
+                $out.='<option value="'.$key.'"';
5471
+                $out.= (((string) $value == (string) $key)?' selected':'');
5472
+                $out.= (!empty($parent)?' parent="'.$parent.'"':'');
5473
+                $out.='>'.$val.'</option>';
5474
+            }
5475
+            $out.='</select>';
5476
+        }
5477
+        elseif ($type == 'sellist')
5478
+        {
5479
+            $out = '';
5480
+            if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5481
+            {
5482
+                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5483
+                $out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5484
+            }
5485
+
5486
+            $out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5487
+            if (is_array($param['options']))
5488
+            {
5489
+                $param_list=array_keys($param['options']);
5490
+                $InfoFieldList = explode(":", $param_list[0]);
5491
+                $parentName='';
5492
+                $parentField='';
5493
+                // 0 : tableName
5494
+                // 1 : label field name
5495
+                // 2 : key fields name (if differ of rowid)
5496
+                // 3 : key field parent (for dependent lists)
5497
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5498
+                $keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5499
+
5500
+
5501
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5502
+                {
5503
+                    if (strpos($InfoFieldList[4], 'extra.') !== false)
5504
+                    {
5505
+                        $keyList='main.'.$InfoFieldList[2].' as rowid';
5506
+                    } else {
5507
+                        $keyList=$InfoFieldList[2].' as rowid';
5508
+                    }
5509
+                }
5510
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5511
+                {
5512
+                    list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5513
+                    $keyList.= ', '.$parentField;
5514
+                }
5515
+
5516
+                $fields_label = explode('|',$InfoFieldList[1]);
5517
+                if (is_array($fields_label))
5518
+                {
5519
+                    $keyList .=', ';
5520
+                    $keyList .= implode(', ', $fields_label);
5521
+                }
5522
+
5523
+                $sqlwhere='';
5524
+                $sql = 'SELECT '.$keyList;
5525
+                $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5526
+                if (!empty($InfoFieldList[4]))
5527
+                {
5528
+                    // can use SELECT request
5529
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5530
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5531
+                    }
5532
+
5533
+                    // current object id can be use into filter
5534
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5535
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5536
+                    } else {
5537
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5538
+                    }
5539
+                    //We have to join on extrafield table
5540
+                    if (strpos($InfoFieldList[4], 'extra')!==false)
5541
+                    {
5542
+                        $sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5543
+                        $sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5544
+                    }
5545
+                    else
5546
+                    {
5547
+                        $sqlwhere.= ' WHERE '.$InfoFieldList[4];
5548
+                    }
5549
+                }
5550
+                else
5551
+                {
5552
+                    $sqlwhere.= ' WHERE 1=1';
5553
+                }
5554
+                // Some tables may have field, some other not. For the moment we disable it.
5555
+                if (in_array($InfoFieldList[0],array('tablewithentity')))
5556
+                {
5557
+                    $sqlwhere.= ' AND entity = '.$conf->entity;
5558
+                }
5559
+                $sql.=$sqlwhere;
5560
+                //print $sql;
5561
+
5562
+                $sql .= ' ORDER BY ' . implode(', ', $fields_label);
5563
+
5564
+                dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5565
+                $resql = $this->db->query($sql);
5566
+                if ($resql)
5567
+                {
5568
+                    $out.='<option value="0">&nbsp;</option>';
5569
+                    $num = $this->db->num_rows($resql);
5570
+                    $i = 0;
5571
+                    while ($i < $num)
5572
+                    {
5573
+                        $labeltoshow='';
5574
+                        $obj = $this->db->fetch_object($resql);
5575
+
5576
+                        // Several field into label (eq table:code|libelle:rowid)
5577
+                        $notrans = false;
5578
+                        $fields_label = explode('|',$InfoFieldList[1]);
5579
+                        if (is_array($fields_label))
5580
+                        {
5581
+                            $notrans = true;
5582
+                            foreach ($fields_label as $field_toshow)
5583
+                            {
5584
+                                $labeltoshow.= $obj->$field_toshow.' ';
5585
+                            }
5586
+                        }
5587
+                        else
5588
+                        {
5589
+                            $labeltoshow=$obj->{$InfoFieldList[1]};
5590
+                        }
5591
+                        $labeltoshow=dol_trunc($labeltoshow,45);
5592
+
5593
+                        if ($value == $obj->rowid)
5594
+                        {
5595
+                            foreach ($fields_label as $field_toshow)
5596
+                            {
5597
+                                $translabel=$langs->trans($obj->$field_toshow);
5598
+                                if ($translabel!=$obj->$field_toshow) {
5599
+                                    $labeltoshow=dol_trunc($translabel,18).' ';
5600
+                                }else {
5601
+                                    $labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5602
+                                }
5603
+                            }
5604
+                            $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5605
+                        }
5606
+                        else
5607
+                        {
5608
+                            if (! $notrans)
5609
+                            {
5610
+                                $translabel=$langs->trans($obj->{$InfoFieldList[1]});
5611
+                                if ($translabel!=$obj->{$InfoFieldList[1]}) {
5612
+                                    $labeltoshow=dol_trunc($translabel,18);
5613
+                                }
5614
+                                else {
5615
+                                    $labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5616
+                                }
5617
+                            }
5618
+                            if (empty($labeltoshow)) $labeltoshow='(not defined)';
5619
+                            if ($value==$obj->rowid)
5620
+                            {
5621
+                                $out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5622
+                            }
5623
+
5624
+                            if (!empty($InfoFieldList[3]) && $parentField)
5625
+                            {
5626
+                                $parent = $parentName.':'.$obj->{$parentField};
5627
+                            }
5628
+
5629
+                            $out.='<option value="'.$obj->rowid.'"';
5630
+                            $out.= ($value==$obj->rowid?' selected':'');
5631
+                            $out.= (!empty($parent)?' parent="'.$parent.'"':'');
5632
+                            $out.='>'.$labeltoshow.'</option>';
5633
+                        }
5634
+
5635
+                        $i++;
5636
+                    }
5637
+                    $this->db->free($resql);
5638
+                }
5639
+                else {
5640
+                    print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5641
+                }
5642
+            }
5643
+            $out.='</select>';
5644
+        }
5645
+        elseif ($type == 'checkbox')
5646
+        {
5647
+            $value_arr=explode(',',$value);
5648
+            $out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5649
+        }
5650
+        elseif ($type == 'radio')
5651
+        {
5652
+            $out='';
5653
+            foreach ($param['options'] as $keyopt => $val)
5654
+            {
5655
+                $out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5656
+                $out.=' value="'.$keyopt.'"';
5657
+                $out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5658
+                $out.= ($value==$keyopt?'checked':'');
5659
+                $out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5660
+            }
5661
+        }
5662
+        elseif ($type == 'chkbxlst')
5663
+        {
5664
+            if (is_array($value)) {
5665
+                $value_arr = $value;
5666
+            }
5667
+            else {
5668
+                $value_arr = explode(',', $value);
5669
+            }
5670
+
5671
+            if (is_array($param['options'])) {
5672
+                $param_list = array_keys($param['options']);
5673
+                $InfoFieldList = explode(":", $param_list[0]);
5674
+                $parentName='';
5675
+                $parentField='';
5676
+                // 0 : tableName
5677
+                // 1 : label field name
5678
+                // 2 : key fields name (if differ of rowid)
5679
+                // 3 : key field parent (for dependent lists)
5680
+                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5681
+                $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5682
+
5683
+                if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5684
+                    list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5685
+                    $keyList .= ', ' . $parentField;
5686
+                }
5687
+                if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5688
+                    if (strpos($InfoFieldList[4], 'extra.') !== false) {
5689
+                        $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5690
+                    } else {
5691
+                        $keyList = $InfoFieldList[2] . ' as rowid';
5692
+                    }
5693
+                }
5694
+
5695
+                $fields_label = explode('|', $InfoFieldList[1]);
5696
+                if (is_array($fields_label)) {
5697
+                    $keyList .= ', ';
5698
+                    $keyList .= implode(', ', $fields_label);
5699
+                }
5700
+
5701
+                $sqlwhere = '';
5702
+                $sql = 'SELECT ' . $keyList;
5703
+                $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5704
+                if (! empty($InfoFieldList[4])) {
5705
+
5706
+                    // can use SELECT request
5707
+                    if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5708
+                        $InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5709
+                    }
5710
+
5711
+                    // current object id can be use into filter
5712
+                    if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5713
+                        $InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5714
+                    } else {
5715
+                        $InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5716
+                    }
5717
+
5718
+                    // We have to join on extrafield table
5719
+                    if (strpos($InfoFieldList[4], 'extra') !== false) {
5720
+                        $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5721
+                        $sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5722
+                    } else {
5723
+                        $sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5724
+                    }
5725
+                } else {
5726
+                    $sqlwhere .= ' WHERE 1=1';
5727
+                }
5728
+                // Some tables may have field, some other not. For the moment we disable it.
5729
+                if (in_array($InfoFieldList[0], array ('tablewithentity')))
5730
+                {
5731
+                    $sqlwhere .= ' AND entity = ' . $conf->entity;
5732
+                }
5733
+                // $sql.=preg_replace('/^ AND /','',$sqlwhere);
5734
+                // print $sql;
5735
+
5736
+                $sql .= $sqlwhere;
5737
+                dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5738
+                $resql = $this->db->query($sql);
5739
+                if ($resql) {
5740
+                    $num = $this->db->num_rows($resql);
5741
+                    $i = 0;
5742
+
5743
+                    $data=array();
5744
+
5745
+                    while ( $i < $num ) {
5746
+                        $labeltoshow = '';
5747
+                        $obj = $this->db->fetch_object($resql);
5748
+
5749
+                        $notrans = false;
5750
+                        // Several field into label (eq table:code|libelle:rowid)
5751
+                        $fields_label = explode('|', $InfoFieldList[1]);
5752
+                        if (is_array($fields_label)) {
5753
+                            $notrans = true;
5754
+                            foreach ( $fields_label as $field_toshow ) {
5755
+                                $labeltoshow .= $obj->$field_toshow . ' ';
5756
+                            }
5757
+                        } else {
5758
+                            $labeltoshow = $obj->{$InfoFieldList[1]};
5759
+                        }
5760
+                        $labeltoshow = dol_trunc($labeltoshow, 45);
5761
+
5762
+                        if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5763
+                            foreach ( $fields_label as $field_toshow ) {
5764
+                                $translabel = $langs->trans($obj->$field_toshow);
5765
+                                if ($translabel != $obj->$field_toshow) {
5766
+                                    $labeltoshow = dol_trunc($translabel, 18) . ' ';
5767
+                                } else {
5768
+                                    $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5769
+                                }
5770
+                            }
5771
+
5772
+                            $data[$obj->rowid]=$labeltoshow;
5773
+                        } else {
5774
+                            if (! $notrans) {
5775
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
5776
+                                if ($translabel != $obj->{$InfoFieldList[1]}) {
5777
+                                    $labeltoshow = dol_trunc($translabel, 18);
5778
+                                } else {
5779
+                                    $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5780
+                                }
5781
+                            }
5782
+                            if (empty($labeltoshow))
5783
+                                $labeltoshow = '(not defined)';
5784
+
5785
+                                if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5786
+                                    $data[$obj->rowid]=$labeltoshow;
5787
+                                }
5788
+
5789
+                                if (! empty($InfoFieldList[3]) && $parentField) {
5790
+                                    $parent = $parentName . ':' . $obj->{$parentField};
5791
+                                }
5792
+
5793
+                                $data[$obj->rowid]=$labeltoshow;
5794
+                        }
5795
+
5796
+                        $i ++;
5797
+                    }
5798
+                    $this->db->free($resql);
5799
+
5800
+                    $out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5801
+                } else {
5802
+                    print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5803
+                }
5804
+            }
5805
+        }
5806
+        elseif ($type == 'link')
5807
+        {
5808
+            $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5809
+            $showempty=(($required && $default != '')?0:1);
5810
+            $out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5811
+            if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
5812
+            {
5813
+                        list($class,$classfile)=explode(':',$param_list[0]);
5814
+                        if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5815
+                        else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5816
+                        $out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5817
+                        // TODO Add Javascript code to add input fields contents to new elements urls
5818
+            }
5819
+        }
5820
+        elseif ($type == 'password')
5821
+        {
5822
+            // If prefix is 'search_', field is used as a filter, we use a common text field.
5823
+            $out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5824
+        }
5825
+        elseif ($type == 'array')
5826
+        {
5827
+            $newval = $val;
5828
+            $newval['type'] = 'varchar(256)';
5829
+
5830
+            $out='';
5831
+
5832
+            $inputs = array();
5833
+            if(! empty($value)) {
5834
+                foreach($value as $option) {
5835
+                    $out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5836
+                    $out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5837
+                }
5838
+            }
5839
+
5840
+            $out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5841
+
5842
+            $newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5843
+            $newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5844
+
5845
+            if(! empty($conf->use_javascript_ajax)) {
5846
+                $out.= '
5847
+					<script type="text/javascript">
5848
+					$(document).ready(function() {
5849
+						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
5850
+							$("'.dol_escape_js($newInput).'").insertBefore(this);
5851
+						});
5852
+
5853
+						$(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
5854
+							$(this).parent().remove();
5855
+						});
5856
+					});
5857
+					</script>';
5858
+            }
5859
+        }
5860
+        if (!empty($hidden)) {
5861
+            $out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5862
+        }
5863
+        /* Add comments
5864
+		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
5865
+		 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
5866
+		 */
5867
+        return $out;
5868
+    }
5869
+
5870
+    /**
5871
+     * Return HTML string to show a field into a page
5872
+     * Code very similar with showOutputField of extra fields
5873
+     *
5874
+     * @param  array   $val		       Array of properties of field to show
5875
+     * @param  string  $key            Key of attribute
5876
+     * @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)
5877
+     * @param  string  $moreparam      To add more parametes on html input tag
5878
+     * @param  string  $keysuffix      Prefix string to add into name and id of field (can be used to avoid duplicate names)
5879
+     * @param  string  $keyprefix      Suffix string to add into name and id of field (can be used to avoid duplicate names)
5880
+     * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5881
+     * @return string
5882
+     */
5883
+    function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5884
+    {
5885
+        global $conf,$langs,$form;
5886
+
5887
+        if (! is_object($form))
5888
+        {
5889
+            require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5890
+            $form=new Form($this->db);
5891
+        }
5892
+
5893
+        $objectid = $this->id;
5894
+        $label = $val['label'];
5895
+        $type  = $val['type'];
5896
+        $size  = $val['css'];
5897
+
5898
+        // Convert var to be able to share same code than showOutputField of extrafields
5899
+        if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5900
+        {
5901
+            $type = 'varchar';		// convert varchar(xx) int varchar
5902
+            $size = $reg[1];
5903
+        }
5904
+        elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5905
+        if (is_array($val['arrayofkeyval'])) $type='select';
5906
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5907
+
5908
+        $default=$val['default'];
5909
+        $computed=$val['computed'];
5910
+        $unique=$val['unique'];
5911
+        $required=$val['required'];
5912
+        $param=$val['param'];
5913
+        if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5914
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5915
+        {
5916
+            $type='link';
5917
+            $param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5918
+        }
5919
+        $langfile=$val['langfile'];
5920
+        $list=$val['list'];
5921
+        $help=$val['help'];
5922
+        $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)
5923
+
5924
+        if ($hidden) return '';
5925
+
5926
+        // If field is a computed field, value must become result of compute
5927
+        if ($computed)
5928
+        {
5929
+            // Make the eval of compute string
5930
+            //var_dump($computed);
5931
+            $value = dol_eval($computed, 1, 0);
5932
+        }
5933
+
5934
+        if (empty($showsize))
5935
+        {
5936
+            if ($type == 'date')
5937
+            {
5938
+                //$showsize=10;
5939
+                $showsize = 'minwidth100imp';
5940
+            }
5941
+            elseif ($type == 'datetime')
5942
+            {
5943
+                //$showsize=19;
5944
+                $showsize = 'minwidth200imp';
5945
+            }
5946
+            elseif (in_array($type,array('int','double','price')))
5947
+            {
5948
+                //$showsize=10;
5949
+                $showsize = 'maxwidth75';
5950
+            }
5951
+            elseif ($type == 'url')
5952
+            {
5953
+                $showsize='minwidth400';
5954
+            }
5955
+            elseif ($type == 'boolean')
5956
+            {
5957
+                $showsize='';
5958
+            }
5959
+            else
5960
+            {
5961
+                if (round($size) < 12)
5962
+                {
5963
+                    $showsize = 'minwidth100';
5964
+                }
5965
+                else if (round($size) <= 48)
5966
+                {
5967
+                    $showsize = 'minwidth200';
5968
+                }
5969
+                else
5970
+                {
5971
+                    //$showsize=48;
5972
+                    $showsize = 'minwidth400';
5973
+                }
5974
+            }
5975
+        }
5976
+
5977
+        // Format output value differently according to properties of field
5978
+        if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5979
+        elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5980
+        elseif ($type == 'date')
5981
+        {
5982
+            if(! empty($value)) {
5983
+                $value=dol_print_date($value,'day');
5984
+            } else {
5985
+                $value='';
5986
+            }
5987
+        }
5988
+        elseif ($type == 'datetime')
5989
+        {
5990
+            if(! empty($value)) {
5991
+                $value=dol_print_date($value,'dayhour');
5992
+            } else {
5993
+                $value='';
5994
+            }
5995
+        }
5996
+        elseif ($type == 'double')
5997
+        {
5998
+            if (!empty($value)) {
5999
+                $value=price($value);
6000
+            }
6001
+        }
6002
+        elseif ($type == 'boolean')
6003
+        {
6004
+            $checked='';
6005
+            if (!empty($value)) {
6006
+                $checked=' checked ';
6007
+            }
6008
+            $value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6009
+        }
6010
+        elseif ($type == 'mail')
6011
+        {
6012
+            $value=dol_print_email($value,0,0,0,64,1,1);
6013
+        }
6014
+        elseif ($type == 'url')
6015
+        {
6016
+            $value=dol_print_url($value,'_blank',32,1);
6017
+        }
6018
+        elseif ($type == 'phone')
6019
+        {
6020
+            $value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6021
+        }
6022
+        elseif ($type == 'price')
6023
+        {
6024
+            $value=price($value,0,$langs,0,0,-1,$conf->currency);
6025
+        }
6026
+        elseif ($type == 'select')
6027
+        {
6028
+            $value=$param['options'][$value];
6029
+        }
6030
+        elseif ($type == 'sellist')
6031
+        {
6032
+            $param_list=array_keys($param['options']);
6033
+            $InfoFieldList = explode(":", $param_list[0]);
6034
+
6035
+            $selectkey="rowid";
6036
+            $keyList='rowid';
6037
+
6038
+            if (count($InfoFieldList)>=3)
6039
+            {
6040
+                $selectkey = $InfoFieldList[2];
6041
+                $keyList=$InfoFieldList[2].' as rowid';
6042
+            }
6043
+
6044
+            $fields_label = explode('|',$InfoFieldList[1]);
6045
+            if(is_array($fields_label)) {
6046
+                $keyList .=', ';
6047
+                $keyList .= implode(', ', $fields_label);
6048
+            }
6049
+
6050
+            $sql = 'SELECT '.$keyList;
6051
+            $sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6052
+            if (strpos($InfoFieldList[4], 'extra')!==false)
6053
+            {
6054
+                $sql.= ' as main';
6055
+            }
6056
+            if ($selectkey=='rowid' && empty($value)) {
6057
+                $sql.= " WHERE ".$selectkey."=0";
6058
+            } elseif ($selectkey=='rowid') {
6059
+                $sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6060
+            }else {
6061
+                $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6062
+            }
6063
+
6064
+            //$sql.= ' AND entity = '.$conf->entity;
6065
+
6066
+            dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
6067
+            $resql = $this->db->query($sql);
6068
+            if ($resql)
6069
+            {
6070
+                $value='';	// value was used, so now we reste it to use it to build final output
6071
+
6072
+                $obj = $this->db->fetch_object($resql);
6073
+
6074
+                // Several field into label (eq table:code|libelle:rowid)
6075
+                $fields_label = explode('|',$InfoFieldList[1]);
6076
+
6077
+                if(is_array($fields_label) && count($fields_label)>1)
6078
+                {
6079
+                    foreach ($fields_label as $field_toshow)
6080
+                    {
6081
+                        $translabel='';
6082
+                        if (!empty($obj->$field_toshow)) {
6083
+                            $translabel=$langs->trans($obj->$field_toshow);
6084
+                        }
6085
+                        if ($translabel!=$field_toshow) {
6086
+                            $value.=dol_trunc($translabel,18).' ';
6087
+                        }else {
6088
+                            $value.=$obj->$field_toshow.' ';
6089
+                        }
6090
+                    }
6091
+                }
6092
+                else
6093
+                {
6094
+                    $translabel='';
6095
+                    if (!empty($obj->{$InfoFieldList[1]})) {
6096
+                        $translabel=$langs->trans($obj->{$InfoFieldList[1]});
6097
+                    }
6098
+                    if ($translabel!=$obj->{$InfoFieldList[1]}) {
6099
+                        $value=dol_trunc($translabel,18);
6100
+                    }else {
6101
+                        $value=$obj->{$InfoFieldList[1]};
6102
+                    }
6103
+                }
6104
+            }
6105
+            else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6106
+        }
6107
+        elseif ($type == 'radio')
6108
+        {
6109
+            $value=$param['options'][$value];
6110
+        }
6111
+        elseif ($type == 'checkbox')
6112
+        {
6113
+            $value_arr=explode(',',$value);
6114
+            $value='';
6115
+            if (is_array($value_arr) && count($value_arr)>0)
6116
+            {
6117
+                foreach ($value_arr as $keyval=>$valueval) {
6118
+                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6119
+                }
6120
+                $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6121
+            }
6122
+        }
6123
+        elseif ($type == 'chkbxlst')
6124
+        {
6125
+            $value_arr = explode(',', $value);
6126
+
6127
+            $param_list = array_keys($param['options']);
6128
+            $InfoFieldList = explode(":", $param_list[0]);
6129
+
6130
+            $selectkey = "rowid";
6131
+            $keyList = 'rowid';
6132
+
6133
+            if (count($InfoFieldList) >= 3) {
6134
+                $selectkey = $InfoFieldList[2];
6135
+                $keyList = $InfoFieldList[2] . ' as rowid';
6136
+            }
6137
+
6138
+            $fields_label = explode('|', $InfoFieldList[1]);
6139
+            if (is_array($fields_label)) {
6140
+                $keyList .= ', ';
6141
+                $keyList .= implode(', ', $fields_label);
6142
+            }
6143
+
6144
+            $sql = 'SELECT ' . $keyList;
6145
+            $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6146
+            if (strpos($InfoFieldList[4], 'extra') !== false) {
6147
+                $sql .= ' as main';
6148
+            }
6149
+            // $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6150
+            // $sql.= ' AND entity = '.$conf->entity;
6151
+
6152
+            dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6153
+            $resql = $this->db->query($sql);
6154
+            if ($resql) {
6155
+                $value = ''; // value was used, so now we reste it to use it to build final output
6156
+                $toprint=array();
6157
+                while ( $obj = $this->db->fetch_object($resql) ) {
6158
+
6159
+                    // Several field into label (eq table:code|libelle:rowid)
6160
+                    $fields_label = explode('|', $InfoFieldList[1]);
6161
+                    if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6162
+                        if (is_array($fields_label) && count($fields_label) > 1) {
6163
+                            foreach ( $fields_label as $field_toshow ) {
6164
+                                $translabel = '';
6165
+                                if (! empty($obj->$field_toshow)) {
6166
+                                    $translabel = $langs->trans($obj->$field_toshow);
6167
+                                }
6168
+                                if ($translabel != $field_toshow) {
6169
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6170
+                                } else {
6171
+                                    $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6172
+                                }
6173
+                            }
6174
+                        } else {
6175
+                            $translabel = '';
6176
+                            if (! empty($obj->{$InfoFieldList[1]})) {
6177
+                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
6178
+                            }
6179
+                            if ($translabel != $obj->{$InfoFieldList[1]}) {
6180
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6181
+                            } else {
6182
+                                $toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6183
+                            }
6184
+                        }
6185
+                    }
6186
+                }
6187
+                $value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6188
+            } else {
6189
+                dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6190
+            }
6191
+        }
6192
+        elseif ($type == 'link')
6193
+        {
6194
+            $out='';
6195
+
6196
+            // only if something to display (perf)
6197
+            if ($value)
6198
+            {
6199
+                $param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6200
+
6201
+                $InfoFieldList = explode(":", $param_list[0]);
6202
+                $classname=$InfoFieldList[0];
6203
+                $classpath=$InfoFieldList[1];
6204
+                $getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6205
+                if (! empty($classpath))
6206
+                {
6207
+                    dol_include_once($InfoFieldList[1]);
6208
+                    if ($classname && class_exists($classname))
6209
+                    {
6210
+                        $object = new $classname($this->db);
6211
+                        $object->fetch($value);
6212
+                        $value=$object->getNomUrl($getnomurlparam);
6213
+                    }
6214
+                }
6215
+                else
6216
+                {
6217
+                    dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6218
+                    return 'Error bad setup of extrafield';
6219
+                }
6220
+            }
6221
+            else $value='';
6222
+        }
6223
+        elseif ($type == 'text' || $type == 'html')
6224
+        {
6225
+            $value=dol_htmlentitiesbr($value);
6226
+        }
6227
+        elseif ($type == 'password')
6228
+        {
6229
+            $value=preg_replace('/./i','*',$value);
6230
+        }
6231
+        elseif ($type == 'array')
6232
+        {
6233
+            $value = implode('<br>', $value);
6234
+        }
6235
+
6236
+        //print $type.'-'.$size;
6237
+        $out=$value;
6238
+
6239
+        return $out;
6240
+    }
6241
+
6242
+
6243
+    /**
6244
+     * Function to show lines of extrafields with output datas
6245
+     *
6246
+     * @param 	Extrafields $extrafields    Extrafield Object
6247
+     * @param 	string      $mode           Show output (view) or input (edit) for extrafield
6248
+     * @param 	array       $params         Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
6249
+     * @param 	string      $keysuffix      Suffix string to add after name and id of field (can be used to avoid duplicate names)
6250
+     * @param 	string      $keyprefix      Prefix string to add before name and id of field (can be used to avoid duplicate names)
6251
+     * @param	string		$onetrtd		All fields in same tr td
6252
+     * @return 	string
6253
+     */
6254
+    function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6255
+    {
6256
+        global $db, $conf, $langs, $action, $form;
6257
+
6258
+        if (! is_object($form)) $form=new Form($db);
6259
+
6260
+        $out = '';
6261
+
6262
+        if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
6263
+        {
6264
+            $out .= "\n";
6265
+            $out .= '<!-- showOptionalsInput --> ';
6266
+            $out .= "\n";
6267
+
6268
+            $e = 0;
6269
+            foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6270
+            {
6271
+                // Show only the key field in params
6272
+                if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6273
+
6274
+                $enabled = 1;
6275
+                if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
6276
+                {
6277
+                    $enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
6278
+                }
6279
+
6280
+                $perms = 1;
6281
+                if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
6282
+                {
6283
+                    $perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6284
+                }
6285
+
6286
+                if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6287
+                if (empty($perms)) continue;
6288
+
6289
+                // Load language if required
6290
+                if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6291
+
6292
+                $colspan='3';
6293
+                if (is_array($params) && count($params)>0) {
6294
+                    if (array_key_exists('colspan',$params)) {
6295
+                        $colspan=$params['colspan'];
6296
+                    }
6297
+                }
6298
+
6299
+                switch($mode) {
6300
+                    case "view":
6301
+                        $value=$this->array_options["options_".$key.$keysuffix];
6302
+                        break;
6303
+                    case "edit":
6304
+                        $getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6305
+                        // GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6306
+                        if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6307
+                        {
6308
+                            if (is_array($getposttemp)) {
6309
+                                // $getposttemp is an array but following code expects a comma separated string
6310
+                                $value = implode(",", $getposttemp);
6311
+                            } else {
6312
+                                $value = $getposttemp;
6313
+                            }
6314
+                        } else {
6315
+                            $value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6316
+                        }
6317
+                        //var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6318
+                        break;
6319
+                }
6320
+
6321
+                if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6322
+                {
6323
+                    $out .= $extrafields->showSeparator($key, $this);
6324
+                }
6325
+                else
6326
+                {
6327
+                    $csstyle='';
6328
+                    $class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6329
+                    if (is_array($params) && count($params)>0) {
6330
+                        if (array_key_exists('style',$params)) {
6331
+                            $csstyle=$params['style'];
6332
+                        }
6333
+                    }
6334
+
6335
+                    // add html5 elements
6336
+                    $domData  = ' data-element="extrafield"';
6337
+                    $domData .= ' data-targetelement="'.$this->element.'"';
6338
+                    $domData .= ' data-targetid="'.$this->id.'"';
6339
+
6340
+                    $html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : '';
6341
+
6342
+                    $out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
6343
+
6344
+                    if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
6345
+                    {
6346
+                        if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan='0'; }
6347
+                    }
6348
+
6349
+                    if ($action == 'selectlines') { $colspan++; }
6350
+
6351
+                    // Convert date into timestamp format (value in memory must be a timestamp)
6352
+                    if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6353
+                    {
6354
+                        $datenotinstring = $this->array_options['options_' . $key];
6355
+                        if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6356
+                        {
6357
+                            $datenotinstring = $this->db->jdate($datenotinstring);
6358
+                        }
6359
+                        $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;
6360
+                    }
6361
+                    // Convert float submited string into real php numeric (value in memory must be a php numeric)
6362
+                    if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6363
+                    {
6364
+                        $value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6365
+                    }
6366
+
6367
+                    $labeltoshow = $langs->trans($label);
6368
+
6369
+                    $out .= '<td class="titlefield';
6370
+                    if (GETPOST('action','none') == 'create') $out.='create';
6371
+                    if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6372
+                    $out .= '">';
6373
+                    if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6374
+                    else $out .= $labeltoshow;
6375
+                    $out .= '</td>';
6376
+
6377
+                    $html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6378
+                    $out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6379
+
6380
+                    switch($mode) {
6381
+                        case "view":
6382
+                            $out .= $extrafields->showOutputField($key, $value);
6383
+                            break;
6384
+                        case "edit":
6385
+                            $out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id);
6386
+                            break;
6387
+                    }
6388
+
6389
+                    $out .= '</td>';
6390
+
6391
+                    if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
6392
+                    else $out .= '</tr>';
6393
+                    $e++;
6394
+                }
6395
+            }
6396
+            $out .= "\n";
6397
+            // Add code to manage list depending on others
6398
+            if (! empty($conf->use_javascript_ajax)) {
6399
+                $out .= '
6400
+				<script type="text/javascript">
6401
+				    jQuery(document).ready(function() {
6402
+				    	function showOptions(child_list, parent_list)
6403
+				    	{
6404
+				    		var val = $("select[name=\"options_"+parent_list+"\"]").val();
6405
+				    		var parentVal = parent_list + ":" + val;
6406
+							if(val > 0) {
6407
+					    		$("select[name=\""+child_list+"\"] option[parent]").hide();
6408
+					    		$("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
6409
+							} else {
6410
+								$("select[name=\""+child_list+"\"] option").show();
5603 6411
 							}
5604
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
6412
+				    	}
6413
+						function setListDependencies() {
6414
+					    	jQuery("select option[parent]").parent().each(function() {
6415
+					    		var child_list = $(this).attr("name");
6416
+								var parent = $(this).find("option[parent]:first").attr("parent");
6417
+								var infos = parent.split(":");
6418
+								var parent_list = infos[0];
6419
+								$("select[name=\""+parent_list+"\"]").change(function() {
6420
+									showOptions(child_list, parent_list);
6421
+								});
6422
+					    	});
5605 6423
 						}
5606
-						else
5607
-						{
5608
-							if (! $notrans)
5609
-							{
5610
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5611
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5612
-									$labeltoshow=dol_trunc($translabel,18);
5613
-								}
5614
-								else {
5615
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5616
-								}
5617
-							}
5618
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
5619
-							if ($value==$obj->rowid)
5620
-							{
5621
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5622
-							}
5623 6424
 
5624
-							if (!empty($InfoFieldList[3]) && $parentField)
5625
-							{
5626
-								$parent = $parentName.':'.$obj->{$parentField};
5627
-							}
6425
+						setListDependencies();
6426
+				    });
6427
+				</script>'."\n";
6428
+                $out .= '<!-- /showOptionalsInput --> '."\n";
6429
+            }
6430
+        }
6431
+        return $out;
6432
+    }
5628 6433
 
5629
-							$out.='<option value="'.$obj->rowid.'"';
5630
-							$out.= ($value==$obj->rowid?' selected':'');
5631
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5632
-							$out.='>'.$labeltoshow.'</option>';
5633
-						}
5634 6434
 
5635
-						$i++;
5636
-					}
5637
-					$this->db->free($resql);
5638
-				}
5639
-				else {
5640
-					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5641
-				}
5642
-			}
5643
-			$out.='</select>';
5644
-		}
5645
-		elseif ($type == 'checkbox')
5646
-		{
5647
-			$value_arr=explode(',',$value);
5648
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5649
-		}
5650
-		elseif ($type == 'radio')
5651
-		{
5652
-			$out='';
5653
-			foreach ($param['options'] as $keyopt => $val)
5654
-			{
5655
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5656
-				$out.=' value="'.$keyopt.'"';
5657
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5658
-				$out.= ($value==$keyopt?'checked':'');
5659
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5660
-			}
5661
-		}
5662
-		elseif ($type == 'chkbxlst')
5663
-		{
5664
-			if (is_array($value)) {
5665
-				$value_arr = $value;
5666
-			}
5667
-			else {
5668
-				$value_arr = explode(',', $value);
5669
-			}
5670
-
5671
-			if (is_array($param['options'])) {
5672
-				$param_list = array_keys($param['options']);
5673
-				$InfoFieldList = explode(":", $param_list[0]);
5674
-				$parentName='';
5675
-				$parentField='';
5676
-				// 0 : tableName
5677
-				// 1 : label field name
5678
-				// 2 : key fields name (if differ of rowid)
5679
-				// 3 : key field parent (for dependent lists)
5680
-				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5681
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5682
-
5683
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5684
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5685
-					$keyList .= ', ' . $parentField;
5686
-				}
5687
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5688
-					if (strpos($InfoFieldList[4], 'extra.') !== false) {
5689
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5690
-					} else {
5691
-						$keyList = $InfoFieldList[2] . ' as rowid';
5692
-					}
5693
-				}
6435
+    /**
6436
+     * Returns the rights used for this class
6437
+     * @return stdClass
6438
+     */
6439
+    public function getRights()
6440
+    {
6441
+        global $user;
5694 6442
 
5695
-				$fields_label = explode('|', $InfoFieldList[1]);
5696
-				if (is_array($fields_label)) {
5697
-					$keyList .= ', ';
5698
-					$keyList .= implode(', ', $fields_label);
5699
-				}
6443
+        $element = $this->element;
6444
+        if ($element == 'facturerec') $element='facture';
5700 6445
 
5701
-				$sqlwhere = '';
5702
-				$sql = 'SELECT ' . $keyList;
5703
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5704
-				if (! empty($InfoFieldList[4])) {
5705
-
5706
-					// can use SELECT request
5707
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5708
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5709
-					}
5710
-
5711
-					// current object id can be use into filter
5712
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5713
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5714
-					} else {
5715
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5716
-					}
5717
-
5718
-					// We have to join on extrafield table
5719
-					if (strpos($InfoFieldList[4], 'extra') !== false) {
5720
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5721
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5722
-					} else {
5723
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5724
-					}
5725
-				} else {
5726
-					$sqlwhere .= ' WHERE 1=1';
5727
-				}
5728
-				// Some tables may have field, some other not. For the moment we disable it.
5729
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
5730
-				{
5731
-					$sqlwhere .= ' AND entity = ' . $conf->entity;
5732
-				}
5733
-				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
5734
-				// print $sql;
5735
-
5736
-				$sql .= $sqlwhere;
5737
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5738
-				$resql = $this->db->query($sql);
5739
-				if ($resql) {
5740
-					$num = $this->db->num_rows($resql);
5741
-					$i = 0;
5742
-
5743
-					$data=array();
5744
-
5745
-					while ( $i < $num ) {
5746
-						$labeltoshow = '';
5747
-						$obj = $this->db->fetch_object($resql);
5748
-
5749
-						$notrans = false;
5750
-						// Several field into label (eq table:code|libelle:rowid)
5751
-						$fields_label = explode('|', $InfoFieldList[1]);
5752
-						if (is_array($fields_label)) {
5753
-							$notrans = true;
5754
-							foreach ( $fields_label as $field_toshow ) {
5755
-								$labeltoshow .= $obj->$field_toshow . ' ';
5756
-							}
5757
-						} else {
5758
-							$labeltoshow = $obj->{$InfoFieldList[1]};
5759
-						}
5760
-						$labeltoshow = dol_trunc($labeltoshow, 45);
5761
-
5762
-						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5763
-							foreach ( $fields_label as $field_toshow ) {
5764
-								$translabel = $langs->trans($obj->$field_toshow);
5765
-								if ($translabel != $obj->$field_toshow) {
5766
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
5767
-								} else {
5768
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5769
-								}
5770
-							}
6446
+        return $user->rights->{$element};
6447
+    }
5771 6448
 
5772
-							$data[$obj->rowid]=$labeltoshow;
5773
-						} else {
5774
-							if (! $notrans) {
5775
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5776
-								if ($translabel != $obj->{$InfoFieldList[1]}) {
5777
-									$labeltoshow = dol_trunc($translabel, 18);
5778
-								} else {
5779
-									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5780
-								}
5781
-							}
5782
-							if (empty($labeltoshow))
5783
-								$labeltoshow = '(not defined)';
6449
+    /**
6450
+     * Function used to replace a thirdparty id with another one.
6451
+     * This function is meant to be called from replaceThirdparty with the appropiate tables
6452
+     * Column name fk_soc MUST be used to identify thirdparties
6453
+     *
6454
+     * @param  DoliDB 	   $db 			  Database handler
6455
+     * @param  int 		   $origin_id     Old thirdparty id (the thirdparty to delete)
6456
+     * @param  int 		   $dest_id       New thirdparty id (the thirdparty that will received element of the other)
6457
+     * @param  string[]    $tables        Tables that need to be changed
6458
+     * @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)
6459
+     * @return bool						  True if success, False if error
6460
+     */
6461
+    public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6462
+    {
6463
+        foreach ($tables as $table)
6464
+        {
6465
+            $sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
5784 6466
 
5785
-								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5786
-									$data[$obj->rowid]=$labeltoshow;
5787
-								}
6467
+            if (! $db->query($sql))
6468
+            {
6469
+                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.
6470
+                //$this->errors = $db->lasterror();
6471
+                return false;
6472
+            }
6473
+        }
5788 6474
 
5789
-								if (! empty($InfoFieldList[3]) && $parentField) {
5790
-									$parent = $parentName . ':' . $obj->{$parentField};
5791
-								}
6475
+        return true;
6476
+    }
5792 6477
 
5793
-								$data[$obj->rowid]=$labeltoshow;
5794
-						}
6478
+    /**
6479
+     * Get buy price to use for margin calculation. This function is called when buy price is unknown.
6480
+     *	 Set buy price = sell price if ForceBuyingPriceIfNull configured,
6481
+     *   else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
6482
+     *	 else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
6483
+     *	 else set min buy price as buy price
6484
+     *
6485
+     * @param float		$unitPrice		 Product unit price
6486
+     * @param float		$discountPercent Line discount percent
6487
+     * @param int		$fk_product		 Product id
6488
+     * @return	float                    <0 if KO, buyprice if OK
6489
+     */
6490
+    public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
6491
+    {
6492
+        global $conf;
5795 6493
 
5796
-						$i ++;
5797
-					}
5798
-					$this->db->free($resql);
6494
+        $buyPrice = 0;
5799 6495
 
5800
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5801
-				} else {
5802
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5803
-				}
5804
-			}
5805
-		}
5806
-		elseif ($type == 'link')
5807
-		{
5808
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5809
-			$showempty=(($required && $default != '')?0:1);
5810
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5811
-			if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
5812
-			{
5813
-            			list($class,$classfile)=explode(':',$param_list[0]);
5814
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5815
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5816
-            			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5817
-            			// TODO Add Javascript code to add input fields contents to new elements urls
5818
-			}
5819
-		}
5820
-		elseif ($type == 'password')
5821
-		{
5822
-			// If prefix is 'search_', field is used as a filter, we use a common text field.
5823
-			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5824
-		}
5825
-		elseif ($type == 'array')
5826
-		{
5827
-			$newval = $val;
5828
-			$newval['type'] = 'varchar(256)';
5829
-
5830
-			$out='';
5831
-
5832
-			$inputs = array();
5833
-			if(! empty($value)) {
5834
-				foreach($value as $option) {
5835
-					$out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5836
-					$out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5837
-				}
5838
-			}
6496
+        if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
6497
+        {
6498
+            $buyPrice = $unitPrice * (1 - $discountPercent / 100);
6499
+        }
6500
+        else
6501
+        {
6502
+            // Get cost price for margin calculation
6503
+            if (! empty($fk_product))
6504
+            {
6505
+                if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
6506
+                {
6507
+                    require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6508
+                    $product = new Product($this->db);
6509
+                    $result = $product->fetch($fk_product);
6510
+                    if ($result <= 0)
6511
+                    {
6512
+                        $this->errors[] = 'ErrorProductIdDoesNotExists';
6513
+                        return -1;
6514
+                    }
6515
+                    if ($product->cost_price > 0)
6516
+                    {
6517
+                        $buyPrice = $product->cost_price;
6518
+                    }
6519
+                    else if ($product->pmp > 0)
6520
+                    {
6521
+                        $buyPrice = $product->pmp;
6522
+                    }
6523
+                }
6524
+                else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
6525
+                {
6526
+                    require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6527
+                    $product = new Product($this->db);
6528
+                    $result = $product->fetch($fk_product);
6529
+                    if ($result <= 0)
6530
+                    {
6531
+                        $this->errors[] = 'ErrorProductIdDoesNotExists';
6532
+                        return -1;
6533
+                    }
6534
+                    if ($product->pmp > 0)
6535
+                    {
6536
+                        $buyPrice = $product->pmp;
6537
+                    }
6538
+                }
6539
+
6540
+                if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
6541
+                {
6542
+                    require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6543
+                    $productFournisseur = new ProductFournisseur($this->db);
6544
+                    if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6545
+                    {
6546
+                        $buyPrice = $productFournisseur->fourn_unitprice;
6547
+                    }
6548
+                    else if ($result < 0)
6549
+                    {
6550
+                        $this->errors[] = $productFournisseur->error;
6551
+                        return -2;
6552
+                    }
6553
+                }
6554
+            }
6555
+        }
6556
+        return $buyPrice;
6557
+    }
5839 6558
 
5840
-			$out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
6559
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6560
+    /**
6561
+     *  Show photos of an object (nbmax maximum), into several columns
6562
+     *
6563
+     *  @param		string	$modulepart		'product', 'ticket', ...
6564
+     *  @param      string	$sdir        	Directory to scan (full absolute path)
6565
+     *  @param      int		$size        	0=original size, 1='small' use thumbnail if possible
6566
+     *  @param      int		$nbmax       	Nombre maximum de photos (0=pas de max)
6567
+     *  @param      int		$nbbyrow     	Number of image per line or -1 to use div. Used only if size=1.
6568
+     * 	@param		int		$showfilename	1=Show filename
6569
+     * 	@param		int		$showaction		1=Show icon with action links (resize, delete)
6570
+     * 	@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.
6571
+     * 	@param		int		$maxWidth		Max width of original image when size='small'
6572
+     *  @param      int     $nolink         Do not add a href link to view enlarged imaged into a new tab
6573
+     *  @param      int     $notitle        Do not add title tag on image
6574
+     *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6575
+     *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6576
+     */
6577
+    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)
6578
+    {
6579
+        // phpcs:enable
6580
+        global $conf,$user,$langs;
5841 6581
 
5842
-			$newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5843
-			$newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
6582
+        include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6583
+        include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
5844 6584
 
5845
-			if(! empty($conf->use_javascript_ajax)) {
5846
-				$out.= '
5847
-					<script type="text/javascript">
5848
-					$(document).ready(function() {
5849
-						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
5850
-							$("'.dol_escape_js($newInput).'").insertBefore(this);
5851
-						});
6585
+        $sortfield='position_name';
6586
+        $sortorder='asc';
5852 6587
 
5853
-						$(document).on("click", "a.'.dol_escape_js($keyprefix.$key.$keysuffix).'_del", function() {
5854
-							$(this).parent().remove();
5855
-						});
5856
-					});
5857
-					</script>';
5858
-			}
5859
-		}
5860
-		if (!empty($hidden)) {
5861
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5862
-		}
5863
-		/* Add comments
5864
-		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
5865
-		 elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
5866
-		 */
5867
-		return $out;
5868
-	}
5869
-
5870
-	/**
5871
-	 * Return HTML string to show a field into a page
5872
-	 * Code very similar with showOutputField of extra fields
5873
-	 *
5874
-	 * @param  array   $val		       Array of properties of field to show
5875
-	 * @param  string  $key            Key of attribute
5876
-	 * @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)
5877
-	 * @param  string  $moreparam      To add more parametes on html input tag
5878
-	 * @param  string  $keysuffix      Prefix string to add into name and id of field (can be used to avoid duplicate names)
5879
-	 * @param  string  $keyprefix      Suffix string to add into name and id of field (can be used to avoid duplicate names)
5880
-	 * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5881
-	 * @return string
5882
-	 */
5883
-	function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5884
-	{
5885
-		global $conf,$langs,$form;
5886
-
5887
-		if (! is_object($form))
5888
-		{
5889
-			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5890
-			$form=new Form($this->db);
5891
-		}
5892
-
5893
-		$objectid = $this->id;
5894
-		$label = $val['label'];
5895
-		$type  = $val['type'];
5896
-		$size  = $val['css'];
5897
-
5898
-		// Convert var to be able to share same code than showOutputField of extrafields
5899
-		if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5900
-		{
5901
-			$type = 'varchar';		// convert varchar(xx) int varchar
5902
-			$size = $reg[1];
5903
-		}
5904
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5905
-		if (is_array($val['arrayofkeyval'])) $type='select';
5906
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5907
-
5908
-		$default=$val['default'];
5909
-		$computed=$val['computed'];
5910
-		$unique=$val['unique'];
5911
-		$required=$val['required'];
5912
-		$param=$val['param'];
5913
-		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5914
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5915
-		{
5916
-			$type='link';
5917
-			$param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5918
-		}
5919
-		$langfile=$val['langfile'];
5920
-		$list=$val['list'];
5921
-		$help=$val['help'];
5922
-		$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)
5923
-
5924
-		if ($hidden) return '';
5925
-
5926
-		// If field is a computed field, value must become result of compute
5927
-		if ($computed)
5928
-		{
5929
-			// Make the eval of compute string
5930
-			//var_dump($computed);
5931
-			$value = dol_eval($computed, 1, 0);
5932
-		}
5933
-
5934
-		if (empty($showsize))
5935
-		{
5936
-			if ($type == 'date')
5937
-			{
5938
-				//$showsize=10;
5939
-				$showsize = 'minwidth100imp';
5940
-			}
5941
-			elseif ($type == 'datetime')
5942
-			{
5943
-				//$showsize=19;
5944
-				$showsize = 'minwidth200imp';
5945
-			}
5946
-			elseif (in_array($type,array('int','double','price')))
5947
-			{
5948
-				//$showsize=10;
5949
-				$showsize = 'maxwidth75';
5950
-			}
5951
-			elseif ($type == 'url')
5952
-			{
5953
-				$showsize='minwidth400';
5954
-			}
5955
-			elseif ($type == 'boolean')
5956
-			{
5957
-				$showsize='';
5958
-			}
5959
-			else
5960
-			{
5961
-				if (round($size) < 12)
5962
-				{
5963
-					$showsize = 'minwidth100';
5964
-				}
5965
-				else if (round($size) <= 48)
5966
-				{
5967
-					$showsize = 'minwidth200';
5968
-				}
5969
-				else
5970
-				{
5971
-					//$showsize=48;
5972
-					$showsize = 'minwidth400';
5973
-				}
5974
-			}
5975
-		}
5976
-
5977
-		// Format output value differently according to properties of field
5978
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5979
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5980
-		elseif ($type == 'date')
5981
-		{
5982
-			if(! empty($value)) {
5983
-				$value=dol_print_date($value,'day');
5984
-			} else {
5985
-				$value='';
5986
-			}
5987
-		}
5988
-		elseif ($type == 'datetime')
5989
-		{
5990
-			if(! empty($value)) {
5991
-				$value=dol_print_date($value,'dayhour');
5992
-			} else {
5993
-				$value='';
5994
-			}
5995
-		}
5996
-		elseif ($type == 'double')
5997
-		{
5998
-			if (!empty($value)) {
5999
-				$value=price($value);
6000
-			}
6001
-		}
6002
-		elseif ($type == 'boolean')
6003
-		{
6004
-			$checked='';
6005
-			if (!empty($value)) {
6006
-				$checked=' checked ';
6007
-			}
6008
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6009
-		}
6010
-		elseif ($type == 'mail')
6011
-		{
6012
-			$value=dol_print_email($value,0,0,0,64,1,1);
6013
-		}
6014
-		elseif ($type == 'url')
6015
-		{
6016
-			$value=dol_print_url($value,'_blank',32,1);
6017
-		}
6018
-		elseif ($type == 'phone')
6019
-		{
6020
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6021
-		}
6022
-		elseif ($type == 'price')
6023
-		{
6024
-			$value=price($value,0,$langs,0,0,-1,$conf->currency);
6025
-		}
6026
-		elseif ($type == 'select')
6027
-		{
6028
-			$value=$param['options'][$value];
6029
-		}
6030
-		elseif ($type == 'sellist')
6031
-		{
6032
-			$param_list=array_keys($param['options']);
6033
-			$InfoFieldList = explode(":", $param_list[0]);
6034
-
6035
-			$selectkey="rowid";
6036
-			$keyList='rowid';
6037
-
6038
-			if (count($InfoFieldList)>=3)
6039
-			{
6040
-				$selectkey = $InfoFieldList[2];
6041
-				$keyList=$InfoFieldList[2].' as rowid';
6042
-			}
6043
-
6044
-			$fields_label = explode('|',$InfoFieldList[1]);
6045
-			if(is_array($fields_label)) {
6046
-				$keyList .=', ';
6047
-				$keyList .= implode(', ', $fields_label);
6048
-			}
6049
-
6050
-			$sql = 'SELECT '.$keyList;
6051
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6052
-			if (strpos($InfoFieldList[4], 'extra')!==false)
6053
-			{
6054
-				$sql.= ' as main';
6055
-			}
6056
-			if ($selectkey=='rowid' && empty($value)) {
6057
-				$sql.= " WHERE ".$selectkey."=0";
6058
-			} elseif ($selectkey=='rowid') {
6059
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6060
-			}else {
6061
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6062
-			}
6063
-
6064
-			//$sql.= ' AND entity = '.$conf->entity;
6065
-
6066
-			dol_syslog(get_class($this).':showOutputField:$type=sellist', LOG_DEBUG);
6067
-			$resql = $this->db->query($sql);
6068
-			if ($resql)
6069
-			{
6070
-				$value='';	// value was used, so now we reste it to use it to build final output
6588
+        $dir = $sdir . '/';
6589
+        $pdir = '/';
6590
+        if ($modulepart == 'ticket')
6591
+        {
6592
+            $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6593
+            $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6594
+        }
6595
+        else
6596
+        {
6597
+            $dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6598
+            $pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6599
+        }
6600
+
6601
+        // For backward compatibility
6602
+        if ($modulepart == 'product' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
6603
+        {
6604
+            $dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6605
+            $pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6606
+        }
6607
+
6608
+        // Defined relative dir to DOL_DATA_ROOT
6609
+        $relativedir = '';
6610
+        if ($dir)
6611
+        {
6612
+            $relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6613
+            $relativedir = preg_replace('/^[\\/]/','',$relativedir);
6614
+            $relativedir = preg_replace('/[\\/]$/','',$relativedir);
6615
+        }
6616
+
6617
+        $dirthumb = $dir.'thumbs/';
6618
+        $pdirthumb = $pdir.'thumbs/';
6619
+
6620
+        $return ='<!-- Photo -->'."\n";
6621
+        $nbphoto=0;
6622
+
6623
+        $filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6624
+
6625
+        /*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6626
+		 {
6627
+		 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6628
+		 $filearray=array_merge($filearray, $filearrayold);
6629
+		 }*/
6630
+
6631
+        completeFileArrayWithDatabaseInfo($filearray, $relativedir);
6632
+
6633
+        if (count($filearray))
6634
+        {
6635
+            if ($sortfield && $sortorder)
6636
+            {
6637
+                $filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6638
+            }
6639
+
6640
+            foreach($filearray as $key => $val)
6641
+            {
6642
+                $photo='';
6643
+                $file = $val['name'];
6644
+
6645
+                //if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
6646
+
6647
+                //if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
6648
+                if (image_format_supported($file) >= 0)
6649
+                {
6650
+                    $nbphoto++;
6651
+                    $photo = $file;
6652
+                    $viewfilename = $file;
6653
+
6654
+                    if ($size == 1 || $size == 'small') {   // Format vignette
6655
+
6656
+                        // Find name of thumb file
6657
+                        $photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6658
+                        if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
6659
+
6660
+                        // Get filesize of original file
6661
+                        $imgarray=dol_getImageSize($dir.$photo);
6662
+
6663
+                        if ($nbbyrow > 0)
6664
+                        {
6665
+                            if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6666
+
6667
+                            if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6668
+                            $return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6669
+                        }
6670
+                        else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
6671
+
6672
+                        $return.= "\n";
6673
+
6674
+                        $relativefile=preg_replace('/^\//', '', $pdir.$photo);
6675
+                        if (empty($nolink))
6676
+                        {
6677
+                            $urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6678
+                            if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6679
+                            else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6680
+                        }
6681
+
6682
+                        // Show image (width height=$maxHeight)
6683
+                        // Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6684
+                        $alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6685
+                        $alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6686
+                        if ($notitle) $alt='';
6687
+
6688
+                        if ($usesharelink)
6689
+                        {
6690
+                            if ($val['share'])
6691
+                            {
6692
+                                if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6693
+                                {
6694
+                                    $return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6695
+                                    $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6696
+                                }
6697
+                                else {
6698
+                                    $return.= '<!-- Show original file -->';
6699
+                                    $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6700
+                                }
6701
+                            }
6702
+                            else
6703
+                            {
6704
+                                $return.= '<!-- Show nophoto file (because file is not shared) -->';
6705
+                                $return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6706
+                            }
6707
+                        }
6708
+                        else
6709
+                        {
6710
+                            if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6711
+                            {
6712
+                                $return.= '<!-- Show thumb -->';
6713
+                                $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).'">';
6714
+                            }
6715
+                            else {
6716
+                                $return.= '<!-- Show original file -->';
6717
+                                $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).'">';
6718
+                            }
6719
+                        }
6720
+
6721
+                        if (empty($nolink)) $return.= '</a>';
6722
+                        $return.="\n";
6723
+
6724
+                        if ($showfilename) $return.= '<br>'.$viewfilename;
6725
+                        if ($showaction)
6726
+                        {
6727
+                            $return.= '<br>';
6728
+                            // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6729
+                            if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6730
+                            {
6731
+                                $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>';
6732
+                            }
6733
+                            // Special cas for product
6734
+                            if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6735
+                            {
6736
+                                // Link to resize
6737
+                                $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; ';
6738
+
6739
+                                // Link to delete
6740
+                                $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6741
+                                $return.= img_delete().'</a>';
6742
+                            }
6743
+                        }
6744
+                        $return.= "\n";
6745
+
6746
+                        if ($nbbyrow > 0)
6747
+                        {
6748
+                            $return.= '</td>';
6749
+                            if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6750
+                        }
6751
+                        else if ($nbbyrow < 0) $return.='</div>';
6752
+                    }
6753
+
6754
+                    if (empty($size)) {     // Format origine
6755
+                        $return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6756
+
6757
+                        if ($showfilename) $return.= '<br>'.$viewfilename;
6758
+                        if ($showaction)
6759
+                        {
6760
+                            // Special case for product
6761
+                            if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6762
+                            {
6763
+                                // Link to resize
6764
+                                $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; ';
6765
+
6766
+                                // Link to delete
6767
+                                $return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6768
+                                $return.= img_delete().'</a>';
6769
+                            }
6770
+                        }
6771
+                    }
6772
+
6773
+                    // On continue ou on arrete de boucler ?
6774
+                    if ($nbmax && $nbphoto >= $nbmax) break;
6775
+                }
6776
+            }
6777
+
6778
+            if ($size==1 || $size=='small')
6779
+            {
6780
+                if ($nbbyrow > 0)
6781
+                {
6782
+                    // Ferme tableau
6783
+                    while ($nbphoto % $nbbyrow)
6784
+                    {
6785
+                        $return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6786
+                        $nbphoto++;
6787
+                    }
6788
+
6789
+                    if ($nbphoto) $return.= '</table>';
6790
+                }
6791
+            }
6792
+        }
6793
+
6794
+        $this->nbphoto = $nbphoto;
6795
+
6796
+        return $return;
6797
+    }
6798
+
6799
+
6800
+    /**
6801
+     * Function test if type is array
6802
+     *
6803
+     * @param   array   $info   content informations of field
6804
+     * @return                  bool
6805
+     */
6806
+    protected function isArray($info)
6807
+    {
6808
+        if(is_array($info))
6809
+        {
6810
+            if(isset($info['type']) && $info['type']=='array') return true;
6811
+            else return false;
6812
+        }
6813
+        else return false;
6814
+    }
6815
+
6816
+    /**
6817
+     * Function test if type is null
6818
+     *
6819
+     * @param   array   $info   content informations of field
6820
+     * @return                  bool
6821
+     */
6822
+    protected function isNull($info)
6823
+    {
6824
+        if(is_array($info))
6825
+        {
6826
+            if(isset($info['type']) && $info['type']=='null') return true;
6827
+            else return false;
6828
+        }
6829
+        else return false;
6830
+    }
6831
+
6832
+    /**
6833
+     * Function test if type is date
6834
+     *
6835
+     * @param   array   $info   content informations of field
6836
+     * @return                  bool
6837
+     */
6838
+    public function isDate($info)
6839
+    {
6840
+        if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6841
+        else return false;
6842
+    }
6843
+
6844
+    /**
6845
+     * Function test if type is integer
6846
+     *
6847
+     * @param   array   $info   content informations of field
6848
+     * @return                  bool
6849
+     */
6850
+    public function isInt($info)
6851
+    {
6852
+        if(is_array($info))
6853
+        {
6854
+            if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6855
+            else return false;
6856
+        }
6857
+        else return false;
6858
+    }
6859
+
6860
+    /**
6861
+     * Function test if type is float
6862
+     *
6863
+     * @param   array   $info   content informations of field
6864
+     * @return                  bool
6865
+     */
6866
+    public function isFloat($info)
6867
+    {
6868
+        if(is_array($info))
6869
+        {
6870
+            if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6871
+            else return false;
6872
+        }
6873
+        else return false;
6874
+    }
6875
+
6876
+    /**
6877
+     * Function test if type is text
6878
+     *
6879
+     * @param   array   $info   content informations of field
6880
+     * @return                  bool
6881
+     */
6882
+    public function isText($info)
6883
+    {
6884
+        if(is_array($info))
6885
+        {
6886
+            if(isset($info['type']) && $info['type']=='text') return true;
6887
+            else return false;
6888
+        }
6889
+        else return false;
6890
+    }
6891
+
6892
+    /**
6893
+     * Function test if is indexed
6894
+     *
6895
+     * @param   array   $info   content informations of field
6896
+     * @return                  bool
6897
+     */
6898
+    protected function isIndex($info)
6899
+    {
6900
+        if(is_array($info))
6901
+        {
6902
+            if(isset($info['index']) && $info['index']==true) return true;
6903
+            else return false;
6904
+        }
6905
+        else return false;
6906
+    }
6907
+
6908
+    /**
6909
+     * Function to prepare the values to insert.
6910
+     * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
6911
+     *
6912
+     * @return array
6913
+     */
6914
+    protected function setSaveQuery()
6915
+    {
6916
+        global $conf;
6917
+
6918
+        $queryarray=array();
6919
+        foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6920
+        {
6921
+            // Depending on field type ('datetime', ...)
6922
+            if($this->isDate($info))
6923
+            {
6924
+                if(empty($this->{$field}))
6925
+                {
6926
+                    $queryarray[$field] = null;
6927
+                }
6928
+                else
6929
+                {
6930
+                    $queryarray[$field] = $this->db->idate($this->{$field});
6931
+                }
6932
+            }
6933
+            else if($this->isArray($info))
6934
+            {
6935
+                if(! empty($this->{$field})) {
6936
+                    if(! is_array($this->{$field})) {
6937
+                        $this->{$field} = array($this->{$field});
6938
+                    }
6939
+                    $queryarray[$field] = serialize($this->{$field});
6940
+                } else {
6941
+                    $queryarray[$field] = null;
6942
+                }
6943
+            }
6944
+            else if($this->isInt($info))
6945
+            {
6946
+                if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity;
6947
+                else
6948
+                {
6949
+                    $queryarray[$field] = (int) price2num($this->{$field});
6950
+                    if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6951
+                }
6952
+            }
6953
+            else if($this->isFloat($info))
6954
+            {
6955
+                $queryarray[$field] = (double) price2num($this->{$field});
6956
+                if (empty($queryarray[$field])) $queryarray[$field]=0;
6957
+            }
6958
+            else
6959
+            {
6960
+                $queryarray[$field] = $this->{$field};
6961
+            }
6962
+
6963
+            if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6964
+            if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6965
+        }
6966
+
6967
+        return $queryarray;
6968
+    }
6969
+
6970
+    /**
6971
+     * Function to load data from a SQL pointer into properties of current object $this
6972
+     *
6973
+     * @param   stdClass    $obj    Contain data of object from database
6974
+     * @return void
6975
+     */
6976
+    protected function setVarsFromFetchObj(&$obj)
6977
+    {
6978
+        foreach ($this->fields as $field => $info)
6979
+        {
6980
+            if($this->isDate($info))
6981
+            {
6982
+                if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6983
+                else $this->{$field} = strtotime($obj->{$field});
6984
+            }
6985
+            elseif($this->isArray($info))
6986
+            {
6987
+                if(! empty($obj->{$field})) {
6988
+                    $this->{$field} = @unserialize($obj->{$field});
6989
+                    // Hack for data not in UTF8
6990
+                    if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6991
+                } else {
6992
+                    $this->{$field} = array();
6993
+                }
6994
+            }
6995
+            elseif($this->isInt($info))
6996
+            {
6997
+                if ($field == 'rowid') $this->id = (int) $obj->{$field};
6998
+                else $this->{$field} = (int) $obj->{$field};
6999
+            }
7000
+            elseif($this->isFloat($info))
7001
+            {
7002
+                $this->{$field} = (double) $obj->{$field};
7003
+            }
7004
+            elseif($this->isNull($info))
7005
+            {
7006
+                $val = $obj->{$field};
7007
+                // zero is not null
7008
+                $this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7009
+            }
7010
+            else
7011
+            {
7012
+                $this->{$field} = $obj->{$field};
7013
+            }
7014
+        }
7015
+
7016
+        // If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7017
+        if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7018
+    }
7019
+
7020
+    /**
7021
+     * Function to concat keys of fields
7022
+     *
7023
+     * @return string
7024
+     */
7025
+    protected function getFieldList()
7026
+    {
7027
+        $keys = array_keys($this->fields);
7028
+        return implode(',', $keys);
7029
+    }
7030
+
7031
+    /**
7032
+     * Add quote to field value if necessary
7033
+     *
7034
+     * @param 	string|int	$value			Value to protect
7035
+     * @param	array		$fieldsentry	Properties of field
7036
+     * @return 	string
7037
+     */
7038
+    protected function quote($value, $fieldsentry)
7039
+    {
7040
+        if (is_null($value)) return 'NULL';
7041
+        else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7042
+        else return "'".$this->db->escape($value)."'";
7043
+    }
7044
+
7045
+
7046
+    /**
7047
+     * Create object into database
7048
+     *
7049
+     * @param  User $user      User that creates
7050
+     * @param  bool $notrigger false=launch triggers after, true=disable triggers
7051
+     * @return int             <0 if KO, Id of created object if OK
7052
+     */
7053
+    public function createCommon(User $user, $notrigger = false)
7054
+    {
7055
+        global $langs;
6071 7056
 
6072
-				$obj = $this->db->fetch_object($resql);
7057
+        $error = 0;
6073 7058
 
6074
-				// Several field into label (eq table:code|libelle:rowid)
6075
-				$fields_label = explode('|',$InfoFieldList[1]);
7059
+        $now=dol_now();
6076 7060
 
6077
-				if(is_array($fields_label) && count($fields_label)>1)
6078
-				{
6079
-					foreach ($fields_label as $field_toshow)
6080
-					{
6081
-						$translabel='';
6082
-						if (!empty($obj->$field_toshow)) {
6083
-							$translabel=$langs->trans($obj->$field_toshow);
6084
-						}
6085
-						if ($translabel!=$field_toshow) {
6086
-							$value.=dol_trunc($translabel,18).' ';
6087
-						}else {
6088
-							$value.=$obj->$field_toshow.' ';
6089
-						}
6090
-					}
6091
-				}
6092
-				else
6093
-				{
6094
-					$translabel='';
6095
-					if (!empty($obj->{$InfoFieldList[1]})) {
6096
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
6097
-					}
6098
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6099
-						$value=dol_trunc($translabel,18);
6100
-					}else {
6101
-						$value=$obj->{$InfoFieldList[1]};
6102
-					}
6103
-				}
6104
-			}
6105
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6106
-		}
6107
-		elseif ($type == 'radio')
6108
-		{
6109
-			$value=$param['options'][$value];
6110
-		}
6111
-		elseif ($type == 'checkbox')
6112
-		{
6113
-			$value_arr=explode(',',$value);
6114
-			$value='';
6115
-			if (is_array($value_arr) && count($value_arr)>0)
6116
-			{
6117
-				foreach ($value_arr as $keyval=>$valueval) {
6118
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6119
-				}
6120
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6121
-			}
6122
-		}
6123
-		elseif ($type == 'chkbxlst')
6124
-		{
6125
-			$value_arr = explode(',', $value);
6126
-
6127
-			$param_list = array_keys($param['options']);
6128
-			$InfoFieldList = explode(":", $param_list[0]);
6129
-
6130
-			$selectkey = "rowid";
6131
-			$keyList = 'rowid';
6132
-
6133
-			if (count($InfoFieldList) >= 3) {
6134
-				$selectkey = $InfoFieldList[2];
6135
-				$keyList = $InfoFieldList[2] . ' as rowid';
6136
-			}
6137
-
6138
-			$fields_label = explode('|', $InfoFieldList[1]);
6139
-			if (is_array($fields_label)) {
6140
-				$keyList .= ', ';
6141
-				$keyList .= implode(', ', $fields_label);
6142
-			}
6143
-
6144
-			$sql = 'SELECT ' . $keyList;
6145
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6146
-			if (strpos($InfoFieldList[4], 'extra') !== false) {
6147
-				$sql .= ' as main';
6148
-			}
6149
-			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6150
-			// $sql.= ' AND entity = '.$conf->entity;
6151
-
6152
-			dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6153
-			$resql = $this->db->query($sql);
6154
-			if ($resql) {
6155
-				$value = ''; // value was used, so now we reste it to use it to build final output
6156
-				$toprint=array();
6157
-				while ( $obj = $this->db->fetch_object($resql) ) {
6158
-
6159
-					// Several field into label (eq table:code|libelle:rowid)
6160
-					$fields_label = explode('|', $InfoFieldList[1]);
6161
-					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6162
-						if (is_array($fields_label) && count($fields_label) > 1) {
6163
-							foreach ( $fields_label as $field_toshow ) {
6164
-								$translabel = '';
6165
-								if (! empty($obj->$field_toshow)) {
6166
-									$translabel = $langs->trans($obj->$field_toshow);
6167
-								}
6168
-								if ($translabel != $field_toshow) {
6169
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6170
-								} else {
6171
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6172
-								}
6173
-							}
6174
-						} else {
6175
-							$translabel = '';
6176
-							if (! empty($obj->{$InfoFieldList[1]})) {
6177
-								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6178
-							}
6179
-							if ($translabel != $obj->{$InfoFieldList[1]}) {
6180
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6181
-							} else {
6182
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6183
-							}
6184
-						}
6185
-					}
6186
-				}
6187
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6188
-			} else {
6189
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6190
-			}
6191
-		}
6192
-		elseif ($type == 'link')
6193
-		{
6194
-			$out='';
6195
-
6196
-			// only if something to display (perf)
6197
-			if ($value)
6198
-			{
6199
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
7061
+        $fieldvalues = $this->setSaveQuery();
7062
+        if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7063
+        if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7064
+        unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
6200 7065
 
6201
-				$InfoFieldList = explode(":", $param_list[0]);
6202
-				$classname=$InfoFieldList[0];
6203
-				$classpath=$InfoFieldList[1];
6204
-				$getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6205
-				if (! empty($classpath))
6206
-				{
6207
-					dol_include_once($InfoFieldList[1]);
6208
-					if ($classname && class_exists($classname))
6209
-					{
6210
-						$object = new $classname($this->db);
6211
-						$object->fetch($value);
6212
-						$value=$object->getNomUrl($getnomurlparam);
6213
-					}
6214
-				}
6215
-				else
6216
-				{
6217
-					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6218
-					return 'Error bad setup of extrafield';
6219
-				}
6220
-			}
6221
-			else $value='';
6222
-		}
6223
-		elseif ($type == 'text' || $type == 'html')
6224
-		{
6225
-			$value=dol_htmlentitiesbr($value);
6226
-		}
6227
-		elseif ($type == 'password')
6228
-		{
6229
-			$value=preg_replace('/./i','*',$value);
6230
-		}
6231
-		elseif ($type == 'array')
6232
-		{
6233
-			$value = implode('<br>', $value);
6234
-		}
6235
-
6236
-		//print $type.'-'.$size;
6237
-		$out=$value;
6238
-
6239
-		return $out;
6240
-	}
6241
-
6242
-
6243
-	/**
6244
-	 * Function to show lines of extrafields with output datas
6245
-	 *
6246
-	 * @param 	Extrafields $extrafields    Extrafield Object
6247
-	 * @param 	string      $mode           Show output (view) or input (edit) for extrafield
6248
-	 * @param 	array       $params         Optional parameters. Example: array('style'=>'class="oddeven"', 'colspan'=>$colspan)
6249
-	 * @param 	string      $keysuffix      Suffix string to add after name and id of field (can be used to avoid duplicate names)
6250
-	 * @param 	string      $keyprefix      Prefix string to add before name and id of field (can be used to avoid duplicate names)
6251
-	 * @param	string		$onetrtd		All fields in same tr td
6252
-	 * @return 	string
6253
-	 */
6254
-	function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6255
-	{
6256
-		global $db, $conf, $langs, $action, $form;
6257
-
6258
-		if (! is_object($form)) $form=new Form($db);
6259
-
6260
-		$out = '';
6261
-
6262
-		if (is_array($extrafields->attributes[$this->table_element]['label']) && count($extrafields->attributes[$this->table_element]['label']) > 0)
6263
-		{
6264
-			$out .= "\n";
6265
-			$out .= '<!-- showOptionalsInput --> ';
6266
-			$out .= "\n";
6267
-
6268
-			$e = 0;
6269
-			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6270
-			{
6271
-				// Show only the key field in params
6272
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
7066
+        $keys=array();
7067
+        $values = array();
7068
+        foreach ($fieldvalues as $k => $v) {
7069
+            $keys[$k] = $k;
7070
+            $value = $this->fields[$k];
7071
+            $values[$k] = $this->quote($v, $value);
7072
+        }
6273 7073
 
6274
-				$enabled = 1;
6275
-				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
6276
-				{
6277
-					$enabled = dol_eval($extrafields->attributes[$this->table_element]['list'][$key], 1);
6278
-				}
7074
+        // Clean and check mandatory
7075
+        foreach($keys as $key)
7076
+        {
7077
+            // If field is an implicit foreign key field
7078
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7079
+            if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
6279 7080
 
6280
-				$perms = 1;
6281
-				if ($perms && isset($extrafields->attributes[$this->table_element]['perms'][$key]))
6282
-				{
6283
-					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6284
-				}
7081
+            //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7082
+            if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7083
+            {
7084
+                $error++;
7085
+                $this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7086
+            }
6285 7087
 
6286
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6287
-				if (empty($perms)) continue;
7088
+            // If field is an implicit foreign key field
7089
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7090
+            if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7091
+        }
6288 7092
 
6289
-				// Load language if required
6290
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
7093
+        if ($error) return -1;
6291 7094
 
6292
-				$colspan='3';
6293
-				if (is_array($params) && count($params)>0) {
6294
-					if (array_key_exists('colspan',$params)) {
6295
-						$colspan=$params['colspan'];
6296
-					}
6297
-				}
7095
+        $this->db->begin();
6298 7096
 
6299
-				switch($mode) {
6300
-					case "view":
6301
-						$value=$this->array_options["options_".$key.$keysuffix];
6302
-						break;
6303
-					case "edit":
6304
-						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6305
-						// GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6306
-						if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6307
-						{
6308
-							if (is_array($getposttemp)) {
6309
-								// $getposttemp is an array but following code expects a comma separated string
6310
-								$value = implode(",", $getposttemp);
6311
-							} else {
6312
-								$value = $getposttemp;
6313
-							}
6314
-						} else {
6315
-							$value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6316
-						}
6317
-						//var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6318
-						break;
6319
-				}
7097
+        if (! $error)
7098
+        {
7099
+            $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7100
+            $sql.= ' ('.implode( ", ", $keys ).')';
7101
+            $sql.= ' VALUES ('.implode( ", ", $values ).')';
7102
+
7103
+            $res = $this->db->query($sql);
7104
+            if ($res===false) {
7105
+                $error++;
7106
+                $this->errors[] = $this->db->lasterror();
7107
+            }
7108
+        }
6320 7109
 
6321
-				if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6322
-				{
6323
-					$out .= $extrafields->showSeparator($key, $this);
6324
-				}
6325
-				else
6326
-				{
6327
-					$csstyle='';
6328
-					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6329
-					if (is_array($params) && count($params)>0) {
6330
-						if (array_key_exists('style',$params)) {
6331
-							$csstyle=$params['style'];
6332
-						}
6333
-					}
7110
+        if (! $error)
7111
+        {
7112
+            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7113
+        }
6334 7114
 
6335
-					// add html5 elements
6336
-					$domData  = ' data-element="extrafield"';
6337
-					$domData .= ' data-targetelement="'.$this->element.'"';
6338
-					$domData .= ' data-targetid="'.$this->id.'"';
7115
+        // Create extrafields
7116
+        if (! $error)
7117
+        {
7118
+            $result=$this->insertExtraFields();
7119
+            if ($result < 0) $error++;
7120
+        }
6339 7121
 
6340
-					$html_id = !empty($this->id) ? 'extrarow-'.$this->element.'_'.$key.'_'.$this->id : '';
7122
+        // Triggers
7123
+        if (! $error && ! $notrigger)
7124
+        {
7125
+            // Call triggers
7126
+            $result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7127
+            if ($result < 0) { $error++; }
7128
+            // End call triggers
7129
+        }
6341 7130
 
6342
-					$out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
7131
+        // Commit or rollback
7132
+        if ($error) {
7133
+            $this->db->rollback();
7134
+            return -1;
7135
+        } else {
7136
+            $this->db->commit();
7137
+            return $this->id;
7138
+        }
7139
+    }
6343 7140
 
6344
-					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
6345
-					{
6346
-						if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan='0'; }
6347
-					}
6348 7141
 
6349
-					if ($action == 'selectlines') { $colspan++; }
7142
+    /**
7143
+     * Load object in memory from the database
7144
+     *
7145
+     * @param	int    $id				Id object
7146
+     * @param	string $ref				Ref
7147
+     * @param	string	$morewhere		More SQL filters (' AND ...')
7148
+     * @return 	int         			<0 if KO, 0 if not found, >0 if OK
7149
+     */
7150
+    public function fetchCommon($id, $ref = null, $morewhere = '')
7151
+    {
7152
+        if (empty($id) && empty($ref) && empty($morewhere)) return -1;
6350 7153
 
6351
-					// Convert date into timestamp format (value in memory must be a timestamp)
6352
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6353
-					{
6354
-						$datenotinstring = $this->array_options['options_' . $key];
6355
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6356
-						{
6357
-							$datenotinstring = $this->db->jdate($datenotinstring);
6358
-						}
6359
-						$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;
6360
-					}
6361
-					// Convert float submited string into real php numeric (value in memory must be a php numeric)
6362
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6363
-					{
6364
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6365
-					}
6366
-
6367
-					$labeltoshow = $langs->trans($label);
6368
-
6369
-					$out .= '<td class="titlefield';
6370
-					if (GETPOST('action','none') == 'create') $out.='create';
6371
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6372
-					$out .= '">';
6373
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6374
-					else $out .= $labeltoshow;
6375
-					$out .= '</td>';
6376
-
6377
-					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6378
-					$out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6379
-
6380
-					switch($mode) {
6381
-						case "view":
6382
-							$out .= $extrafields->showOutputField($key, $value);
6383
-							break;
6384
-						case "edit":
6385
-							$out .= $extrafields->showInputField($key, $value, '', $keysuffix, '', 0, $this->id);
6386
-							break;
6387
-					}
6388
-
6389
-					$out .= '</td>';
6390
-
6391
-					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
6392
-					else $out .= '</tr>';
6393
-					$e++;
6394
-				}
6395
-			}
6396
-			$out .= "\n";
6397
-			// Add code to manage list depending on others
6398
-			if (! empty($conf->use_javascript_ajax)) {
6399
-				$out .= '
6400
-				<script type="text/javascript">
6401
-				    jQuery(document).ready(function() {
6402
-				    	function showOptions(child_list, parent_list)
6403
-				    	{
6404
-				    		var val = $("select[name=\"options_"+parent_list+"\"]").val();
6405
-				    		var parentVal = parent_list + ":" + val;
6406
-							if(val > 0) {
6407
-					    		$("select[name=\""+child_list+"\"] option[parent]").hide();
6408
-					    		$("select[name=\""+child_list+"\"] option[parent=\""+parentVal+"\"]").show();
6409
-							} else {
6410
-								$("select[name=\""+child_list+"\"] option").show();
6411
-							}
6412
-				    	}
6413
-						function setListDependencies() {
6414
-					    	jQuery("select option[parent]").parent().each(function() {
6415
-					    		var child_list = $(this).attr("name");
6416
-								var parent = $(this).find("option[parent]:first").attr("parent");
6417
-								var infos = parent.split(":");
6418
-								var parent_list = infos[0];
6419
-								$("select[name=\""+parent_list+"\"]").change(function() {
6420
-									showOptions(child_list, parent_list);
6421
-								});
6422
-					    	});
6423
-						}
7154
+        $sql = 'SELECT '.$this->getFieldList();
7155
+        $sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
6424 7156
 
6425
-						setListDependencies();
6426
-				    });
6427
-				</script>'."\n";
6428
-				$out .= '<!-- /showOptionalsInput --> '."\n";
6429
-			}
6430
-		}
6431
-		return $out;
6432
-	}
6433
-
6434
-
6435
-	/**
6436
-	 * Returns the rights used for this class
6437
-	 * @return stdClass
6438
-	 */
6439
-	public function getRights()
6440
-	{
6441
-		global $user;
6442
-
6443
-		$element = $this->element;
6444
-		if ($element == 'facturerec') $element='facture';
6445
-
6446
-		return $user->rights->{$element};
6447
-	}
6448
-
6449
-	/**
6450
-	 * Function used to replace a thirdparty id with another one.
6451
-	 * This function is meant to be called from replaceThirdparty with the appropiate tables
6452
-	 * Column name fk_soc MUST be used to identify thirdparties
6453
-	 *
6454
-	 * @param  DoliDB 	   $db 			  Database handler
6455
-	 * @param  int 		   $origin_id     Old thirdparty id (the thirdparty to delete)
6456
-	 * @param  int 		   $dest_id       New thirdparty id (the thirdparty that will received element of the other)
6457
-	 * @param  string[]    $tables        Tables that need to be changed
6458
-	 * @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)
6459
-	 * @return bool						  True if success, False if error
6460
-	 */
6461
-	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6462
-	{
6463
-		foreach ($tables as $table)
6464
-		{
6465
-			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6466
-
6467
-			if (! $db->query($sql))
6468
-			{
6469
-				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.
6470
-				//$this->errors = $db->lasterror();
6471
-				return false;
6472
-			}
6473
-		}
6474
-
6475
-		return true;
6476
-	}
6477
-
6478
-	/**
6479
-	 * Get buy price to use for margin calculation. This function is called when buy price is unknown.
6480
-	 *	 Set buy price = sell price if ForceBuyingPriceIfNull configured,
6481
-	 *   else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
6482
-	 *	 else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
6483
-	 *	 else set min buy price as buy price
6484
-	 *
6485
-	 * @param float		$unitPrice		 Product unit price
6486
-	 * @param float		$discountPercent Line discount percent
6487
-	 * @param int		$fk_product		 Product id
6488
-	 * @return	float                    <0 if KO, buyprice if OK
6489
-	 */
6490
-	public function defineBuyPrice($unitPrice = 0.0, $discountPercent = 0.0, $fk_product = 0)
6491
-	{
6492
-		global $conf;
6493
-
6494
-		$buyPrice = 0;
6495
-
6496
-		if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
6497
-		{
6498
-			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
6499
-		}
6500
-		else
6501
-		{
6502
-			// Get cost price for margin calculation
6503
-			if (! empty($fk_product))
6504
-			{
6505
-				if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
6506
-				{
6507
-					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6508
-					$product = new Product($this->db);
6509
-					$result = $product->fetch($fk_product);
6510
-					if ($result <= 0)
6511
-					{
6512
-						$this->errors[] = 'ErrorProductIdDoesNotExists';
6513
-						return -1;
6514
-					}
6515
-					if ($product->cost_price > 0)
6516
-					{
6517
-						$buyPrice = $product->cost_price;
6518
-					}
6519
-					else if ($product->pmp > 0)
6520
-					{
6521
-						$buyPrice = $product->pmp;
6522
-					}
6523
-				}
6524
-				else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
6525
-				{
6526
-					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6527
-					$product = new Product($this->db);
6528
-					$result = $product->fetch($fk_product);
6529
-					if ($result <= 0)
6530
-					{
6531
-						$this->errors[] = 'ErrorProductIdDoesNotExists';
6532
-						return -1;
6533
-					}
6534
-					if ($product->pmp > 0)
6535
-					{
6536
-						$buyPrice = $product->pmp;
6537
-					}
6538
-				}
7157
+        if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7158
+        elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7159
+        else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7160
+        if ($morewhere)   $sql.= $morewhere;
7161
+        $sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
6539 7162
 
6540
-				if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
6541
-				{
6542
-					require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6543
-					$productFournisseur = new ProductFournisseur($this->db);
6544
-					if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6545
-					{
6546
-						$buyPrice = $productFournisseur->fourn_unitprice;
6547
-					}
6548
-					else if ($result < 0)
6549
-					{
6550
-						$this->errors[] = $productFournisseur->error;
6551
-						return -2;
6552
-					}
6553
-				}
6554
-			}
6555
-		}
6556
-		return $buyPrice;
6557
-	}
7163
+        $res = $this->db->query($sql);
7164
+        if ($res)
7165
+        {
7166
+            $obj = $this->db->fetch_object($res);
7167
+            if ($obj)
7168
+            {
7169
+                $this->setVarsFromFetchObj($obj);
7170
+                return $this->id;
7171
+            }
7172
+            else
7173
+            {
7174
+                return 0;
7175
+            }
7176
+        }
7177
+        else
7178
+        {
7179
+            $this->error = $this->db->lasterror();
7180
+            $this->errors[] = $this->error;
7181
+            return -1;
7182
+        }
7183
+    }
6558 7184
 
6559
-    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
6560
-	/**
6561
-	 *  Show photos of an object (nbmax maximum), into several columns
6562
-	 *
6563
-	 *  @param		string	$modulepart		'product', 'ticket', ...
6564
-	 *  @param      string	$sdir        	Directory to scan (full absolute path)
6565
-	 *  @param      int		$size        	0=original size, 1='small' use thumbnail if possible
6566
-	 *  @param      int		$nbmax       	Nombre maximum de photos (0=pas de max)
6567
-	 *  @param      int		$nbbyrow     	Number of image per line or -1 to use div. Used only if size=1.
6568
-	 * 	@param		int		$showfilename	1=Show filename
6569
-	 * 	@param		int		$showaction		1=Show icon with action links (resize, delete)
6570
-	 * 	@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.
6571
-	 * 	@param		int		$maxWidth		Max width of original image when size='small'
6572
-	 *  @param      int     $nolink         Do not add a href link to view enlarged imaged into a new tab
6573
-	 *  @param      int     $notitle        Do not add title tag on image
6574
-	 *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6575
-	 *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6576
-	 */
6577
-	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)
6578
-	{
6579
-        // phpcs:enable
6580
-		global $conf,$user,$langs;
6581
-
6582
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6583
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6584
-
6585
-		$sortfield='position_name';
6586
-		$sortorder='asc';
6587
-
6588
-		$dir = $sdir . '/';
6589
-		$pdir = '/';
6590
-		if ($modulepart == 'ticket')
6591
-		{
6592
-			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6593
-			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6594
-		}
6595
-		else
6596
-		{
6597
-			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6598
-			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6599
-		}
6600
-
6601
-		// For backward compatibility
6602
-		if ($modulepart == 'product' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
6603
-		{
6604
-			$dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6605
-			$pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6606
-		}
6607
-
6608
-		// Defined relative dir to DOL_DATA_ROOT
6609
-		$relativedir = '';
6610
-		if ($dir)
6611
-		{
6612
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6613
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
6614
-			$relativedir = preg_replace('/[\\/]$/','',$relativedir);
6615
-		}
6616
-
6617
-		$dirthumb = $dir.'thumbs/';
6618
-		$pdirthumb = $pdir.'thumbs/';
6619
-
6620
-		$return ='<!-- Photo -->'."\n";
6621
-		$nbphoto=0;
6622
-
6623
-		$filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6624
-
6625
-		/*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6626
-		 {
6627
-		 $filearrayold=dol_dir_list($dirold,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6628
-		 $filearray=array_merge($filearray, $filearrayold);
6629
-		 }*/
7185
+    /**
7186
+     * Update object into database
7187
+     *
7188
+     * @param  User $user      	User that modifies
7189
+     * @param  bool $notrigger 	false=launch triggers after, true=disable triggers
7190
+     * @return int             	<0 if KO, >0 if OK
7191
+     */
7192
+    public function updateCommon(User $user, $notrigger = false)
7193
+    {
7194
+        global $conf, $langs;
6630 7195
 
6631
-		completeFileArrayWithDatabaseInfo($filearray, $relativedir);
7196
+        $error = 0;
6632 7197
 
6633
-		if (count($filearray))
6634
-		{
6635
-			if ($sortfield && $sortorder)
6636
-			{
6637
-				$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6638
-			}
7198
+        $now=dol_now();
6639 7199
 
6640
-			foreach($filearray as $key => $val)
6641
-			{
6642
-				$photo='';
6643
-				$file = $val['name'];
7200
+        $fieldvalues = $this->setSaveQuery();
7201
+        if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7202
+        if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7203
+        unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
6644 7204
 
6645
-				//if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
7205
+        $keys=array();
7206
+        $values = array();
7207
+        foreach ($fieldvalues as $k => $v) {
7208
+            $keys[$k] = $k;
7209
+            $value = $this->fields[$k];
7210
+            $values[$k] = $this->quote($v, $value);
7211
+            $tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
7212
+        }
6646 7213
 
6647
-				//if (dol_is_file($dir.$file) && image_format_supported($file) >= 0)
6648
-				if (image_format_supported($file) >= 0)
6649
-				{
6650
-					$nbphoto++;
6651
-					$photo = $file;
6652
-					$viewfilename = $file;
7214
+        // Clean and check mandatory
7215
+        foreach($keys as $key)
7216
+        {
7217
+            if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7218
+            if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7219
+
7220
+            //var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7221
+            /*
7222
+			if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
7223
+			{
7224
+				$error++;
7225
+				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7226
+			}*/
7227
+        }
6653 7228
 
6654
-					if ($size == 1 || $size == 'small') {   // Format vignette
7229
+        $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
6655 7230
 
6656
-						// Find name of thumb file
6657
-						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6658
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
7231
+        $this->db->begin();
7232
+        if (! $error)
7233
+        {
7234
+            $res = $this->db->query($sql);
7235
+            if ($res===false)
7236
+            {
7237
+                $error++;
7238
+                $this->errors[] = $this->db->lasterror();
7239
+            }
7240
+        }
6659 7241
 
6660
-						// Get filesize of original file
6661
-						$imgarray=dol_getImageSize($dir.$photo);
7242
+        // Update extrafield
7243
+        if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
7244
+        {
7245
+            $result=$this->insertExtraFields();
7246
+            if ($result < 0)
7247
+            {
7248
+                $error++;
7249
+            }
7250
+        }
6662 7251
 
6663
-						if ($nbbyrow > 0)
6664
-						{
6665
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7252
+        // Triggers
7253
+        if (! $error && ! $notrigger)
7254
+        {
7255
+            // Call triggers
7256
+            $result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7257
+            if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7258
+            // End call triggers
7259
+        }
6666 7260
 
6667
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6668
-							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6669
-						}
6670
-						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
7261
+        // Commit or rollback
7262
+        if ($error) {
7263
+            $this->db->rollback();
7264
+            return -1;
7265
+        } else {
7266
+            $this->db->commit();
7267
+            return $this->id;
7268
+        }
7269
+    }
6671 7270
 
6672
-						$return.= "\n";
7271
+    /**
7272
+     * Delete object in database
7273
+     *
7274
+     * @param 	User 	$user       			User that deletes
7275
+     * @param 	bool 	$notrigger  			false=launch triggers after, true=disable triggers
7276
+     * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7277
+     * @return 	int             				<=0 if KO, >0 if OK
7278
+     */
7279
+    public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7280
+    {
7281
+        $error=0;
6673 7282
 
6674
-						$relativefile=preg_replace('/^\//', '', $pdir.$photo);
6675
-						if (empty($nolink))
6676
-						{
6677
-							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6678
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6679
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6680
-						}
7283
+        $this->db->begin();
6681 7284
 
6682
-						// Show image (width height=$maxHeight)
6683
-						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6684
-						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6685
-						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6686
-						if ($notitle) $alt='';
6687
-
6688
-						if ($usesharelink)
6689
-						{
6690
-							if ($val['share'])
6691
-							{
6692
-								if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6693
-								{
6694
-									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6695
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6696
-								}
6697
-								else {
6698
-									$return.= '<!-- Show original file -->';
6699
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6700
-								}
6701
-							}
6702
-							else
6703
-							{
6704
-								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6705
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6706
-							}
6707
-						}
6708
-						else
6709
-						{
6710
-							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6711
-							{
6712
-								$return.= '<!-- Show thumb -->';
6713
-								$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).'">';
6714
-							}
6715
-							else {
6716
-								$return.= '<!-- Show original file -->';
6717
-								$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).'">';
6718
-							}
6719
-						}
7285
+        if ($forcechilddeletion)
7286
+        {
7287
+            foreach($this->childtables as $table)
7288
+            {
7289
+                $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7290
+                $resql = $this->db->query($sql);
7291
+                if (! $resql)
7292
+                {
7293
+                    $this->error=$this->db->lasterror();
7294
+                    $this->errors[]=$this->error;
7295
+                    $this->db->rollback();
7296
+                    return -1;
7297
+                }
7298
+            }
7299
+        }
7300
+        elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7301
+        {
7302
+            $objectisused = $this->isObjectUsed($this->id);
7303
+            if (! empty($objectisused))
7304
+            {
7305
+                dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7306
+                $this->error='ErrorRecordHasChildren';
7307
+                $this->errors[]=$this->error;
7308
+                $this->db->rollback();
7309
+                return 0;
7310
+            }
7311
+        }
6720 7312
 
6721
-						if (empty($nolink)) $return.= '</a>';
6722
-						$return.="\n";
6723
-
6724
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6725
-						if ($showaction)
6726
-						{
6727
-							$return.= '<br>';
6728
-							// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6729
-							if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6730
-							{
6731
-								$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>';
6732
-							}
6733
-							// Special cas for product
6734
-							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6735
-							{
6736
-								// Link to resize
6737
-								$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; ';
6738
-
6739
-								// Link to delete
6740
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6741
-								$return.= img_delete().'</a>';
6742
-							}
6743
-						}
6744
-						$return.= "\n";
7313
+        if (! $error) {
7314
+            if (! $notrigger) {
7315
+                // Call triggers
7316
+                $result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7317
+                if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7318
+                // End call triggers
7319
+            }
7320
+        }
6745 7321
 
6746
-						if ($nbbyrow > 0)
6747
-						{
6748
-							$return.= '</td>';
6749
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6750
-						}
6751
-						else if ($nbbyrow < 0) $return.='</div>';
6752
-					}
6753
-
6754
-					if (empty($size)) {     // Format origine
6755
-						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6756
-
6757
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6758
-						if ($showaction)
6759
-						{
6760
-							// Special case for product
6761
-							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6762
-							{
6763
-								// Link to resize
6764
-								$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; ';
6765
-
6766
-								// Link to delete
6767
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6768
-								$return.= img_delete().'</a>';
6769
-							}
6770
-						}
6771
-					}
7322
+        if (! $error && ! empty($this->isextrafieldmanaged))
7323
+        {
7324
+            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7325
+            $sql.= " WHERE fk_object=" . $this->id;
6772 7326
 
6773
-					// On continue ou on arrete de boucler ?
6774
-					if ($nbmax && $nbphoto >= $nbmax) break;
6775
-				}
6776
-			}
7327
+            $resql = $this->db->query($sql);
7328
+            if (! $resql)
7329
+            {
7330
+                $this->errors[] = $this->db->lasterror();
7331
+                $error++;
7332
+            }
7333
+        }
6777 7334
 
6778
-			if ($size==1 || $size=='small')
6779
-			{
6780
-				if ($nbbyrow > 0)
6781
-				{
6782
-					// Ferme tableau
6783
-					while ($nbphoto % $nbbyrow)
6784
-					{
6785
-						$return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6786
-						$nbphoto++;
6787
-					}
6788
-
6789
-					if ($nbphoto) $return.= '</table>';
6790
-				}
6791
-			}
6792
-		}
6793
-
6794
-		$this->nbphoto = $nbphoto;
6795
-
6796
-		return $return;
6797
-	}
6798
-
6799
-
6800
-	/**
6801
-	 * Function test if type is array
6802
-	 *
6803
-	 * @param   array   $info   content informations of field
6804
-	 * @return                  bool
6805
-	 */
6806
-	protected function isArray($info)
6807
-	{
6808
-		if(is_array($info))
6809
-		{
6810
-			if(isset($info['type']) && $info['type']=='array') return true;
6811
-			else return false;
6812
-		}
6813
-		else return false;
6814
-	}
6815
-
6816
-	/**
6817
-	 * Function test if type is null
6818
-	 *
6819
-	 * @param   array   $info   content informations of field
6820
-	 * @return                  bool
6821
-	 */
6822
-	protected function isNull($info)
6823
-	{
6824
-		if(is_array($info))
6825
-		{
6826
-			if(isset($info['type']) && $info['type']=='null') return true;
6827
-			else return false;
6828
-		}
6829
-		else return false;
6830
-	}
6831
-
6832
-	/**
6833
-	 * Function test if type is date
6834
-	 *
6835
-	 * @param   array   $info   content informations of field
6836
-	 * @return                  bool
6837
-	 */
6838
-	public function isDate($info)
6839
-	{
6840
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6841
-		else return false;
6842
-	}
6843
-
6844
-	/**
6845
-	 * Function test if type is integer
6846
-	 *
6847
-	 * @param   array   $info   content informations of field
6848
-	 * @return                  bool
6849
-	 */
6850
-	public function isInt($info)
6851
-	{
6852
-		if(is_array($info))
6853
-		{
6854
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6855
-			else return false;
6856
-		}
6857
-		else return false;
6858
-	}
6859
-
6860
-	/**
6861
-	 * Function test if type is float
6862
-	 *
6863
-	 * @param   array   $info   content informations of field
6864
-	 * @return                  bool
6865
-	 */
6866
-	public function isFloat($info)
6867
-	{
6868
-		if(is_array($info))
6869
-		{
6870
-			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6871
-			else return false;
6872
-		}
6873
-		else return false;
6874
-	}
6875
-
6876
-	/**
6877
-	 * Function test if type is text
6878
-	 *
6879
-	 * @param   array   $info   content informations of field
6880
-	 * @return                  bool
6881
-	 */
6882
-	public function isText($info)
6883
-	{
6884
-		if(is_array($info))
6885
-		{
6886
-			if(isset($info['type']) && $info['type']=='text') return true;
6887
-			else return false;
6888
-		}
6889
-		else return false;
6890
-	}
6891
-
6892
-	/**
6893
-	 * Function test if is indexed
6894
-	 *
6895
-	 * @param   array   $info   content informations of field
6896
-	 * @return                  bool
6897
-	 */
6898
-	protected function isIndex($info)
6899
-	{
6900
-		if(is_array($info))
6901
-		{
6902
-			if(isset($info['index']) && $info['index']==true) return true;
6903
-			else return false;
6904
-		}
6905
-		else return false;
6906
-	}
6907
-
6908
-	/**
6909
-	 * Function to prepare the values to insert.
6910
-	 * Note $this->${field} are set by the page that make the createCommon or the updateCommon.
6911
-	 *
6912
-	 * @return array
6913
-	 */
6914
-	protected function setSaveQuery()
6915
-	{
6916
-		global $conf;
6917
-
6918
-		$queryarray=array();
6919
-		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6920
-		{
6921
-			// Depending on field type ('datetime', ...)
6922
-			if($this->isDate($info))
6923
-			{
6924
-				if(empty($this->{$field}))
6925
-				{
6926
-					$queryarray[$field] = null;
6927
-				}
6928
-				else
6929
-				{
6930
-					$queryarray[$field] = $this->db->idate($this->{$field});
6931
-				}
6932
-			}
6933
-			else if($this->isArray($info))
6934
-			{
6935
-				if(! empty($this->{$field})) {
6936
-					if(! is_array($this->{$field})) {
6937
-						$this->{$field} = array($this->{$field});
6938
-					}
6939
-					$queryarray[$field] = serialize($this->{$field});
6940
-				} else {
6941
-					$queryarray[$field] = null;
6942
-				}
6943
-			}
6944
-			else if($this->isInt($info))
6945
-			{
6946
-				if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity;
6947
-				else
6948
-				{
6949
-					$queryarray[$field] = (int) price2num($this->{$field});
6950
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6951
-				}
6952
-			}
6953
-			else if($this->isFloat($info))
6954
-			{
6955
-				$queryarray[$field] = (double) price2num($this->{$field});
6956
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6957
-			}
6958
-			else
6959
-			{
6960
-				$queryarray[$field] = $this->{$field};
6961
-			}
7335
+        if (! $error)
7336
+        {
7337
+            $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
6962 7338
 
6963
-			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6964
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6965
-		}
7339
+            $res = $this->db->query($sql);
7340
+            if($res===false) {
7341
+                $error++;
7342
+                $this->errors[] = $this->db->lasterror();
7343
+            }
7344
+        }
6966 7345
 
6967
-		return $queryarray;
6968
-	}
7346
+        // Commit or rollback
7347
+        if ($error) {
7348
+            $this->db->rollback();
7349
+            return -1;
7350
+        } else {
7351
+            $this->db->commit();
7352
+            return 1;
7353
+        }
7354
+    }
6969 7355
 
6970
-	/**
6971
-	 * Function to load data from a SQL pointer into properties of current object $this
6972
-	 *
6973
-	 * @param   stdClass    $obj    Contain data of object from database
7356
+    /**
7357
+     * Initialise object with example values
7358
+     * Id must be 0 if object instance is a specimen
7359
+     *
6974 7360
      * @return void
6975
-	 */
6976
-	protected function setVarsFromFetchObj(&$obj)
6977
-	{
6978
-		foreach ($this->fields as $field => $info)
6979
-		{
6980
-			if($this->isDate($info))
6981
-			{
6982
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6983
-				else $this->{$field} = strtotime($obj->{$field});
6984
-			}
6985
-			elseif($this->isArray($info))
6986
-			{
6987
-				if(! empty($obj->{$field})) {
6988
-					$this->{$field} = @unserialize($obj->{$field});
6989
-					// Hack for data not in UTF8
6990
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6991
-				} else {
6992
-					$this->{$field} = array();
6993
-				}
6994
-			}
6995
-			elseif($this->isInt($info))
6996
-			{
6997
-				if ($field == 'rowid') $this->id = (int) $obj->{$field};
6998
-				else $this->{$field} = (int) $obj->{$field};
6999
-			}
7000
-			elseif($this->isFloat($info))
7001
-			{
7002
-				$this->{$field} = (double) $obj->{$field};
7003
-			}
7004
-			elseif($this->isNull($info))
7005
-			{
7006
-				$val = $obj->{$field};
7007
-				// zero is not null
7008
-				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7009
-			}
7010
-			else
7011
-			{
7012
-				$this->{$field} = $obj->{$field};
7013
-			}
7014
-		}
7015
-
7016
-		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7017
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7018
-	}
7019
-
7020
-	/**
7021
-	 * Function to concat keys of fields
7022
-	 *
7023
-	 * @return string
7024
-	 */
7025
-	protected function getFieldList()
7026
-	{
7027
-		$keys = array_keys($this->fields);
7028
-		return implode(',', $keys);
7029
-	}
7030
-
7031
-	/**
7032
-	 * Add quote to field value if necessary
7033
-	 *
7034
-	 * @param 	string|int	$value			Value to protect
7035
-	 * @param	array		$fieldsentry	Properties of field
7036
-	 * @return 	string
7037
-	 */
7038
-    protected function quote($value, $fieldsentry)
7361
+     */
7362
+    public function initAsSpecimenCommon()
7039 7363
     {
7040
-		if (is_null($value)) return 'NULL';
7041
-		else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7042
-		else return "'".$this->db->escape($value)."'";
7043
-	}
7044
-
7045
-
7046
-	/**
7047
-	 * Create object into database
7048
-	 *
7049
-	 * @param  User $user      User that creates
7050
-	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
7051
-	 * @return int             <0 if KO, Id of created object if OK
7052
-	 */
7053
-	public function createCommon(User $user, $notrigger = false)
7054
-	{
7055
-		global $langs;
7056
-
7057
-		$error = 0;
7058
-
7059
-		$now=dol_now();
7060
-
7061
-		$fieldvalues = $this->setSaveQuery();
7062
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7063
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7064
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7065
-
7066
-		$keys=array();
7067
-		$values = array();
7068
-		foreach ($fieldvalues as $k => $v) {
7069
-			$keys[$k] = $k;
7070
-			$value = $this->fields[$k];
7071
-			$values[$k] = $this->quote($v, $value);
7072
-		}
7073
-
7074
-		// Clean and check mandatory
7075
-		foreach($keys as $key)
7076
-		{
7077
-			// If field is an implicit foreign key field
7078
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7079
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7080
-
7081
-			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7082
-			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7083
-			{
7084
-				$error++;
7085
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7086
-			}
7087
-
7088
-			// If field is an implicit foreign key field
7089
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7090
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7091
-		}
7092
-
7093
-		if ($error) return -1;
7094
-
7095
-		$this->db->begin();
7364
+        $this->id = 0;
7096 7365
 
7097
-		if (! $error)
7098
-		{
7099
-			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7100
-			$sql.= ' ('.implode( ", ", $keys ).')';
7101
-			$sql.= ' VALUES ('.implode( ", ", $values ).')';
7366
+        // TODO...
7367
+    }
7102 7368
 
7103
-			$res = $this->db->query($sql);
7104
-			if ($res===false) {
7105
-				$error++;
7106
-				$this->errors[] = $this->db->lasterror();
7107
-			}
7108
-		}
7109
-
7110
-		if (! $error)
7111
-		{
7112
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7113
-		}
7114
-
7115
-		// Create extrafields
7116
-		if (! $error)
7117
-		{
7118
-			$result=$this->insertExtraFields();
7119
-			if ($result < 0) $error++;
7120
-		}
7121
-
7122
-		// Triggers
7123
-		if (! $error && ! $notrigger)
7124
-		{
7125
-			// Call triggers
7126
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7127
-			if ($result < 0) { $error++; }
7128
-			// End call triggers
7129
-		}
7130
-
7131
-		// Commit or rollback
7132
-		if ($error) {
7133
-			$this->db->rollback();
7134
-			return -1;
7135
-		} else {
7136
-			$this->db->commit();
7137
-			return $this->id;
7138
-		}
7139
-	}
7140
-
7141
-
7142
-	/**
7143
-	 * Load object in memory from the database
7144
-	 *
7145
-	 * @param	int    $id				Id object
7146
-	 * @param	string $ref				Ref
7147
-	 * @param	string	$morewhere		More SQL filters (' AND ...')
7148
-	 * @return 	int         			<0 if KO, 0 if not found, >0 if OK
7149
-	 */
7150
-	public function fetchCommon($id, $ref = null, $morewhere = '')
7151
-	{
7152
-		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7153
-
7154
-		$sql = 'SELECT '.$this->getFieldList();
7155
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7156
-
7157
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7158
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7159
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7160
-		if ($morewhere)   $sql.= $morewhere;
7161
-		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7162
-
7163
-		$res = $this->db->query($sql);
7164
-		if ($res)
7165
-		{
7166
-			$obj = $this->db->fetch_object($res);
7167
-			if ($obj)
7168
-			{
7169
-				$this->setVarsFromFetchObj($obj);
7170
-				return $this->id;
7171
-			}
7172
-			else
7173
-			{
7174
-				return 0;
7175
-			}
7176
-		}
7177
-		else
7178
-		{
7179
-			$this->error = $this->db->lasterror();
7180
-			$this->errors[] = $this->error;
7181
-			return -1;
7182
-		}
7183
-	}
7184
-
7185
-	/**
7186
-	 * Update object into database
7187
-	 *
7188
-	 * @param  User $user      	User that modifies
7189
-	 * @param  bool $notrigger 	false=launch triggers after, true=disable triggers
7190
-	 * @return int             	<0 if KO, >0 if OK
7191
-	 */
7192
-	public function updateCommon(User $user, $notrigger = false)
7193
-	{
7194
-		global $conf, $langs;
7195
-
7196
-		$error = 0;
7197
-
7198
-		$now=dol_now();
7199
-
7200
-		$fieldvalues = $this->setSaveQuery();
7201
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7202
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7203
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7204
-
7205
-		$keys=array();
7206
-		$values = array();
7207
-		foreach ($fieldvalues as $k => $v) {
7208
-			$keys[$k] = $k;
7209
-			$value = $this->fields[$k];
7210
-			$values[$k] = $this->quote($v, $value);
7211
-			$tmp[] = $k.'='.$this->quote($v, $this->fields[$k]);
7212
-		}
7213
-
7214
-		// Clean and check mandatory
7215
-		foreach($keys as $key)
7216
-		{
7217
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7218
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7219
-
7220
-			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7221
-			/*
7222
-			if ($this->fields[$key]['notnull'] == 1 && empty($values[$key]))
7223
-			{
7224
-				$error++;
7225
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7226
-			}*/
7227
-		}
7228 7369
 
7229
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
7370
+    /* Part for comments */
7230 7371
 
7231
-		$this->db->begin();
7232
-		if (! $error)
7233
-		{
7234
-			$res = $this->db->query($sql);
7235
-			if ($res===false)
7236
-			{
7237
-				$error++;
7238
-				$this->errors[] = $this->db->lasterror();
7239
-			}
7240
-		}
7241
-
7242
-		// Update extrafield
7243
-		if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
7244
-		{
7245
-			$result=$this->insertExtraFields();
7246
-			if ($result < 0)
7247
-			{
7248
-				$error++;
7249
-			}
7250
-		}
7251
-
7252
-		// Triggers
7253
-		if (! $error && ! $notrigger)
7254
-		{
7255
-			// Call triggers
7256
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7257
-			if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7258
-			// End call triggers
7259
-		}
7260
-
7261
-		// Commit or rollback
7262
-		if ($error) {
7263
-			$this->db->rollback();
7264
-			return -1;
7265
-		} else {
7266
-			$this->db->commit();
7267
-			return $this->id;
7268
-		}
7269
-	}
7270
-
7271
-	/**
7272
-	 * Delete object in database
7273
-	 *
7274
-	 * @param 	User 	$user       			User that deletes
7275
-	 * @param 	bool 	$notrigger  			false=launch triggers after, true=disable triggers
7276
-	 * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7277
-	 * @return 	int             				<=0 if KO, >0 if OK
7278
-	 */
7279
-	public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7280
-	{
7281
-		$error=0;
7282
-
7283
-		$this->db->begin();
7284
-
7285
-		if ($forcechilddeletion)
7286
-		{
7287
-			foreach($this->childtables as $table)
7288
-			{
7289
-				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7290
-				$resql = $this->db->query($sql);
7291
-				if (! $resql)
7292
-				{
7293
-					$this->error=$this->db->lasterror();
7294
-					$this->errors[]=$this->error;
7295
-					$this->db->rollback();
7296
-					return -1;
7297
-				}
7298
-			}
7299
-		}
7300
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7301
-		{
7302
-			$objectisused = $this->isObjectUsed($this->id);
7303
-			if (! empty($objectisused))
7304
-			{
7305
-				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7306
-				$this->error='ErrorRecordHasChildren';
7307
-				$this->errors[]=$this->error;
7308
-				$this->db->rollback();
7309
-				return 0;
7310
-			}
7311
-		}
7312
-
7313
-		if (! $error) {
7314
-			if (! $notrigger) {
7315
-				// Call triggers
7316
-				$result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7317
-				if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7318
-				// End call triggers
7319
-			}
7320
-		}
7321
-
7322
-		if (! $error && ! empty($this->isextrafieldmanaged))
7323
-		{
7324
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7325
-			$sql.= " WHERE fk_object=" . $this->id;
7326
-
7327
-			$resql = $this->db->query($sql);
7328
-			if (! $resql)
7329
-			{
7330
-				$this->errors[] = $this->db->lasterror();
7331
-				$error++;
7332
-			}
7333
-		}
7372
+    /**
7373
+     * Load comments linked with current task
7374
+     *	@return boolean	1 if ok
7375
+     */
7376
+    public function fetchComments()
7377
+    {
7378
+        require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7334 7379
 
7335
-		if (! $error)
7336
-		{
7337
-			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7380
+        $comment = new Comment($this->db);
7381
+        $result=$comment->fetchAllFor($this->element, $this->id);
7382
+        if ($result<0) {
7383
+            $this->errors=array_merge($this->errors, $comment->errors);
7384
+            return -1;
7385
+        } else {
7386
+            $this->comments = $comment->comments;
7387
+        }
7388
+        return count($this->comments);
7389
+    }
7338 7390
 
7339
-			$res = $this->db->query($sql);
7340
-			if($res===false) {
7341
-				$error++;
7342
-				$this->errors[] = $this->db->lasterror();
7343
-			}
7344
-		}
7345
-
7346
-		// Commit or rollback
7347
-		if ($error) {
7348
-			$this->db->rollback();
7349
-			return -1;
7350
-		} else {
7351
-			$this->db->commit();
7352
-			return 1;
7353
-		}
7354
-	}
7355
-
7356
-	/**
7357
-	 * Initialise object with example values
7358
-	 * Id must be 0 if object instance is a specimen
7359
-	 *
7360
-	 * @return void
7361
-	 */
7362
-	public function initAsSpecimenCommon()
7363
-	{
7364
-		$this->id = 0;
7365
-
7366
-		// TODO...
7367
-	}
7368
-
7369
-
7370
-	/* Part for comments */
7371
-
7372
-	/**
7373
-	 * Load comments linked with current task
7374
-	 *	@return boolean	1 if ok
7375
-	 */
7376
-	public function fetchComments()
7377
-	{
7378
-		require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7379
-
7380
-		$comment = new Comment($this->db);
7381
-		$result=$comment->fetchAllFor($this->element, $this->id);
7382
-		if ($result<0) {
7383
-			$this->errors=array_merge($this->errors, $comment->errors);
7384
-			return -1;
7385
-		} else {
7386
-			$this->comments = $comment->comments;
7387
-		}
7388
-		return count($this->comments);
7389
-	}
7390
-
7391
-	/**
7392
-	 * Return nb comments already posted
7393
-	 *
7394
-	 * @return int
7395
-	 */
7396
-	public function getNbComments()
7397
-	{
7398
-		return count($this->comments);
7399
-	}
7391
+    /**
7392
+     * Return nb comments already posted
7393
+     *
7394
+     * @return int
7395
+     */
7396
+    public function getNbComments()
7397
+    {
7398
+        return count($this->comments);
7399
+    }
7400 7400
 
7401 7401
     /**
7402 7402
      * Trim object parameters
Please login to merge, or discard this patch.
Spacing   +1524 added lines, -1524 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,29 +393,29 @@  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
-		if ($ref || $ref_ext) $sql.= " AND entity = ".$conf->entity;
412
+		if ($ref || $ref_ext) $sql .= " AND entity = ".$conf->entity;
413 413
 
414 414
 		dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
415 415
 		$resql = $db->query($sql);
416 416
 		if ($resql)
417 417
 		{
418
-			$num=$db->num_rows($resql);
418
+			$num = $db->num_rows($resql);
419 419
 			if ($num > 0) return 1;
420 420
 			else return 0;
421 421
 		}
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
 	 */
430 430
 	function errorsToString()
431 431
 	{
432
-		return $this->error.(is_array($this->errors)?(($this->error!=''?', ':'').join(', ',$this->errors)):'');
432
+		return $this->error.(is_array($this->errors) ? (($this->error != '' ? ', ' : '').join(', ', $this->errors)) : '');
433 433
 	}
434 434
 
435 435
 	/**
@@ -441,18 +441,18 @@  discard block
 block discarded – undo
441 441
 	 * 	@param	int			$maxlen			Maximum length
442 442
 	 * 	@return	string						String with full name
443 443
 	 */
444
-	function getFullName($langs,$option=0,$nameorder=-1,$maxlen=0)
444
+	function getFullName($langs, $option = 0, $nameorder = -1, $maxlen = 0)
445 445
 	{
446 446
 		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
447
-		$lastname=$this->lastname;
448
-		$firstname=$this->firstname;
449
-		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:'')))));
447
+		$lastname = $this->lastname;
448
+		$firstname = $this->firstname;
449
+		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 : '')))));
450 450
 
451
-		$ret='';
451
+		$ret = '';
452 452
 		if ($option && $this->civility_id)
453 453
 		{
454
-			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
455
-			else $ret.=$this->civility_id.' ';
454
+			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id) != "Civility".$this->civility_id) $ret .= $langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
455
+			else $ret .= $this->civility_id.' ';
456 456
 		}
457 457
 
458 458
 		$ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
@@ -468,24 +468,24 @@  discard block
 block discarded – undo
468 468
 	 *  @param		int		    $withregion			1=Add region into address string
469 469
 	 *	@return		string							Full address string
470 470
 	 */
471
-	function getFullAddress($withcountry=0, $sep="\n", $withregion=0)
471
+	function getFullAddress($withcountry = 0, $sep = "\n", $withregion = 0)
472 472
 	{
473 473
 		if ($withcountry && $this->country_id && (empty($this->country_code) || empty($this->country)))
474 474
 		{
475
-			require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
476
-			$tmparray=getCountry($this->country_id,'all');
477
-			$this->country_code=$tmparray['code'];
478
-			$this->country     =$tmparray['label'];
475
+			require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
476
+			$tmparray = getCountry($this->country_id, 'all');
477
+			$this->country_code = $tmparray['code'];
478
+			$this->country     = $tmparray['label'];
479 479
 		}
480 480
 
481 481
         if ($withregion && $this->state_id && (empty($this->state_code) || empty($this->state) || empty($this->region) || empty($this->region_cpde)))
482 482
     	{
483
-    		require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
484
-    		$tmparray=getState($this->state_id,'all',0,1);
485
-			$this->state_code   =$tmparray['code'];
486
-			$this->state        =$tmparray['label'];
487
-			$this->region_code  =$tmparray['region_code'];
488
-			$this->region       =$tmparray['region'];
483
+    		require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
484
+    		$tmparray = getState($this->state_id, 'all', 0, 1);
485
+			$this->state_code   = $tmparray['code'];
486
+			$this->state        = $tmparray['label'];
487
+			$this->region_code  = $tmparray['region_code'];
488
+			$this->region       = $tmparray['region'];
489 489
         }
490 490
 
491 491
 		return dol_format_address($this, $withcountry, $sep);
@@ -503,108 +503,108 @@  discard block
 block discarded – undo
503 503
 	{
504 504
 		global $conf, $langs;
505 505
 
506
-		$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
506
+		$countriesusingstate = array('AU', 'US', 'IN', 'GB', 'ES', 'UK', 'TR'); // See also option MAIN_FORCE_STATE_INTO_ADDRESS
507 507
 
508
-		$contactid=0;
509
-		$thirdpartyid=0;
508
+		$contactid = 0;
509
+		$thirdpartyid = 0;
510 510
 		if ($this->element == 'societe')
511 511
 		{
512
-			$thirdpartyid=$this->id;
512
+			$thirdpartyid = $this->id;
513 513
 		}
514 514
 		if ($this->element == 'contact')
515 515
 		{
516
-			$contactid=$this->id;
517
-			$thirdpartyid=$object->fk_soc;
516
+			$contactid = $this->id;
517
+			$thirdpartyid = $object->fk_soc;
518 518
 		}
519 519
 		if ($this->element == 'user')
520 520
 		{
521
-			$contactid=$this->contact_id;
522
-			$thirdpartyid=$object->fk_soc;
521
+			$contactid = $this->contact_id;
522
+			$thirdpartyid = $object->fk_soc;
523 523
 		}
524 524
 
525
-		$out='<!-- BEGIN part to show address block -->';
525
+		$out = '<!-- BEGIN part to show address block -->';
526 526
 
527
-		$outdone=0;
528
-		$coords = $this->getFullAddress(1,', ',$conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
527
+		$outdone = 0;
528
+		$coords = $this->getFullAddress(1, ', ', $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT);
529 529
 		if ($coords)
530 530
 		{
531
-			if (! empty($conf->use_javascript_ajax))
531
+			if (!empty($conf->use_javascript_ajax))
532 532
 			{
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
-		if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
543
+		if (!in_array($this->country_code, $countriesusingstate) && empty($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($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
545 545
 		{
546 546
             if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
547
-                $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
547
+                $out .= ($outdone ? ' - ' : '').$this->region.' - '.$this->state;
548 548
             }
549 549
             else {
550
-                $out.=($outdone?' - ':'').$this->state;
550
+                $out .= ($outdone ? ' - ' : '').$this->state;
551 551
             }
552 552
 			$outdone++;
553 553
 		}
554 554
 
555
-		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>':'');
556
-		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
557
-			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
555
+		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>' : '');
556
+		if (!empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
557
+			$out .= dol_print_phone($this->phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
558 558
 		}
559
-		if (! empty($this->phone_pro)) {
560
-			$out.=dol_print_phone($this->phone_pro,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
559
+		if (!empty($this->phone_pro)) {
560
+			$out .= dol_print_phone($this->phone_pro, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
561 561
 		}
562
-		if (! empty($this->phone_mobile)) {
563
-			$out.=dol_print_phone($this->phone_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
562
+		if (!empty($this->phone_mobile)) {
563
+			$out .= dol_print_phone($this->phone_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
564 564
 		}
565
-		if (! empty($this->phone_perso)) {
566
-			$out.=dol_print_phone($this->phone_perso,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePerso")); $outdone++;
565
+		if (!empty($this->phone_perso)) {
566
+			$out .= dol_print_phone($this->phone_perso, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePerso")); $outdone++;
567 567
 		}
568
-		if (! empty($this->office_phone)) {
569
-			$out.=dol_print_phone($this->office_phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
568
+		if (!empty($this->office_phone)) {
569
+			$out .= dol_print_phone($this->office_phone, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'phone', $langs->trans("PhonePro")); $outdone++;
570 570
 		}
571
-		if (! empty($this->user_mobile)) {
572
-			$out.=dol_print_phone($this->user_mobile,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','mobile',$langs->trans("PhoneMobile")); $outdone++;
571
+		if (!empty($this->user_mobile)) {
572
+			$out .= dol_print_phone($this->user_mobile, $this->country_code, $contactid, $thirdpartyid, 'AC_TEL', '&nbsp;', 'mobile', $langs->trans("PhoneMobile")); $outdone++;
573 573
 		}
574
-		if (! empty($this->fax)) {
575
-			$out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
574
+		if (!empty($this->fax)) {
575
+			$out .= dol_print_phone($this->fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
576 576
 		}
577
-		if (! empty($this->office_fax)) {
578
-			$out.=dol_print_phone($this->office_fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
577
+		if (!empty($this->office_fax)) {
578
+			$out .= dol_print_phone($this->office_fax, $this->country_code, $contactid, $thirdpartyid, 'AC_FAX', '&nbsp;', 'fax', $langs->trans("Fax")); $outdone++;
579 579
 		}
580 580
 
581
-		$out.='<div style="clear: both;"></div>';
582
-		$outdone=0;
583
-		if (! empty($this->email))
581
+		$out .= '<div style="clear: both;"></div>';
582
+		$outdone = 0;
583
+		if (!empty($this->email))
584 584
 		{
585
-			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
585
+			$out .= dol_print_email($this->email, $this->id, $object->id, 'AC_EMAIL', 0, 0, 1);
586 586
 			$outdone++;
587 587
 		}
588
-		if (! empty($this->url))
588
+		if (!empty($this->url))
589 589
 		{
590
-			$out.=dol_print_url($this->url,'_goout',0,1);
590
+			$out .= dol_print_url($this->url, '_goout', 0, 1);
591 591
 			$outdone++;
592 592
 		}
593
-		$out.='<div style="clear: both;">';
594
-		if (! empty($conf->socialnetworks->enabled))
593
+		$out .= '<div style="clear: both;">';
594
+		if (!empty($conf->socialnetworks->enabled))
595 595
 		{
596
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
596
+			if ($this->skype) $out .= dol_print_socialnetworks($this->skype, $this->id, $object->id, 'skype');
597 597
 			$outdone++;
598
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
598
+			if ($this->jabberid) $out .= dol_print_socialnetworks($this->jabberid, $this->id, $object->id, 'jabber');
599 599
 			$outdone++;
600
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
600
+			if ($this->twitter) $out .= dol_print_socialnetworks($this->twitter, $this->id, $object->id, 'twitter');
601 601
 			$outdone++;
602
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
602
+			if ($this->facebook) $out .= dol_print_socialnetworks($this->facebook, $this->id, $object->id, 'facebook');
603 603
 			$outdone++;
604 604
 		}
605
-		$out.='</div>';
605
+		$out .= '</div>';
606 606
 
607
-		$out.='<!-- END Part to show address block -->';
607
+		$out .= '<!-- END Part to show address block -->';
608 608
 
609 609
 		return $out;
610 610
 	}
@@ -617,17 +617,17 @@  discard block
 block discarded – undo
617 617
 	 * @param	int		$relativelink		0=Return full external link, 1=Return link relative to root of file
618 618
 	 * @return	string						Link or empty string if there is no download link
619 619
 	 */
620
-	function getLastMainDocLink($modulepart, $initsharekey=0, $relativelink=0)
620
+	function getLastMainDocLink($modulepart, $initsharekey = 0, $relativelink = 0)
621 621
 	{
622 622
 		global $user, $dolibarr_main_url_root;
623 623
 
624 624
 		if (empty($this->last_main_doc))
625 625
 		{
626
-			return '';		// No way to known which document name to use
626
+			return ''; // No way to known which document name to use
627 627
 		}
628 628
 
629 629
 		include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
630
-		$ecmfile=new EcmFiles($this->db);
630
+		$ecmfile = new EcmFiles($this->db);
631 631
 		$result = $ecmfile->fetch(0, '', $this->last_main_doc);
632 632
 		if ($result < 0)
633 633
 		{
@@ -675,26 +675,26 @@  discard block
 block discarded – undo
675 675
 		}
676 676
 
677 677
 		// Define $urlwithroot
678
-		$urlwithouturlroot=preg_replace('/'.preg_quote(DOL_URL_ROOT,'/').'$/i','',trim($dolibarr_main_url_root));
679
-		$urlwithroot=$urlwithouturlroot.DOL_URL_ROOT;		// This is to use external domain name found into config file
678
+		$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
679
+		$urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
680 680
 		//$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
681 681
 
682
-		$forcedownload=0;
682
+		$forcedownload = 0;
683 683
 
684
-		$paramlink='';
684
+		$paramlink = '';
685 685
 		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
686 686
 		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
687 687
 		//$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
688
-		if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
689
-		if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
688
+		if (!empty($ecmfile->share)) $paramlink .= ($paramlink ? '&' : '').'hashp='.$ecmfile->share; // Hash for public share
689
+		if ($forcedownload) $paramlink .= ($paramlink ? '&' : '').'attachment=1';
690 690
 
691 691
 		if ($relativelink)
692 692
 		{
693
-			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
693
+			$linktoreturn = 'document.php'.($paramlink ? '?'.$paramlink : '');
694 694
 		}
695 695
 		else
696 696
 		{
697
-			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
697
+			$linktoreturn = $urlwithroot.'/document.php'.($paramlink ? '?'.$paramlink : '');
698 698
 		}
699 699
 
700 700
 		// Here $ecmfile->share is defined
@@ -712,10 +712,10 @@  discard block
 block discarded – undo
712 712
 	 *  @param  int		$notrigger			Disable all triggers
713 713
 	 *  @return int                 		<0 if KO, >0 if OK
714 714
 	 */
715
-	function add_contact($fk_socpeople, $type_contact, $source='external',$notrigger=0)
715
+	function add_contact($fk_socpeople, $type_contact, $source = 'external', $notrigger = 0)
716 716
 	{
717 717
         // phpcs:enable
718
-		global $user,$langs;
718
+		global $user, $langs;
719 719
 
720 720
 
721 721
 		dol_syslog(get_class($this)."::add_contact $fk_socpeople, $type_contact, $source, $notrigger");
@@ -724,43 +724,43 @@  discard block
 block discarded – undo
724 724
 		if ($fk_socpeople <= 0)
725 725
 		{
726 726
 			$langs->load("errors");
727
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","1");
728
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
727
+			$this->error = $langs->trans("ErrorWrongValueForParameterX", "1");
728
+			dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
729 729
 			return -1;
730 730
 		}
731
-		if (! $type_contact)
731
+		if (!$type_contact)
732 732
 		{
733 733
 			$langs->load("errors");
734
-			$this->error=$langs->trans("ErrorWrongValueForParameterX","2");
735
-			dol_syslog(get_class($this)."::add_contact ".$this->error,LOG_ERR);
734
+			$this->error = $langs->trans("ErrorWrongValueForParameterX", "2");
735
+			dol_syslog(get_class($this)."::add_contact ".$this->error, LOG_ERR);
736 736
 			return -2;
737 737
 		}
738 738
 
739
-		$id_type_contact=0;
739
+		$id_type_contact = 0;
740 740
 		if (is_numeric($type_contact))
741 741
 		{
742
-			$id_type_contact=$type_contact;
742
+			$id_type_contact = $type_contact;
743 743
 		}
744 744
 		else
745 745
 		{
746 746
 			// We look for id type_contact
747 747
 			$sql = "SELECT tc.rowid";
748
-			$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
749
-			$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
750
-			$sql.= " AND tc.source='".$this->db->escape($source)."'";
751
-			$sql.= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
748
+			$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
749
+			$sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
750
+			$sql .= " AND tc.source='".$this->db->escape($source)."'";
751
+			$sql .= " AND tc.code='".$this->db->escape($type_contact)."' AND tc.active=1";
752 752
 			//print $sql;
753
-			$resql=$this->db->query($sql);
753
+			$resql = $this->db->query($sql);
754 754
 			if ($resql)
755 755
 			{
756 756
 				$obj = $this->db->fetch_object($resql);
757
-				if ($obj) $id_type_contact=$obj->rowid;
757
+				if ($obj) $id_type_contact = $obj->rowid;
758 758
 			}
759 759
 		}
760 760
 
761 761
 		if ($id_type_contact == 0)
762 762
 		{
763
-			$this->error='CODE_NOT_VALID_FOR_THIS_ELEMENT';
763
+			$this->error = 'CODE_NOT_VALID_FOR_THIS_ELEMENT';
764 764
 			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");
765 765
 			return -3;
766 766
 		}
@@ -768,35 +768,35 @@  discard block
 block discarded – undo
768 768
 		$datecreate = dol_now();
769 769
 
770 770
 		// Socpeople must have already been added by some trigger, then we have to check it to avoid DB_ERROR_RECORD_ALREADY_EXISTS error
771
-		$TListeContacts=$this->liste_contact(-1, $source);
772
-		$already_added=false;
773
-		if(!empty($TListeContacts)) {
774
-			foreach($TListeContacts as $array_contact) {
775
-				if($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
776
-					$already_added=true;
771
+		$TListeContacts = $this->liste_contact(-1, $source);
772
+		$already_added = false;
773
+		if (!empty($TListeContacts)) {
774
+			foreach ($TListeContacts as $array_contact) {
775
+				if ($array_contact['status'] == 4 && $array_contact['id'] == $fk_socpeople && $array_contact['fk_c_type_contact'] == $id_type_contact) {
776
+					$already_added = true;
777 777
 					break;
778 778
 				}
779 779
 			}
780 780
 		}
781 781
 
782
-		if(!$already_added) {
782
+		if (!$already_added) {
783 783
 
784 784
 			$this->db->begin();
785 785
 
786 786
 			// Insert into database
787 787
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_contact";
788
-			$sql.= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
789
-			$sql.= " VALUES (".$this->id.", ".$fk_socpeople." , " ;
790
-			$sql.= "'".$this->db->idate($datecreate)."'";
791
-			$sql.= ", 4, ". $id_type_contact;
792
-			$sql.= ")";
788
+			$sql .= " (element_id, fk_socpeople, datecreate, statut, fk_c_type_contact) ";
789
+			$sql .= " VALUES (".$this->id.", ".$fk_socpeople." , ";
790
+			$sql .= "'".$this->db->idate($datecreate)."'";
791
+			$sql .= ", 4, ".$id_type_contact;
792
+			$sql .= ")";
793 793
 
794
-			$resql=$this->db->query($sql);
794
+			$resql = $this->db->query($sql);
795 795
 			if ($resql)
796 796
 			{
797
-				if (! $notrigger)
797
+				if (!$notrigger)
798 798
 				{
799
-					$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
799
+					$result = $this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
800 800
 					if ($result < 0)
801 801
 					{
802 802
 						$this->db->rollback();
@@ -811,14 +811,14 @@  discard block
 block discarded – undo
811 811
 			{
812 812
 				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
813 813
 				{
814
-					$this->error=$this->db->errno();
814
+					$this->error = $this->db->errno();
815 815
 					$this->db->rollback();
816 816
 					echo 'err rollback';
817 817
 					return -2;
818 818
 				}
819 819
 				else
820 820
 				{
821
-					$this->error=$this->db->error();
821
+					$this->error = $this->db->error();
822 822
 					$this->db->rollback();
823 823
 					return -1;
824 824
 				}
@@ -834,15 +834,15 @@  discard block
 block discarded – undo
834 834
 	 *    @param    string          $source     Nature of contact ('internal' or 'external')
835 835
 	 *    @return   int                         >0 if OK, <0 if KO
836 836
 	 */
837
-	function copy_linked_contact($objFrom, $source='internal')
837
+	function copy_linked_contact($objFrom, $source = 'internal')
838 838
 	{
839 839
         // phpcs:enable
840 840
 		$contacts = $objFrom->liste_contact(-1, $source);
841
-		foreach($contacts as $contact)
841
+		foreach ($contacts as $contact)
842 842
 		{
843 843
 			if ($this->add_contact($contact['id'], $contact['fk_c_type_contact'], $contact['source']) < 0)
844 844
 			{
845
-				$this->error=$this->db->lasterror();
845
+				$this->error = $this->db->lasterror();
846 846
 				return -1;
847 847
 			}
848 848
 		}
@@ -859,23 +859,23 @@  discard block
 block discarded – undo
859 859
 	 *      @param  int		$fk_socpeople	    Id of soc_people to update (not modified if 0)
860 860
 	 *      @return int                 		<0 if KO, >= 0 if OK
861 861
 	 */
862
-	function update_contact($rowid, $statut, $type_contact_id=0, $fk_socpeople=0)
862
+	function update_contact($rowid, $statut, $type_contact_id = 0, $fk_socpeople = 0)
863 863
 	{
864 864
         // phpcs:enable
865 865
 		// Insert into database
866 866
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
867
-		$sql.= " statut = ".$statut;
868
-		if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
869
-		if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
870
-		$sql.= " where rowid = ".$rowid;
871
-		$resql=$this->db->query($sql);
867
+		$sql .= " statut = ".$statut;
868
+		if ($type_contact_id) $sql .= ", fk_c_type_contact = '".$type_contact_id."'";
869
+		if ($fk_socpeople) $sql .= ", fk_socpeople = '".$fk_socpeople."'";
870
+		$sql .= " where rowid = ".$rowid;
871
+		$resql = $this->db->query($sql);
872 872
 		if ($resql)
873 873
 		{
874 874
 			return 0;
875 875
 		}
876 876
 		else
877 877
 		{
878
-			$this->error=$this->db->lasterror();
878
+			$this->error = $this->db->lasterror();
879 879
 			return -1;
880 880
 		}
881 881
 	}
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
 	 *    @param	int		$notrigger		Disable all triggers
889 889
 	 *    @return   int						>0 if OK, <0 if KO
890 890
 	 */
891
-	function delete_contact($rowid, $notrigger=0)
891
+	function delete_contact($rowid, $notrigger = 0)
892 892
 	{
893 893
         // phpcs:enable
894 894
 		global $user;
@@ -897,14 +897,14 @@  discard block
 block discarded – undo
897 897
 		$this->db->begin();
898 898
 
899 899
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
900
-		$sql.= " WHERE rowid =".$rowid;
900
+		$sql .= " WHERE rowid =".$rowid;
901 901
 
902 902
 		dol_syslog(get_class($this)."::delete_contact", LOG_DEBUG);
903 903
 		if ($this->db->query($sql))
904 904
 		{
905
-			if (! $notrigger)
905
+			if (!$notrigger)
906 906
 			{
907
-				$result=$this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
907
+				$result = $this->call_trigger(strtoupper($this->element).'_DELETE_CONTACT', $user);
908 908
 				if ($result < 0) { $this->db->rollback(); return -1; }
909 909
 			}
910 910
 
@@ -913,7 +913,7 @@  discard block
 block discarded – undo
913 913
 		}
914 914
 		else
915 915
 		{
916
-			$this->error=$this->db->lasterror();
916
+			$this->error = $this->db->lasterror();
917 917
 			$this->db->rollback();
918 918
 			return -1;
919 919
 		}
@@ -927,22 +927,22 @@  discard block
 block discarded – undo
927 927
 	 *	  @param	string	$code		Type of contact (code or id)
928 928
 	 *    @return   int					>0 if OK, <0 if KO
929 929
 	 */
930
-	function delete_linked_contact($source='',$code='')
930
+	function delete_linked_contact($source = '', $code = '')
931 931
 	{
932 932
         // phpcs:enable
933 933
 		$temp = array();
934
-		$typeContact = $this->liste_type_contact($source,'',0,0,$code);
934
+		$typeContact = $this->liste_type_contact($source, '', 0, 0, $code);
935 935
 
936
-		foreach($typeContact as $key => $value)
936
+		foreach ($typeContact as $key => $value)
937 937
 		{
938
-			array_push($temp,$key);
938
+			array_push($temp, $key);
939 939
 		}
940 940
 		$listId = implode(",", $temp);
941 941
 
942 942
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
943
-		$sql.= " WHERE element_id = ".$this->id;
943
+		$sql .= " WHERE element_id = ".$this->id;
944 944
 		if ($listId)
945
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
945
+			$sql .= " AND fk_c_type_contact IN (".$listId.")";
946 946
 
947 947
 		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
948 948
 		if ($this->db->query($sql))
@@ -951,7 +951,7 @@  discard block
 block discarded – undo
951 951
 		}
952 952
 		else
953 953
 		{
954
-			$this->error=$this->db->lasterror();
954
+			$this->error = $this->db->lasterror();
955 955
 			return -1;
956 956
 		}
957 957
 	}
@@ -966,54 +966,54 @@  discard block
 block discarded – undo
966 966
 	 *    @param    string      $code       Filter on this code of contact type ('SHIPPING', 'BILLING', ...)
967 967
 	 *    @return	array|int		        Array of contacts, -1 if error
968 968
 	 */
969
-	function liste_contact($statut=-1,$source='external',$list=0,$code='')
969
+	function liste_contact($statut = -1, $source = 'external', $list = 0, $code = '')
970 970
 	{
971 971
         // phpcs:enable
972 972
 		global $langs;
973 973
 
974
-		$tab=array();
975
-
976
-		$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
977
-		if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
978
-		if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
979
-		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
980
-		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
981
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
982
-		$sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
983
-		if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
984
-		if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
985
-		$sql.= " WHERE ec.element_id =".$this->id;
986
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
987
-		$sql.= " AND tc.element='".$this->db->escape($this->element)."'";
988
-		if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
989
-		if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
990
-		if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
991
-		$sql.= " AND tc.active=1";
992
-		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
993
-		$sql.=" ORDER BY t.lastname ASC";
974
+		$tab = array();
975
+
976
+		$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
977
+		if ($source == 'internal') $sql .= ", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
978
+		if ($source == 'external' || $source == 'thirdparty') $sql .= ", t.fk_soc as socid, t.statut as statuscontact";
979
+		$sql .= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
980
+		$sql .= ", tc.source, tc.element, tc.code, tc.libelle";
981
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
982
+		$sql .= ", ".MAIN_DB_PREFIX."element_contact ec";
983
+		if ($source == 'internal') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
984
+		if ($source == 'external' || $source == 'thirdparty') $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
985
+		$sql .= " WHERE ec.element_id =".$this->id;
986
+		$sql .= " AND ec.fk_c_type_contact=tc.rowid";
987
+		$sql .= " AND tc.element='".$this->db->escape($this->element)."'";
988
+		if ($code) $sql .= " AND tc.code = '".$this->db->escape($code)."'";
989
+		if ($source == 'internal') $sql .= " AND tc.source = 'internal'";
990
+		if ($source == 'external' || $source == 'thirdparty') $sql .= " AND tc.source = 'external'";
991
+		$sql .= " AND tc.active=1";
992
+		if ($statut >= 0) $sql .= " AND ec.statut = '".$statut."'";
993
+		$sql .= " ORDER BY t.lastname ASC";
994 994
 
995 995
 		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
996
-		$resql=$this->db->query($sql);
996
+		$resql = $this->db->query($sql);
997 997
 		if ($resql)
998 998
 		{
999
-			$num=$this->db->num_rows($resql);
1000
-			$i=0;
999
+			$num = $this->db->num_rows($resql);
1000
+			$i = 0;
1001 1001
 			while ($i < $num)
1002 1002
 			{
1003 1003
 				$obj = $this->db->fetch_object($resql);
1004 1004
 
1005
-				if (! $list)
1005
+				if (!$list)
1006 1006
 				{
1007
-					$transkey="TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1008
-					$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1009
-					$tab[$i]=array('source'=>$obj->source,'socid'=>$obj->socid,'id'=>$obj->id,
1010
-								   'nom'=>$obj->lastname,      // For backward compatibility
1007
+					$transkey = "TypeContact_".$obj->element."_".$obj->source."_".$obj->code;
1008
+					$libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1009
+					$tab[$i] = array('source'=>$obj->source, 'socid'=>$obj->socid, 'id'=>$obj->id,
1010
+								   'nom'=>$obj->lastname, // For backward compatibility
1011 1011
 								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1012 1012
 								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1013 1013
 				}
1014 1014
 				else
1015 1015
 				{
1016
-					$tab[$i]=$obj->id;
1016
+					$tab[$i] = $obj->id;
1017 1017
 				}
1018 1018
 
1019 1019
 				$i++;
@@ -1023,7 +1023,7 @@  discard block
 block discarded – undo
1023 1023
 		}
1024 1024
 		else
1025 1025
 		{
1026
-			$this->error=$this->db->lasterror();
1026
+			$this->error = $this->db->lasterror();
1027 1027
 			dol_print_error($this->db);
1028 1028
 			return -1;
1029 1029
 		}
@@ -1039,16 +1039,16 @@  discard block
 block discarded – undo
1039 1039
 	function swapContactStatus($rowid)
1040 1040
 	{
1041 1041
 		$sql = "SELECT ec.datecreate, ec.statut, ec.fk_socpeople, ec.fk_c_type_contact,";
1042
-		$sql.= " tc.code, tc.libelle";
1042
+		$sql .= " tc.code, tc.libelle";
1043 1043
 		//$sql.= ", s.fk_soc";
1044
-		$sql.= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1044
+		$sql .= " FROM (".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as tc)";
1045 1045
 		//$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
1046
-		$sql.= " WHERE ec.rowid =".$rowid;
1047
-		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
1048
-		$sql.= " AND tc.element = '".$this->db->escape($this->element)."'";
1046
+		$sql .= " WHERE ec.rowid =".$rowid;
1047
+		$sql .= " AND ec.fk_c_type_contact=tc.rowid";
1048
+		$sql .= " AND tc.element = '".$this->db->escape($this->element)."'";
1049 1049
 
1050 1050
 		dol_syslog(get_class($this)."::swapContactStatus", LOG_DEBUG);
1051
-		$resql=$this->db->query($sql);
1051
+		$resql = $this->db->query($sql);
1052 1052
 		if ($resql)
1053 1053
 		{
1054 1054
 			$obj = $this->db->fetch_object($resql);
@@ -1059,7 +1059,7 @@  discard block
 block discarded – undo
1059 1059
 		}
1060 1060
 		else
1061 1061
 		{
1062
-			$this->error=$this->db->error();
1062
+			$this->error = $this->db->error();
1063 1063
 			dol_print_error($this->db);
1064 1064
 			return -1;
1065 1065
 		}
@@ -1076,44 +1076,44 @@  discard block
 block discarded – undo
1076 1076
 	 *		@param	string	$code		Type of contact (Example: 'CUSTOMER', 'SERVICE')
1077 1077
 	 *      @return array       		Array list of type of contacts (id->label if option=0, code->label if option=1)
1078 1078
 	 */
1079
-	function liste_type_contact($source='internal', $order='position', $option=0, $activeonly=0, $code='')
1079
+	function liste_type_contact($source = 'internal', $order = 'position', $option = 0, $activeonly = 0, $code = '')
1080 1080
 	{
1081 1081
         // phpcs:enable
1082 1082
 		global $langs;
1083 1083
 
1084
-		if (empty($order)) $order='position';
1085
-		if ($order == 'position') $order.=',code';
1084
+		if (empty($order)) $order = 'position';
1085
+		if ($order == 'position') $order .= ',code';
1086 1086
 
1087 1087
 		$tab = array();
1088 1088
 		$sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1089
-		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1090
-		$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
1091
-		if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
1092
-		if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
1093
-		if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
1094
-		$sql.= $this->db->order($order,'ASC');
1089
+		$sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1090
+		$sql .= " WHERE tc.element='".$this->db->escape($this->element)."'";
1091
+		if ($activeonly == 1) $sql .= " AND tc.active=1"; // only the active types
1092
+		if (!empty($source) && $source != 'all') $sql .= " AND tc.source='".$this->db->escape($source)."'";
1093
+		if (!empty($code)) $sql .= " AND tc.code='".$this->db->escape($code)."'";
1094
+		$sql .= $this->db->order($order, 'ASC');
1095 1095
 
1096 1096
 		//print "sql=".$sql;
1097
-		$resql=$this->db->query($sql);
1097
+		$resql = $this->db->query($sql);
1098 1098
 		if ($resql)
1099 1099
 		{
1100
-			$num=$this->db->num_rows($resql);
1101
-			$i=0;
1100
+			$num = $this->db->num_rows($resql);
1101
+			$i = 0;
1102 1102
 			while ($i < $num)
1103 1103
 			{
1104 1104
 				$obj = $this->db->fetch_object($resql);
1105 1105
 
1106
-				$transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1107
-				$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1108
-				if (empty($option)) $tab[$obj->rowid]=$libelle_type;
1109
-				else $tab[$obj->code]=$libelle_type;
1106
+				$transkey = "TypeContact_".$this->element."_".$source."_".$obj->code;
1107
+				$libelle_type = ($langs->trans($transkey) != $transkey ? $langs->trans($transkey) : $obj->libelle);
1108
+				if (empty($option)) $tab[$obj->rowid] = $libelle_type;
1109
+				else $tab[$obj->code] = $libelle_type;
1110 1110
 				$i++;
1111 1111
 			}
1112 1112
 			return $tab;
1113 1113
 		}
1114 1114
 		else
1115 1115
 		{
1116
-			$this->error=$this->db->lasterror();
1116
+			$this->error = $this->db->lasterror();
1117 1117
 			//dol_print_error($this->db);
1118 1118
 			return null;
1119 1119
 		}
@@ -1130,53 +1130,53 @@  discard block
 block discarded – undo
1130 1130
 	 *		@param	int		$status		limited to a certain status
1131 1131
 	 *      @return array       		List of id for such contacts
1132 1132
 	 */
1133
-	function getIdContact($source,$code,$status=0)
1133
+	function getIdContact($source, $code, $status = 0)
1134 1134
 	{
1135 1135
 		global $conf;
1136 1136
 
1137
-		$result=array();
1138
-		$i=0;
1137
+		$result = array();
1138
+		$i = 0;
1139 1139
 		//cas particulier pour les expeditions
1140
-		if($this->element=='shipping' && $this->origin_id != 0) {
1141
-			$id=$this->origin_id;
1142
-			$element='commande';
1143
-        } else if($this->element=='reception' && $this->origin_id != 0) {
1144
-            $id=$this->origin_id;
1145
-            $element='order_supplier';
1140
+		if ($this->element == 'shipping' && $this->origin_id != 0) {
1141
+			$id = $this->origin_id;
1142
+			$element = 'commande';
1143
+        } else if ($this->element == 'reception' && $this->origin_id != 0) {
1144
+            $id = $this->origin_id;
1145
+            $element = 'order_supplier';
1146 1146
 		} else {
1147
-			$id=$this->id;
1148
-			$element=$this->element;
1147
+			$id = $this->id;
1148
+			$element = $this->element;
1149 1149
 		}
1150 1150
 
1151 1151
 		$sql = "SELECT ec.fk_socpeople";
1152
-		$sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1153
-		if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
1154
-		if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1155
-		$sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1156
-		$sql.= " WHERE ec.element_id = ".$id;
1157
-		$sql.= " AND ec.fk_socpeople = c.rowid";
1158
-		if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
1159
-		if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
1160
-		$sql.= " AND ec.fk_c_type_contact = tc.rowid";
1161
-		$sql.= " AND tc.element = '".$element."'";
1162
-		$sql.= " AND tc.source = '".$source."'";
1163
-		$sql.= " AND tc.code = '".$code."'";
1164
-		$sql.= " AND tc.active = 1";
1165
-		if ($status) $sql.= " AND ec.statut = ".$status;
1152
+		$sql .= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1153
+		if ($source == 'internal') $sql .= " ".MAIN_DB_PREFIX."user as c,";
1154
+		if ($source == 'external') $sql .= " ".MAIN_DB_PREFIX."socpeople as c,";
1155
+		$sql .= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1156
+		$sql .= " WHERE ec.element_id = ".$id;
1157
+		$sql .= " AND ec.fk_socpeople = c.rowid";
1158
+		if ($source == 'internal') $sql .= " AND c.entity IN (".getEntity('user').")";
1159
+		if ($source == 'external') $sql .= " AND c.entity IN (".getEntity('societe').")";
1160
+		$sql .= " AND ec.fk_c_type_contact = tc.rowid";
1161
+		$sql .= " AND tc.element = '".$element."'";
1162
+		$sql .= " AND tc.source = '".$source."'";
1163
+		$sql .= " AND tc.code = '".$code."'";
1164
+		$sql .= " AND tc.active = 1";
1165
+		if ($status) $sql .= " AND ec.statut = ".$status;
1166 1166
 
1167 1167
 		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1168
-		$resql=$this->db->query($sql);
1168
+		$resql = $this->db->query($sql);
1169 1169
 		if ($resql)
1170 1170
 		{
1171 1171
 			while ($obj = $this->db->fetch_object($resql))
1172 1172
 			{
1173
-				$result[$i]=$obj->fk_socpeople;
1173
+				$result[$i] = $obj->fk_socpeople;
1174 1174
 				$i++;
1175 1175
 			}
1176 1176
 		}
1177 1177
 		else
1178 1178
 		{
1179
-			$this->error=$this->db->error();
1179
+			$this->error = $this->db->error();
1180 1180
 			return null;
1181 1181
 		}
1182 1182
 
@@ -1190,16 +1190,16 @@  discard block
 block discarded – undo
1190 1190
 	 *		@param	int		$contactid      Id du contact. Use this->contactid if empty.
1191 1191
 	 *		@return	int						<0 if KO, >0 if OK
1192 1192
 	 */
1193
-	function fetch_contact($contactid=null)
1193
+	function fetch_contact($contactid = null)
1194 1194
 	{
1195 1195
         // phpcs:enable
1196
-		if (empty($contactid)) $contactid=$this->contactid;
1196
+		if (empty($contactid)) $contactid = $this->contactid;
1197 1197
 
1198 1198
 		if (empty($contactid)) return 0;
1199 1199
 
1200 1200
 		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1201 1201
 		$contact = new Contact($this->db);
1202
-		$result=$contact->fetch($contactid);
1202
+		$result = $contact->fetch($contactid);
1203 1203
 		$this->contact = $contact;
1204 1204
 		return $result;
1205 1205
 	}
@@ -1211,7 +1211,7 @@  discard block
 block discarded – undo
1211 1211
 	 *		@param		int		$force_thirdparty_id	Force thirdparty id
1212 1212
 	 *		@return		int								<0 if KO, >0 if OK
1213 1213
 	 */
1214
-	function fetch_thirdparty($force_thirdparty_id=0)
1214
+	function fetch_thirdparty($force_thirdparty_id = 0)
1215 1215
 	{
1216 1216
         // phpcs:enable
1217 1217
 		global $conf;
@@ -1219,7 +1219,7 @@  discard block
 block discarded – undo
1219 1219
 		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1220 1220
 			return 0;
1221 1221
 
1222
-		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1222
+		require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1223 1223
 
1224 1224
 		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1225 1225
 		if ($force_thirdparty_id)
@@ -1282,7 +1282,7 @@  discard block
 block discarded – undo
1282 1282
 
1283 1283
 		dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1284 1284
 
1285
-		$idtype=$this->barcode_type;
1285
+		$idtype = $this->barcode_type;
1286 1286
 		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
1287 1287
 		{
1288 1288
 			if ($this->element == 'product')      $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
@@ -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 = ".$conf->entity;
1419
+			$sql .= " AND entity = ".$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";
1580
-		if ($this->element == 'user' && ! empty($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
1579
+		$sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
1580
+		if ($this->element == 'user' && !empty($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 1597
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598
-			if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
-				if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
1600
-					$sql.= " AND te.entity IS NOT NULL"; // Show all users
1598
+			if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599
+				if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
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";
1626
-		if ($this->element == 'user' && ! empty($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
1625
+		$sql .= " FROM ".(empty($nodbprefix) ?MAIN_DB_PREFIX:'').$this->table_element." as te";
1626
+		if ($this->element == 'user' && !empty($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 1643
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644
-			if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
-				if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
1646
-					$sql.= " AND te.entity IS NOT NULL"; // Show all users
1644
+			if ($this->element == 'user' && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645
+				if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
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,8 +2669,8 @@  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)) {
2673
-			if (! empty($conf->global->$MODULE)) {
2672
+		if (!empty($MODULE)) {
2673
+			if (!empty($conf->global->$MODULE)) {
2674 2674
 				$modsactivated = explode(',', $conf->global->$MODULE);
2675 2675
 				foreach ($modsactivated as $mod) {
2676 2676
 					if ($conf->$mod->enabled)
@@ -2681,44 +2681,44 @@  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;
2687
-		if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2688
-		elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2686
+		$forcedroundingmode = $roundingadjust;
2687
+		if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode = $conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2688
+		elseif ($forcedroundingmode == 'auto') $forcedroundingmode = '0';
2689 2689
 
2690
-		$error=0;
2690
+		$error = 0;
2691 2691
 
2692 2692
 		$multicurrency_tx = !empty($this->multicurrency_tx) ? $this->multicurrency_tx : 1;
2693 2693
 
2694 2694
 		// Define constants to find lines to sum
2695
-		$fieldtva='total_tva';
2696
-		$fieldlocaltax1='total_localtax1';
2697
-		$fieldlocaltax2='total_localtax2';
2698
-		$fieldup='subprice';
2695
+		$fieldtva = 'total_tva';
2696
+		$fieldlocaltax1 = 'total_localtax1';
2697
+		$fieldlocaltax2 = 'total_localtax2';
2698
+		$fieldup = 'subprice';
2699 2699
 		if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier')
2700 2700
 		{
2701
-			$fieldtva='tva';
2702
-			$fieldup='pu_ht';
2701
+			$fieldtva = 'tva';
2702
+			$fieldup = 'pu_ht';
2703 2703
 		}
2704 2704
 		if ($this->element == 'expensereport')
2705 2705
 		{
2706
-			$fieldup='value_unit';
2706
+			$fieldup = 'value_unit';
2707 2707
 		}
2708 2708
 
2709 2709
 		$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,';
2710
-		$sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2711
-			if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
2712
-			$sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2713
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2714
-		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2710
+		$sql .= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2711
+			if ($this->table_element_line == 'facturedet') $sql .= ', situation_percent';
2712
+			$sql .= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2713
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2714
+		$sql .= ' WHERE '.$this->fk_element.' = '.$this->id;
2715 2715
 		if ($exclspec)
2716 2716
 		{
2717
-			$product_field='product_type';
2718
-			if ($this->table_element_line == 'contratdet') $product_field='';    // contratdet table has no product_type field
2719
-			if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
2717
+			$product_field = 'product_type';
2718
+			if ($this->table_element_line == 'contratdet') $product_field = ''; // contratdet table has no product_type field
2719
+			if ($product_field) $sql .= ' AND '.$product_field.' <> 9';
2720 2720
 		}
2721
-		$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
2721
+		$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 2722
 
2723 2723
 		dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2724 2724
 		$resql = $this->db->query($sql);
@@ -2732,7 +2732,7 @@  discard block
 block discarded – undo
2732 2732
 			$total_ht_by_vats  = array();
2733 2733
 			$total_tva_by_vats = array();
2734 2734
 			$total_ttc_by_vats = array();
2735
-			$this->multicurrency_total_ht	= 0;
2735
+			$this->multicurrency_total_ht = 0;
2736 2736
 			$this->multicurrency_total_tva	= 0;
2737 2737
 			$this->multicurrency_total_ttc	= 0;
2738 2738
 
@@ -2743,54 +2743,54 @@  discard block
 block discarded – undo
2743 2743
 				$obj = $this->db->fetch_object($resql);
2744 2744
 
2745 2745
 				// Note: There is no check on detail line and no check on total, if $forcedroundingmode = 'none'
2746
-				$parameters=array('fk_element' => $obj->rowid);
2746
+				$parameters = array('fk_element' => $obj->rowid);
2747 2747
 				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2748 2748
 
2749 2749
 				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'
2750 2750
 				{
2751
-					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2752
-					$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);
2753
-					$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2751
+					$localtax_array = array($obj->localtax1_type, $obj->localtax1_tx, $obj->localtax2_type, $obj->localtax2_tx);
2752
+					$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);
2753
+					$diff = price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2754 2754
 					if ($diff)
2755 2755
 					{
2756
-						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2756
+						$sqlfix = "UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2757 2757
 						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);
2758
-								$resqlfix=$this->db->query($sqlfix);
2759
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2758
+								$resqlfix = $this->db->query($sqlfix);
2759
+								if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
2760 2760
 								$obj->total_tva = $tmpcal[1];
2761 2761
 								$obj->total_ttc = $tmpcal[2];
2762 2762
 						//
2763 2763
 					}
2764 2764
 				}
2765 2765
 
2766
-				$this->total_ht        += $obj->total_ht;		// The field visible at end of line detail
2766
+				$this->total_ht        += $obj->total_ht; // The field visible at end of line detail
2767 2767
 				$this->total_tva       += $obj->total_tva;
2768 2768
 				$this->total_localtax1 += $obj->total_localtax1;
2769 2769
 				$this->total_localtax2 += $obj->total_localtax2;
2770 2770
 				$this->total_ttc       += $obj->total_ttc;
2771
-				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht;		// The field visible at end of line detail
2771
+				$this->multicurrency_total_ht        += $obj->multicurrency_total_ht; // The field visible at end of line detail
2772 2772
 				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2773 2773
 				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2774 2774
 
2775
-				if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
2776
-				if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
2777
-				if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
2775
+				if (!isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate] = 0;
2776
+				if (!isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate] = 0;
2777
+				if (!isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate] = 0;
2778 2778
 				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2779 2779
 				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2780 2780
 				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2781 2781
 
2782 2782
 				if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2783 2783
 				{
2784
-					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2785
-					$diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2784
+					$tmpvat = price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
2785
+					$diff = price2num($total_tva_by_vats[$obj->vatrate] - $tmpvat, 'MT', 1);
2786 2786
 					//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";
2787 2787
 					if ($diff)
2788 2788
 					{
2789 2789
 						if (abs($diff) > 0.1) { dol_syslog('A rounding difference was detected into TOTAL but is too high to be corrected', LOG_WARNING); exit; }
2790
-						$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;
2790
+						$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 2791
 						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);
2792
-								$resqlfix=$this->db->query($sqlfix);
2793
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2792
+								$resqlfix = $this->db->query($sqlfix);
2793
+								if (!$resqlfix) dol_print_error($this->db, 'Failed to update line');
2794 2794
 								$this->total_tva -= $diff;
2795 2795
 								$this->total_ttc -= $diff;
2796 2796
 								$total_tva_by_vats[$obj->vatrate] -= $diff;
@@ -2802,11 +2802,11 @@  discard block
 block discarded – undo
2802 2802
 			}
2803 2803
 
2804 2804
 			// Add revenue stamp to total
2805
-			$this->total_ttc       			+= isset($this->revenuestamp)?$this->revenuestamp:0;
2806
-			$this->multicurrency_total_ttc  += isset($this->revenuestamp)?($this->revenuestamp * $multicurrency_tx):0;
2805
+			$this->total_ttc += isset($this->revenuestamp) ? $this->revenuestamp : 0;
2806
+			$this->multicurrency_total_ttc += isset($this->revenuestamp) ? ($this->revenuestamp * $multicurrency_tx) : 0;
2807 2807
 
2808 2808
 			// Situations totals
2809
-			if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE )
2809
+			if ($this->situation_cycle_ref && $this->situation_counter > 1 && method_exists($this, 'get_prev_sits') && $this->type != $this::TYPE_CREDIT_NOTE)
2810 2810
 			{
2811 2811
 				$prev_sits = $this->get_prev_sits();
2812 2812
 
@@ -2825,17 +2825,17 @@  discard block
 block discarded – undo
2825 2825
 			$this->db->free($resql);
2826 2826
 
2827 2827
 			// Now update global field total_ht, total_ttc and tva
2828
-			$fieldht='total_ht';
2829
-			$fieldtva='tva';
2830
-			$fieldlocaltax1='localtax1';
2831
-			$fieldlocaltax2='localtax2';
2832
-			$fieldttc='total_ttc';
2828
+			$fieldht = 'total_ht';
2829
+			$fieldtva = 'tva';
2830
+			$fieldlocaltax1 = 'localtax1';
2831
+			$fieldlocaltax2 = 'localtax2';
2832
+			$fieldttc = 'total_ttc';
2833 2833
 			// Specific code for backward compatibility with old field names
2834
-			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht='total';
2835
-			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
2836
-			if ($this->element == 'propal')                                                $fieldttc='total';
2837
-			if ($this->element == 'expensereport')                                         $fieldtva='total_tva';
2838
-			if ($this->element == 'supplier_proposal')                                     $fieldttc='total';
2834
+			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht = 'total';
2835
+			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva = 'total_tva';
2836
+			if ($this->element == 'propal')                                                $fieldttc = 'total';
2837
+			if ($this->element == 'expensereport')                                         $fieldtva = 'total_tva';
2838
+			if ($this->element == 'supplier_proposal')                                     $fieldttc = 'total';
2839 2839
 
2840 2840
 			if (empty($nodatabaseupdate))
2841 2841
 			{
@@ -2852,16 +2852,16 @@  discard block
 block discarded – undo
2852 2852
 
2853 2853
 
2854 2854
 				dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
2855
-				$resql=$this->db->query($sql);
2856
-				if (! $resql)
2855
+				$resql = $this->db->query($sql);
2856
+				if (!$resql)
2857 2857
 				{
2858 2858
 					$error++;
2859
-					$this->error=$this->db->lasterror();
2860
-					$this->errors[]=$this->db->lasterror();
2859
+					$this->error = $this->db->lasterror();
2860
+					$this->errors[] = $this->db->lasterror();
2861 2861
 				}
2862 2862
 			}
2863 2863
 
2864
-			if (! $error)
2864
+			if (!$error)
2865 2865
 			{
2866 2866
 				return 1;
2867 2867
 			}
@@ -2872,7 +2872,7 @@  discard block
 block discarded – undo
2872 2872
 		}
2873 2873
 		else
2874 2874
 		{
2875
-			dol_print_error($this->db,'Bad request in update_price');
2875
+			dol_print_error($this->db, 'Bad request in update_price');
2876 2876
 			return -1;
2877 2877
 		}
2878 2878
 	}
@@ -2886,30 +2886,30 @@  discard block
 block discarded – undo
2886 2886
 	 *	@return		int					<=0 if KO, >0 if OK
2887 2887
 	 *	@see		fetchObjectLinked, updateObjectLinked, deleteObjectLinked
2888 2888
 	 */
2889
-	function add_object_linked($origin=null, $origin_id=null)
2889
+	function add_object_linked($origin = null, $origin_id = null)
2890 2890
 	{
2891 2891
         // phpcs:enable
2892
-		$origin = (! empty($origin) ? $origin : $this->origin);
2893
-		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2892
+		$origin = (!empty($origin) ? $origin : $this->origin);
2893
+		$origin_id = (!empty($origin_id) ? $origin_id : $this->origin_id);
2894 2894
 
2895 2895
 		// Special case
2896
-		if ($origin == 'order') $origin='commande';
2897
-		if ($origin == 'invoice') $origin='facture';
2898
-		if ($origin == 'invoice_template') $origin='facturerec';
2899
-    	if ($origin == 'supplierorder') $origin='order_supplier';
2896
+		if ($origin == 'order') $origin = 'commande';
2897
+		if ($origin == 'invoice') $origin = 'facture';
2898
+		if ($origin == 'invoice_template') $origin = 'facturerec';
2899
+    	if ($origin == 'supplierorder') $origin = 'order_supplier';
2900 2900
 		$this->db->begin();
2901 2901
 
2902 2902
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
2903
-		$sql.= "fk_source";
2904
-		$sql.= ", sourcetype";
2905
-		$sql.= ", fk_target";
2906
-		$sql.= ", targettype";
2907
-		$sql.= ") VALUES (";
2908
-		$sql.= $origin_id;
2909
-		$sql.= ", '".$this->db->escape($origin)."'";
2910
-		$sql.= ", ".$this->id;
2911
-		$sql.= ", '".$this->db->escape($this->element)."'";
2912
-		$sql.= ")";
2903
+		$sql .= "fk_source";
2904
+		$sql .= ", sourcetype";
2905
+		$sql .= ", fk_target";
2906
+		$sql .= ", targettype";
2907
+		$sql .= ") VALUES (";
2908
+		$sql .= $origin_id;
2909
+		$sql .= ", '".$this->db->escape($origin)."'";
2910
+		$sql .= ", ".$this->id;
2911
+		$sql .= ", '".$this->db->escape($this->element)."'";
2912
+		$sql .= ")";
2913 2913
 
2914 2914
 		dol_syslog(get_class($this)."::add_object_linked", LOG_DEBUG);
2915 2915
 		if ($this->db->query($sql))
@@ -2919,7 +2919,7 @@  discard block
 block discarded – undo
2919 2919
 	  	}
2920 2920
 	  	else
2921 2921
 	  	{
2922
-	  		$this->error=$this->db->lasterror();
2922
+	  		$this->error = $this->db->lasterror();
2923 2923
 	  		$this->db->rollback();
2924 2924
 	  		return 0;
2925 2925
 	  	}
@@ -2947,33 +2947,33 @@  discard block
 block discarded – undo
2947 2947
 	 *	@return int							<0 if KO, >0 if OK
2948 2948
 	 *  @see	add_object_linked, updateObjectLinked, deleteObjectLinked
2949 2949
 	 */
2950
-	function fetchObjectLinked($sourceid=null,$sourcetype='',$targetid=null,$targettype='',$clause='OR',$alsosametype=1,$orderby='sourcetype',$loadalsoobjects=1)
2950
+	function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
2951 2951
 	{
2952 2952
 		global $conf;
2953 2953
 
2954
-		$this->linkedObjectsIds=array();
2955
-		$this->linkedObjects=array();
2954
+		$this->linkedObjectsIds = array();
2955
+		$this->linkedObjects = array();
2956 2956
 
2957
-		$justsource=false;
2958
-		$justtarget=false;
2959
-		$withtargettype=false;
2960
-		$withsourcetype=false;
2957
+		$justsource = false;
2958
+		$justtarget = false;
2959
+		$withtargettype = false;
2960
+		$withsourcetype = false;
2961 2961
 
2962
-		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2962
+		if (!empty($sourceid) && !empty($sourcetype) && empty($targetid))
2963 2963
 		{
2964
-			$justsource=true;  // the source (id and type) is a search criteria
2965
-			if (! empty($targettype)) $withtargettype=true;
2964
+			$justsource = true; // the source (id and type) is a search criteria
2965
+			if (!empty($targettype)) $withtargettype = true;
2966 2966
 		}
2967
-		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2967
+		if (!empty($targetid) && !empty($targettype) && empty($sourceid))
2968 2968
 		{
2969
-			$justtarget=true;  // the target (id and type) is a search criteria
2970
-			if (! empty($sourcetype)) $withsourcetype=true;
2969
+			$justtarget = true; // the target (id and type) is a search criteria
2970
+			if (!empty($sourcetype)) $withsourcetype = true;
2971 2971
 		}
2972 2972
 
2973
-		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
2974
-		$targetid = (! empty($targetid) ? $targetid : $this->id);
2975
-		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
2976
-		$targettype = (! empty($targettype) ? $targettype : $this->element);
2973
+		$sourceid = (!empty($sourceid) ? $sourceid : $this->id);
2974
+		$targetid = (!empty($targetid) ? $targetid : $this->id);
2975
+		$sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
2976
+		$targettype = (!empty($targettype) ? $targettype : $this->element);
2977 2977
 
2978 2978
 		/*if (empty($sourceid) && empty($targetid))
2979 2979
 		 {
@@ -2983,25 +2983,25 @@  discard block
 block discarded – undo
2983 2983
 
2984 2984
 		// Links between objects are stored in table element_element
2985 2985
 		$sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
2986
-		$sql.= ' FROM '.MAIN_DB_PREFIX.'element_element';
2987
-		$sql.= " WHERE ";
2986
+		$sql .= ' FROM '.MAIN_DB_PREFIX.'element_element';
2987
+		$sql .= " WHERE ";
2988 2988
 		if ($justsource || $justtarget)
2989 2989
 		{
2990 2990
 			if ($justsource)
2991 2991
 			{
2992
-				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2993
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2992
+				$sql .= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2993
+				if ($withtargettype) $sql .= " AND targettype = '".$targettype."'";
2994 2994
 			}
2995 2995
 			else if ($justtarget)
2996 2996
 			{
2997
-				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2998
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
2997
+				$sql .= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2998
+				if ($withsourcetype) $sql .= " AND sourcetype = '".$sourcetype."'";
2999 2999
 			}
3000 3000
 		}
3001 3001
 		else
3002 3002
 		{
3003
-			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3004
-			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3003
+			$sql .= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3004
+			$sql .= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
3005 3005
 		}
3006 3006
 		$sql .= ' ORDER BY '.$orderby;
3007 3007
 
@@ -3018,36 +3018,36 @@  discard block
 block discarded – undo
3018 3018
 				{
3019 3019
 					if ($justsource)
3020 3020
 					{
3021
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3021
+						$this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3022 3022
 					}
3023 3023
 					else if ($justtarget)
3024 3024
 					{
3025
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3025
+						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3026 3026
 					}
3027 3027
 				}
3028 3028
 				else
3029 3029
 				{
3030 3030
 					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3031 3031
 					{
3032
-						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3032
+						$this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
3033 3033
 					}
3034 3034
 					if ($obj->fk_target == $targetid && $obj->targettype == $targettype)
3035 3035
 					{
3036
-						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3036
+						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
3037 3037
 					}
3038 3038
 				}
3039 3039
 				$i++;
3040 3040
 			}
3041 3041
 
3042
-			if (! empty($this->linkedObjectsIds))
3042
+			if (!empty($this->linkedObjectsIds))
3043 3043
 			{
3044 3044
 				$tmparray = $this->linkedObjectsIds;
3045
-				foreach($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3045
+				foreach ($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3046 3046
 				{
3047 3047
 					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3048 3048
 					$module = $element = $subelement = $objecttype;
3049 3049
 					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3050
-						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3050
+						&& preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
3051 3051
 					{
3052 3052
 						$module = $element = $regs[1];
3053 3053
 						$subelement = $regs[2];
@@ -3055,31 +3055,31 @@  discard block
 block discarded – undo
3055 3055
 
3056 3056
 					$classpath = $element.'/class';
3057 3057
 					// To work with non standard classpath or module name
3058
-					if ($objecttype == 'facture')			{
3058
+					if ($objecttype == 'facture') {
3059 3059
 						$classpath = 'compta/facture/class';
3060 3060
 					}
3061
-					else if ($objecttype == 'facturerec')			{
3061
+					else if ($objecttype == 'facturerec') {
3062 3062
 						$classpath = 'compta/facture/class'; $module = 'facture';
3063 3063
 					}
3064
-					else if ($objecttype == 'propal')			{
3064
+					else if ($objecttype == 'propal') {
3065 3065
 						$classpath = 'comm/propal/class';
3066 3066
 					}
3067
-					else if ($objecttype == 'supplier_proposal')			{
3067
+					else if ($objecttype == 'supplier_proposal') {
3068 3068
 						$classpath = 'supplier_proposal/class';
3069 3069
 					}
3070
-					else if ($objecttype == 'shipping')			{
3070
+					else if ($objecttype == 'shipping') {
3071 3071
 						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3072 3072
 					}
3073
-					else if ($objecttype == 'delivery')			{
3073
+					else if ($objecttype == 'delivery') {
3074 3074
 						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3075 3075
 					}
3076
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3076
+					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
3077 3077
 						$classpath = 'fourn/class'; $module = 'fournisseur';
3078 3078
 					}
3079
-					else if ($objecttype == 'fichinter')			{
3079
+					else if ($objecttype == 'fichinter') {
3080 3080
 						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3081 3081
 					}
3082
-					else if ($objecttype == 'subscription')			{
3082
+					else if ($objecttype == 'subscription') {
3083 3083
 						$classpath = 'adherents/class'; $module = 'adherent';
3084 3084
 					}
3085 3085
 
@@ -3092,16 +3092,16 @@  discard block
 block discarded – undo
3092 3092
 					else if ($objecttype == 'invoice_supplier') {
3093 3093
 						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3094 3094
 					}
3095
-					else if ($objecttype == 'order_supplier')   {
3095
+					else if ($objecttype == 'order_supplier') {
3096 3096
 						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3097 3097
 					}
3098
-					else if ($objecttype == 'supplier_proposal')   {
3098
+					else if ($objecttype == 'supplier_proposal') {
3099 3099
 						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3100 3100
 					}
3101
-					else if ($objecttype == 'facturerec')   {
3101
+					else if ($objecttype == 'facturerec') {
3102 3102
 						$classfile = 'facture-rec'; $classname = 'FactureRec';
3103 3103
 					}
3104
-					else if ($objecttype == 'subscription')   {
3104
+					else if ($objecttype == 'subscription') {
3105 3105
 						$classfile = 'subscription'; $classname = 'Subscription';
3106 3106
 					}
3107 3107
 
@@ -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,21 +3347,21 @@  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
-		if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0;    // To increase speed. Not enabled by default.
3355
+		if (!empty($conf->global->MAIN_DISABLE_CANVAS)) return 0; // To increase speed. Not enabled by default.
3356 3356
 
3357 3357
 		// Clean parameters
3358 3358
 		$ref = trim($ref);
3359 3359
 
3360 3360
 		$sql = "SELECT rowid, canvas";
3361
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3362
-		$sql.= " WHERE entity IN (".getEntity($this->element).")";
3363
-		if (! empty($id))  $sql.= " AND rowid = ".$id;
3364
-		if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
3361
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3362
+		$sql .= " WHERE entity IN (".getEntity($this->element).")";
3363
+		if (!empty($id))  $sql .= " AND rowid = ".$id;
3364
+		if (!empty($ref)) $sql .= " AND ref = '".$this->db->escape($ref)."'";
3365 3365
 
3366 3366
 		$resql = $this->db->query($sql);
3367 3367
 		if ($resql)
@@ -3369,7 +3369,7 @@  discard block
 block discarded – undo
3369 3369
 			$obj = $this->db->fetch_object($resql);
3370 3370
 			if ($obj)
3371 3371
 			{
3372
-				$this->canvas   = $obj->canvas;
3372
+				$this->canvas = $obj->canvas;
3373 3373
 				return 1;
3374 3374
 			}
3375 3375
 			else return 0;
@@ -3391,7 +3391,7 @@  discard block
 block discarded – undo
3391 3391
 	function getSpecialCode($lineid)
3392 3392
 	{
3393 3393
 		$sql = 'SELECT special_code FROM '.MAIN_DB_PREFIX.$this->table_element_line;
3394
-		$sql.= ' WHERE rowid = '.$lineid;
3394
+		$sql .= ' WHERE rowid = '.$lineid;
3395 3395
 		$resql = $this->db->query($sql);
3396 3396
 		if ($resql)
3397 3397
 		{
@@ -3407,14 +3407,14 @@  discard block
 block discarded – undo
3407 3407
 	 *  @param	int		$id			Force id of object
3408 3408
 	 *  @return	int					<0 if KO, 0 if not used, >0 if already used
3409 3409
 	 */
3410
-	function isObjectUsed($id=0)
3410
+	function isObjectUsed($id = 0)
3411 3411
 	{
3412 3412
 		global $langs;
3413 3413
 
3414
-		if (empty($id)) $id=$this->id;
3414
+		if (empty($id)) $id = $this->id;
3415 3415
 
3416 3416
 		// Check parameters
3417
-		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
3417
+		if (!isset($this->childtables) || !is_array($this->childtables) || count($this->childtables) == 0)
3418 3418
 		{
3419 3419
 			dol_print_error('Called isObjectUsed on a class with property this->childtables not defined');
3420 3420
 			return -1;
@@ -3422,24 +3422,24 @@  discard block
 block discarded – undo
3422 3422
 
3423 3423
 		$arraytoscan = $this->childtables;
3424 3424
 		// For backward compatibility, we check if array is old format array('table1', 'table2', ...)
3425
-		$tmparray=array_keys($this->childtables);
3425
+		$tmparray = array_keys($this->childtables);
3426 3426
 		if (is_numeric($tmparray[0]))
3427 3427
 		{
3428 3428
 			$arraytoscan = array_flip($this->childtables);
3429 3429
 		}
3430 3430
 
3431 3431
 		// Test if child exists
3432
-		$haschild=0;
3433
-		foreach($arraytoscan as $table => $elementname)
3432
+		$haschild = 0;
3433
+		foreach ($arraytoscan as $table => $elementname)
3434 3434
 		{
3435 3435
 			//print $id.'-'.$table.'-'.$elementname.'<br>';
3436 3436
 			// Check if third party can be deleted
3437 3437
 			$sql = "SELECT COUNT(*) as nb from ".MAIN_DB_PREFIX.$table;
3438
-			$sql.= " WHERE ".$this->fk_element." = ".$id;
3439
-			$resql=$this->db->query($sql);
3438
+			$sql .= " WHERE ".$this->fk_element." = ".$id;
3439
+			$resql = $this->db->query($sql);
3440 3440
 			if ($resql)
3441 3441
 			{
3442
-				$obj=$this->db->fetch_object($resql);
3442
+				$obj = $this->db->fetch_object($resql);
3443 3443
 				if ($obj->nb > 0)
3444 3444
 				{
3445 3445
 					$langs->load("errors");
@@ -3447,24 +3447,24 @@  discard block
 block discarded – undo
3447 3447
 					$haschild += $obj->nb;
3448 3448
 					if (is_numeric($elementname))	// old usage
3449 3449
 					{
3450
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3450
+						$this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3451 3451
 					}
3452 3452
 					else	// new usage: $elementname=Translation key
3453 3453
 					{
3454
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3454
+						$this->errors[] = $langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3455 3455
 					}
3456
-					break;    // We found at least one, we stop here
3456
+					break; // We found at least one, we stop here
3457 3457
 				}
3458 3458
 			}
3459 3459
 			else
3460 3460
 			{
3461
-				$this->errors[]=$this->db->lasterror();
3461
+				$this->errors[] = $this->db->lasterror();
3462 3462
 				return -1;
3463 3463
 			}
3464 3464
 		}
3465 3465
 		if ($haschild > 0)
3466 3466
 		{
3467
-			$this->errors[]="ErrorRecordHasChildren";
3467
+			$this->errors[] = "ErrorRecordHasChildren";
3468 3468
 			return $haschild;
3469 3469
 		}
3470 3470
 		else return 0;
@@ -3476,18 +3476,18 @@  discard block
 block discarded – undo
3476 3476
 	 *	@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
3477 3477
 	 *  @return	int						<0 if KO, 0 if no predefined products, nb of lines with predefined products if found
3478 3478
 	 */
3479
-	function hasProductsOrServices($predefined=-1)
3479
+	function hasProductsOrServices($predefined = -1)
3480 3480
 	{
3481
-		$nb=0;
3481
+		$nb = 0;
3482 3482
 
3483
-		foreach($this->lines as $key => $val)
3483
+		foreach ($this->lines as $key => $val)
3484 3484
 		{
3485
-			$qualified=0;
3486
-			if ($predefined == -1) $qualified=1;
3487
-			if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
3488
-			if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
3489
-			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
3490
-			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
3485
+			$qualified = 0;
3486
+			if ($predefined == -1) $qualified = 1;
3487
+			if ($predefined == 1 && $val->fk_product > 0) $qualified = 1;
3488
+			if ($predefined == 0 && $val->fk_product <= 0) $qualified = 1;
3489
+			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type == 0) $qualified = 1;
3490
+			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type == 1) $qualified = 1;
3491 3491
 			if ($qualified) $nb++;
3492 3492
 		}
3493 3493
 		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
@@ -3501,24 +3501,24 @@  discard block
 block discarded – undo
3501 3501
 	 */
3502 3502
 	function getTotalDiscount()
3503 3503
 	{
3504
-		$total_discount=0.00;
3504
+		$total_discount = 0.00;
3505 3505
 
3506 3506
 		$sql = "SELECT subprice as pu_ht, qty, remise_percent, total_ht";
3507
-		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3508
-		$sql.= " WHERE ".$this->fk_element." = ".$this->id;
3507
+		$sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element."det";
3508
+		$sql .= " WHERE ".$this->fk_element." = ".$this->id;
3509 3509
 
3510 3510
 		dol_syslog(get_class($this).'::getTotalDiscount', LOG_DEBUG);
3511 3511
 		$resql = $this->db->query($sql);
3512 3512
 		if ($resql)
3513 3513
 		{
3514
-			$num=$this->db->num_rows($resql);
3515
-			$i=0;
3514
+			$num = $this->db->num_rows($resql);
3515
+			$i = 0;
3516 3516
 			while ($i < $num)
3517 3517
 			{
3518 3518
 				$obj = $this->db->fetch_object($resql);
3519 3519
 
3520 3520
 				$pu_ht = $obj->pu_ht;
3521
-				$qty= $obj->qty;
3521
+				$qty = $obj->qty;
3522 3522
 				$total_ht = $obj->total_ht;
3523 3523
 
3524 3524
 				$total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT'));
@@ -3552,17 +3552,17 @@  discard block
 block discarded – undo
3552 3552
 		{
3553 3553
 			if (isset($line->qty_asked))
3554 3554
 			{
3555
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3556
-				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3555
+				if (empty($totalOrdered)) $totalOrdered = 0; // Avoid warning because $totalOrdered is ''
3556
+				$totalOrdered += $line->qty_asked; // defined for shipment only
3557 3557
 			}
3558 3558
 			if (isset($line->qty_shipped))
3559 3559
 			{
3560
-				if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3561
-				$totalToShip+=$line->qty_shipped;   // defined for shipment only
3562
-            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3560
+				if (empty($totalToShip)) $totalToShip = 0; // Avoid warning because $totalToShip is ''
3561
+				$totalToShip += $line->qty_shipped; // defined for shipment only
3562
+            } else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3563 3563
             {
3564
-                if (empty($totalToShip)) $totalToShip=0;
3565
-                $totalToShip+=$line->qty;   // defined for reception only
3564
+                if (empty($totalToShip)) $totalToShip = 0;
3565
+                $totalToShip += $line->qty; // defined for reception only
3566 3566
 			}
3567 3567
 
3568 3568
 			// Define qty, weight, volume, weight_units, volume_units
@@ -3575,27 +3575,27 @@  discard block
 block discarded – undo
3575 3575
 			}
3576 3576
 
3577 3577
 			$weight = $line->weight ? $line->weight : 0;
3578
-            ($weight==0 && !empty($line->product->weight))? $weight=$line->product->weight: 0;
3578
+            ($weight == 0 && !empty($line->product->weight)) ? $weight = $line->product->weight : 0;
3579 3579
 			$volume = $line->volume ? $line->volume : 0;
3580
-			($volume==0 && !empty($line->product->volume))? $volume=$line->product->volume: 0;
3580
+			($volume == 0 && !empty($line->product->volume)) ? $volume = $line->product->volume : 0;
3581 3581
 
3582
-			$weight_units=$line->weight_units;
3583
-			($weight_units==0 && !empty($line->product->weight_units))? $weight_units=$line->product->weight_units: 0;
3584
-			$volume_units=$line->volume_units;
3585
-			($volume_units==0 && !empty($line->product->volume_units))? $volume_units=$line->product->volume_units: 0;
3582
+			$weight_units = $line->weight_units;
3583
+			($weight_units == 0 && !empty($line->product->weight_units)) ? $weight_units = $line->product->weight_units : 0;
3584
+			$volume_units = $line->volume_units;
3585
+			($volume_units == 0 && !empty($line->product->volume_units)) ? $volume_units = $line->product->volume_units : 0;
3586 3586
 
3587
-			$weightUnit=0;
3588
-			$volumeUnit=0;
3589
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3590
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
3587
+			$weightUnit = 0;
3588
+			$volumeUnit = 0;
3589
+			if (!empty($weight_units)) $weightUnit = $weight_units;
3590
+			if (!empty($volume_units)) $volumeUnit = $volume_units;
3591 3591
 
3592
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3593
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3592
+			if (empty($totalWeight)) $totalWeight = 0; // Avoid warning because $totalWeight is ''
3593
+			if (empty($totalVolume)) $totalVolume = 0; // Avoid warning because $totalVolume is ''
3594 3594
 
3595 3595
 			//var_dump($line->volume_units);
3596 3596
 			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3597 3597
 			{
3598
-				$trueWeightUnit=pow(10, $weightUnit);
3598
+				$trueWeightUnit = pow(10, $weightUnit);
3599 3599
 				$totalWeight += $weight * $qty * $trueWeightUnit;
3600 3600
 			}
3601 3601
 			else {
@@ -3609,18 +3609,18 @@  discard block
 block discarded – undo
3609 3609
 			$totalWeight += $weight * $qty * $trueWeightUnit;
3610 3610
 		}
3611 3611
 		else
3612
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3612
+					$totalWeight += $weight * $qty; // This may be wrong if we mix different units
3613 3613
 			}
3614 3614
 			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3615 3615
 			{
3616 3616
 				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3617
-				$trueVolumeUnit=pow(10, $volumeUnit);
3617
+				$trueVolumeUnit = pow(10, $volumeUnit);
3618 3618
 				//print $line->volume;
3619 3619
 				$totalVolume += $volume * $qty * $trueVolumeUnit;
3620 3620
 			}
3621 3621
 			else
3622 3622
 			{
3623
-				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3623
+				$totalVolume += $volume * $qty; // This may be wrong if we mix different units
3624 3624
 			}
3625 3625
 		}
3626 3626
 
@@ -3637,17 +3637,17 @@  discard block
 block discarded – undo
3637 3637
 	{
3638 3638
 		$this->db->begin();
3639 3639
 
3640
-		$extraparams = (! empty($this->extraparams) ? json_encode($this->extraparams) : null);
3640
+		$extraparams = (!empty($this->extraparams) ? json_encode($this->extraparams) : null);
3641 3641
 
3642 3642
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3643
-		$sql.= " SET extraparams = ".(! empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3644
-		$sql.= " WHERE rowid = ".$this->id;
3643
+		$sql .= " SET extraparams = ".(!empty($extraparams) ? "'".$this->db->escape($extraparams)."'" : "null");
3644
+		$sql .= " WHERE rowid = ".$this->id;
3645 3645
 
3646 3646
 		dol_syslog(get_class($this)."::setExtraParameters", LOG_DEBUG);
3647 3647
 		$resql = $this->db->query($sql);
3648
-		if (! $resql)
3648
+		if (!$resql)
3649 3649
 		{
3650
-			$this->error=$this->db->lasterror();
3650
+			$this->error = $this->db->lasterror();
3651 3651
 			$this->db->rollback();
3652 3652
 			return -1;
3653 3653
 		}
@@ -3682,7 +3682,7 @@  discard block
 block discarded – undo
3682 3682
 			}
3683 3683
 		}
3684 3684
 
3685
-		$out .= (($res->code && $this->location_incoterms)?' - ':'').$this->location_incoterms;
3685
+		$out .= (($res->code && $this->location_incoterms) ? ' - ' : '').$this->location_incoterms;
3686 3686
 
3687 3687
 		return $out;
3688 3688
 	}
@@ -3728,11 +3728,11 @@  discard block
 block discarded – undo
3728 3728
 		if ($this->id && $this->table_element)
3729 3729
 		{
3730 3730
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
3731
-			$sql.= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3732
-			$sql.= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3733
-			$sql.= " WHERE rowid = " . $this->id;
3731
+			$sql .= " SET fk_incoterms = ".($id_incoterm > 0 ? $id_incoterm : "null");
3732
+			$sql .= ", location_incoterms = ".($id_incoterm > 0 ? "'".$this->db->escape($location)."'" : "null");
3733
+			$sql .= " WHERE rowid = ".$this->id;
3734 3734
 			dol_syslog(get_class($this).'::setIncoterms', LOG_DEBUG);
3735
-			$resql=$this->db->query($sql);
3735
+			$resql = $this->db->query($sql);
3736 3736
 			if ($resql)
3737 3737
 			{
3738 3738
 				$this->fk_incoterms = $id_incoterm;
@@ -3773,24 +3773,24 @@  discard block
 block discarded – undo
3773 3773
 	 */
3774 3774
 	function formAddObjectLine($dateSelector, $seller, $buyer)
3775 3775
 	{
3776
-		global $conf,$user,$langs,$object,$hookmanager;
3777
-		global $form,$bcnd,$var;
3776
+		global $conf, $user, $langs, $object, $hookmanager;
3777
+		global $form, $bcnd, $var;
3778 3778
 
3779 3779
 		// Line extrafield
3780 3780
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3781 3781
 		$extrafieldsline = new ExtraFields($this->db);
3782
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3782
+		$extralabelslines = $extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3783 3783
 
3784 3784
 		// Output template part (modules that overwrite templates must declare this into descriptor)
3785 3785
 		// Use global variables + $dateSelector + $seller and $buyer
3786
-		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
3787
-		foreach($dirtpls as $reldir)
3786
+		$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
3787
+		foreach ($dirtpls as $reldir)
3788 3788
 		{
3789 3789
 			$tpl = dol_buildpath($reldir.'/objectline_create.tpl.php');
3790 3790
 			if (empty($conf->file->strict_mode)) {
3791
-				$res=@include $tpl;
3791
+				$res = @include $tpl;
3792 3792
 			} else {
3793
-				$res=include $tpl; // for debug
3793
+				$res = include $tpl; // for debug
3794 3794
 			}
3795 3795
 			if ($res) break;
3796 3796
 		}
@@ -3814,24 +3814,24 @@  discard block
 block discarded – undo
3814 3814
 	 *	@param  int	    	$dateSelector      	1=Show also date range input fields
3815 3815
 	 *	@return	void
3816 3816
 	 */
3817
-	function printObjectLines($action, $seller, $buyer, $selected=0, $dateSelector=0)
3817
+	function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0)
3818 3818
 	{
3819 3819
 		global $conf, $hookmanager, $langs, $user;
3820 3820
 		// TODO We should not use global var for this !
3821 3821
 		global $inputalsopricewithtax, $usemargins, $disableedit, $disablemove, $disableremove, $outputalsopricetotalwithtax;
3822 3822
 
3823 3823
 		// Define usemargins
3824
-		$usemargins=0;
3825
-		if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
3824
+		$usemargins = 0;
3825
+		if (!empty($conf->margin->enabled) && !empty($this->element) && in_array($this->element, array('facture', 'propal', 'commande'))) $usemargins = 1;
3826 3826
 
3827 3827
 		$num = count($this->lines);
3828 3828
 
3829 3829
 		// Line extrafield
3830 3830
 		require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
3831 3831
 		$extrafieldsline = new ExtraFields($this->db);
3832
-		$extralabelslines=$extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3832
+		$extralabelslines = $extrafieldsline->fetch_name_optionals_label($this->table_element_line);
3833 3833
 
3834
-		$parameters = array('num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3834
+		$parameters = array('num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3835 3835
 		$reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3836 3836
 		if (empty($reshook))
3837 3837
 		{
@@ -3841,7 +3841,7 @@  discard block
 block discarded – undo
3841 3841
 			print '<tr class="liste_titre nodrag nodrop">';
3842 3842
 
3843 3843
 			// Adds a line numbering column
3844
-			if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
3844
+			if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
3845 3845
 
3846 3846
 			// Description
3847 3847
 			print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
@@ -3865,7 +3865,7 @@  discard block
 block discarded – undo
3865 3865
 			// Qty
3866 3866
 			print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
3867 3867
 
3868
-			if($conf->global->PRODUCT_USE_UNITS)
3868
+			if ($conf->global->PRODUCT_USE_UNITS)
3869 3869
 			{
3870 3870
 				print '<td class="linecoluseunit" align="left">'.$langs->trans('Unit').'</td>';
3871 3871
 			}
@@ -3874,10 +3874,10 @@  discard block
 block discarded – undo
3874 3874
 			print '<td class="linecoldiscount" align="right">'.$langs->trans('ReductionShort').'</td>';
3875 3875
 
3876 3876
 			if ($this->situation_cycle_ref) {
3877
-				print '<td class="linecolcycleref" align="right">' . $langs->trans('Progress') . '</td>';
3877
+				print '<td class="linecolcycleref" align="right">'.$langs->trans('Progress').'</td>';
3878 3878
 			}
3879 3879
 
3880
-			if ($usemargins && ! empty($conf->margin->enabled) && empty($user->societe_id))
3880
+			if ($usemargins && !empty($conf->margin->enabled) && empty($user->societe_id))
3881 3881
 			{
3882 3882
 				if (!empty($user->rights->margins->creer))
3883 3883
 				{
@@ -3887,9 +3887,9 @@  discard block
 block discarded – undo
3887 3887
 						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
3888 3888
 				}
3889 3889
 
3890
-				if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3890
+				if (!empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3891 3891
 					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3892
-				if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3892
+				if (!empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3893 3893
 					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
3894 3894
 			}
3895 3895
 
@@ -3901,13 +3901,13 @@  discard block
 block discarded – undo
3901 3901
 
3902 3902
 			if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
3903 3903
 
3904
-			print '<td class="linecoledit"></td>';  // No width to allow autodim
3904
+			print '<td class="linecoledit"></td>'; // No width to allow autodim
3905 3905
 
3906 3906
 			print '<td class="linecoldelete" width="10"></td>';
3907 3907
 
3908 3908
 			print '<td class="linecolmove" width="10"></td>';
3909 3909
 
3910
-			if($action == 'selectlines')
3910
+			if ($action == 'selectlines')
3911 3911
 			{
3912 3912
 			    print '<td class="linecolcheckall" align="center">';
3913 3913
 			    print '<input type="checkbox" class="linecheckboxtoggle" />';
@@ -3920,7 +3920,7 @@  discard block
 block discarded – undo
3920 3920
 		}
3921 3921
 
3922 3922
 		$var = true;
3923
-		$i	 = 0;
3923
+		$i = 0;
3924 3924
 
3925 3925
 		print "<tbody>\n";
3926 3926
 		foreach ($this->lines as $line)
@@ -3933,18 +3933,18 @@  discard block
 block discarded – undo
3933 3933
 			{
3934 3934
 				if (empty($line->fk_parent_line))
3935 3935
 				{
3936
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3937
-					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3936
+					$parameters = array('line'=>$line, 'var'=>$var, 'num'=>$num, 'i'=>$i, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer, 'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
3937
+					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3938 3938
 				}
3939 3939
 				else
3940 3940
 				{
3941
-					$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);
3942
-					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3941
+					$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);
3942
+					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
3943 3943
 				}
3944 3944
 			}
3945 3945
 			if (empty($reshook))
3946 3946
 			{
3947
-				$this->printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected,$extrafieldsline);
3947
+				$this->printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected, $extrafieldsline);
3948 3948
 			}
3949 3949
 
3950 3950
 			$i++;
@@ -3968,23 +3968,23 @@  discard block
 block discarded – undo
3968 3968
 	 *  @param  int			$extrafieldsline	Object of extrafield line attribute
3969 3969
 	 *	@return	void
3970 3970
 	 */
3971
-	function printObjectLine($action,$line,$var,$num,$i,$dateSelector,$seller,$buyer,$selected=0,$extrafieldsline=0)
3971
+	function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafieldsline = 0)
3972 3972
 	{
3973
-		global $conf,$langs,$user,$object,$hookmanager;
3974
-		global $form,$bc,$bcdd;
3975
-		global $object_rights, $disableedit, $disablemove, $disableremove;   // TODO We should not use global var for this !
3973
+		global $conf, $langs, $user, $object, $hookmanager;
3974
+		global $form, $bc, $bcdd;
3975
+		global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
3976 3976
 
3977 3977
 		$object_rights = $this->getRights();
3978 3978
 
3979
-		$element=$this->element;
3979
+		$element = $this->element;
3980 3980
 
3981
-		$text=''; $description=''; $type=0;
3981
+		$text = ''; $description = ''; $type = 0;
3982 3982
 
3983 3983
 		// Show product and description
3984
-		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3984
+		$type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type);
3985 3985
 		// Try to enhance type detection using date_start and date_end for free lines where type was not saved.
3986
-		if (! empty($line->date_start)) $type=1; // deprecated
3987
-		if (! empty($line->date_end)) $type=1; // deprecated
3986
+		if (!empty($line->date_start)) $type = 1; // deprecated
3987
+		if (!empty($line->date_end)) $type = 1; // deprecated
3988 3988
 
3989 3989
 		// Ligne en mode visu
3990 3990
 		if ($action != 'editline' || $selected != $line->id)
@@ -3997,14 +3997,14 @@  discard block
 block discarded – undo
3997 3997
 
3998 3998
 				$product_static->ref = $line->ref; //can change ref in hook
3999 3999
 				$product_static->label = $line->label; //can change label in hook
4000
-				$text=$product_static->getNomUrl(1);
4000
+				$text = $product_static->getNomUrl(1);
4001 4001
 
4002 4002
 				// Define output language and label
4003
-				if (! empty($conf->global->MAIN_MULTILANGS))
4003
+				if (!empty($conf->global->MAIN_MULTILANGS))
4004 4004
 				{
4005
-					if (! is_object($this->thirdparty))
4005
+					if (!is_object($this->thirdparty))
4006 4006
 					{
4007
-						dol_print_error('','Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4007
+						dol_print_error('', 'Error: Method printObjectLine was called on an object and object->fetch_thirdparty was not done before');
4008 4008
 						return;
4009 4009
 					}
4010 4010
 
@@ -4012,38 +4012,38 @@  discard block
 block discarded – undo
4012 4012
 					$prod->fetch($line->fk_product);
4013 4013
 
4014 4014
 					$outputlangs = $langs;
4015
-					$newlang='';
4016
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
4017
-					if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang;		// For language to language of customer
4018
-					if (! empty($newlang))
4015
+					$newlang = '';
4016
+					if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
4017
+					if (!empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang = $this->thirdparty->default_lang; // For language to language of customer
4018
+					if (!empty($newlang))
4019 4019
 					{
4020
-						$outputlangs = new Translate("",$conf);
4020
+						$outputlangs = new Translate("", $conf);
4021 4021
 						$outputlangs->setDefaultLang($newlang);
4022 4022
 					}
4023 4023
 
4024
-					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4024
+					$label = (!empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4025 4025
 				}
4026 4026
 				else
4027 4027
 				{
4028 4028
 					$label = $line->product_label;
4029 4029
 				}
4030 4030
 
4031
-				$text.= ' - '.(! empty($line->label)?$line->label:$label);
4032
-				$description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description));	// Description is what to show on popup. We shown nothing if already into desc.
4031
+				$text .= ' - '.(!empty($line->label) ? $line->label : $label);
4032
+				$description .= (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($line->description)); // Description is what to show on popup. We shown nothing if already into desc.
4033 4033
 			}
4034 4034
 
4035
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4035
+			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
4036 4036
 
4037 4037
 			// Output template part (modules that overwrite templates must declare this into descriptor)
4038 4038
 			// Use global variables + $dateSelector + $seller and $buyer
4039
-			$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4040
-			foreach($dirtpls as $reldir)
4039
+			$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
4040
+			foreach ($dirtpls as $reldir)
4041 4041
 			{
4042 4042
 				$tpl = dol_buildpath($reldir.'/objectline_view.tpl.php');
4043 4043
 				if (empty($conf->file->strict_mode)) {
4044
-					$res=@include $tpl;
4044
+					$res = @include $tpl;
4045 4045
 				} else {
4046
-					$res=include $tpl; // for debug
4046
+					$res = include $tpl; // for debug
4047 4047
 				}
4048 4048
 				if ($res) break;
4049 4049
 			}
@@ -4052,21 +4052,21 @@  discard block
 block discarded – undo
4052 4052
 		// Ligne en mode update
4053 4053
 		if ($this->statut == 0 && $action == 'editline' && $selected == $line->id)
4054 4054
 		{
4055
-			$label = (! empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4056
-			$placeholder=' placeholder="'.$langs->trans("Label").'"';
4055
+			$label = (!empty($line->label) ? $line->label : (($line->fk_product > 0) ? $line->product_label : ''));
4056
+			$placeholder = ' placeholder="'.$langs->trans("Label").'"';
4057 4057
 
4058
-			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
4058
+			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx / 100)), 'MU');
4059 4059
 
4060 4060
 			// Output template part (modules that overwrite templates must declare this into descriptor)
4061 4061
 			// Use global variables + $dateSelector + $seller and $buyer
4062
-			$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4063
-			foreach($dirtpls as $reldir)
4062
+			$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
4063
+			foreach ($dirtpls as $reldir)
4064 4064
 			{
4065 4065
 				$tpl = dol_buildpath($reldir.'/objectline_edit.tpl.php');
4066 4066
 				if (empty($conf->file->strict_mode)) {
4067
-					$res=@include $tpl;
4067
+					$res = @include $tpl;
4068 4068
 				} else {
4069
-					$res=include $tpl; // for debug
4069
+					$res = include $tpl; // for debug
4070 4070
 				}
4071 4071
 				if ($res) break;
4072 4072
 			}
@@ -4086,7 +4086,7 @@  discard block
 block discarded – undo
4086 4086
 	 *	@param	string		$restrictlist		''=All lines, 'services'=Restrict to services only
4087 4087
 	 *  @return	void
4088 4088
 	 */
4089
-	function printOriginLinesList($restrictlist='')
4089
+	function printOriginLinesList($restrictlist = '')
4090 4090
 	{
4091 4091
 		global $langs, $hookmanager, $conf;
4092 4092
 
@@ -4097,26 +4097,26 @@  discard block
 block discarded – undo
4097 4097
 		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4098 4098
 		if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4099 4099
 		print '<td align="right">'.$langs->trans('Qty').'</td>';
4100
-		if($conf->global->PRODUCT_USE_UNITS)
4100
+		if ($conf->global->PRODUCT_USE_UNITS)
4101 4101
 		{
4102 4102
 			print '<td align="left">'.$langs->trans('Unit').'</td>';
4103 4103
 		}
4104 4104
 		print '<td align="right">'.$langs->trans('ReductionShort').'</td></tr>';
4105 4105
 
4106 4106
 		$var = true;
4107
-		$i	 = 0;
4107
+		$i = 0;
4108 4108
 
4109
-		if (! empty($this->lines))
4109
+		if (!empty($this->lines))
4110 4110
 		{
4111 4111
 			foreach ($this->lines as $line)
4112 4112
 			{
4113
-				if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
4113
+				if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
4114 4114
 				{
4115 4115
 					if (empty($line->fk_parent_line))
4116 4116
 					{
4117
-						$parameters=array('line'=>$line,'var'=>$var,'i'=>$i);
4118
-						$action='';
4119
-						$hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4117
+						$parameters = array('line'=>$line, 'var'=>$var, 'i'=>$i);
4118
+						$action = '';
4119
+						$hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
4120 4120
 					}
4121 4121
 				}
4122 4122
 				else
@@ -4140,103 +4140,103 @@  discard block
 block discarded – undo
4140 4140
 	 *	@param	string				$restrictlist		''=All lines, 'services'=Restrict to services only (strike line if not)
4141 4141
 	 * 	@return	void
4142 4142
 	 */
4143
-	function printOriginLine($line, $var, $restrictlist='')
4143
+	function printOriginLine($line, $var, $restrictlist = '')
4144 4144
 	{
4145 4145
 		global $langs, $conf;
4146 4146
 
4147 4147
 		//var_dump($line);
4148 4148
 		if (!empty($line->date_start))
4149 4149
 		{
4150
-			$date_start=$line->date_start;
4150
+			$date_start = $line->date_start;
4151 4151
 		}
4152 4152
 		else
4153 4153
 		{
4154
-			$date_start=$line->date_debut_prevue;
4155
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4154
+			$date_start = $line->date_debut_prevue;
4155
+			if ($line->date_debut_reel) $date_start = $line->date_debut_reel;
4156 4156
 		}
4157 4157
 		if (!empty($line->date_end))
4158 4158
 		{
4159
-			$date_end=$line->date_end;
4159
+			$date_end = $line->date_end;
4160 4160
 		}
4161 4161
 		else
4162 4162
 		{
4163
-			$date_end=$line->date_fin_prevue;
4164
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4163
+			$date_end = $line->date_fin_prevue;
4164
+			if ($line->date_fin_reel) $date_end = $line->date_fin_reel;
4165 4165
 		}
4166 4166
 
4167 4167
 		$this->tpl['label'] = '';
4168
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4168
+		if (!empty($line->fk_parent_line)) $this->tpl['label'] .= img_picto('', 'rightarrow');
4169 4169
 
4170 4170
 		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4171 4171
 		{
4172
-			$discount=new DiscountAbsolute($this->db);
4172
+			$discount = new DiscountAbsolute($this->db);
4173 4173
 			$discount->fk_soc = $this->socid;
4174
-			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4174
+			$this->tpl['label'] .= $discount->getNomUrl(0, 'discount');
4175 4175
 		}
4176
-		else if (! empty($line->fk_product))
4176
+		else if (!empty($line->fk_product))
4177 4177
 		{
4178 4178
 			$productstatic = new Product($this->db);
4179 4179
 			$productstatic->id = $line->fk_product;
4180 4180
 			$productstatic->ref = $line->ref;
4181 4181
 			$productstatic->type = $line->fk_product_type;
4182
-            if(empty($productstatic->ref)){
4182
+            if (empty($productstatic->ref)) {
4183 4183
 				$line->fetch_product();
4184 4184
 				$productstatic = $line->product;
4185 4185
 			}
4186 4186
 			
4187
-			$this->tpl['label'].= $productstatic->getNomUrl(1);
4188
-			$this->tpl['label'].= ' - '.(! empty($line->label)?$line->label:$line->product_label);
4187
+			$this->tpl['label'] .= $productstatic->getNomUrl(1);
4188
+			$this->tpl['label'] .= ' - '.(!empty($line->label) ? $line->label : $line->product_label);
4189 4189
 			// Dates
4190 4190
 			if ($line->product_type == 1 && ($date_start || $date_end))
4191 4191
 			{
4192
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4192
+				$this->tpl['label'] .= get_date_range($date_start, $date_end);
4193 4193
 			}
4194 4194
 		}
4195 4195
 		else
4196 4196
 		{
4197
-			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4197
+			$this->tpl['label'] .= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''), 'service') : img_object($langs->trans(''), 'product')));
4198 4198
 			if (!empty($line->desc)) {
4199
-				$this->tpl['label'].=$line->desc;
4200
-			}else {
4201
-				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4199
+				$this->tpl['label'] .= $line->desc;
4200
+			} else {
4201
+				$this->tpl['label'] .= ($line->label ? '&nbsp;'.$line->label : '');
4202 4202
 			}
4203 4203
 			
4204 4204
 			// Dates
4205 4205
 			if ($line->product_type == 1 && ($date_start || $date_end))
4206 4206
 			{
4207
-				$this->tpl['label'].= get_date_range($date_start,$date_end);
4207
+				$this->tpl['label'] .= get_date_range($date_start, $date_end);
4208 4208
 			}
4209 4209
 		}
4210 4210
 
4211
-		if (! empty($line->desc))
4211
+		if (!empty($line->desc))
4212 4212
 		{
4213 4213
 			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4214 4214
 			{
4215
-				$discount=new DiscountAbsolute($this->db);
4215
+				$discount = new DiscountAbsolute($this->db);
4216 4216
 				$discount->fetch($line->fk_remise_except);
4217
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4217
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0));
4218 4218
 			}
4219 4219
 			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4220 4220
 			{
4221
-				$discount=new DiscountAbsolute($this->db);
4221
+				$discount = new DiscountAbsolute($this->db);
4222 4222
 				$discount->fetch($line->fk_remise_except);
4223
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4223
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0));
4224 4224
 			}
4225 4225
 			elseif ($line->desc == '(EXCESS RECEIVED)')
4226 4226
 			{
4227
-				$discount=new DiscountAbsolute($this->db);
4227
+				$discount = new DiscountAbsolute($this->db);
4228 4228
 				$discount->fetch($line->fk_remise_except);
4229
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4229
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0));
4230 4230
 			}
4231 4231
 			elseif ($line->desc == '(EXCESS PAID)')
4232 4232
 			{
4233
-				$discount=new DiscountAbsolute($this->db);
4233
+				$discount = new DiscountAbsolute($this->db);
4234 4234
 				$discount->fetch($line->fk_remise_except);
4235
-				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4235
+				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0));
4236 4236
 			}
4237 4237
 			else
4238 4238
 			{
4239
-				$this->tpl['description'] = dol_trunc($line->desc,60);
4239
+				$this->tpl['description'] = dol_trunc($line->desc, 60);
4240 4240
 			}
4241 4241
 		}
4242 4242
 		else
@@ -4247,7 +4247,7 @@  discard block
 block discarded – undo
4247 4247
         // VAT Rate
4248 4248
         $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4249 4249
         $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
4250
-        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4250
+        if (!empty($line->vat_src_code) && !preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'] .= ' ('.$line->vat_src_code.')';
4251 4251
 
4252 4252
 		$this->tpl['price'] = price($line->subprice);
4253 4253
 		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
@@ -4256,19 +4256,19 @@  discard block
 block discarded – undo
4256 4256
 		$this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4257 4257
 
4258 4258
 		// Is the line strike or not
4259
-		$this->tpl['strike']=0;
4260
-		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4259
+		$this->tpl['strike'] = 0;
4260
+		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike'] = 1;
4261 4261
 
4262 4262
 		// Output template part (modules that overwrite templates must declare this into descriptor)
4263 4263
 		// Use global variables + $dateSelector + $seller and $buyer
4264
-		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/core/tpl'));
4265
-		foreach($dirtpls as $reldir)
4264
+		$dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl'));
4265
+		foreach ($dirtpls as $reldir)
4266 4266
 		{
4267 4267
 			$tpl = dol_buildpath($reldir.'/originproductline.tpl.php');
4268 4268
 			if (empty($conf->file->strict_mode)) {
4269
-				$res=@include $tpl;
4269
+				$res = @include $tpl;
4270 4270
 			} else {
4271
-				$res=include $tpl; // for debug
4271
+				$res = include $tpl; // for debug
4272 4272
 			}
4273 4273
 			if ($res) break;
4274 4274
 		}
@@ -4286,26 +4286,26 @@  discard block
 block discarded – undo
4286 4286
 	 *	@param		int		$mandatory			Mandatory or not
4287 4287
 	 *	@return		int							<=0 if KO, >0 if OK
4288 4288
 	 */
4289
-	function add_element_resource($resource_id, $resource_type, $busy=0, $mandatory=0)
4289
+	function add_element_resource($resource_id, $resource_type, $busy = 0, $mandatory = 0)
4290 4290
 	{
4291 4291
         // phpcs:enable
4292 4292
 		$this->db->begin();
4293 4293
 
4294 4294
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_resources (";
4295
-		$sql.= "resource_id";
4296
-		$sql.= ", resource_type";
4297
-		$sql.= ", element_id";
4298
-		$sql.= ", element_type";
4299
-		$sql.= ", busy";
4300
-		$sql.= ", mandatory";
4301
-		$sql.= ") VALUES (";
4302
-		$sql.= $resource_id;
4303
-		$sql.= ", '".$this->db->escape($resource_type)."'";
4304
-		$sql.= ", '".$this->db->escape($this->id)."'";
4305
-		$sql.= ", '".$this->db->escape($this->element)."'";
4306
-		$sql.= ", '".$this->db->escape($busy)."'";
4307
-		$sql.= ", '".$this->db->escape($mandatory)."'";
4308
-		$sql.= ")";
4295
+		$sql .= "resource_id";
4296
+		$sql .= ", resource_type";
4297
+		$sql .= ", element_id";
4298
+		$sql .= ", element_type";
4299
+		$sql .= ", busy";
4300
+		$sql .= ", mandatory";
4301
+		$sql .= ") VALUES (";
4302
+		$sql .= $resource_id;
4303
+		$sql .= ", '".$this->db->escape($resource_type)."'";
4304
+		$sql .= ", '".$this->db->escape($this->id)."'";
4305
+		$sql .= ", '".$this->db->escape($this->element)."'";
4306
+		$sql .= ", '".$this->db->escape($busy)."'";
4307
+		$sql .= ", '".$this->db->escape($mandatory)."'";
4308
+		$sql .= ")";
4309 4309
 
4310 4310
 		dol_syslog(get_class($this)."::add_element_resource", LOG_DEBUG);
4311 4311
 		if ($this->db->query($sql))
@@ -4315,7 +4315,7 @@  discard block
 block discarded – undo
4315 4315
 		}
4316 4316
 		else
4317 4317
 		{
4318
-			$this->error=$this->db->lasterror();
4318
+			$this->error = $this->db->lasterror();
4319 4319
 			$this->db->rollback();
4320 4320
 			return  0;
4321 4321
 		}
@@ -4330,7 +4330,7 @@  discard block
 block discarded – undo
4330 4330
 	 *    @param	int		$notrigger		Disable all triggers
4331 4331
 	 *    @return   int						>0 if OK, <0 if KO
4332 4332
 	 */
4333
-	function delete_resource($rowid, $element, $notrigger=0)
4333
+	function delete_resource($rowid, $element, $notrigger = 0)
4334 4334
 	{
4335 4335
         // phpcs:enable
4336 4336
 		global $user;
@@ -4338,22 +4338,22 @@  discard block
 block discarded – undo
4338 4338
 		$this->db->begin();
4339 4339
 
4340 4340
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_resources";
4341
-		$sql.= " WHERE rowid=".$rowid;
4341
+		$sql .= " WHERE rowid=".$rowid;
4342 4342
 
4343 4343
 		dol_syslog(get_class($this)."::delete_resource", LOG_DEBUG);
4344 4344
 
4345
-		$resql=$this->db->query($sql);
4346
-		if (! $resql)
4345
+		$resql = $this->db->query($sql);
4346
+		if (!$resql)
4347 4347
 		{
4348
-			$this->error=$this->db->lasterror();
4348
+			$this->error = $this->db->lasterror();
4349 4349
 			$this->db->rollback();
4350 4350
 			return -1;
4351 4351
 		}
4352 4352
 		else
4353 4353
 		{
4354
-			if (! $notrigger)
4354
+			if (!$notrigger)
4355 4355
 			{
4356
-				$result=$this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4356
+				$result = $this->call_trigger(strtoupper($element).'_DELETE_RESOURCE', $user);
4357 4357
 				if ($result < 0) { $this->db->rollback(); return -1; }
4358 4358
 			}
4359 4359
 			$this->db->commit();
@@ -4372,8 +4372,8 @@  discard block
 block discarded – undo
4372 4372
 		// Force a copy of this->lines, otherwise it will point to same object.
4373 4373
 		if (isset($this->lines) && is_array($this->lines))
4374 4374
 		{
4375
-			$nboflines=count($this->lines);
4376
-			for($i=0; $i < $nboflines; $i++)
4375
+			$nboflines = count($this->lines);
4376
+			for ($i = 0; $i < $nboflines; $i++)
4377 4377
 			{
4378 4378
 				$this->lines[$i] = clone $this->lines[$i];
4379 4379
 			}
@@ -4393,43 +4393,43 @@  discard block
 block discarded – undo
4393 4393
 	 * @return 	int 						>0 if OK, <0 if KO
4394 4394
 	 * @see	addFileIntoDatabaseIndex
4395 4395
 	 */
4396
-	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
4396
+	protected function commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams = null)
4397 4397
 	{
4398 4398
 		global $conf, $langs, $user;
4399 4399
 
4400
-		$srctemplatepath='';
4400
+		$srctemplatepath = '';
4401 4401
 
4402 4402
 		// Increase limit for PDF build
4403
-		$err=error_reporting();
4403
+		$err = error_reporting();
4404 4404
 		error_reporting(0);
4405 4405
 		@set_time_limit(120);
4406 4406
 		error_reporting($err);
4407 4407
 
4408 4408
 		// If selected model is a filename template (then $modele="modelname" or "modelname:filename")
4409
-		$tmp=explode(':',$modele,2);
4410
-		if (! empty($tmp[1]))
4409
+		$tmp = explode(':', $modele, 2);
4410
+		if (!empty($tmp[1]))
4411 4411
 		{
4412
-			$modele=$tmp[0];
4413
-			$srctemplatepath=$tmp[1];
4412
+			$modele = $tmp[0];
4413
+			$srctemplatepath = $tmp[1];
4414 4414
 		}
4415 4415
 
4416 4416
 		// Search template files
4417
-		$file=''; $classname=''; $filefound=0;
4418
-		$dirmodels=array('/');
4419
-		if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
4420
-		foreach($dirmodels as $reldir)
4417
+		$file = ''; $classname = ''; $filefound = 0;
4418
+		$dirmodels = array('/');
4419
+		if (is_array($conf->modules_parts['models'])) $dirmodels = array_merge($dirmodels, $conf->modules_parts['models']);
4420
+		foreach ($dirmodels as $reldir)
4421 4421
 		{
4422
-			foreach(array('doc','pdf') as $prefix)
4422
+			foreach (array('doc', 'pdf') as $prefix)
4423 4423
 			{
4424
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4424
+				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php"; // Member module use prefix_module.class.php
4425 4425
 				else $file = $prefix."_".$modele.".modules.php";
4426 4426
 
4427 4427
 				// On verifie l'emplacement du modele
4428
-				$file=dol_buildpath($reldir.$modelspath.$file,0);
4428
+				$file = dol_buildpath($reldir.$modelspath.$file, 0);
4429 4429
 				if (file_exists($file))
4430 4430
 				{
4431
-					$filefound=1;
4432
-					$classname=$prefix.'_'.$modele;
4431
+					$filefound = 1;
4432
+					$classname = $prefix.'_'.$modele;
4433 4433
 					break;
4434 4434
 				}
4435 4435
 			}
@@ -4439,7 +4439,7 @@  discard block
 block discarded – undo
4439 4439
 		// If generator was found
4440 4440
 		if ($filefound)
4441 4441
 		{
4442
-			global $db;  // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4442
+			global $db; // Required to solve a conception default in commonstickergenerator.class.php making an include of code using $db
4443 4443
 
4444 4444
 			require_once $file;
4445 4445
 
@@ -4448,32 +4448,32 @@  discard block
 block discarded – undo
4448 4448
 			// If generator is ODT, we must have srctemplatepath defined, if not we set it.
4449 4449
 			if ($obj->type == 'odt' && empty($srctemplatepath))
4450 4450
 			{
4451
-				$varfortemplatedir=$obj->scandir;
4452
-				if ($varfortemplatedir && ! empty($conf->global->$varfortemplatedir))
4451
+				$varfortemplatedir = $obj->scandir;
4452
+				if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir))
4453 4453
 				{
4454
-					$dirtoscan=$conf->global->$varfortemplatedir;
4454
+					$dirtoscan = $conf->global->$varfortemplatedir;
4455 4455
 
4456
-					$listoffiles=array();
4456
+					$listoffiles = array();
4457 4457
 
4458 4458
 					// Now we add first model found in directories scanned
4459
-					$listofdir=explode(',',$dirtoscan);
4460
-					foreach($listofdir as $key => $tmpdir)
4459
+					$listofdir = explode(',', $dirtoscan);
4460
+					foreach ($listofdir as $key => $tmpdir)
4461 4461
 					{
4462
-						$tmpdir=trim($tmpdir);
4463
-						$tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
4464
-						if (! $tmpdir) { unset($listofdir[$key]); continue; }
4462
+						$tmpdir = trim($tmpdir);
4463
+						$tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
4464
+						if (!$tmpdir) { unset($listofdir[$key]); continue; }
4465 4465
 						if (is_dir($tmpdir))
4466 4466
 						{
4467
-							$tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4468
-							if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4467
+							$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '\.od(s|t)$', '', 'name', SORT_ASC, 0);
4468
+							if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
4469 4469
 						}
4470 4470
 					}
4471 4471
 
4472 4472
 					if (count($listoffiles))
4473 4473
 					{
4474
-						foreach($listoffiles as $record)
4474
+						foreach ($listoffiles as $record)
4475 4475
 						{
4476
-							$srctemplatepath=$record['fullname'];
4476
+							$srctemplatepath = $record['fullname'];
4477 4477
 							break;
4478 4478
 						}
4479 4479
 					}
@@ -4481,27 +4481,27 @@  discard block
 block discarded – undo
4481 4481
 
4482 4482
 				if (empty($srctemplatepath))
4483 4483
 				{
4484
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4484
+					$this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotDefined';
4485 4485
 					return -1;
4486 4486
 				}
4487 4487
 			}
4488 4488
 
4489
-			if ($obj->type == 'odt' && ! empty($srctemplatepath))
4489
+			if ($obj->type == 'odt' && !empty($srctemplatepath))
4490 4490
 			{
4491
-				if (! dol_is_file($srctemplatepath))
4491
+				if (!dol_is_file($srctemplatepath))
4492 4492
 				{
4493
-					$this->error='ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4493
+					$this->error = 'ErrorGenerationAskedForOdtTemplateWithSrcFileNotFound';
4494 4494
 					return -1;
4495 4495
 				}
4496 4496
 			}
4497 4497
 
4498 4498
 			// We save charset_output to restore it because write_file can change it if needed for
4499 4499
 			// output format that does not support UTF8.
4500
-			$sav_charset_output=$outputlangs->charset_output;
4500
+			$sav_charset_output = $outputlangs->charset_output;
4501 4501
 
4502 4502
 			if (in_array(get_class($this), array('Adherent')))
4503 4503
 			{
4504
-				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4504
+				$arrayofrecords = array(); // The write_file of templates of adherent class need this var
4505 4505
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4506 4506
 			}
4507 4507
 			else
@@ -4512,41 +4512,41 @@  discard block
 block discarded – undo
4512 4512
 
4513 4513
 			if ($resultwritefile > 0)
4514 4514
 			{
4515
-				$outputlangs->charset_output=$sav_charset_output;
4515
+				$outputlangs->charset_output = $sav_charset_output;
4516 4516
 
4517 4517
 				// We delete old preview
4518 4518
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
4519 4519
 				dol_delete_preview($this);
4520 4520
 
4521 4521
 				// Index file in database
4522
-				if (! empty($obj->result['fullpath']))
4522
+				if (!empty($obj->result['fullpath']))
4523 4523
 				{
4524 4524
 					$destfull = $obj->result['fullpath'];
4525 4525
 					$upload_dir = dirname($destfull);
4526 4526
 					$destfile = basename($destfull);
4527
-					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4527
+					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $upload_dir);
4528 4528
 
4529
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4529
+					if (!preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4530 4530
 					{
4531 4531
 						$filename = basename($destfile);
4532 4532
 						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4533 4533
 						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4534 4534
 
4535 4535
 						include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
4536
-						$ecmfile=new EcmFiles($this->db);
4537
-						$result = $ecmfile->fetch(0, '', ($rel_dir?$rel_dir.'/':'').$filename);
4536
+						$ecmfile = new EcmFiles($this->db);
4537
+						$result = $ecmfile->fetch(0, '', ($rel_dir ? $rel_dir.'/' : '').$filename);
4538 4538
 
4539 4539
 						// Set the public "share" key
4540 4540
 						$setsharekey = false;
4541 4541
 						if ($this->element == 'propal')
4542 4542
 						{
4543
-							$useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL;	// Replace this with 1 when feature to make online signature is ok
4544
-							if ($useonlinesignature) $setsharekey=true;
4545
-							if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4543
+							$useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL; // Replace this with 1 when feature to make online signature is ok
4544
+							if ($useonlinesignature) $setsharekey = true;
4545
+							if (!empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true;
4546 4546
 						}
4547
-						if ($this->element == 'commande'     && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))        $setsharekey=true;
4548
-						if ($this->element == 'facture'      && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))      $setsharekey=true;
4549
-						if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4547
+						if ($this->element == 'commande' && !empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))        $setsharekey = true;
4548
+						if ($this->element == 'facture' && !empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))      $setsharekey = true;
4549
+						if ($this->element == 'bank_account' && !empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey = true;
4550 4550
 
4551 4551
 						if ($setsharekey)
4552 4552
 						{
@@ -4559,11 +4559,11 @@  discard block
 block discarded – undo
4559 4559
 
4560 4560
 						if ($result > 0)
4561 4561
 						{
4562
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4562
+							$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
4563 4563
 							$ecmfile->fullpath_orig = '';
4564 4564
 							$ecmfile->gen_or_uploaded = 'generated';
4565
-							$ecmfile->description = '';    // indexed content
4566
-							$ecmfile->keyword = '';        // keyword content
4565
+							$ecmfile->description = ''; // indexed content
4566
+							$ecmfile->keyword = ''; // keyword content
4567 4567
 							$result = $ecmfile->update($user);
4568 4568
 							if ($result < 0)
4569 4569
 							{
@@ -4575,11 +4575,11 @@  discard block
 block discarded – undo
4575 4575
 							$ecmfile->entity = $conf->entity;
4576 4576
 							$ecmfile->filepath = $rel_dir;
4577 4577
 							$ecmfile->filename = $filename;
4578
-							$ecmfile->label = md5_file(dol_osencode($destfull));	// hash of file content
4578
+							$ecmfile->label = md5_file(dol_osencode($destfull)); // hash of file content
4579 4579
 							$ecmfile->fullpath_orig = '';
4580 4580
 							$ecmfile->gen_or_uploaded = 'generated';
4581
-							$ecmfile->description = '';    // indexed content
4582
-							$ecmfile->keyword = '';        // keyword content
4581
+							$ecmfile->description = ''; // indexed content
4582
+							$ecmfile->keyword = ''; // keyword content
4583 4583
 							$ecmfile->src_object_type = $this->table_element;
4584 4584
 							$ecmfile->src_object_id   = $this->id;
4585 4585
 
@@ -4596,14 +4596,14 @@  discard block
 block discarded – undo
4596 4596
 						//var_dump($obj->update_main_doc_field);exit;
4597 4597
 
4598 4598
 						// Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4599
-						$update_main_doc_field=0;
4600
-						if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4601
-						if ($update_main_doc_field && ! empty($this->table_element))
4599
+						$update_main_doc_field = 0;
4600
+						if (!empty($obj->update_main_doc_field)) $update_main_doc_field = 1;
4601
+						if ($update_main_doc_field && !empty($this->table_element))
4602 4602
 						{
4603 4603
 							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4604
-							$sql.= ' WHERE rowid = '.$this->id;
4604
+							$sql .= ' WHERE rowid = '.$this->id;
4605 4605
 							$resql = $this->db->query($sql);
4606
-							if (! $resql) dol_print_error($this->db);
4606
+							if (!$resql) dol_print_error($this->db);
4607 4607
 						}
4608 4608
 					}
4609 4609
 				}
@@ -4619,15 +4619,15 @@  discard block
 block discarded – undo
4619 4619
 			}
4620 4620
 			else
4621 4621
 			{
4622
-				$outputlangs->charset_output=$sav_charset_output;
4622
+				$outputlangs->charset_output = $sav_charset_output;
4623 4623
 				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4624 4624
 				return -1;
4625 4625
 			}
4626 4626
 		}
4627 4627
 		else
4628 4628
 		{
4629
-			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4630
-			dol_print_error('',$this->error);
4629
+			$this->error = $langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists", $file);
4630
+			dol_print_error('', $this->error);
4631 4631
 			return -1;
4632 4632
 		}
4633 4633
 	}
@@ -4643,9 +4643,9 @@  discard block
 block discarded – undo
4643 4643
 	{
4644 4644
 		global $maxwidthsmall, $maxheightsmall, $maxwidthmini, $maxheightmini, $quality;
4645 4645
 
4646
-		require_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';		// This define also $maxwidthsmall, $quality, ...
4646
+		require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // This define also $maxwidthsmall, $quality, ...
4647 4647
 
4648
-		$file_osencoded=dol_osencode($file);
4648
+		$file_osencoded = dol_osencode($file);
4649 4649
 		if (file_exists($file_osencoded))
4650 4650
 		{
4651 4651
 			// Create small thumbs for company (Ratio is near 16/9)
@@ -4675,7 +4675,7 @@  discard block
 block discarded – undo
4675 4675
 	 * @param   string              $alternatevalue     Alternate value to use
4676 4676
 	 * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
4677 4677
 	 **/
4678
-	function getDefaultCreateValueFor($fieldname, $alternatevalue=null)
4678
+	function getDefaultCreateValueFor($fieldname, $alternatevalue = null)
4679 4679
 	{
4680 4680
 		global $conf, $_POST;
4681 4681
 
@@ -4684,16 +4684,16 @@  discard block
 block discarded – undo
4684 4684
 
4685 4685
 		if (isset($alternatevalue)) return $alternatevalue;
4686 4686
 
4687
-		$newelement=$this->element;
4688
-		if ($newelement == 'facture') $newelement='invoice';
4689
-		if ($newelement == 'commande') $newelement='order';
4687
+		$newelement = $this->element;
4688
+		if ($newelement == 'facture') $newelement = 'invoice';
4689
+		if ($newelement == 'commande') $newelement = 'order';
4690 4690
 		if (empty($newelement))
4691 4691
 		{
4692 4692
 			dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
4693 4693
 			return '';
4694 4694
 		}
4695 4695
 
4696
-		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4696
+		$keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname);
4697 4697
 		//var_dump($keyforfieldname);
4698 4698
 		if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
4699 4699
 
@@ -4718,21 +4718,21 @@  discard block
 block discarded – undo
4718 4718
 	function call_trigger($trigger_name, $user)
4719 4719
 	{
4720 4720
         // phpcs:enable
4721
-		global $langs,$conf;
4721
+		global $langs, $conf;
4722 4722
 
4723
-		include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
4724
-		$interface=new Interfaces($this->db);
4725
-		$result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
4723
+		include_once DOL_DOCUMENT_ROOT.'/core/class/interfaces.class.php';
4724
+		$interface = new Interfaces($this->db);
4725
+		$result = $interface->run_triggers($trigger_name, $this, $user, $langs, $conf);
4726 4726
 
4727 4727
 		if ($result < 0)
4728 4728
 		{
4729 4729
 			if (!empty($this->errors))
4730 4730
 			{
4731
-				$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.
4731
+				$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.
4732 4732
 			}
4733 4733
 			else
4734 4734
 			{
4735
-				$this->errors=$interface->errors;
4735
+				$this->errors = $interface->errors;
4736 4736
 			}
4737 4737
 		}
4738 4738
 		return $result;
@@ -4751,19 +4751,19 @@  discard block
 block discarded – undo
4751 4751
 	 *  @param  array	$optionsArray   Array resulting of call of extrafields->fetch_name_optionals_label(). Deprecated. Function must be called without parameters.
4752 4752
 	 *  @return	int						<0 if error, 0 if no values of extrafield to find nor found, 1 if an attribute is found and value loaded
4753 4753
 	 */
4754
-	function fetch_optionals($rowid=null, $optionsArray=null)
4754
+	function fetch_optionals($rowid = null, $optionsArray = null)
4755 4755
 	{
4756 4756
         // phpcs:enable
4757
-		if (empty($rowid)) $rowid=$this->id;
4757
+		if (empty($rowid)) $rowid = $this->id;
4758 4758
 
4759 4759
 		// To avoid SQL errors. Probably not the better solution though
4760 4760
 		if (!$this->table_element) {
4761 4761
 			return 0;
4762 4762
 		}
4763 4763
 
4764
-		$this->array_options=array();
4764
+		$this->array_options = array();
4765 4765
 
4766
-		if (! is_array($optionsArray))
4766
+		if (!is_array($optionsArray))
4767 4767
 		{
4768 4768
 			// If $extrafields is not a known object, we initialize it. Best practice is to have $extrafields defined into card.php or list.php page.
4769 4769
 			// TODO Use of existing $extrafield is not yet ready (must mutualize code that use extrafields in form first)
@@ -4779,7 +4779,7 @@  discard block
 block discarded – undo
4779 4779
 			{
4780 4780
 				$extrafields->fetch_name_optionals_label($this->table_element);
4781 4781
 			}
4782
-			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4782
+			$optionsArray = (!empty($extrafields->attributes[$this->table_element]['label']) ? $extrafields->attributes[$this->table_element]['label'] : null);
4783 4783
 		}
4784 4784
 		else
4785 4785
 		{
@@ -4798,18 +4798,18 @@  discard block
 block discarded – undo
4798 4798
 			{
4799 4799
 				if (empty($extrafields->attributes[$this->table_element]['type'][$name]) || $extrafields->attributes[$this->table_element]['type'][$name] != 'separate')
4800 4800
 				{
4801
-					$sql.= ", ".$name;
4801
+					$sql .= ", ".$name;
4802 4802
 				}
4803 4803
 			}
4804
-			$sql.= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4805
-			$sql.= " WHERE fk_object = ".$rowid;
4804
+			$sql .= " FROM ".MAIN_DB_PREFIX.$table_element."_extrafields";
4805
+			$sql .= " WHERE fk_object = ".$rowid;
4806 4806
 
4807 4807
 			//dol_syslog(get_class($this)."::fetch_optionals get extrafields data for ".$this->table_element, LOG_DEBUG);		// Too verbose
4808
-			$resql=$this->db->query($sql);
4808
+			$resql = $this->db->query($sql);
4809 4809
 			if ($resql)
4810 4810
 			{
4811 4811
 				$this->array_options = array();
4812
-				$numrows=$this->db->num_rows($resql);
4812
+				$numrows = $this->db->num_rows($resql);
4813 4813
 				if ($numrows)
4814 4814
 				{
4815 4815
 					$tab = $this->db->fetch_array($resql);
@@ -4817,17 +4817,17 @@  discard block
 block discarded – undo
4817 4817
 					foreach ($tab as $key => $value)
4818 4818
 					{
4819 4819
 						// 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)
4820
-						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && ! is_int($key))
4820
+						if ($key != 'rowid' && $key != 'tms' && $key != 'fk_member' && !is_int($key))
4821 4821
 						{
4822 4822
 							// we can add this attribute to object
4823
-							if (! empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date','datetime')))
4823
+							if (!empty($extrafields) && in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
4824 4824
 							{
4825 4825
 								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4826
-								$this->array_options["options_".$key]=$this->db->jdate($value);
4826
+								$this->array_options["options_".$key] = $this->db->jdate($value);
4827 4827
 							}
4828 4828
 							else
4829 4829
 							{
4830
-								$this->array_options["options_".$key]=$value;
4830
+								$this->array_options["options_".$key] = $value;
4831 4831
 							}
4832 4832
 
4833 4833
 							//var_dump('key '.$key.' '.$value.' type='.$extrafields->attributes[$this->table_element]['type'][$key].' '.$this->array_options["options_".$key]);
@@ -4863,10 +4863,10 @@  discard block
 block discarded – undo
4863 4863
 
4864 4864
 		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4865 4865
 		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
4866
-		$resql=$this->db->query($sql_del);
4867
-		if (! $resql)
4866
+		$resql = $this->db->query($sql_del);
4867
+		if (!$resql)
4868 4868
 		{
4869
-			$this->error=$this->db->lasterror();
4869
+			$this->error = $this->db->lasterror();
4870 4870
 			$this->db->rollback();
4871 4871
 			return -1;
4872 4872
 		}
@@ -4887,36 +4887,36 @@  discard block
 block discarded – undo
4887 4887
 	 *  @return int 						-1=error, O=did nothing, 1=OK
4888 4888
 	 *  @see updateExtraField, setValueFrom
4889 4889
 	 */
4890
-	function insertExtraFields($trigger='', $userused=null)
4890
+	function insertExtraFields($trigger = '', $userused = null)
4891 4891
 	{
4892
-		global $conf,$langs,$user;
4892
+		global $conf, $langs, $user;
4893 4893
 
4894
-		if (empty($userused)) $userused=$user;
4894
+		if (empty($userused)) $userused = $user;
4895 4895
 
4896
-		$error=0;
4896
+		$error = 0;
4897 4897
 
4898
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
4898
+		if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
4899 4899
 
4900
-		if (! empty($this->array_options))
4900
+		if (!empty($this->array_options))
4901 4901
 		{
4902 4902
 			// Check parameters
4903 4903
 			$langs->load('admin');
4904 4904
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
4905 4905
 			$extrafields = new ExtraFields($this->db);
4906
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
4906
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
4907 4907
 
4908 4908
 			//Eliminate copied source object extra_fields that do not exist in target object
4909
-			$new_array_options=array();
4909
+			$new_array_options = array();
4910 4910
 			foreach ($this->array_options as $key => $value) {
4911
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4911
+				if (in_array(substr($key, 8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4912 4912
 					$new_array_options[$key] = $value;
4913 4913
 				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4914 4914
 					$new_array_options['options_'.$key] = $value;
4915 4915
 			}
4916 4916
 
4917
-			foreach($new_array_options as $key => $value)
4917
+			foreach ($new_array_options as $key => $value)
4918 4918
 			{
4919
-			   	$attributeKey      = substr($key,8);   // Remove 'options_' prefix
4919
+			   	$attributeKey      = substr($key, 8); // Remove 'options_' prefix
4920 4920
 			   	$attributeType     = $extrafields->attributes[$this->table_element]['type'][$attributeKey];
4921 4921
 			   	$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$attributeKey];
4922 4922
 			   	$attributeParam    = $extrafields->attributes[$this->table_element]['param'][$attributeKey];
@@ -4924,13 +4924,13 @@  discard block
 block discarded – undo
4924 4924
 
4925 4925
 			   	if ($attributeRequired)
4926 4926
 			   	{
4927
-			   		$mandatorypb=false;
4928
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4929
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
4927
+			   		$mandatorypb = false;
4928
+			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb = true;
4929
+			   		if ($this->array_options[$key] === '') $mandatorypb = true;
4930 4930
 			   		if ($mandatorypb)
4931 4931
 			   		{
4932 4932
 			   			dol_syslog($this->error);
4933
-			   			$this->errors[]=$langs->trans('ErrorFieldRequired', $attributeLabel);
4933
+			   			$this->errors[] = $langs->trans('ErrorFieldRequired', $attributeLabel);
4934 4934
 			   			return -1;
4935 4935
 			   		}
4936 4936
 			   	}
@@ -4941,25 +4941,25 @@  discard block
 block discarded – undo
4941 4941
 			   	switch ($attributeType)
4942 4942
 			   	{
4943 4943
 			   		case 'int':
4944
-			  			if (!is_numeric($value) && $value!='')
4944
+			  			if (!is_numeric($value) && $value != '')
4945 4945
 			   			{
4946
-			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4946
+			   				$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4947 4947
 			   				return -1;
4948 4948
 			  			}
4949
-			   			elseif ($value=='')
4949
+			   			elseif ($value == '')
4950 4950
 			   			{
4951 4951
 			   				$new_array_options[$key] = null;
4952 4952
 			   			}
4953 4953
 			 			break;
4954 4954
 					case 'double':
4955 4955
 						$value = price2num($value);
4956
-						if (!is_numeric($value) && $value!='')
4956
+						if (!is_numeric($value) && $value != '')
4957 4957
 						{
4958 4958
 							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4959
-							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4959
+							$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4960 4960
 							return -1;
4961 4961
 						}
4962
-						elseif ($value=='')
4962
+						elseif ($value == '')
4963 4963
 						{
4964 4964
 							$new_array_options[$key] = null;
4965 4965
 						}
@@ -4973,12 +4973,12 @@  discard block
 block discarded – undo
4973 4973
              			}
4974 4974
              			break;*/
4975 4975
 			   		case 'password':
4976
-			   			$algo='';
4976
+			   			$algo = '';
4977 4977
 			   			if ($this->array_options[$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']))
4978 4978
 			   			{
4979 4979
 			   				// If there is an encryption choice, we use it to crypt data before insert
4980 4980
 			   				$tmparrays = array_keys($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options']);
4981
-			   				$algo=reset($tmparrays);
4981
+			   				$algo = reset($tmparrays);
4982 4982
 			   				if ($algo != '')
4983 4983
 			   				{
4984 4984
 			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
@@ -4989,7 +4989,7 @@  discard block
 block discarded – undo
4989 4989
 			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
4990 4990
 				   					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.
4991 4991
 				   					{
4992
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
4992
+				   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
4993 4993
 				   					}
4994 4994
 									else
4995 4995
 									{
@@ -5000,7 +5000,7 @@  discard block
 block discarded – undo
5000 5000
 			   					}
5001 5001
 			   					else
5002 5002
 			   					{
5003
-			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5003
+			   						$new_array_options[$key] = $this->array_options[$key]; // Value is kept
5004 5004
 			   					}
5005 5005
 			   				}
5006 5006
 			   			}
@@ -5017,13 +5017,13 @@  discard block
 block discarded – undo
5017 5017
 						break;
5018 5018
 					case 'datetime':
5019 5019
 						// If data is a string instead of a timestamp, we convert it
5020
-						if (! is_int($this->array_options[$key])) {
5020
+						if (!is_int($this->array_options[$key])) {
5021 5021
 							$this->array_options[$key] = strtotime($this->array_options[$key]);
5022 5022
 						}
5023 5023
 						$new_array_options[$key] = $this->db->idate($this->array_options[$key]);
5024 5024
 						break;
5025 5025
 		   			case 'link':
5026
-						$param_list=array_keys($attributeParam['options']);
5026
+						$param_list = array_keys($attributeParam['options']);
5027 5027
 						// 0 : ObjectName
5028 5028
 						// 1 : classPath
5029 5029
 						$InfoFieldList = explode(":", $param_list[0]);
@@ -5032,18 +5032,18 @@  discard block
 block discarded – undo
5032 5032
 						{
5033 5033
 							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5034 5034
 							{
5035
-								$new_array_options[$key]='';
5035
+								$new_array_options[$key] = '';
5036 5036
 							}
5037 5037
 							elseif ($value)
5038 5038
 							{
5039 5039
 								$object = new $InfoFieldList[0]($this->db);
5040
-								if (is_numeric($value)) $res=$object->fetch($value);
5041
-								else $res=$object->fetch('',$value);
5040
+								if (is_numeric($value)) $res = $object->fetch($value);
5041
+								else $res = $object->fetch('', $value);
5042 5042
 
5043
-								if ($res > 0) $new_array_options[$key]=$object->id;
5043
+								if ($res > 0) $new_array_options[$key] = $object->id;
5044 5044
 								else
5045 5045
 								{
5046
-									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5046
+									$this->error = "Id/Ref '".$value."' for object '".$object->element."' not found";
5047 5047
 									$this->db->rollback();
5048 5048
 									return -1;
5049 5049
 								}
@@ -5067,46 +5067,46 @@  discard block
 block discarded – undo
5067 5067
 			$this->db->query($sql_del);
5068 5068
 
5069 5069
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX.$table_element."_extrafields (fk_object";
5070
-			foreach($new_array_options as $key => $value)
5070
+			foreach ($new_array_options as $key => $value)
5071 5071
 			{
5072
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5072
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5073 5073
 				// Add field of attribut
5074 5074
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5075
-					$sql.=",".$attributeKey;
5075
+					$sql .= ",".$attributeKey;
5076 5076
 			}
5077 5077
 			$sql .= ") VALUES (".$this->id;
5078 5078
 
5079
-			foreach($new_array_options as $key => $value)
5079
+			foreach ($new_array_options as $key => $value)
5080 5080
 			{
5081
-				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5081
+				$attributeKey = substr($key, 8); // Remove 'options_' prefix
5082 5082
 				// Add field of attribute
5083 5083
 				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5084 5084
 				{
5085 5085
 					if ($new_array_options[$key] != '')
5086 5086
 					{
5087
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5087
+						$sql .= ",'".$this->db->escape($new_array_options[$key])."'";
5088 5088
 					}
5089 5089
 					else
5090 5090
 					{
5091
-						$sql.=",null";
5091
+						$sql .= ",null";
5092 5092
 					}
5093 5093
 				}
5094 5094
 			}
5095
-			$sql.=")";
5095
+			$sql .= ")";
5096 5096
 
5097 5097
 			dol_syslog(get_class($this)."::insertExtraFields insert", LOG_DEBUG);
5098 5098
 			$resql = $this->db->query($sql);
5099
-			if (! $resql)
5099
+			if (!$resql)
5100 5100
 			{
5101
-				$this->error=$this->db->lasterror();
5101
+				$this->error = $this->db->lasterror();
5102 5102
 				$error++;
5103 5103
 			}
5104 5104
 
5105
-			if (! $error && $trigger)
5105
+			if (!$error && $trigger)
5106 5106
 			{
5107 5107
 				// Call trigger
5108
-				$this->context=array('extrafieldaddupdate'=>1);
5109
-				$result=$this->call_trigger($trigger, $userused);
5108
+				$this->context = array('extrafieldaddupdate'=>1);
5109
+				$result = $this->call_trigger($trigger, $userused);
5110 5110
 				if ($result < 0) $error++;
5111 5111
 				// End call trigger
5112 5112
 			}
@@ -5135,25 +5135,25 @@  discard block
 block discarded – undo
5135 5135
 	 *  @return int                 		-1=error, O=did nothing, 1=OK
5136 5136
 	 *  @see setValueFrom, insertExtraFields
5137 5137
 	 */
5138
-	function updateExtraField($key, $trigger=null, $userused=null)
5138
+	function updateExtraField($key, $trigger = null, $userused = null)
5139 5139
 	{
5140
-		global $conf,$langs,$user;
5140
+		global $conf, $langs, $user;
5141 5141
 
5142
-		if (empty($userused)) $userused=$user;
5142
+		if (empty($userused)) $userused = $user;
5143 5143
 
5144
-		$error=0;
5144
+		$error = 0;
5145 5145
 
5146
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
5146
+		if (!empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0; // For avoid conflicts if trigger used
5147 5147
 
5148
-		if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5148
+		if (!empty($this->array_options) && isset($this->array_options["options_".$key]))
5149 5149
 		{
5150 5150
 			// Check parameters
5151 5151
 			$langs->load('admin');
5152 5152
 			require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
5153 5153
 			$extrafields = new ExtraFields($this->db);
5154
-			$target_extrafields=$extrafields->fetch_name_optionals_label($this->table_element);
5154
+			$target_extrafields = $extrafields->fetch_name_optionals_label($this->table_element);
5155 5155
 
5156
-			$value=$this->array_options["options_".$key];
5156
+			$value = $this->array_options["options_".$key];
5157 5157
 
5158 5158
 			$attributeType     = $extrafields->attributes[$this->table_element]['type'][$key];
5159 5159
 			$attributeLabel    = $extrafields->attributes[$this->table_element]['label'][$key];
@@ -5166,25 +5166,25 @@  discard block
 block discarded – undo
5166 5166
 			switch ($attributeType)
5167 5167
 			{
5168 5168
 				case 'int':
5169
-					if (!is_numeric($value) && $value!='')
5169
+					if (!is_numeric($value) && $value != '')
5170 5170
 					{
5171
-						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5171
+						$this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5172 5172
 						return -1;
5173 5173
 					}
5174
-					elseif ($value=='')
5174
+					elseif ($value == '')
5175 5175
 					{
5176 5176
 						$this->array_options["options_".$key] = null;
5177 5177
 					}
5178 5178
 					break;
5179 5179
 				case 'double':
5180 5180
 					$value = price2num($value);
5181
-					if (!is_numeric($value) && $value!='')
5181
+					if (!is_numeric($value) && $value != '')
5182 5182
 					{
5183 5183
 						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
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
 					}
@@ -5201,13 +5201,13 @@  discard block
 block discarded – undo
5201 5201
 					$this->array_options["options_".$key] = price2num($this->array_options["options_".$key]);
5202 5202
 					break;
5203 5203
 				case 'date':
5204
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5204
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5205 5205
 					break;
5206 5206
 				case 'datetime':
5207
-					$this->array_options["options_".$key]=$this->db->idate($this->array_options["options_".$key]);
5207
+					$this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]);
5208 5208
 					break;
5209 5209
 				case 'link':
5210
-					$param_list=array_keys($attributeParam['options']);
5210
+					$param_list = array_keys($attributeParam['options']);
5211 5211
 					// 0 : ObjectName
5212 5212
 					// 1 : classPath
5213 5213
 					$InfoFieldList = explode(":", $param_list[0]);
@@ -5215,8 +5215,8 @@  discard block
 block discarded – undo
5215 5215
 					if ($value)
5216 5216
 					{
5217 5217
 						$object = new $InfoFieldList[0]($this->db);
5218
-						$object->fetch(0,$value);
5219
-						$this->array_options["options_".$key]=$object->id;
5218
+						$object->fetch(0, $value);
5219
+						$this->array_options["options_".$key] = $object->id;
5220 5220
 					}
5221 5221
 					break;
5222 5222
 			}
@@ -5225,24 +5225,24 @@  discard block
 block discarded – undo
5225 5225
 			$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
5226 5226
 			$sql .= " WHERE fk_object = ".$this->id;
5227 5227
 			$resql = $this->db->query($sql);
5228
-			if (! $resql)
5228
+			if (!$resql)
5229 5229
 			{
5230 5230
 				$error++;
5231
-				$this->error=$this->db->lasterror();
5231
+				$this->error = $this->db->lasterror();
5232 5232
 			}
5233 5233
 
5234
-			if (! $error && $trigger)
5234
+			if (!$error && $trigger)
5235 5235
 			{
5236 5236
 				// Call trigger
5237
-				$this->context=array('extrafieldupdate'=>1);
5238
-				$result=$this->call_trigger($trigger, $userused);
5237
+				$this->context = array('extrafieldupdate'=>1);
5238
+				$result = $this->call_trigger($trigger, $userused);
5239 5239
 				if ($result < 0) $error++;
5240 5240
 				// End call trigger
5241 5241
 			}
5242 5242
 
5243 5243
 			if ($error)
5244 5244
 			{
5245
-				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5245
+				dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
5246 5246
 				$this->db->rollback();
5247 5247
 				return -1;
5248 5248
 			}
@@ -5269,71 +5269,71 @@  discard block
 block discarded – undo
5269 5269
 	 * @param  string|int		$morecss       Value for css to define style/length of field. May also be a numeric.
5270 5270
 	 * @return string
5271 5271
 	 */
5272
-	function showInputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $morecss=0)
5272
+	function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0)
5273 5273
 	{
5274
-		global $conf,$langs,$form;
5274
+		global $conf, $langs, $form;
5275 5275
 
5276
-		if (! is_object($form))
5276
+		if (!is_object($form))
5277 5277
 		{
5278 5278
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5279
-			$form=new Form($this->db);
5279
+			$form = new Form($this->db);
5280 5280
 		}
5281 5281
 
5282
-		$val=$this->fields[$key];
5282
+		$val = $this->fields[$key];
5283 5283
 
5284
-		$out='';
5285
-        $type='';
5284
+		$out = '';
5285
+        $type = '';
5286 5286
         $param = array();
5287
-        $param['options']=array();
5288
-        $size =$this->fields[$key]['size'];
5287
+        $param['options'] = array();
5288
+        $size = $this->fields[$key]['size'];
5289 5289
         // Because we work on extrafields
5290
-        if(preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)){
5291
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5292
-            $type ='link';
5293
-        } elseif(preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5294
-            $param['options']=array($reg[1].':'.$reg[2]=>'N');
5295
-            $type ='link';
5296
-        } elseif(preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5297
-            $param['options']=array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5298
-            $type ='sellist';
5299
-        } elseif(preg_match('/varchar\((\d+)\)/', $val['type'],$reg)) {
5300
-            $param['options']=array();
5301
-            $type ='varchar';
5302
-            $size=$reg[1];
5303
-        } elseif(preg_match('/varchar/', $val['type'])) {
5304
-            $param['options']=array();
5305
-            $type ='varchar';
5306
-        } elseif(is_array($this->fields[$key]['arrayofkeyval'])) {
5307
-            $param['options']=$this->fields[$key]['arrayofkeyval'];
5308
-            $type ='select';
5290
+        if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
5291
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5292
+            $type = 'link';
5293
+        } elseif (preg_match('/^link:(.*):(.*)/i', $val['type'], $reg)) {
5294
+            $param['options'] = array($reg[1].':'.$reg[2]=>'N');
5295
+            $type = 'link';
5296
+        } elseif (preg_match('/^sellist:(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
5297
+            $param['options'] = array($reg[1].':'.$reg[2].':'.$reg[3].':'.$reg[4]=>'N');
5298
+            $type = 'sellist';
5299
+        } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
5300
+            $param['options'] = array();
5301
+            $type = 'varchar';
5302
+            $size = $reg[1];
5303
+        } elseif (preg_match('/varchar/', $val['type'])) {
5304
+            $param['options'] = array();
5305
+            $type = 'varchar';
5306
+        } elseif (is_array($this->fields[$key]['arrayofkeyval'])) {
5307
+            $param['options'] = $this->fields[$key]['arrayofkeyval'];
5308
+            $type = 'select';
5309 5309
         } else {
5310
-            $param['options']=array();
5311
-            $type =$this->fields[$key]['type'];
5310
+            $param['options'] = array();
5311
+            $type = $this->fields[$key]['type'];
5312 5312
         }
5313 5313
 
5314
-		$label=$this->fields[$key]['label'];
5314
+		$label = $this->fields[$key]['label'];
5315 5315
 		//$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
5316
-		$default=$this->fields[$key]['default'];
5317
-		$computed=$this->fields[$key]['computed'];
5318
-		$unique=$this->fields[$key]['unique'];
5319
-		$required=$this->fields[$key]['required'];
5316
+		$default = $this->fields[$key]['default'];
5317
+		$computed = $this->fields[$key]['computed'];
5318
+		$unique = $this->fields[$key]['unique'];
5319
+		$required = $this->fields[$key]['required'];
5320 5320
 
5321
-		$langfile=$this->fields[$key]['langfile'];
5322
-		$list=$this->fields[$key]['list'];
5323
-		$hidden=abs($this->fields[$key]['visible'])!=1?1:0;
5321
+		$langfile = $this->fields[$key]['langfile'];
5322
+		$list = $this->fields[$key]['list'];
5323
+		$hidden = abs($this->fields[$key]['visible']) != 1 ? 1 : 0;
5324 5324
 
5325 5325
 		$objectid = $this->id;
5326 5326
 
5327 5327
 
5328 5328
 		if ($computed)
5329 5329
 		{
5330
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5330
+			if (!preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5331 5331
 			else return '';
5332 5332
 		}
5333 5333
 
5334 5334
 
5335 5335
 		// Use in priority showsize from parameters, then $val['css'] then autodefine
5336
-		if (empty($morecss) && ! empty($val['css']))
5336
+		if (empty($morecss) && !empty($val['css']))
5337 5337
 		{
5338 5338
 			$showsize = $val['css'];
5339 5339
 		}
@@ -5347,16 +5347,16 @@  discard block
 block discarded – undo
5347 5347
 			{
5348 5348
 				$morecss = 'minwidth200imp';
5349 5349
 			}
5350
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5350
+			elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5351 5351
 			{
5352 5352
 				$morecss = 'maxwidth75';
5353 5353
                         }elseif ($type == 'url')
5354 5354
 			{
5355
-				$morecss='minwidth400';
5355
+				$morecss = 'minwidth400';
5356 5356
 			}
5357 5357
 			elseif ($type == 'boolean')
5358 5358
 			{
5359
-				$morecss='';
5359
+				$morecss = '';
5360 5360
 			}
5361 5361
 			else
5362 5362
 			{
@@ -5375,12 +5375,12 @@  discard block
 block discarded – undo
5375 5375
 			}
5376 5376
 		}
5377 5377
 
5378
-		if (in_array($type,array('date','datetime')))
5378
+		if (in_array($type, array('date', 'datetime')))
5379 5379
 		{
5380
-			$tmp=explode(',',$size);
5381
-			$newsize=$tmp[0];
5380
+			$tmp = explode(',', $size);
5381
+			$newsize = $tmp[0];
5382 5382
 
5383
-			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5383
+			$showtime = in_array($type, array('datetime')) ? 1 : 0;
5384 5384
 
5385 5385
 			// Do not show current date when field not required (see selectDate() method)
5386 5386
 			if (!$required && $value == '') $value = '-1';
@@ -5388,237 +5388,237 @@  discard block
 block discarded – undo
5388 5388
 			// TODO Must also support $moreparam
5389 5389
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5390 5390
 		}
5391
-		elseif (in_array($type,array('int','integer')))
5391
+		elseif (in_array($type, array('int', 'integer')))
5392 5392
 		{
5393
-			$tmp=explode(',',$size);
5394
-			$newsize=$tmp[0];
5395
-			$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:'').'>';
5393
+			$tmp = explode(',', $size);
5394
+			$newsize = $tmp[0];
5395
+			$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 : '').'>';
5396 5396
 		}
5397 5397
 		elseif (preg_match('/varchar/', $type))
5398 5398
 		{
5399
-			$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:'').'>';
5399
+			$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 : '').'>';
5400 5400
 		}
5401 5401
 		elseif (in_array($type, array('mail', 'phone', 'url')))
5402 5402
 		{
5403
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5403
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5404 5404
 		}
5405 5405
 		elseif ($type == 'text')
5406 5406
 		{
5407
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5407
+			if (!preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5408 5408
 			{
5409 5409
 				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5410
-				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5411
-				$out=$doleditor->Create(1);
5410
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
5411
+				$out = $doleditor->Create(1);
5412 5412
 			}
5413 5413
 			else
5414 5414
 			{
5415
-				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5415
+				$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam ? $moreparam : '').'>';
5416 5416
 			}
5417 5417
 		}
5418 5418
 		elseif ($type == 'html')
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,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
5424
-				$out=$doleditor->Create(1);
5423
+				$doleditor = new DolEditor($keyprefix.$key.$keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
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 == 'boolean')
5432 5432
 		{
5433
-			$checked='';
5433
+			$checked = '';
5434 5434
 			if (!empty($value)) {
5435
-				$checked=' checked value="1" ';
5435
+				$checked = ' checked value="1" ';
5436 5436
 			} else {
5437
-				$checked=' value="1" ';
5437
+				$checked = ' value="1" ';
5438 5438
 			}
5439
-			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5439
+			$out = '<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam ? $moreparam : '').'>';
5440 5440
 		}
5441 5441
 		elseif ($type == 'price')
5442 5442
 		{
5443 5443
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5444
-				$value=price($value);
5444
+				$value = price($value);
5445 5445
 			}
5446
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
5446
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> '.$langs->getCurrencySymbol($conf->currency);
5447 5447
 		}
5448
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5448
+		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type))
5449 5449
 		{
5450 5450
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5451
-				$value=price($value);
5451
+				$value = price($value);
5452 5452
 			}
5453
-			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5453
+			$out = '<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'> ';
5454 5454
 		}
5455 5455
 		elseif ($type == 'select')
5456 5456
 		{
5457 5457
 			$out = '';
5458
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5458
+			if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5459 5459
 			{
5460
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5461
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5460
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5461
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5462 5462
 			}
5463 5463
 
5464
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5465
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5464
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5465
+                if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1))$out .= '<option value="0">&nbsp;</option>';
5466 5466
 			foreach ($param['options'] as $key => $val)
5467 5467
 			{
5468 5468
 				if ((string) $key == '') continue;
5469 5469
 				list($val, $parent) = explode('|', $val);
5470
-				$out.='<option value="'.$key.'"';
5471
-				$out.= (((string) $value == (string) $key)?' selected':'');
5472
-				$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5473
-				$out.='>'.$val.'</option>';
5470
+				$out .= '<option value="'.$key.'"';
5471
+				$out .= (((string) $value == (string) $key) ? ' selected' : '');
5472
+				$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5473
+				$out .= '>'.$val.'</option>';
5474 5474
 			}
5475
-			$out.='</select>';
5475
+			$out .= '</select>';
5476 5476
 		}
5477 5477
 		elseif ($type == 'sellist')
5478 5478
 		{
5479 5479
 			$out = '';
5480
-			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5480
+			if (!empty($conf->use_javascript_ajax) && !empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
5481 5481
 			{
5482
-				include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
5483
-				$out.= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5482
+				include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
5483
+				$out .= ajax_combobox($keyprefix.$key.$keysuffix, array(), 0);
5484 5484
 			}
5485 5485
 
5486
-			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5486
+			$out .= '<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '').'>';
5487 5487
 			if (is_array($param['options']))
5488 5488
 			{
5489
-				$param_list=array_keys($param['options']);
5489
+				$param_list = array_keys($param['options']);
5490 5490
 				$InfoFieldList = explode(":", $param_list[0]);
5491
-				$parentName='';
5492
-				$parentField='';
5491
+				$parentName = '';
5492
+				$parentField = '';
5493 5493
 				// 0 : tableName
5494 5494
 				// 1 : label field name
5495 5495
 				// 2 : key fields name (if differ of rowid)
5496 5496
 				// 3 : key field parent (for dependent lists)
5497 5497
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5498
-				$keyList=(empty($InfoFieldList[2])?'rowid':$InfoFieldList[2].' as rowid');
5498
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5499 5499
 
5500 5500
 
5501
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4]))
5501
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4]))
5502 5502
 				{
5503 5503
 					if (strpos($InfoFieldList[4], 'extra.') !== false)
5504 5504
 					{
5505
-						$keyList='main.'.$InfoFieldList[2].' as rowid';
5505
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5506 5506
 					} else {
5507
-						$keyList=$InfoFieldList[2].' as rowid';
5507
+						$keyList = $InfoFieldList[2].' as rowid';
5508 5508
 					}
5509 5509
 				}
5510
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3]))
5510
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3]))
5511 5511
 				{
5512 5512
 					list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5513
-					$keyList.= ', '.$parentField;
5513
+					$keyList .= ', '.$parentField;
5514 5514
 				}
5515 5515
 
5516
-				$fields_label = explode('|',$InfoFieldList[1]);
5516
+				$fields_label = explode('|', $InfoFieldList[1]);
5517 5517
 				if (is_array($fields_label))
5518 5518
 				{
5519
-					$keyList .=', ';
5519
+					$keyList .= ', ';
5520 5520
 					$keyList .= implode(', ', $fields_label);
5521 5521
 				}
5522 5522
 
5523
-				$sqlwhere='';
5523
+				$sqlwhere = '';
5524 5524
 				$sql = 'SELECT '.$keyList;
5525
-				$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
5525
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5526 5526
 				if (!empty($InfoFieldList[4]))
5527 5527
 				{
5528 5528
 					// can use SELECT request
5529
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5530
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5529
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5530
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5531 5531
 					}
5532 5532
 
5533 5533
 					// current object id can be use into filter
5534
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5535
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5534
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5535
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5536 5536
 					} else {
5537
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5537
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5538 5538
 					}
5539 5539
 					//We have to join on extrafield table
5540
-					if (strpos($InfoFieldList[4], 'extra')!==false)
5540
+					if (strpos($InfoFieldList[4], 'extra') !== false)
5541 5541
 					{
5542
-						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5543
-						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5542
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5543
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5544 5544
 					}
5545 5545
 					else
5546 5546
 					{
5547
-						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5547
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5548 5548
 					}
5549 5549
 				}
5550 5550
 				else
5551 5551
 				{
5552
-					$sqlwhere.= ' WHERE 1=1';
5552
+					$sqlwhere .= ' WHERE 1=1';
5553 5553
 				}
5554 5554
 				// Some tables may have field, some other not. For the moment we disable it.
5555
-				if (in_array($InfoFieldList[0],array('tablewithentity')))
5555
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5556 5556
 				{
5557
-					$sqlwhere.= ' AND entity = '.$conf->entity;
5557
+					$sqlwhere .= ' AND entity = '.$conf->entity;
5558 5558
 				}
5559
-				$sql.=$sqlwhere;
5559
+				$sql .= $sqlwhere;
5560 5560
 				//print $sql;
5561 5561
 
5562
-				$sql .= ' ORDER BY ' . implode(', ', $fields_label);
5562
+				$sql .= ' ORDER BY '.implode(', ', $fields_label);
5563 5563
 
5564 5564
 				dol_syslog(get_class($this).'::showInputField type=sellist', LOG_DEBUG);
5565 5565
 				$resql = $this->db->query($sql);
5566 5566
 				if ($resql)
5567 5567
 				{
5568
-					$out.='<option value="0">&nbsp;</option>';
5568
+					$out .= '<option value="0">&nbsp;</option>';
5569 5569
 					$num = $this->db->num_rows($resql);
5570 5570
 					$i = 0;
5571 5571
 					while ($i < $num)
5572 5572
 					{
5573
-						$labeltoshow='';
5573
+						$labeltoshow = '';
5574 5574
 						$obj = $this->db->fetch_object($resql);
5575 5575
 
5576 5576
 						// Several field into label (eq table:code|libelle:rowid)
5577 5577
 						$notrans = false;
5578
-						$fields_label = explode('|',$InfoFieldList[1]);
5578
+						$fields_label = explode('|', $InfoFieldList[1]);
5579 5579
 						if (is_array($fields_label))
5580 5580
 						{
5581 5581
 							$notrans = true;
5582 5582
 							foreach ($fields_label as $field_toshow)
5583 5583
 							{
5584
-								$labeltoshow.= $obj->$field_toshow.' ';
5584
+								$labeltoshow .= $obj->$field_toshow.' ';
5585 5585
 							}
5586 5586
 						}
5587 5587
 						else
5588 5588
 						{
5589
-							$labeltoshow=$obj->{$InfoFieldList[1]};
5589
+							$labeltoshow = $obj->{$InfoFieldList[1]};
5590 5590
 						}
5591
-						$labeltoshow=dol_trunc($labeltoshow,45);
5591
+						$labeltoshow = dol_trunc($labeltoshow, 45);
5592 5592
 
5593 5593
 						if ($value == $obj->rowid)
5594 5594
 						{
5595 5595
 							foreach ($fields_label as $field_toshow)
5596 5596
 							{
5597
-								$translabel=$langs->trans($obj->$field_toshow);
5598
-								if ($translabel!=$obj->$field_toshow) {
5599
-									$labeltoshow=dol_trunc($translabel,18).' ';
5600
-								}else {
5601
-									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5597
+								$translabel = $langs->trans($obj->$field_toshow);
5598
+								if ($translabel != $obj->$field_toshow) {
5599
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5600
+								} else {
5601
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5602 5602
 								}
5603 5603
 							}
5604
-							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5604
+							$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5605 5605
 						}
5606 5606
 						else
5607 5607
 						{
5608
-							if (! $notrans)
5608
+							if (!$notrans)
5609 5609
 							{
5610
-								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5611
-								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5612
-									$labeltoshow=dol_trunc($translabel,18);
5610
+								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5611
+								if ($translabel != $obj->{$InfoFieldList[1]}) {
5612
+									$labeltoshow = dol_trunc($translabel, 18);
5613 5613
 								}
5614 5614
 								else {
5615
-									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5615
+									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]},18);
5616 5616
 								}
5617 5617
 							}
5618
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
5619
-							if ($value==$obj->rowid)
5618
+							if (empty($labeltoshow)) $labeltoshow = '(not defined)';
5619
+							if ($value == $obj->rowid)
5620 5620
 							{
5621
-								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5621
+								$out .= '<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5622 5622
 							}
5623 5623
 
5624 5624
 							if (!empty($InfoFieldList[3]) && $parentField)
@@ -5626,10 +5626,10 @@  discard block
 block discarded – undo
5626 5626
 								$parent = $parentName.':'.$obj->{$parentField};
5627 5627
 							}
5628 5628
 
5629
-							$out.='<option value="'.$obj->rowid.'"';
5630
-							$out.= ($value==$obj->rowid?' selected':'');
5631
-							$out.= (!empty($parent)?' parent="'.$parent.'"':'');
5632
-							$out.='>'.$labeltoshow.'</option>';
5629
+							$out .= '<option value="'.$obj->rowid.'"';
5630
+							$out .= ($value == $obj->rowid ? ' selected' : '');
5631
+							$out .= (!empty($parent) ? ' parent="'.$parent.'"' : '');
5632
+							$out .= '>'.$labeltoshow.'</option>';
5633 5633
 						}
5634 5634
 
5635 5635
 						$i++;
@@ -5640,23 +5640,23 @@  discard block
 block discarded – undo
5640 5640
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5641 5641
 				}
5642 5642
 			}
5643
-			$out.='</select>';
5643
+			$out .= '</select>';
5644 5644
 		}
5645 5645
 		elseif ($type == 'checkbox')
5646 5646
 		{
5647
-			$value_arr=explode(',',$value);
5648
-			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5647
+			$value_arr = explode(',', $value);
5648
+			$out = $form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options']) ?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5649 5649
 		}
5650 5650
 		elseif ($type == 'radio')
5651 5651
 		{
5652
-			$out='';
5652
+			$out = '';
5653 5653
 			foreach ($param['options'] as $keyopt => $val)
5654 5654
 			{
5655
-				$out.='<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'');
5656
-				$out.=' value="'.$keyopt.'"';
5657
-				$out.=' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5658
-				$out.= ($value==$keyopt?'checked':'');
5659
-				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5655
+				$out .= '<input class="flat '.$morecss.'" type="radio" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam ? $moreparam : '');
5656
+				$out .= ' value="'.$keyopt.'"';
5657
+				$out .= ' id="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'"';
5658
+				$out .= ($value == $keyopt ? 'checked' : '');
5659
+				$out .= '/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5660 5660
 			}
5661 5661
 		}
5662 5662
 		elseif ($type == 'chkbxlst')
@@ -5671,24 +5671,24 @@  discard block
 block discarded – undo
5671 5671
 			if (is_array($param['options'])) {
5672 5672
 				$param_list = array_keys($param['options']);
5673 5673
 				$InfoFieldList = explode(":", $param_list[0]);
5674
-				$parentName='';
5675
-				$parentField='';
5674
+				$parentName = '';
5675
+				$parentField = '';
5676 5676
 				// 0 : tableName
5677 5677
 				// 1 : label field name
5678 5678
 				// 2 : key fields name (if differ of rowid)
5679 5679
 				// 3 : key field parent (for dependent lists)
5680 5680
 				// 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
5681
-				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');
5681
+				$keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2].' as rowid');
5682 5682
 
5683
-				if (count($InfoFieldList) > 3 && ! empty($InfoFieldList[3])) {
5684
-					list ( $parentName, $parentField ) = explode('|', $InfoFieldList[3]);
5685
-					$keyList .= ', ' . $parentField;
5683
+				if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
5684
+					list ($parentName, $parentField) = explode('|', $InfoFieldList[3]);
5685
+					$keyList .= ', '.$parentField;
5686 5686
 				}
5687
-				if (count($InfoFieldList) > 4 && ! empty($InfoFieldList[4])) {
5687
+				if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
5688 5688
 					if (strpos($InfoFieldList[4], 'extra.') !== false) {
5689
-						$keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
5689
+						$keyList = 'main.'.$InfoFieldList[2].' as rowid';
5690 5690
 					} else {
5691
-						$keyList = $InfoFieldList[2] . ' as rowid';
5691
+						$keyList = $InfoFieldList[2].' as rowid';
5692 5692
 					}
5693 5693
 				}
5694 5694
 
@@ -5699,50 +5699,50 @@  discard block
 block discarded – undo
5699 5699
 				}
5700 5700
 
5701 5701
 				$sqlwhere = '';
5702
-				$sql = 'SELECT ' . $keyList;
5703
-				$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
5704
-				if (! empty($InfoFieldList[4])) {
5702
+				$sql = 'SELECT '.$keyList;
5703
+				$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
5704
+				if (!empty($InfoFieldList[4])) {
5705 5705
 
5706 5706
 					// can use SELECT request
5707
-					if (strpos($InfoFieldList[4], '$SEL$')!==false) {
5708
-						$InfoFieldList[4]=str_replace('$SEL$','SELECT',$InfoFieldList[4]);
5707
+					if (strpos($InfoFieldList[4], '$SEL$') !== false) {
5708
+						$InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
5709 5709
 					}
5710 5710
 
5711 5711
 					// current object id can be use into filter
5712
-					if (strpos($InfoFieldList[4], '$ID$')!==false && !empty($objectid)) {
5713
-						$InfoFieldList[4]=str_replace('$ID$',$objectid,$InfoFieldList[4]);
5712
+					if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
5713
+						$InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
5714 5714
 					} else {
5715
-						$InfoFieldList[4]=str_replace('$ID$','0',$InfoFieldList[4]);
5715
+						$InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
5716 5716
 					}
5717 5717
 
5718 5718
 					// We have to join on extrafield table
5719 5719
 					if (strpos($InfoFieldList[4], 'extra') !== false) {
5720
-						$sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
5721
-						$sqlwhere .= ' WHERE extra.fk_object=main.' . $InfoFieldList[2] . ' AND ' . $InfoFieldList[4];
5720
+						$sql .= ' as main, '.MAIN_DB_PREFIX.$InfoFieldList[0].'_extrafields as extra';
5721
+						$sqlwhere .= ' WHERE extra.fk_object=main.'.$InfoFieldList[2].' AND '.$InfoFieldList[4];
5722 5722
 					} else {
5723
-						$sqlwhere .= ' WHERE ' . $InfoFieldList[4];
5723
+						$sqlwhere .= ' WHERE '.$InfoFieldList[4];
5724 5724
 					}
5725 5725
 				} else {
5726 5726
 					$sqlwhere .= ' WHERE 1=1';
5727 5727
 				}
5728 5728
 				// Some tables may have field, some other not. For the moment we disable it.
5729
-				if (in_array($InfoFieldList[0], array ('tablewithentity')))
5729
+				if (in_array($InfoFieldList[0], array('tablewithentity')))
5730 5730
 				{
5731
-					$sqlwhere .= ' AND entity = ' . $conf->entity;
5731
+					$sqlwhere .= ' AND entity = '.$conf->entity;
5732 5732
 				}
5733 5733
 				// $sql.=preg_replace('/^ AND /','',$sqlwhere);
5734 5734
 				// print $sql;
5735 5735
 
5736 5736
 				$sql .= $sqlwhere;
5737
-				dol_syslog(get_class($this) . '::showInputField type=chkbxlst',LOG_DEBUG);
5737
+				dol_syslog(get_class($this).'::showInputField type=chkbxlst', LOG_DEBUG);
5738 5738
 				$resql = $this->db->query($sql);
5739 5739
 				if ($resql) {
5740 5740
 					$num = $this->db->num_rows($resql);
5741 5741
 					$i = 0;
5742 5742
 
5743
-					$data=array();
5743
+					$data = array();
5744 5744
 
5745
-					while ( $i < $num ) {
5745
+					while ($i < $num) {
5746 5746
 						$labeltoshow = '';
5747 5747
 						$obj = $this->db->fetch_object($resql);
5748 5748
 
@@ -5751,8 +5751,8 @@  discard block
 block discarded – undo
5751 5751
 						$fields_label = explode('|', $InfoFieldList[1]);
5752 5752
 						if (is_array($fields_label)) {
5753 5753
 							$notrans = true;
5754
-							foreach ( $fields_label as $field_toshow ) {
5755
-								$labeltoshow .= $obj->$field_toshow . ' ';
5754
+							foreach ($fields_label as $field_toshow) {
5755
+								$labeltoshow .= $obj->$field_toshow.' ';
5756 5756
 							}
5757 5757
 						} else {
5758 5758
 							$labeltoshow = $obj->{$InfoFieldList[1]};
@@ -5760,18 +5760,18 @@  discard block
 block discarded – undo
5760 5760
 						$labeltoshow = dol_trunc($labeltoshow, 45);
5761 5761
 
5762 5762
 						if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5763
-							foreach ( $fields_label as $field_toshow ) {
5763
+							foreach ($fields_label as $field_toshow) {
5764 5764
 								$translabel = $langs->trans($obj->$field_toshow);
5765 5765
 								if ($translabel != $obj->$field_toshow) {
5766
-									$labeltoshow = dol_trunc($translabel, 18) . ' ';
5766
+									$labeltoshow = dol_trunc($translabel, 18).' ';
5767 5767
 								} else {
5768
-									$labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
5768
+									$labeltoshow = dol_trunc($obj->$field_toshow, 18).' ';
5769 5769
 								}
5770 5770
 							}
5771 5771
 
5772
-							$data[$obj->rowid]=$labeltoshow;
5772
+							$data[$obj->rowid] = $labeltoshow;
5773 5773
 						} else {
5774
-							if (! $notrans) {
5774
+							if (!$notrans) {
5775 5775
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
5776 5776
 								if ($translabel != $obj->{$InfoFieldList[1]}) {
5777 5777
 									$labeltoshow = dol_trunc($translabel, 18);
@@ -5783,67 +5783,67 @@  discard block
 block discarded – undo
5783 5783
 								$labeltoshow = '(not defined)';
5784 5784
 
5785 5785
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5786
-									$data[$obj->rowid]=$labeltoshow;
5786
+									$data[$obj->rowid] = $labeltoshow;
5787 5787
 								}
5788 5788
 
5789
-								if (! empty($InfoFieldList[3]) && $parentField) {
5790
-									$parent = $parentName . ':' . $obj->{$parentField};
5789
+								if (!empty($InfoFieldList[3]) && $parentField) {
5790
+									$parent = $parentName.':'.$obj->{$parentField};
5791 5791
 								}
5792 5792
 
5793
-								$data[$obj->rowid]=$labeltoshow;
5793
+								$data[$obj->rowid] = $labeltoshow;
5794 5794
 						}
5795 5795
 
5796
-						$i ++;
5796
+						$i++;
5797 5797
 					}
5798 5798
 					$this->db->free($resql);
5799 5799
 
5800
-					$out=$form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5800
+					$out = $form->multiselectarray($keyprefix.$key.$keysuffix, $data, $value_arr, '', 0, '', 0, '100%');
5801 5801
 				} else {
5802
-					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5802
+					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5803 5803
 				}
5804 5804
 			}
5805 5805
 		}
5806 5806
 		elseif ($type == 'link')
5807 5807
 		{
5808
-			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5809
-			$showempty=(($required && $default != '')?0:1);
5810
-			$out=$form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5808
+			$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
5809
+			$showempty = (($required && $default != '') ? 0 : 1);
5810
+			$out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty);
5811 5811
 			if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
5812 5812
 			{
5813
-            			list($class,$classfile)=explode(':',$param_list[0]);
5814
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5815
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
5816
-            			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5813
+            			list($class, $classfile) = explode(':', $param_list[0]);
5814
+            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path = dol_buildpath(dirname(dirname($classfile)).'/card.php', 1);
5815
+            			else $url_path = dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php', 1);
5816
+            			$out .= '<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5817 5817
             			// TODO Add Javascript code to add input fields contents to new elements urls
5818 5818
 			}
5819 5819
 		}
5820 5820
 		elseif ($type == 'password')
5821 5821
 		{
5822 5822
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
5823
-			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5823
+			$out = '<input type="'.($keyprefix == 'search_' ? 'text' : 'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam ? $moreparam : '').'>';
5824 5824
 		}
5825 5825
 		elseif ($type == 'array')
5826 5826
 		{
5827 5827
 			$newval = $val;
5828 5828
 			$newval['type'] = 'varchar(256)';
5829 5829
 
5830
-			$out='';
5830
+			$out = '';
5831 5831
 
5832 5832
 			$inputs = array();
5833
-			if(! empty($value)) {
5834
-				foreach($value as $option) {
5835
-					$out.= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5836
-					$out.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5833
+			if (!empty($value)) {
5834
+				foreach ($value as $option) {
5835
+					$out .= '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5836
+					$out .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', $option, $moreparam, '', '', $showsize).'<br></span>';
5837 5837
 				}
5838 5838
 			}
5839 5839
 
5840
-			$out.= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5840
+			$out .= '<a id="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5841 5841
 
5842 5842
 			$newInput = '<span><a class="'.dol_escape_htmltag($keyprefix.$key.$keysuffix).'_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
5843
-			$newInput.= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5843
+			$newInput .= $this->showInputField($newval, $keyprefix.$key.$keysuffix.'[]', '', $moreparam, '', '', $showsize).'<br></span>';
5844 5844
 
5845
-			if(! empty($conf->use_javascript_ajax)) {
5846
-				$out.= '
5845
+			if (!empty($conf->use_javascript_ajax)) {
5846
+				$out .= '
5847 5847
 					<script type="text/javascript">
5848 5848
 					$(document).ready(function() {
5849 5849
 						$("a#'.dol_escape_js($keyprefix.$key.$keysuffix).'_add").click(function() {
@@ -5858,7 +5858,7 @@  discard block
 block discarded – undo
5858 5858
 			}
5859 5859
 		}
5860 5860
 		if (!empty($hidden)) {
5861
-			$out='<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5861
+			$out = '<input type="hidden" value="'.$value.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'"/>';
5862 5862
 		}
5863 5863
 		/* Add comments
5864 5864
 		 if ($type == 'date') $out.=' (YYYY-MM-DD)';
@@ -5880,14 +5880,14 @@  discard block
 block discarded – undo
5880 5880
 	 * @param  mixed   $showsize       Value for css to define size. May also be a numeric.
5881 5881
 	 * @return string
5882 5882
 	 */
5883
-	function showOutputField($val, $key, $value, $moreparam='', $keysuffix='', $keyprefix='', $showsize=0)
5883
+	function showOutputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $showsize = 0)
5884 5884
 	{
5885
-		global $conf,$langs,$form;
5885
+		global $conf, $langs, $form;
5886 5886
 
5887
-		if (! is_object($form))
5887
+		if (!is_object($form))
5888 5888
 		{
5889 5889
 			require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
5890
-			$form=new Form($this->db);
5890
+			$form = new Form($this->db);
5891 5891
 		}
5892 5892
 
5893 5893
 		$objectid = $this->id;
@@ -5898,28 +5898,28 @@  discard block
 block discarded – undo
5898 5898
 		// Convert var to be able to share same code than showOutputField of extrafields
5899 5899
 		if (preg_match('/varchar\((\d+)\)/', $type, $reg))
5900 5900
 		{
5901
-			$type = 'varchar';		// convert varchar(xx) int varchar
5901
+			$type = 'varchar'; // convert varchar(xx) int varchar
5902 5902
 			$size = $reg[1];
5903 5903
 		}
5904
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5905
-		if (is_array($val['arrayofkeyval'])) $type='select';
5906
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
5904
+		elseif (preg_match('/varchar/', $type)) $type = 'varchar'; // convert varchar(xx) int varchar
5905
+		if (is_array($val['arrayofkeyval'])) $type = 'select';
5906
+		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type = 'link';
5907 5907
 
5908
-		$default=$val['default'];
5909
-		$computed=$val['computed'];
5910
-		$unique=$val['unique'];
5911
-		$required=$val['required'];
5912
-		$param=$val['param'];
5908
+		$default = $val['default'];
5909
+		$computed = $val['computed'];
5910
+		$unique = $val['unique'];
5911
+		$required = $val['required'];
5912
+		$param = $val['param'];
5913 5913
 		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
5914 5914
 		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5915 5915
 		{
5916
-			$type='link';
5917
-			$param['options']=array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5916
+			$type = 'link';
5917
+			$param['options'] = array($reg[1].':'.$reg[2]=>$reg[1].':'.$reg[2]);
5918 5918
 		}
5919
-		$langfile=$val['langfile'];
5920
-		$list=$val['list'];
5921
-		$help=$val['help'];
5922
-		$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)
5919
+		$langfile = $val['langfile'];
5920
+		$list = $val['list'];
5921
+		$help = $val['help'];
5922
+		$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)
5923 5923
 
5924 5924
 		if ($hidden) return '';
5925 5925
 
@@ -5943,18 +5943,18 @@  discard block
 block discarded – undo
5943 5943
 				//$showsize=19;
5944 5944
 				$showsize = 'minwidth200imp';
5945 5945
 			}
5946
-			elseif (in_array($type,array('int','double','price')))
5946
+			elseif (in_array($type, array('int', 'double', 'price')))
5947 5947
 			{
5948 5948
 				//$showsize=10;
5949 5949
 				$showsize = 'maxwidth75';
5950 5950
 			}
5951 5951
 			elseif ($type == 'url')
5952 5952
 			{
5953
-				$showsize='minwidth400';
5953
+				$showsize = 'minwidth400';
5954 5954
 			}
5955 5955
 			elseif ($type == 'boolean')
5956 5956
 			{
5957
-				$showsize='';
5957
+				$showsize = '';
5958 5958
 			}
5959 5959
 			else
5960 5960
 			{
@@ -5975,90 +5975,90 @@  discard block
 block discarded – undo
5975 5975
 		}
5976 5976
 
5977 5977
 		// Format output value differently according to properties of field
5978
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5979
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5978
+		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value = $this->getNomUrl(1, '', 0, '', 1);
5979
+		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value = $this->getLibStatut(3);
5980 5980
 		elseif ($type == 'date')
5981 5981
 		{
5982
-			if(! empty($value)) {
5983
-				$value=dol_print_date($value,'day');
5982
+			if (!empty($value)) {
5983
+				$value = dol_print_date($value, 'day');
5984 5984
 			} else {
5985
-				$value='';
5985
+				$value = '';
5986 5986
 			}
5987 5987
 		}
5988 5988
 		elseif ($type == 'datetime')
5989 5989
 		{
5990
-			if(! empty($value)) {
5991
-				$value=dol_print_date($value,'dayhour');
5990
+			if (!empty($value)) {
5991
+				$value = dol_print_date($value, 'dayhour');
5992 5992
 			} else {
5993
-				$value='';
5993
+				$value = '';
5994 5994
 			}
5995 5995
 		}
5996 5996
 		elseif ($type == 'double')
5997 5997
 		{
5998 5998
 			if (!empty($value)) {
5999
-				$value=price($value);
5999
+				$value = price($value);
6000 6000
 			}
6001 6001
 		}
6002 6002
 		elseif ($type == 'boolean')
6003 6003
 		{
6004
-			$checked='';
6004
+			$checked = '';
6005 6005
 			if (!empty($value)) {
6006
-				$checked=' checked ';
6006
+				$checked = ' checked ';
6007 6007
 			}
6008
-			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6008
+			$value = '<input type="checkbox" '.$checked.' '.($moreparam ? $moreparam : '').' readonly disabled>';
6009 6009
 		}
6010 6010
 		elseif ($type == 'mail')
6011 6011
 		{
6012
-			$value=dol_print_email($value,0,0,0,64,1,1);
6012
+			$value = dol_print_email($value, 0, 0, 0, 64, 1, 1);
6013 6013
 		}
6014 6014
 		elseif ($type == 'url')
6015 6015
 		{
6016
-			$value=dol_print_url($value,'_blank',32,1);
6016
+			$value = dol_print_url($value, '_blank', 32, 1);
6017 6017
 		}
6018 6018
 		elseif ($type == 'phone')
6019 6019
 		{
6020
-			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6020
+			$value = dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6021 6021
 		}
6022 6022
 		elseif ($type == 'price')
6023 6023
 		{
6024
-			$value=price($value,0,$langs,0,0,-1,$conf->currency);
6024
+			$value = price($value, 0, $langs, 0, 0, -1, $conf->currency);
6025 6025
 		}
6026 6026
 		elseif ($type == 'select')
6027 6027
 		{
6028
-			$value=$param['options'][$value];
6028
+			$value = $param['options'][$value];
6029 6029
 		}
6030 6030
 		elseif ($type == 'sellist')
6031 6031
 		{
6032
-			$param_list=array_keys($param['options']);
6032
+			$param_list = array_keys($param['options']);
6033 6033
 			$InfoFieldList = explode(":", $param_list[0]);
6034 6034
 
6035
-			$selectkey="rowid";
6036
-			$keyList='rowid';
6035
+			$selectkey = "rowid";
6036
+			$keyList = 'rowid';
6037 6037
 
6038
-			if (count($InfoFieldList)>=3)
6038
+			if (count($InfoFieldList) >= 3)
6039 6039
 			{
6040 6040
 				$selectkey = $InfoFieldList[2];
6041
-				$keyList=$InfoFieldList[2].' as rowid';
6041
+				$keyList = $InfoFieldList[2].' as rowid';
6042 6042
 			}
6043 6043
 
6044
-			$fields_label = explode('|',$InfoFieldList[1]);
6045
-			if(is_array($fields_label)) {
6046
-				$keyList .=', ';
6044
+			$fields_label = explode('|', $InfoFieldList[1]);
6045
+			if (is_array($fields_label)) {
6046
+				$keyList .= ', ';
6047 6047
 				$keyList .= implode(', ', $fields_label);
6048 6048
 			}
6049 6049
 
6050 6050
 			$sql = 'SELECT '.$keyList;
6051
-			$sql.= ' FROM '.MAIN_DB_PREFIX .$InfoFieldList[0];
6052
-			if (strpos($InfoFieldList[4], 'extra')!==false)
6051
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6052
+			if (strpos($InfoFieldList[4], 'extra') !== false)
6053 6053
 			{
6054
-				$sql.= ' as main';
6054
+				$sql .= ' as main';
6055 6055
 			}
6056
-			if ($selectkey=='rowid' && empty($value)) {
6057
-				$sql.= " WHERE ".$selectkey."=0";
6058
-			} elseif ($selectkey=='rowid') {
6059
-				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6060
-			}else {
6061
-				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6056
+			if ($selectkey == 'rowid' && empty($value)) {
6057
+				$sql .= " WHERE ".$selectkey."=0";
6058
+			} elseif ($selectkey == 'rowid') {
6059
+				$sql .= " WHERE ".$selectkey."=".$this->db->escape($value);
6060
+			} else {
6061
+				$sql .= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6062 6062
 			}
6063 6063
 
6064 6064
 			//$sql.= ' AND entity = '.$conf->entity;
@@ -6067,38 +6067,38 @@  discard block
 block discarded – undo
6067 6067
 			$resql = $this->db->query($sql);
6068 6068
 			if ($resql)
6069 6069
 			{
6070
-				$value='';	// value was used, so now we reste it to use it to build final output
6070
+				$value = ''; // value was used, so now we reste it to use it to build final output
6071 6071
 
6072 6072
 				$obj = $this->db->fetch_object($resql);
6073 6073
 
6074 6074
 				// Several field into label (eq table:code|libelle:rowid)
6075
-				$fields_label = explode('|',$InfoFieldList[1]);
6075
+				$fields_label = explode('|', $InfoFieldList[1]);
6076 6076
 
6077
-				if(is_array($fields_label) && count($fields_label)>1)
6077
+				if (is_array($fields_label) && count($fields_label) > 1)
6078 6078
 				{
6079 6079
 					foreach ($fields_label as $field_toshow)
6080 6080
 					{
6081
-						$translabel='';
6081
+						$translabel = '';
6082 6082
 						if (!empty($obj->$field_toshow)) {
6083
-							$translabel=$langs->trans($obj->$field_toshow);
6083
+							$translabel = $langs->trans($obj->$field_toshow);
6084 6084
 						}
6085
-						if ($translabel!=$field_toshow) {
6086
-							$value.=dol_trunc($translabel,18).' ';
6087
-						}else {
6088
-							$value.=$obj->$field_toshow.' ';
6085
+						if ($translabel != $field_toshow) {
6086
+							$value .= dol_trunc($translabel, 18).' ';
6087
+						} else {
6088
+							$value .= $obj->$field_toshow.' ';
6089 6089
 						}
6090 6090
 					}
6091 6091
 				}
6092 6092
 				else
6093 6093
 				{
6094
-					$translabel='';
6094
+					$translabel = '';
6095 6095
 					if (!empty($obj->{$InfoFieldList[1]})) {
6096
-						$translabel=$langs->trans($obj->{$InfoFieldList[1]});
6096
+						$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6097 6097
 					}
6098
-					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6099
-						$value=dol_trunc($translabel,18);
6100
-					}else {
6101
-						$value=$obj->{$InfoFieldList[1]};
6098
+					if ($translabel != $obj->{$InfoFieldList[1]}) {
6099
+						$value = dol_trunc($translabel, 18);
6100
+					} else {
6101
+						$value = $obj->{$InfoFieldList[1]};
6102 6102
 					}
6103 6103
 				}
6104 6104
 			}
@@ -6106,18 +6106,18 @@  discard block
 block discarded – undo
6106 6106
 		}
6107 6107
 		elseif ($type == 'radio')
6108 6108
 		{
6109
-			$value=$param['options'][$value];
6109
+			$value = $param['options'][$value];
6110 6110
 		}
6111 6111
 		elseif ($type == 'checkbox')
6112 6112
 		{
6113
-			$value_arr=explode(',',$value);
6114
-			$value='';
6115
-			if (is_array($value_arr) && count($value_arr)>0)
6113
+			$value_arr = explode(',', $value);
6114
+			$value = '';
6115
+			if (is_array($value_arr) && count($value_arr) > 0)
6116 6116
 			{
6117 6117
 				foreach ($value_arr as $keyval=>$valueval) {
6118
-					$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6118
+					$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$param['options'][$valueval].'</li>';
6119 6119
 				}
6120
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6120
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6121 6121
 			}
6122 6122
 		}
6123 6123
 		elseif ($type == 'chkbxlst')
@@ -6132,7 +6132,7 @@  discard block
 block discarded – undo
6132 6132
 
6133 6133
 			if (count($InfoFieldList) >= 3) {
6134 6134
 				$selectkey = $InfoFieldList[2];
6135
-				$keyList = $InfoFieldList[2] . ' as rowid';
6135
+				$keyList = $InfoFieldList[2].' as rowid';
6136 6136
 			}
6137 6137
 
6138 6138
 			$fields_label = explode('|', $InfoFieldList[1]);
@@ -6141,75 +6141,75 @@  discard block
 block discarded – undo
6141 6141
 				$keyList .= implode(', ', $fields_label);
6142 6142
 			}
6143 6143
 
6144
-			$sql = 'SELECT ' . $keyList;
6145
-			$sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
6144
+			$sql = 'SELECT '.$keyList;
6145
+			$sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[0];
6146 6146
 			if (strpos($InfoFieldList[4], 'extra') !== false) {
6147 6147
 				$sql .= ' as main';
6148 6148
 			}
6149 6149
 			// $sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6150 6150
 			// $sql.= ' AND entity = '.$conf->entity;
6151 6151
 
6152
-			dol_syslog(get_class($this) . ':showOutputField:$type=chkbxlst',LOG_DEBUG);
6152
+			dol_syslog(get_class($this).':showOutputField:$type=chkbxlst', LOG_DEBUG);
6153 6153
 			$resql = $this->db->query($sql);
6154 6154
 			if ($resql) {
6155 6155
 				$value = ''; // value was used, so now we reste it to use it to build final output
6156
-				$toprint=array();
6157
-				while ( $obj = $this->db->fetch_object($resql) ) {
6156
+				$toprint = array();
6157
+				while ($obj = $this->db->fetch_object($resql)) {
6158 6158
 
6159 6159
 					// Several field into label (eq table:code|libelle:rowid)
6160 6160
 					$fields_label = explode('|', $InfoFieldList[1]);
6161 6161
 					if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
6162 6162
 						if (is_array($fields_label) && count($fields_label) > 1) {
6163
-							foreach ( $fields_label as $field_toshow ) {
6163
+							foreach ($fields_label as $field_toshow) {
6164 6164
 								$translabel = '';
6165
-								if (! empty($obj->$field_toshow)) {
6165
+								if (!empty($obj->$field_toshow)) {
6166 6166
 									$translabel = $langs->trans($obj->$field_toshow);
6167 6167
 								}
6168 6168
 								if ($translabel != $field_toshow) {
6169
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6169
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6170 6170
 								} else {
6171
-									$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6171
+									$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->$field_toshow.'</li>';
6172 6172
 								}
6173 6173
 							}
6174 6174
 						} else {
6175 6175
 							$translabel = '';
6176
-							if (! empty($obj->{$InfoFieldList[1]})) {
6176
+							if (!empty($obj->{$InfoFieldList[1]})) {
6177 6177
 								$translabel = $langs->trans($obj->{$InfoFieldList[1]});
6178 6178
 							}
6179 6179
 							if ($translabel != $obj->{$InfoFieldList[1]}) {
6180
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6180
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.dol_trunc($translabel, 18).'</li>';
6181 6181
 							} else {
6182
-								$toprint[]='<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6182
+								$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #aaa">'.$obj->{$InfoFieldList[1]}.'</li>';
6183 6183
 							}
6184 6184
 						}
6185 6185
 					}
6186 6186
 				}
6187
-				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6187
+				$value = '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6188 6188
 			} else {
6189
-				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6189
+				dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6190 6190
 			}
6191 6191
 		}
6192 6192
 		elseif ($type == 'link')
6193 6193
 		{
6194
-			$out='';
6194
+			$out = '';
6195 6195
 
6196 6196
 			// only if something to display (perf)
6197 6197
 			if ($value)
6198 6198
 			{
6199
-				$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
6199
+				$param_list = array_keys($param['options']); // $param_list='ObjectName:classPath'
6200 6200
 
6201 6201
 				$InfoFieldList = explode(":", $param_list[0]);
6202
-				$classname=$InfoFieldList[0];
6203
-				$classpath=$InfoFieldList[1];
6204
-				$getnomurlparam=(empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6205
-				if (! empty($classpath))
6202
+				$classname = $InfoFieldList[0];
6203
+				$classpath = $InfoFieldList[1];
6204
+				$getnomurlparam = (empty($InfoFieldList[2]) ? 3 : $InfoFieldList[2]);
6205
+				if (!empty($classpath))
6206 6206
 				{
6207 6207
 					dol_include_once($InfoFieldList[1]);
6208 6208
 					if ($classname && class_exists($classname))
6209 6209
 					{
6210 6210
 						$object = new $classname($this->db);
6211 6211
 						$object->fetch($value);
6212
-						$value=$object->getNomUrl($getnomurlparam);
6212
+						$value = $object->getNomUrl($getnomurlparam);
6213 6213
 					}
6214 6214
 				}
6215 6215
 				else
@@ -6218,15 +6218,15 @@  discard block
 block discarded – undo
6218 6218
 					return 'Error bad setup of extrafield';
6219 6219
 				}
6220 6220
 			}
6221
-			else $value='';
6221
+			else $value = '';
6222 6222
 		}
6223 6223
 		elseif ($type == 'text' || $type == 'html')
6224 6224
 		{
6225
-			$value=dol_htmlentitiesbr($value);
6225
+			$value = dol_htmlentitiesbr($value);
6226 6226
 		}
6227 6227
 		elseif ($type == 'password')
6228 6228
 		{
6229
-			$value=preg_replace('/./i','*',$value);
6229
+			$value = preg_replace('/./i', '*', $value);
6230 6230
 		}
6231 6231
 		elseif ($type == 'array')
6232 6232
 		{
@@ -6234,7 +6234,7 @@  discard block
 block discarded – undo
6234 6234
 		}
6235 6235
 
6236 6236
 		//print $type.'-'.$size;
6237
-		$out=$value;
6237
+		$out = $value;
6238 6238
 
6239 6239
 		return $out;
6240 6240
 	}
@@ -6251,11 +6251,11 @@  discard block
 block discarded – undo
6251 6251
 	 * @param	string		$onetrtd		All fields in same tr td
6252 6252
 	 * @return 	string
6253 6253
 	 */
6254
-	function showOptionals($extrafields, $mode='view', $params=null, $keysuffix='', $keyprefix='', $onetrtd=0)
6254
+	function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0)
6255 6255
 	{
6256 6256
 		global $db, $conf, $langs, $action, $form;
6257 6257
 
6258
-		if (! is_object($form)) $form=new Form($db);
6258
+		if (!is_object($form)) $form = new Form($db);
6259 6259
 
6260 6260
 		$out = '';
6261 6261
 
@@ -6266,10 +6266,10 @@  discard block
 block discarded – undo
6266 6266
 			$out .= "\n";
6267 6267
 
6268 6268
 			$e = 0;
6269
-			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6269
+			foreach ($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6270 6270
 			{
6271 6271
 				// Show only the key field in params
6272
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6272
+				if (is_array($params) && array_key_exists('onlykey', $params) && $key != $params['onlykey']) continue;
6273 6273
 
6274 6274
 				$enabled = 1;
6275 6275
 				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
@@ -6283,25 +6283,25 @@  discard block
 block discarded – undo
6283 6283
 					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6284 6284
 				}
6285 6285
 
6286
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6286
+				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6287 6287
 				if (empty($perms)) continue;
6288 6288
 
6289 6289
 				// Load language if required
6290
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6290
+				if (!empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6291 6291
 
6292
-				$colspan='3';
6293
-				if (is_array($params) && count($params)>0) {
6294
-					if (array_key_exists('colspan',$params)) {
6295
-						$colspan=$params['colspan'];
6292
+				$colspan = '3';
6293
+				if (is_array($params) && count($params) > 0) {
6294
+					if (array_key_exists('colspan', $params)) {
6295
+						$colspan = $params['colspan'];
6296 6296
 					}
6297 6297
 				}
6298 6298
 
6299
-				switch($mode) {
6299
+				switch ($mode) {
6300 6300
 					case "view":
6301
-						$value=$this->array_options["options_".$key.$keysuffix];
6301
+						$value = $this->array_options["options_".$key.$keysuffix];
6302 6302
 						break;
6303 6303
 					case "edit":
6304
-						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none');				// GETPOST can get value from GET, POST or setup of default values.
6304
+						$getposttemp = GETPOST($keyprefix.'options_'.$key.$keysuffix, 'none'); // GETPOST can get value from GET, POST or setup of default values.
6305 6305
 						// GETPOST("options_" . $key) can be 'abc' or array(0=>'abc')
6306 6306
 						if (is_array($getposttemp) || $getposttemp != '' || GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix))
6307 6307
 						{
@@ -6312,7 +6312,7 @@  discard block
 block discarded – undo
6312 6312
 								$value = $getposttemp;
6313 6313
 							}
6314 6314
 						} else {
6315
-							$value = $this->array_options["options_" . $key];			// No GET, no POST, no default value, so we take value of object.
6315
+							$value = $this->array_options["options_".$key]; // No GET, no POST, no default value, so we take value of object.
6316 6316
 						}
6317 6317
 						//var_dump($keyprefix.' - '.$key.' - '.$keysuffix.' - '.$keyprefix.'options_'.$key.$keysuffix.' - '.$this->array_options["options_".$key.$keysuffix].' - '.$getposttemp.' - '.$value);
6318 6318
 						break;
@@ -6324,11 +6324,11 @@  discard block
 block discarded – undo
6324 6324
 				}
6325 6325
 				else
6326 6326
 				{
6327
-					$csstyle='';
6328
-					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6329
-					if (is_array($params) && count($params)>0) {
6330
-						if (array_key_exists('style',$params)) {
6331
-							$csstyle=$params['style'];
6327
+					$csstyle = '';
6328
+					$class = (!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
6329
+					if (is_array($params) && count($params) > 0) {
6330
+						if (array_key_exists('style', $params)) {
6331
+							$csstyle = $params['style'];
6332 6332
 						}
6333 6333
 					}
6334 6334
 
@@ -6341,43 +6341,43 @@  discard block
 block discarded – undo
6341 6341
 
6342 6342
 					$out .= '<tr id="'.$html_id.'" '.$csstyle.' class="'.$class.$this->element.'_extras_'.$key.'" '.$domData.' >';
6343 6343
 
6344
-					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
6344
+					if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0)
6345 6345
 					{
6346
-						if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan='0'; }
6346
+						if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && ($e % 2) == 0) { $colspan = '0'; }
6347 6347
 					}
6348 6348
 
6349 6349
 					if ($action == 'selectlines') { $colspan++; }
6350 6350
 
6351 6351
 					// Convert date into timestamp format (value in memory must be a timestamp)
6352
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6352
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('date', 'datetime')))
6353 6353
 					{
6354
-						$datenotinstring = $this->array_options['options_' . $key];
6355
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6354
+						$datenotinstring = $this->array_options['options_'.$key];
6355
+						if (!is_numeric($this->array_options['options_'.$key]))	// For backward compatibility
6356 6356
 						{
6357 6357
 							$datenotinstring = $this->db->jdate($datenotinstring);
6358 6358
 						}
6359
-						$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;
6359
+						$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;
6360 6360
 					}
6361 6361
 					// Convert float submited string into real php numeric (value in memory must be a php numeric)
6362
-					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('price','double')))
6362
+					if (in_array($extrafields->attributes[$this->table_element]['type'][$key], array('price', 'double')))
6363 6363
 					{
6364
-						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix)?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)):$this->array_options['options_'.$key];
6364
+						$value = GETPOSTISSET($keyprefix.'options_'.$key.$keysuffix) ?price2num(GETPOST($keyprefix.'options_'.$key.$keysuffix, 'alpha', 3)) : $this->array_options['options_'.$key];
6365 6365
 					}
6366 6366
 
6367 6367
 					$labeltoshow = $langs->trans($label);
6368 6368
 
6369 6369
 					$out .= '<td class="titlefield';
6370
-					if (GETPOST('action','none') == 'create') $out.='create';
6371
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6370
+					if (GETPOST('action', 'none') == 'create') $out .= 'create';
6371
+					if ($mode != 'view' && !empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6372 6372
 					$out .= '">';
6373
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6373
+					if (!empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6374 6374
 					else $out .= $labeltoshow;
6375 6375
 					$out .= '</td>';
6376 6376
 
6377 6377
 					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
6378
-					$out .='<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan?' colspan="'.$colspan.'"':'').'>';
6378
+					$out .= '<td id="'.$html_id.'" class="'.$this->element.'_extras_'.$key.'" '.($colspan ? ' colspan="'.$colspan.'"' : '').'>';
6379 6379
 
6380
-					switch($mode) {
6380
+					switch ($mode) {
6381 6381
 						case "view":
6382 6382
 							$out .= $extrafields->showOutputField($key, $value);
6383 6383
 							break;
@@ -6388,14 +6388,14 @@  discard block
 block discarded – undo
6388 6388
 
6389 6389
 					$out .= '</td>';
6390 6390
 
6391
-					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
6391
+					if (!empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
6392 6392
 					else $out .= '</tr>';
6393 6393
 					$e++;
6394 6394
 				}
6395 6395
 			}
6396 6396
 			$out .= "\n";
6397 6397
 			// Add code to manage list depending on others
6398
-			if (! empty($conf->use_javascript_ajax)) {
6398
+			if (!empty($conf->use_javascript_ajax)) {
6399 6399
 				$out .= '
6400 6400
 				<script type="text/javascript">
6401 6401
 				    jQuery(document).ready(function() {
@@ -6441,7 +6441,7 @@  discard block
 block discarded – undo
6441 6441
 		global $user;
6442 6442
 
6443 6443
 		$element = $this->element;
6444
-		if ($element == 'facturerec') $element='facture';
6444
+		if ($element == 'facturerec') $element = 'facture';
6445 6445
 
6446 6446
 		return $user->rights->{$element};
6447 6447
 	}
@@ -6458,15 +6458,15 @@  discard block
 block discarded – undo
6458 6458
 	 * @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)
6459 6459
 	 * @return bool						  True if success, False if error
6460 6460
 	 */
6461
-	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
6461
+	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors = 0)
6462 6462
 	{
6463 6463
 		foreach ($tables as $table)
6464 6464
 		{
6465 6465
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
6466 6466
 
6467
-			if (! $db->query($sql))
6467
+			if (!$db->query($sql))
6468 6468
 			{
6469
-				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.
6469
+				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.
6470 6470
 				//$this->errors = $db->lasterror();
6471 6471
 				return false;
6472 6472
 			}
@@ -6500,7 +6500,7 @@  discard block
 block discarded – undo
6500 6500
 		else
6501 6501
 		{
6502 6502
 			// Get cost price for margin calculation
6503
-			if (! empty($fk_product))
6503
+			if (!empty($fk_product))
6504 6504
 			{
6505 6505
 				if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'costprice')
6506 6506
 				{
@@ -6537,7 +6537,7 @@  discard block
 block discarded – undo
6537 6537
 					}
6538 6538
 				}
6539 6539
 
6540
-				if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
6540
+				if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1', 'pmp', 'costprice')))
6541 6541
 				{
6542 6542
 					require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
6543 6543
 					$productFournisseur = new ProductFournisseur($this->db);
@@ -6574,18 +6574,18 @@  discard block
 block discarded – undo
6574 6574
 	 *  @param		int		$usesharelink	Use the public shared link of image (if not available, the 'nophoto' image will be shown instead)
6575 6575
 	 *  @return     string					Html code to show photo. Number of photos shown is saved in this->nbphoto
6576 6576
 	 */
6577
-	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)
6577
+	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)
6578 6578
 	{
6579 6579
         // phpcs:enable
6580
-		global $conf,$user,$langs;
6580
+		global $conf, $user, $langs;
6581 6581
 
6582
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/files.lib.php';
6583
-		include_once DOL_DOCUMENT_ROOT .'/core/lib/images.lib.php';
6582
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
6583
+		include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
6584 6584
 
6585
-		$sortfield='position_name';
6586
-		$sortorder='asc';
6585
+		$sortfield = 'position_name';
6586
+		$sortorder = 'asc';
6587 6587
 
6588
-		$dir = $sdir . '/';
6588
+		$dir = $sdir.'/';
6589 6589
 		$pdir = '/';
6590 6590
 		if ($modulepart == 'ticket')
6591 6591
 		{
@@ -6599,28 +6599,28 @@  discard block
 block discarded – undo
6599 6599
 		}
6600 6600
 
6601 6601
 		// For backward compatibility
6602
-		if ($modulepart == 'product' && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
6602
+		if ($modulepart == 'product' && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
6603 6603
 		{
6604
-			$dir = $sdir . '/'. get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6605
-			$pdir = '/' . get_exdir($this->id,2,0,0,$this,$modulepart) . $this->id ."/photos/";
6604
+			$dir = $sdir.'/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6605
+			$pdir = '/'.get_exdir($this->id, 2, 0, 0, $this, $modulepart).$this->id."/photos/";
6606 6606
 		}
6607 6607
 
6608 6608
 		// Defined relative dir to DOL_DATA_ROOT
6609 6609
 		$relativedir = '';
6610 6610
 		if ($dir)
6611 6611
 		{
6612
-			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $dir);
6613
-			$relativedir = preg_replace('/^[\\/]/','',$relativedir);
6614
-			$relativedir = preg_replace('/[\\/]$/','',$relativedir);
6612
+			$relativedir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT, '/').'/', '', $dir);
6613
+			$relativedir = preg_replace('/^[\\/]/', '', $relativedir);
6614
+			$relativedir = preg_replace('/[\\/]$/', '', $relativedir);
6615 6615
 		}
6616 6616
 
6617 6617
 		$dirthumb = $dir.'thumbs/';
6618 6618
 		$pdirthumb = $pdir.'thumbs/';
6619 6619
 
6620
-		$return ='<!-- Photo -->'."\n";
6621
-		$nbphoto=0;
6620
+		$return = '<!-- Photo -->'."\n";
6621
+		$nbphoto = 0;
6622 6622
 
6623
-		$filearray=dol_dir_list($dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
6623
+		$filearray = dol_dir_list($dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
6624 6624
 
6625 6625
 		/*if (! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))    // For backward compatiblity, we scan also old dirs
6626 6626
 		 {
@@ -6634,12 +6634,12 @@  discard block
 block discarded – undo
6634 6634
 		{
6635 6635
 			if ($sortfield && $sortorder)
6636 6636
 			{
6637
-				$filearray=dol_sort_array($filearray, $sortfield, $sortorder);
6637
+				$filearray = dol_sort_array($filearray, $sortfield, $sortorder);
6638 6638
 			}
6639 6639
 
6640
-			foreach($filearray as $key => $val)
6640
+			foreach ($filearray as $key => $val)
6641 6641
 			{
6642
-				$photo='';
6642
+				$photo = '';
6643 6643
 				$file = $val['name'];
6644 6644
 
6645 6645
 				//if (! utf8_check($file)) $file=utf8_encode($file);	// To be sure file is stored in UTF8 in memory
@@ -6654,36 +6654,36 @@  discard block
 block discarded – undo
6654 6654
 					if ($size == 1 || $size == 'small') {   // Format vignette
6655 6655
 
6656 6656
 						// Find name of thumb file
6657
-						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6658
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
6657
+						$photo_vignette = basename(getImageFileNameForSize($dir.$file, '_small'));
6658
+						if (!dol_is_file($dirthumb.$photo_vignette)) $photo_vignette = '';
6659 6659
 
6660 6660
 						// Get filesize of original file
6661
-						$imgarray=dol_getImageSize($dir.$photo);
6661
+						$imgarray = dol_getImageSize($dir.$photo);
6662 6662
 
6663 6663
 						if ($nbbyrow > 0)
6664 6664
 						{
6665
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6665
+							if ($nbphoto == 1) $return .= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
6666 6666
 
6667
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
6668
-							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6667
+							if ($nbphoto % $nbbyrow == 1) $return .= '<tr align=center valign=middle border=1>';
6668
+							$return .= '<td width="'.ceil(100 / $nbbyrow).'%" class="photo">';
6669 6669
 						}
6670 6670
 						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
6671 6671
 
6672
-						$return.= "\n";
6672
+						$return .= "\n";
6673 6673
 
6674
-						$relativefile=preg_replace('/^\//', '', $pdir.$photo);
6674
+						$relativefile = preg_replace('/^\//', '', $pdir.$photo);
6675 6675
 						if (empty($nolink))
6676 6676
 						{
6677
-							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6678
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6679
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6677
+							$urladvanced = getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6678
+							if ($urladvanced) $return .= '<a href="'.$urladvanced.'">';
6679
+							else $return .= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
6680 6680
 						}
6681 6681
 
6682 6682
 						// Show image (width height=$maxHeight)
6683 6683
 						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6684
-						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6685
-						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6686
-						if ($notitle) $alt='';
6684
+						$alt = $langs->transnoentitiesnoconv('File').': '.$relativefile;
6685
+						$alt .= ' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6686
+						if ($notitle) $alt = '';
6687 6687
 
6688 6688
 						if ($usesharelink)
6689 6689
 						{
@@ -6691,81 +6691,81 @@  discard block
 block discarded – undo
6691 6691
 							{
6692 6692
 								if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6693 6693
 								{
6694
-									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6695
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6694
+									$return .= '<!-- Show original file (thumb not yet available with shared links) -->';
6695
+									$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6696 6696
 								}
6697 6697
 								else {
6698
-									$return.= '<!-- Show original file -->';
6699
-									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6698
+									$return .= '<!-- Show original file -->';
6699
+									$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6700 6700
 								}
6701 6701
 							}
6702 6702
 							else
6703 6703
 							{
6704
-								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6705
-								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6704
+								$return .= '<!-- Show nophoto file (because file is not shared) -->';
6705
+								$return .= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6706 6706
 							}
6707 6707
 						}
6708 6708
 						else
6709 6709
 						{
6710 6710
 							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6711 6711
 							{
6712
-								$return.= '<!-- Show thumb -->';
6713
-								$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).'">';
6712
+								$return .= '<!-- Show thumb -->';
6713
+								$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).'">';
6714 6714
 							}
6715 6715
 							else {
6716
-								$return.= '<!-- Show original file -->';
6717
-								$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).'">';
6716
+								$return .= '<!-- Show original file -->';
6717
+								$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).'">';
6718 6718
 							}
6719 6719
 						}
6720 6720
 
6721
-						if (empty($nolink)) $return.= '</a>';
6722
-						$return.="\n";
6721
+						if (empty($nolink)) $return .= '</a>';
6722
+						$return .= "\n";
6723 6723
 
6724
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6724
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6725 6725
 						if ($showaction)
6726 6726
 						{
6727
-							$return.= '<br>';
6727
+							$return .= '<br>';
6728 6728
 							// On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites
6729 6729
 							if ($photo_vignette && (image_format_supported($photo) > 0) && ($this->imgWidth > $maxWidth || $this->imgHeight > $maxHeight))
6730 6730
 							{
6731
-								$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>';
6731
+								$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>';
6732 6732
 							}
6733 6733
 							// Special cas for product
6734 6734
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6735 6735
 							{
6736 6736
 								// Link to resize
6737
-								$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; ';
6737
+								$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; ';
6738 6738
 
6739 6739
 								// Link to delete
6740
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6741
-								$return.= img_delete().'</a>';
6740
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6741
+								$return .= img_delete().'</a>';
6742 6742
 							}
6743 6743
 						}
6744
-						$return.= "\n";
6744
+						$return .= "\n";
6745 6745
 
6746 6746
 						if ($nbbyrow > 0)
6747 6747
 						{
6748
-							$return.= '</td>';
6749
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6748
+							$return .= '</td>';
6749
+							if (($nbphoto % $nbbyrow) == 0) $return .= '</tr>';
6750 6750
 						}
6751
-						else if ($nbbyrow < 0) $return.='</div>';
6751
+						else if ($nbbyrow < 0) $return .= '</div>';
6752 6752
 					}
6753 6753
 
6754 6754
 					if (empty($size)) {     // Format origine
6755
-						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6755
+						$return .= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6756 6756
 
6757
-						if ($showfilename) $return.= '<br>'.$viewfilename;
6757
+						if ($showfilename) $return .= '<br>'.$viewfilename;
6758 6758
 						if ($showaction)
6759 6759
 						{
6760 6760
 							// Special case for product
6761 6761
 							if ($modulepart == 'product' && ($user->rights->produit->creer || $user->rights->service->creer))
6762 6762
 							{
6763 6763
 								// Link to resize
6764
-								$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; ';
6764
+								$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; ';
6765 6765
 
6766 6766
 								// Link to delete
6767
-								$return.= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6768
-								$return.= img_delete().'</a>';
6767
+								$return .= '<a href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=delete&amp;file='.urlencode($pdir.$viewfilename).'">';
6768
+								$return .= img_delete().'</a>';
6769 6769
 							}
6770 6770
 						}
6771 6771
 					}
@@ -6775,18 +6775,18 @@  discard block
 block discarded – undo
6775 6775
 				}
6776 6776
 			}
6777 6777
 
6778
-			if ($size==1 || $size=='small')
6778
+			if ($size == 1 || $size == 'small')
6779 6779
 			{
6780 6780
 				if ($nbbyrow > 0)
6781 6781
 				{
6782 6782
 					// Ferme tableau
6783 6783
 					while ($nbphoto % $nbbyrow)
6784 6784
 					{
6785
-						$return.= '<td width="'.ceil(100/$nbbyrow).'%">&nbsp;</td>';
6785
+						$return .= '<td width="'.ceil(100 / $nbbyrow).'%">&nbsp;</td>';
6786 6786
 						$nbphoto++;
6787 6787
 					}
6788 6788
 
6789
-					if ($nbphoto) $return.= '</table>';
6789
+					if ($nbphoto) $return .= '</table>';
6790 6790
 				}
6791 6791
 			}
6792 6792
 		}
@@ -6805,9 +6805,9 @@  discard block
 block discarded – undo
6805 6805
 	 */
6806 6806
 	protected function isArray($info)
6807 6807
 	{
6808
-		if(is_array($info))
6808
+		if (is_array($info))
6809 6809
 		{
6810
-			if(isset($info['type']) && $info['type']=='array') return true;
6810
+			if (isset($info['type']) && $info['type'] == 'array') return true;
6811 6811
 			else return false;
6812 6812
 		}
6813 6813
 		else return false;
@@ -6821,9 +6821,9 @@  discard block
 block discarded – undo
6821 6821
 	 */
6822 6822
 	protected function isNull($info)
6823 6823
 	{
6824
-		if(is_array($info))
6824
+		if (is_array($info))
6825 6825
 		{
6826
-			if(isset($info['type']) && $info['type']=='null') return true;
6826
+			if (isset($info['type']) && $info['type'] == 'null') return true;
6827 6827
 			else return false;
6828 6828
 		}
6829 6829
 		else return false;
@@ -6837,7 +6837,7 @@  discard block
 block discarded – undo
6837 6837
 	 */
6838 6838
 	public function isDate($info)
6839 6839
 	{
6840
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6840
+		if (isset($info['type']) && ($info['type'] == 'date' || $info['type'] == 'datetime' || $info['type'] == 'timestamp')) return true;
6841 6841
 		else return false;
6842 6842
 	}
6843 6843
 
@@ -6849,9 +6849,9 @@  discard block
 block discarded – undo
6849 6849
 	 */
6850 6850
 	public function isInt($info)
6851 6851
 	{
6852
-		if(is_array($info))
6852
+		if (is_array($info))
6853 6853
 		{
6854
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6854
+			if (isset($info['type']) && ($info['type'] == 'int' || preg_match('/^integer/i', $info['type']))) return true;
6855 6855
 			else return false;
6856 6856
 		}
6857 6857
 		else return false;
@@ -6865,7 +6865,7 @@  discard block
 block discarded – undo
6865 6865
 	 */
6866 6866
 	public function isFloat($info)
6867 6867
 	{
6868
-		if(is_array($info))
6868
+		if (is_array($info))
6869 6869
 		{
6870 6870
 			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6871 6871
 			else return false;
@@ -6881,9 +6881,9 @@  discard block
 block discarded – undo
6881 6881
 	 */
6882 6882
 	public function isText($info)
6883 6883
 	{
6884
-		if(is_array($info))
6884
+		if (is_array($info))
6885 6885
 		{
6886
-			if(isset($info['type']) && $info['type']=='text') return true;
6886
+			if (isset($info['type']) && $info['type'] == 'text') return true;
6887 6887
 			else return false;
6888 6888
 		}
6889 6889
 		else return false;
@@ -6897,9 +6897,9 @@  discard block
 block discarded – undo
6897 6897
 	 */
6898 6898
 	protected function isIndex($info)
6899 6899
 	{
6900
-		if(is_array($info))
6900
+		if (is_array($info))
6901 6901
 		{
6902
-			if(isset($info['index']) && $info['index']==true) return true;
6902
+			if (isset($info['index']) && $info['index'] == true) return true;
6903 6903
 			else return false;
6904 6904
 		}
6905 6905
 		else return false;
@@ -6915,13 +6915,13 @@  discard block
 block discarded – undo
6915 6915
 	{
6916 6916
 		global $conf;
6917 6917
 
6918
-		$queryarray=array();
6918
+		$queryarray = array();
6919 6919
 		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
6920 6920
 		{
6921 6921
 			// Depending on field type ('datetime', ...)
6922
-			if($this->isDate($info))
6922
+			if ($this->isDate($info))
6923 6923
 			{
6924
-				if(empty($this->{$field}))
6924
+				if (empty($this->{$field}))
6925 6925
 				{
6926 6926
 					$queryarray[$field] = null;
6927 6927
 				}
@@ -6930,10 +6930,10 @@  discard block
 block discarded – undo
6930 6930
 					$queryarray[$field] = $this->db->idate($this->{$field});
6931 6931
 				}
6932 6932
 			}
6933
-			else if($this->isArray($info))
6933
+			else if ($this->isArray($info))
6934 6934
 			{
6935
-				if(! empty($this->{$field})) {
6936
-					if(! is_array($this->{$field})) {
6935
+				if (!empty($this->{$field})) {
6936
+					if (!is_array($this->{$field})) {
6937 6937
 						$this->{$field} = array($this->{$field});
6938 6938
 					}
6939 6939
 					$queryarray[$field] = serialize($this->{$field});
@@ -6941,19 +6941,19 @@  discard block
 block discarded – undo
6941 6941
 					$queryarray[$field] = null;
6942 6942
 				}
6943 6943
 			}
6944
-			else if($this->isInt($info))
6944
+			else if ($this->isInt($info))
6945 6945
 			{
6946
-				if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity;
6946
+				if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field] = $conf->entity;
6947 6947
 				else
6948 6948
 				{
6949 6949
 					$queryarray[$field] = (int) price2num($this->{$field});
6950
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
6950
+					if (empty($queryarray[$field])) $queryarray[$field] = 0; // May be reset to null later if property 'notnull' is -1 for this field.
6951 6951
 				}
6952 6952
 			}
6953
-			else if($this->isFloat($info))
6953
+			else if ($this->isFloat($info))
6954 6954
 			{
6955 6955
 				$queryarray[$field] = (double) price2num($this->{$field});
6956
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6956
+				if (empty($queryarray[$field])) $queryarray[$field] = 0;
6957 6957
 			}
6958 6958
 			else
6959 6959
 			{
@@ -6961,7 +6961,7 @@  discard block
 block discarded – undo
6961 6961
 			}
6962 6962
 
6963 6963
 			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6964
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6964
+			if (!empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
6965 6965
 		}
6966 6966
 
6967 6967
 		return $queryarray;
@@ -6977,35 +6977,35 @@  discard block
 block discarded – undo
6977 6977
 	{
6978 6978
 		foreach ($this->fields as $field => $info)
6979 6979
 		{
6980
-			if($this->isDate($info))
6980
+			if ($this->isDate($info))
6981 6981
 			{
6982
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6982
+				if (empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6983 6983
 				else $this->{$field} = strtotime($obj->{$field});
6984 6984
 			}
6985
-			elseif($this->isArray($info))
6985
+			elseif ($this->isArray($info))
6986 6986
 			{
6987
-				if(! empty($obj->{$field})) {
6987
+				if (!empty($obj->{$field})) {
6988 6988
 					$this->{$field} = @unserialize($obj->{$field});
6989 6989
 					// Hack for data not in UTF8
6990
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6990
+					if ($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
6991 6991
 				} else {
6992 6992
 					$this->{$field} = array();
6993 6993
 				}
6994 6994
 			}
6995
-			elseif($this->isInt($info))
6995
+			elseif ($this->isInt($info))
6996 6996
 			{
6997 6997
 				if ($field == 'rowid') $this->id = (int) $obj->{$field};
6998 6998
 				else $this->{$field} = (int) $obj->{$field};
6999 6999
 			}
7000
-			elseif($this->isFloat($info))
7000
+			elseif ($this->isFloat($info))
7001 7001
 			{
7002 7002
 				$this->{$field} = (double) $obj->{$field};
7003 7003
 			}
7004
-			elseif($this->isNull($info))
7004
+			elseif ($this->isNull($info))
7005 7005
 			{
7006 7006
 				$val = $obj->{$field};
7007 7007
 				// zero is not null
7008
-				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7008
+				$this->{$field} = (is_null($val) || (empty($val) && $val !== 0 && $val !== '0') ? null : $val);
7009 7009
 			}
7010 7010
 			else
7011 7011
 			{
@@ -7014,7 +7014,7 @@  discard block
 block discarded – undo
7014 7014
 		}
7015 7015
 
7016 7016
 		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7017
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7017
+		if (!isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7018 7018
 	}
7019 7019
 
7020 7020
 	/**
@@ -7056,14 +7056,14 @@  discard block
 block discarded – undo
7056 7056
 
7057 7057
 		$error = 0;
7058 7058
 
7059
-		$now=dol_now();
7059
+		$now = dol_now();
7060 7060
 
7061 7061
 		$fieldvalues = $this->setSaveQuery();
7062
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7063
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7064
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7062
+		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation'] = $this->db->idate($now);
7063
+		if (array_key_exists('fk_user_creat', $fieldvalues) && !($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat'] = $user->id;
7064
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7065 7065
 
7066
-		$keys=array();
7066
+		$keys = array();
7067 7067
 		$values = array();
7068 7068
 		foreach ($fieldvalues as $k => $v) {
7069 7069
 			$keys[$k] = $k;
@@ -7072,58 +7072,58 @@  discard block
 block discarded – undo
7072 7072
 		}
7073 7073
 
7074 7074
 		// Clean and check mandatory
7075
-		foreach($keys as $key)
7075
+		foreach ($keys as $key)
7076 7076
 		{
7077 7077
 			// If field is an implicit foreign key field
7078
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7079
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7078
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = '';
7079
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = '';
7080 7080
 
7081 7081
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7082
-			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
7082
+			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && !isset($values[$key]) && is_null($val['default']))
7083 7083
 			{
7084 7084
 				$error++;
7085
-				$this->errors[]=$langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7085
+				$this->errors[] = $langs->trans("ErrorFieldRequired", $this->fields[$key]['label']);
7086 7086
 			}
7087 7087
 
7088 7088
 			// If field is an implicit foreign key field
7089
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7090
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7089
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key] = 'null';
7090
+			if (!empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key] = 'null';
7091 7091
 		}
7092 7092
 
7093 7093
 		if ($error) return -1;
7094 7094
 
7095 7095
 		$this->db->begin();
7096 7096
 
7097
-		if (! $error)
7097
+		if (!$error)
7098 7098
 		{
7099 7099
 			$sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element;
7100
-			$sql.= ' ('.implode( ", ", $keys ).')';
7101
-			$sql.= ' VALUES ('.implode( ", ", $values ).')';
7100
+			$sql .= ' ('.implode(", ", $keys).')';
7101
+			$sql .= ' VALUES ('.implode(", ", $values).')';
7102 7102
 
7103 7103
 			$res = $this->db->query($sql);
7104
-			if ($res===false) {
7104
+			if ($res === false) {
7105 7105
 				$error++;
7106 7106
 				$this->errors[] = $this->db->lasterror();
7107 7107
 			}
7108 7108
 		}
7109 7109
 
7110
-		if (! $error)
7110
+		if (!$error)
7111 7111
 		{
7112
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
7112
+			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
7113 7113
 		}
7114 7114
 
7115 7115
 		// Create extrafields
7116
-		if (! $error)
7116
+		if (!$error)
7117 7117
 		{
7118
-			$result=$this->insertExtraFields();
7118
+			$result = $this->insertExtraFields();
7119 7119
 			if ($result < 0) $error++;
7120 7120
 		}
7121 7121
 
7122 7122
 		// Triggers
7123
-		if (! $error && ! $notrigger)
7123
+		if (!$error && !$notrigger)
7124 7124
 		{
7125 7125
 			// Call triggers
7126
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_CREATE',$user);
7126
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_CREATE', $user);
7127 7127
 			if ($result < 0) { $error++; }
7128 7128
 			// End call triggers
7129 7129
 		}
@@ -7152,13 +7152,13 @@  discard block
 block discarded – undo
7152 7152
 		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7153 7153
 
7154 7154
 		$sql = 'SELECT '.$this->getFieldList();
7155
-		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7155
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7156 7156
 
7157
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7158
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7159
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7160
-		if ($morewhere)   $sql.= $morewhere;
7161
-		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7157
+		if (!empty($id))  $sql .= ' WHERE rowid = '.$id;
7158
+		elseif (!empty($ref)) $sql .= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7159
+		else $sql .= ' WHERE 1 = 1'; // usage with empty id and empty ref is very rare
7160
+		if ($morewhere)   $sql .= $morewhere;
7161
+		$sql .= ' LIMIT 1'; // This is a fetch, to be sure to get only one record
7162 7162
 
7163 7163
 		$res = $this->db->query($sql);
7164 7164
 		if ($res)
@@ -7195,14 +7195,14 @@  discard block
 block discarded – undo
7195 7195
 
7196 7196
 		$error = 0;
7197 7197
 
7198
-		$now=dol_now();
7198
+		$now = dol_now();
7199 7199
 
7200 7200
 		$fieldvalues = $this->setSaveQuery();
7201
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7202
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7203
-		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7201
+		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification'] = $this->db->idate($now);
7202
+		if (array_key_exists('fk_user_modif', $fieldvalues) && !($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif'] = $user->id;
7203
+		unset($fieldvalues['rowid']); // The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7204 7204
 
7205
-		$keys=array();
7205
+		$keys = array();
7206 7206
 		$values = array();
7207 7207
 		foreach ($fieldvalues as $k => $v) {
7208 7208
 			$keys[$k] = $k;
@@ -7212,10 +7212,10 @@  discard block
 block discarded – undo
7212 7212
 		}
7213 7213
 
7214 7214
 		// Clean and check mandatory
7215
-		foreach($keys as $key)
7215
+		foreach ($keys as $key)
7216 7216
 		{
7217
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7218
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7217
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key] = ''; // This is an implicit foreign key field
7218
+			if (!empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key] = ''; // This is an explicit foreign key field
7219 7219
 
7220 7220
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7221 7221
 			/*
@@ -7226,13 +7226,13 @@  discard block
 block discarded – undo
7226 7226
 			}*/
7227 7227
 		}
7228 7228
 
7229
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode( ',', $tmp ).' WHERE rowid='.$this->id ;
7229
+		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element.' SET '.implode(',', $tmp).' WHERE rowid='.$this->id;
7230 7230
 
7231 7231
 		$this->db->begin();
7232
-		if (! $error)
7232
+		if (!$error)
7233 7233
 		{
7234 7234
 			$res = $this->db->query($sql);
7235
-			if ($res===false)
7235
+			if ($res === false)
7236 7236
 			{
7237 7237
 				$error++;
7238 7238
 				$this->errors[] = $this->db->lasterror();
@@ -7240,9 +7240,9 @@  discard block
 block discarded – undo
7240 7240
 		}
7241 7241
 
7242 7242
 		// Update extrafield
7243
-		if (! $error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options)>0)
7243
+		if (!$error && empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && is_array($this->array_options) && count($this->array_options) > 0)
7244 7244
 		{
7245
-			$result=$this->insertExtraFields();
7245
+			$result = $this->insertExtraFields();
7246 7246
 			if ($result < 0)
7247 7247
 			{
7248 7248
 				$error++;
@@ -7250,10 +7250,10 @@  discard block
 block discarded – undo
7250 7250
 		}
7251 7251
 
7252 7252
 		// Triggers
7253
-		if (! $error && ! $notrigger)
7253
+		if (!$error && !$notrigger)
7254 7254
 		{
7255 7255
 			// Call triggers
7256
-			$result=$this->call_trigger(strtoupper(get_class($this)).'_MODIFY',$user);
7256
+			$result = $this->call_trigger(strtoupper(get_class($this)).'_MODIFY', $user);
7257 7257
 			if ($result < 0) { $error++; } //Do also here what you must do to rollback action if trigger fail
7258 7258
 			// End call triggers
7259 7259
 		}
@@ -7276,68 +7276,68 @@  discard block
 block discarded – undo
7276 7276
 	 * @param	int		$forcechilddeletion		0=no, 1=Force deletion of children
7277 7277
 	 * @return 	int             				<=0 if KO, >0 if OK
7278 7278
 	 */
7279
-	public function deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
7279
+	public function deleteCommon(User $user, $notrigger = false, $forcechilddeletion = 0)
7280 7280
 	{
7281
-		$error=0;
7281
+		$error = 0;
7282 7282
 
7283 7283
 		$this->db->begin();
7284 7284
 
7285 7285
 		if ($forcechilddeletion)
7286 7286
 		{
7287
-			foreach($this->childtables as $table)
7287
+			foreach ($this->childtables as $table)
7288 7288
 			{
7289 7289
 				$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$table.' WHERE '.$this->fk_element.' = '.$this->id;
7290 7290
 				$resql = $this->db->query($sql);
7291
-				if (! $resql)
7291
+				if (!$resql)
7292 7292
 				{
7293
-					$this->error=$this->db->lasterror();
7294
-					$this->errors[]=$this->error;
7293
+					$this->error = $this->db->lasterror();
7294
+					$this->errors[] = $this->error;
7295 7295
 					$this->db->rollback();
7296 7296
 					return -1;
7297 7297
 				}
7298 7298
 			}
7299 7299
 		}
7300
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7300
+		elseif (!empty($this->fk_element) && !empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7301 7301
 		{
7302 7302
 			$objectisused = $this->isObjectUsed($this->id);
7303
-			if (! empty($objectisused))
7303
+			if (!empty($objectisused))
7304 7304
 			{
7305 7305
 				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
7306
-				$this->error='ErrorRecordHasChildren';
7307
-				$this->errors[]=$this->error;
7306
+				$this->error = 'ErrorRecordHasChildren';
7307
+				$this->errors[] = $this->error;
7308 7308
 				$this->db->rollback();
7309 7309
 				return 0;
7310 7310
 			}
7311 7311
 		}
7312 7312
 
7313
-		if (! $error) {
7314
-			if (! $notrigger) {
7313
+		if (!$error) {
7314
+			if (!$notrigger) {
7315 7315
 				// Call triggers
7316
-				$result=$this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7316
+				$result = $this->call_trigger(strtoupper(get_class($this)).'_DELETE', $user);
7317 7317
 				if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail
7318 7318
 				// End call triggers
7319 7319
 			}
7320 7320
 		}
7321 7321
 
7322
-		if (! $error && ! empty($this->isextrafieldmanaged))
7322
+		if (!$error && !empty($this->isextrafieldmanaged))
7323 7323
 		{
7324
-			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element."_extrafields";
7325
-			$sql.= " WHERE fk_object=" . $this->id;
7324
+			$sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element."_extrafields";
7325
+			$sql .= " WHERE fk_object=".$this->id;
7326 7326
 
7327 7327
 			$resql = $this->db->query($sql);
7328
-			if (! $resql)
7328
+			if (!$resql)
7329 7329
 			{
7330 7330
 				$this->errors[] = $this->db->lasterror();
7331 7331
 				$error++;
7332 7332
 			}
7333 7333
 		}
7334 7334
 
7335
-		if (! $error)
7335
+		if (!$error)
7336 7336
 		{
7337 7337
 			$sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id;
7338 7338
 
7339 7339
 			$res = $this->db->query($sql);
7340
-			if($res===false) {
7340
+			if ($res === false) {
7341 7341
 				$error++;
7342 7342
 				$this->errors[] = $this->db->lasterror();
7343 7343
 			}
@@ -7378,9 +7378,9 @@  discard block
 block discarded – undo
7378 7378
 		require_once DOL_DOCUMENT_ROOT.'/core/class/comment.class.php';
7379 7379
 
7380 7380
 		$comment = new Comment($this->db);
7381
-		$result=$comment->fetchAllFor($this->element, $this->id);
7382
-		if ($result<0) {
7383
-			$this->errors=array_merge($this->errors, $comment->errors);
7381
+		$result = $comment->fetchAllFor($this->element, $this->id);
7382
+		if ($result < 0) {
7383
+			$this->errors = array_merge($this->errors, $comment->errors);
7384 7384
 			return -1;
7385 7385
 		} else {
7386 7386
 			$this->comments = $comment->comments;
Please login to merge, or discard this patch.
Braces   +1380 added lines, -847 removed lines patch added patch discarded remove patch
@@ -401,23 +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) $sql.= " AND entity = ".$conf->entity;
415
+		if ($ref || $ref_ext) {
416
+		    $sql.= " AND entity = ".$conf->entity;
417
+		}
413 418
 
414 419
 		dol_syslog(get_class()."::isExistingObject", LOG_DEBUG);
415 420
 		$resql = $db->query($sql);
416 421
 		if ($resql)
417 422
 		{
418 423
 			$num=$db->num_rows($resql);
419
-			if ($num > 0) return 1;
420
-			else return 0;
424
+			if ($num > 0) {
425
+			    return 1;
426
+			} else {
427
+			    return 0;
428
+			}
421 429
 		}
422 430
 		return -1;
423 431
 	}
@@ -446,13 +454,18 @@  discard block
 block discarded – undo
446 454
 		//print "lastname=".$this->lastname." name=".$this->name." nom=".$this->nom."<br>\n";
447 455
 		$lastname=$this->lastname;
448 456
 		$firstname=$this->firstname;
449
-		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
+		}
450 460
 
451 461
 		$ret='';
452 462
 		if ($option && $this->civility_id)
453 463
 		{
454
-			if ($langs->transnoentitiesnoconv("Civility".$this->civility_id)!="Civility".$this->civility_id) $ret.=$langs->transnoentitiesnoconv("Civility".$this->civility_id).' ';
455
-			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
+			}
456 469
 		}
457 470
 
458 471
 		$ret .= DolUtils::dolGetFirstLastname($firstname, $lastname, $nameorder);
@@ -545,14 +558,15 @@  discard block
 block discarded – undo
545 558
 		{
546 559
             if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 && $this->region) {
547 560
                 $out.=($outdone?' - ':'').$this->region.' - '.$this->state;
548
-            }
549
-            else {
561
+            } else {
550 562
                 $out.=($outdone?' - ':'').$this->state;
551 563
             }
552 564
 			$outdone++;
553 565
 		}
554 566
 
555
-		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>':'');
567
+		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)) {
568
+		    $out.=($outdone?'<br>':'');
569
+		}
556 570
 		if (! empty($this->phone) && empty($this->phone_pro)) {		// For objects that store pro phone into ->phone
557 571
 			$out.=dol_print_phone($this->phone,$this->country_code,$contactid,$thirdpartyid,'AC_TEL','&nbsp;','phone',$langs->trans("PhonePro")); $outdone++;
558 572
 		}
@@ -593,13 +607,21 @@  discard block
 block discarded – undo
593 607
 		$out.='<div style="clear: both;">';
594 608
 		if (! empty($conf->socialnetworks->enabled))
595 609
 		{
596
-			if ($this->skype) $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
610
+			if ($this->skype) {
611
+			    $out.=dol_print_socialnetworks($this->skype,$this->id,$object->id,'skype');
612
+			}
597 613
 			$outdone++;
598
-			if ($this->jabberid) $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
614
+			if ($this->jabberid) {
615
+			    $out.=dol_print_socialnetworks($this->jabberid,$this->id,$object->id,'jabber');
616
+			}
599 617
 			$outdone++;
600
-			if ($this->twitter) $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
618
+			if ($this->twitter) {
619
+			    $out.=dol_print_socialnetworks($this->twitter,$this->id,$object->id,'twitter');
620
+			}
601 621
 			$outdone++;
602
-			if ($this->facebook) $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
622
+			if ($this->facebook) {
623
+			    $out.=dol_print_socialnetworks($this->facebook,$this->id,$object->id,'facebook');
624
+			}
603 625
 			$outdone++;
604 626
 		}
605 627
 		$out.='</div>';
@@ -659,10 +681,10 @@  discard block
 block discarded – undo
659 681
 					$this->errors = $ecmfile->errors;
660 682
 				}
661 683
 				*/
662
-			}
663
-			else return '';
664
-		}
665
-		elseif (empty($ecmfile->share))
684
+			} else {
685
+			    return '';
686
+			}
687
+		} elseif (empty($ecmfile->share))
666 688
 		{
667 689
 			// Add entry into index
668 690
 			if ($initsharekey)
@@ -670,8 +692,9 @@  discard block
 block discarded – undo
670 692
 				require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
671 693
 				$ecmfile->share = getRandomPassword(true);
672 694
 				$ecmfile->update($user);
673
-			}
674
-			else return '';
695
+			} else {
696
+			    return '';
697
+			}
675 698
 		}
676 699
 
677 700
 		// Define $urlwithroot
@@ -685,14 +708,18 @@  discard block
 block discarded – undo
685 708
 		//if (! empty($modulepart)) $paramlink.=($paramlink?'&':'').'modulepart='.$modulepart;		// For sharing with hash (so public files), modulepart is not required.
686 709
 		//if (! empty($ecmfile->entity)) $paramlink.='&entity='.$ecmfile->entity; 					// For sharing with hash (so public files), entity is not required.
687 710
 		//$paramlink.=($paramlink?'&':'').'file='.urlencode($filepath);								// No need of name of file for public link, we will use the hash
688
-		if (! empty($ecmfile->share)) $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;			// Hash for public share
689
-		if ($forcedownload) $paramlink.=($paramlink?'&':'').'attachment=1';
711
+		if (! empty($ecmfile->share)) {
712
+		    $paramlink.=($paramlink?'&':'').'hashp='.$ecmfile->share;
713
+		}
714
+		// Hash for public share
715
+		if ($forcedownload) {
716
+		    $paramlink.=($paramlink?'&':'').'attachment=1';
717
+		}
690 718
 
691 719
 		if ($relativelink)
692 720
 		{
693 721
 			$linktoreturn='document.php'.($paramlink?'?'.$paramlink:'');
694
-		}
695
-		else
722
+		} else
696 723
 		{
697 724
 			$linktoreturn=$urlwithroot.'/document.php'.($paramlink?'?'.$paramlink:'');
698 725
 		}
@@ -740,8 +767,7 @@  discard block
 block discarded – undo
740 767
 		if (is_numeric($type_contact))
741 768
 		{
742 769
 			$id_type_contact=$type_contact;
743
-		}
744
-		else
770
+		} else
745 771
 		{
746 772
 			// We look for id type_contact
747 773
 			$sql = "SELECT tc.rowid";
@@ -754,7 +780,9 @@  discard block
 block discarded – undo
754 780
 			if ($resql)
755 781
 			{
756 782
 				$obj = $this->db->fetch_object($resql);
757
-				if ($obj) $id_type_contact=$obj->rowid;
783
+				if ($obj) {
784
+				    $id_type_contact=$obj->rowid;
785
+				}
758 786
 			}
759 787
 		}
760 788
 
@@ -806,8 +834,7 @@  discard block
 block discarded – undo
806 834
 
807 835
 				$this->db->commit();
808 836
 				return 1;
809
-			}
810
-			else
837
+			} else
811 838
 			{
812 839
 				if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
813 840
 				{
@@ -815,15 +842,16 @@  discard block
 block discarded – undo
815 842
 					$this->db->rollback();
816 843
 					echo 'err rollback';
817 844
 					return -2;
818
-				}
819
-				else
845
+				} else
820 846
 				{
821 847
 					$this->error=$this->db->error();
822 848
 					$this->db->rollback();
823 849
 					return -1;
824 850
 				}
825 851
 			}
826
-		} else return 0;
852
+		} else {
853
+		    return 0;
854
+		}
827 855
 	}
828 856
 
829 857
     // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
@@ -865,15 +893,18 @@  discard block
 block discarded – undo
865 893
 		// Insert into database
866 894
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_contact set";
867 895
 		$sql.= " statut = ".$statut;
868
-		if ($type_contact_id) $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
869
-		if ($fk_socpeople) $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
896
+		if ($type_contact_id) {
897
+		    $sql.= ", fk_c_type_contact = '".$type_contact_id ."'";
898
+		}
899
+		if ($fk_socpeople) {
900
+		    $sql.= ", fk_socpeople = '".$fk_socpeople ."'";
901
+		}
870 902
 		$sql.= " where rowid = ".$rowid;
871 903
 		$resql=$this->db->query($sql);
872 904
 		if ($resql)
873 905
 		{
874 906
 			return 0;
875
-		}
876
-		else
907
+		} else
877 908
 		{
878 909
 			$this->error=$this->db->lasterror();
879 910
 			return -1;
@@ -910,8 +941,7 @@  discard block
 block discarded – undo
910 941
 
911 942
 			$this->db->commit();
912 943
 			return 1;
913
-		}
914
-		else
944
+		} else
915 945
 		{
916 946
 			$this->error=$this->db->lasterror();
917 947
 			$this->db->rollback();
@@ -941,15 +971,15 @@  discard block
 block discarded – undo
941 971
 
942 972
 		$sql = "DELETE FROM ".MAIN_DB_PREFIX."element_contact";
943 973
 		$sql.= " WHERE element_id = ".$this->id;
944
-		if ($listId)
945
-			$sql.= " AND fk_c_type_contact IN (".$listId.")";
974
+		if ($listId) {
975
+					$sql.= " AND fk_c_type_contact IN (".$listId.")";
976
+		}
946 977
 
947 978
 		dol_syslog(get_class($this)."::delete_linked_contact", LOG_DEBUG);
948 979
 		if ($this->db->query($sql))
949 980
 		{
950 981
 			return 1;
951
-		}
952
-		else
982
+		} else
953 983
 		{
954 984
 			$this->error=$this->db->lasterror();
955 985
 			return -1;
@@ -974,22 +1004,38 @@  discard block
 block discarded – undo
974 1004
 		$tab=array();
975 1005
 
976 1006
 		$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
977
-		if ($source == 'internal') $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
978
-		if ($source == 'external' || $source == 'thirdparty') $sql.=", t.fk_soc as socid, t.statut as statuscontact";
1007
+		if ($source == 'internal') {
1008
+		    $sql.=", '-1' as socid, t.statut as statuscontact, t.login, t.photo";
1009
+		}
1010
+		if ($source == 'external' || $source == 'thirdparty') {
1011
+		    $sql.=", t.fk_soc as socid, t.statut as statuscontact";
1012
+		}
979 1013
 		$sql.= ", t.civility as civility, t.lastname as lastname, t.firstname, t.email";
980 1014
 		$sql.= ", tc.source, tc.element, tc.code, tc.libelle";
981 1015
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact tc";
982 1016
 		$sql.= ", ".MAIN_DB_PREFIX."element_contact ec";
983
-		if ($source == 'internal') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
984
-		if ($source == 'external'|| $source == 'thirdparty') $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
1017
+		if ($source == 'internal') {
1018
+		    $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."user t on ec.fk_socpeople = t.rowid";
1019
+		}
1020
+		if ($source == 'external'|| $source == 'thirdparty') {
1021
+		    $sql.=" LEFT JOIN ".MAIN_DB_PREFIX."socpeople t on ec.fk_socpeople = t.rowid";
1022
+		}
985 1023
 		$sql.= " WHERE ec.element_id =".$this->id;
986 1024
 		$sql.= " AND ec.fk_c_type_contact=tc.rowid";
987 1025
 		$sql.= " AND tc.element='".$this->db->escape($this->element)."'";
988
-		if ($code) $sql.= " AND tc.code = '".$this->db->escape($code)."'";
989
-		if ($source == 'internal') $sql.= " AND tc.source = 'internal'";
990
-		if ($source == 'external' || $source == 'thirdparty') $sql.= " AND tc.source = 'external'";
1026
+		if ($code) {
1027
+		    $sql.= " AND tc.code = '".$this->db->escape($code)."'";
1028
+		}
1029
+		if ($source == 'internal') {
1030
+		    $sql.= " AND tc.source = 'internal'";
1031
+		}
1032
+		if ($source == 'external' || $source == 'thirdparty') {
1033
+		    $sql.= " AND tc.source = 'external'";
1034
+		}
991 1035
 		$sql.= " AND tc.active=1";
992
-		if ($statut >= 0) $sql.= " AND ec.statut = '".$statut."'";
1036
+		if ($statut >= 0) {
1037
+		    $sql.= " AND ec.statut = '".$statut."'";
1038
+		}
993 1039
 		$sql.=" ORDER BY t.lastname ASC";
994 1040
 
995 1041
 		dol_syslog(get_class($this)."::liste_contact", LOG_DEBUG);
@@ -1010,8 +1056,7 @@  discard block
 block discarded – undo
1010 1056
 								   'nom'=>$obj->lastname,      // For backward compatibility
1011 1057
 								   'civility'=>$obj->civility, 'lastname'=>$obj->lastname, 'firstname'=>$obj->firstname, 'email'=>$obj->email, 'login'=>$obj->login, 'photo'=>$obj->photo, 'statuscontact'=>$obj->statuscontact,
1012 1058
 								   'rowid'=>$obj->rowid, 'code'=>$obj->code, 'libelle'=>$libelle_type, 'status'=>$obj->statuslink, 'fk_c_type_contact'=>$obj->fk_c_type_contact);
1013
-				}
1014
-				else
1059
+				} else
1015 1060
 				{
1016 1061
 					$tab[$i]=$obj->id;
1017 1062
 				}
@@ -1020,8 +1065,7 @@  discard block
 block discarded – undo
1020 1065
 			}
1021 1066
 
1022 1067
 			return $tab;
1023
-		}
1024
-		else
1068
+		} else
1025 1069
 		{
1026 1070
 			$this->error=$this->db->lasterror();
1027 1071
 			dol_print_error($this->db);
@@ -1056,8 +1100,7 @@  discard block
 block discarded – undo
1056 1100
 			$result = $this->update_contact($rowid, $newstatut);
1057 1101
 			$this->db->free($resql);
1058 1102
 			return $result;
1059
-		}
1060
-		else
1103
+		} else
1061 1104
 		{
1062 1105
 			$this->error=$this->db->error();
1063 1106
 			dol_print_error($this->db);
@@ -1081,16 +1124,27 @@  discard block
 block discarded – undo
1081 1124
         // phpcs:enable
1082 1125
 		global $langs;
1083 1126
 
1084
-		if (empty($order)) $order='position';
1085
-		if ($order == 'position') $order.=',code';
1127
+		if (empty($order)) {
1128
+		    $order='position';
1129
+		}
1130
+		if ($order == 'position') {
1131
+		    $order.=',code';
1132
+		}
1086 1133
 
1087 1134
 		$tab = array();
1088 1135
 		$sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
1089 1136
 		$sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
1090 1137
 		$sql.= " WHERE tc.element='".$this->db->escape($this->element)."'";
1091
-		if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
1092
-		if (! empty($source) && $source != 'all') $sql.= " AND tc.source='".$this->db->escape($source)."'";
1093
-		if (! empty($code)) $sql.= " AND tc.code='".$this->db->escape($code)."'";
1138
+		if ($activeonly == 1) {
1139
+		    $sql.= " AND tc.active=1";
1140
+		}
1141
+		// only the active types
1142
+		if (! empty($source) && $source != 'all') {
1143
+		    $sql.= " AND tc.source='".$this->db->escape($source)."'";
1144
+		}
1145
+		if (! empty($code)) {
1146
+		    $sql.= " AND tc.code='".$this->db->escape($code)."'";
1147
+		}
1094 1148
 		$sql.= $this->db->order($order,'ASC');
1095 1149
 
1096 1150
 		//print "sql=".$sql;
@@ -1105,13 +1159,15 @@  discard block
 block discarded – undo
1105 1159
 
1106 1160
 				$transkey="TypeContact_".$this->element."_".$source."_".$obj->code;
1107 1161
 				$libelle_type=($langs->trans($transkey)!=$transkey ? $langs->trans($transkey) : $obj->libelle);
1108
-				if (empty($option)) $tab[$obj->rowid]=$libelle_type;
1109
-				else $tab[$obj->code]=$libelle_type;
1162
+				if (empty($option)) {
1163
+				    $tab[$obj->rowid]=$libelle_type;
1164
+				} else {
1165
+				    $tab[$obj->code]=$libelle_type;
1166
+				}
1110 1167
 				$i++;
1111 1168
 			}
1112 1169
 			return $tab;
1113
-		}
1114
-		else
1170
+		} else
1115 1171
 		{
1116 1172
 			$this->error=$this->db->lasterror();
1117 1173
 			//dol_print_error($this->db);
@@ -1150,19 +1206,29 @@  discard block
 block discarded – undo
1150 1206
 
1151 1207
 		$sql = "SELECT ec.fk_socpeople";
1152 1208
 		$sql.= " FROM ".MAIN_DB_PREFIX."element_contact as ec,";
1153
-		if ($source == 'internal') $sql.= " ".MAIN_DB_PREFIX."user as c,";
1154
-		if ($source == 'external') $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1209
+		if ($source == 'internal') {
1210
+		    $sql.= " ".MAIN_DB_PREFIX."user as c,";
1211
+		}
1212
+		if ($source == 'external') {
1213
+		    $sql.= " ".MAIN_DB_PREFIX."socpeople as c,";
1214
+		}
1155 1215
 		$sql.= " ".MAIN_DB_PREFIX."c_type_contact as tc";
1156 1216
 		$sql.= " WHERE ec.element_id = ".$id;
1157 1217
 		$sql.= " AND ec.fk_socpeople = c.rowid";
1158
-		if ($source == 'internal') $sql.= " AND c.entity IN (".getEntity('user').")";
1159
-		if ($source == 'external') $sql.= " AND c.entity IN (".getEntity('societe').")";
1218
+		if ($source == 'internal') {
1219
+		    $sql.= " AND c.entity IN (".getEntity('user').")";
1220
+		}
1221
+		if ($source == 'external') {
1222
+		    $sql.= " AND c.entity IN (".getEntity('societe').")";
1223
+		}
1160 1224
 		$sql.= " AND ec.fk_c_type_contact = tc.rowid";
1161 1225
 		$sql.= " AND tc.element = '".$element."'";
1162 1226
 		$sql.= " AND tc.source = '".$source."'";
1163 1227
 		$sql.= " AND tc.code = '".$code."'";
1164 1228
 		$sql.= " AND tc.active = 1";
1165
-		if ($status) $sql.= " AND ec.statut = ".$status;
1229
+		if ($status) {
1230
+		    $sql.= " AND ec.statut = ".$status;
1231
+		}
1166 1232
 
1167 1233
 		dol_syslog(get_class($this)."::getIdContact", LOG_DEBUG);
1168 1234
 		$resql=$this->db->query($sql);
@@ -1173,8 +1239,7 @@  discard block
 block discarded – undo
1173 1239
 				$result[$i]=$obj->fk_socpeople;
1174 1240
 				$i++;
1175 1241
 			}
1176
-		}
1177
-		else
1242
+		} else
1178 1243
 		{
1179 1244
 			$this->error=$this->db->error();
1180 1245
 			return null;
@@ -1193,9 +1258,13 @@  discard block
 block discarded – undo
1193 1258
 	function fetch_contact($contactid=null)
1194 1259
 	{
1195 1260
         // phpcs:enable
1196
-		if (empty($contactid)) $contactid=$this->contactid;
1261
+		if (empty($contactid)) {
1262
+		    $contactid=$this->contactid;
1263
+		}
1197 1264
 
1198
-		if (empty($contactid)) return 0;
1265
+		if (empty($contactid)) {
1266
+		    return 0;
1267
+		}
1199 1268
 
1200 1269
 		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
1201 1270
 		$contact = new Contact($this->db);
@@ -1216,14 +1285,16 @@  discard block
 block discarded – undo
1216 1285
         // phpcs:enable
1217 1286
 		global $conf;
1218 1287
 
1219
-		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id))
1220
-			return 0;
1288
+		if (empty($this->socid) && empty($this->fk_soc) && empty($this->fk_thirdparty) && empty($force_thirdparty_id)) {
1289
+					return 0;
1290
+		}
1221 1291
 
1222 1292
 		require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
1223 1293
 
1224 1294
 		$idtofetch = isset($this->socid) ? $this->socid : (isset($this->fk_soc) ? $this->fk_soc : $this->fk_thirdparty);
1225
-		if ($force_thirdparty_id)
1226
-			$idtofetch = $force_thirdparty_id;
1295
+		if ($force_thirdparty_id) {
1296
+					$idtofetch = $force_thirdparty_id;
1297
+		}
1227 1298
 
1228 1299
 		if ($idtofetch) {
1229 1300
 			$thirdparty = new Societe($this->db);
@@ -1236,8 +1307,9 @@  discard block
 block discarded – undo
1236 1307
 			}
1237 1308
 
1238 1309
 			return $result;
1239
-		} else
1240
-			return -1;
1310
+		} else {
1311
+					return -1;
1312
+		}
1241 1313
 	}
1242 1314
 
1243 1315
 
@@ -1283,18 +1355,24 @@  discard block
 block discarded – undo
1283 1355
 		dol_syslog(get_class($this).'::fetch_barcode this->element='.$this->element.' this->barcode_type='.$this->barcode_type);
1284 1356
 
1285 1357
 		$idtype=$this->barcode_type;
1286
-		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
1358
+		if (empty($idtype) && $idtype != '0') {
1359
+		    // If type of barcode no set, we try to guess. If set to '0' it means we forced to have type remain not defined
1287 1360
 		{
1288
-			if ($this->element == 'product')      $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1289
-			else if ($this->element == 'societe') $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1290
-			else dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1361
+			if ($this->element == 'product')      $idtype = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
1362
+		} else if ($this->element == 'societe') {
1363
+			    $idtype = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
1364
+			} else {
1365
+			    dol_syslog('Call fetch_barcode with barcode_type not defined and cant be guessed', LOG_WARNING);
1366
+			}
1291 1367
 		}
1292 1368
 
1293 1369
 		if ($idtype > 0)
1294 1370
 		{
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
1371
+			if (empty($this->barcode_type) || empty($this->barcode_type_code) || empty($this->barcode_type_label) || empty($this->barcode_type_coder)) {
1372
+			    // If data not already loaded
1296 1373
 			{
1297
-				$sql = "SELECT rowid, code, libelle as label, coder";
1374
+				$sql = "SELECT rowid, code, libelle as label, coder";
1375
+			}
1298 1376
 				$sql.= " FROM ".MAIN_DB_PREFIX."c_barcode_type";
1299 1377
 				$sql.= " WHERE rowid = ".$idtype;
1300 1378
 				dol_syslog(get_class($this).'::fetch_barcode', LOG_DEBUG);
@@ -1307,8 +1385,7 @@  discard block
 block discarded – undo
1307 1385
 					$this->barcode_type_label = $obj->label;
1308 1386
 					$this->barcode_type_coder = $obj->coder;
1309 1387
 					return 1;
1310
-				}
1311
-				else
1388
+				} else
1312 1389
 				{
1313 1390
 					dol_print_error($this->db);
1314 1391
 					return -1;
@@ -1329,8 +1406,13 @@  discard block
 block discarded – undo
1329 1406
         // phpcs:enable
1330 1407
 		include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1331 1408
 
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;
1409
+		if (empty($this->fk_project) && ! empty($this->fk_projet)) {
1410
+		    $this->fk_project = $this->fk_projet;
1411
+		}
1412
+		// For backward compatibility
1413
+		if (empty($this->fk_project)) {
1414
+		    return 0;
1415
+		}
1334 1416
 
1335 1417
 		$project = new Project($this->db);
1336 1418
 		$result = $project->fetch($this->fk_project);
@@ -1351,7 +1433,9 @@  discard block
 block discarded – undo
1351 1433
         // phpcs:enable
1352 1434
 		include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1353 1435
 
1354
-		if (empty($this->fk_product)) return 0;
1436
+		if (empty($this->fk_product)) {
1437
+		    return 0;
1438
+		}
1355 1439
 
1356 1440
 		$product = new Product($this->db);
1357 1441
 		$result = $product->fetch($this->fk_product);
@@ -1385,9 +1469,15 @@  discard block
 block discarded – undo
1385 1469
 	function fetch_origin()
1386 1470
 	{
1387 1471
         // 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';
1472
+		if ($this->origin == 'shipping') {
1473
+		    $this->origin = 'expedition';
1474
+		}
1475
+		if ($this->origin == 'delivery') {
1476
+		    $this->origin = 'livraison';
1477
+		}
1478
+        if ($this->origin == 'order_supplier') {
1479
+            $this->origin = 'commandeFournisseur';
1480
+        }
1391 1481
 
1392 1482
 		$origin = $this->origin;
1393 1483
 
@@ -1479,29 +1569,48 @@  discard block
 block discarded – undo
1479 1569
 	{
1480 1570
 		global $user,$langs,$conf;
1481 1571
 
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';
1572
+		if (empty($table)) {
1573
+		    $table=$this->table_element;
1574
+		}
1575
+		if (empty($id)) {
1576
+		    $id=$this->id;
1577
+		}
1578
+		if (empty($format)) {
1579
+		    $format='text';
1580
+		}
1581
+		if (empty($id_field)) {
1582
+		    $id_field='rowid';
1583
+		}
1486 1584
 
1487 1585
 		$error=0;
1488 1586
 
1489 1587
 		$this->db->begin();
1490 1588
 
1491 1589
 		// 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';
1590
+		if ($table == 'product' && $field == 'note_private') {
1591
+		    $field='note';
1592
+		}
1593
+		if (in_array($table, array('actioncomm', 'adherent', 'advtargetemailing', 'cronjob', 'establishment'))) {
1594
+		    $fk_user_field = 'fk_user_mod';
1595
+		}
1494 1596
 
1495 1597
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$table." SET ";
1496 1598
 
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");
1599
+		if ($format == 'text') {
1600
+		    $sql.= $field." = '".$this->db->escape($value)."'";
1601
+		} else if ($format == 'int') {
1602
+		    $sql.= $field." = ".$this->db->escape($value);
1603
+		} else if ($format == 'date') {
1604
+		    $sql.= $field." = ".($value ? "'".$this->db->idate($value)."'" : "null");
1605
+		}
1500 1606
 
1501 1607
 		if ($fk_user_field)
1502 1608
 		{
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;
1609
+			if (! empty($fuser) && is_object($fuser)) {
1610
+			    $sql.=", ".$fk_user_field." = ".$fuser->id;
1611
+			} elseif (empty($fuser) || $fuser != 'none') {
1612
+			    $sql.=", ".$fk_user_field." = ".$user->id;
1613
+			}
1505 1614
 		}
1506 1615
 
1507 1616
 		$sql.= " WHERE ".$id_field." = ".$id;
@@ -1516,28 +1625,32 @@  discard block
 block discarded – undo
1516 1625
 				if (empty($this->fields) && method_exists($this, 'fetch'))
1517 1626
 				{
1518 1627
 					$result = $this->fetch($id);
1519
-				}
1520
-				else
1628
+				} else
1521 1629
 				{
1522 1630
 					$result = $this->fetchCommon($id);
1523 1631
 				}
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++;
1632
+				if ($result >= 0) {
1633
+				    $result=$this->call_trigger($trigkey, (! empty($fuser) && is_object($fuser)) ? $fuser : $user);
1634
+				}
1635
+				// This may set this->errors
1636
+				if ($result < 0) {
1637
+				    $error++;
1638
+				}
1526 1639
 			}
1527 1640
 
1528 1641
 			if (! $error)
1529 1642
 			{
1530
-				if (property_exists($this, $field)) $this->$field = $value;
1643
+				if (property_exists($this, $field)) {
1644
+				    $this->$field = $value;
1645
+				}
1531 1646
 				$this->db->commit();
1532 1647
 				return 1;
1533
-			}
1534
-			else
1648
+			} else
1535 1649
 			{
1536 1650
 				$this->db->rollback();
1537 1651
 				return -2;
1538 1652
 			}
1539
-		}
1540
-		else
1653
+		} else
1541 1654
 		{
1542 1655
 			$this->error=$this->db->lasterror();
1543 1656
 			$this->db->rollback();
@@ -1564,36 +1677,66 @@  discard block
 block discarded – undo
1564 1677
 			dol_print_error('',get_class($this)."::load_previous_next_ref was called on objet with property table_element not defined");
1565 1678
 			return -1;
1566 1679
 		}
1567
-		if ($fieldid == 'none') return 1;
1680
+		if ($fieldid == 'none') {
1681
+		    return 1;
1682
+		}
1568 1683
 
1569 1684
 		// Security on socid
1570 1685
 		$socid = 0;
1571
-		if ($user->societe_id > 0) $socid = $user->societe_id;
1686
+		if ($user->societe_id > 0) {
1687
+		    $socid = $user->societe_id;
1688
+		}
1572 1689
 
1573 1690
 		// this->ismultientitymanaged contains
1574 1691
 		// 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
1575 1692
 		$alias = 's';
1576
-		if ($this->element == 'societe') $alias = 'te';
1693
+		if ($this->element == 'societe') {
1694
+		    $alias = 'te';
1695
+		}
1577 1696
 
1578 1697
 		$sql = "SELECT MAX(te.".$fieldid.")";
1579 1698
 		$sql.= " FROM ".(empty($nodbprefix)?MAIN_DB_PREFIX:'').$this->table_element." as te";
1580 1699
 		if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1581 1700
 			$sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1582 1701
 		}
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";
1702
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1703
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1704
+		}
1705
+		// If we need to link to societe to limit select to entity
1706
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1707
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1708
+		}
1709
+		// If we need to link to societe to limit select to socid
1710
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1711
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";
1712
+		}
1713
+		// If we need to link to societe to limit select to socid
1714
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
1715
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1716
+		}
1587 1717
 		$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)';
1718
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
1719
+		    $sql.= " AND sc.fk_user = " .$user->id;
1720
+		}
1721
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
1722
+		    $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1723
+		}
1590 1724
 		if (! empty($filter))
1591 1725
 		{
1592
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1726
+			if (! preg_match('/^\s*AND/i', $filter)) {
1727
+			    $sql.=" AND ";
1728
+			}
1729
+			// For backward compatibility
1593 1730
 			$sql.=$filter;
1594 1731
 		}
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
1732
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1733
+		    $sql.= ' AND te.fk_soc = s.rowid';
1734
+		}
1735
+		// If we need to link to societe to limit select to entity
1736
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1737
+		    $sql.= ' AND te.fk_soc = s.rowid';
1738
+		}
1739
+		// If we need to link to societe to limit select to socid
1597 1740
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1598 1741
 			if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1599 1742
 				if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
@@ -1606,9 +1749,15 @@  discard block
 block discarded – undo
1606 1749
 				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1607 1750
 			}
1608 1751
 		}
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;
1752
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
1753
+		    $sql.= ' AND te.fk_soc = ' . $socid;
1754
+		}
1755
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
1756
+		    $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1757
+		}
1758
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') {
1759
+		    $sql.= ' AND te.rowid = ' . $socid;
1760
+		}
1612 1761
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1613 1762
 
1614 1763
 		$result = $this->db->query($sql);
@@ -1626,20 +1775,44 @@  discard block
 block discarded – undo
1626 1775
 		if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1627 1776
 			$sql.= ",".MAIN_DB_PREFIX."usergroup_user as ug";
1628 1777
 		}
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";
1778
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1779
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1780
+		}
1781
+		// If we need to link to societe to limit select to entity
1782
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1783
+		    $sql.= ", ".MAIN_DB_PREFIX."societe as s";
1784
+		}
1785
+		// If we need to link to societe to limit select to socid
1786
+		else if ($this->restrictiononfksoc == 2 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1787
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON te.fk_soc = s.rowid";
1788
+		}
1789
+		// If we need to link to societe to limit select to socid
1790
+		if ($this->restrictiononfksoc && !$user->rights->societe->client->voir && !$socid) {
1791
+		    $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON ".$alias.".rowid = sc.fk_soc";
1792
+		}
1633 1793
 		$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)';
1794
+		if ($this->restrictiononfksoc == 1 && !$user->rights->societe->client->voir && !$socid) {
1795
+		    $sql.= " AND sc.fk_user = " .$user->id;
1796
+		}
1797
+		if ($this->restrictiononfksoc == 2 && !$user->rights->societe->client->voir && !$socid) {
1798
+		    $sql.= " AND (sc.fk_user = " .$user->id.' OR te.fk_soc IS NULL)';
1799
+		}
1636 1800
 		if (! empty($filter))
1637 1801
 		{
1638
-			if (! preg_match('/^\s*AND/i', $filter)) $sql.=" AND ";   // For backward compatibility
1802
+			if (! preg_match('/^\s*AND/i', $filter)) {
1803
+			    $sql.=" AND ";
1804
+			}
1805
+			// For backward compatibility
1639 1806
 			$sql.=$filter;
1640 1807
 		}
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
1808
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 2) {
1809
+		    $sql.= ' AND te.fk_soc = s.rowid';
1810
+		}
1811
+		// If we need to link to societe to limit select to entity
1812
+		else if ($this->restrictiononfksoc == 1 && $this->element != 'societe' && !$user->rights->societe->client->voir && !$socid) {
1813
+		    $sql.= ' AND te.fk_soc = s.rowid';
1814
+		}
1815
+		// If we need to link to societe to limit select to socid
1643 1816
 		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1644 1817
 			if ($this->element == 'user' && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
1645 1818
 				if (! empty($user->admin) && empty($user->entity) && $conf->entity == 1) {
@@ -1652,9 +1825,15 @@  discard block
 block discarded – undo
1652 1825
 				$sql.= ' AND te.entity IN ('.getEntity($this->element).')';
1653 1826
 			}
1654 1827
 		}
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;
1828
+		if ($this->restrictiononfksoc == 1 && $socid && $this->element != 'societe') {
1829
+		    $sql.= ' AND te.fk_soc = ' . $socid;
1830
+		}
1831
+		if ($this->restrictiononfksoc == 2 && $socid && $this->element != 'societe') {
1832
+		    $sql.= ' AND (te.fk_soc = ' . $socid.' OR te.fk_soc IS NULL)';
1833
+		}
1834
+		if ($this->restrictiononfksoc && $socid && $this->element == 'societe') {
1835
+		    $sql.= ' AND te.rowid = ' . $socid;
1836
+		}
1658 1837
 		//print 'socid='.$socid.' restrictiononfksoc='.$this->restrictiononfksoc.' ismultientitymanaged = '.$this->ismultientitymanaged.' filter = '.$filter.' -> '.$sql."<br>";
1659 1838
 		// 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 1839
 
@@ -1686,8 +1865,11 @@  discard block
 block discarded – undo
1686 1865
 		$i = 0;
1687 1866
 		while ($i < $num)
1688 1867
 		{
1689
-			if ($source == 'thirdparty') $contactAlreadySelected[$i] = $tab[$i]['socid'];
1690
-			else  $contactAlreadySelected[$i] = $tab[$i]['id'];
1868
+			if ($source == 'thirdparty') {
1869
+			    $contactAlreadySelected[$i] = $tab[$i]['socid'];
1870
+			} else {
1871
+			    $contactAlreadySelected[$i] = $tab[$i]['id'];
1872
+			}
1691 1873
 			$i++;
1692 1874
 		}
1693 1875
 		return $contactAlreadySelected;
@@ -1711,14 +1893,19 @@  discard block
 block discarded – undo
1711 1893
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1712 1894
 		if ($this->table_element == 'actioncomm')
1713 1895
 		{
1714
-			if ($projectid) $sql.= ' SET fk_project = '.$projectid;
1715
-			else $sql.= ' SET fk_project = NULL';
1896
+			if ($projectid) {
1897
+			    $sql.= ' SET fk_project = '.$projectid;
1898
+			} else {
1899
+			    $sql.= ' SET fk_project = NULL';
1900
+			}
1716 1901
 			$sql.= ' WHERE id = '.$this->id;
1717
-		}
1718
-		else
1902
+		} else
1719 1903
 		{
1720
-			if ($projectid) $sql.= ' SET fk_projet = '.$projectid;
1721
-			else $sql.= ' SET fk_projet = NULL';
1904
+			if ($projectid) {
1905
+			    $sql.= ' SET fk_projet = '.$projectid;
1906
+			} else {
1907
+			    $sql.= ' SET fk_projet = NULL';
1908
+			}
1722 1909
 			$sql.= ' WHERE rowid = '.$this->id;
1723 1910
 		}
1724 1911
 
@@ -1727,8 +1914,7 @@  discard block
 block discarded – undo
1727 1914
 		{
1728 1915
 			$this->fk_project = $projectid;
1729 1916
 			return 1;
1730
-		}
1731
-		else
1917
+		} else
1732 1918
 		{
1733 1919
 			dol_print_error($this->db);
1734 1920
 			return -1;
@@ -1748,8 +1934,12 @@  discard block
 block discarded – undo
1748 1934
 		{
1749 1935
 			// TODO uniformize field name
1750 1936
 			$fieldname = 'fk_mode_reglement';
1751
-			if ($this->element == 'societe') $fieldname = 'mode_reglement';
1752
-			if (get_class($this) == 'Fournisseur') $fieldname = 'mode_reglement_supplier';
1937
+			if ($this->element == 'societe') {
1938
+			    $fieldname = 'mode_reglement';
1939
+			}
1940
+			if (get_class($this) == 'Fournisseur') {
1941
+			    $fieldname = 'mode_reglement_supplier';
1942
+			}
1753 1943
 
1754 1944
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1755 1945
 			$sql .= ' SET '.$fieldname.' = '.$id;
@@ -1759,17 +1949,17 @@  discard block
 block discarded – undo
1759 1949
 			{
1760 1950
 				$this->mode_reglement_id = $id;
1761 1951
 				// for supplier
1762
-				if (get_class($this) == 'Fournisseur') $this->mode_reglement_supplier_id = $id;
1952
+				if (get_class($this) == 'Fournisseur') {
1953
+				    $this->mode_reglement_supplier_id = $id;
1954
+				}
1763 1955
 				return 1;
1764
-			}
1765
-			else
1956
+			} else
1766 1957
 			{
1767 1958
 				dol_syslog(get_class($this).'::setPaymentMethods Erreur '.$sql.' - '.$this->db->error());
1768 1959
 				$this->error=$this->db->error();
1769 1960
 				return -1;
1770 1961
 			}
1771
-		}
1772
-		else
1962
+		} else
1773 1963
 		{
1774 1964
 			dol_syslog(get_class($this).'::setPaymentMethods, status of the object is incompatible');
1775 1965
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1799,18 +1989,18 @@  discard block
 block discarded – undo
1799 1989
 				$this->multicurrency_code = $code;
1800 1990
 
1801 1991
 				list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
1802
-				if ($rate) $this->setMulticurrencyRate($rate,2);
1992
+				if ($rate) {
1993
+				    $this->setMulticurrencyRate($rate,2);
1994
+				}
1803 1995
 
1804 1996
 				return 1;
1805
-			}
1806
-			else
1997
+			} else
1807 1998
 			{
1808 1999
 				dol_syslog(get_class($this).'::setMulticurrencyCode Erreur '.$sql.' - '.$this->db->error());
1809 2000
 				$this->error=$this->db->error();
1810 2001
 				return -1;
1811 2002
 			}
1812
-		}
1813
-		else
2003
+		} else
1814 2004
 		{
1815 2005
 			dol_syslog(get_class($this).'::setMulticurrencyCode, status of the object is incompatible');
1816 2006
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1904,15 +2094,13 @@  discard block
 block discarded – undo
1904 2094
 				}
1905 2095
 
1906 2096
 				return 1;
1907
-			}
1908
-			else
2097
+			} else
1909 2098
 			{
1910 2099
 				dol_syslog(get_class($this).'::setMulticurrencyRate Erreur '.$sql.' - '.$this->db->error());
1911 2100
 				$this->error=$this->db->error();
1912 2101
 				return -1;
1913 2102
 			}
1914
-		}
1915
-		else
2103
+		} else
1916 2104
 		{
1917 2105
 			dol_syslog(get_class($this).'::setMulticurrencyRate, status of the object is incompatible');
1918 2106
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1933,8 +2121,12 @@  discard block
 block discarded – undo
1933 2121
 		{
1934 2122
 			// TODO uniformize field name
1935 2123
 			$fieldname = 'fk_cond_reglement';
1936
-			if ($this->element == 'societe') $fieldname = 'cond_reglement';
1937
-			if (get_class($this) == 'Fournisseur') $fieldname = 'cond_reglement_supplier';
2124
+			if ($this->element == 'societe') {
2125
+			    $fieldname = 'cond_reglement';
2126
+			}
2127
+			if (get_class($this) == 'Fournisseur') {
2128
+			    $fieldname = 'cond_reglement_supplier';
2129
+			}
1938 2130
 
1939 2131
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1940 2132
 			$sql .= ' SET '.$fieldname.' = '.$id;
@@ -1944,18 +2136,18 @@  discard block
 block discarded – undo
1944 2136
 			{
1945 2137
 				$this->cond_reglement_id = $id;
1946 2138
 				// for supplier
1947
-				if (get_class($this) == 'Fournisseur') $this->cond_reglement_supplier_id = $id;
2139
+				if (get_class($this) == 'Fournisseur') {
2140
+				    $this->cond_reglement_supplier_id = $id;
2141
+				}
1948 2142
 				$this->cond_reglement = $id;	// for compatibility
1949 2143
 				return 1;
1950
-			}
1951
-			else
2144
+			} else
1952 2145
 			{
1953 2146
 				dol_syslog(get_class($this).'::setPaymentTerms Erreur '.$sql.' - '.$this->db->error());
1954 2147
 				$this->error=$this->db->error();
1955 2148
 				return -1;
1956 2149
 			}
1957
-		}
1958
-		else
2150
+		} else
1959 2151
 		{
1960 2152
 			dol_syslog(get_class($this).'::setPaymentTerms, status of the object is incompatible');
1961 2153
 			$this->error='Status of the object is incompatible '.$this->statut;
@@ -1973,7 +2165,9 @@  discard block
 block discarded – undo
1973 2165
 	function setDeliveryAddress($id)
1974 2166
 	{
1975 2167
 		$fieldname = 'fk_delivery_address';
1976
-		if ($this->element == 'delivery' || $this->element == 'shipping') $fieldname = 'fk_address';
2168
+		if ($this->element == 'delivery' || $this->element == 'shipping') {
2169
+		    $fieldname = 'fk_address';
2170
+		}
1977 2171
 
1978 2172
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET ".$fieldname." = ".$id;
1979 2173
 		$sql.= " WHERE rowid = ".$this->id." AND fk_statut = 0";
@@ -1982,8 +2176,7 @@  discard block
 block discarded – undo
1982 2176
 		{
1983 2177
 			$this->fk_delivery_address = $id;
1984 2178
 			return 1;
1985
-		}
1986
-		else
2179
+		} else
1987 2180
 		{
1988 2181
 			$this->error=$this->db->error();
1989 2182
 			dol_syslog(get_class($this).'::setDeliveryAddress Erreur '.$sql.' - '.$this->error);
@@ -2005,7 +2198,9 @@  discard block
 block discarded – undo
2005 2198
 	{
2006 2199
         global $user;
2007 2200
 
2008
-        if (empty($userused)) $userused=$user;
2201
+        if (empty($userused)) {
2202
+            $userused=$user;
2203
+        }
2009 2204
 
2010 2205
         $error = 0;
2011 2206
 
@@ -2016,7 +2211,9 @@  discard block
 block discarded – undo
2016 2211
 
2017 2212
         $this->db->begin();
2018 2213
 
2019
-		if ($shipping_method_id<0) $shipping_method_id='NULL';
2214
+		if ($shipping_method_id<0) {
2215
+		    $shipping_method_id='NULL';
2216
+		}
2020 2217
 		dol_syslog(get_class($this).'::setShippingMethod('.$shipping_method_id.')');
2021 2218
 
2022 2219
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2033,7 +2230,9 @@  discard block
 block discarded – undo
2033 2230
                 // Call trigger
2034 2231
                 $this->context=array('shippingmethodupdate'=>1);
2035 2232
                 $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2036
-                if ($result < 0) $error++;
2233
+                if ($result < 0) {
2234
+                    $error++;
2235
+                }
2037 2236
                 // End call trigger
2038 2237
             }
2039 2238
         }
@@ -2061,7 +2260,9 @@  discard block
 block discarded – undo
2061 2260
 			dol_syslog(get_class($this)."::setWarehouse was called on objet with property table_element not defined",LOG_ERR);
2062 2261
 			return -1;
2063 2262
 		}
2064
-		if ($warehouse_id<0) $warehouse_id='NULL';
2263
+		if ($warehouse_id<0) {
2264
+		    $warehouse_id='NULL';
2265
+		}
2065 2266
 		dol_syslog(get_class($this).'::setWarehouse('.$warehouse_id.')');
2066 2267
 
2067 2268
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2108,8 +2309,7 @@  discard block
 block discarded – undo
2108 2309
 		{
2109 2310
 			$this->modelpdf=$modelpdf;
2110 2311
 			return 1;
2111
-		}
2112
-		else
2312
+		} else
2113 2313
 		{
2114 2314
 			dol_print_error($this->db);
2115 2315
 			return 0;
@@ -2129,7 +2329,9 @@  discard block
 block discarded – undo
2129 2329
 	{
2130 2330
         global $user;
2131 2331
 
2132
-        if (empty($userused)) $userused=$user;
2332
+        if (empty($userused)) {
2333
+            $userused=$user;
2334
+        }
2133 2335
 
2134 2336
         $error = 0;
2135 2337
 
@@ -2139,7 +2341,9 @@  discard block
 block discarded – undo
2139 2341
 		}
2140 2342
         $this->db->begin();
2141 2343
 
2142
-		if ($fk_account<0) $fk_account='NULL';
2344
+		if ($fk_account<0) {
2345
+		    $fk_account='NULL';
2346
+		}
2143 2347
 		dol_syslog(get_class($this).'::setBankAccount('.$fk_account.')');
2144 2348
 
2145 2349
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
@@ -2152,15 +2356,16 @@  discard block
 block discarded – undo
2152 2356
             dol_syslog(get_class($this).'::setBankAccount Error '.$sql.' - '.$this->db->error());
2153 2357
             $this->error = $this->db->lasterror();
2154 2358
             $error++;
2155
-        }
2156
-        else
2359
+        } else
2157 2360
         {
2158 2361
             if (!$notrigger)
2159 2362
             {
2160 2363
                 // Call trigger
2161 2364
                 $this->context=array('bankaccountupdate'=>1);
2162 2365
                 $result = $this->call_trigger(strtoupper(get_class($this)) . '_MODIFY', $userused);
2163
-                if ($result < 0) $error++;
2366
+                if ($result < 0) {
2367
+                    $error++;
2368
+                }
2164 2369
                 // End call trigger
2165 2370
             }
2166 2371
         }
@@ -2168,8 +2373,7 @@  discard block
 block discarded – undo
2168 2373
         {
2169 2374
             $this->db->rollback();
2170 2375
             return -1;
2171
-        }
2172
-        else
2376
+        } else
2173 2377
         {
2174 2378
             $this->fk_account = ($fk_account=='NULL')?null:$fk_account;
2175 2379
             $this->db->commit();
@@ -2208,8 +2412,12 @@  discard block
 block discarded – undo
2208 2412
 		$nl=0;
2209 2413
 		$sql = 'SELECT count(rowid) FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2210 2414
 		$sql.= ' WHERE '.$this->fk_element.'='.$this->id;
2211
-		if (! $renum) $sql.= ' AND rang = 0';
2212
-		if ($renum) $sql.= ' AND rang <> 0';
2415
+		if (! $renum) {
2416
+		    $sql.= ' AND rang = 0';
2417
+		}
2418
+		if ($renum) {
2419
+		    $sql.= ' AND rang <> 0';
2420
+		}
2213 2421
 
2214 2422
 		dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
2215 2423
 		$resql = $this->db->query($sql);
@@ -2217,8 +2425,9 @@  discard block
 block discarded – undo
2217 2425
 		{
2218 2426
 			$row = $this->db->fetch_row($resql);
2219 2427
 			$nl = $row[0];
2220
-		}
2221
-		else dol_print_error($this->db);
2428
+		} else {
2429
+		    dol_print_error($this->db);
2430
+		}
2222 2431
 		if ($nl > 0)
2223 2432
 		{
2224 2433
 			// The goal of this part is to reorder all lines, with all children lines sharing the same
@@ -2228,7 +2437,9 @@  discard block
 block discarded – undo
2228 2437
 			// We first search all lines that are parent lines (for multilevel details lines)
2229 2438
 			$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2230 2439
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2231
-			if ($fk_parent_line) $sql.= ' AND fk_parent_line IS NULL';
2440
+			if ($fk_parent_line) {
2441
+			    $sql.= ' AND fk_parent_line IS NULL';
2442
+			}
2232 2443
 			$sql.= ' ORDER BY rang ASC, rowid '.$rowidorder;
2233 2444
 
2234 2445
 			dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
@@ -2260,8 +2471,7 @@  discard block
 block discarded – undo
2260 2471
 						$this->updateRangOfLine($row, ($key+1));
2261 2472
 					}
2262 2473
 				}
2263
-			}
2264
-			else
2474
+			} else
2265 2475
 			{
2266 2476
 				dol_print_error($this->db);
2267 2477
 			}
@@ -2354,7 +2564,9 @@  discard block
 block discarded – undo
2354 2564
 	function updateRangOfLine($rowid,$rang)
2355 2565
 	{
2356 2566
 		$fieldposition = 'rang';
2357
-		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2567
+		if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2568
+		    $fieldposition = 'position';
2569
+		}
2358 2570
 
2359 2571
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2360 2572
 		$sql.= ' WHERE rowid = '.$rowid;
@@ -2395,7 +2607,9 @@  discard block
 block discarded – undo
2395 2607
 		if ($rang > 1)
2396 2608
 		{
2397 2609
 			$fieldposition = 'rang';
2398
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2610
+			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2611
+			    $fieldposition = 'position';
2612
+			}
2399 2613
 
2400 2614
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang ;
2401 2615
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
@@ -2408,8 +2622,7 @@  discard block
 block discarded – undo
2408 2622
 				{
2409 2623
 					dol_print_error($this->db);
2410 2624
 				}
2411
-			}
2412
-			else
2625
+			} else
2413 2626
 			{
2414 2627
 				dol_print_error($this->db);
2415 2628
 			}
@@ -2429,7 +2642,9 @@  discard block
 block discarded – undo
2429 2642
 		if ($rang < $max)
2430 2643
 		{
2431 2644
 			$fieldposition = 'rang';
2432
-			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) $fieldposition = 'position';
2645
+			if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
2646
+			    $fieldposition = 'position';
2647
+			}
2433 2648
 
2434 2649
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element_line.' SET '.$fieldposition.' = '.$rang;
2435 2650
 			$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
@@ -2442,8 +2657,7 @@  discard block
 block discarded – undo
2442 2657
 				{
2443 2658
 					dol_print_error($this->db);
2444 2659
 				}
2445
-			}
2446
-			else
2660
+			} else
2447 2661
 			{
2448 2662
 				dol_print_error($this->db);
2449 2663
 			}
@@ -2514,8 +2728,7 @@  discard block
 block discarded – undo
2514 2728
 				if (! empty($row[0]))
2515 2729
 				{
2516 2730
 					return $row[0];
2517
-				}
2518
-				else
2731
+				} else
2519 2732
 				{
2520 2733
 					return $this->getRangOfLine($fk_parent_line);
2521 2734
 				}
@@ -2562,8 +2775,7 @@  discard block
 block discarded – undo
2562 2775
 		{
2563 2776
 			$this->ref_ext = $ref_ext;
2564 2777
 			return 1;
2565
-		}
2566
-		else
2778
+		} else
2567 2779
 		{
2568 2780
 			$this->error=$this->db->error();
2569 2781
 			return -1;
@@ -2597,7 +2809,9 @@  discard block
 block discarded – undo
2597 2809
 		}
2598 2810
 		// Special cas
2599 2811
 		//var_dump($this->table_element);exit;
2600
-		if ($this->table_element == 'product') $suffix='';
2812
+		if ($this->table_element == 'product') {
2813
+		    $suffix='';
2814
+		}
2601 2815
 
2602 2816
 		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
2603 2817
 		$sql.= " SET note".$suffix." = ".(!empty($note)?("'".$this->db->escape($note)."'"):"NULL");
@@ -2607,16 +2821,17 @@  discard block
 block discarded – undo
2607 2821
 		dol_syslog(get_class($this)."::update_note", LOG_DEBUG);
2608 2822
 		if ($this->db->query($sql))
2609 2823
 		{
2610
-			if ($suffix == '_public') $this->note_public = $note;
2611
-			else if ($suffix == '_private') $this->note_private = $note;
2612
-			else
2824
+			if ($suffix == '_public') {
2825
+			    $this->note_public = $note;
2826
+			} else if ($suffix == '_private') {
2827
+			    $this->note_private = $note;
2828
+			} else
2613 2829
 			{
2614 2830
 				$this->note = $note;      // deprecated
2615 2831
 				$this->note_private = $note;
2616 2832
 			}
2617 2833
 			return 1;
2618
-		}
2619
-		else
2834
+		} else
2620 2835
 		{
2621 2836
 			$this->error=$this->db->lasterror();
2622 2837
 			return -1;
@@ -2656,36 +2871,45 @@  discard block
 block discarded – undo
2656 2871
 
2657 2872
 		// Some external module want no update price after a trigger because they have another method to calculate the total (ex: with an extrafield)
2658 2873
 		$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";
2874
+		if ($this->element == 'propal') {
2875
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_PROPOSAL";
2876
+		} elseif ($this->element == 'order') {
2877
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_ORDER";
2878
+		} elseif ($this->element == 'facture') {
2879
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_INVOICE";
2880
+		} elseif ($this->element == 'facture_fourn') {
2881
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_INVOICE";
2882
+		} elseif ($this->element == 'order_supplier') {
2883
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_ORDER";
2884
+		} elseif ($this->element == 'supplier_proposal') {
2885
+					$MODULE = "MODULE_DISALLOW_UPDATE_PRICE_SUPPLIER_PROPOSAL";
2886
+		}
2671 2887
 
2672 2888
 		if (! empty($MODULE)) {
2673 2889
 			if (! empty($conf->global->$MODULE)) {
2674 2890
 				$modsactivated = explode(',', $conf->global->$MODULE);
2675 2891
 				foreach ($modsactivated as $mod) {
2676
-					if ($conf->$mod->enabled)
2677
-						return 1; // update was disabled by specific setup
2892
+					if ($conf->$mod->enabled) {
2893
+											return 1;
2894
+					}
2895
+					// update was disabled by specific setup
2678 2896
 				}
2679 2897
 			}
2680 2898
 		}
2681 2899
 
2682 2900
 		include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
2683 2901
 
2684
-		if ($roundingadjust == '-1') $roundingadjust='auto';	// For backward compatibility
2902
+		if ($roundingadjust == '-1') {
2903
+		    $roundingadjust='auto';
2904
+		}
2905
+		// For backward compatibility
2685 2906
 
2686 2907
 		$forcedroundingmode=$roundingadjust;
2687
-		if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2688
-		elseif ($forcedroundingmode == 'auto') $forcedroundingmode='0';
2908
+		if ($forcedroundingmode == 'auto' && isset($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND)) {
2909
+		    $forcedroundingmode=$conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND;
2910
+		} elseif ($forcedroundingmode == 'auto') {
2911
+		    $forcedroundingmode='0';
2912
+		}
2689 2913
 
2690 2914
 		$error=0;
2691 2915
 
@@ -2708,15 +2932,22 @@  discard block
 block discarded – undo
2708 2932
 
2709 2933
 		$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,';
2710 2934
 		$sql.= ' tva_tx as vatrate, localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, info_bits, product_type';
2711
-			if ($this->table_element_line == 'facturedet') $sql.= ', situation_percent';
2935
+			if ($this->table_element_line == 'facturedet') {
2936
+			    $sql.= ', situation_percent';
2937
+			}
2712 2938
 			$sql.= ', multicurrency_total_ht, multicurrency_total_tva, multicurrency_total_ttc';
2713 2939
 		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element_line;
2714 2940
 		$sql.= ' WHERE '.$this->fk_element.' = '.$this->id;
2715 2941
 		if ($exclspec)
2716 2942
 		{
2717 2943
 			$product_field='product_type';
2718
-			if ($this->table_element_line == 'contratdet') $product_field='';    // contratdet table has no product_type field
2719
-			if ($product_field) $sql.= ' AND '.$product_field.' <> 9';
2944
+			if ($this->table_element_line == 'contratdet') {
2945
+			    $product_field='';
2946
+			}
2947
+			// contratdet table has no product_type field
2948
+			if ($product_field) {
2949
+			    $sql.= ' AND '.$product_field.' <> 9';
2950
+			}
2720 2951
 		}
2721 2952
 		$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 2953
 
@@ -2746,9 +2977,11 @@  discard block
 block discarded – undo
2746 2977
 				$parameters=array('fk_element' => $obj->rowid);
2747 2978
 				$reshook = $hookmanager->executeHooks('changeRoundingMode', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
2748 2979
 
2749
-				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'
2980
+				if (empty($reshook) && $forcedroundingmode == '0') {
2981
+				    // Check if data on line are consistent. This may solve lines that were not consistent because set with $forcedroundingmode='auto'
2750 2982
 				{
2751
-					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2983
+					$localtax_array=array($obj->localtax1_type,$obj->localtax1_tx,$obj->localtax2_type,$obj->localtax2_tx);
2984
+				}
2752 2985
 					$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);
2753 2986
 					$diff=price2num($tmpcal[1] - $obj->total_tva, 'MT', 1);
2754 2987
 					if ($diff)
@@ -2756,7 +2989,9 @@  discard block
 block discarded – undo
2756 2989
 						$sqlfix="UPDATE ".MAIN_DB_PREFIX.$this->table_element_line." SET ".$fieldtva." = ".$tmpcal[1].", total_ttc = ".$tmpcal[2]." WHERE rowid = ".$obj->rowid;
2757 2990
 						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);
2758 2991
 								$resqlfix=$this->db->query($sqlfix);
2759
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
2992
+								if (! $resqlfix) {
2993
+								    dol_print_error($this->db,'Failed to update line');
2994
+								}
2760 2995
 								$obj->total_tva = $tmpcal[1];
2761 2996
 								$obj->total_ttc = $tmpcal[2];
2762 2997
 						//
@@ -2772,16 +3007,24 @@  discard block
 block discarded – undo
2772 3007
 				$this->multicurrency_total_tva       += $obj->multicurrency_total_tva;
2773 3008
 				$this->multicurrency_total_ttc       += $obj->multicurrency_total_ttc;
2774 3009
 
2775
-				if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
2776
-				if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
2777
-				if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
3010
+				if (! isset($total_ht_by_vats[$obj->vatrate])) {
3011
+				    $total_ht_by_vats[$obj->vatrate]=0;
3012
+				}
3013
+				if (! isset($total_tva_by_vats[$obj->vatrate])) {
3014
+				    $total_tva_by_vats[$obj->vatrate]=0;
3015
+				}
3016
+				if (! isset($total_ttc_by_vats[$obj->vatrate])) {
3017
+				    $total_ttc_by_vats[$obj->vatrate]=0;
3018
+				}
2778 3019
 				$total_ht_by_vats[$obj->vatrate]  += $obj->total_ht;
2779 3020
 				$total_tva_by_vats[$obj->vatrate] += $obj->total_tva;
2780 3021
 				$total_ttc_by_vats[$obj->vatrate] += $obj->total_ttc;
2781 3022
 
2782
-				if ($forcedroundingmode == '1')	// Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
3023
+				if ($forcedroundingmode == '1') {
3024
+				    // Check if we need adjustement onto line for vat. TODO This works on the company currency but not on multicurrency
2783 3025
 				{
2784
-					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3026
+					$tmpvat=price2num($total_ht_by_vats[$obj->vatrate] * $obj->vatrate / 100, 'MT', 1);
3027
+				}
2785 3028
 					$diff=price2num($total_tva_by_vats[$obj->vatrate]-$tmpvat, 'MT', 1);
2786 3029
 					//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";
2787 3030
 					if ($diff)
@@ -2790,7 +3033,9 @@  discard block
 block discarded – undo
2790 3033
 						$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 3034
 						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);
2792 3035
 								$resqlfix=$this->db->query($sqlfix);
2793
-								if (! $resqlfix) dol_print_error($this->db,'Failed to update line');
3036
+								if (! $resqlfix) {
3037
+								    dol_print_error($this->db,'Failed to update line');
3038
+								}
2794 3039
 								$this->total_tva -= $diff;
2795 3040
 								$this->total_ttc -= $diff;
2796 3041
 								$total_tva_by_vats[$obj->vatrate] -= $diff;
@@ -2831,11 +3076,21 @@  discard block
 block discarded – undo
2831 3076
 			$fieldlocaltax2='localtax2';
2832 3077
 			$fieldttc='total_ttc';
2833 3078
 			// Specific code for backward compatibility with old field names
2834
-			if ($this->element == 'facture' || $this->element == 'facturerec')             $fieldht='total';
2835
-			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') $fieldtva='total_tva';
2836
-			if ($this->element == 'propal')                                                $fieldttc='total';
2837
-			if ($this->element == 'expensereport')                                         $fieldtva='total_tva';
2838
-			if ($this->element == 'supplier_proposal')                                     $fieldttc='total';
3079
+			if ($this->element == 'facture' || $this->element == 'facturerec') {
3080
+			    $fieldht='total';
3081
+			}
3082
+			if ($this->element == 'facture_fourn' || $this->element == 'invoice_supplier') {
3083
+			    $fieldtva='total_tva';
3084
+			}
3085
+			if ($this->element == 'propal') {
3086
+			    $fieldttc='total';
3087
+			}
3088
+			if ($this->element == 'expensereport') {
3089
+			    $fieldtva='total_tva';
3090
+			}
3091
+			if ($this->element == 'supplier_proposal') {
3092
+			    $fieldttc='total';
3093
+			}
2839 3094
 
2840 3095
 			if (empty($nodatabaseupdate))
2841 3096
 			{
@@ -2864,13 +3119,11 @@  discard block
 block discarded – undo
2864 3119
 			if (! $error)
2865 3120
 			{
2866 3121
 				return 1;
2867
-			}
2868
-			else
3122
+			} else
2869 3123
 			{
2870 3124
 				return -1;
2871 3125
 			}
2872
-		}
2873
-		else
3126
+		} else
2874 3127
 		{
2875 3128
 			dol_print_error($this->db,'Bad request in update_price');
2876 3129
 			return -1;
@@ -2893,10 +3146,18 @@  discard block
 block discarded – undo
2893 3146
 		$origin_id = (! empty($origin_id) ? $origin_id : $this->origin_id);
2894 3147
 
2895 3148
 		// Special case
2896
-		if ($origin == 'order') $origin='commande';
2897
-		if ($origin == 'invoice') $origin='facture';
2898
-		if ($origin == 'invoice_template') $origin='facturerec';
2899
-    	if ($origin == 'supplierorder') $origin='order_supplier';
3149
+		if ($origin == 'order') {
3150
+		    $origin='commande';
3151
+		}
3152
+		if ($origin == 'invoice') {
3153
+		    $origin='facture';
3154
+		}
3155
+		if ($origin == 'invoice_template') {
3156
+		    $origin='facturerec';
3157
+		}
3158
+    	if ($origin == 'supplierorder') {
3159
+    	    $origin='order_supplier';
3160
+    	}
2900 3161
 		$this->db->begin();
2901 3162
 
2902 3163
 		$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
@@ -2916,8 +3177,7 @@  discard block
 block discarded – undo
2916 3177
 	  	{
2917 3178
 	  		$this->db->commit();
2918 3179
 	  		return 1;
2919
-	  	}
2920
-	  	else
3180
+	  	} else
2921 3181
 	  	{
2922 3182
 	  		$this->error=$this->db->lasterror();
2923 3183
 	  		$this->db->rollback();
@@ -2962,12 +3222,16 @@  discard block
 block discarded – undo
2962 3222
 		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid))
2963 3223
 		{
2964 3224
 			$justsource=true;  // the source (id and type) is a search criteria
2965
-			if (! empty($targettype)) $withtargettype=true;
3225
+			if (! empty($targettype)) {
3226
+			    $withtargettype=true;
3227
+			}
2966 3228
 		}
2967 3229
 		if (! empty($targetid) && ! empty($targettype) && empty($sourceid))
2968 3230
 		{
2969 3231
 			$justtarget=true;  // the target (id and type) is a search criteria
2970
-			if (! empty($sourcetype)) $withsourcetype=true;
3232
+			if (! empty($sourcetype)) {
3233
+			    $withsourcetype=true;
3234
+			}
2971 3235
 		}
2972 3236
 
2973 3237
 		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
@@ -2990,15 +3254,17 @@  discard block
 block discarded – undo
2990 3254
 			if ($justsource)
2991 3255
 			{
2992 3256
 				$sql.= "fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."'";
2993
-				if ($withtargettype) $sql.= " AND targettype = '".$targettype."'";
2994
-			}
2995
-			else if ($justtarget)
3257
+				if ($withtargettype) {
3258
+				    $sql.= " AND targettype = '".$targettype."'";
3259
+				}
3260
+			} else if ($justtarget)
2996 3261
 			{
2997 3262
 				$sql.= "fk_target = ".$targetid." AND targettype = '".$targettype."'";
2998
-				if ($withsourcetype) $sql.= " AND sourcetype = '".$sourcetype."'";
3263
+				if ($withsourcetype) {
3264
+				    $sql.= " AND sourcetype = '".$sourcetype."'";
3265
+				}
2999 3266
 			}
3000
-		}
3001
-		else
3267
+		} else
3002 3268
 		{
3003 3269
 			$sql.= "(fk_source = ".$sourceid." AND sourcetype = '".$sourcetype."')";
3004 3270
 			$sql.= " ".$clause." (fk_target = ".$targetid." AND targettype = '".$targettype."')";
@@ -3019,13 +3285,11 @@  discard block
 block discarded – undo
3019 3285
 					if ($justsource)
3020 3286
 					{
3021 3287
 						$this->linkedObjectsIds[$obj->targettype][$obj->rowid]=$obj->fk_target;
3022
-					}
3023
-					else if ($justtarget)
3288
+					} else if ($justtarget)
3024 3289
 					{
3025 3290
 						$this->linkedObjectsIds[$obj->sourcetype][$obj->rowid]=$obj->fk_source;
3026 3291
 					}
3027
-				}
3028
-				else
3292
+				} else
3029 3293
 				{
3030 3294
 					if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype)
3031 3295
 					{
@@ -3042,10 +3306,12 @@  discard block
 block discarded – undo
3042 3306
 			if (! empty($this->linkedObjectsIds))
3043 3307
 			{
3044 3308
 				$tmparray = $this->linkedObjectsIds;
3045
-				foreach($tmparray as $objecttype => $objectids)       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3309
+				foreach($tmparray as $objecttype => $objectids) {
3310
+				    // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
3046 3311
 				{
3047 3312
 					// Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
3048
-					$module = $element = $subelement = $objecttype;
3313
+					$module = $element = $subelement = $objecttype;
3314
+				}
3049 3315
 					if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
3050 3316
 						&& preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
3051 3317
 					{
@@ -3057,29 +3323,21 @@  discard block
 block discarded – undo
3057 3323
 					// To work with non standard classpath or module name
3058 3324
 					if ($objecttype == 'facture')			{
3059 3325
 						$classpath = 'compta/facture/class';
3060
-					}
3061
-					else if ($objecttype == 'facturerec')			{
3326
+					} else if ($objecttype == 'facturerec')			{
3062 3327
 						$classpath = 'compta/facture/class'; $module = 'facture';
3063
-					}
3064
-					else if ($objecttype == 'propal')			{
3328
+					} else if ($objecttype == 'propal')			{
3065 3329
 						$classpath = 'comm/propal/class';
3066
-					}
3067
-					else if ($objecttype == 'supplier_proposal')			{
3330
+					} else if ($objecttype == 'supplier_proposal')			{
3068 3331
 						$classpath = 'supplier_proposal/class';
3069
-					}
3070
-					else if ($objecttype == 'shipping')			{
3332
+					} else if ($objecttype == 'shipping')			{
3071 3333
 						$classpath = 'expedition/class'; $subelement = 'expedition'; $module = 'expedition_bon';
3072
-					}
3073
-					else if ($objecttype == 'delivery')			{
3334
+					} else if ($objecttype == 'delivery')			{
3074 3335
 						$classpath = 'livraison/class'; $subelement = 'livraison'; $module = 'livraison_bon';
3075
-					}
3076
-					else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3336
+					} else if ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier')	{
3077 3337
 						$classpath = 'fourn/class'; $module = 'fournisseur';
3078
-					}
3079
-					else if ($objecttype == 'fichinter')			{
3338
+					} else if ($objecttype == 'fichinter')			{
3080 3339
 						$classpath = 'fichinter/class'; $subelement = 'fichinter'; $module = 'ficheinter';
3081
-					}
3082
-					else if ($objecttype == 'subscription')			{
3340
+					} else if ($objecttype == 'subscription')			{
3083 3341
 						$classpath = 'adherents/class'; $module = 'adherent';
3084 3342
 					}
3085 3343
 
@@ -3088,20 +3346,15 @@  discard block
 block discarded – undo
3088 3346
 
3089 3347
 					if ($objecttype == 'order') {
3090 3348
 						$classfile = 'commande'; $classname = 'Commande';
3091
-					}
3092
-					else if ($objecttype == 'invoice_supplier') {
3349
+					} else if ($objecttype == 'invoice_supplier') {
3093 3350
 						$classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
3094
-					}
3095
-					else if ($objecttype == 'order_supplier')   {
3351
+					} else if ($objecttype == 'order_supplier')   {
3096 3352
 						$classfile = 'fournisseur.commande'; $classname = 'CommandeFournisseur';
3097
-					}
3098
-					else if ($objecttype == 'supplier_proposal')   {
3353
+					} else if ($objecttype == 'supplier_proposal')   {
3099 3354
 						$classfile = 'supplier_proposal'; $classname = 'SupplierProposal';
3100
-					}
3101
-					else if ($objecttype == 'facturerec')   {
3355
+					} else if ($objecttype == 'facturerec')   {
3102 3356
 						$classfile = 'facture-rec'; $classname = 'FactureRec';
3103
-					}
3104
-					else if ($objecttype == 'subscription')   {
3357
+					} else if ($objecttype == 'subscription')   {
3105 3358
 						$classfile = 'subscription'; $classname = 'Subscription';
3106 3359
 					}
3107 3360
 
@@ -3114,9 +3367,11 @@  discard block
 block discarded – undo
3114 3367
 							//print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
3115 3368
 							if (class_exists($classname))
3116 3369
 							{
3117
-								foreach($objectids as $i => $objectid)	// $i is rowid into llx_element_element
3370
+								foreach($objectids as $i => $objectid) {
3371
+								    // $i is rowid into llx_element_element
3118 3372
 								{
3119
-									$object = new $classname($this->db);
3373
+									$object = new $classname($this->db);
3374
+								}
3120 3375
 									$ret = $object->fetch($objectid);
3121 3376
 									if ($ret >= 0)
3122 3377
 									{
@@ -3125,16 +3380,14 @@  discard block
 block discarded – undo
3125 3380
 								}
3126 3381
 							}
3127 3382
 						}
3128
-					}
3129
-					else
3383
+					} else
3130 3384
 					{
3131 3385
 						unset($this->linkedObjectsIds[$objecttype]);
3132 3386
 					}
3133 3387
 				}
3134 3388
 			}
3135 3389
 			return 1;
3136
-		}
3137
-		else
3390
+		} else
3138 3391
 		{
3139 3392
 			dol_print_error($this->db);
3140 3393
 			return -1;
@@ -3156,8 +3409,11 @@  discard block
 block discarded – undo
3156 3409
 		$updatesource=false;
3157 3410
 		$updatetarget=false;
3158 3411
 
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;
3412
+		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) {
3413
+		    $updatesource=true;
3414
+		} else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) {
3415
+		    $updatetarget=true;
3416
+		}
3161 3417
 
3162 3418
 		$sql = "UPDATE ".MAIN_DB_PREFIX."element_element SET ";
3163 3419
 		if ($updatesource)
@@ -3166,8 +3422,7 @@  discard block
 block discarded – undo
3166 3422
 			$sql.= ", sourcetype = '".$this->db->escape($sourcetype)."'";
3167 3423
 			$sql.= " WHERE fk_target = ".$this->id;
3168 3424
 			$sql.= " AND targettype = '".$this->db->escape($this->element)."'";
3169
-		}
3170
-		else if ($updatetarget)
3425
+		} else if ($updatetarget)
3171 3426
 		{
3172 3427
 			$sql.= "fk_target = ".$targetid;
3173 3428
 			$sql.= ", targettype = '".$this->db->escape($targettype)."'";
@@ -3179,8 +3434,7 @@  discard block
 block discarded – undo
3179 3434
 		if ($this->db->query($sql))
3180 3435
 		{
3181 3436
 			return 1;
3182
-		}
3183
-		else
3437
+		} else
3184 3438
 		{
3185 3439
 			$this->error=$this->db->lasterror();
3186 3440
 			return -1;
@@ -3203,8 +3457,11 @@  discard block
 block discarded – undo
3203 3457
 		$deletesource=false;
3204 3458
 		$deletetarget=false;
3205 3459
 
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;
3460
+		if (! empty($sourceid) && ! empty($sourcetype) && empty($targetid) && empty($targettype)) {
3461
+		    $deletesource=true;
3462
+		} else if (empty($sourceid) && empty($sourcetype) && ! empty($targetid) && ! empty($targettype)) {
3463
+		    $deletetarget=true;
3464
+		}
3208 3465
 
3209 3466
 		$sourceid = (! empty($sourceid) ? $sourceid : $this->id);
3210 3467
 		$sourcetype = (! empty($sourcetype) ? $sourcetype : $this->element);
@@ -3216,20 +3473,17 @@  discard block
 block discarded – undo
3216 3473
 		if ($rowid > 0)
3217 3474
 		{
3218 3475
 			$sql.=" rowid = ".$rowid;
3219
-		}
3220
-		else
3476
+		} else
3221 3477
 		{
3222 3478
 			if ($deletesource)
3223 3479
 			{
3224 3480
 				$sql.= " fk_source = ".$sourceid." AND sourcetype = '".$this->db->escape($sourcetype)."'";
3225 3481
 				$sql.= " AND fk_target = ".$this->id." AND targettype = '".$this->db->escape($this->element)."'";
3226
-			}
3227
-			else if ($deletetarget)
3482
+			} else if ($deletetarget)
3228 3483
 			{
3229 3484
 				$sql.= " fk_target = ".$targetid." AND targettype = '".$this->db->escape($targettype)."'";
3230 3485
 				$sql.= " AND fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."'";
3231
-			}
3232
-			else
3486
+			} else
3233 3487
 			{
3234 3488
 				$sql.= " (fk_source = ".$this->id." AND sourcetype = '".$this->db->escape($this->element)."')";
3235 3489
 				$sql.= " OR";
@@ -3241,8 +3495,7 @@  discard block
 block discarded – undo
3241 3495
 		if ($this->db->query($sql))
3242 3496
 		{
3243 3497
 			return 1;
3244
-		}
3245
-		else
3498
+		} else
3246 3499
 		{
3247 3500
 			$this->error=$this->db->lasterror();
3248 3501
 			$this->errors[]=$this->error;
@@ -3271,17 +3524,31 @@  discard block
 block discarded – undo
3271 3524
 		$this->db->begin();
3272 3525
 
3273 3526
 		$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";
3527
+		if ($elementTable == 'facture_rec') {
3528
+		    $fieldstatus="suspended";
3529
+		}
3530
+		if ($elementTable == 'mailing') {
3531
+		    $fieldstatus="statut";
3532
+		}
3533
+		if ($elementTable == 'cronjob') {
3534
+		    $fieldstatus="status";
3535
+		}
3536
+		if ($elementTable == 'user') {
3537
+		    $fieldstatus="statut";
3538
+		}
3539
+		if ($elementTable == 'expensereport') {
3540
+		    $fieldstatus="fk_statut";
3541
+		}
3542
+		if ($elementTable == 'commande_fournisseur_dispatch') {
3543
+		    $fieldstatus="status";
3544
+		}
3280 3545
 
3281 3546
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$elementTable;
3282 3547
 		$sql.= " SET ".$fieldstatus." = ".$status;
3283 3548
 		// If status = 1 = validated, update also fk_user_valid
3284
-		if ($status == 1 && $elementTable == 'expensereport') $sql.=", fk_user_valid = ".$user->id;
3549
+		if ($status == 1 && $elementTable == 'expensereport') {
3550
+		    $sql.=", fk_user_valid = ".$user->id;
3551
+		}
3285 3552
 		$sql.= " WHERE rowid=".$elementId;
3286 3553
 
3287 3554
 		dol_syslog(get_class($this)."::setStatut", LOG_DEBUG);
@@ -3292,12 +3559,27 @@  discard block
 block discarded – undo
3292 3559
 			// Try autoset of trigkey
3293 3560
 			if (empty($trigkey))
3294 3561
 			{
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';
3562
+				if ($this->element == 'supplier_proposal' && $status == 2) {
3563
+				    $trigkey='SUPPLIER_PROPOSAL_SIGN';
3564
+				}
3565
+				// 2 = SupplierProposal::STATUS_SIGNED. Can't use constant into this generic class
3566
+				if ($this->element == 'supplier_proposal' && $status == 3) {
3567
+				    $trigkey='SUPPLIER_PROPOSAL_REFUSE';
3568
+				}
3569
+				// 3 = SupplierProposal::STATUS_REFUSED. Can't use constant into this generic class
3570
+				if ($this->element == 'supplier_proposal' && $status == 4) {
3571
+				    $trigkey='SUPPLIER_PROPOSAL_CLOSE';
3572
+				}
3573
+				// 4 = SupplierProposal::STATUS_CLOSED. Can't use constant into this generic class
3574
+				if ($this->element == 'fichinter' && $status == 3) {
3575
+				    $trigkey='FICHINTER_CLASSIFY_DONE';
3576
+				}
3577
+				if ($this->element == 'fichinter' && $status == 2) {
3578
+				    $trigkey='FICHINTER_CLASSIFY_BILLED';
3579
+				}
3580
+				if ($this->element == 'fichinter' && $status == 1) {
3581
+				    $trigkey='FICHINTER_CLASSIFY_UNBILLED';
3582
+				}
3301 3583
 			}
3302 3584
 
3303 3585
 			if ($trigkey)
@@ -3316,22 +3598,22 @@  discard block
 block discarded – undo
3316 3598
 			{
3317 3599
 				$this->db->commit();
3318 3600
 
3319
-				if (empty($savElementId))    // If the element we update was $this (so $elementId is null)
3601
+				if (empty($savElementId)) {
3602
+				    // If the element we update was $this (so $elementId is null)
3320 3603
 				{
3321
-					$this->statut = $status;
3604
+					$this->statut = $status;
3605
+				}
3322 3606
 					$this->status = $status;
3323 3607
 				}
3324 3608
 
3325 3609
 				return 1;
3326
-			}
3327
-			else
3610
+			} else
3328 3611
 			{
3329 3612
 				$this->db->rollback();
3330 3613
 				dol_syslog(get_class($this)."::setStatus ".$this->error,LOG_ERR);
3331 3614
 				return -1;
3332 3615
 			}
3333
-		}
3334
-		else
3616
+		} else
3335 3617
 		{
3336 3618
 			$this->error=$this->db->lasterror();
3337 3619
 			$this->db->rollback();
@@ -3351,8 +3633,13 @@  discard block
 block discarded – undo
3351 3633
 	{
3352 3634
 		global $conf;
3353 3635
 
3354
-		if (empty($id) && empty($ref)) return 0;
3355
-		if (! empty($conf->global->MAIN_DISABLE_CANVAS)) return 0;    // To increase speed. Not enabled by default.
3636
+		if (empty($id) && empty($ref)) {
3637
+		    return 0;
3638
+		}
3639
+		if (! empty($conf->global->MAIN_DISABLE_CANVAS)) {
3640
+		    return 0;
3641
+		}
3642
+		// To increase speed. Not enabled by default.
3356 3643
 
3357 3644
 		// Clean parameters
3358 3645
 		$ref = trim($ref);
@@ -3360,8 +3647,12 @@  discard block
 block discarded – undo
3360 3647
 		$sql = "SELECT rowid, canvas";
3361 3648
 		$sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element;
3362 3649
 		$sql.= " WHERE entity IN (".getEntity($this->element).")";
3363
-		if (! empty($id))  $sql.= " AND rowid = ".$id;
3364
-		if (! empty($ref)) $sql.= " AND ref = '".$this->db->escape($ref)."'";
3650
+		if (! empty($id)) {
3651
+		    $sql.= " AND rowid = ".$id;
3652
+		}
3653
+		if (! empty($ref)) {
3654
+		    $sql.= " AND ref = '".$this->db->escape($ref)."'";
3655
+		}
3365 3656
 
3366 3657
 		$resql = $this->db->query($sql);
3367 3658
 		if ($resql)
@@ -3371,10 +3662,10 @@  discard block
 block discarded – undo
3371 3662
 			{
3372 3663
 				$this->canvas   = $obj->canvas;
3373 3664
 				return 1;
3374
-			}
3375
-			else return 0;
3376
-		}
3377
-		else
3665
+			} else {
3666
+			    return 0;
3667
+			}
3668
+		} else
3378 3669
 		{
3379 3670
 			dol_print_error($this->db);
3380 3671
 			return -1;
@@ -3411,7 +3702,9 @@  discard block
 block discarded – undo
3411 3702
 	{
3412 3703
 		global $langs;
3413 3704
 
3414
-		if (empty($id)) $id=$this->id;
3705
+		if (empty($id)) {
3706
+		    $id=$this->id;
3707
+		}
3415 3708
 
3416 3709
 		// Check parameters
3417 3710
 		if (! isset($this->childtables) || ! is_array($this->childtables) || count($this->childtables) == 0)
@@ -3445,18 +3738,18 @@  discard block
 block discarded – undo
3445 3738
 					$langs->load("errors");
3446 3739
 					//print 'Found into table '.$table.', type '.$langs->transnoentitiesnoconv($elementname).', haschild='.$haschild;
3447 3740
 					$haschild += $obj->nb;
3448
-					if (is_numeric($elementname))	// old usage
3741
+					if (is_numeric($elementname)) {
3742
+					    // old usage
3449 3743
 					{
3450
-						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3451
-					}
3452
-					else	// new usage: $elementname=Translation key
3744
+						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $table);
3745
+					}
3746
+					} else	// new usage: $elementname=Translation key
3453 3747
 					{
3454 3748
 						$this->errors[]=$langs->trans("ErrorRecordHasAtLeastOneChildOfType", $langs->transnoentitiesnoconv($elementname));
3455 3749
 					}
3456 3750
 					break;    // We found at least one, we stop here
3457 3751
 				}
3458
-			}
3459
-			else
3752
+			} else
3460 3753
 			{
3461 3754
 				$this->errors[]=$this->db->lasterror();
3462 3755
 				return -1;
@@ -3466,8 +3759,9 @@  discard block
 block discarded – undo
3466 3759
 		{
3467 3760
 			$this->errors[]="ErrorRecordHasChildren";
3468 3761
 			return $haschild;
3469
-		}
3470
-		else return 0;
3762
+		} else {
3763
+		    return 0;
3764
+		}
3471 3765
 	}
3472 3766
 
3473 3767
 	/**
@@ -3483,12 +3777,24 @@  discard block
 block discarded – undo
3483 3777
 		foreach($this->lines as $key => $val)
3484 3778
 		{
3485 3779
 			$qualified=0;
3486
-			if ($predefined == -1) $qualified=1;
3487
-			if ($predefined == 1 && $val->fk_product > 0) $qualified=1;
3488
-			if ($predefined == 0 && $val->fk_product <= 0) $qualified=1;
3489
-			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) $qualified=1;
3490
-			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) $qualified=1;
3491
-			if ($qualified) $nb++;
3780
+			if ($predefined == -1) {
3781
+			    $qualified=1;
3782
+			}
3783
+			if ($predefined == 1 && $val->fk_product > 0) {
3784
+			    $qualified=1;
3785
+			}
3786
+			if ($predefined == 0 && $val->fk_product <= 0) {
3787
+			    $qualified=1;
3788
+			}
3789
+			if ($predefined == 2 && $val->fk_product > 0 && $val->product_type==0) {
3790
+			    $qualified=1;
3791
+			}
3792
+			if ($predefined == 3 && $val->fk_product > 0 && $val->product_type==1) {
3793
+			    $qualified=1;
3794
+			}
3795
+			if ($qualified) {
3796
+			    $nb++;
3797
+			}
3492 3798
 		}
3493 3799
 		dol_syslog(get_class($this).'::hasProductsOrServices we found '.$nb.' qualified lines of products/servcies');
3494 3800
 		return $nb;
@@ -3552,16 +3858,24 @@  discard block
 block discarded – undo
3552 3858
 		{
3553 3859
 			if (isset($line->qty_asked))
3554 3860
 			{
3555
-				if (empty($totalOrdered)) $totalOrdered=0;  // Avoid warning because $totalOrdered is ''
3861
+				if (empty($totalOrdered)) {
3862
+				    $totalOrdered=0;
3863
+				}
3864
+				// Avoid warning because $totalOrdered is ''
3556 3865
 				$totalOrdered+=$line->qty_asked;    // defined for shipment only
3557 3866
 			}
3558 3867
 			if (isset($line->qty_shipped))
3559 3868
 			{
3560
-				if (empty($totalToShip)) $totalToShip=0;    // Avoid warning because $totalToShip is ''
3869
+				if (empty($totalToShip)) {
3870
+				    $totalToShip=0;
3871
+				}
3872
+				// Avoid warning because $totalToShip is ''
3561 3873
 				$totalToShip+=$line->qty_shipped;   // defined for shipment only
3562
-            }else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3874
+            } else if ($line->element == 'commandefournisseurdispatch' && isset($line->qty))
3563 3875
             {
3564
-                if (empty($totalToShip)) $totalToShip=0;
3876
+                if (empty($totalToShip)) {
3877
+                    $totalToShip=0;
3878
+                }
3565 3879
                 $totalToShip+=$line->qty;   // defined for reception only
3566 3880
 			}
3567 3881
 
@@ -3569,8 +3883,7 @@  discard block
 block discarded – undo
3569 3883
 			if ($this->element == 'shipping') {
3570 3884
 				// for shipments
3571 3885
 				$qty = $line->qty_shipped ? $line->qty_shipped : 0;
3572
-			}
3573
-			else {
3886
+			} else {
3574 3887
 				$qty = $line->qty ? $line->qty : 0;
3575 3888
 			}
3576 3889
 
@@ -3586,19 +3899,30 @@  discard block
 block discarded – undo
3586 3899
 
3587 3900
 			$weightUnit=0;
3588 3901
 			$volumeUnit=0;
3589
-			if (! empty($weight_units)) $weightUnit = $weight_units;
3590
-			if (! empty($volume_units)) $volumeUnit = $volume_units;
3591
-
3592
-			if (empty($totalWeight)) $totalWeight=0;  // Avoid warning because $totalWeight is ''
3593
-			if (empty($totalVolume)) $totalVolume=0;  // Avoid warning because $totalVolume is ''
3902
+			if (! empty($weight_units)) {
3903
+			    $weightUnit = $weight_units;
3904
+			}
3905
+			if (! empty($volume_units)) {
3906
+			    $volumeUnit = $volume_units;
3907
+			}
3908
+
3909
+			if (empty($totalWeight)) {
3910
+			    $totalWeight=0;
3911
+			}
3912
+			// Avoid warning because $totalWeight is ''
3913
+			if (empty($totalVolume)) {
3914
+			    $totalVolume=0;
3915
+			}
3916
+			// Avoid warning because $totalVolume is ''
3594 3917
 
3595 3918
 			//var_dump($line->volume_units);
3596
-			if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3919
+			if ($weight_units < 50) {
3920
+			    // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3597 3921
 			{
3598
-				$trueWeightUnit=pow(10, $weightUnit);
3922
+				$trueWeightUnit=pow(10, $weightUnit);
3923
+			}
3599 3924
 				$totalWeight += $weight * $qty * $trueWeightUnit;
3600
-			}
3601
-			else {
3925
+			} else {
3602 3926
 		if ($weight_units == 99) {
3603 3927
 			// conversion 1 Pound = 0.45359237 KG
3604 3928
 			$trueWeightUnit = 0.45359237;
@@ -3607,18 +3931,20 @@  discard block
 block discarded – undo
3607 3931
 			// conversion 1 Ounce = 0.0283495 KG
3608 3932
 			$trueWeightUnit = 0.0283495;
3609 3933
 			$totalWeight += $weight * $qty * $trueWeightUnit;
3610
-		}
3611
-		else
3612
-					$totalWeight += $weight * $qty;   // This may be wrong if we mix different units
3934
+		} else {
3935
+							$totalWeight += $weight * $qty;
3936
+		}
3937
+		// This may be wrong if we mix different units
3613 3938
 			}
3614
-			if ($volume_units < 50)   // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3939
+			if ($volume_units < 50) {
3940
+			    // >50 means a standard unit (power of 10 of official unit), > 50 means an exotic unit (like inch)
3615 3941
 			{
3616 3942
 				//print $line->volume."x".$line->volume_units."x".($line->volume_units < 50)."x".$volumeUnit;
3617
-				$trueVolumeUnit=pow(10, $volumeUnit);
3943
+				$trueVolumeUnit=pow(10, $volumeUnit);
3944
+			}
3618 3945
 				//print $line->volume;
3619 3946
 				$totalVolume += $volume * $qty * $trueVolumeUnit;
3620
-			}
3621
-			else
3947
+			} else
3622 3948
 			{
3623 3949
 				$totalVolume += $volume * $qty;   // This may be wrong if we mix different units
3624 3950
 			}
@@ -3650,8 +3976,7 @@  discard block
 block discarded – undo
3650 3976
 			$this->error=$this->db->lasterror();
3651 3977
 			$this->db->rollback();
3652 3978
 			return -1;
3653
-		}
3654
-		else
3979
+		} else
3655 3980
 		{
3656 3981
 			$this->db->commit();
3657 3982
 			return 1;
@@ -3703,13 +4028,11 @@  discard block
 block discarded – undo
3703 4028
 			{
3704 4029
 				$res = $this->db->fetch_object($resql);
3705 4030
 				return 'Incoterm : '.$res->code.' - '.$this->location_incoterms;
3706
-			}
3707
-			else
4031
+			} else
3708 4032
 			{
3709 4033
 				return '';
3710 4034
 			}
3711
-		}
3712
-		else
4035
+		} else
3713 4036
 		{
3714 4037
 			$this->errors[] = $this->db->lasterror();
3715 4038
 			return false;
@@ -3746,14 +4069,14 @@  discard block
 block discarded – undo
3746 4069
 					$this->libelle_incoterms = $obj->libelle;
3747 4070
 				}
3748 4071
 				return 1;
3749
-			}
3750
-			else
4072
+			} else
3751 4073
 			{
3752 4074
 				$this->errors[] = $this->db->lasterror();
3753 4075
 				return -1;
3754 4076
 			}
3755
-		}
3756
-		else return -1;
4077
+		} else {
4078
+		    return -1;
4079
+		}
3757 4080
 	}
3758 4081
 
3759 4082
 
@@ -3792,7 +4115,9 @@  discard block
 block discarded – undo
3792 4115
 			} else {
3793 4116
 				$res=include $tpl; // for debug
3794 4117
 			}
3795
-			if ($res) break;
4118
+			if ($res) {
4119
+			    break;
4120
+			}
3796 4121
 		}
3797 4122
 	}
3798 4123
 
@@ -3822,7 +4147,9 @@  discard block
 block discarded – undo
3822 4147
 
3823 4148
 		// Define usemargins
3824 4149
 		$usemargins=0;
3825
-		if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) $usemargins=1;
4150
+		if (! empty($conf->margin->enabled) && ! empty($this->element) && in_array($this->element,array('facture','propal','commande'))) {
4151
+		    $usemargins=1;
4152
+		}
3826 4153
 
3827 4154
 		$num = count($this->lines);
3828 4155
 
@@ -3841,7 +4168,9 @@  discard block
 block discarded – undo
3841 4168
 			print '<tr class="liste_titre nodrag nodrop">';
3842 4169
 
3843 4170
 			// Adds a line numbering column
3844
-			if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
4171
+			if (! empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
4172
+			    print '<td class="linecolnum" align="center" width="5">&nbsp;</td>';
4173
+			}
3845 4174
 
3846 4175
 			// Description
3847 4176
 			print '<td class="linecoldescription">'.$langs->trans('Description').'</td>';
@@ -3858,9 +4187,13 @@  discard block
 block discarded – undo
3858 4187
 			print '<td class="linecoluht" align="right" width="80">'.$langs->trans('PriceUHT').'</td>';
3859 4188
 
3860 4189
 			// Multicurrency
3861
-			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
4190
+			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) {
4191
+			    print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).'</td>';
4192
+			}
3862 4193
 
3863
-			if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
4194
+			if ($inputalsopricewithtax) {
4195
+			    print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
4196
+			}
3864 4197
 
3865 4198
 			// Qty
3866 4199
 			print '<td class="linecolqty" align="right">'.$langs->trans('Qty').'</td>';
@@ -3881,25 +4214,32 @@  discard block
 block discarded – undo
3881 4214
 			{
3882 4215
 				if (!empty($user->rights->margins->creer))
3883 4216
 				{
3884
-					if ($conf->global->MARGIN_TYPE == "1")
3885
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
3886
-					else
3887
-						print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
4217
+					if ($conf->global->MARGIN_TYPE == "1") {
4218
+											print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('BuyingPrice').'</td>';
4219
+					} else {
4220
+											print '<td class="linecolmargin1 margininfos" align="right" width="80">'.$langs->trans('CostPrice').'</td>';
4221
+					}
3888 4222
 				}
3889 4223
 
3890
-				if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous)
3891
-					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
3892
-				if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous)
3893
-					print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
4224
+				if (! empty($conf->global->DISPLAY_MARGIN_RATES) && $user->rights->margins->liretous) {
4225
+									print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarginRate').'</td>';
4226
+				}
4227
+				if (! empty($conf->global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) {
4228
+									print '<td class="linecolmargin2 margininfos" align="right" width="50">'.$langs->trans('MarkRate').'</td>';
4229
+				}
3894 4230
 			}
3895 4231
 
3896 4232
 			// Total HT
3897 4233
 			print '<td class="linecolht" align="right">'.$langs->trans('TotalHTShort').'</td>';
3898 4234
 
3899 4235
 			// Multicurrency
3900
-			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
4236
+			if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) {
4237
+			    print '<td class="linecoltotalht_currency" align="right">'.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).'</td>';
4238
+			}
3901 4239
 
3902
-			if ($outputalsopricetotalwithtax) print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
4240
+			if ($outputalsopricetotalwithtax) {
4241
+			    print '<td align="right" width="80">'.$langs->trans('TotalTTCShort').'</td>';
4242
+			}
3903 4243
 
3904 4244
 			print '<td class="linecoledit"></td>';  // No width to allow autodim
3905 4245
 
@@ -3929,14 +4269,15 @@  discard block
 block discarded – undo
3929 4269
 			$line->fetch_optionals();
3930 4270
 
3931 4271
 			//if (is_object($hookmanager) && (($line->product_type == 9 && ! empty($line->special_code)) || ! empty($line->fk_parent_line)))
3932
-			if (is_object($hookmanager))   // Old code is commented on preceding line.
4272
+			if (is_object($hookmanager)) {
4273
+			    // Old code is commented on preceding line.
3933 4274
 			{
3934 4275
 				if (empty($line->fk_parent_line))
3935 4276
 				{
3936
-					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
4277
+					$parameters = array('line'=>$line,'var'=>$var,'num'=>$num,'i'=>$i,'dateSelector'=>$dateSelector,'seller'=>$seller,'buyer'=>$buyer,'selected'=>$selected, 'extrafieldsline'=>$extrafieldsline);
4278
+			}
3937 4279
 					$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
3938
-				}
3939
-				else
4280
+				} else
3940 4281
 				{
3941 4282
 					$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);
3942 4283
 					$reshook = $hookmanager->executeHooks('printObjectSubLine', $parameters, $this, $action);    // Note that $action and $object may have been modified by some hooks
@@ -3983,8 +4324,14 @@  discard block
 block discarded – undo
3983 4324
 		// Show product and description
3984 4325
 		$type=(! empty($line->product_type)?$line->product_type:$line->fk_product_type);
3985 4326
 		// Try to enhance type detection using date_start and date_end for free lines where type was not saved.
3986
-		if (! empty($line->date_start)) $type=1; // deprecated
3987
-		if (! empty($line->date_end)) $type=1; // deprecated
4327
+		if (! empty($line->date_start)) {
4328
+		    $type=1;
4329
+		}
4330
+		// deprecated
4331
+		if (! empty($line->date_end)) {
4332
+		    $type=1;
4333
+		}
4334
+		// deprecated
3988 4335
 
3989 4336
 		// Ligne en mode visu
3990 4337
 		if ($action != 'editline' || $selected != $line->id)
@@ -4013,8 +4360,13 @@  discard block
 block discarded – undo
4013 4360
 
4014 4361
 					$outputlangs = $langs;
4015 4362
 					$newlang='';
4016
-					if (empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
4017
-					if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) $newlang=$this->thirdparty->default_lang;		// For language to language of customer
4363
+					if (empty($newlang) && GETPOST('lang_id','aZ09')) {
4364
+					    $newlang=GETPOST('lang_id','aZ09');
4365
+					}
4366
+					if (! empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE) && empty($newlang)) {
4367
+					    $newlang=$this->thirdparty->default_lang;
4368
+					}
4369
+					// For language to language of customer
4018 4370
 					if (! empty($newlang))
4019 4371
 					{
4020 4372
 						$outputlangs = new Translate("",$conf);
@@ -4022,8 +4374,7 @@  discard block
 block discarded – undo
4022 4374
 					}
4023 4375
 
4024 4376
 					$label = (! empty($prod->multilangs[$outputlangs->defaultlang]["label"])) ? $prod->multilangs[$outputlangs->defaultlang]["label"] : $line->product_label;
4025
-				}
4026
-				else
4377
+				} else
4027 4378
 				{
4028 4379
 					$label = $line->product_label;
4029 4380
 				}
@@ -4045,7 +4396,9 @@  discard block
 block discarded – undo
4045 4396
 				} else {
4046 4397
 					$res=include $tpl; // for debug
4047 4398
 				}
4048
-				if ($res) break;
4399
+				if ($res) {
4400
+				    break;
4401
+				}
4049 4402
 			}
4050 4403
 		}
4051 4404
 
@@ -4068,7 +4421,9 @@  discard block
 block discarded – undo
4068 4421
 				} else {
4069 4422
 					$res=include $tpl; // for debug
4070 4423
 				}
4071
-				if ($res) break;
4424
+				if ($res) {
4425
+				    break;
4426
+				}
4072 4427
 			}
4073 4428
 		}
4074 4429
 	}
@@ -4095,7 +4450,9 @@  discard block
 block discarded – undo
4095 4450
 		print '<td>'.$langs->trans('Description').'</td>';
4096 4451
 		print '<td align="right">'.$langs->trans('VATRate').'</td>';
4097 4452
 		print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
4098
-		if (!empty($conf->multicurrency->enabled)) print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4453
+		if (!empty($conf->multicurrency->enabled)) {
4454
+		    print '<td align="right">'.$langs->trans('PriceUHTCurrency').'</td>';
4455
+		}
4099 4456
 		print '<td align="right">'.$langs->trans('Qty').'</td>';
4100 4457
 		if($conf->global->PRODUCT_USE_UNITS)
4101 4458
 		{
@@ -4118,8 +4475,7 @@  discard block
 block discarded – undo
4118 4475
 						$action='';
4119 4476
 						$hookmanager->executeHooks('printOriginObjectLine',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
4120 4477
 					}
4121
-				}
4122
-				else
4478
+				} else
4123 4479
 				{
4124 4480
 					$this->printOriginLine($line, $var, $restrictlist);
4125 4481
 				}
@@ -4148,32 +4504,37 @@  discard block
 block discarded – undo
4148 4504
 		if (!empty($line->date_start))
4149 4505
 		{
4150 4506
 			$date_start=$line->date_start;
4151
-		}
4152
-		else
4507
+		} else
4153 4508
 		{
4154 4509
 			$date_start=$line->date_debut_prevue;
4155
-			if ($line->date_debut_reel) $date_start=$line->date_debut_reel;
4510
+			if ($line->date_debut_reel) {
4511
+			    $date_start=$line->date_debut_reel;
4512
+			}
4156 4513
 		}
4157 4514
 		if (!empty($line->date_end))
4158 4515
 		{
4159 4516
 			$date_end=$line->date_end;
4160
-		}
4161
-		else
4517
+		} else
4162 4518
 		{
4163 4519
 			$date_end=$line->date_fin_prevue;
4164
-			if ($line->date_fin_reel) $date_end=$line->date_fin_reel;
4520
+			if ($line->date_fin_reel) {
4521
+			    $date_end=$line->date_fin_reel;
4522
+			}
4165 4523
 		}
4166 4524
 
4167 4525
 		$this->tpl['label'] = '';
4168
-		if (! empty($line->fk_parent_line)) $this->tpl['label'].= img_picto('', 'rightarrow');
4526
+		if (! empty($line->fk_parent_line)) {
4527
+		    $this->tpl['label'].= img_picto('', 'rightarrow');
4528
+		}
4169 4529
 
4170
-		if (($line->info_bits & 2) == 2)  // TODO Not sure this is used for source object
4530
+		if (($line->info_bits & 2) == 2) {
4531
+		    // TODO Not sure this is used for source object
4171 4532
 		{
4172
-			$discount=new DiscountAbsolute($this->db);
4533
+			$discount=new DiscountAbsolute($this->db);
4534
+		}
4173 4535
 			$discount->fk_soc = $this->socid;
4174 4536
 			$this->tpl['label'].= $discount->getNomUrl(0,'discount');
4175
-		}
4176
-		else if (! empty($line->fk_product))
4537
+		} else if (! empty($line->fk_product))
4177 4538
 		{
4178 4539
 			$productstatic = new Product($this->db);
4179 4540
 			$productstatic->id = $line->fk_product;
@@ -4191,13 +4552,12 @@  discard block
 block discarded – undo
4191 4552
 			{
4192 4553
 				$this->tpl['label'].= get_date_range($date_start,$date_end);
4193 4554
 			}
4194
-		}
4195
-		else
4555
+		} else
4196 4556
 		{
4197 4557
 			$this->tpl['label'].= ($line->product_type == -1 ? '&nbsp;' : ($line->product_type == 1 ? img_object($langs->trans(''),'service') : img_object($langs->trans(''),'product')));
4198 4558
 			if (!empty($line->desc)) {
4199 4559
 				$this->tpl['label'].=$line->desc;
4200
-			}else {
4560
+			} else {
4201 4561
 				$this->tpl['label'].= ($line->label ? '&nbsp;'.$line->label : '');
4202 4562
 			}
4203 4563
 			
@@ -4210,36 +4570,35 @@  discard block
 block discarded – undo
4210 4570
 
4211 4571
 		if (! empty($line->desc))
4212 4572
 		{
4213
-			if ($line->desc == '(CREDIT_NOTE)')  // TODO Not sure this is used for source object
4573
+			if ($line->desc == '(CREDIT_NOTE)') {
4574
+			    // TODO Not sure this is used for source object
4214 4575
 			{
4215
-				$discount=new DiscountAbsolute($this->db);
4576
+				$discount=new DiscountAbsolute($this->db);
4577
+			}
4216 4578
 				$discount->fetch($line->fk_remise_except);
4217 4579
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromCreditNote",$discount->getNomUrl(0));
4218
-			}
4219
-			elseif ($line->desc == '(DEPOSIT)')  // TODO Not sure this is used for source object
4580
+			} elseif ($line->desc == '(DEPOSIT)') {
4581
+			    // TODO Not sure this is used for source object
4220 4582
 			{
4221
-				$discount=new DiscountAbsolute($this->db);
4583
+				$discount=new DiscountAbsolute($this->db);
4584
+			}
4222 4585
 				$discount->fetch($line->fk_remise_except);
4223 4586
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromDeposit",$discount->getNomUrl(0));
4224
-			}
4225
-			elseif ($line->desc == '(EXCESS RECEIVED)')
4587
+			} elseif ($line->desc == '(EXCESS RECEIVED)')
4226 4588
 			{
4227 4589
 				$discount=new DiscountAbsolute($this->db);
4228 4590
 				$discount->fetch($line->fk_remise_except);
4229 4591
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessReceived",$discount->getNomUrl(0));
4230
-			}
4231
-			elseif ($line->desc == '(EXCESS PAID)')
4592
+			} elseif ($line->desc == '(EXCESS PAID)')
4232 4593
 			{
4233 4594
 				$discount=new DiscountAbsolute($this->db);
4234 4595
 				$discount->fetch($line->fk_remise_except);
4235 4596
 				$this->tpl['description'] = $langs->transnoentities("DiscountFromExcessPaid",$discount->getNomUrl(0));
4236
-			}
4237
-			else
4597
+			} else
4238 4598
 			{
4239 4599
 				$this->tpl['description'] = dol_trunc($line->desc,60);
4240 4600
 			}
4241
-		}
4242
-		else
4601
+		} else
4243 4602
 		{
4244 4603
 			$this->tpl['description'] = '&nbsp;';
4245 4604
 		}
@@ -4247,17 +4606,23 @@  discard block
 block discarded – undo
4247 4606
         // VAT Rate
4248 4607
         $this->tpl['vat_rate'] = vatrate($line->tva_tx, true);
4249 4608
         $this->tpl['vat_rate'] .= (($line->info_bits & 1) == 1) ? '*' : '';
4250
-        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4609
+        if (! empty($line->vat_src_code) && ! preg_match('/\(/', $this->tpl['vat_rate'])) {
4610
+            $this->tpl['vat_rate'].=' ('.$line->vat_src_code.')';
4611
+        }
4251 4612
 
4252 4613
 		$this->tpl['price'] = price($line->subprice);
4253 4614
 		$this->tpl['multicurrency_price'] = price($line->multicurrency_subprice);
4254 4615
 		$this->tpl['qty'] = (($line->info_bits & 2) != 2) ? $line->qty : '&nbsp;';
4255
-		if ($conf->global->PRODUCT_USE_UNITS) $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4616
+		if ($conf->global->PRODUCT_USE_UNITS) {
4617
+		    $this->tpl['unit'] = $langs->transnoentities($line->getLabelOfUnit('long'));
4618
+		}
4256 4619
 		$this->tpl['remise_percent'] = (($line->info_bits & 2) != 2) ? vatrate($line->remise_percent, true) : '&nbsp;';
4257 4620
 
4258 4621
 		// Is the line strike or not
4259 4622
 		$this->tpl['strike']=0;
4260
-		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) $this->tpl['strike']=1;
4623
+		if ($restrictlist == 'services' && $line->product_type != Product::TYPE_SERVICE) {
4624
+		    $this->tpl['strike']=1;
4625
+		}
4261 4626
 
4262 4627
 		// Output template part (modules that overwrite templates must declare this into descriptor)
4263 4628
 		// Use global variables + $dateSelector + $seller and $buyer
@@ -4270,7 +4635,9 @@  discard block
 block discarded – undo
4270 4635
 			} else {
4271 4636
 				$res=include $tpl; // for debug
4272 4637
 			}
4273
-			if ($res) break;
4638
+			if ($res) {
4639
+			    break;
4640
+			}
4274 4641
 		}
4275 4642
 	}
4276 4643
 
@@ -4312,8 +4679,7 @@  discard block
 block discarded – undo
4312 4679
 		{
4313 4680
 			$this->db->commit();
4314 4681
 			return 1;
4315
-		}
4316
-		else
4682
+		} else
4317 4683
 		{
4318 4684
 			$this->error=$this->db->lasterror();
4319 4685
 			$this->db->rollback();
@@ -4348,8 +4714,7 @@  discard block
 block discarded – undo
4348 4714
 			$this->error=$this->db->lasterror();
4349 4715
 			$this->db->rollback();
4350 4716
 			return -1;
4351
-		}
4352
-		else
4717
+		} else
4353 4718
 		{
4354 4719
 			if (! $notrigger)
4355 4720
 			{
@@ -4416,13 +4781,20 @@  discard block
 block discarded – undo
4416 4781
 		// Search template files
4417 4782
 		$file=''; $classname=''; $filefound=0;
4418 4783
 		$dirmodels=array('/');
4419
-		if (is_array($conf->modules_parts['models'])) $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
4784
+		if (is_array($conf->modules_parts['models'])) {
4785
+		    $dirmodels=array_merge($dirmodels,$conf->modules_parts['models']);
4786
+		}
4420 4787
 		foreach($dirmodels as $reldir)
4421 4788
 		{
4422 4789
 			foreach(array('doc','pdf') as $prefix)
4423 4790
 			{
4424
-				if (in_array(get_class($this), array('Adherent'))) $file = $prefix."_".$modele.".class.php";     // Member module use prefix_module.class.php
4425
-				else $file = $prefix."_".$modele.".modules.php";
4791
+				if (in_array(get_class($this), array('Adherent'))) {
4792
+				    $file = $prefix."_".$modele.".class.php";
4793
+				}
4794
+				// Member module use prefix_module.class.php
4795
+				else {
4796
+				    $file = $prefix."_".$modele.".modules.php";
4797
+				}
4426 4798
 
4427 4799
 				// On verifie l'emplacement du modele
4428 4800
 				$file=dol_buildpath($reldir.$modelspath.$file,0);
@@ -4433,7 +4805,9 @@  discard block
 block discarded – undo
4433 4805
 					break;
4434 4806
 				}
4435 4807
 			}
4436
-			if ($filefound) break;
4808
+			if ($filefound) {
4809
+			    break;
4810
+			}
4437 4811
 		}
4438 4812
 
4439 4813
 		// If generator was found
@@ -4465,7 +4839,9 @@  discard block
 block discarded – undo
4465 4839
 						if (is_dir($tmpdir))
4466 4840
 						{
4467 4841
 							$tmpfiles=dol_dir_list($tmpdir,'files',0,'\.od(s|t)$','','name',SORT_ASC,0);
4468
-							if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
4842
+							if (count($tmpfiles)) {
4843
+							    $listoffiles=array_merge($listoffiles,$tmpfiles);
4844
+							}
4469 4845
 						}
4470 4846
 					}
4471 4847
 
@@ -4503,8 +4879,7 @@  discard block
 block discarded – undo
4503 4879
 			{
4504 4880
 				$arrayofrecords = array();   // The write_file of templates of adherent class need this var
4505 4881
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, 'member', 1, $moreparams);
4506
-			}
4507
-			else
4882
+			} else
4508 4883
 			{
4509 4884
 				$resultwritefile = $obj->write_file($this, $outputlangs, $srctemplatepath, $hidedetails, $hidedesc, $hideref, $moreparams);
4510 4885
 			}
@@ -4526,9 +4901,11 @@  discard block
 block discarded – undo
4526 4901
 					$destfile = basename($destfull);
4527 4902
 					$rel_dir = preg_replace('/^'.preg_quote(DOL_DATA_ROOT,'/').'/', '', $upload_dir);
4528 4903
 
4529
-					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir))     // If not a tmp dir
4904
+					if (! preg_match('/[\\/]temp[\\/]|[\\/]thumbs|\.meta$/', $rel_dir)) {
4905
+					    // If not a tmp dir
4530 4906
 					{
4531
-						$filename = basename($destfile);
4907
+						$filename = basename($destfile);
4908
+					}
4532 4909
 						$rel_dir = preg_replace('/[\\/]$/', '', $rel_dir);
4533 4910
 						$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
4534 4911
 
@@ -4541,18 +4918,30 @@  discard block
 block discarded – undo
4541 4918
 						if ($this->element == 'propal')
4542 4919
 						{
4543 4920
 							$useonlinesignature = $conf->global->MAIN_FEATURES_LEVEL;	// Replace this with 1 when feature to make online signature is ok
4544
-							if ($useonlinesignature) $setsharekey=true;
4545
-							if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4921
+							if ($useonlinesignature) {
4922
+							    $setsharekey=true;
4923
+							}
4924
+							if (! empty($conf->global->PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD)) {
4925
+							    $setsharekey=true;
4926
+							}
4546 4927
 						}
4547
-						if ($this->element == 'commande'     && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD))        $setsharekey=true;
4548
-						if ($this->element == 'facture'      && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD))      $setsharekey=true;
4549
-						if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) $setsharekey=true;
4928
+						if ($this->element == 'commande'     && ! empty($conf->global->ORDER_ALLOW_EXTERNAL_DOWNLOAD)) {
4929
+						    $setsharekey=true;
4930
+						}
4931
+						if ($this->element == 'facture'      && ! empty($conf->global->INVOICE_ALLOW_EXTERNAL_DOWNLOAD)) {
4932
+						    $setsharekey=true;
4933
+						}
4934
+						if ($this->element == 'bank_account' && ! empty($conf->global->BANK_ACCOUNT_ALLOW_EXTERNAL_DOWNLOAD)) {
4935
+						    $setsharekey=true;
4936
+						}
4550 4937
 
4551 4938
 						if ($setsharekey)
4552 4939
 						{
4553
-							if (empty($ecmfile->share))	// Because object not found or share not set yet
4940
+							if (empty($ecmfile->share)) {
4941
+							    // Because object not found or share not set yet
4554 4942
 							{
4555
-								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4943
+								require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
4944
+							}
4556 4945
 								$ecmfile->share = getRandomPassword(true);
4557 4946
 							}
4558 4947
 						}
@@ -4569,8 +4958,7 @@  discard block
 block discarded – undo
4569 4958
 							{
4570 4959
 								setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
4571 4960
 							}
4572
-						}
4573
-						else
4961
+						} else
4574 4962
 						{
4575 4963
 							$ecmfile->entity = $conf->entity;
4576 4964
 							$ecmfile->filepath = $rel_dir;
@@ -4597,17 +4985,20 @@  discard block
 block discarded – undo
4597 4985
 
4598 4986
 						// Update the last_main_doc field into main object (if documenent generator has property ->update_main_doc_field set)
4599 4987
 						$update_main_doc_field=0;
4600
-						if (! empty($obj->update_main_doc_field)) $update_main_doc_field=1;
4988
+						if (! empty($obj->update_main_doc_field)) {
4989
+						    $update_main_doc_field=1;
4990
+						}
4601 4991
 						if ($update_main_doc_field && ! empty($this->table_element))
4602 4992
 						{
4603 4993
 							$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET last_main_doc = '".($ecmfile->filepath.'/'.$ecmfile->filename)."'";
4604 4994
 							$sql.= ' WHERE rowid = '.$this->id;
4605 4995
 							$resql = $this->db->query($sql);
4606
-							if (! $resql) dol_print_error($this->db);
4996
+							if (! $resql) {
4997
+							    dol_print_error($this->db);
4998
+							}
4607 4999
 						}
4608 5000
 					}
4609
-				}
4610
-				else
5001
+				} else
4611 5002
 				{
4612 5003
 					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);
4613 5004
 				}
@@ -4616,15 +5007,13 @@  discard block
 block discarded – undo
4616 5007
 				dol_meta_create($this);
4617 5008
 
4618 5009
 				return 1;
4619
-			}
4620
-			else
5010
+			} else
4621 5011
 			{
4622 5012
 				$outputlangs->charset_output=$sav_charset_output;
4623 5013
 				dol_print_error($this->db, "Error generating document for ".__CLASS__.". Error: ".$obj->error, $obj->errors);
4624 5014
 				return -1;
4625 5015
 			}
4626
-		}
4627
-		else
5016
+		} else
4628 5017
 		{
4629 5018
 			$this->error=$langs->trans("Error")." ".$langs->trans("ErrorFileDoesNotExists",$file);
4630 5019
 			dol_print_error('',$this->error);
@@ -4680,13 +5069,21 @@  discard block
 block discarded – undo
4680 5069
 		global $conf, $_POST;
4681 5070
 
4682 5071
 		// If param here has been posted, we use this value first.
4683
-		if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
5072
+		if (isset($_POST[$fieldname])) {
5073
+		    return GETPOST($fieldname, 2);
5074
+		}
4684 5075
 
4685
-		if (isset($alternatevalue)) return $alternatevalue;
5076
+		if (isset($alternatevalue)) {
5077
+		    return $alternatevalue;
5078
+		}
4686 5079
 
4687 5080
 		$newelement=$this->element;
4688
-		if ($newelement == 'facture') $newelement='invoice';
4689
-		if ($newelement == 'commande') $newelement='order';
5081
+		if ($newelement == 'facture') {
5082
+		    $newelement='invoice';
5083
+		}
5084
+		if ($newelement == 'commande') {
5085
+		    $newelement='order';
5086
+		}
4690 5087
 		if (empty($newelement))
4691 5088
 		{
4692 5089
 			dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
@@ -4695,7 +5092,9 @@  discard block
 block discarded – undo
4695 5092
 
4696 5093
 		$keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
4697 5094
 		//var_dump($keyforfieldname);
4698
-		if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
5095
+		if (isset($conf->global->$keyforfieldname)) {
5096
+		    return $conf->global->$keyforfieldname;
5097
+		}
4699 5098
 
4700 5099
 		// TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
4701 5100
 	}
@@ -4729,8 +5128,7 @@  discard block
 block discarded – undo
4729 5128
 			if (!empty($this->errors))
4730 5129
 			{
4731 5130
 				$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.
4732
-			}
4733
-			else
5131
+			} else
4734 5132
 			{
4735 5133
 				$this->errors=$interface->errors;
4736 5134
 			}
@@ -4754,7 +5152,9 @@  discard block
 block discarded – undo
4754 5152
 	function fetch_optionals($rowid=null, $optionsArray=null)
4755 5153
 	{
4756 5154
         // phpcs:enable
4757
-		if (empty($rowid)) $rowid=$this->id;
5155
+		if (empty($rowid)) {
5156
+		    $rowid=$this->id;
5157
+		}
4758 5158
 
4759 5159
 		// To avoid SQL errors. Probably not the better solution though
4760 5160
 		if (!$this->table_element) {
@@ -4780,15 +5180,17 @@  discard block
 block discarded – undo
4780 5180
 				$extrafields->fetch_name_optionals_label($this->table_element);
4781 5181
 			}
4782 5182
 			$optionsArray = (! empty($extrafields->attributes[$this->table_element]['label'])?$extrafields->attributes[$this->table_element]['label']:null);
4783
-		}
4784
-		else
5183
+		} else
4785 5184
 		{
4786 5185
 			global $extrafields;
4787 5186
 			dol_syslog("Warning: fetch_optionals was called with param optionsArray defined when you should pass null now", LOG_WARNING);
4788 5187
 		}
4789 5188
 
4790 5189
 		$table_element = $this->table_element;
4791
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5190
+		if ($table_element == 'categorie') {
5191
+		    $table_element = 'categories';
5192
+		}
5193
+		// For compatibility
4792 5194
 
4793 5195
 		// Request to get complementary values
4794 5196
 		if (is_array($optionsArray) && count($optionsArray) > 0)
@@ -4824,8 +5226,7 @@  discard block
 block discarded – undo
4824 5226
 							{
4825 5227
 								//var_dump($extrafields->attributes[$this->table_element]['type'][$key]);
4826 5228
 								$this->array_options["options_".$key]=$this->db->jdate($value);
4827
-							}
4828
-							else
5229
+							} else
4829 5230
 							{
4830 5231
 								$this->array_options["options_".$key]=$value;
4831 5232
 							}
@@ -4837,10 +5238,12 @@  discard block
 block discarded – undo
4837 5238
 
4838 5239
 				$this->db->free($resql);
4839 5240
 
4840
-				if ($numrows) return $numrows;
4841
-				else return 0;
4842
-			}
4843
-			else
5241
+				if ($numrows) {
5242
+				    return $numrows;
5243
+				} else {
5244
+				    return 0;
5245
+				}
5246
+			} else
4844 5247
 			{
4845 5248
 				dol_print_error($this->db);
4846 5249
 				return -1;
@@ -4859,7 +5262,10 @@  discard block
 block discarded – undo
4859 5262
 		$this->db->begin();
4860 5263
 
4861 5264
 		$table_element = $this->table_element;
4862
-		if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5265
+		if ($table_element == 'categorie') {
5266
+		    $table_element = 'categories';
5267
+		}
5268
+		// For compatibility
4863 5269
 
4864 5270
 		$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
4865 5271
 		dol_syslog(get_class($this)."::deleteExtraFields delete", LOG_DEBUG);
@@ -4869,8 +5275,7 @@  discard block
 block discarded – undo
4869 5275
 			$this->error=$this->db->lasterror();
4870 5276
 			$this->db->rollback();
4871 5277
 			return -1;
4872
-		}
4873
-		else
5278
+		} else
4874 5279
 		{
4875 5280
 			$this->db->commit();
4876 5281
 			return 1;
@@ -4891,11 +5296,16 @@  discard block
 block discarded – undo
4891 5296
 	{
4892 5297
 		global $conf,$langs,$user;
4893 5298
 
4894
-		if (empty($userused)) $userused=$user;
5299
+		if (empty($userused)) {
5300
+		    $userused=$user;
5301
+		}
4895 5302
 
4896 5303
 		$error=0;
4897 5304
 
4898
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
5305
+		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
5306
+		    return 0;
5307
+		}
5308
+		// For avoid conflicts if trigger used
4899 5309
 
4900 5310
 		if (! empty($this->array_options))
4901 5311
 		{
@@ -4908,10 +5318,13 @@  discard block
 block discarded – undo
4908 5318
 			//Eliminate copied source object extra_fields that do not exist in target object
4909 5319
 			$new_array_options=array();
4910 5320
 			foreach ($this->array_options as $key => $value) {
4911
-				if (in_array(substr($key,8), array_keys($target_extrafields)))	// We remove the 'options_' from $key for test
4912
-					$new_array_options[$key] = $value;
4913
-				elseif (in_array($key, array_keys($target_extrafields)))		// We test on $key that does not contains the 'options_' prefix
4914
-					$new_array_options['options_'.$key] = $value;
5321
+				if (in_array(substr($key,8), array_keys($target_extrafields))) {
5322
+				    // We remove the 'options_' from $key for test
5323
+					$new_array_options[$key] = $value;
5324
+				} elseif (in_array($key, array_keys($target_extrafields))) {
5325
+				    // We test on $key that does not contains the 'options_' prefix
5326
+					$new_array_options['options_'.$key] = $value;
5327
+				}
4915 5328
 			}
4916 5329
 
4917 5330
 			foreach($new_array_options as $key => $value)
@@ -4925,8 +5338,12 @@  discard block
 block discarded – undo
4925 5338
 			   	if ($attributeRequired)
4926 5339
 			   	{
4927 5340
 			   		$mandatorypb=false;
4928
-			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') $mandatorypb=true;
4929
-			   		if ($this->array_options[$key] === '') $mandatorypb=true;
5341
+			   		if ($attributeType == 'link' && $this->array_options[$key] == '-1') {
5342
+			   		    $mandatorypb=true;
5343
+			   		}
5344
+			   		if ($this->array_options[$key] === '') {
5345
+			   		    $mandatorypb=true;
5346
+			   		}
4930 5347
 			   		if ($mandatorypb)
4931 5348
 			   		{
4932 5349
 			   			dol_syslog($this->error);
@@ -4945,8 +5362,7 @@  discard block
 block discarded – undo
4945 5362
 			   			{
4946 5363
 			   				$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4947 5364
 			   				return -1;
4948
-			  			}
4949
-			   			elseif ($value=='')
5365
+			  			} elseif ($value=='')
4950 5366
 			   			{
4951 5367
 			   				$new_array_options[$key] = null;
4952 5368
 			   			}
@@ -4958,8 +5374,7 @@  discard block
 block discarded – undo
4958 5374
 							dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
4959 5375
 							$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
4960 5376
 							return -1;
4961
-						}
4962
-						elseif ($value=='')
5377
+						} elseif ($value=='')
4963 5378
 						{
4964 5379
 							$new_array_options[$key] = null;
4965 5380
 						}
@@ -4984,27 +5399,27 @@  discard block
 block discarded – undo
4984 5399
 			   					//global $action;		// $action may be 'create', 'update', 'update_extras'...
4985 5400
 			   					//var_dump($action);
4986 5401
 			   					//var_dump($this->oldcopy);exit;
4987
-			   					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
5402
+			   					if (is_object($this->oldcopy)) {
5403
+			   					    // If this->oldcopy is not defined, we can't know if we change attribute or not, so we must keep value
4988 5404
 			   					{
4989 5405
 			   						//var_dump($this->oldcopy->array_options[$key]); var_dump($this->array_options[$key]);
4990 5406
 				   					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.
4991 5407
 				   					{
4992
-				   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
4993
-				   					}
4994
-									else
5408
+				   						$new_array_options[$key] = $this->array_options[$key];
5409
+			   					}
5410
+			   					// Value is kept
5411
+				   					} else
4995 5412
 									{
4996 5413
 										// var_dump($algo);
4997 5414
 										$newvalue = dol_hash($this->array_options[$key], $algo);
4998 5415
 										$new_array_options[$key] = $newvalue;
4999 5416
 									}
5000
-			   					}
5001
-			   					else
5417
+			   					} else
5002 5418
 			   					{
5003 5419
 			   						$new_array_options[$key] = $this->array_options[$key];	// Value is kept
5004 5420
 			   					}
5005 5421
 			   				}
5006
-			   			}
5007
-			   			else	// Common usage
5422
+			   			} else	// Common usage
5008 5423
 			   			{
5009 5424
 			   				$new_array_options[$key] = $this->array_options[$key];
5010 5425
 			   			}
@@ -5030,26 +5445,30 @@  discard block
 block discarded – undo
5030 5445
 						dol_include_once($InfoFieldList[1]);
5031 5446
 						if ($InfoFieldList[0] && class_exists($InfoFieldList[0]))
5032 5447
 						{
5033
-							if ($value == '-1')	// -1 is key for no defined in combo list of objects
5448
+							if ($value == '-1') {
5449
+							    // -1 is key for no defined in combo list of objects
5034 5450
 							{
5035
-								$new_array_options[$key]='';
5036
-							}
5037
-							elseif ($value)
5451
+								$new_array_options[$key]='';
5452
+							}
5453
+							} elseif ($value)
5038 5454
 							{
5039 5455
 								$object = new $InfoFieldList[0]($this->db);
5040
-								if (is_numeric($value)) $res=$object->fetch($value);
5041
-								else $res=$object->fetch('',$value);
5042
-
5043
-								if ($res > 0) $new_array_options[$key]=$object->id;
5044
-								else
5456
+								if (is_numeric($value)) {
5457
+								    $res=$object->fetch($value);
5458
+								} else {
5459
+								    $res=$object->fetch('',$value);
5460
+								}
5461
+
5462
+								if ($res > 0) {
5463
+								    $new_array_options[$key]=$object->id;
5464
+								} else
5045 5465
 								{
5046 5466
 									$this->error="Id/Ref '".$value."' for object '".$object->element."' not found";
5047 5467
 									$this->db->rollback();
5048 5468
 									return -1;
5049 5469
 								}
5050 5470
 							}
5051
-						}
5052
-						else
5471
+						} else
5053 5472
 						{
5054 5473
 							dol_syslog('Error bad setup of extrafield', LOG_WARNING);
5055 5474
 						}
@@ -5060,7 +5479,10 @@  discard block
 block discarded – undo
5060 5479
 			$this->db->begin();
5061 5480
 
5062 5481
 			$table_element = $this->table_element;
5063
-			if ($table_element == 'categorie') $table_element = 'categories'; // For compatibility
5482
+			if ($table_element == 'categorie') {
5483
+			    $table_element = 'categories';
5484
+			}
5485
+			// For compatibility
5064 5486
 
5065 5487
 			$sql_del = "DELETE FROM ".MAIN_DB_PREFIX.$table_element."_extrafields WHERE fk_object = ".$this->id;
5066 5488
 			dol_syslog(get_class($this)."::insertExtraFields delete", LOG_DEBUG);
@@ -5071,8 +5493,10 @@  discard block
 block discarded – undo
5071 5493
 			{
5072 5494
 				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5073 5495
 				// Add field of attribut
5074
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator
5075
-					$sql.=",".$attributeKey;
5496
+				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') {
5497
+				    // Only for other type than separator
5498
+					$sql.=",".$attributeKey;
5499
+				}
5076 5500
 			}
5077 5501
 			$sql .= ") VALUES (".$this->id;
5078 5502
 
@@ -5080,13 +5504,14 @@  discard block
 block discarded – undo
5080 5504
 			{
5081 5505
 				$attributeKey = substr($key,8);   // Remove 'options_' prefix
5082 5506
 				// Add field of attribute
5083
-				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') // Only for other type than separator)
5507
+				if ($extrafields->attributes[$this->table_element]['type'][$attributeKey] != 'separate') {
5508
+				    // Only for other type than separator)
5084 5509
 				{
5085 5510
 					if ($new_array_options[$key] != '')
5086 5511
 					{
5087
-						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5088
-					}
5089
-					else
5512
+						$sql.=",'".$this->db->escape($new_array_options[$key])."'";
5513
+				}
5514
+					} else
5090 5515
 					{
5091 5516
 						$sql.=",null";
5092 5517
 					}
@@ -5107,7 +5532,9 @@  discard block
 block discarded – undo
5107 5532
 				// Call trigger
5108 5533
 				$this->context=array('extrafieldaddupdate'=>1);
5109 5534
 				$result=$this->call_trigger($trigger, $userused);
5110
-				if ($result < 0) $error++;
5535
+				if ($result < 0) {
5536
+				    $error++;
5537
+				}
5111 5538
 				// End call trigger
5112 5539
 			}
5113 5540
 
@@ -5115,14 +5542,14 @@  discard block
 block discarded – undo
5115 5542
 			{
5116 5543
 				$this->db->rollback();
5117 5544
 				return -1;
5118
-			}
5119
-			else
5545
+			} else
5120 5546
 			{
5121 5547
 				$this->db->commit();
5122 5548
 				return 1;
5123 5549
 			}
5124
-		}
5125
-		else return 0;
5550
+		} else {
5551
+		    return 0;
5552
+		}
5126 5553
 	}
5127 5554
 
5128 5555
 	/**
@@ -5139,11 +5566,16 @@  discard block
 block discarded – undo
5139 5566
 	{
5140 5567
 		global $conf,$langs,$user;
5141 5568
 
5142
-		if (empty($userused)) $userused=$user;
5569
+		if (empty($userused)) {
5570
+		    $userused=$user;
5571
+		}
5143 5572
 
5144 5573
 		$error=0;
5145 5574
 
5146
-		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) return 0;	// For avoid conflicts if trigger used
5575
+		if (! empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) {
5576
+		    return 0;
5577
+		}
5578
+		// For avoid conflicts if trigger used
5147 5579
 
5148 5580
 		if (! empty($this->array_options) && isset($this->array_options["options_".$key]))
5149 5581
 		{
@@ -5170,8 +5602,7 @@  discard block
 block discarded – undo
5170 5602
 					{
5171 5603
 						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue",$attributeLabel);
5172 5604
 						return -1;
5173
-					}
5174
-					elseif ($value=='')
5605
+					} elseif ($value=='')
5175 5606
 					{
5176 5607
 						$this->array_options["options_".$key] = null;
5177 5608
 					}
@@ -5183,8 +5614,7 @@  discard block
 block discarded – undo
5183 5614
 						dol_syslog($langs->trans("ExtraFieldHasWrongValue")." sur ".$attributeLabel."(".$value."is not '".$attributeType."')", LOG_DEBUG);
5184 5615
 						$this->errors[]=$langs->trans("ExtraFieldHasWrongValue", $attributeLabel);
5185 5616
 						return -1;
5186
-					}
5187
-					elseif ($value=='')
5617
+					} elseif ($value=='')
5188 5618
 					{
5189 5619
 						$this->array_options["options_".$key] = null;
5190 5620
 					}
@@ -5236,7 +5666,9 @@  discard block
 block discarded – undo
5236 5666
 				// Call trigger
5237 5667
 				$this->context=array('extrafieldupdate'=>1);
5238 5668
 				$result=$this->call_trigger($trigger, $userused);
5239
-				if ($result < 0) $error++;
5669
+				if ($result < 0) {
5670
+				    $error++;
5671
+				}
5240 5672
 				// End call trigger
5241 5673
 			}
5242 5674
 
@@ -5245,14 +5677,14 @@  discard block
 block discarded – undo
5245 5677
 				dol_syslog(get_class($this) . "::".__METHOD__ . $this->error, LOG_ERR);
5246 5678
 				$this->db->rollback();
5247 5679
 				return -1;
5248
-			}
5249
-			else
5680
+			} else
5250 5681
 			{
5251 5682
 				$this->db->commit();
5252 5683
 				return 1;
5253 5684
 			}
5254
-		}
5255
-		else return 0;
5685
+		} else {
5686
+		    return 0;
5687
+		}
5256 5688
 	}
5257 5689
 
5258 5690
 
@@ -5327,8 +5759,11 @@  discard block
 block discarded – undo
5327 5759
 
5328 5760
 		if ($computed)
5329 5761
 		{
5330
-			if (! preg_match('/^search_/', $keyprefix)) return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5331
-			else return '';
5762
+			if (! preg_match('/^search_/', $keyprefix)) {
5763
+			    return '<span class="opacitymedium">'.$langs->trans("AutomaticallyCalculated").'</span>';
5764
+			} else {
5765
+			    return '';
5766
+			}
5332 5767
 		}
5333 5768
 
5334 5769
 
@@ -5342,33 +5777,27 @@  discard block
 block discarded – undo
5342 5777
 			if ($type == 'date')
5343 5778
 			{
5344 5779
 				$morecss = 'minwidth100imp';
5345
-			}
5346
-			elseif ($type == 'datetime')
5780
+			} elseif ($type == 'datetime')
5347 5781
 			{
5348 5782
 				$morecss = 'minwidth200imp';
5349
-			}
5350
-			elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5783
+			} elseif (in_array($type,array('int','integer','price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5351 5784
 			{
5352 5785
 				$morecss = 'maxwidth75';
5353
-                        }elseif ($type == 'url')
5786
+                        } elseif ($type == 'url')
5354 5787
 			{
5355 5788
 				$morecss='minwidth400';
5356
-			}
5357
-			elseif ($type == 'boolean')
5789
+			} elseif ($type == 'boolean')
5358 5790
 			{
5359 5791
 				$morecss='';
5360
-			}
5361
-			else
5792
+			} else
5362 5793
 			{
5363 5794
 				if (round($size) < 12)
5364 5795
 				{
5365 5796
 					$morecss = 'minwidth100';
5366
-				}
5367
-				else if (round($size) <= 48)
5797
+				} else if (round($size) <= 48)
5368 5798
 				{
5369 5799
 					$morecss = 'minwidth200';
5370
-				}
5371
-				else
5800
+				} else
5372 5801
 				{
5373 5802
 					$morecss = 'minwidth400';
5374 5803
 				}
@@ -5383,52 +5812,50 @@  discard block
 block discarded – undo
5383 5812
 			$showtime = in_array($type,array('datetime')) ? 1 : 0;
5384 5813
 
5385 5814
 			// Do not show current date when field not required (see selectDate() method)
5386
-			if (!$required && $value == '') $value = '-1';
5815
+			if (!$required && $value == '') {
5816
+			    $value = '-1';
5817
+			}
5387 5818
 
5388 5819
 			// TODO Must also support $moreparam
5389 5820
 			$out = $form->selectDate($value, $keyprefix.$key.$keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
5390
-		}
5391
-		elseif (in_array($type,array('int','integer')))
5821
+		} elseif (in_array($type,array('int','integer')))
5392 5822
 		{
5393 5823
 			$tmp=explode(',',$size);
5394 5824
 			$newsize=$tmp[0];
5395 5825
 			$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:'').'>';
5396
-		}
5397
-		elseif (preg_match('/varchar/', $type))
5826
+		} elseif (preg_match('/varchar/', $type))
5398 5827
 		{
5399 5828
 			$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:'').'>';
5400
-		}
5401
-		elseif (in_array($type, array('mail', 'phone', 'url')))
5829
+		} elseif (in_array($type, array('mail', 'phone', 'url')))
5402 5830
 		{
5403 5831
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5404
-		}
5405
-		elseif ($type == 'text')
5832
+		} elseif ($type == 'text')
5406 5833
 		{
5407
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5834
+			if (! preg_match('/search_/', $keyprefix)) {
5835
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
5408 5836
 			{
5409
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5837
+				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5838
+			}
5410 5839
 				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,false,ROWS_5,'90%');
5411 5840
 				$out=$doleditor->Create(1);
5412
-			}
5413
-			else
5841
+			} else
5414 5842
 			{
5415 5843
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5416 5844
 			}
5417
-		}
5418
-		elseif ($type == 'html')
5845
+		} elseif ($type == 'html')
5419 5846
 		{
5420
-			if (! preg_match('/search_/', $keyprefix))		// If keyprefix is search_ or search_options_, we must just use a simple text field
5847
+			if (! preg_match('/search_/', $keyprefix)) {
5848
+			    // If keyprefix is search_ or search_options_, we must just use a simple text field
5421 5849
 			{
5422
-				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5850
+				require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
5851
+			}
5423 5852
 				$doleditor=new DolEditor($keyprefix.$key.$keysuffix,$value,'',200,'dolibarr_notes','In',false,false,! empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE,ROWS_5,'90%');
5424 5853
 				$out=$doleditor->Create(1);
5425
-			}
5426
-			else
5854
+			} else
5427 5855
 			{
5428 5856
 				$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.dol_escape_htmltag($value).'" '.($moreparam?$moreparam:'').'>';
5429 5857
 			}
5430
-		}
5431
-		elseif ($type == 'boolean')
5858
+		} elseif ($type == 'boolean')
5432 5859
 		{
5433 5860
 			$checked='';
5434 5861
 			if (!empty($value)) {
@@ -5437,22 +5864,19 @@  discard block
 block discarded – undo
5437 5864
 				$checked=' value="1" ';
5438 5865
 			}
5439 5866
 			$out='<input type="checkbox" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.$checked.' '.($moreparam?$moreparam:'').'>';
5440
-		}
5441
-		elseif ($type == 'price')
5867
+		} elseif ($type == 'price')
5442 5868
 		{
5443 5869
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5444 5870
 				$value=price($value);
5445 5871
 			}
5446 5872
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> '.$langs->getCurrencySymbol($conf->currency);
5447
-		}
5448
-		elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5873
+		} elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/',$type))
5449 5874
 		{
5450 5875
 			if (!empty($value)) {		// $value in memory is a php numeric, we format it into user number format.
5451 5876
 				$value=price($value);
5452 5877
 			}
5453 5878
 			$out='<input type="text" class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'> ';
5454
-		}
5455
-		elseif ($type == 'select')
5879
+		} elseif ($type == 'select')
5456 5880
 		{
5457 5881
 			$out = '';
5458 5882
 			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
@@ -5462,10 +5886,14 @@  discard block
 block discarded – undo
5462 5886
 			}
5463 5887
 
5464 5888
 			$out.='<select class="flat '.$morecss.' maxwidthonsmartphone" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" '.($moreparam?$moreparam:'').'>';
5465
-                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1))$out.='<option value="0">&nbsp;</option>';
5889
+                if((! isset($this->fields[$key]['default'])) ||($this->fields[$key]['notnull']!=1)) {
5890
+                    $out.='<option value="0">&nbsp;</option>';
5891
+                }
5466 5892
 			foreach ($param['options'] as $key => $val)
5467 5893
 			{
5468
-				if ((string) $key == '') continue;
5894
+				if ((string) $key == '') {
5895
+				    continue;
5896
+				}
5469 5897
 				list($val, $parent) = explode('|', $val);
5470 5898
 				$out.='<option value="'.$key.'"';
5471 5899
 				$out.= (((string) $value == (string) $key)?' selected':'');
@@ -5473,8 +5901,7 @@  discard block
 block discarded – undo
5473 5901
 				$out.='>'.$val.'</option>';
5474 5902
 			}
5475 5903
 			$out.='</select>';
5476
-		}
5477
-		elseif ($type == 'sellist')
5904
+		} elseif ($type == 'sellist')
5478 5905
 		{
5479 5906
 			$out = '';
5480 5907
 			if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->MAIN_EXTRAFIELDS_USE_SELECT2))
@@ -5541,13 +5968,11 @@  discard block
 block discarded – undo
5541 5968
 					{
5542 5969
 						$sql.= ' as main, '.MAIN_DB_PREFIX .$InfoFieldList[0].'_extrafields as extra';
5543 5970
 						$sqlwhere.= ' WHERE extra.fk_object=main.'.$InfoFieldList[2]. ' AND '.$InfoFieldList[4];
5544
-					}
5545
-					else
5971
+					} else
5546 5972
 					{
5547 5973
 						$sqlwhere.= ' WHERE '.$InfoFieldList[4];
5548 5974
 					}
5549
-				}
5550
-				else
5975
+				} else
5551 5976
 				{
5552 5977
 					$sqlwhere.= ' WHERE 1=1';
5553 5978
 				}
@@ -5583,8 +6008,7 @@  discard block
 block discarded – undo
5583 6008
 							{
5584 6009
 								$labeltoshow.= $obj->$field_toshow.' ';
5585 6010
 							}
5586
-						}
5587
-						else
6011
+						} else
5588 6012
 						{
5589 6013
 							$labeltoshow=$obj->{$InfoFieldList[1]};
5590 6014
 						}
@@ -5597,25 +6021,25 @@  discard block
 block discarded – undo
5597 6021
 								$translabel=$langs->trans($obj->$field_toshow);
5598 6022
 								if ($translabel!=$obj->$field_toshow) {
5599 6023
 									$labeltoshow=dol_trunc($translabel,18).' ';
5600
-								}else {
6024
+								} else {
5601 6025
 									$labeltoshow=dol_trunc($obj->$field_toshow,18).' ';
5602 6026
 								}
5603 6027
 							}
5604 6028
 							$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
5605
-						}
5606
-						else
6029
+						} else
5607 6030
 						{
5608 6031
 							if (! $notrans)
5609 6032
 							{
5610 6033
 								$translabel=$langs->trans($obj->{$InfoFieldList[1]});
5611 6034
 								if ($translabel!=$obj->{$InfoFieldList[1]}) {
5612 6035
 									$labeltoshow=dol_trunc($translabel,18);
5613
-								}
5614
-								else {
6036
+								} else {
5615 6037
 									$labeltoshow=dol_trunc($obj->{$InfoFieldList[1]},18);
5616 6038
 								}
5617 6039
 							}
5618
-							if (empty($labeltoshow)) $labeltoshow='(not defined)';
6040
+							if (empty($labeltoshow)) {
6041
+							    $labeltoshow='(not defined)';
6042
+							}
5619 6043
 							if ($value==$obj->rowid)
5620 6044
 							{
5621 6045
 								$out.='<option value="'.$obj->rowid.'" selected>'.$labeltoshow.'</option>';
@@ -5635,19 +6059,16 @@  discard block
 block discarded – undo
5635 6059
 						$i++;
5636 6060
 					}
5637 6061
 					$this->db->free($resql);
5638
-				}
5639
-				else {
6062
+				} else {
5640 6063
 					print 'Error in request '.$sql.' '.$this->db->lasterror().'. Check setup of extra parameters.<br>';
5641 6064
 				}
5642 6065
 			}
5643 6066
 			$out.='</select>';
5644
-		}
5645
-		elseif ($type == 'checkbox')
6067
+		} elseif ($type == 'checkbox')
5646 6068
 		{
5647 6069
 			$value_arr=explode(',',$value);
5648 6070
 			$out=$form->multiselectarray($keyprefix.$key.$keysuffix, (empty($param['options'])?null:$param['options']), $value_arr, '', 0, '', 0, '100%');
5649
-		}
5650
-		elseif ($type == 'radio')
6071
+		} elseif ($type == 'radio')
5651 6072
 		{
5652 6073
 			$out='';
5653 6074
 			foreach ($param['options'] as $keyopt => $val)
@@ -5658,13 +6079,11 @@  discard block
 block discarded – undo
5658 6079
 				$out.= ($value==$keyopt?'checked':'');
5659 6080
 				$out.='/><label for="'.$keyprefix.$key.$keysuffix.'_'.$keyopt.'">'.$val.'</label><br>';
5660 6081
 			}
5661
-		}
5662
-		elseif ($type == 'chkbxlst')
6082
+		} elseif ($type == 'chkbxlst')
5663 6083
 		{
5664 6084
 			if (is_array($value)) {
5665 6085
 				$value_arr = $value;
5666
-			}
5667
-			else {
6086
+			} else {
5668 6087
 				$value_arr = explode(',', $value);
5669 6088
 			}
5670 6089
 
@@ -5779,8 +6198,9 @@  discard block
 block discarded – undo
5779 6198
 									$labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
5780 6199
 								}
5781 6200
 							}
5782
-							if (empty($labeltoshow))
5783
-								$labeltoshow = '(not defined)';
6201
+							if (empty($labeltoshow)) {
6202
+															$labeltoshow = '(not defined)';
6203
+							}
5784 6204
 
5785 6205
 								if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
5786 6206
 									$data[$obj->rowid]=$labeltoshow;
@@ -5802,8 +6222,7 @@  discard block
 block discarded – undo
5802 6222
 					print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
5803 6223
 				}
5804 6224
 			}
5805
-		}
5806
-		elseif ($type == 'link')
6225
+		} elseif ($type == 'link')
5807 6226
 		{
5808 6227
 			$param_list=array_keys($param['options']);				// $param_list='ObjectName:classPath'
5809 6228
 			$showempty=(($required && $default != '')?0:1);
@@ -5811,18 +6230,19 @@  discard block
 block discarded – undo
5811 6230
 			if ($conf->global->MAIN_FEATURES_LEVEL >= 2)
5812 6231
 			{
5813 6232
             			list($class,$classfile)=explode(':',$param_list[0]);
5814
-            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
5815
-            			else $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
6233
+            			if (file_exists(dol_buildpath(dirname(dirname($classfile)).'/card.php'))) {
6234
+            			    $url_path=dol_buildpath(dirname(dirname($classfile)).'/card.php',1);
6235
+            			} else {
6236
+            			    $url_path=dol_buildpath(dirname(dirname($classfile)).'/'.$class.'_card.php',1);
6237
+            			}
5816 6238
             			$out.='<a class="butActionNew" href="'.$url_path.'?action=create&backtopage='.$_SERVER['PHP_SELF'].'"><span class="fa fa-plus-circle valignmiddle"></span></a>';
5817 6239
             			// TODO Add Javascript code to add input fields contents to new elements urls
5818 6240
 			}
5819
-		}
5820
-		elseif ($type == 'password')
6241
+		} elseif ($type == 'password')
5821 6242
 		{
5822 6243
 			// If prefix is 'search_', field is used as a filter, we use a common text field.
5823 6244
 			$out='<input type="'.($keyprefix=='search_'?'text':'password').'" class="flat '.$morecss.'" name="'.$keyprefix.$key.$keysuffix.'" id="'.$keyprefix.$key.$keysuffix.'" value="'.$value.'" '.($moreparam?$moreparam:'').'>';
5824
-		}
5825
-		elseif ($type == 'array')
6245
+		} elseif ($type == 'array')
5826 6246
 		{
5827 6247
 			$newval = $val;
5828 6248
 			$newval['type'] = 'varchar(256)';
@@ -5900,17 +6320,25 @@  discard block
 block discarded – undo
5900 6320
 		{
5901 6321
 			$type = 'varchar';		// convert varchar(xx) int varchar
5902 6322
 			$size = $reg[1];
5903
-		}
5904
-		elseif (preg_match('/varchar/', $type)) $type = 'varchar';		// convert varchar(xx) int varchar
5905
-		if (is_array($val['arrayofkeyval'])) $type='select';
5906
-		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) $type='link';
6323
+		} elseif (preg_match('/varchar/', $type)) {
6324
+		    $type = 'varchar';
6325
+		}
6326
+		// convert varchar(xx) int varchar
6327
+		if (is_array($val['arrayofkeyval'])) {
6328
+		    $type='select';
6329
+		}
6330
+		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg)) {
6331
+		    $type='link';
6332
+		}
5907 6333
 
5908 6334
 		$default=$val['default'];
5909 6335
 		$computed=$val['computed'];
5910 6336
 		$unique=$val['unique'];
5911 6337
 		$required=$val['required'];
5912 6338
 		$param=$val['param'];
5913
-		if (is_array($val['arrayofkeyval'])) $param['options'] = $val['arrayofkeyval'];
6339
+		if (is_array($val['arrayofkeyval'])) {
6340
+		    $param['options'] = $val['arrayofkeyval'];
6341
+		}
5914 6342
 		if (preg_match('/^integer:(.*):(.*)/i', $val['type'], $reg))
5915 6343
 		{
5916 6344
 			$type='link';
@@ -5921,7 +6349,9 @@  discard block
 block discarded – undo
5921 6349
 		$help=$val['help'];
5922 6350
 		$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)
5923 6351
 
5924
-		if ($hidden) return '';
6352
+		if ($hidden) {
6353
+		    return '';
6354
+		}
5925 6355
 
5926 6356
 		// If field is a computed field, value must become result of compute
5927 6357
 		if ($computed)
@@ -5937,36 +6367,29 @@  discard block
 block discarded – undo
5937 6367
 			{
5938 6368
 				//$showsize=10;
5939 6369
 				$showsize = 'minwidth100imp';
5940
-			}
5941
-			elseif ($type == 'datetime')
6370
+			} elseif ($type == 'datetime')
5942 6371
 			{
5943 6372
 				//$showsize=19;
5944 6373
 				$showsize = 'minwidth200imp';
5945
-			}
5946
-			elseif (in_array($type,array('int','double','price')))
6374
+			} elseif (in_array($type,array('int','double','price')))
5947 6375
 			{
5948 6376
 				//$showsize=10;
5949 6377
 				$showsize = 'maxwidth75';
5950
-			}
5951
-			elseif ($type == 'url')
6378
+			} elseif ($type == 'url')
5952 6379
 			{
5953 6380
 				$showsize='minwidth400';
5954
-			}
5955
-			elseif ($type == 'boolean')
6381
+			} elseif ($type == 'boolean')
5956 6382
 			{
5957 6383
 				$showsize='';
5958
-			}
5959
-			else
6384
+			} else
5960 6385
 			{
5961 6386
 				if (round($size) < 12)
5962 6387
 				{
5963 6388
 					$showsize = 'minwidth100';
5964
-				}
5965
-				else if (round($size) <= 48)
6389
+				} else if (round($size) <= 48)
5966 6390
 				{
5967 6391
 					$showsize = 'minwidth200';
5968
-				}
5969
-				else
6392
+				} else
5970 6393
 				{
5971 6394
 					//$showsize=48;
5972 6395
 					$showsize = 'minwidth400';
@@ -5975,59 +6398,52 @@  discard block
 block discarded – undo
5975 6398
 		}
5976 6399
 
5977 6400
 		// Format output value differently according to properties of field
5978
-		if ($key == 'ref' && method_exists($this, 'getNomUrl')) $value=$this->getNomUrl(1, '', 0, '', 1);
5979
-		elseif ($key == 'status' && method_exists($this, 'getLibStatut')) $value=$this->getLibStatut(3);
5980
-		elseif ($type == 'date')
6401
+		if ($key == 'ref' && method_exists($this, 'getNomUrl')) {
6402
+		    $value=$this->getNomUrl(1, '', 0, '', 1);
6403
+		} elseif ($key == 'status' && method_exists($this, 'getLibStatut')) {
6404
+		    $value=$this->getLibStatut(3);
6405
+		} elseif ($type == 'date')
5981 6406
 		{
5982 6407
 			if(! empty($value)) {
5983 6408
 				$value=dol_print_date($value,'day');
5984 6409
 			} else {
5985 6410
 				$value='';
5986 6411
 			}
5987
-		}
5988
-		elseif ($type == 'datetime')
6412
+		} elseif ($type == 'datetime')
5989 6413
 		{
5990 6414
 			if(! empty($value)) {
5991 6415
 				$value=dol_print_date($value,'dayhour');
5992 6416
 			} else {
5993 6417
 				$value='';
5994 6418
 			}
5995
-		}
5996
-		elseif ($type == 'double')
6419
+		} elseif ($type == 'double')
5997 6420
 		{
5998 6421
 			if (!empty($value)) {
5999 6422
 				$value=price($value);
6000 6423
 			}
6001
-		}
6002
-		elseif ($type == 'boolean')
6424
+		} elseif ($type == 'boolean')
6003 6425
 		{
6004 6426
 			$checked='';
6005 6427
 			if (!empty($value)) {
6006 6428
 				$checked=' checked ';
6007 6429
 			}
6008 6430
 			$value='<input type="checkbox" '.$checked.' '.($moreparam?$moreparam:'').' readonly disabled>';
6009
-		}
6010
-		elseif ($type == 'mail')
6431
+		} elseif ($type == 'mail')
6011 6432
 		{
6012 6433
 			$value=dol_print_email($value,0,0,0,64,1,1);
6013
-		}
6014
-		elseif ($type == 'url')
6434
+		} elseif ($type == 'url')
6015 6435
 		{
6016 6436
 			$value=dol_print_url($value,'_blank',32,1);
6017
-		}
6018
-		elseif ($type == 'phone')
6437
+		} elseif ($type == 'phone')
6019 6438
 		{
6020 6439
 			$value=dol_print_phone($value, '', 0, 0, '', '&nbsp;', 1);
6021
-		}
6022
-		elseif ($type == 'price')
6440
+		} elseif ($type == 'price')
6023 6441
 		{
6024 6442
 			$value=price($value,0,$langs,0,0,-1,$conf->currency);
6025
-		}
6026
-		elseif ($type == 'select')
6443
+		} elseif ($type == 'select')
6027 6444
 		{
6028 6445
 			$value=$param['options'][$value];
6029
-		}
6030
-		elseif ($type == 'sellist')
6446
+		} elseif ($type == 'sellist')
6031 6447
 		{
6032 6448
 			$param_list=array_keys($param['options']);
6033 6449
 			$InfoFieldList = explode(":", $param_list[0]);
@@ -6057,7 +6473,7 @@  discard block
 block discarded – undo
6057 6473
 				$sql.= " WHERE ".$selectkey."=0";
6058 6474
 			} elseif ($selectkey=='rowid') {
6059 6475
 				$sql.= " WHERE ".$selectkey."=".$this->db->escape($value);
6060
-			}else {
6476
+			} else {
6061 6477
 				$sql.= " WHERE ".$selectkey."='".$this->db->escape($value)."'";
6062 6478
 			}
6063 6479
 
@@ -6084,12 +6500,11 @@  discard block
 block discarded – undo
6084 6500
 						}
6085 6501
 						if ($translabel!=$field_toshow) {
6086 6502
 							$value.=dol_trunc($translabel,18).' ';
6087
-						}else {
6503
+						} else {
6088 6504
 							$value.=$obj->$field_toshow.' ';
6089 6505
 						}
6090 6506
 					}
6091
-				}
6092
-				else
6507
+				} else
6093 6508
 				{
6094 6509
 					$translabel='';
6095 6510
 					if (!empty($obj->{$InfoFieldList[1]})) {
@@ -6097,18 +6512,17 @@  discard block
 block discarded – undo
6097 6512
 					}
6098 6513
 					if ($translabel!=$obj->{$InfoFieldList[1]}) {
6099 6514
 						$value=dol_trunc($translabel,18);
6100
-					}else {
6515
+					} else {
6101 6516
 						$value=$obj->{$InfoFieldList[1]};
6102 6517
 					}
6103 6518
 				}
6104
-			}
6105
-			else dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6106
-		}
6107
-		elseif ($type == 'radio')
6519
+			} else {
6520
+			    dol_syslog(get_class($this).'::showOutputField error '.$this->db->lasterror(), LOG_WARNING);
6521
+			}
6522
+		} elseif ($type == 'radio')
6108 6523
 		{
6109 6524
 			$value=$param['options'][$value];
6110
-		}
6111
-		elseif ($type == 'checkbox')
6525
+		} elseif ($type == 'checkbox')
6112 6526
 		{
6113 6527
 			$value_arr=explode(',',$value);
6114 6528
 			$value='';
@@ -6119,8 +6533,7 @@  discard block
 block discarded – undo
6119 6533
 				}
6120 6534
 				$value='<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">'.implode(' ', $toprint).'</ul></div>';
6121 6535
 			}
6122
-		}
6123
-		elseif ($type == 'chkbxlst')
6536
+		} elseif ($type == 'chkbxlst')
6124 6537
 		{
6125 6538
 			$value_arr = explode(',', $value);
6126 6539
 
@@ -6188,8 +6601,7 @@  discard block
 block discarded – undo
6188 6601
 			} else {
6189 6602
 				dol_syslog(get_class($this) . '::showOutputField error ' . $this->db->lasterror(), LOG_WARNING);
6190 6603
 			}
6191
-		}
6192
-		elseif ($type == 'link')
6604
+		} elseif ($type == 'link')
6193 6605
 		{
6194 6606
 			$out='';
6195 6607
 
@@ -6211,24 +6623,21 @@  discard block
 block discarded – undo
6211 6623
 						$object->fetch($value);
6212 6624
 						$value=$object->getNomUrl($getnomurlparam);
6213 6625
 					}
6214
-				}
6215
-				else
6626
+				} else
6216 6627
 				{
6217 6628
 					dol_syslog('Error bad setup of extrafield', LOG_WARNING);
6218 6629
 					return 'Error bad setup of extrafield';
6219 6630
 				}
6220
-			}
6221
-			else $value='';
6222
-		}
6223
-		elseif ($type == 'text' || $type == 'html')
6631
+			} else {
6632
+			    $value='';
6633
+			}
6634
+		} elseif ($type == 'text' || $type == 'html')
6224 6635
 		{
6225 6636
 			$value=dol_htmlentitiesbr($value);
6226
-		}
6227
-		elseif ($type == 'password')
6637
+		} elseif ($type == 'password')
6228 6638
 		{
6229 6639
 			$value=preg_replace('/./i','*',$value);
6230
-		}
6231
-		elseif ($type == 'array')
6640
+		} elseif ($type == 'array')
6232 6641
 		{
6233 6642
 			$value = implode('<br>', $value);
6234 6643
 		}
@@ -6255,7 +6664,9 @@  discard block
 block discarded – undo
6255 6664
 	{
6256 6665
 		global $db, $conf, $langs, $action, $form;
6257 6666
 
6258
-		if (! is_object($form)) $form=new Form($db);
6667
+		if (! is_object($form)) {
6668
+		    $form=new Form($db);
6669
+		}
6259 6670
 
6260 6671
 		$out = '';
6261 6672
 
@@ -6269,7 +6680,9 @@  discard block
 block discarded – undo
6269 6680
 			foreach($extrafields->attributes[$this->table_element]['label'] as $key=>$label)
6270 6681
 			{
6271 6682
 				// Show only the key field in params
6272
-				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) continue;
6683
+				if (is_array($params) && array_key_exists('onlykey',$params) && $key != $params['onlykey']) {
6684
+				    continue;
6685
+				}
6273 6686
 
6274 6687
 				$enabled = 1;
6275 6688
 				if ($enabled && isset($extrafields->attributes[$this->table_element]['list'][$key]))
@@ -6283,11 +6696,18 @@  discard block
 block discarded – undo
6283 6696
 					$perms = dol_eval($extrafields->attributes[$this->table_element]['perms'][$key], 1);
6284 6697
 				}
6285 6698
 
6286
-				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) continue;	// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6287
-				if (empty($perms)) continue;
6699
+				if (($mode == 'create' || $mode == 'edit') && abs($enabled) != 1 && abs($enabled) != 3) {
6700
+				    continue;
6701
+				}
6702
+				// <> -1 and <> 1 and <> 3 = not visible on forms, only on list
6703
+				if (empty($perms)) {
6704
+				    continue;
6705
+				}
6288 6706
 
6289 6707
 				// Load language if required
6290
-				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6708
+				if (! empty($extrafields->attributes[$this->table_element]['langfile'][$key])) {
6709
+				    $langs->load($extrafields->attributes[$this->table_element]['langfile'][$key]);
6710
+				}
6291 6711
 
6292 6712
 				$colspan='3';
6293 6713
 				if (is_array($params) && count($params)>0) {
@@ -6321,8 +6741,7 @@  discard block
 block discarded – undo
6321 6741
 				if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate')
6322 6742
 				{
6323 6743
 					$out .= $extrafields->showSeparator($key, $this);
6324
-				}
6325
-				else
6744
+				} else
6326 6745
 				{
6327 6746
 					$csstyle='';
6328 6747
 					$class=(!empty($extrafields->attributes[$this->table_element]['hidden'][$key]) ? 'hideobject ' : '');
@@ -6352,9 +6771,11 @@  discard block
 block discarded – undo
6352 6771
 					if (in_array($extrafields->attributes[$this->table_element]['type'][$key],array('date','datetime')))
6353 6772
 					{
6354 6773
 						$datenotinstring = $this->array_options['options_' . $key];
6355
-						if (! is_numeric($this->array_options['options_' . $key]))	// For backward compatibility
6774
+						if (! is_numeric($this->array_options['options_' . $key])) {
6775
+						    // For backward compatibility
6356 6776
 						{
6357
-							$datenotinstring = $this->db->jdate($datenotinstring);
6777
+							$datenotinstring = $this->db->jdate($datenotinstring);
6778
+						}
6358 6779
 						}
6359 6780
 						$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;
6360 6781
 					}
@@ -6367,11 +6788,18 @@  discard block
 block discarded – undo
6367 6788
 					$labeltoshow = $langs->trans($label);
6368 6789
 
6369 6790
 					$out .= '<td class="titlefield';
6370
-					if (GETPOST('action','none') == 'create') $out.='create';
6371
-					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) $out .= ' fieldrequired';
6791
+					if (GETPOST('action','none') == 'create') {
6792
+					    $out.='create';
6793
+					}
6794
+					if ($mode != 'view' && ! empty($extrafields->attributes[$this->table_element]['required'][$key])) {
6795
+					    $out .= ' fieldrequired';
6796
+					}
6372 6797
 					$out .= '">';
6373
-					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6374
-					else $out .= $labeltoshow;
6798
+					if (! empty($extrafields->attributes[$object->table_element]['help'][$key])) {
6799
+					    $out .= $form->textwithpicto($labeltoshow, $extrafields->attributes[$object->table_element]['help'][$key]);
6800
+					} else {
6801
+					    $out .= $labeltoshow;
6802
+					}
6375 6803
 					$out .= '</td>';
6376 6804
 
6377 6805
 					$html_id = !empty($this->id) ? $this->element.'_extras_'.$key.'_'.$this->id : '';
@@ -6388,8 +6816,11 @@  discard block
 block discarded – undo
6388 6816
 
6389 6817
 					$out .= '</td>';
6390 6818
 
6391
-					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) $out .= '</tr>';
6392
-					else $out .= '</tr>';
6819
+					if (! empty($conf->global->MAIN_EXTRAFIELDS_USE_TWO_COLUMS) && (($e % 2) == 1)) {
6820
+					    $out .= '</tr>';
6821
+					} else {
6822
+					    $out .= '</tr>';
6823
+					}
6393 6824
 					$e++;
6394 6825
 				}
6395 6826
 			}
@@ -6441,7 +6872,9 @@  discard block
 block discarded – undo
6441 6872
 		global $user;
6442 6873
 
6443 6874
 		$element = $this->element;
6444
-		if ($element == 'facturerec') $element='facture';
6875
+		if ($element == 'facturerec') {
6876
+		    $element='facture';
6877
+		}
6445 6878
 
6446 6879
 		return $user->rights->{$element};
6447 6880
 	}
@@ -6466,7 +6899,10 @@  discard block
 block discarded – undo
6466 6899
 
6467 6900
 			if (! $db->query($sql))
6468 6901
 			{
6469
-				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.
6902
+				if ($ignoreerrors) {
6903
+				    return true;
6904
+				}
6905
+				// 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.
6470 6906
 				//$this->errors = $db->lasterror();
6471 6907
 				return false;
6472 6908
 			}
@@ -6493,11 +6929,12 @@  discard block
 block discarded – undo
6493 6929
 
6494 6930
 		$buyPrice = 0;
6495 6931
 
6496
-		if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
6932
+		if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) {
6933
+		    // In most cases, test here is false
6497 6934
 		{
6498
-			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
6499
-		}
6500
-		else
6935
+			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
6936
+		}
6937
+		} else
6501 6938
 		{
6502 6939
 			// Get cost price for margin calculation
6503 6940
 			if (! empty($fk_product))
@@ -6515,13 +6952,11 @@  discard block
 block discarded – undo
6515 6952
 					if ($product->cost_price > 0)
6516 6953
 					{
6517 6954
 						$buyPrice = $product->cost_price;
6518
-					}
6519
-					else if ($product->pmp > 0)
6955
+					} else if ($product->pmp > 0)
6520 6956
 					{
6521 6957
 						$buyPrice = $product->pmp;
6522 6958
 					}
6523
-				}
6524
-				else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
6959
+				} else if (isset($conf->global->MARGIN_TYPE) && $conf->global->MARGIN_TYPE == 'pmp')
6525 6960
 				{
6526 6961
 					require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
6527 6962
 					$product = new Product($this->db);
@@ -6544,8 +6979,7 @@  discard block
 block discarded – undo
6544 6979
 					if (($result = $productFournisseur->find_min_price_product_fournisseur($fk_product)) > 0)
6545 6980
 					{
6546 6981
 						$buyPrice = $productFournisseur->fourn_unitprice;
6547
-					}
6548
-					else if ($result < 0)
6982
+					} else if ($result < 0)
6549 6983
 					{
6550 6984
 						$this->errors[] = $productFournisseur->error;
6551 6985
 						return -2;
@@ -6591,8 +7025,7 @@  discard block
 block discarded – undo
6591 7025
 		{
6592 7026
 			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6593 7027
 			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->track_id.'/';
6594
-		}
6595
-		else
7028
+		} else
6596 7029
 		{
6597 7030
 			$dir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
6598 7031
 			$pdir .= get_exdir(0, 0, 0, 0, $this, $modulepart).$this->ref.'/';
@@ -6655,19 +7088,26 @@  discard block
 block discarded – undo
6655 7088
 
6656 7089
 						// Find name of thumb file
6657 7090
 						$photo_vignette=basename(getImageFileNameForSize($dir.$file, '_small'));
6658
-						if (! dol_is_file($dirthumb.$photo_vignette)) $photo_vignette='';
7091
+						if (! dol_is_file($dirthumb.$photo_vignette)) {
7092
+						    $photo_vignette='';
7093
+						}
6659 7094
 
6660 7095
 						// Get filesize of original file
6661 7096
 						$imgarray=dol_getImageSize($dir.$photo);
6662 7097
 
6663 7098
 						if ($nbbyrow > 0)
6664 7099
 						{
6665
-							if ($nbphoto == 1) $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7100
+							if ($nbphoto == 1) {
7101
+							    $return.= '<table width="100%" valign="top" align="center" border="0" cellpadding="2" cellspacing="2">';
7102
+							}
6666 7103
 
6667
-							if ($nbphoto % $nbbyrow == 1) $return.= '<tr align=center valign=middle border=1>';
7104
+							if ($nbphoto % $nbbyrow == 1) {
7105
+							    $return.= '<tr align=center valign=middle border=1>';
7106
+							}
6668 7107
 							$return.= '<td width="'.ceil(100/$nbbyrow).'%" class="photo">';
6669
-						}
6670
-						else if ($nbbyrow < 0) $return .= '<div class="inline-block">';
7108
+						} else if ($nbbyrow < 0) {
7109
+						    $return .= '<div class="inline-block">';
7110
+						}
6671 7111
 
6672 7112
 						$return.= "\n";
6673 7113
 
@@ -6675,15 +7115,20 @@  discard block
 block discarded – undo
6675 7115
 						if (empty($nolink))
6676 7116
 						{
6677 7117
 							$urladvanced=getAdvancedPreviewUrl($modulepart, $relativefile, 0, 'entity='.$this->entity);
6678
-							if ($urladvanced) $return.='<a href="'.$urladvanced.'">';
6679
-							else $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
7118
+							if ($urladvanced) {
7119
+							    $return.='<a href="'.$urladvanced.'">';
7120
+							} else {
7121
+							    $return.= '<a href="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'" class="aphoto" target="_blank">';
7122
+							}
6680 7123
 						}
6681 7124
 
6682 7125
 						// Show image (width height=$maxHeight)
6683 7126
 						// Si fichier vignette disponible et image source trop grande, on utilise la vignette, sinon on utilise photo origine
6684 7127
 						$alt=$langs->transnoentitiesnoconv('File').': '.$relativefile;
6685 7128
 						$alt.=' - '.$langs->transnoentitiesnoconv('Size').': '.$imgarray['width'].'x'.$imgarray['height'];
6686
-						if ($notitle) $alt='';
7129
+						if ($notitle) {
7130
+						    $alt='';
7131
+						}
6687 7132
 
6688 7133
 						if ($usesharelink)
6689 7134
 						{
@@ -6693,35 +7138,35 @@  discard block
 block discarded – undo
6693 7138
 								{
6694 7139
 									$return.= '<!-- Show original file (thumb not yet available with shared links) -->';
6695 7140
 									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6696
-								}
6697
-								else {
7141
+								} else {
6698 7142
 									$return.= '<!-- Show original file -->';
6699 7143
 									$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/viewimage.php?hashp='.urlencode($val['share']).'" title="'.dol_escape_htmltag($alt).'">';
6700 7144
 								}
6701
-							}
6702
-							else
7145
+							} else
6703 7146
 							{
6704 7147
 								$return.= '<!-- Show nophoto file (because file is not shared) -->';
6705 7148
 								$return.= '<img class="photo photowithmargin" border="0" height="'.$maxHeight.'" src="'.DOL_URL_ROOT.'/public/theme/common/nophoto.png" title="'.dol_escape_htmltag($alt).'">';
6706 7149
 							}
6707
-						}
6708
-						else
7150
+						} else
6709 7151
 						{
6710 7152
 							if (empty($maxHeight) || $photo_vignette && $imgarray['height'] > $maxHeight)
6711 7153
 							{
6712 7154
 								$return.= '<!-- Show thumb -->';
6713 7155
 								$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).'">';
6714
-							}
6715
-							else {
7156
+							} else {
6716 7157
 								$return.= '<!-- Show original file -->';
6717 7158
 								$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).'">';
6718 7159
 							}
6719 7160
 						}
6720 7161
 
6721
-						if (empty($nolink)) $return.= '</a>';
7162
+						if (empty($nolink)) {
7163
+						    $return.= '</a>';
7164
+						}
6722 7165
 						$return.="\n";
6723 7166
 
6724
-						if ($showfilename) $return.= '<br>'.$viewfilename;
7167
+						if ($showfilename) {
7168
+						    $return.= '<br>'.$viewfilename;
7169
+						}
6725 7170
 						if ($showaction)
6726 7171
 						{
6727 7172
 							$return.= '<br>';
@@ -6746,15 +7191,20 @@  discard block
 block discarded – undo
6746 7191
 						if ($nbbyrow > 0)
6747 7192
 						{
6748 7193
 							$return.= '</td>';
6749
-							if (($nbphoto % $nbbyrow) == 0) $return.= '</tr>';
6750
-						}
6751
-						else if ($nbbyrow < 0) $return.='</div>';
7194
+							if (($nbphoto % $nbbyrow) == 0) {
7195
+							    $return.= '</tr>';
7196
+							}
7197
+						} else if ($nbbyrow < 0) {
7198
+						    $return.='</div>';
7199
+						}
6752 7200
 					}
6753 7201
 
6754 7202
 					if (empty($size)) {     // Format origine
6755 7203
 						$return.= '<img class="photo photowithmargin" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$modulepart.'&entity='.$this->entity.'&file='.urlencode($pdir.$photo).'">';
6756 7204
 
6757
-						if ($showfilename) $return.= '<br>'.$viewfilename;
7205
+						if ($showfilename) {
7206
+						    $return.= '<br>'.$viewfilename;
7207
+						}
6758 7208
 						if ($showaction)
6759 7209
 						{
6760 7210
 							// Special case for product
@@ -6771,7 +7221,9 @@  discard block
 block discarded – undo
6771 7221
 					}
6772 7222
 
6773 7223
 					// On continue ou on arrete de boucler ?
6774
-					if ($nbmax && $nbphoto >= $nbmax) break;
7224
+					if ($nbmax && $nbphoto >= $nbmax) {
7225
+					    break;
7226
+					}
6775 7227
 				}
6776 7228
 			}
6777 7229
 
@@ -6786,7 +7238,9 @@  discard block
 block discarded – undo
6786 7238
 						$nbphoto++;
6787 7239
 					}
6788 7240
 
6789
-					if ($nbphoto) $return.= '</table>';
7241
+					if ($nbphoto) {
7242
+					    $return.= '</table>';
7243
+					}
6790 7244
 				}
6791 7245
 			}
6792 7246
 		}
@@ -6807,10 +7261,14 @@  discard block
 block discarded – undo
6807 7261
 	{
6808 7262
 		if(is_array($info))
6809 7263
 		{
6810
-			if(isset($info['type']) && $info['type']=='array') return true;
6811
-			else return false;
6812
-		}
6813
-		else return false;
7264
+			if(isset($info['type']) && $info['type']=='array') {
7265
+			    return true;
7266
+			} else {
7267
+			    return false;
7268
+			}
7269
+		} else {
7270
+		    return false;
7271
+		}
6814 7272
 	}
6815 7273
 
6816 7274
 	/**
@@ -6823,10 +7281,14 @@  discard block
 block discarded – undo
6823 7281
 	{
6824 7282
 		if(is_array($info))
6825 7283
 		{
6826
-			if(isset($info['type']) && $info['type']=='null') return true;
6827
-			else return false;
6828
-		}
6829
-		else return false;
7284
+			if(isset($info['type']) && $info['type']=='null') {
7285
+			    return true;
7286
+			} else {
7287
+			    return false;
7288
+			}
7289
+		} else {
7290
+		    return false;
7291
+		}
6830 7292
 	}
6831 7293
 
6832 7294
 	/**
@@ -6837,8 +7299,11 @@  discard block
 block discarded – undo
6837 7299
 	 */
6838 7300
 	public function isDate($info)
6839 7301
 	{
6840
-		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) return true;
6841
-		else return false;
7302
+		if(isset($info['type']) && ($info['type']=='date' || $info['type']=='datetime' || $info['type']=='timestamp')) {
7303
+		    return true;
7304
+		} else {
7305
+		    return false;
7306
+		}
6842 7307
 	}
6843 7308
 
6844 7309
 	/**
@@ -6851,10 +7316,14 @@  discard block
 block discarded – undo
6851 7316
 	{
6852 7317
 		if(is_array($info))
6853 7318
 		{
6854
-			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) return true;
6855
-			else return false;
6856
-		}
6857
-		else return false;
7319
+			if(isset($info['type']) && ($info['type']=='int' || preg_match('/^integer/i',$info['type']) ) ) {
7320
+			    return true;
7321
+			} else {
7322
+			    return false;
7323
+			}
7324
+		} else {
7325
+		    return false;
7326
+		}
6858 7327
 	}
6859 7328
 
6860 7329
 	/**
@@ -6867,10 +7336,14 @@  discard block
 block discarded – undo
6867 7336
 	{
6868 7337
 		if(is_array($info))
6869 7338
 		{
6870
-			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) return true;
6871
-			else return false;
6872
-		}
6873
-		else return false;
7339
+			if (isset($info['type']) && (preg_match('/^(double|real)/i', $info['type']))) {
7340
+			    return true;
7341
+			} else {
7342
+			    return false;
7343
+			}
7344
+		} else {
7345
+		    return false;
7346
+		}
6874 7347
 	}
6875 7348
 
6876 7349
 	/**
@@ -6883,10 +7356,14 @@  discard block
 block discarded – undo
6883 7356
 	{
6884 7357
 		if(is_array($info))
6885 7358
 		{
6886
-			if(isset($info['type']) && $info['type']=='text') return true;
6887
-			else return false;
6888
-		}
6889
-		else return false;
7359
+			if(isset($info['type']) && $info['type']=='text') {
7360
+			    return true;
7361
+			} else {
7362
+			    return false;
7363
+			}
7364
+		} else {
7365
+		    return false;
7366
+		}
6890 7367
 	}
6891 7368
 
6892 7369
 	/**
@@ -6899,10 +7376,14 @@  discard block
 block discarded – undo
6899 7376
 	{
6900 7377
 		if(is_array($info))
6901 7378
 		{
6902
-			if(isset($info['index']) && $info['index']==true) return true;
6903
-			else return false;
6904
-		}
6905
-		else return false;
7379
+			if(isset($info['index']) && $info['index']==true) {
7380
+			    return true;
7381
+			} else {
7382
+			    return false;
7383
+			}
7384
+		} else {
7385
+		    return false;
7386
+		}
6906 7387
 	}
6907 7388
 
6908 7389
 	/**
@@ -6916,21 +7397,21 @@  discard block
 block discarded – undo
6916 7397
 		global $conf;
6917 7398
 
6918 7399
 		$queryarray=array();
6919
-		foreach ($this->fields as $field=>$info)	// Loop on definition of fields
7400
+		foreach ($this->fields as $field=>$info) {
7401
+		    // Loop on definition of fields
6920 7402
 		{
6921 7403
 			// Depending on field type ('datetime', ...)
6922 7404
 			if($this->isDate($info))
6923 7405
 			{
6924 7406
 				if(empty($this->{$field}))
6925 7407
 				{
6926
-					$queryarray[$field] = null;
6927
-				}
6928
-				else
7408
+					$queryarray[$field] = null;
7409
+		}
7410
+				} else
6929 7411
 				{
6930 7412
 					$queryarray[$field] = $this->db->idate($this->{$field});
6931 7413
 				}
6932
-			}
6933
-			else if($this->isArray($info))
7414
+			} else if($this->isArray($info))
6934 7415
 			{
6935 7416
 				if(! empty($this->{$field})) {
6936 7417
 					if(! is_array($this->{$field})) {
@@ -6940,28 +7421,35 @@  discard block
 block discarded – undo
6940 7421
 				} else {
6941 7422
 					$queryarray[$field] = null;
6942 7423
 				}
6943
-			}
6944
-			else if($this->isInt($info))
7424
+			} else if($this->isInt($info))
6945 7425
 			{
6946
-				if ($field == 'entity' && is_null($this->{$field})) $queryarray[$field]=$conf->entity;
6947
-				else
7426
+				if ($field == 'entity' && is_null($this->{$field})) {
7427
+				    $queryarray[$field]=$conf->entity;
7428
+				} else
6948 7429
 				{
6949 7430
 					$queryarray[$field] = (int) price2num($this->{$field});
6950
-					if (empty($queryarray[$field])) $queryarray[$field]=0;		// May be reset to null later if property 'notnull' is -1 for this field.
7431
+					if (empty($queryarray[$field])) {
7432
+					    $queryarray[$field]=0;
7433
+					}
7434
+					// May be reset to null later if property 'notnull' is -1 for this field.
6951 7435
 				}
6952
-			}
6953
-			else if($this->isFloat($info))
7436
+			} else if($this->isFloat($info))
6954 7437
 			{
6955 7438
 				$queryarray[$field] = (double) price2num($this->{$field});
6956
-				if (empty($queryarray[$field])) $queryarray[$field]=0;
6957
-			}
6958
-			else
7439
+				if (empty($queryarray[$field])) {
7440
+				    $queryarray[$field]=0;
7441
+				}
7442
+			} else
6959 7443
 			{
6960 7444
 				$queryarray[$field] = $this->{$field};
6961 7445
 			}
6962 7446
 
6963
-			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) unset($queryarray[$field]);
6964
-			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) $queryarray[$field] = null;
7447
+			if ($info['type'] == 'timestamp' && empty($queryarray[$field])) {
7448
+			    unset($queryarray[$field]);
7449
+			}
7450
+			if (! empty($info['notnull']) && $info['notnull'] == -1 && empty($queryarray[$field])) {
7451
+			    $queryarray[$field] = null;
7452
+			}
6965 7453
 		}
6966 7454
 
6967 7455
 		return $queryarray;
@@ -6979,42 +7467,47 @@  discard block
 block discarded – undo
6979 7467
 		{
6980 7468
 			if($this->isDate($info))
6981 7469
 			{
6982
-				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') $this->{$field} = 0;
6983
-				else $this->{$field} = strtotime($obj->{$field});
6984
-			}
6985
-			elseif($this->isArray($info))
7470
+				if(empty($obj->{$field}) || $obj->{$field} === '0000-00-00 00:00:00' || $obj->{$field} === '1000-01-01 00:00:00') {
7471
+				    $this->{$field} = 0;
7472
+				} else {
7473
+				    $this->{$field} = strtotime($obj->{$field});
7474
+				}
7475
+			} elseif($this->isArray($info))
6986 7476
 			{
6987 7477
 				if(! empty($obj->{$field})) {
6988 7478
 					$this->{$field} = @unserialize($obj->{$field});
6989 7479
 					// Hack for data not in UTF8
6990
-					if($this->{$field } === false) @unserialize(utf8_decode($obj->{$field}));
7480
+					if($this->{$field } === false) {
7481
+					    @unserialize(utf8_decode($obj->{$field}));
7482
+					}
6991 7483
 				} else {
6992 7484
 					$this->{$field} = array();
6993 7485
 				}
6994
-			}
6995
-			elseif($this->isInt($info))
7486
+			} elseif($this->isInt($info))
6996 7487
 			{
6997
-				if ($field == 'rowid') $this->id = (int) $obj->{$field};
6998
-				else $this->{$field} = (int) $obj->{$field};
6999
-			}
7000
-			elseif($this->isFloat($info))
7488
+				if ($field == 'rowid') {
7489
+				    $this->id = (int) $obj->{$field};
7490
+				} else {
7491
+				    $this->{$field} = (int) $obj->{$field};
7492
+				}
7493
+			} elseif($this->isFloat($info))
7001 7494
 			{
7002 7495
 				$this->{$field} = (double) $obj->{$field};
7003
-			}
7004
-			elseif($this->isNull($info))
7496
+			} elseif($this->isNull($info))
7005 7497
 			{
7006 7498
 				$val = $obj->{$field};
7007 7499
 				// zero is not null
7008 7500
 				$this->{$field} = (is_null($val) || (empty($val) && $val!==0 && $val!=='0') ? null : $val);
7009
-			}
7010
-			else
7501
+			} else
7011 7502
 			{
7012 7503
 				$this->{$field} = $obj->{$field};
7013 7504
 			}
7014 7505
 		}
7015 7506
 
7016 7507
 		// If there is no 'ref' field, we force property ->ref to ->id for a better compatibility with common functions.
7017
-		if (! isset($this->fields['ref']) && isset($this->id)) $this->ref = $this->id;
7508
+		if (! isset($this->fields['ref']) && isset($this->id)) {
7509
+		    $this->ref = $this->id;
7510
+		}
7018 7511
 	}
7019 7512
 
7020 7513
 	/**
@@ -7037,9 +7530,13 @@  discard block
 block discarded – undo
7037 7530
 	 */
7038 7531
     protected function quote($value, $fieldsentry)
7039 7532
     {
7040
-		if (is_null($value)) return 'NULL';
7041
-		else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) return $this->db->escape("$value");
7042
-		else return "'".$this->db->escape($value)."'";
7533
+		if (is_null($value)) {
7534
+		    return 'NULL';
7535
+		} else if (preg_match('/^(int|double|real)/i', $fieldsentry['type'])) {
7536
+		    return $this->db->escape("$value");
7537
+		} else {
7538
+		    return "'".$this->db->escape($value)."'";
7539
+		}
7043 7540
 	}
7044 7541
 
7045 7542
 
@@ -7059,8 +7556,12 @@  discard block
 block discarded – undo
7059 7556
 		$now=dol_now();
7060 7557
 
7061 7558
 		$fieldvalues = $this->setSaveQuery();
7062
-		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) $fieldvalues['date_creation']=$this->db->idate($now);
7063
-		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) $fieldvalues['fk_user_creat']=$user->id;
7559
+		if (array_key_exists('date_creation', $fieldvalues) && empty($fieldvalues['date_creation'])) {
7560
+		    $fieldvalues['date_creation']=$this->db->idate($now);
7561
+		}
7562
+		if (array_key_exists('fk_user_creat', $fieldvalues) && ! ($fieldvalues['fk_user_creat'] > 0)) {
7563
+		    $fieldvalues['fk_user_creat']=$user->id;
7564
+		}
7064 7565
 		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into insert.
7065 7566
 
7066 7567
 		$keys=array();
@@ -7075,8 +7576,12 @@  discard block
 block discarded – undo
7075 7576
 		foreach($keys as $key)
7076 7577
 		{
7077 7578
 			// If field is an implicit foreign key field
7078
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';
7079
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';
7579
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
7580
+			    $values[$key]='';
7581
+			}
7582
+			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
7583
+			    $values[$key]='';
7584
+			}
7080 7585
 
7081 7586
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7082 7587
 			if (isset($this->fields[$key]['notnull']) && $this->fields[$key]['notnull'] == 1 && ! isset($values[$key]) && is_null($val['default']))
@@ -7086,11 +7591,17 @@  discard block
 block discarded – undo
7086 7591
 			}
7087 7592
 
7088 7593
 			// If field is an implicit foreign key field
7089
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) $values[$key]='null';
7090
-			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) $values[$key]='null';
7594
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && empty($values[$key])) {
7595
+			    $values[$key]='null';
7596
+			}
7597
+			if (! empty($this->fields[$key]['foreignkey']) && empty($values[$key])) {
7598
+			    $values[$key]='null';
7599
+			}
7091 7600
 		}
7092 7601
 
7093
-		if ($error) return -1;
7602
+		if ($error) {
7603
+		    return -1;
7604
+		}
7094 7605
 
7095 7606
 		$this->db->begin();
7096 7607
 
@@ -7116,7 +7627,9 @@  discard block
 block discarded – undo
7116 7627
 		if (! $error)
7117 7628
 		{
7118 7629
 			$result=$this->insertExtraFields();
7119
-			if ($result < 0) $error++;
7630
+			if ($result < 0) {
7631
+			    $error++;
7632
+			}
7120 7633
 		}
7121 7634
 
7122 7635
 		// Triggers
@@ -7149,15 +7662,24 @@  discard block
 block discarded – undo
7149 7662
 	 */
7150 7663
 	public function fetchCommon($id, $ref = null, $morewhere = '')
7151 7664
 	{
7152
-		if (empty($id) && empty($ref) && empty($morewhere)) return -1;
7665
+		if (empty($id) && empty($ref) && empty($morewhere)) {
7666
+		    return -1;
7667
+		}
7153 7668
 
7154 7669
 		$sql = 'SELECT '.$this->getFieldList();
7155 7670
 		$sql.= ' FROM '.MAIN_DB_PREFIX.$this->table_element;
7156 7671
 
7157
-		if (!empty($id))  $sql.= ' WHERE rowid = '.$id;
7158
-		elseif (!empty($ref)) $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7159
-		else $sql.=' WHERE 1 = 1';	// usage with empty id and empty ref is very rare
7160
-		if ($morewhere)   $sql.= $morewhere;
7672
+		if (!empty($id)) {
7673
+		    $sql.= ' WHERE rowid = '.$id;
7674
+		} elseif (!empty($ref)) {
7675
+		    $sql.= " WHERE ref = ".$this->quote($ref, $this->fields['ref']);
7676
+		} else {
7677
+		    $sql.=' WHERE 1 = 1';
7678
+		}
7679
+		// usage with empty id and empty ref is very rare
7680
+		if ($morewhere) {
7681
+		    $sql.= $morewhere;
7682
+		}
7161 7683
 		$sql.=' LIMIT 1';	// This is a fetch, to be sure to get only one record
7162 7684
 
7163 7685
 		$res = $this->db->query($sql);
@@ -7168,13 +7690,11 @@  discard block
 block discarded – undo
7168 7690
 			{
7169 7691
 				$this->setVarsFromFetchObj($obj);
7170 7692
 				return $this->id;
7171
-			}
7172
-			else
7693
+			} else
7173 7694
 			{
7174 7695
 				return 0;
7175 7696
 			}
7176
-		}
7177
-		else
7697
+		} else
7178 7698
 		{
7179 7699
 			$this->error = $this->db->lasterror();
7180 7700
 			$this->errors[] = $this->error;
@@ -7198,8 +7718,12 @@  discard block
 block discarded – undo
7198 7718
 		$now=dol_now();
7199 7719
 
7200 7720
 		$fieldvalues = $this->setSaveQuery();
7201
-		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) $fieldvalues['date_modification']=$this->db->idate($now);
7202
-		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) $fieldvalues['fk_user_modif']=$user->id;
7721
+		if (array_key_exists('date_modification', $fieldvalues) && empty($fieldvalues['date_modification'])) {
7722
+		    $fieldvalues['date_modification']=$this->db->idate($now);
7723
+		}
7724
+		if (array_key_exists('fk_user_modif', $fieldvalues) && ! ($fieldvalues['fk_user_modif'] > 0)) {
7725
+		    $fieldvalues['fk_user_modif']=$user->id;
7726
+		}
7203 7727
 		unset($fieldvalues['rowid']);	// The field 'rowid' is reserved field name for autoincrement field so we don't need it into update.
7204 7728
 
7205 7729
 		$keys=array();
@@ -7214,8 +7738,14 @@  discard block
 block discarded – undo
7214 7738
 		// Clean and check mandatory
7215 7739
 		foreach($keys as $key)
7216 7740
 		{
7217
-			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') $values[$key]='';		// This is an implicit foreign key field
7218
-			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') $values[$key]='';					// This is an explicit foreign key field
7741
+			if (preg_match('/^integer:/i', $this->fields[$key]['type']) && $values[$key] == '-1') {
7742
+			    $values[$key]='';
7743
+			}
7744
+			// This is an implicit foreign key field
7745
+			if (! empty($this->fields[$key]['foreignkey']) && $values[$key] == '-1') {
7746
+			    $values[$key]='';
7747
+			}
7748
+			// This is an explicit foreign key field
7219 7749
 
7220 7750
 			//var_dump($key.'-'.$values[$key].'-'.($this->fields[$key]['notnull'] == 1));
7221 7751
 			/*
@@ -7296,10 +7826,11 @@  discard block
 block discarded – undo
7296 7826
 					return -1;
7297 7827
 				}
7298 7828
 			}
7299
-		}
7300
-		elseif (! empty($this->fk_element) && ! empty($this->childtables))	// If object has childs linked with a foreign key field, we check all child tables.
7829
+		} elseif (! empty($this->fk_element) && ! empty($this->childtables)) {
7830
+		    // If object has childs linked with a foreign key field, we check all child tables.
7301 7831
 		{
7302
-			$objectisused = $this->isObjectUsed($this->id);
7832
+			$objectisused = $this->isObjectUsed($this->id);
7833
+		}
7303 7834
 			if (! empty($objectisused))
7304 7835
 			{
7305 7836
 				dol_syslog(get_class($this)."::deleteCommon Can't delete record as it has some child", LOG_WARNING);
@@ -7406,7 +7937,9 @@  discard block
 block discarded – undo
7406 7937
      */
7407 7938
     public function trimParameters($parameters)
7408 7939
     {
7409
-        if (!is_array($parameters)) return;
7940
+        if (!is_array($parameters)) {
7941
+            return;
7942
+        }
7410 7943
         foreach ($parameters as $parameter) {
7411 7944
             if (isset($this->$parameter)) {
7412 7945
                 $this->$parameter = trim($this->$parameter);
Please login to merge, or discard this patch.