Passed
Push — master ( 65bdac...4e88da )
by Alxarafe
32:38
created
Controllers/Categories.php 3 patches
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@
 block discarded – undo
46 46
     {
47 47
 
48 48
 // Load translation files required by the page
49
-       Globals::$langs->load("categories");
49
+        Globals::$langs->load("categories");
50 50
 
51 51
 // Security check
52 52
         $socid = DolUtils::GETPOST('socid', 'int');
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -104,28 +104,28 @@  discard block
 block discarded – undo
104 104
             // Action ajout d'une categorie
105 105
             if ($cancel) {
106 106
                 if ($urlfrom) {
107
-                    header("Location: " . $urlfrom);
107
+                    header("Location: ".$urlfrom);
108 108
                     exit;
109 109
                 } else if ($idProdOrigin) {
110
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idProdOrigin . '&type=' . $type);
110
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type);
111 111
                     exit;
112 112
                 } else if ($idCompanyOrigin) {
113
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idCompanyOrigin . '&type=' . $type);
113
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type);
114 114
                     exit;
115 115
                 } else if ($idSupplierOrigin) {
116
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idSupplierOrigin . '&type=' . $type);
116
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type);
117 117
                     exit;
118 118
                 } else if ($idMemberOrigin) {
119
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idMemberOrigin . '&type=' . $type);
119
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type);
120 120
                     exit;
121 121
                 } else if ($idContactOrigin) {
122
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idContactOrigin . '&type=' . $type);
122
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type);
123 123
                     exit;
124 124
                 } else if ($idProjectOrigin) {
125
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idProjectOrigin . '&type=' . $type);
125
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type);
126 126
                     exit;
127 127
                 } else {
128
-                    header("Location: " . DOL_URL_ROOT . '/categories/index.php?leftmenu=cat&type=' . $type);
128
+                    header("Location: ".DOL_URL_ROOT.'/categories/index.php?leftmenu=cat&type='.$type);
129 129
                     exit;
130 130
                 }
131 131
             }
@@ -169,32 +169,32 @@  discard block
 block discarded – undo
169 169
             // Action confirmation de creation categorie
170 170
             if ($action == 'confirmed') {
171 171
                 if ($urlfrom) {
172
-                    header("Location: " . $urlfrom);
172
+                    header("Location: ".$urlfrom);
173 173
                     exit;
174 174
                 } elseif ($backtopage) {
175
-                    header("Location: " . $backtopage);
175
+                    header("Location: ".$backtopage);
176 176
                     exit;
177 177
                 } else if ($idProdOrigin) {
178
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idProdOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
178
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
179 179
                     exit;
180 180
                 } else if ($idCompanyOrigin) {
181
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idCompanyOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
181
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
182 182
                     exit;
183 183
                 } else if ($idSupplierOrigin) {
184
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idSupplierOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
184
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
185 185
                     exit;
186 186
                 } else if ($idMemberOrigin) {
187
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idMemberOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
187
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
188 188
                     exit;
189 189
                 } else if ($idContactOrigin) {
190
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idContactOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
190
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
191 191
                     exit;
192 192
                 } else if ($idProjectOrigin) {
193
-                    header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $idProjectOrigin . '&type=' . $type . '&mesg=' . urlencode($langs->trans("CatCreated")));
193
+                    header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated")));
194 194
                     exit;
195 195
                 }
196 196
 
197
-                header("Location: " . DOL_URL_ROOT . '/categories/viewcat.php?id=' . $result . '&type=' . $type);
197
+                header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$result.'&type='.$type);
198 198
                 exit;
199 199
             }
200 200
         }
Please login to merge, or discard this patch.
Braces   +30 added lines, -20 removed lines patch added patch discarded remove patch
@@ -50,8 +50,9 @@  discard block
 block discarded – undo
50 50
 
51 51
 // Security check
52 52
         $socid = DolUtils::GETPOST('socid', 'int');
53
-        if (!Globals::$user->rights->categorie->lire)
54
-            accessforbidden();
53
+        if (!Globals::$user->rights->categorie->lire) {
54
+                    accessforbidden();
55
+        }
55 56
 
56 57
         $action = DolUtils::GETPOST('action', 'alpha');
57 58
         $cancel = DolUtils::GETPOST('cancel', 'alpha');
@@ -69,22 +70,29 @@  discard block
 block discarded – undo
69 70
         $parent = DolUtils::GETPOST('parent');
70 71
 
71 72
         if ($origin) {
72
-            if ($type == Categorie::TYPE_PRODUCT)
73
-                $idProdOrigin = $origin;
74
-            if ($type == Categorie::TYPE_SUPPLIER)
75
-                $idSupplierOrigin = $origin;
76
-            if ($type == Categorie::TYPE_CUSTOMER)
77
-                $idCompanyOrigin = $origin;
78
-            if ($type == Categorie::TYPE_MEMBER)
79
-                $idMemberOrigin = $origin;
80
-            if ($type == Categorie::TYPE_CONTACT)
81
-                $idContactOrigin = $origin;
82
-            if ($type == Categorie::TYPE_PROJECT)
83
-                $idProjectOrigin = $origin;
73
+            if ($type == Categorie::TYPE_PRODUCT) {
74
+                            $idProdOrigin = $origin;
75
+            }
76
+            if ($type == Categorie::TYPE_SUPPLIER) {
77
+                            $idSupplierOrigin = $origin;
78
+            }
79
+            if ($type == Categorie::TYPE_CUSTOMER) {
80
+                            $idCompanyOrigin = $origin;
81
+            }
82
+            if ($type == Categorie::TYPE_MEMBER) {
83
+                            $idMemberOrigin = $origin;
84
+            }
85
+            if ($type == Categorie::TYPE_CONTACT) {
86
+                            $idContactOrigin = $origin;
87
+            }
88
+            if ($type == Categorie::TYPE_PROJECT) {
89
+                            $idProjectOrigin = $origin;
90
+            }
84 91
         }
85 92
 
86
-        if ($catorigin && $type == Categorie::TYPE_PRODUCT)
87
-            $idCatOrigin = $catorigin;
93
+        if ($catorigin && $type == Categorie::TYPE_PRODUCT) {
94
+                    $idCatOrigin = $catorigin;
95
+        }
88 96
 
89 97
         $object = new Categorie();
90 98
 
@@ -139,12 +147,14 @@  discard block
 block discarded – undo
139 147
             $object->visible = $visible;
140 148
             $object->type = $type;
141 149
 
142
-            if ($parent != "-1")
143
-                $object->fk_parent = $parent;
150
+            if ($parent != "-1") {
151
+                            $object->fk_parent = $parent;
152
+            }
144 153
 
145 154
             $ret = $extrafields->setOptionalsFromPost($extralabels, $object);
146
-            if ($ret < 0)
147
-                $error++;
155
+            if ($ret < 0) {
156
+                            $error++;
157
+            }
148 158
 
149 159
             if (!$object->label) {
150 160
                 $error++;
Please login to merge, or discard this patch.
Views/CategoriesView.php 1 patch
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -64,21 +64,21 @@  discard block
 block discarded – undo
64 64
             if ($action == 'create' || $_POST["addcat"] == 'addcat') {
65 65
                 DolUtils::dol_set_focus('#label');
66 66
 
67
-                print '<form action="' . $_SERVER['PHP_SELF'] . '?type=' . $type . '" method="POST">';
68
-                print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
69
-                print '<input type="hidden" name="urlfrom" value="' . $urlfrom . '">';
67
+                print '<form action="'.$_SERVER['PHP_SELF'].'?type='.$type.'" method="POST">';
68
+                print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
69
+                print '<input type="hidden" name="urlfrom" value="'.$urlfrom.'">';
70 70
                 print '<input type="hidden" name="action" value="add">';
71 71
                 print '<input type="hidden" name="addcat" value="addcat">';
72
-                print '<input type="hidden" name="id" value="' . DolUtils::GETPOST('origin', 'alpha') . '">';
73
-                print '<input type="hidden" name="type" value="' . $type . '">';
74
-                print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
72
+                print '<input type="hidden" name="id" value="'.DolUtils::GETPOST('origin', 'alpha').'">';
73
+                print '<input type="hidden" name="type" value="'.$type.'">';
74
+                print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
75 75
                 if ($origin)
76 76
                 {
77
-                    print '<input type="hidden" name="origin" value="' . $origin . '">';
77
+                    print '<input type="hidden" name="origin" value="'.$origin.'">';
78 78
                 }
79 79
                 if ($catorigin)
80 80
                 {
81
-                    print '<input type="hidden" name="catorigin" value="' . $catorigin . '">';
81
+                    print '<input type="hidden" name="catorigin" value="'.$catorigin.'">';
82 82
                 }
83 83
 
84 84
                 print load_fiche_titre($langs->trans("CreateCat"));
@@ -89,29 +89,29 @@  discard block
 block discarded – undo
89 89
 
90 90
                 // Ref
91 91
                 print '<tr>';
92
-                print '<td class="titlefieldcreate fieldrequired">' . $langs->trans("Ref") . '</td><td><input id="label" class="minwidth100" name="label" value="' . $label . '">';
92
+                print '<td class="titlefieldcreate fieldrequired">'.$langs->trans("Ref").'</td><td><input id="label" class="minwidth100" name="label" value="'.$label.'">';
93 93
                 print'</td></tr>';
94 94
 
95 95
                 // Description
96
-                print '<tr><td class="tdtop">' . $langs->trans("Description") . '</td><td>';
96
+                print '<tr><td class="tdtop">'.$langs->trans("Description").'</td><td>';
97 97
                 //require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
98 98
                 $doleditor = new DolEditor('description', $description, '', 200, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_6, '90%');
99 99
                 $doleditor->Create();
100 100
                 print '</td></tr>';
101 101
 
102 102
                 // Color
103
-                print '<tr><td>' . $langs->trans("Color") . '</td><td>';
103
+                print '<tr><td>'.$langs->trans("Color").'</td><td>';
104 104
                 print $formother->selectColor($color, 'color');
105 105
                 print '</td></tr>';
106 106
 
107 107
                 // Parent category
108
-                print '<tr><td>' . $langs->trans("AddIn") . '</td><td>';
108
+                print '<tr><td>'.$langs->trans("AddIn").'</td><td>';
109 109
                 print $form->select_all_categories($type, $catorigin, 'parent');
110 110
                 print ajax_combobox('parent');
111 111
                 print '</td></tr>';
112 112
 
113 113
                 $parameters = array();
114
-                $reshook = Globals::$hookManager->executeHooks('formObjectOptions', $parameters, $object, $action);    // Note that $action and $object may have been modified by hook
114
+                $reshook = Globals::$hookManager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
115 115
                 print Globals::$hookManager->resPrint;
116 116
                 if (empty($reshook)) {
117 117
                     print $object->showOptionals($extrafields, 'edit');
@@ -122,9 +122,9 @@  discard block
 block discarded – undo
122 122
                 DolUtils::dol_fiche_end('');
123 123
 
124 124
                 print '<div class="center">';
125
-                print '<input type="submit" class="button" value="' . $langs->trans("CreateThisCat") . '" name="creation" />';
125
+                print '<input type="submit" class="button" value="'.$langs->trans("CreateThisCat").'" name="creation" />';
126 126
                 print '&nbsp; &nbsp; &nbsp;';
127
-                print '<input type="submit" class="button" value="' . $langs->trans("Cancel") . '" name="cancel" />';
127
+                print '<input type="submit" class="button" value="'.$langs->trans("Cancel").'" name="cancel" />';
128 128
                 print '</div>';
129 129
 
130 130
                 print '</form>';
Please login to merge, or discard this patch.
Views/LoginView.php 1 patch
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -61,7 +61,7 @@  discard block
 block discarded – undo
61 61
     public function draw()
62 62
     {
63 63
         header('Cache-Control: Public, must-revalidate');
64
-        header("Content-type: text/html; charset=" . Globals::$conf->file->character_set_client);
64
+        header("Content-type: text/html; charset=".Globals::$conf->file->character_set_client);
65 65
 
66 66
 // Need global variable $title to be defined by caller (like dol_loginfunction)
67 67
 // Caller can also set 	$morelogincontent = array(['options']=>array('js'=>..., 'table'=>...);
@@ -94,9 +94,9 @@  discard block
 block discarded – undo
94 94
         }
95 95
 
96 96
         $php_self = DolUtils::dol_escape_htmltag($_SERVER['PHP_SELF']);
97
-        $php_self .= DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?' . DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '';
97
+        $php_self .= DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?'.DolUtils::dol_escape_htmltag($_SERVER["QUERY_STRING"]) : '';
98 98
         if (!preg_match('/mainmenu=/', $php_self)) {
99
-            $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?') . 'mainmenu=home';
99
+            $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home';
100 100
         }
101 101
 
102 102
         $this->url = $php_self;
@@ -110,28 +110,28 @@  discard block
 block discarded – undo
110 110
           );
111 111
          */
112 112
         $arrayofjs = array(
113
-            DOL_BASE_URI . '/includes/jstz/jstz.min.js' . (empty(Globals::$conf->dol_use_jmobile) ? '' : '?version=' . urlencode(DOL_VERSION)),
114
-            DOL_BASE_URI . '/core/js/dst.js' . (empty(Globals::$conf->dol_use_jmobile) ? '' : '?version=' . urlencode(DOL_VERSION))
113
+            DOL_BASE_URI.'/includes/jstz/jstz.min.js'.(empty(Globals::$conf->dol_use_jmobile) ? '' : '?version='.urlencode(DOL_VERSION)),
114
+            DOL_BASE_URI.'/core/js/dst.js'.(empty(Globals::$conf->dol_use_jmobile) ? '' : '?version='.urlencode(DOL_VERSION))
115 115
         );
116 116
 
117 117
         // $titletruedolibarrversion is defined by dol_loginfunction in security2.lib.php.
118 118
         // We must keep the @, some tools use it to know it is login page and find true dolibarr version.
119 119
         // $titleofloginpage = Globals::$langs->trans('Login') . ' @ ' . $titletruedolibarrversion;
120
-        $titleofloginpage = Globals::$langs->trans('Login') . ' @ ' . DOL_VERSION;
120
+        $titleofloginpage = Globals::$langs->trans('Login').' @ '.DOL_VERSION;
121 121
 
122 122
         $disablenofollow = 1;
123
-        if (!preg_match('/' . constant('DOL_APPLICATION_TITLE') . '/', $this->title)) {
123
+        if (!preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $this->title)) {
124 124
             $disablenofollow = 0;
125 125
         }
126 126
 
127 127
         print $this->top_htmlhead('', $titleofloginpage, 0, 0, $arrayofjs, array(), 0, $disablenofollow);
128 128
 
129 129
 
130
-        $colorbackhmenu1 = '60,70,100';      // topmenu
130
+        $colorbackhmenu1 = '60,70,100'; // topmenu
131 131
         if (!isset(Globals::$conf->global->THEME_ELDY_TOPMENU_BACK1)) {
132 132
             Globals::$conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1;
133 133
         }
134 134
         $colorbackhmenu1 = empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED) ? (empty(Globals::$conf->global->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : Globals::$conf->global->THEME_ELDY_TOPMENU_BACK1) : (empty($user->conf->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : $user->conf->THEME_ELDY_TOPMENU_BACK1);
135
-        $colorbackhmenu1 = join(',', DolUtils2::colorStringToArray($colorbackhmenu1));    // Normalize value to 'x,y,z'
135
+        $colorbackhmenu1 = join(',', DolUtils2::colorStringToArray($colorbackhmenu1)); // Normalize value to 'x,y,z'
136 136
     }
137 137
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/install/inc.php 2 patches
Spacing   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -33,12 +33,12 @@  discard block
 block discarded – undo
33 33
 // Just to define version DOL_VERSION
34 34
 if (!defined('DOL_INC_FOR_VERSION_ERROR'))
35 35
     define('DOL_INC_FOR_VERSION_ERROR', '1');
36
-require_once DOL_BASE_PATH . '/filefunc.inc.php';
36
+require_once DOL_BASE_PATH.'/filefunc.inc.php';
37 37
 
38
-require_once DOL_BASE_PATH . '/core/class/translate.class.php';
39
-require_once DOL_BASE_PATH . '/core/lib/functions.lib.php';
40
-require_once DOL_BASE_PATH . '/core/lib/admin.lib.php';
41
-require_once DOL_BASE_PATH . '/core/lib/files.lib.php';
38
+require_once DOL_BASE_PATH.'/core/class/translate.class.php';
39
+require_once DOL_BASE_PATH.'/core/lib/functions.lib.php';
40
+require_once DOL_BASE_PATH.'/core/lib/admin.lib.php';
41
+require_once DOL_BASE_PATH.'/core/lib/files.lib.php';
42 42
 
43 43
 /*
44 44
  * adobdbtime package
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
 // Define vars
79 79
 $conffiletoshowshort = "conf.php";
80 80
 // Define localization of conf file
81
-$conffile = DOL_BASE_PATH . "/conf/conf.php";
81
+$conffile = DOL_BASE_PATH."/conf/conf.php";
82 82
 $conffiletoshow = "htdocs/conf/conf.php";
83 83
 // For debian/redhat like systems
84 84
 //$conffile = "/etc/dolibarr/conf.php";
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
             $dolibarr_main_db_port = '3306'; // For backward compatibility
101 101
         }
102 102
         // Clean parameters
103
-        $dolibarr_main_data_root = isset($dolibarr_main_data_root) ? trim($dolibarr_main_data_root) : DOL_BASE_PATH . '../documents';
103
+        $dolibarr_main_data_root = isset($dolibarr_main_data_root) ? trim($dolibarr_main_data_root) : DOL_BASE_PATH.'../documents';
104 104
         $dolibarr_main_url_root = isset($dolibarr_main_url_root) ? trim($dolibarr_main_url_root) : '';
105 105
         $dolibarr_main_url_root_alt = isset($dolibarr_main_url_root_alt) ? trim($dolibarr_main_url_root_alt) : '';
106 106
         $dolibarr_main_document_root = isset($dolibarr_main_document_root) ? trim($dolibarr_main_document_root) : '';
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
         // Load database driver
127 127
         if ($result) {
128 128
             if (!empty($dolibarr_main_document_root) && !empty($dolibarr_main_db_type)) {
129
-                $result = include_once $dolibarr_main_document_root . "/core/db/" . $dolibarr_main_db_type . '.class.php';
129
+                $result = include_once $dolibarr_main_document_root."/core/db/".$dolibarr_main_db_type.'.class.php';
130 130
                 if (!$result) {
131 131
                     $includeconferror = 'ErrorBadValueForDolibarrMainDBType';
132 132
                 }
@@ -146,14 +146,14 @@  discard block
 block discarded – undo
146 146
 }
147 147
 define('MAIN_DB_PREFIX', (isset($dolibarr_main_db_prefix) ? $dolibarr_main_db_prefix : ''));
148 148
 
149
-define('DOL_CLASS_PATH', 'class/');                             // Filsystem path to class dir
150
-define('DOL_DATA_ROOT', (isset($dolibarr_main_data_root) ? $dolibarr_main_data_root : DOL_BASE_PATH . '../documents'));
151
-define('DOL_MAIN_URL_ROOT', (isset($dolibarr_main_url_root) ? $dolibarr_main_url_root : ''));           // URL relative root
152
-$uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT'));  // $uri contains url without http*
153
-$suburi = strstr($uri, '/');       // $suburi contains url without domain
149
+define('DOL_CLASS_PATH', 'class/'); // Filsystem path to class dir
150
+define('DOL_DATA_ROOT', (isset($dolibarr_main_data_root) ? $dolibarr_main_data_root : DOL_BASE_PATH.'../documents'));
151
+define('DOL_MAIN_URL_ROOT', (isset($dolibarr_main_url_root) ? $dolibarr_main_url_root : '')); // URL relative root
152
+$uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT')); // $uri contains url without http*
153
+$suburi = strstr($uri, '/'); // $suburi contains url without domain
154 154
 if ($suburi == '/')
155
-    $suburi = '';   // If $suburi is /, it is now ''
156
-define('DOL_URL_ROOT', $suburi);    // URL relative root ('', '/dolibarr', ...)
155
+    $suburi = ''; // If $suburi is /, it is now ''
156
+define('DOL_URL_ROOT', $suburi); // URL relative root ('', '/dolibarr', ...)
157 157
 
158 158
 
159 159
 if (empty($conf->file->character_set_client))
@@ -189,14 +189,14 @@  discard block
 block discarded – undo
189 189
     $langs->load("install");
190 190
     print $langs->trans("YouTryInstallDisabledByDirLock");
191 191
     if (!empty($dolibarr_main_url_root)) {
192
-        print 'Click on following link, <a href="' . $dolibarr_main_url_root . '/admin/index.php?mainmenu=home&leftmenu=setup' . (isset($_POST["login"]) ? '&username=' . urlencode($_POST["login"]) : '') . '">';
192
+        print 'Click on following link, <a href="'.$dolibarr_main_url_root.'/admin/index.php?mainmenu=home&leftmenu=setup'.(isset($_POST["login"]) ? '&username='.urlencode($_POST["login"]) : '').'">';
193 193
         print $langs->trans("ClickHereToGoToApp");
194 194
         print '</a>';
195 195
     }
196 196
     exit;
197 197
 }
198 198
 
199
-$lockfile = DOL_DATA_ROOT . '/install.lock';
199
+$lockfile = DOL_DATA_ROOT.'/install.lock';
200 200
 if (constant('DOL_DATA_ROOT') === null) {
201 201
     // We don't have a configuration file yet
202 202
     // Try to detect any lockfile in the default documents path
@@ -210,8 +210,8 @@  discard block
 block discarded – undo
210 210
     $langs->load("install");
211 211
     print $langs->trans("YouTryInstallDisabledByFileLock");
212 212
     if (!empty($dolibarr_main_url_root)) {
213
-        print $langs->trans("ClickOnLinkOrRemoveManualy") . '<br>';
214
-        print '<a href="' . $dolibarr_main_url_root . '/admin/index.php?mainmenu=home&leftmenu=setup' . (isset($_POST["login"]) ? '&username=' . urlencode($_POST["login"]) : '') . '">';
213
+        print $langs->trans("ClickOnLinkOrRemoveManualy").'<br>';
214
+        print '<a href="'.$dolibarr_main_url_root.'/admin/index.php?mainmenu=home&leftmenu=setup'.(isset($_POST["login"]) ? '&username='.urlencode($_POST["login"]) : '').'">';
215 215
         print $langs->trans("ClickHereToGoToApp");
216 216
         print '</a>';
217 217
     } else {
@@ -230,13 +230,13 @@  discard block
 block discarded – undo
230 230
     if (@is_writable('/tmp'))
231 231
         define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
232 232
     else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"]))
233
-        define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
233
+        define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log');
234 234
     else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"]))
235
-        define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
235
+        define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log');
236 236
     else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat'))
237 237
         define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
238 238
     else if (@is_writable('../../'))
239
-        define('SYSLOG_FILE', '../../dolibarr_install.log');    // For others
239
+        define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others
240 240
 
241 241
 
242 242
 
@@ -258,9 +258,9 @@  discard block
 block discarded – undo
258 258
 // We init log handler for install
259 259
 $handlers = array('mod_syslog_file');
260 260
 foreach ($handlers as $handler) {
261
-    $file = DOL_BASE_PATH . '/core/modules/syslog/' . $handler . '.php';
261
+    $file = DOL_BASE_PATH.'/core/modules/syslog/'.$handler.'.php';
262 262
     if (!file_exists($file)) {
263
-        throw new Exception('Missing log handler file ' . $handler . '.php');
263
+        throw new Exception('Missing log handler file '.$handler.'.php');
264 264
     }
265 265
 
266 266
     require_once $file;
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
     global $dolibarr_main_db_pass;
321 321
     global $character_set_client;
322 322
 
323
-    $return = include_once $dolibarr_main_document_root . '/core/class/conf.class.php';
323
+    $return = include_once $dolibarr_main_document_root.'/core/class/conf.class.php';
324 324
     if (!$return)
325 325
         return -1;
326 326
 
@@ -360,13 +360,13 @@  discard block
 block discarded – undo
360 360
         if (@is_writable('/tmp'))
361 361
             define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
362 362
         else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"]))
363
-            define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
363
+            define('SYSLOG_FILE', $_ENV["TMP"].'/dolibarr_install.log');
364 364
         else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"]))
365
-            define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
365
+            define('SYSLOG_FILE', $_ENV["TEMP"].'/dolibarr_install.log');
366 366
         else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat'))
367 367
             define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
368 368
         else if (@is_writable('../../'))
369
-            define('SYSLOG_FILE', '../../dolibarr_install.log');    // For others
369
+            define('SYSLOG_FILE', '../../dolibarr_install.log'); // For others
370 370
 
371 371
 
372 372
 
@@ -388,9 +388,9 @@  discard block
 block discarded – undo
388 388
     // We init log handler for install
389 389
     $handlers = array('mod_syslog_file');
390 390
     foreach ($handlers as $handler) {
391
-        $file = DOL_BASE_PATH . '/core/modules/syslog/' . $handler . '.php';
391
+        $file = DOL_BASE_PATH.'/core/modules/syslog/'.$handler.'.php';
392 392
         if (!file_exists($file)) {
393
-            throw new Exception('Missing log handler file ' . $handler . '.php');
393
+            throw new Exception('Missing log handler file '.$handler.'.php');
394 394
         }
395 395
 
396 396
         require_once $file;
@@ -436,63 +436,63 @@  discard block
 block discarded – undo
436 436
     }
437 437
 
438 438
     // We force the content charset
439
-    header("Content-type: text/html; charset=" . $conf->file->character_set_client);
439
+    header("Content-type: text/html; charset=".$conf->file->character_set_client);
440 440
     header("X-Content-Type-Options: nosniff");
441 441
 
442
-    print '<!DOCTYPE HTML>' . "\n";
443
-    print '<html>' . "\n";
444
-    print '<head>' . "\n";
445
-    print '<meta charset="' . $conf->file->character_set_client . '">' . "\n";
446
-    print '<meta name="viewport" content="width=device-width, initial-scale=1.0">' . "\n";
447
-    print '<meta name="generator" content="Dolibarr installer">' . "\n";
448
-    print '<link rel="stylesheet" type="text/css" href="' . DOL_BASE_URI . '/install/default.css">' . "\n";
442
+    print '<!DOCTYPE HTML>'."\n";
443
+    print '<html>'."\n";
444
+    print '<head>'."\n";
445
+    print '<meta charset="'.$conf->file->character_set_client.'">'."\n";
446
+    print '<meta name="viewport" content="width=device-width, initial-scale=1.0">'."\n";
447
+    print '<meta name="generator" content="Dolibarr installer">'."\n";
448
+    print '<link rel="stylesheet" type="text/css" href="'.DOL_BASE_URI.'/install/default.css">'."\n";
449 449
 
450
-    print '<!-- Includes CSS for JQuery -->' . "\n";
450
+    print '<!-- Includes CSS for JQuery -->'."\n";
451 451
     if ($jQueryUiCustomPath) {
452
-        print '<link rel="stylesheet" type="text/css" href="' . $jQueryUiCustomPath . 'css/' . $jquerytheme . '/jquery-ui.min.css" />' . "\n";  // JQuery
452
+        print '<link rel="stylesheet" type="text/css" href="'.$jQueryUiCustomPath.'css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery
453 453
     } else {
454 454
         //print '<link rel="stylesheet" type="text/css" href="' . DOL_BASE_URI . '/includes/jquery/css/' . $jquerytheme . '/jquery-ui.min.css" />' . "\n";    // JQuery
455
-        print '<link rel="stylesheet" type="text/css" href="' . BASE_URI . '/includes/jquery/css/' . $jquerytheme . '/jquery-ui.min.css" />' . "\n";    // JQuery
455
+        print '<link rel="stylesheet" type="text/css" href="'.BASE_URI.'/includes/jquery/css/'.$jquerytheme.'/jquery-ui.min.css" />'."\n"; // JQuery
456 456
     }
457
-    print '<!-- Includes JS for JQuery -->' . "\n";
457
+    print '<!-- Includes JS for JQuery -->'."\n";
458 458
     if ($jQueryCustomPath) {
459
-        print '<script type="text/javascript" src="' . $jQueryCustomPath . 'jquery.min.js"></script>' . "\n";
459
+        print '<script type="text/javascript" src="'.$jQueryCustomPath.'jquery.min.js"></script>'."\n";
460 460
     } else {
461 461
         // print '<script type="text/javascript" src="' . DOL_BASE_URI . '/includes/jquery/js/jquery.min.js"></script>' . "\n";
462
-        print '<script type="text/javascript" src="' . BASE_URI . '/vendor/components/jquery/jquery.min.js"></script>' . "\n";
462
+        print '<script type="text/javascript" src="'.BASE_URI.'/vendor/components/jquery/jquery.min.js"></script>'."\n";
463 463
     }
464 464
     if ($jQueryUiCustomPath) {
465
-        print '<script type="text/javascript" src="' . $jQueryUiCustomPath . 'jquery-ui.min.js"></script>' . "\n";
465
+        print '<script type="text/javascript" src="'.$jQueryUiCustomPath.'jquery-ui.min.js"></script>'."\n";
466 466
     } else {
467 467
         // print '<script type="text/javascript" src="' . DOL_BASE_URI . '/includes/jquery/js/jquery-ui.min.js"></script>' . "\n";
468
-        print '<script type="text/javascript" src="' . BASE_URI . '/vendor/components/jqueryui/jquery-ui.min.js"></script>' . "\n";
468
+        print '<script type="text/javascript" src="'.BASE_URI.'/vendor/components/jqueryui/jquery-ui.min.js"></script>'."\n";
469 469
     }
470
-    print '<title>' . $langs->trans("DolibarrSetup") . '</title>' . "\n";
470
+    print '<title>'.$langs->trans("DolibarrSetup").'</title>'."\n";
471 471
     print "<!-- Alixar debugBar header -->";
472 472
     print Debug::getRenderHeader(); // Includes Alixar debugBar header
473
-    print '</head>' . "\n";
473
+    print '</head>'."\n";
474 474
 
475
-    print '<body>' . "\n";
475
+    print '<body>'."\n";
476 476
 
477 477
     print '<div class="divlogoinstall" style="text-align:center">';
478
-    print '<img class="imglogoinstall" src="' . DOL_BASE_URI . '/theme/dolibarr_logo.png" alt="Dolibarr logo"><br>';
478
+    print '<img class="imglogoinstall" src="'.DOL_BASE_URI.'/theme/dolibarr_logo.png" alt="Dolibarr logo"><br>';
479 479
     print DOL_VERSION;
480 480
     print '</div><br>';
481 481
 
482
-    print '<span class="titre">' . $langs->trans("DolibarrSetup");
482
+    print '<span class="titre">'.$langs->trans("DolibarrSetup");
483 483
     if ($subtitle) {
484
-        print ' - ' . $subtitle;
484
+        print ' - '.$subtitle;
485 485
     }
486
-    print '</span>' . "\n";
486
+    print '</span>'."\n";
487 487
 
488 488
     //print '<form name="forminstall" style="width: 100%" action="' . $next . '.php' . ($param ? '?' . $param : '') . '" method="POST">' . "\n";
489
-    print '<form name="forminstall" style="width: 100%" action="' . BASE_URI . '?controller=install&method=' . $next . ($param ? '&' . $param : '') . '" method="POST">' . "\n";
490
-    print '<input type="hidden" name="testpost" value="ok">' . "\n";
491
-    print '<input type="hidden" name="action" value="' . $action . '">' . "\n";
489
+    print '<form name="forminstall" style="width: 100%" action="'.BASE_URI.'?controller=install&method='.$next.($param ? '&'.$param : '').'" method="POST">'."\n";
490
+    print '<input type="hidden" name="testpost" value="ok">'."\n";
491
+    print '<input type="hidden" name="action" value="'.$action.'">'."\n";
492 492
 
493
-    print '<table class="main" width="100%"><tr><td>' . "\n";
493
+    print '<table class="main" width="100%"><tr><td>'."\n";
494 494
 
495
-    print '<table class="' . $csstable . '" width="100%"><tr><td>' . "\n";
495
+    print '<table class="'.$csstable.'" width="100%"><tr><td>'."\n";
496 496
 }
497 497
 
498 498
 /**
@@ -512,27 +512,27 @@  discard block
 block discarded – undo
512 512
     $langs->load("other");
513 513
     $langs->load("admin");
514 514
 
515
-    print '</td></tr></table>' . "\n";
516
-    print '</td></tr></table>' . "\n";
515
+    print '</td></tr></table>'."\n";
516
+    print '</td></tr></table>'."\n";
517 517
 
518 518
     if (!$nonext || ($nonext == '2')) {
519 519
         print '<div class="nextbutton" id="nextbutton">';
520 520
         if ($nonext == '2') {
521
-            print $langs->trans("ErrorFoundDuringMigration", isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"] . '&ignoreerrors=1' : '') . '<br><br>';
521
+            print $langs->trans("ErrorFoundDuringMigration", isset($_SERVER["REQUEST_URI"]) ? $_SERVER["REQUEST_URI"].'&ignoreerrors=1' : '').'<br><br>';
522 522
         }
523 523
 
524
-        print '<input type="submit" ' . ($nonext == '2' ? 'disabled="disabled" ' : '') . 'value="' . $langs->trans("NextStep") . ' ->"';
524
+        print '<input type="submit" '.($nonext == '2' ? 'disabled="disabled" ' : '').'value="'.$langs->trans("NextStep").' ->"';
525 525
         if ($jscheckfunction)
526
-            print ' onClick="return ' . $jscheckfunction . '();"';
526
+            print ' onClick="return '.$jscheckfunction.'();"';
527 527
         print '></div>';
528 528
         if ($withpleasewait)
529
-            print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>' . $langs->trans("NextStepMightLastALongTime") . '<br><br><div class="blinkwait">' . $langs->trans("PleaseBePatient") . '</div></div>';
529
+            print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>'.$langs->trans("NextStepMightLastALongTime").'<br><br><div class="blinkwait">'.$langs->trans("PleaseBePatient").'</div></div>';
530 530
     }
531 531
     if ($setuplang) {
532
-        print '<input type="hidden" name="selectlang" value="' . $setuplang . '">';
532
+        print '<input type="hidden" name="selectlang" value="'.$setuplang.'">';
533 533
     }
534 534
 
535
-    print '</form>' . "\n";
535
+    print '</form>'."\n";
536 536
 
537 537
     // If there is some logs in buffer to show
538 538
     if (isset($conf->logbuffer) && count($conf->logbuffer)) {
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
         print "<!-- Start of log output\n";
541 541
         //print '<div class="hidden">'."\n";
542 542
         foreach ($conf->logbuffer as $logline) {
543
-            print $logline . "<br>\n";
543
+            print $logline."<br>\n";
544 544
         }
545 545
         //print '</div>'."\n";
546 546
         print "End of log output -->\n";
@@ -549,8 +549,8 @@  discard block
 block discarded – undo
549 549
 
550 550
     print "<!-- Alixar debugBar footer -->";
551 551
     print Debug::getRenderFooter(); // Includes Alixar debugBar footer
552
-    print '</body>' . "\n";
553
-    print '</html>' . "\n";
552
+    print '</body>'."\n";
553
+    print '</html>'."\n";
554 554
 }
555 555
 
556 556
 /**
@@ -615,16 +615,16 @@  discard block
 block discarded – undo
615 615
         $dolibarr_main_url_root = $_SERVER["SCRIPT_URI"];
616 616
     } // If defined (Ie: Apache with Caudium)
617 617
     elseif (isset($_SERVER["SERVER_URL"]) && isset($_SERVER["DOCUMENT_URI"])) {
618
-        $dolibarr_main_url_root = $_SERVER["SERVER_URL"] . $_SERVER["DOCUMENT_URI"];
618
+        $dolibarr_main_url_root = $_SERVER["SERVER_URL"].$_SERVER["DOCUMENT_URI"];
619 619
     } // If SCRIPT_URI, SERVER_URL, DOCUMENT_URI not defined (Ie: Apache 2.0.44 for Windows)
620 620
     else {
621
-        $proto = ( (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') || $_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http';
621
+        $proto = ((!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == 'on') || $_SERVER['SERVER_PORT'] == 443) ? 'https' : 'http';
622 622
         if (!empty($_SERVER["HTTP_HOST"])) {
623 623
             $serverport = $_SERVER["HTTP_HOST"];
624 624
         } else {
625 625
             $serverport = $_SERVER["SERVER_NAME"];
626 626
         }
627
-        $dolibarr_main_url_root = $proto . "://" . $serverport . $_SERVER["SCRIPT_NAME"];
627
+        $dolibarr_main_url_root = $proto."://".$serverport.$_SERVER["SCRIPT_NAME"];
628 628
     }
629 629
     // Clean proposed URL
630 630
     // We assume /install to be under /htdocs, so we get the parent path of the current URL
Please login to merge, or discard this patch.
Braces   +101 added lines, -65 removed lines patch added patch discarded remove patch
@@ -31,8 +31,9 @@  discard block
 block discarded – undo
31 31
  * 	\brief      File that define environment for support pages
32 32
  */
33 33
 // Just to define version DOL_VERSION
34
-if (!defined('DOL_INC_FOR_VERSION_ERROR'))
34
+if (!defined('DOL_INC_FOR_VERSION_ERROR')) {
35 35
     define('DOL_INC_FOR_VERSION_ERROR', '1');
36
+}
36 37
 require_once DOL_BASE_PATH . '/filefunc.inc.php';
37 38
 
38 39
 require_once DOL_BASE_PATH . '/core/class/translate.class.php';
@@ -151,23 +152,31 @@  discard block
 block discarded – undo
151 152
 define('DOL_MAIN_URL_ROOT', (isset($dolibarr_main_url_root) ? $dolibarr_main_url_root : ''));           // URL relative root
152 153
 $uri = preg_replace('/^http(s?):\/\//i', '', constant('DOL_MAIN_URL_ROOT'));  // $uri contains url without http*
153 154
 $suburi = strstr($uri, '/');       // $suburi contains url without domain
154
-if ($suburi == '/')
155
-    $suburi = '';   // If $suburi is /, it is now ''
155
+if ($suburi == '/') {
156
+    $suburi = '';
157
+}
158
+// If $suburi is /, it is now ''
156 159
 define('DOL_URL_ROOT', $suburi);    // URL relative root ('', '/dolibarr', ...)
157 160
 
158 161
 
159
-if (empty($conf->file->character_set_client))
162
+if (empty($conf->file->character_set_client)) {
160 163
     $conf->file->character_set_client = "utf-8";
161
-if (empty($conf->db->character_set))
164
+}
165
+if (empty($conf->db->character_set)) {
162 166
     $conf->db->character_set = 'utf8';
163
-if (empty($conf->db->dolibarr_main_db_collation))
167
+}
168
+if (empty($conf->db->dolibarr_main_db_collation)) {
164 169
     $conf->db->dolibarr_main_db_collation = 'utf8_unicode_ci';
165
-if (empty($conf->db->dolibarr_main_db_encryption))
170
+}
171
+if (empty($conf->db->dolibarr_main_db_encryption)) {
166 172
     $conf->db->dolibarr_main_db_encryption = 0;
167
-if (empty($conf->db->dolibarr_main_db_cryptkey))
173
+}
174
+if (empty($conf->db->dolibarr_main_db_cryptkey)) {
168 175
     $conf->db->dolibarr_main_db_cryptkey = '';
169
-if (empty($conf->db->user))
176
+}
177
+if (empty($conf->db->user)) {
170 178
     $conf->db->user = '';
179
+}
171 180
 
172 181
 // Define array of document root directories
173 182
 $conf->file->dol_document_root = array(DOL_DOCUMENT_ROOT);
@@ -224,19 +233,24 @@  discard block
 block discarded – undo
224 233
 // Force usage of log file for install and upgrades
225 234
 $conf->syslog->enabled = 1;
226 235
 $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG');
227
-if (!defined('SYSLOG_HANDLERS'))
236
+if (!defined('SYSLOG_HANDLERS')) {
228 237
     define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
238
+}
229 239
 if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined
230
-    if (@is_writable('/tmp'))
231
-        define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
232
-    else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"]))
233
-        define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
234
-    else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"]))
235
-        define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
236
-    else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat'))
237
-        define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
238
-    else if (@is_writable('../../'))
239
-        define('SYSLOG_FILE', '../../dolibarr_install.log');    // For others
240
+    if (@is_writable('/tmp')) {
241
+            define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
242
+    } else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) {
243
+            define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
244
+    } else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) {
245
+            define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
246
+    } else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) {
247
+            define('SYSLOG_FILE', '../../../../dolibarr_install.log');
248
+    }
249
+    // For DoliWamp
250
+    else if (@is_writable('../../')) {
251
+            define('SYSLOG_FILE', '../../dolibarr_install.log');
252
+    }
253
+    // For others
240 254
 
241 255
 
242 256
 
@@ -251,10 +265,12 @@  discard block
 block discarded – undo
251 265
         
252 266
 //print 'SYSLOG_FILE='.SYSLOG_FILE;exit;
253 267
 }
254
-if (defined('SYSLOG_FILE'))
268
+if (defined('SYSLOG_FILE')) {
255 269
     $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
256
-if (!defined('SYSLOG_FILE_NO_ERROR'))
270
+}
271
+if (!defined('SYSLOG_FILE_NO_ERROR')) {
257 272
     define('SYSLOG_FILE_NO_ERROR', 1);
273
+}
258 274
 // We init log handler for install
259 275
 $handlers = array('mod_syslog_file');
260 276
 foreach ($handlers as $handler) {
@@ -269,9 +285,10 @@  discard block
 block discarded – undo
269 285
         throw new Exception('Log handler does not extend LogHandlerInterface');
270 286
     }
271 287
 
272
-    if (empty($conf->loghandlers[$handler]))
273
-        $conf->loghandlers[$handler] = $loghandlerinstance;
274
-}
288
+    if (empty($conf->loghandlers[$handler])) {
289
+            $conf->loghandlers[$handler] = $loghandlerinstance;
290
+    }
291
+    }
275 292
 
276 293
 // Removed magic_quotes
277 294
 if (function_exists('get_magic_quotes_gpc')) { // magic_quotes_* removed in PHP 5.4
@@ -295,10 +312,11 @@  discard block
 block discarded – undo
295 312
 
296 313
 // Defini objet langs
297 314
 $langs = new Translate('..', $conf);
298
-if (GETPOST('lang', 'aZ09'))
315
+if (GETPOST('lang', 'aZ09')) {
299 316
     $langs->setDefaultLang(GETPOST('lang', 'aZ09'));
300
-else
317
+} else {
301 318
     $langs->setDefaultLang('auto');
319
+}
302 320
 
303 321
 $bc[false] = ' class="bg1"';
304 322
 $bc[true] = ' class="bg2"';
@@ -321,8 +339,9 @@  discard block
 block discarded – undo
321 339
     global $character_set_client;
322 340
 
323 341
     $return = include_once $dolibarr_main_document_root . '/core/class/conf.class.php';
324
-    if (!$return)
325
-        return -1;
342
+    if (!$return) {
343
+            return -1;
344
+    }
326 345
 
327 346
     $conf = new Conf();
328 347
     $conf->db->type = trim($dolibarr_main_db_type);
@@ -333,40 +352,51 @@  discard block
 block discarded – undo
333 352
     $conf->db->pass = trim($dolibarr_main_db_pass);
334 353
 
335 354
     // Mysql driver support has been removed in favor of mysqli
336
-    if ($conf->db->type == 'mysql')
337
-        $conf->db->type = 'mysqli';
338
-    if (empty($character_set_client))
339
-        $character_set_client = "UTF-8";
355
+    if ($conf->db->type == 'mysql') {
356
+            $conf->db->type = 'mysqli';
357
+    }
358
+    if (empty($character_set_client)) {
359
+            $character_set_client = "UTF-8";
360
+    }
340 361
     $conf->file->character_set_client = strtoupper($character_set_client);
341
-    if (empty($dolibarr_main_db_character_set))
342
-        $dolibarr_main_db_character_set = ($conf->db->type == 'mysqli' ? 'utf8' : '');
362
+    if (empty($dolibarr_main_db_character_set)) {
363
+            $dolibarr_main_db_character_set = ($conf->db->type == 'mysqli' ? 'utf8' : '');
364
+    }
343 365
     $conf->db->character_set = $dolibarr_main_db_character_set;
344
-    if (empty($dolibarr_main_db_collation))
345
-        $dolibarr_main_db_collation = ($conf->db->type == 'mysqli' ? 'utf8_unicode_ci' : '');
366
+    if (empty($dolibarr_main_db_collation)) {
367
+            $dolibarr_main_db_collation = ($conf->db->type == 'mysqli' ? 'utf8_unicode_ci' : '');
368
+    }
346 369
     $conf->db->dolibarr_main_db_collation = $dolibarr_main_db_collation;
347
-    if (empty($dolibarr_main_db_encryption))
348
-        $dolibarr_main_db_encryption = 0;
370
+    if (empty($dolibarr_main_db_encryption)) {
371
+            $dolibarr_main_db_encryption = 0;
372
+    }
349 373
     $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption;
350
-    if (empty($dolibarr_main_db_cryptkey))
351
-        $dolibarr_main_db_cryptkey = '';
374
+    if (empty($dolibarr_main_db_cryptkey)) {
375
+            $dolibarr_main_db_cryptkey = '';
376
+    }
352 377
     $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey;
353 378
 
354 379
     // Force usage of log file for install and upgrades
355 380
     $conf->syslog->enabled = 1;
356 381
     $conf->global->SYSLOG_LEVEL = constant('LOG_DEBUG');
357
-    if (!defined('SYSLOG_HANDLERS'))
358
-        define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
382
+    if (!defined('SYSLOG_HANDLERS')) {
383
+            define('SYSLOG_HANDLERS', '["mod_syslog_file"]');
384
+    }
359 385
     if (!defined('SYSLOG_FILE')) { // To avoid warning on systems with constant already defined
360
-        if (@is_writable('/tmp'))
361
-            define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
362
-        else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"]))
363
-            define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
364
-        else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"]))
365
-            define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
366
-        else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat'))
367
-            define('SYSLOG_FILE', '../../../../dolibarr_install.log'); // For DoliWamp
368
-        else if (@is_writable('../../'))
369
-            define('SYSLOG_FILE', '../../dolibarr_install.log');    // For others
386
+        if (@is_writable('/tmp')) {
387
+                    define('SYSLOG_FILE', '/tmp/dolibarr_install.log');
388
+        } else if (!empty($_ENV["TMP"]) && @is_writable($_ENV["TMP"])) {
389
+                    define('SYSLOG_FILE', $_ENV["TMP"] . '/dolibarr_install.log');
390
+        } else if (!empty($_ENV["TEMP"]) && @is_writable($_ENV["TEMP"])) {
391
+                    define('SYSLOG_FILE', $_ENV["TEMP"] . '/dolibarr_install.log');
392
+        } else if (@is_writable('../../../../') && @file_exists('../../../../startdoliwamp.bat')) {
393
+                    define('SYSLOG_FILE', '../../../../dolibarr_install.log');
394
+        }
395
+        // For DoliWamp
396
+        else if (@is_writable('../../')) {
397
+                    define('SYSLOG_FILE', '../../dolibarr_install.log');
398
+        }
399
+        // For others
370 400
 
371 401
 
372 402
 
@@ -381,10 +411,12 @@  discard block
 block discarded – undo
381 411
             
382 412
 //print 'SYSLOG_FILE='.SYSLOG_FILE;exit;
383 413
     }
384
-    if (defined('SYSLOG_FILE'))
385
-        $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
386
-    if (!defined('SYSLOG_FILE_NO_ERROR'))
387
-        define('SYSLOG_FILE_NO_ERROR', 1);
414
+    if (defined('SYSLOG_FILE')) {
415
+            $conf->global->SYSLOG_FILE = constant('SYSLOG_FILE');
416
+    }
417
+    if (!defined('SYSLOG_FILE_NO_ERROR')) {
418
+            define('SYSLOG_FILE_NO_ERROR', 1);
419
+    }
388 420
     // We init log handler for install
389 421
     $handlers = array('mod_syslog_file');
390 422
     foreach ($handlers as $handler) {
@@ -399,8 +431,9 @@  discard block
 block discarded – undo
399 431
             throw new Exception('Log handler does not extend LogHandlerInterface');
400 432
         }
401 433
 
402
-        if (empty($conf->loghandlers[$handler]))
403
-            $conf->loghandlers[$handler] = $loghandlerinstance;
434
+        if (empty($conf->loghandlers[$handler])) {
435
+                    $conf->loghandlers[$handler] = $loghandlerinstance;
436
+        }
404 437
     }
405 438
 
406 439
     return 1;
@@ -522,11 +555,13 @@  discard block
 block discarded – undo
522 555
         }
523 556
 
524 557
         print '<input type="submit" ' . ($nonext == '2' ? 'disabled="disabled" ' : '') . 'value="' . $langs->trans("NextStep") . ' ->"';
525
-        if ($jscheckfunction)
526
-            print ' onClick="return ' . $jscheckfunction . '();"';
558
+        if ($jscheckfunction) {
559
+                    print ' onClick="return ' . $jscheckfunction . '();"';
560
+        }
527 561
         print '></div>';
528
-        if ($withpleasewait)
529
-            print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>' . $langs->trans("NextStepMightLastALongTime") . '<br><br><div class="blinkwait">' . $langs->trans("PleaseBePatient") . '</div></div>';
562
+        if ($withpleasewait) {
563
+                    print '<div style="visibility: hidden;" class="pleasewait" id="pleasewait"><br>' . $langs->trans("NextStepMightLastALongTime") . '<br><br><div class="blinkwait">' . $langs->trans("PleaseBePatient") . '</div></div>';
564
+        }
530 565
     }
531 566
     if ($setuplang) {
532 567
         print '<input type="hidden" name="selectlang" value="' . $setuplang . '">';
@@ -562,8 +597,9 @@  discard block
 block discarded – undo
562 597
  */
563 598
 function dolibarr_install_syslog($message, $level = LOG_DEBUG)
564 599
 {
565
-    if (!defined('LOG_DEBUG'))
566
-        define('LOG_DEBUG', 6);
600
+    if (!defined('LOG_DEBUG')) {
601
+            define('LOG_DEBUG', 6);
602
+    }
567 603
     dol_syslog($message, $level);
568 604
 }
569 605
 
Please login to merge, or discard this patch.
Helpers/DolUtils2.php 3 patches
Indentation   +405 added lines, -405 removed lines patch added patch discarded remove patch
@@ -36,11 +36,11 @@  discard block
 block discarded – undo
36 36
 {
37 37
 
38 38
     /**
39
- * Same function than javascript unescape() function but in PHP.
40
- *
41
- * @param 	string	$source		String to decode
42
- * @return	string				Unescaped string
43
- */
39
+     * Same function than javascript unescape() function but in PHP.
40
+     *
41
+     * @param 	string	$source		String to decode
42
+     * @return	string				Unescaped string
43
+     */
44 44
 function jsUnEscape($source)
45 45
 {
46 46
     $decodedStr = "";
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 
131 131
     $selected='EUA4';
132 132
     if (!$outputlangs) {
133
-    	$outputlangs=$langs;
133
+        $outputlangs=$langs;
134 134
     }
135 135
 
136 136
     if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
@@ -234,15 +234,15 @@  discard block
 block discarded – undo
234 234
         else print ': ';
235 235
         if (is_object($object->user_creation))
236 236
         {
237
-        	if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
238
-        	else print $langs->trans("Unknown");
237
+            if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
238
+            else print $langs->trans("Unknown");
239 239
         }
240 240
         else
241 241
         {
242 242
             $userstatic=new User($db);
243 243
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
244 244
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
245
-        	else print $langs->trans("Unknown");
245
+            else print $langs->trans("Unknown");
246 246
         }
247 247
         if ($usetable) print '</td></tr>';
248 248
         else print '<br>';
@@ -270,15 +270,15 @@  discard block
 block discarded – undo
270 270
         else print ': ';
271 271
         if (is_object($object->user_modification))
272 272
         {
273
-        	if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
274
-        	else print $langs->trans("Unknown");
273
+            if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
274
+            else print $langs->trans("Unknown");
275 275
         }
276 276
         else
277 277
         {
278 278
             $userstatic=new User($db);
279 279
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
280 280
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
281
-        	else print $langs->trans("Unknown");
281
+            else print $langs->trans("Unknown");
282 282
         }
283 283
         if ($usetable) print '</td></tr>';
284 284
         else print '<br>';
@@ -307,14 +307,14 @@  discard block
 block discarded – undo
307 307
         if (is_object($object->user_validation))
308 308
         {
309 309
             if ($object->user_validation->id) print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
310
-        	else print $langs->trans("Unknown");
310
+            else print $langs->trans("Unknown");
311 311
         }
312 312
         else
313 313
         {
314 314
             $userstatic=new User($db);
315 315
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
316
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
317
-        	else print $langs->trans("Unknown");
316
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
317
+            else print $langs->trans("Unknown");
318 318
         }
319 319
         if ($usetable) print '</td></tr>';
320 320
         else print '<br>';
@@ -343,14 +343,14 @@  discard block
 block discarded – undo
343 343
         if (is_object($object->user_approve))
344 344
         {
345 345
             if ($object->user_approve->id) print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
346
-        	else print $langs->trans("Unknown");
346
+            else print $langs->trans("Unknown");
347 347
         }
348 348
         else
349 349
         {
350 350
             $userstatic=new User($db);
351 351
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
352
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
353
-        	else print $langs->trans("Unknown");
352
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
353
+            else print $langs->trans("Unknown");
354 354
         }
355 355
         if ($usetable) print '</td></tr>';
356 356
         else print '<br>';
@@ -406,15 +406,15 @@  discard block
 block discarded – undo
406 406
         else print ': ';
407 407
         if (is_object($object->user_cloture))
408 408
         {
409
-			if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
410
-        	else print $langs->trans("Unknown");
409
+            if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
410
+            else print $langs->trans("Unknown");
411 411
         }
412 412
         else
413 413
         {
414 414
             $userstatic=new User($db);
415 415
             $userstatic->fetch($object->user_cloture);
416
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
417
-        	else print $langs->trans("Unknown");
416
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
417
+            else print $langs->trans("Unknown");
418 418
         }
419 419
         if ($usetable) print '</td></tr>';
420 420
         else print '<br>';
@@ -442,15 +442,15 @@  discard block
 block discarded – undo
442 442
         else print ': ';
443 443
         if (is_object($object->user_rappro))
444 444
         {
445
-			if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
446
-        	else print $langs->trans("Unknown");
445
+            if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
446
+            else print $langs->trans("Unknown");
447 447
         }
448 448
         else
449 449
         {
450 450
             $userstatic=new User($db);
451 451
             $userstatic->fetch($object->user_rappro);
452
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
453
-        	else print $langs->trans("Unknown");
452
+            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
453
+            else print $langs->trans("Unknown");
454 454
         }
455 455
         if ($usetable) print '</td></tr>';
456 456
         else print '<br>';
@@ -496,8 +496,8 @@  discard block
 block discarded – undo
496 496
  */
497 497
 function dolAddEmailTrackId($email, $trackingid)
498 498
 {
499
-	$tmp=explode('@',$email);
500
-	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
499
+    $tmp=explode('@',$email);
500
+    return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
501 501
 }
502 502
 
503 503
 /**
@@ -623,33 +623,33 @@  discard block
 block discarded – undo
623 623
  */
624 624
 function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
625 625
 {
626
-	if(!isValidEmail($mail))return '';
627
-	$tab = explode('@', $mail);
628
-	$tab2 = explode('.',$tab[1]);
629
-	$string_replace = '';
630
-	$mail_name = $tab[0];
631
-	$mail_domaine = $tab2[0];
632
-	$mail_tld = '';
633
-
634
-	$nbofelem = count($tab2);
635
-	for($i=1; $i < $nbofelem && $displaytld; $i++)
636
-	{
637
-		$mail_tld .= '.'.$tab2[$i];
638
-	}
639
-
640
-	for($i=0; $i < $nbreplace; $i++){
641
-		$string_replace .= $replace;
642
-	}
643
-
644
-	if(strlen($mail_name) > $nbdisplaymail){
645
-		$mail_name = substr($mail_name, 0, $nbdisplaymail);
646
-	}
647
-
648
-	if(strlen($mail_domaine) > $nbdisplaydomain){
649
-		$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
650
-	}
651
-
652
-	return $mail_name . $string_replace . $mail_domaine . $mail_tld;
626
+    if(!isValidEmail($mail))return '';
627
+    $tab = explode('@', $mail);
628
+    $tab2 = explode('.',$tab[1]);
629
+    $string_replace = '';
630
+    $mail_name = $tab[0];
631
+    $mail_domaine = $tab2[0];
632
+    $mail_tld = '';
633
+
634
+    $nbofelem = count($tab2);
635
+    for($i=1; $i < $nbofelem && $displaytld; $i++)
636
+    {
637
+        $mail_tld .= '.'.$tab2[$i];
638
+    }
639
+
640
+    for($i=0; $i < $nbreplace; $i++){
641
+        $string_replace .= $replace;
642
+    }
643
+
644
+    if(strlen($mail_name) > $nbdisplaymail){
645
+        $mail_name = substr($mail_name, 0, $nbdisplaymail);
646
+    }
647
+
648
+    if(strlen($mail_domaine) > $nbdisplaydomain){
649
+        $mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
650
+    }
651
+
652
+    return $mail_name . $string_replace . $mail_domaine . $mail_tld;
653 653
 }
654 654
 
655 655
 
@@ -787,24 +787,24 @@  discard block
 block discarded – undo
787 787
     }
788 788
     else
789 789
     {
790
-    	$masktype='';
791
-    	$masktype_value='';
790
+        $masktype='';
791
+        $masktype_value='';
792 792
     }
793 793
 
794 794
     // Extract value for user
795 795
     if (preg_match('/\{(u+)\}/i',$mask,$regType))
796 796
     {
797
-    	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
798
-    	if (is_object($objuser)) $lastname = $objuser->lastname;
797
+        $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
798
+        if (is_object($objuser)) $lastname = $objuser->lastname;
799 799
 
800
-    	$maskuser=$regType[1];
801
-    	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
802
-    	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
800
+        $maskuser=$regType[1];
801
+        $maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
802
+        $maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
803 803
     }
804 804
     else
805 805
     {
806
-    	$maskuser='';
807
-    	$maskuser_value='';
806
+        $maskuser='';
807
+        $maskuser_value='';
808 808
     }
809 809
 
810 810
     // Personalized field {XXX-1} à {XXX-9}
@@ -820,12 +820,12 @@  discard block
 block discarded – undo
820 820
 
821 821
     if (strstr($mask,'user_extra_'))
822 822
     {
823
-			$start = "{user_extra_";
824
-			$end = "\}";
825
-			$extra= get_string_between($mask, "user_extra_", "}");
826
-			if(!empty($user->array_options['options_'.$extra])){
827
-				$mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
828
-			}
823
+            $start = "{user_extra_";
824
+            $end = "\}";
825
+            $extra= get_string_between($mask, "user_extra_", "}");
826
+            if(!empty($user->array_options['options_'.$extra])){
827
+                $mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
828
+            }
829 829
     }
830 830
     $maskwithonlyymcode=$mask;
831 831
     $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
@@ -886,7 +886,7 @@  discard block
 block discarded – undo
886 886
         else // if reset is for a specific month in year, we need year
887 887
         {
888 888
             if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
889
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
889
+            else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
890 890
             else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
891 891
             else return 'ErrorCantUseRazIfNoYearInMask';
892 892
         }
@@ -894,11 +894,11 @@  discard block
 block discarded – undo
894 894
         $yearlen = $posy?dol_strlen($reg[$posy]):0;
895 895
         $monthlen = $posm?dol_strlen($reg[$posm]):0;
896 896
         // Define pos
897
-       	$yearpos = (dol_strlen($reg[1])+1);
897
+            $yearpos = (dol_strlen($reg[1])+1);
898 898
         $monthpos = ($yearpos+$yearlen);
899 899
         if ($posy == 3 && $posm == 2) {		// if month is before year
900
-          	$monthpos = (dol_strlen($reg[1])+1);
901
-           	$yearpos = ($monthpos+$monthlen);
900
+                $monthpos = (dol_strlen($reg[1])+1);
901
+                $yearpos = ($monthpos+$monthlen);
902 902
         }
903 903
         //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
904 904
 
@@ -908,20 +908,20 @@  discard block
 block discarded – undo
908 908
 
909 909
         if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
910 910
         {
911
-        	$currentyear=date("Y", $date);
912
-        	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
913
-        	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
914
-        	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
915
-        	//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
916
-
917
-        	// If after or equal of current fiscal date
918
-        	if ($date >= $fiscaldate)
919
-        	{
920
-        		// If before of next new year date
921
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
922
-        	}
923
-        	// If after or equal of current new year date
924
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
911
+            $currentyear=date("Y", $date);
912
+            $fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
913
+            $newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
914
+            $nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
915
+            //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
916
+
917
+            // If after or equal of current fiscal date
918
+            if ($date >= $fiscaldate)
919
+            {
920
+                // If before of next new year date
921
+                if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
922
+            }
923
+            // If after or equal of current new year date
924
+            else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
925 925
         }
926 926
         // For backward compatibility
927 927
         else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
@@ -942,11 +942,11 @@  discard block
 block discarded – undo
942 942
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
943 943
             $sqlwhere.=')';
944 944
         }
945
-		else if ($resetEveryMonth)
946
-		{
947
-			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
945
+        else if ($resetEveryMonth)
946
+        {
947
+            $sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
948 948
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
949
-		}
949
+        }
950 950
         else   // reset is done on january
951 951
         {
952 952
             $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
@@ -957,13 +957,13 @@  discard block
 block discarded – undo
957 957
 
958 958
     // Define $sqlstring
959 959
     if (function_exists('mb_strrpos'))
960
-    	{
961
-    	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
962
-	}
963
-	else
964
-	{
965
-    	$posnumstart=strrpos($maskwithnocode,$maskcounter);
966
-	}	// Pos of counter in final string (from 0 to ...)
960
+        {
961
+        $posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
962
+    }
963
+    else
964
+    {
965
+        $posnumstart=strrpos($maskwithnocode,$maskcounter);
966
+    }	// Pos of counter in final string (from 0 to ...)
967 967
     if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
968 968
     $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
969 969
 
@@ -982,7 +982,7 @@  discard block
 block discarded – undo
982 982
     if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
983 983
     foreach($maskperso as $key => $val)
984 984
     {
985
-    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
985
+        $maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
986 986
     }
987 987
 
988 988
     // Get counter in database
@@ -990,11 +990,11 @@  discard block
 block discarded – undo
990 990
     $sql = "SELECT MAX(".$sqlstring.") as val";
991 991
     $sql.= " FROM ".MAIN_DB_PREFIX.$table;
992 992
     $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
993
-	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
993
+    $sql.= " AND ".$field." NOT LIKE '(PROV%)'";
994 994
     if ($bentityon) // only if entity enable
995
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
995
+        $sql.= " AND entity IN (".getEntity($sharetable).")";
996 996
     else if (! empty($forceentity))
997
-    	$sql.= " AND entity IN (".$forceentity.")";
997
+        $sql.= " AND entity IN (".$forceentity.")";
998 998
     if ($where) $sql.=$where;
999 999
     if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1000 1000
 
@@ -1012,8 +1012,8 @@  discard block
 block discarded – undo
1012 1012
     if (empty($counter)) $counter=$maskoffset;
1013 1013
     else if (preg_match('/[^0-9]/i',$counter))
1014 1014
     {
1015
-    	$counter=0;
1016
-    	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1015
+        $counter=0;
1016
+        dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1017 1017
     }
1018 1018
     else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1019 1019
 
@@ -1039,11 +1039,11 @@  discard block
 block discarded – undo
1039 1039
         $sql = "SELECT ".$field." as ref";
1040 1040
         $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1041 1041
         $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1042
-    	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1043
-    	if ($bentityon) // only if entity enable
1044
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1042
+        $sql.= " AND ".$field." NOT LIKE '%PROV%'";
1043
+        if ($bentityon) // only if entity enable
1044
+            $sql.= " AND entity IN (".getEntity($sharetable).")";
1045 1045
         else if (! empty($forceentity))
1046
-        	$sql.= " AND entity IN (".$forceentity.")";
1046
+            $sql.= " AND entity IN (".$forceentity.")";
1047 1047
         if ($where) $sql.=$where;
1048 1048
         if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1049 1049
 
@@ -1065,7 +1065,7 @@  discard block
 block discarded – undo
1065 1065
         // If value for $counter has a length higher than $maskcounter chars
1066 1066
         if ($counter >= pow(10, dol_strlen($maskcounter)))
1067 1067
         {
1068
-        	$counter='ErrorMaxNumberReachForThisMask';
1068
+            $counter='ErrorMaxNumberReachForThisMask';
1069 1069
         }
1070 1070
 
1071 1071
         if (! empty($maskrefclient_maskcounter))
@@ -1097,9 +1097,9 @@  discard block
 block discarded – undo
1097 1097
             //$sql.= " WHERE ".$field." not like '(%'";
1098 1098
             $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1099 1099
             if ($bentityon) // only if entity enable
1100
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1100
+                $maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1101 1101
             else if (! empty($forceentity))
1102
-            	$sql.= " AND entity IN (".$forceentity.")";
1102
+                $sql.= " AND entity IN (".$forceentity.")";
1103 1103
             if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1104 1104
             if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1105 1105
             $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
@@ -1114,25 +1114,25 @@  discard block
 block discarded – undo
1114 1114
             else dol_print_error($db);
1115 1115
 
1116 1116
             if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1117
-			$maskrefclient_counter++;
1117
+            $maskrefclient_counter++;
1118 1118
         }
1119 1119
 
1120 1120
         // Build numFinal
1121 1121
         $numFinal = $mask;
1122 1122
 
1123 1123
         // We replace special codes except refclient
1124
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1125
-		{
1126
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1127
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1128
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1129
-		}
1130
-		else	// we want yyyy to be current year
1131
-		{
1132
-        	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1133
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1134
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1135
-		}
1124
+        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1125
+        {
1126
+            $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1127
+            $numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1128
+            $numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1129
+        }
1130
+        else	// we want yyyy to be current year
1131
+        {
1132
+            $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1133
+            $numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1134
+            $numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1135
+        }
1136 1136
         $numFinal = preg_replace('/\{mm\}/i',  date("m",$date), $numFinal);
1137 1137
         $numFinal = preg_replace('/\{dd\}/i',  date("d",$date), $numFinal);
1138 1138
 
@@ -1162,9 +1162,9 @@  discard block
 block discarded – undo
1162 1162
         // Now we replace the user
1163 1163
         if ($maskuser)
1164 1164
         {
1165
-        	$maskuser_maskbefore='{'.$maskuser.'}';
1166
-        	$maskuser_maskafter=$maskuser_value;
1167
-        	$numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1165
+            $maskuser_maskbefore='{'.$maskuser.'}';
1166
+            $maskuser_maskafter=$maskuser_value;
1167
+            $numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1168 1168
         }
1169 1169
     }
1170 1170
 
@@ -1183,11 +1183,11 @@  discard block
 block discarded – undo
1183 1183
 function get_string_between($string, $start, $end)
1184 1184
 {
1185 1185
     $string = " ".$string;
1186
-     $ini = strpos($string,$start);
1187
-     if ($ini == 0) return "";
1188
-     $ini += strlen($start);
1189
-     $len = strpos($string,$end,$ini) - $ini;
1190
-     return substr($string,$ini,$len);
1186
+        $ini = strpos($string,$start);
1187
+        if ($ini == 0) return "";
1188
+        $ini += strlen($start);
1189
+        $len = strpos($string,$end,$ini) - $ini;
1190
+        return substr($string,$ini,$len);
1191 1191
 }
1192 1192
 
1193 1193
 /**
@@ -1535,7 +1535,7 @@  discard block
 block discarded – undo
1535 1535
     }
1536 1536
     else
1537 1537
     {
1538
-    	$string = vatrate($reduction,true);
1538
+        $string = vatrate($reduction,true);
1539 1539
     }
1540 1540
 
1541 1541
     return $string;
@@ -1628,7 +1628,7 @@  discard block
 block discarded – undo
1628 1628
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1629 1629
                 $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1630 1630
 
1631
-		$listoffiles=array();
1631
+        $listoffiles=array();
1632 1632
 
1633 1633
                 // Now we add models found in directories scanned
1634 1634
                 $listofdir=explode(',',$dirtoscan);
@@ -1639,8 +1639,8 @@  discard block
 block discarded – undo
1639 1639
                     if (! $tmpdir) { unset($listofdir[$key]); continue; }
1640 1640
                     if (is_dir($tmpdir))
1641 1641
                     {
1642
-			// all type of template is allowed
1643
-			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1642
+            // all type of template is allowed
1643
+            $tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1644 1644
                         if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1645 1645
                     }
1646 1646
                 }
@@ -1696,19 +1696,19 @@  discard block
 block discarded – undo
1696 1696
  */
1697 1697
 function is_ip($ip)
1698 1698
 {
1699
-	// First we test if it is a valid IPv4
1700
-	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1699
+    // First we test if it is a valid IPv4
1700
+    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1701 1701
 
1702
-		// Then we test if it is a private range
1703
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1702
+        // Then we test if it is a private range
1703
+        if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1704 1704
 
1705
-		// Then we test if it is a reserved range
1706
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1705
+        // Then we test if it is a reserved range
1706
+        if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1707 1707
 
1708
-		return 1;
1709
-	}
1708
+        return 1;
1709
+    }
1710 1710
 
1711
-	return 0;
1711
+    return 0;
1712 1712
 }
1713 1713
 
1714 1714
 /**
@@ -1748,25 +1748,25 @@  discard block
 block discarded – undo
1748 1748
     if ($proxyuse)
1749 1749
     {
1750 1750
         $params=array('connection_timeout'=>$timeout,
1751
-                      'response_timeout'=>$response_timeout,
1752
-                      'proxy_use'      => 1,
1753
-                      'proxy_host'     => $proxyhost,
1754
-                      'proxy_port'     => $proxyport,
1755
-                      'proxy_login'    => $proxyuser,
1756
-                      'proxy_password' => $proxypass,
1757
-                      'trace'		   => 1
1751
+                        'response_timeout'=>$response_timeout,
1752
+                        'proxy_use'      => 1,
1753
+                        'proxy_host'     => $proxyhost,
1754
+                        'proxy_port'     => $proxyport,
1755
+                        'proxy_login'    => $proxyuser,
1756
+                        'proxy_password' => $proxypass,
1757
+                        'trace'		   => 1
1758 1758
         );
1759 1759
     }
1760 1760
     else
1761 1761
     {
1762 1762
         $params=array('connection_timeout'=>$timeout,
1763
-                      'response_timeout'=>$response_timeout,
1764
-                      'proxy_use'      => 0,
1765
-                      'proxy_host'     => false,
1766
-                      'proxy_port'     => false,
1767
-                      'proxy_login'    => false,
1768
-                      'proxy_password' => false,
1769
-                      'trace'		   => 1
1763
+                        'response_timeout'=>$response_timeout,
1764
+                        'proxy_use'      => 0,
1765
+                        'proxy_host'     => false,
1766
+                        'proxy_port'     => false,
1767
+                        'proxy_login'    => false,
1768
+                        'proxy_password' => false,
1769
+                        'trace'		   => 1
1770 1770
         );
1771 1771
     }
1772 1772
     return $params;
@@ -1784,118 +1784,118 @@  discard block
 block discarded – undo
1784 1784
  */
1785 1785
 function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
1786 1786
 {
1787
-	global $db, $conf, $langs;
1788
-
1789
-	$ret='';
1790
-
1791
-	// Parse element/subelement (ex: project_task)
1792
-	$module = $element = $subelement = $objecttype;
1793
-	if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1794
-	{
1795
-		$module = $element = $regs[1];
1796
-		$subelement = $regs[2];
1797
-	}
1798
-
1799
-	$classpath = $element.'/class';
1800
-
1801
-	// To work with non standard path
1802
-	if ($objecttype == 'facture' || $objecttype == 'invoice') {
1803
-		$classpath = 'compta/facture/class';
1804
-		$module='facture';
1805
-		$subelement='facture';
1806
-	}
1807
-	if ($objecttype == 'commande' || $objecttype == 'order') {
1808
-		$classpath = 'commande/class';
1809
-		$module='commande';
1810
-		$subelement='commande';
1811
-	}
1812
-	if ($objecttype == 'propal')  {
1813
-		$classpath = 'comm/propal/class';
1814
-	}
1815
-	if ($objecttype == 'supplier_proposal')  {
1816
-		$classpath = 'supplier_proposal/class';
1817
-	}
1818
-	if ($objecttype == 'shipping') {
1819
-		$classpath = 'expedition/class';
1820
-		$subelement = 'expedition';
1821
-		$module = 'expedition_bon';
1822
-	}
1823
-	if ($objecttype == 'delivery') {
1824
-		$classpath = 'livraison/class';
1825
-		$subelement = 'livraison';
1826
-		$module = 'livraison_bon';
1827
-	}
1828
-	if ($objecttype == 'contract') {
1829
-		$classpath = 'contrat/class';
1830
-		$module='contrat';
1831
-		$subelement='contrat';
1832
-	}
1833
-	if ($objecttype == 'member') {
1834
-		$classpath = 'adherents/class';
1835
-		$module='adherent';
1836
-		$subelement='adherent';
1837
-	}
1838
-	if ($objecttype == 'cabinetmed_cons') {
1839
-		$classpath = 'cabinetmed/class';
1840
-		$module='cabinetmed';
1841
-		$subelement='cabinetmedcons';
1842
-	}
1843
-	if ($objecttype == 'fichinter') {
1844
-		$classpath = 'fichinter/class';
1845
-		$module='ficheinter';
1846
-		$subelement='fichinter';
1847
-	}
1848
-	if ($objecttype == 'task') {
1849
-		$classpath = 'projet/class';
1850
-		$module='projet';
1851
-		$subelement='task';
1852
-	}
1853
-	if ($objecttype == 'stock') {
1854
-		$classpath = 'product/stock/class';
1855
-		$module='stock';
1856
-		$subelement='stock';
1857
-	}
1858
-
1859
-	//print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
1860
-
1861
-	$classfile = strtolower($subelement); $classname = ucfirst($subelement);
1862
-	if ($objecttype == 'invoice_supplier') {
1863
-		$classfile = 'fournisseur.facture';
1864
-		$classname='FactureFournisseur';
1865
-		$classpath = 'fourn/class';
1866
-		$module='fournisseur';
1867
-	}
1868
-	elseif ($objecttype == 'order_supplier')   {
1869
-		$classfile = 'fournisseur.commande';
1870
-		$classname='CommandeFournisseur';
1871
-		$classpath = 'fourn/class';
1872
-		$module='fournisseur';
1873
-	}
1874
-	elseif ($objecttype == 'stock')   {
1875
-		$classpath = 'product/stock/class';
1876
-		$classfile='entrepot';
1877
-		$classname='Entrepot';
1878
-	}
1879
-	if (! empty($conf->$module->enabled))
1880
-	{
1881
-		$res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1882
-		if ($res)
1883
-		{
1884
-			if (class_exists($classname))
1885
-			{
1886
-				$object = new $classname($db);
1887
-				$res=$object->fetch($objectid);
1888
-				if ($res > 0) {
1889
-					$ret=$object->getNomUrl($withpicto,$option);
1890
-				} elseif($res==0) {
1891
-					$ret=$langs->trans('Deleted');
1892
-				}
1893
-				unset($object);
1894
-			}
1895
-			else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1896
-		}
1897
-	}
1898
-	return $ret;
1787
+    global $db, $conf, $langs;
1788
+
1789
+    $ret='';
1790
+
1791
+    // Parse element/subelement (ex: project_task)
1792
+    $module = $element = $subelement = $objecttype;
1793
+    if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1794
+    {
1795
+        $module = $element = $regs[1];
1796
+        $subelement = $regs[2];
1797
+    }
1798
+
1799
+    $classpath = $element.'/class';
1800
+
1801
+    // To work with non standard path
1802
+    if ($objecttype == 'facture' || $objecttype == 'invoice') {
1803
+        $classpath = 'compta/facture/class';
1804
+        $module='facture';
1805
+        $subelement='facture';
1806
+    }
1807
+    if ($objecttype == 'commande' || $objecttype == 'order') {
1808
+        $classpath = 'commande/class';
1809
+        $module='commande';
1810
+        $subelement='commande';
1811
+    }
1812
+    if ($objecttype == 'propal')  {
1813
+        $classpath = 'comm/propal/class';
1814
+    }
1815
+    if ($objecttype == 'supplier_proposal')  {
1816
+        $classpath = 'supplier_proposal/class';
1817
+    }
1818
+    if ($objecttype == 'shipping') {
1819
+        $classpath = 'expedition/class';
1820
+        $subelement = 'expedition';
1821
+        $module = 'expedition_bon';
1822
+    }
1823
+    if ($objecttype == 'delivery') {
1824
+        $classpath = 'livraison/class';
1825
+        $subelement = 'livraison';
1826
+        $module = 'livraison_bon';
1827
+    }
1828
+    if ($objecttype == 'contract') {
1829
+        $classpath = 'contrat/class';
1830
+        $module='contrat';
1831
+        $subelement='contrat';
1832
+    }
1833
+    if ($objecttype == 'member') {
1834
+        $classpath = 'adherents/class';
1835
+        $module='adherent';
1836
+        $subelement='adherent';
1837
+    }
1838
+    if ($objecttype == 'cabinetmed_cons') {
1839
+        $classpath = 'cabinetmed/class';
1840
+        $module='cabinetmed';
1841
+        $subelement='cabinetmedcons';
1842
+    }
1843
+    if ($objecttype == 'fichinter') {
1844
+        $classpath = 'fichinter/class';
1845
+        $module='ficheinter';
1846
+        $subelement='fichinter';
1847
+    }
1848
+    if ($objecttype == 'task') {
1849
+        $classpath = 'projet/class';
1850
+        $module='projet';
1851
+        $subelement='task';
1852
+    }
1853
+    if ($objecttype == 'stock') {
1854
+        $classpath = 'product/stock/class';
1855
+        $module='stock';
1856
+        $subelement='stock';
1857
+    }
1858
+
1859
+    //print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
1860
+
1861
+    $classfile = strtolower($subelement); $classname = ucfirst($subelement);
1862
+    if ($objecttype == 'invoice_supplier') {
1863
+        $classfile = 'fournisseur.facture';
1864
+        $classname='FactureFournisseur';
1865
+        $classpath = 'fourn/class';
1866
+        $module='fournisseur';
1867
+    }
1868
+    elseif ($objecttype == 'order_supplier')   {
1869
+        $classfile = 'fournisseur.commande';
1870
+        $classname='CommandeFournisseur';
1871
+        $classpath = 'fourn/class';
1872
+        $module='fournisseur';
1873
+    }
1874
+    elseif ($objecttype == 'stock')   {
1875
+        $classpath = 'product/stock/class';
1876
+        $classfile='entrepot';
1877
+        $classname='Entrepot';
1878
+    }
1879
+    if (! empty($conf->$module->enabled))
1880
+    {
1881
+        $res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1882
+        if ($res)
1883
+        {
1884
+            if (class_exists($classname))
1885
+            {
1886
+                $object = new $classname($db);
1887
+                $res=$object->fetch($objectid);
1888
+                if ($res > 0) {
1889
+                    $ret=$object->getNomUrl($withpicto,$option);
1890
+                } elseif($res==0) {
1891
+                    $ret=$langs->trans('Deleted');
1892
+                }
1893
+                unset($object);
1894
+            }
1895
+            else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
1896
+        }
1897
+    }
1898
+    return $ret;
1899 1899
 }
1900 1900
 
1901 1901
 
@@ -1909,113 +1909,113 @@  discard block
 block discarded – undo
1909 1909
  */
1910 1910
 function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
1911 1911
 {
1912
-	$totalnb=0;
1913
-	$listofid=array();
1914
-	$listofparentid=array();
1915
-
1916
-	// Get list of all id in array listofid and all parents in array listofparentid
1917
-	$sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1918
-	$resql = $db->query($sql);
1919
-	if ($resql)
1920
-	{
1921
-		$num = $db->num_rows($resql);
1922
-		$i = 0;
1923
-		while ($i < $num)
1924
-		{
1925
-			$obj = $db->fetch_object($resql);
1926
-			$listofid[]=$obj->rowid;
1927
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1928
-			$i++;
1929
-		}
1930
-	}
1931
-	else
1932
-	{
1933
-		dol_print_error($db);
1934
-	}
1935
-
1936
-	if (count($listofid))
1937
-	{
1938
-		print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1939
-
1940
-		// Check loops on each other
1941
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1942
-		$resql = $db->query($sql);
1943
-		if ($resql)
1944
-		{
1945
-			$nb=$db->affected_rows($sql);
1946
-			if ($nb > 0)
1947
-			{
1948
-				print '<br>Some record that were parent of themself were cleaned.';
1949
-			}
1950
-
1951
-			$totalnb+=$nb;
1952
-		}
1953
-		//else dol_print_error($db);
1954
-
1955
-		// Check other loops
1956
-		$listofidtoclean=array();
1957
-		foreach($listofparentid as $id => $pid)
1958
-		{
1959
-			// Check depth
1960
-			//print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1961
-
1962
-			$cursor=$id; $arrayidparsed=array();	// We start from child $id
1963
-			while ($cursor > 0)
1964
-			{
1965
-				$arrayidparsed[$cursor]=1;
1966
-				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1967
-				{
1968
-					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1969
-					unset($arrayidparsed);
1970
-					$listofidtoclean[$cursor]=$id;
1971
-					break;
1972
-				}
1973
-				$cursor=$listofparentid[$cursor];
1974
-			}
1975
-
1976
-			if (count($listofidtoclean)) break;
1977
-		}
1978
-
1979
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1980
-		$sql.= " SET ".$fieldfkparent." = 0";
1981
-		$sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1982
-		$resql = $db->query($sql);
1983
-		if ($resql)
1984
-		{
1985
-			$nb=$db->affected_rows($sql);
1986
-			if ($nb > 0)
1987
-			{
1988
-				// Removed orphelins records
1989
-				print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1990
-				print join(',',$listofidtoclean);
1991
-			}
1992
-
1993
-			$totalnb+=$nb;
1994
-		}
1995
-		//else dol_print_error($db);
1996
-
1997
-		// Check and clean orphelins
1998
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1999
-		$sql.= " SET ".$fieldfkparent." = 0";
2000
-		$sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
2001
-		$resql = $db->query($sql);
2002
-		if ($resql)
2003
-		{
2004
-			$nb=$db->affected_rows($sql);
2005
-			if ($nb > 0)
2006
-			{
2007
-				// Removed orphelins records
2008
-				print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2009
-				print join(',',$listofid);
2010
-			}
2011
-
2012
-			$totalnb+=$nb;
2013
-		}
2014
-		//else dol_print_error($db);
2015
-
2016
-		print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2017
-		return $totalnb;
2018
-	}
1912
+    $totalnb=0;
1913
+    $listofid=array();
1914
+    $listofparentid=array();
1915
+
1916
+    // Get list of all id in array listofid and all parents in array listofparentid
1917
+    $sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1918
+    $resql = $db->query($sql);
1919
+    if ($resql)
1920
+    {
1921
+        $num = $db->num_rows($resql);
1922
+        $i = 0;
1923
+        while ($i < $num)
1924
+        {
1925
+            $obj = $db->fetch_object($resql);
1926
+            $listofid[]=$obj->rowid;
1927
+            if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1928
+            $i++;
1929
+        }
1930
+    }
1931
+    else
1932
+    {
1933
+        dol_print_error($db);
1934
+    }
1935
+
1936
+    if (count($listofid))
1937
+    {
1938
+        print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1939
+
1940
+        // Check loops on each other
1941
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1942
+        $resql = $db->query($sql);
1943
+        if ($resql)
1944
+        {
1945
+            $nb=$db->affected_rows($sql);
1946
+            if ($nb > 0)
1947
+            {
1948
+                print '<br>Some record that were parent of themself were cleaned.';
1949
+            }
1950
+
1951
+            $totalnb+=$nb;
1952
+        }
1953
+        //else dol_print_error($db);
1954
+
1955
+        // Check other loops
1956
+        $listofidtoclean=array();
1957
+        foreach($listofparentid as $id => $pid)
1958
+        {
1959
+            // Check depth
1960
+            //print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1961
+
1962
+            $cursor=$id; $arrayidparsed=array();	// We start from child $id
1963
+            while ($cursor > 0)
1964
+            {
1965
+                $arrayidparsed[$cursor]=1;
1966
+                if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1967
+                {
1968
+                    print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1969
+                    unset($arrayidparsed);
1970
+                    $listofidtoclean[$cursor]=$id;
1971
+                    break;
1972
+                }
1973
+                $cursor=$listofparentid[$cursor];
1974
+            }
1975
+
1976
+            if (count($listofidtoclean)) break;
1977
+        }
1978
+
1979
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1980
+        $sql.= " SET ".$fieldfkparent." = 0";
1981
+        $sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1982
+        $resql = $db->query($sql);
1983
+        if ($resql)
1984
+        {
1985
+            $nb=$db->affected_rows($sql);
1986
+            if ($nb > 0)
1987
+            {
1988
+                // Removed orphelins records
1989
+                print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1990
+                print join(',',$listofidtoclean);
1991
+            }
1992
+
1993
+            $totalnb+=$nb;
1994
+        }
1995
+        //else dol_print_error($db);
1996
+
1997
+        // Check and clean orphelins
1998
+        $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1999
+        $sql.= " SET ".$fieldfkparent." = 0";
2000
+        $sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
2001
+        $resql = $db->query($sql);
2002
+        if ($resql)
2003
+        {
2004
+            $nb=$db->affected_rows($sql);
2005
+            if ($nb > 0)
2006
+            {
2007
+                // Removed orphelins records
2008
+                print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2009
+                print join(',',$listofid);
2010
+            }
2011
+
2012
+            $totalnb+=$nb;
2013
+        }
2014
+        //else dol_print_error($db);
2015
+
2016
+        print '<br>We fixed '.$totalnb.' record(s). Some records may still be corrupted. New check may be required.';
2017
+        return $totalnb;
2018
+    }
2019 2019
 }
2020 2020
 
2021 2021
 /**
@@ -2147,21 +2147,21 @@  discard block
 block discarded – undo
2147 2147
 function fetchObjectByElement($element_id, $element_type, $element_ref='')
2148 2148
 {
2149 2149
     global $conf;
2150
-	global $db,$conf;
2150
+    global $db,$conf;
2151 2151
 
2152 2152
     $element_prop = getElementProperties($element_type);
2153 2153
     if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
2154 2154
     {
2155 2155
         dol_include_once('/'.$element_prop['classpath'].'/'.$element_prop['classfile'].'.class.php');
2156 2156
 
2157
-		$objecttmp = new $element_prop['classname']($db);
2158
-		$ret = $objecttmp->fetch($element_id, $element_ref);
2159
-		if ($ret >= 0)
2160
-		{
2161
-			return $objecttmp;
2162
-		}
2163
-	}
2164
-	return 0;
2157
+        $objecttmp = new $element_prop['classname']($db);
2158
+        $ret = $objecttmp->fetch($element_id, $element_ref);
2159
+        if ($ret >= 0)
2160
+        {
2161
+            return $objecttmp;
2162
+        }
2163
+    }
2164
+    return 0;
2165 2165
 }
2166 2166
 
2167 2167
 
@@ -2176,9 +2176,9 @@  discard block
 block discarded – undo
2176 2176
  */
2177 2177
 function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2178 2178
 {
2179
-	if (! is_array($arraycolor)) return $colorifnotfound;
2180
-	if (empty($arraycolor)) return $colorifnotfound;
2181
-	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2179
+    if (! is_array($arraycolor)) return $colorifnotfound;
2180
+    if (empty($arraycolor)) return $colorifnotfound;
2181
+    return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2182 2182
 }
2183 2183
 
2184 2184
 /**
@@ -2193,15 +2193,15 @@  discard block
 block discarded – undo
2193 2193
  */
2194 2194
 static function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2195 2195
     {
2196
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2197
-	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2198
-	if (! $tmp)
2199
-	{
2200
-		$tmp=explode(',',$stringcolor);
2201
-		if (count($tmp) < 3) return $colorifnotfound;
2202
-		return $tmp;
2203
-	}
2204
-	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2196
+    if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2197
+    $tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2198
+    if (! $tmp)
2199
+    {
2200
+        $tmp=explode(',',$stringcolor);
2201
+        if (count($tmp) < 3) return $colorifnotfound;
2202
+        return $tmp;
2203
+    }
2204
+    return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2205 2205
 }
2206 2206
 
2207 2207
 /**
@@ -2247,7 +2247,7 @@  discard block
 block discarded – undo
2247 2247
     if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2248 2248
 
2249 2249
     if ($module == 'contracts') {
2250
-    	$moduledirforclass = 'contrat';
2250
+        $moduledirforclass = 'contrat';
2251 2251
     }
2252 2252
     elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2253 2253
         $moduledirforclass = 'api';
@@ -2274,7 +2274,7 @@  discard block
 block discarded – undo
2274 2274
         $moduledirforclass = 'commande';
2275 2275
     }
2276 2276
     elseif ($module == 'shipments') {
2277
-    	$moduledirforclass = 'expedition';
2277
+        $moduledirforclass = 'expedition';
2278 2278
     }
2279 2279
     elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2280 2280
         $moduledirforclass = 'compta/facture';
@@ -2292,7 +2292,7 @@  discard block
 block discarded – undo
2292 2292
         $moduledirforclass = 'product/stock';
2293 2293
     }
2294 2294
     elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2295
-    	$moduledirforclass = 'supplier_proposal';
2295
+        $moduledirforclass = 'supplier_proposal';
2296 2296
     }
2297 2297
     elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2298 2298
         $moduledirforclass = 'fourn';
@@ -2304,10 +2304,10 @@  discard block
 block discarded – undo
2304 2304
         $moduledirforclass = 'user';
2305 2305
     }
2306 2306
     elseif ($module == 'ficheinter' || $module == 'interventions') {
2307
-    	$moduledirforclass = 'fichinter';
2307
+        $moduledirforclass = 'fichinter';
2308 2308
     }
2309 2309
     elseif ($module == 'tickets') {
2310
-    	$moduledirforclass = 'ticket';
2310
+        $moduledirforclass = 'ticket';
2311 2311
     }
2312 2312
 
2313 2313
     return $moduledirforclass;
Please login to merge, or discard this patch.
Spacing   +551 added lines, -551 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
                 $pos++;
57 57
                 $unicodeHexVal = substr($source, $pos, 4);
58 58
                 $unicode = hexdec($unicodeHexVal);
59
-                $entity = "&#". $unicode . ';';
59
+                $entity = "&#".$unicode.';';
60 60
                 $decodedStr .= utf8_encode($entity);
61 61
                 $pos += 4;
62 62
             }
@@ -82,32 +82,32 @@  discard block
 block discarded – undo
82 82
  * @param	string	$subdir		Sub directory (Example: '/mailings')
83 83
  * @return	array				Array of directories that can contains module descriptors
84 84
  */
85
-function dolGetModulesDirs($subdir='')
85
+function dolGetModulesDirs($subdir = '')
86 86
 {
87 87
     global $conf;
88 88
 
89
-    $modulesdir=array();
89
+    $modulesdir = array();
90 90
 
91 91
     foreach ($conf->file->dol_document_root as $type => $dirroot)
92 92
     {
93 93
         // Default core/modules dir
94 94
         if ($type === 'main') {
95
-            $modulesdir[$dirroot . '/core/modules' . $subdir . '/'] = $dirroot . '/core/modules' . $subdir . '/';
95
+            $modulesdir[$dirroot.'/core/modules'.$subdir.'/'] = $dirroot.'/core/modules'.$subdir.'/';
96 96
         }
97 97
 
98 98
         // Scan dir from external modules
99
-        $handle=@opendir($dirroot);
99
+        $handle = @opendir($dirroot);
100 100
         if (is_resource($handle))
101 101
         {
102
-            while (($file = readdir($handle))!==false)
102
+            while (($file = readdir($handle)) !== false)
103 103
             {
104
-                if (preg_match('/disabled/',$file)) continue;   // We discard module if it contains disabled into name.
104
+                if (preg_match('/disabled/', $file)) continue; // We discard module if it contains disabled into name.
105 105
 
106 106
                 if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
107 107
                 {
108
-                    if (is_dir($dirroot . '/' . $file . '/core/modules'.$subdir.'/'))
108
+                    if (is_dir($dirroot.'/'.$file.'/core/modules'.$subdir.'/'))
109 109
                     {
110
-                        $modulesdir[$dirroot . '/' . $file . '/core/modules'.$subdir.'/'] = $dirroot . '/' . $file . '/core/modules'.$subdir.'/';
110
+                        $modulesdir[$dirroot.'/'.$file.'/core/modules'.$subdir.'/'] = $dirroot.'/'.$file.'/core/modules'.$subdir.'/';
111 111
                     }
112 112
                 }
113 113
             }
@@ -128,13 +128,13 @@  discard block
 block discarded – undo
128 128
 {
129 129
     global $langs;
130 130
 
131
-    $selected='EUA4';
131
+    $selected = 'EUA4';
132 132
     if (!$outputlangs) {
133
-    	$outputlangs=$langs;
133
+    	$outputlangs = $langs;
134 134
     }
135 135
 
136
-    if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
137
-    if ($outputlangs->defaultlang == 'en_US') $selected='USLetter';    // US
136
+    if ($outputlangs->defaultlang == 'ca_CA') $selected = 'CAP4'; // Canada
137
+    if ($outputlangs->defaultlang == 'en_US') $selected = 'USLetter'; // US
138 138
     return $selected;
139 139
 }
140 140
 
@@ -146,20 +146,20 @@  discard block
 block discarded – undo
146 146
  *  @param  int			$searchalt      1=Search also in alternative languages
147 147
  *	@return	boolean						true if OK, false if KO
148 148
  */
149
-function dol_print_file($langs,$filename,$searchalt=0)
149
+function dol_print_file($langs, $filename, $searchalt = 0)
150 150
 {
151 151
     global $conf;
152 152
 
153 153
     // Test if file is in lang directory
154
-    foreach($langs->dir as $searchdir)
154
+    foreach ($langs->dir as $searchdir)
155 155
     {
156
-        $formfile=($searchdir."/langs/".$langs->defaultlang."/".$filename);
156
+        $formfile = ($searchdir."/langs/".$langs->defaultlang."/".$filename);
157 157
         dol_syslog('functions2::dol_print_file search file '.$formfile, LOG_DEBUG);
158 158
         if (is_readable($formfile))
159 159
         {
160
-            $content=file_get_contents($formfile);
161
-            $isutf8=utf8_check($content);
162
-            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
160
+            $content = file_get_contents($formfile);
161
+            $isutf8 = utf8_check($content);
162
+            if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
163 163
             elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
164 164
             else print $content;
165 165
             return true;
@@ -174,9 +174,9 @@  discard block
 block discarded – undo
174 174
             //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
175 175
             if (is_readable($formfilealt))
176 176
             {
177
-                $content=file_get_contents($formfilealt);
178
-                $isutf8=utf8_check($content);
179
-                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
177
+                $content = file_get_contents($formfilealt);
178
+                $isutf8 = utf8_check($content);
179
+                if (!$isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
180 180
                 elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
181 181
                 else print $content;
182 182
                 return true;
@@ -196,7 +196,7 @@  discard block
 block discarded – undo
196 196
  *  @param  int     $usetable       Output into a table
197 197
  *	@return	void
198 198
  */
199
-function dol_print_object_info($object, $usetable=0)
199
+function dol_print_object_info($object, $usetable = 0)
200 200
 {
201 201
     global $langs, $db;
202 202
 
@@ -205,16 +205,16 @@  discard block
 block discarded – undo
205 205
 
206 206
     include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
207 207
 
208
-    $deltadateforserver=getServerTimeZoneInt('now');
209
-    $deltadateforclient=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
208
+    $deltadateforserver = getServerTimeZoneInt('now');
209
+    $deltadateforclient = ((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
210 210
     //$deltadateforcompany=((int) $_SESSION['dol_tz'] + (int) $_SESSION['dol_dst']);
211
-    $deltadateforuser=round($deltadateforclient-$deltadateforserver);
211
+    $deltadateforuser = round($deltadateforclient - $deltadateforserver);
212 212
     //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
213 213
 
214 214
     if ($usetable) print '<table class="border centpercent">';
215 215
 
216 216
     // Import key
217
-    if (! empty($object->import_key))
217
+    if (!empty($object->import_key))
218 218
     {
219 219
         if ($usetable) print '<tr><td class="titlefield">';
220 220
         print $langs->trans("ImportedWithSet");
@@ -226,7 +226,7 @@  discard block
 block discarded – undo
226 226
     }
227 227
 
228 228
     // User creation (old method using already loaded object and not id is kept for backward compatibility)
229
-    if (! empty($object->user_creation) || ! empty($object->user_creation_id))
229
+    if (!empty($object->user_creation) || !empty($object->user_creation_id))
230 230
     {
231 231
         if ($usetable) print '<tr><td class="titlefield">';
232 232
         print $langs->trans("CreatedBy");
@@ -239,7 +239,7 @@  discard block
 block discarded – undo
239 239
         }
240 240
         else
241 241
         {
242
-            $userstatic=new User($db);
242
+            $userstatic = new User($db);
243 243
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
244 244
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
245 245
         	else print $langs->trans("Unknown");
@@ -249,20 +249,20 @@  discard block
 block discarded – undo
249 249
     }
250 250
 
251 251
     // Date creation
252
-    if (! empty($object->date_creation))
252
+    if (!empty($object->date_creation))
253 253
     {
254 254
         if ($usetable) print '<tr><td class="titlefield">';
255 255
         print $langs->trans("DateCreation");
256 256
         if ($usetable) print '</td><td>';
257 257
         else print ': ';
258 258
         print dol_print_date($object->date_creation, 'dayhour');
259
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
259
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
260 260
         if ($usetable) print '</td></tr>';
261 261
         else print '<br>';
262 262
     }
263 263
 
264 264
     // User change (old method using already loaded object and not id is kept for backward compatibility)
265
-    if (! empty($object->user_modification) || ! empty($object->user_modification_id))
265
+    if (!empty($object->user_modification) || !empty($object->user_modification_id))
266 266
     {
267 267
         if ($usetable) print '<tr><td class="titlefield">';
268 268
         print $langs->trans("ModifiedBy");
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
         }
276 276
         else
277 277
         {
278
-            $userstatic=new User($db);
278
+            $userstatic = new User($db);
279 279
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
280 280
             if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
281 281
         	else print $langs->trans("Unknown");
@@ -285,20 +285,20 @@  discard block
 block discarded – undo
285 285
     }
286 286
 
287 287
     // Date change
288
-    if (! empty($object->date_modification))
288
+    if (!empty($object->date_modification))
289 289
     {
290 290
         if ($usetable) print '<tr><td class="titlefield">';
291 291
         print $langs->trans("DateLastModification");
292 292
         if ($usetable) print '</td><td>';
293 293
         else print ': ';
294 294
         print dol_print_date($object->date_modification, 'dayhour');
295
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
295
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
296 296
         if ($usetable) print '</td></tr>';
297 297
         else print '<br>';
298 298
     }
299 299
 
300 300
     // User validation (old method using already loaded object and not id is kept for backward compatibility)
301
-    if (! empty($object->user_validation) || ! empty($object->user_validation_id))
301
+    if (!empty($object->user_validation) || !empty($object->user_validation_id))
302 302
     {
303 303
         if ($usetable) print '<tr><td class="titlefield">';
304 304
         print $langs->trans("ValidatedBy");
@@ -311,7 +311,7 @@  discard block
 block discarded – undo
311 311
         }
312 312
         else
313 313
         {
314
-            $userstatic=new User($db);
314
+            $userstatic = new User($db);
315 315
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
316 316
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
317 317
         	else print $langs->trans("Unknown");
@@ -321,20 +321,20 @@  discard block
 block discarded – undo
321 321
     }
322 322
 
323 323
     // Date validation
324
-    if (! empty($object->date_validation))
324
+    if (!empty($object->date_validation))
325 325
     {
326 326
         if ($usetable) print '<tr><td class="titlefield">';
327 327
         print $langs->trans("DateValidation");
328 328
         if ($usetable) print '</td><td>';
329 329
         else print ': ';
330 330
         print dol_print_date($object->date_validation, 'dayhour');
331
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
331
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
332 332
         if ($usetable) print '</td></tr>';
333 333
         else print '<br>';
334 334
     }
335 335
 
336 336
     // User approve (old method using already loaded object and not id is kept for backward compatibility)
337
-    if (! empty($object->user_approve) || ! empty($object->user_approve_id))
337
+    if (!empty($object->user_approve) || !empty($object->user_approve_id))
338 338
     {
339 339
         if ($usetable) print '<tr><td class="titlefield">';
340 340
         print $langs->trans("ApprovedBy");
@@ -347,7 +347,7 @@  discard block
 block discarded – undo
347 347
         }
348 348
         else
349 349
         {
350
-            $userstatic=new User($db);
350
+            $userstatic = new User($db);
351 351
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
352 352
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
353 353
         	else print $langs->trans("Unknown");
@@ -357,26 +357,26 @@  discard block
 block discarded – undo
357 357
     }
358 358
 
359 359
     // Date approve
360
-    if (! empty($object->date_approve))
360
+    if (!empty($object->date_approve))
361 361
     {
362 362
         if ($usetable) print '<tr><td class="titlefield">';
363 363
         print $langs->trans("DateApprove");
364 364
         if ($usetable) print '</td><td>';
365 365
         else print ': ';
366 366
         print dol_print_date($object->date_approve, 'dayhour');
367
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
367
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
368 368
         if ($usetable) print '</td></tr>';
369 369
         else print '<br>';
370 370
     }
371 371
 
372 372
     // User approve
373
-    if (! empty($object->user_approve_id2))
373
+    if (!empty($object->user_approve_id2))
374 374
     {
375 375
         if ($usetable) print '<tr><td class="titlefield">';
376 376
         print $langs->trans("ApprovedBy");
377 377
         if ($usetable) print '</td><td>';
378 378
         else print ': ';
379
-        $userstatic=new User($db);
379
+        $userstatic = new User($db);
380 380
         $userstatic->fetch($object->user_approve_id2);
381 381
         if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
382 382
         else print $langs->trans("Unknown");
@@ -385,20 +385,20 @@  discard block
 block discarded – undo
385 385
     }
386 386
 
387 387
     // Date approve
388
-    if (! empty($object->date_approve2))
388
+    if (!empty($object->date_approve2))
389 389
     {
390 390
         if ($usetable) print '<tr><td class="titlefield">';
391 391
         print $langs->trans("DateApprove2");
392 392
         if ($usetable) print '</td><td>';
393 393
         else print ': ';
394 394
         print dol_print_date($object->date_approve2, 'dayhour');
395
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
395
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2 + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
396 396
         if ($usetable) print '</td></tr>';
397 397
         else print '<br>';
398 398
     }
399 399
 
400 400
     // User close
401
-    if (! empty($object->user_cloture))
401
+    if (!empty($object->user_cloture))
402 402
     {
403 403
         if ($usetable) print '<tr><td class="titlefield">';
404 404
         print $langs->trans("ClosedBy");
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
         }
412 412
         else
413 413
         {
414
-            $userstatic=new User($db);
414
+            $userstatic = new User($db);
415 415
             $userstatic->fetch($object->user_cloture);
416 416
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
417 417
         	else print $langs->trans("Unknown");
@@ -421,20 +421,20 @@  discard block
 block discarded – undo
421 421
     }
422 422
 
423 423
     // Date close
424
-    if (! empty($object->date_cloture))
424
+    if (!empty($object->date_cloture))
425 425
     {
426 426
         if ($usetable) print '<tr><td class="titlefield">';
427 427
         print $langs->trans("DateClosing");
428 428
         if ($usetable) print '</td><td>';
429 429
         else print ': ';
430 430
         print dol_print_date($object->date_cloture, 'dayhour');
431
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
431
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
432 432
         if ($usetable) print '</td></tr>';
433 433
         else print '<br>';
434 434
     }
435 435
 
436 436
     // User conciliate
437
-    if (! empty($object->user_rappro))
437
+    if (!empty($object->user_rappro))
438 438
     {
439 439
         if ($usetable) print '<tr><td class="titlefield">';
440 440
         print $langs->trans("ConciliatedBy");
@@ -447,7 +447,7 @@  discard block
 block discarded – undo
447 447
         }
448 448
         else
449 449
         {
450
-            $userstatic=new User($db);
450
+            $userstatic = new User($db);
451 451
             $userstatic->fetch($object->user_rappro);
452 452
 			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
453 453
         	else print $langs->trans("Unknown");
@@ -457,27 +457,27 @@  discard block
 block discarded – undo
457 457
     }
458 458
 
459 459
     // Date conciliate
460
-    if (! empty($object->date_rappro))
460
+    if (!empty($object->date_rappro))
461 461
     {
462 462
         if ($usetable) print '<tr><td class="titlefield">';
463 463
         print $langs->trans("DateConciliating");
464 464
         if ($usetable) print '</td><td>';
465 465
         else print ': ';
466 466
         print dol_print_date($object->date_rappro, 'dayhour');
467
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
467
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
468 468
         if ($usetable) print '</td></tr>';
469 469
         else print '<br>';
470 470
     }
471 471
 
472 472
     // Date send
473
-    if (! empty($object->date_envoi))
473
+    if (!empty($object->date_envoi))
474 474
     {
475 475
         if ($usetable) print '<tr><td class="titlefield">';
476 476
         print $langs->trans("DateLastSend");
477 477
         if ($usetable) print '</td><td>';
478 478
         else print ': ';
479 479
         print dol_print_date($object->date_envoi, 'dayhour');
480
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
480
+        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi + ($deltadateforuser * 3600), "dayhour").' &nbsp;'.$langs->trans("ClientHour");
481 481
         if ($usetable) print '</td></tr>';
482 482
         else print '<br>';
483 483
     }
@@ -496,8 +496,8 @@  discard block
 block discarded – undo
496 496
  */
497 497
 function dolAddEmailTrackId($email, $trackingid)
498 498
 {
499
-	$tmp=explode('@',$email);
500
-	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1])?$tmp[1]:'');
499
+	$tmp = explode('@', $email);
500
+	return $tmp[0].'+'.$trackingid.'@'.(isset($tmp[1]) ? $tmp[1] : '');
501 501
 }
502 502
 
503 503
 /**
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
  *  @param  int		$anchor		1: verify anchor is provided, 0: not verify anchor
533 533
  *	@return int					1=Check is OK, 0=Check is KO
534 534
  */
535
-function isValidUrl($url,$http=0,$pass=0,$port=0,$path=0,$query=0,$anchor=0)
535
+function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0, $anchor = 0)
536 536
 {
537 537
     $ValidUrl = 0;
538 538
     $urlregex = '';
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
     // HOSTNAME OR IP
547 547
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // x allowed (ex. http://localhost, http://routerlogin)
548 548
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)+";  // x.x
549
-    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*";  // x ou x.xx (2 x ou plus)
549
+    $urlregex .= "([a-z0-9+\$_\\\:-])+(\.[a-z0-9+\$_-][a-z0-9+\$_-]+)*"; // x ou x.xx (2 x ou plus)
550 550
     //use only one of the above
551 551
 
552 552
     // PORT
@@ -575,33 +575,33 @@  discard block
 block discarded – undo
575 575
  *	@param  integer	$http		1 = keep both http:// and https://, 0: remove http:// but not https://
576 576
  *	@return string				Cleaned url
577 577
  */
578
-function clean_url($url,$http=1)
578
+function clean_url($url, $http = 1)
579 579
 {
580 580
     // Fixed by Matelli (see http://matelli.fr/showcases/patchs-dolibarr/fix-cleaning-url.html)
581 581
     // To include the minus sign in a char class, we must not escape it but put it at the end of the class
582 582
     // Also, there's no need of escape a dot sign in a class
583
-    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i',$url,$regs))
583
+    if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs))
584 584
     {
585
-        $proto=$regs[1];
586
-        $domain=$regs[2];
587
-        $port=isset($regs[3])?$regs[3]:'';
585
+        $proto = $regs[1];
586
+        $domain = $regs[2];
587
+        $port = isset($regs[3]) ? $regs[3] : '';
588 588
         //print $url." -> ".$proto." - ".$domain." - ".$port;
589 589
         //$url = dol_string_nospecial(trim($url));
590 590
         $url = trim($url);
591 591
 
592 592
         // Si http: defini on supprime le http (Si https on ne supprime pas)
593
-        $newproto=$proto;
594
-        if ($http==0)
593
+        $newproto = $proto;
594
+        if ($http == 0)
595 595
         {
596
-            if (preg_match('/^http:[\\/]+/i',$url))
596
+            if (preg_match('/^http:[\\/]+/i', $url))
597 597
             {
598
-                $url = preg_replace('/^http:[\\/]+/i','',$url);
598
+                $url = preg_replace('/^http:[\\/]+/i', '', $url);
599 599
                 $newproto = '';
600 600
             }
601 601
         }
602 602
 
603 603
         // On passe le nom de domaine en minuscule
604
-        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
604
+        $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url);
605 605
 
606 606
         return $CleanUrl;
607 607
     }
@@ -621,35 +621,35 @@  discard block
 block discarded – undo
621 621
  * 	@param 		bool		$displaytld			Display tld (default: true)
622 622
  * 	@return		string							Return email with hidden parts or '';
623 623
  */
624
-function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
624
+function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true)
625 625
 {
626
-	if(!isValidEmail($mail))return '';
626
+	if (!isValidEmail($mail))return '';
627 627
 	$tab = explode('@', $mail);
628
-	$tab2 = explode('.',$tab[1]);
628
+	$tab2 = explode('.', $tab[1]);
629 629
 	$string_replace = '';
630 630
 	$mail_name = $tab[0];
631 631
 	$mail_domaine = $tab2[0];
632 632
 	$mail_tld = '';
633 633
 
634 634
 	$nbofelem = count($tab2);
635
-	for($i=1; $i < $nbofelem && $displaytld; $i++)
635
+	for ($i = 1; $i < $nbofelem && $displaytld; $i++)
636 636
 	{
637 637
 		$mail_tld .= '.'.$tab2[$i];
638 638
 	}
639 639
 
640
-	for($i=0; $i < $nbreplace; $i++){
640
+	for ($i = 0; $i < $nbreplace; $i++) {
641 641
 		$string_replace .= $replace;
642 642
 	}
643 643
 
644
-	if(strlen($mail_name) > $nbdisplaymail){
644
+	if (strlen($mail_name) > $nbdisplaymail) {
645 645
 		$mail_name = substr($mail_name, 0, $nbdisplaymail);
646 646
 	}
647 647
 
648
-	if(strlen($mail_domaine) > $nbdisplaydomain){
649
-		$mail_domaine = substr($mail_domaine, strlen($mail_domaine)-$nbdisplaydomain);
648
+	if (strlen($mail_domaine) > $nbdisplaydomain) {
649
+		$mail_domaine = substr($mail_domaine, strlen($mail_domaine) - $nbdisplaydomain);
650 650
 	}
651 651
 
652
-	return $mail_name . $string_replace . $mail_domaine . $mail_tld;
652
+	return $mail_name.$string_replace.$mail_domaine.$mail_tld;
653 653
 }
654 654
 
655 655
 
@@ -662,14 +662,14 @@  discard block
 block discarded – undo
662 662
  * 	@param	string	$tdoptions	Options for td
663 663
  * 	@return	string
664 664
  */
665
-function array2tr($data,$troptions='',$tdoptions='')
665
+function array2tr($data, $troptions = '', $tdoptions = '')
666 666
 {
667
-    $text = '<tr '.$troptions.'>' ;
668
-    foreach($data as $key => $item){
669
-        $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
667
+    $text = '<tr '.$troptions.'>';
668
+    foreach ($data as $key => $item) {
669
+        $text .= '<td '.$tdoptions.'>'.$item.'</td>';
670 670
     }
671
-    $text.= '</tr>' ;
672
-    return $text ;
671
+    $text .= '</tr>';
672
+    return $text;
673 673
 }
674 674
 
675 675
 /**
@@ -682,22 +682,22 @@  discard block
 block discarded – undo
682 682
  * 	@param	string	$tdoptions		Options for td
683 683
  * 	@return	string
684 684
  */
685
-function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
685
+function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '')
686 686
 {
687
-    $text='' ;
688
-    if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
689
-    foreach($data as $key => $item){
690
-        if(is_array($item)){
691
-            $text.=array2tr($item,$troptions,$tdoptions);
687
+    $text = '';
688
+    if ($tableMarkup) $text = '<table '.$tableoptions.'>';
689
+    foreach ($data as $key => $item) {
690
+        if (is_array($item)) {
691
+            $text .= array2tr($item, $troptions, $tdoptions);
692 692
         } else {
693
-            $text.= '<tr '.$troptions.'>' ;
694
-            $text.= '<td '.$tdoptions.'>'.$key.'</td>' ;
695
-            $text.= '<td '.$tdoptions.'>'.$item.'</td>' ;
696
-            $text.= '</tr>' ;
693
+            $text .= '<tr '.$troptions.'>';
694
+            $text .= '<td '.$tdoptions.'>'.$key.'</td>';
695
+            $text .= '<td '.$tdoptions.'>'.$item.'</td>';
696
+            $text .= '</tr>';
697 697
         }
698 698
     }
699
-    if($tableMarkup) $text.= '</table>' ;
700
-    return $text ;
699
+    if ($tableMarkup) $text .= '</table>';
700
+    return $text;
701 701
 }
702 702
 
703 703
 /**
@@ -716,19 +716,19 @@  discard block
 block discarded – undo
716 716
  * @param	int			$forceentity	Entity id to force
717 717
  * @return 	string						New value (numeric) or error message
718 718
  */
719
-function get_next_value($db,$mask,$table,$field,$where='',$objsoc='',$date='',$mode='next', $bentityon=true, $objuser=null, $forceentity=null)
719
+function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $date = '', $mode = 'next', $bentityon = true, $objuser = null, $forceentity = null)
720 720
 {
721
-    global $conf,$user;
721
+    global $conf, $user;
722 722
 
723
-    if (! is_object($objsoc)) $valueforccc=$objsoc;
724
-    else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
725
-    else $valueforccc=$objsoc->code_client;
723
+    if (!is_object($objsoc)) $valueforccc = $objsoc;
724
+    else if ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = $objsoc->code_fournisseur;
725
+    else $valueforccc = $objsoc->code_client;
726 726
 
727 727
     $sharetable = $table;
728 728
     if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
729 729
 
730 730
     // Clean parameters
731
-    if ($date == '') $date=dol_now();	// We use local year and month of PHP server to search numbers
731
+    if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers
732 732
     // but we should use local year and month of user
733 733
 
734 734
     // For debugging
@@ -738,132 +738,132 @@  discard block
 block discarded – undo
738 738
     //$date=dol_mktime(12, 0, 0, 1, 1, 1900);
739 739
     //$date=dol_stringtotime('20130101');
740 740
 
741
-    $hasglobalcounter=false;
741
+    $hasglobalcounter = false;
742 742
     // Extract value for mask counter, mask raz and mask offset
743
-    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$mask,$reg))
743
+    if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg))
744 744
     {
745
-        $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
746
-        $maskcounter=$reg[1];
747
-        $hasglobalcounter=true;
745
+        $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : '');
746
+        $maskcounter = $reg[1];
747
+        $hasglobalcounter = true;
748 748
     }
749 749
     else
750 750
     {
751 751
         // setting some defaults so the rest of the code won't fail if there is a third party counter
752
-        $masktri='00000';
753
-        $maskcounter='00000';
752
+        $masktri = '00000';
753
+        $maskcounter = '00000';
754 754
     }
755 755
 
756
-    $maskraz=-1;
757
-    $maskoffset=0;
758
-    $resetEveryMonth=false;
756
+    $maskraz = -1;
757
+    $maskoffset = 0;
758
+    $resetEveryMonth = false;
759 759
     if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
760 760
 
761 761
     // Extract value for third party mask counter
762
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
763
-    {
764
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
765
-        $maskrefclient_maskclientcode=$regClientRef[1];
766
-        $maskrefclient_maskcounter=$regClientRef[2];
767
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
768
-        $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
769
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
770
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
762
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
763
+    {
764
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
765
+        $maskrefclient_maskclientcode = $regClientRef[1];
766
+        $maskrefclient_maskcounter = $regClientRef[2];
767
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
768
+        $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask
769
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
770
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
771 771
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
772 772
     }
773
-    else $maskrefclient='';
773
+    else $maskrefclient = '';
774 774
 
775 775
     // fail if there is neither a global nor a third party counter
776
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
776
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
777 777
     {
778 778
         return 'ErrorBadMask';
779 779
     }
780 780
 
781 781
     // Extract value for third party type
782
-    if (preg_match('/\{(t+)\}/i',$mask,$regType))
782
+    if (preg_match('/\{(t+)\}/i', $mask, $regType))
783 783
     {
784
-        $masktype=$regType[1];
785
-        $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
786
-        $masktype_value=str_pad($masktype_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
784
+        $masktype = $regType[1];
785
+        $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask)
786
+        $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
787 787
     }
788 788
     else
789 789
     {
790
-    	$masktype='';
791
-    	$masktype_value='';
790
+    	$masktype = '';
791
+    	$masktype_value = '';
792 792
     }
793 793
 
794 794
     // Extract value for user
795
-    if (preg_match('/\{(u+)\}/i',$mask,$regType))
795
+    if (preg_match('/\{(u+)\}/i', $mask, $regType))
796 796
     {
797 797
     	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
798 798
     	if (is_object($objuser)) $lastname = $objuser->lastname;
799 799
 
800
-    	$maskuser=$regType[1];
801
-    	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
802
-    	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
800
+    	$maskuser = $regType[1];
801
+    	$maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask)
802
+    	$maskuser_value = str_pad($maskuser_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask
803 803
     }
804 804
     else
805 805
     {
806
-    	$maskuser='';
807
-    	$maskuser_value='';
806
+    	$maskuser = '';
807
+    	$maskuser_value = '';
808 808
     }
809 809
 
810 810
     // Personalized field {XXX-1} à {XXX-9}
811
-    $maskperso=array();
812
-    $maskpersonew=array();
813
-    $tmpmask=$mask;
814
-    while (preg_match('/\{([A-Z]+)\-([1-9])\}/',$tmpmask,$regKey))
811
+    $maskperso = array();
812
+    $maskpersonew = array();
813
+    $tmpmask = $mask;
814
+    while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey))
815 815
     {
816
-        $maskperso[$regKey[1]]='{'.$regKey[1].'-'.$regKey[2].'}';
817
-        $maskpersonew[$regKey[1]]=str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
818
-        $tmpmask=preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
816
+        $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}';
817
+        $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT);
818
+        $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask);
819 819
     }
820 820
 
821
-    if (strstr($mask,'user_extra_'))
821
+    if (strstr($mask, 'user_extra_'))
822 822
     {
823 823
 			$start = "{user_extra_";
824 824
 			$end = "\}";
825
-			$extra= get_string_between($mask, "user_extra_", "}");
826
-			if(!empty($user->array_options['options_'.$extra])){
827
-				$mask =  preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
825
+			$extra = get_string_between($mask, "user_extra_", "}");
826
+			if (!empty($user->array_options['options_'.$extra])) {
827
+				$mask = preg_replace('#('.$start.')(.*?)('.$end.')#si', $user->array_options['options_'.$extra], $mask);
828 828
 			}
829 829
     }
830
-    $maskwithonlyymcode=$mask;
831
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i',$maskcounter,$maskwithonlyymcode);
832
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
833
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
834
-    $maskwithonlyymcode=preg_replace('/\{(t+)\}/i',$masktype_value,$maskwithonlyymcode);
835
-    $maskwithonlyymcode=preg_replace('/\{(u+)\}/i',$maskuser_value,$maskwithonlyymcode);
836
-    foreach($maskperso as $key => $val)
837
-    {
838
-        $maskwithonlyymcode=preg_replace('/'.preg_quote($val,'/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
839
-    }
840
-    $maskwithnocode=$maskwithonlyymcode;
841
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
842
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
843
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
844
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
830
+    $maskwithonlyymcode = $mask;
831
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $maskcounter, $maskwithonlyymcode);
832
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
833
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
834
+    $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode);
835
+    $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode);
836
+    foreach ($maskperso as $key => $val)
837
+    {
838
+        $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode);
839
+    }
840
+    $maskwithnocode = $maskwithonlyymcode;
841
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
842
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
843
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
844
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
845 845
     // Now maskwithnocode = 0000ddmmyyyyccc for example
846 846
     // and maskcounter    = 0000 for example
847 847
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
848 848
     //var_dump($reg);
849 849
 
850 850
     // If an offset is asked
851
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
852
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
851
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
852
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
853 853
 
854 854
     // Define $sqlwhere
855
-    $sqlwhere='';
856
-    $yearoffset=0;	// Use year of current $date by default
857
-    $yearoffsettype=false;		// false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
855
+    $sqlwhere = '';
856
+    $yearoffset = 0; // Use year of current $date by default
857
+    $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
858 858
 
859 859
     // If a restore to zero after a month is asked we check if there is already a value for this year.
860
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))	$yearoffsettype = preg_replace('/^@/','',$reg[2]);
861
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))	$yearoffsettype = preg_replace('/^@/','',$reg[3]);
860
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))	$yearoffsettype = preg_replace('/^@/', '', $reg[2]);
861
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))	$yearoffsettype = preg_replace('/^@/', '', $reg[3]);
862 862
 
863 863
     //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
864 864
     if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
865
-        $maskraz=$yearoffsettype; // For backward compatibility
866
-    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
865
+        $maskraz = $yearoffsettype; // For backward compatibility
866
+    else if ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
867 867
         $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
868 868
     //print "maskraz=".$maskraz;	// -1=no reset
869 869
 
@@ -877,79 +877,79 @@  discard block
 block discarded – undo
877 877
         // Define posy, posm and reg
878 878
         if ($maskraz > 1)	// if reset is not first month, we need month and year into mask
879 879
         {
880
-            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
881
-            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
880
+            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
881
+            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
882 882
             else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
883 883
 
884 884
             if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
885 885
         }
886 886
         else // if reset is for a specific month in year, we need year
887 887
         {
888
-            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
889
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
890
-            else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
888
+            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; }
889
+        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; }
890
+            else if (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; }
891 891
             else return 'ErrorCantUseRazIfNoYearInMask';
892 892
         }
893 893
         // Define length
894
-        $yearlen = $posy?dol_strlen($reg[$posy]):0;
895
-        $monthlen = $posm?dol_strlen($reg[$posm]):0;
894
+        $yearlen = $posy ?dol_strlen($reg[$posy]) : 0;
895
+        $monthlen = $posm ?dol_strlen($reg[$posm]) : 0;
896 896
         // Define pos
897
-       	$yearpos = (dol_strlen($reg[1])+1);
898
-        $monthpos = ($yearpos+$yearlen);
897
+       	$yearpos = (dol_strlen($reg[1]) + 1);
898
+        $monthpos = ($yearpos + $yearlen);
899 899
         if ($posy == 3 && $posm == 2) {		// if month is before year
900
-          	$monthpos = (dol_strlen($reg[1])+1);
901
-           	$yearpos = ($monthpos+$monthlen);
900
+          	$monthpos = (dol_strlen($reg[1]) + 1);
901
+           	$yearpos = ($monthpos + $monthlen);
902 902
         }
903 903
         //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n";
904 904
 
905 905
         // Define $yearcomp and $monthcomp (that will be use in the select where to search max number)
906
-        $monthcomp=$maskraz;
907
-        $yearcomp=0;
906
+        $monthcomp = $maskraz;
907
+        $yearcomp = 0;
908 908
 
909
-        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
909
+        if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
910 910
         {
911
-        	$currentyear=date("Y", $date);
912
-        	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
913
-        	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
914
-        	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
911
+        	$currentyear = date("Y", $date);
912
+        	$fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear);
913
+        	$newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear);
914
+        	$nextnewyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear + 1);
915 915
         	//echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'<br>';
916 916
 
917 917
         	// If after or equal of current fiscal date
918 918
         	if ($date >= $fiscaldate)
919 919
         	{
920 920
         		// If before of next new year date
921
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
921
+        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1;
922 922
         	}
923 923
         	// If after or equal of current new year date
924
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
924
+        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1;
925 925
         }
926 926
         // For backward compatibility
927
-        else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
927
+        else if (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; }	// If current month lower that month of return to zero, year is previous year
928 928
 
929
-        if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
930
-        elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
931
-        elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
929
+        if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset);
930
+        elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset);
931
+        elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset;
932 932
         if ($monthcomp > 1 && empty($resetEveryMonth))	// Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
933 933
         {
934
-            if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
935
-            elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
936
-
937
-            $sqlwhere.="(";
938
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
939
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
940
-            $sqlwhere.=" OR";
941
-            $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
942
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
943
-            $sqlwhere.=')';
934
+            if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1);
935
+            elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1);
936
+
937
+            $sqlwhere .= "(";
938
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
939
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") >= '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
940
+            $sqlwhere .= " OR";
941
+            $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
942
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
943
+            $sqlwhere .= ')';
944 944
         }
945 945
 		else if ($resetEveryMonth)
946 946
 		{
947
-			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
948
-            $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
947
+			$sqlwhere .= "(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
948
+            $sqlwhere .= " AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
949 949
 		}
950 950
         else   // reset is done on january
951 951
         {
952
-            $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
952
+            $sqlwhere .= '(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
953 953
         }
954 954
     }
955 955
     //print "sqlwhere=".$sqlwhere." yearcomp=".$yearcomp."<br>\n";	// sqlwhere and yearcomp defined only if we ask a reset
@@ -958,49 +958,49 @@  discard block
 block discarded – undo
958 958
     // Define $sqlstring
959 959
     if (function_exists('mb_strrpos'))
960 960
     	{
961
-    	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
961
+    	$posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 'UTF-8');
962 962
 	}
963 963
 	else
964 964
 	{
965
-    	$posnumstart=strrpos($maskwithnocode,$maskcounter);
965
+    	$posnumstart = strrpos($maskwithnocode, $maskcounter);
966 966
 	}	// Pos of counter in final string (from 0 to ...)
967 967
     if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
968
-    $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
968
+    $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')';
969 969
 
970 970
     // Define $maskLike
971 971
     $maskLike = dol_string_nospecial($mask);
972
-    $maskLike = str_replace("%","_",$maskLike);
972
+    $maskLike = str_replace("%", "_", $maskLike);
973 973
     // Replace protected special codes with matching number of _ as wild card caracter
974
-    $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
975
-    $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
976
-    $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
977
-    $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
978
-    $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
979
-    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
980
-    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
981
-    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
982
-    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
983
-    foreach($maskperso as $key => $val)
974
+    $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
975
+    $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
976
+    $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
977
+    $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
978
+    $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
979
+    $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike);
980
+    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
981
+    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
982
+    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
983
+    foreach ($maskperso as $key => $val)
984 984
     {
985
-    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
985
+    	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike);
986 986
     }
987 987
 
988 988
     // Get counter in database
989
-    $counter=0;
989
+    $counter = 0;
990 990
     $sql = "SELECT MAX(".$sqlstring.") as val";
991
-    $sql.= " FROM ".MAIN_DB_PREFIX.$table;
992
-    $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
993
-	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
991
+    $sql .= " FROM ".MAIN_DB_PREFIX.$table;
992
+    $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
993
+	$sql .= " AND ".$field." NOT LIKE '(PROV%)'";
994 994
     if ($bentityon) // only if entity enable
995
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
996
-    else if (! empty($forceentity))
997
-    	$sql.= " AND entity IN (".$forceentity.")";
998
-    if ($where) $sql.=$where;
999
-    if ($sqlwhere) $sql.=' AND '.$sqlwhere;
995
+    	$sql .= " AND entity IN (".getEntity($sharetable).")";
996
+    else if (!empty($forceentity))
997
+    	$sql .= " AND entity IN (".$forceentity.")";
998
+    if ($where) $sql .= $where;
999
+    if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
1000 1000
 
1001 1001
     //print $sql.'<br>';
1002 1002
     dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1003
-    $resql=$db->query($sql);
1003
+    $resql = $db->query($sql);
1004 1004
     if ($resql)
1005 1005
     {
1006 1006
         $obj = $db->fetch_object($resql);
@@ -1009,46 +1009,46 @@  discard block
 block discarded – undo
1009 1009
     else dol_print_error($db);
1010 1010
 
1011 1011
     // Check if we must force counter to maskoffset
1012
-    if (empty($counter)) $counter=$maskoffset;
1013
-    else if (preg_match('/[^0-9]/i',$counter))
1012
+    if (empty($counter)) $counter = $maskoffset;
1013
+    else if (preg_match('/[^0-9]/i', $counter))
1014 1014
     {
1015
-    	$counter=0;
1015
+    	$counter = 0;
1016 1016
     	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1017 1017
     }
1018
-    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1018
+    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset;
1019 1019
 
1020 1020
     if ($mode == 'last')	// We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1021 1021
     {
1022
-        $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1022
+        $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1023 1023
 
1024 1024
         // Define $maskLike
1025 1025
         $maskLike = dol_string_nospecial($mask);
1026
-        $maskLike = str_replace("%","_",$maskLike);
1026
+        $maskLike = str_replace("%", "_", $maskLike);
1027 1027
         // Replace protected special codes with matching number of _ as wild card caracter
1028
-        $maskLike = preg_replace('/\{yyyy\}/i','____',$maskLike);
1029
-        $maskLike = preg_replace('/\{yy\}/i','__',$maskLike);
1030
-        $maskLike = preg_replace('/\{y\}/i','_',$maskLike);
1031
-        $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
1032
-        $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
1033
-        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
1034
-        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1035
-        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1036
-        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1037
-
1038
-        $ref='';
1028
+        $maskLike = preg_replace('/\{yyyy\}/i', '____', $maskLike);
1029
+        $maskLike = preg_replace('/\{yy\}/i', '__', $maskLike);
1030
+        $maskLike = preg_replace('/\{y\}/i', '_', $maskLike);
1031
+        $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike);
1032
+        $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike);
1033
+        $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike);
1034
+        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike);
1035
+        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike);
1036
+        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike);
1037
+
1038
+        $ref = '';
1039 1039
         $sql = "SELECT ".$field." as ref";
1040
-        $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1041
-        $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1042
-    	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1040
+        $sql .= " FROM ".MAIN_DB_PREFIX.$table;
1041
+        $sql .= " WHERE ".$field." LIKE '".$maskLike."'";
1042
+    	$sql .= " AND ".$field." NOT LIKE '%PROV%'";
1043 1043
     	if ($bentityon) // only if entity enable
1044
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1045
-        else if (! empty($forceentity))
1046
-        	$sql.= " AND entity IN (".$forceentity.")";
1047
-        if ($where) $sql.=$where;
1048
-        if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1044
+        	$sql .= " AND entity IN (".getEntity($sharetable).")";
1045
+        else if (!empty($forceentity))
1046
+        	$sql .= " AND entity IN (".$forceentity.")";
1047
+        if ($where) $sql .= $where;
1048
+        if ($sqlwhere) $sql .= ' AND '.$sqlwhere;
1049 1049
 
1050 1050
         dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1051
-        $resql=$db->query($sql);
1051
+        $resql = $db->query($sql);
1052 1052
         if ($resql)
1053 1053
         {
1054 1054
             $obj = $db->fetch_object($resql);
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
         }
1057 1057
         else dol_print_error($db);
1058 1058
 
1059
-        $numFinal=$ref;
1059
+        $numFinal = $ref;
1060 1060
     }
1061 1061
     else if ($mode == 'next')
1062 1062
     {
@@ -1065,47 +1065,47 @@  discard block
 block discarded – undo
1065 1065
         // If value for $counter has a length higher than $maskcounter chars
1066 1066
         if ($counter >= pow(10, dol_strlen($maskcounter)))
1067 1067
         {
1068
-        	$counter='ErrorMaxNumberReachForThisMask';
1068
+        	$counter = 'ErrorMaxNumberReachForThisMask';
1069 1069
         }
1070 1070
 
1071
-        if (! empty($maskrefclient_maskcounter))
1071
+        if (!empty($maskrefclient_maskcounter))
1072 1072
         {
1073 1073
             //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n<br>";
1074 1074
 
1075 1075
             // Define $sqlstring
1076
-            $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient));	// Pos of counter in final string (from 0 to ...)
1076
+            $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...)
1077 1077
             if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
1078
-            $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
1078
+            $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')';
1079 1079
             //print "x".$sqlstring;
1080 1080
 
1081 1081
             // Define $maskrefclient_maskLike
1082 1082
             $maskrefclient_maskLike = dol_string_nospecial($mask);
1083
-            $maskrefclient_maskLike = str_replace("%","_",$maskrefclient_maskLike);
1083
+            $maskrefclient_maskLike = str_replace("%", "_", $maskrefclient_maskLike);
1084 1084
             // Replace protected special codes with matching number of _ as wild card caracter
1085
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'),'____',$maskrefclient_maskLike);
1086
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'),'__',$maskrefclient_maskLike);
1087
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'),'_',$maskrefclient_maskLike);
1088
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'),'__',$maskrefclient_maskLike);
1089
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'),'__',$maskrefclient_maskLike);
1090
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskrefclient_maskLike);
1091
-            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),$maskrefclient_clientcode.str_pad("",dol_strlen($maskrefclient_maskcounter),"_"),$maskrefclient_maskLike);
1085
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yyyy}'), '____', $maskrefclient_maskLike);
1086
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{yy}'), '__', $maskrefclient_maskLike);
1087
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{y}'), '_', $maskrefclient_maskLike);
1088
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{mm}'), '__', $maskrefclient_maskLike);
1089
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{dd}'), '__', $maskrefclient_maskLike);
1090
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskrefclient_maskLike);
1091
+            $maskrefclient_maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), $maskrefclient_clientcode.str_pad("", dol_strlen($maskrefclient_maskcounter), "_"), $maskrefclient_maskLike);
1092 1092
 
1093 1093
             // Get counter in database
1094
-            $maskrefclient_counter=0;
1094
+            $maskrefclient_counter = 0;
1095 1095
             $maskrefclient_sql = "SELECT MAX(".$maskrefclient_sqlstring.") as val";
1096
-            $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
1096
+            $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table;
1097 1097
             //$sql.= " WHERE ".$field." not like '(%'";
1098
-            $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1098
+            $maskrefclient_sql .= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1099 1099
             if ($bentityon) // only if entity enable
1100
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1101
-            else if (! empty($forceentity))
1102
-            	$sql.= " AND entity IN (".$forceentity.")";
1103
-            if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1104
-            if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1105
-            $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1100
+            	$maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")";
1101
+            else if (!empty($forceentity))
1102
+            	$sql .= " AND entity IN (".$forceentity.")";
1103
+            if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask
1104
+            if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask
1105
+            $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1106 1106
 
1107 1107
             dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
1108
-            $maskrefclient_resql=$db->query($maskrefclient_sql);
1108
+            $maskrefclient_resql = $db->query($maskrefclient_sql);
1109 1109
             if ($maskrefclient_resql)
1110 1110
             {
1111 1111
                 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
@@ -1113,7 +1113,7 @@  discard block
 block discarded – undo
1113 1113
             }
1114 1114
             else dol_print_error($db);
1115 1115
 
1116
-            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1116
+            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset;
1117 1117
 			$maskrefclient_counter++;
1118 1118
         }
1119 1119
 
@@ -1121,54 +1121,54 @@  discard block
 block discarded – undo
1121 1121
         $numFinal = $mask;
1122 1122
 
1123 1123
         // We replace special codes except refclient
1124
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1124
+		if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1125 1125
 		{
1126
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1127
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1128
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1126
+	        $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal);
1127
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal);
1128
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal);
1129 1129
 		}
1130 1130
 		else	// we want yyyy to be current year
1131 1131
 		{
1132
-        	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1133
-        	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
1134
-        	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1), $numFinal);
1132
+        	$numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date), $numFinal);
1133
+        	$numFinal = preg_replace('/\{yy\}/i', date("y", $date), $numFinal);
1134
+        	$numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1), $numFinal);
1135 1135
 		}
1136
-        $numFinal = preg_replace('/\{mm\}/i',  date("m",$date), $numFinal);
1137
-        $numFinal = preg_replace('/\{dd\}/i',  date("d",$date), $numFinal);
1136
+        $numFinal = preg_replace('/\{mm\}/i', date("m", $date), $numFinal);
1137
+        $numFinal = preg_replace('/\{dd\}/i', date("d", $date), $numFinal);
1138 1138
 
1139 1139
         // Now we replace the counter
1140
-        $maskbefore='{'.$masktri.'}';
1141
-        $maskafter=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1140
+        $maskbefore = '{'.$masktri.'}';
1141
+        $maskafter = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT);
1142 1142
         //print 'x'.$maskbefore.'-'.$maskafter.'y';
1143
-        $numFinal = str_replace($maskbefore,$maskafter,$numFinal);
1143
+        $numFinal = str_replace($maskbefore, $maskafter, $numFinal);
1144 1144
 
1145 1145
         // Now we replace the refclient
1146 1146
         if ($maskrefclient)
1147 1147
         {
1148 1148
             //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1149
-            $maskrefclient_maskbefore='{'.$maskrefclient.'}';
1150
-            $maskrefclient_maskafter=$maskrefclient_clientcode.str_pad($maskrefclient_counter,dol_strlen($maskrefclient_maskcounter),"0",STR_PAD_LEFT);
1151
-            $numFinal = str_replace($maskrefclient_maskbefore,$maskrefclient_maskafter,$numFinal);
1149
+            $maskrefclient_maskbefore = '{'.$maskrefclient.'}';
1150
+            $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT);
1151
+            $numFinal = str_replace($maskrefclient_maskbefore, $maskrefclient_maskafter, $numFinal);
1152 1152
         }
1153 1153
 
1154 1154
         // Now we replace the type
1155 1155
         if ($masktype)
1156 1156
         {
1157
-            $masktype_maskbefore='{'.$masktype.'}';
1158
-            $masktype_maskafter=$masktype_value;
1159
-            $numFinal = str_replace($masktype_maskbefore,$masktype_maskafter,$numFinal);
1157
+            $masktype_maskbefore = '{'.$masktype.'}';
1158
+            $masktype_maskafter = $masktype_value;
1159
+            $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal);
1160 1160
         }
1161 1161
 
1162 1162
         // Now we replace the user
1163 1163
         if ($maskuser)
1164 1164
         {
1165
-        	$maskuser_maskbefore='{'.$maskuser.'}';
1166
-        	$maskuser_maskafter=$maskuser_value;
1167
-        	$numFinal = str_replace($maskuser_maskbefore,$maskuser_maskafter,$numFinal);
1165
+        	$maskuser_maskbefore = '{'.$maskuser.'}';
1166
+        	$maskuser_maskafter = $maskuser_value;
1167
+        	$numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal);
1168 1168
         }
1169 1169
     }
1170 1170
 
1171
-    dol_syslog("functions2::get_next_value return ".$numFinal,LOG_DEBUG);
1171
+    dol_syslog("functions2::get_next_value return ".$numFinal, LOG_DEBUG);
1172 1172
     return $numFinal;
1173 1173
 }
1174 1174
 
@@ -1183,11 +1183,11 @@  discard block
 block discarded – undo
1183 1183
 function get_string_between($string, $start, $end)
1184 1184
 {
1185 1185
     $string = " ".$string;
1186
-     $ini = strpos($string,$start);
1186
+     $ini = strpos($string, $start);
1187 1187
      if ($ini == 0) return "";
1188 1188
      $ini += strlen($start);
1189
-     $len = strpos($string,$end,$ini) - $ini;
1190
-     return substr($string,$ini,$len);
1189
+     $len = strpos($string, $end, $ini) - $ini;
1190
+     return substr($string, $ini, $len);
1191 1191
 }
1192 1192
 
1193 1193
 /**
@@ -1197,78 +1197,78 @@  discard block
 block discarded – undo
1197 1197
  * @param 	string	$value		Value
1198 1198
  * @return	int|string		    <0 or error string if KO, 0 if OK
1199 1199
  */
1200
-function check_value($mask,$value)
1200
+function check_value($mask, $value)
1201 1201
 {
1202
-    $result=0;
1202
+    $result = 0;
1203 1203
 
1204
-    $hasglobalcounter=false;
1204
+    $hasglobalcounter = false;
1205 1205
     // Extract value for mask counter, mask raz and mask offset
1206
-    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$mask,$reg))
1206
+    if (preg_match('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $mask, $reg))
1207 1207
     {
1208
-        $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
1209
-        $maskcounter=$reg[1];
1210
-        $hasglobalcounter=true;
1208
+        $masktri = $reg[1].(isset($reg[2]) ? $reg[2] : '').(isset($reg[3]) ? $reg[3] : '');
1209
+        $maskcounter = $reg[1];
1210
+        $hasglobalcounter = true;
1211 1211
     }
1212 1212
     else
1213 1213
     {
1214 1214
         // setting some defaults so the rest of the code won't fail if there is a third party counter
1215
-        $masktri='00000';
1216
-        $maskcounter='00000';
1215
+        $masktri = '00000';
1216
+        $maskcounter = '00000';
1217 1217
     }
1218 1218
 
1219
-    $maskraz=-1;
1220
-    $maskoffset=0;
1219
+    $maskraz = -1;
1220
+    $maskoffset = 0;
1221 1221
     if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1222 1222
 
1223 1223
     // Extract value for third party mask counter
1224
-    if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
1225
-    {
1226
-        $maskrefclient=$regClientRef[1].$regClientRef[2];
1227
-        $maskrefclient_maskclientcode=$regClientRef[1];
1228
-        $maskrefclient_maskcounter=$regClientRef[2];
1229
-        $maskrefclient_maskoffset=0; //default value of maskrefclient_counter offset
1230
-        $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
1231
-        $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1232
-        $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
1224
+    if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef))
1225
+    {
1226
+        $maskrefclient = $regClientRef[1].$regClientRef[2];
1227
+        $maskrefclient_maskclientcode = $regClientRef[1];
1228
+        $maskrefclient_maskcounter = $regClientRef[2];
1229
+        $maskrefclient_maskoffset = 0; //default value of maskrefclient_counter offset
1230
+        $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode
1231
+        $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1232
+        $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like
1233 1233
         if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1234 1234
     }
1235
-    else $maskrefclient='';
1235
+    else $maskrefclient = '';
1236 1236
 
1237 1237
     // fail if there is neither a global nor a third party counter
1238
-    if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
1238
+    if (!$hasglobalcounter && ($maskrefclient_maskcounter == ''))
1239 1239
     {
1240 1240
         return 'ErrorBadMask';
1241 1241
     }
1242 1242
 
1243
-    $maskwithonlyymcode=$mask;
1244
-    $maskwithonlyymcode=preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i',$maskcounter,$maskwithonlyymcode);
1245
-    $maskwithonlyymcode=preg_replace('/\{dd\}/i','dd',$maskwithonlyymcode);
1246
-    $maskwithonlyymcode=preg_replace('/\{(c+)(0*)\}/i',$maskrefclient,$maskwithonlyymcode);
1247
-    $maskwithnocode=$maskwithonlyymcode;
1248
-    $maskwithnocode=preg_replace('/\{yyyy\}/i','yyyy',$maskwithnocode);
1249
-    $maskwithnocode=preg_replace('/\{yy\}/i','yy',$maskwithnocode);
1250
-    $maskwithnocode=preg_replace('/\{y\}/i','y',$maskwithnocode);
1251
-    $maskwithnocode=preg_replace('/\{mm\}/i','mm',$maskwithnocode);
1243
+    $maskwithonlyymcode = $mask;
1244
+    $maskwithonlyymcode = preg_replace('/\{(0+)([@\+][0-9]+)?([@\+][0-9]+)?\}/i', $maskcounter, $maskwithonlyymcode);
1245
+    $maskwithonlyymcode = preg_replace('/\{dd\}/i', 'dd', $maskwithonlyymcode);
1246
+    $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode);
1247
+    $maskwithnocode = $maskwithonlyymcode;
1248
+    $maskwithnocode = preg_replace('/\{yyyy\}/i', 'yyyy', $maskwithnocode);
1249
+    $maskwithnocode = preg_replace('/\{yy\}/i', 'yy', $maskwithnocode);
1250
+    $maskwithnocode = preg_replace('/\{y\}/i', 'y', $maskwithnocode);
1251
+    $maskwithnocode = preg_replace('/\{mm\}/i', 'mm', $maskwithnocode);
1252 1252
     // Now maskwithnocode = 0000ddmmyyyyccc for example
1253 1253
     // and maskcounter    = 0000 for example
1254 1254
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1255 1255
 
1256 1256
     // If an offset is asked
1257
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
1258
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1257
+    if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]);
1258
+    if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]);
1259 1259
 
1260 1260
     // Define $sqlwhere
1261 1261
 
1262 1262
     // If a restore to zero after a month is asked we check if there is already a value for this year.
1263
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))  $maskraz=preg_replace('/^@/','',$reg[2]);
1264
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))  $maskraz=preg_replace('/^@/','',$reg[3]);
1263
+    if (!empty($reg[2]) && preg_match('/^@/', $reg[2]))  $maskraz = preg_replace('/^@/', '', $reg[2]);
1264
+    if (!empty($reg[3]) && preg_match('/^@/', $reg[3]))  $maskraz = preg_replace('/^@/', '', $reg[3]);
1265 1265
     if ($maskraz >= 0)
1266 1266
     {
1267 1267
         if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1268 1268
 
1269 1269
         // Define reg
1270
-        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1271
-        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
1270
+        if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1271
+        if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask';
1272 1272
         //print "x".$maskwithonlyymcode." ".$maskraz;
1273 1273
     }
1274 1274
     //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
@@ -1277,8 +1277,8 @@  discard block
 block discarded – undo
1277 1277
     //
1278 1278
 
1279 1279
     // Check length
1280
-    $len=dol_strlen($maskwithnocode);
1281
-    if (dol_strlen($value) != $len) $result=-1;
1280
+    $len = dol_strlen($maskwithnocode);
1281
+    if (dol_strlen($value) != $len) $result = -1;
1282 1282
 
1283 1283
     // Define $maskLike
1284 1284
     /* seems not used
@@ -1294,7 +1294,7 @@  discard block
 block discarded – undo
1294 1294
     if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",strlen($maskrefclient),"_"),$maskLike);
1295 1295
 	*/
1296 1296
 
1297
-    dol_syslog("functions2::check_value result=".$result,LOG_DEBUG);
1297
+    dol_syslog("functions2::check_value result=".$result, LOG_DEBUG);
1298 1298
     return $result;
1299 1299
 }
1300 1300
 
@@ -1306,13 +1306,13 @@  discard block
 block discarded – undo
1306 1306
  *	@param   boolean	$upper		Convert to tupper
1307 1307
  *	@return  string					x
1308 1308
  */
1309
-function binhex($bin, $pad=false, $upper=false)
1309
+function binhex($bin, $pad = false, $upper = false)
1310 1310
 {
1311
-    $last = dol_strlen($bin)-1;
1312
-    for($i=0; $i<=$last; $i++){ $x += $bin[$last-$i] * pow(2,$i); }
1311
+    $last = dol_strlen($bin) - 1;
1312
+    for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); }
1313 1313
     $x = dechex($x);
1314
-    if($pad){ while(dol_strlen($x) < intval(dol_strlen($bin))/4){ $x = "0$x"; } }
1315
-    if($upper){ $x = strtoupper($x); }
1314
+    if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } }
1315
+    if ($upper) { $x = strtoupper($x); }
1316 1316
     return $x;
1317 1317
 }
1318 1318
 
@@ -1324,11 +1324,11 @@  discard block
 block discarded – undo
1324 1324
  */
1325 1325
 function hexbin($hexa)
1326 1326
 {
1327
-    $bin='';
1327
+    $bin = '';
1328 1328
     $strLength = dol_strlen($hexa);
1329
-    for($i=0;$i<$strLength;$i++)
1329
+    for ($i = 0; $i < $strLength; $i++)
1330 1330
     {
1331
-        $bin.=str_pad(decbin(hexdec($hexa{$i})),4,'0',STR_PAD_LEFT);
1331
+        $bin .= str_pad(decbin(hexdec($hexa{$i})), 4, '0', STR_PAD_LEFT);
1332 1332
     }
1333 1333
     return $bin;
1334 1334
 }
@@ -1341,9 +1341,9 @@  discard block
 block discarded – undo
1341 1341
  */
1342 1342
 function numero_semaine($time)
1343 1343
 {
1344
-    $stime = strftime('%Y-%m-%d',$time);
1344
+    $stime = strftime('%Y-%m-%d', $time);
1345 1345
 
1346
-    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i',$stime,$reg))
1346
+    if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg))
1347 1347
     {
1348 1348
         // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS'
1349 1349
         $annee = $reg[1];
@@ -1359,47 +1359,47 @@  discard block
 block discarded – undo
1359 1359
      */
1360 1360
 
1361 1361
     // Definition du Jeudi de la semaine
1362
-    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
1363
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1364
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
1365
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1366
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
1367
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1362
+    if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche
1363
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60;
1364
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi
1365
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60;
1366
+    else if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi
1367
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60;
1368 1368
     else // Jeudi
1369
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1369
+    $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee);
1370 1370
 
1371 1371
     // Definition du premier Jeudi de l'annee
1372
-    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
1372
+    if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche
1373 1373
     {
1374
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1374
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60;
1375 1375
     }
1376
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
1376
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi
1377 1377
     {
1378
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1378
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60;
1379 1379
     }
1380
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
1380
+    else if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi
1381 1381
     {
1382
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1382
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60;
1383 1383
     }
1384 1384
     else // Jeudi
1385 1385
     {
1386
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
1386
+        $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine));
1387 1387
     }
1388 1388
 
1389 1389
     // Definition du numero de semaine: nb de jours entre "premier Jeudi de l'annee" et "Jeudi de la semaine";
1390
-    $numeroSemaine =     (
1390
+    $numeroSemaine = (
1391 1391
     (
1392
-    date("z",mktime(12,0,0,date("m",$jeudiSemaine),date("d",$jeudiSemaine),date("Y",$jeudiSemaine)))
1392
+    date("z", mktime(12, 0, 0, date("m", $jeudiSemaine), date("d", $jeudiSemaine), date("Y", $jeudiSemaine)))
1393 1393
     -
1394
-    date("z",mktime(12,0,0,date("m",$premierJeudiAnnee),date("d",$premierJeudiAnnee),date("Y",$premierJeudiAnnee)))
1394
+    date("z", mktime(12, 0, 0, date("m", $premierJeudiAnnee), date("d", $premierJeudiAnnee), date("Y", $premierJeudiAnnee)))
1395 1395
     ) / 7
1396 1396
     ) + 1;
1397 1397
 
1398 1398
     // Cas particulier de la semaine 53
1399
-    if ($numeroSemaine==53)
1399
+    if ($numeroSemaine == 53)
1400 1400
     {
1401 1401
         // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53
1402
-        if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365))
1402
+        if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365))
1403 1403
         {
1404 1404
             $numeroSemaine = 53;
1405 1405
         }
@@ -1411,7 +1411,7 @@  discard block
 block discarded – undo
1411 1411
 
1412 1412
     //echo $jour."-".$mois."-".$annee." (".date("d-m-Y",$premierJeudiAnnee)." - ".date("d-m-Y",$jeudiSemaine).") -> ".$numeroSemaine."<BR>";
1413 1413
 
1414
-    return sprintf("%02d",$numeroSemaine);
1414
+    return sprintf("%02d", $numeroSemaine);
1415 1415
 }
1416 1416
 
1417 1417
 /**
@@ -1422,26 +1422,26 @@  discard block
 block discarded – undo
1422 1422
  *	@param  int		$to_unit   		Nouvelle unite  en puissance de 10
1423 1423
  *	@return float	        		Masse convertie
1424 1424
  */
1425
-function weight_convert($weight,&$from_unit,$to_unit)
1425
+function weight_convert($weight, &$from_unit, $to_unit)
1426 1426
 {
1427 1427
     /* Pour convertire 320 gr en Kg appeler
1428 1428
      *  $f = -3
1429 1429
      *  weigh_convert(320, $f, 0) retournera 0.32
1430 1430
      *
1431 1431
      */
1432
-    while ($from_unit  <> $to_unit)
1432
+    while ($from_unit <> $to_unit)
1433 1433
     {
1434 1434
         if ($from_unit > $to_unit)
1435 1435
         {
1436 1436
             $weight = $weight * 10;
1437 1437
             $from_unit = $from_unit - 1;
1438
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1438
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1439 1439
         }
1440 1440
         if ($from_unit < $to_unit)
1441 1441
         {
1442 1442
             $weight = $weight / 10;
1443 1443
             $from_unit = $from_unit + 1;
1444
-            $weight = weight_convert($weight,$from_unit, $to_unit);
1444
+            $weight = weight_convert($weight, $from_unit, $to_unit);
1445 1445
         }
1446 1446
     }
1447 1447
 
@@ -1468,21 +1468,21 @@  discard block
 block discarded – undo
1468 1468
 
1469 1469
     // We remove old parameters for all keys in $tab
1470 1470
     $sql = "DELETE FROM ".MAIN_DB_PREFIX."user_param";
1471
-    $sql.= " WHERE fk_user = ".$user->id;
1472
-    $sql.= " AND entity = ".$conf->entity;
1473
-    $sql.= " AND param in (";
1474
-    $i=0;
1471
+    $sql .= " WHERE fk_user = ".$user->id;
1472
+    $sql .= " AND entity = ".$conf->entity;
1473
+    $sql .= " AND param in (";
1474
+    $i = 0;
1475 1475
     foreach ($tab as $key => $value)
1476 1476
     {
1477
-        if ($i > 0) $sql.=',';
1478
-        $sql.="'".$db->escape($key)."'";
1477
+        if ($i > 0) $sql .= ',';
1478
+        $sql .= "'".$db->escape($key)."'";
1479 1479
         $i++;
1480 1480
     }
1481
-    $sql.= ")";
1481
+    $sql .= ")";
1482 1482
     dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1483 1483
 
1484
-    $resql=$db->query($sql);
1485
-    if (! $resql)
1484
+    $resql = $db->query($sql);
1485
+    if (!$resql)
1486 1486
     {
1487 1487
         dol_print_error($db);
1488 1488
         $db->rollback();
@@ -1495,12 +1495,12 @@  discard block
 block discarded – undo
1495 1495
         if ($value)
1496 1496
         {
1497 1497
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)";
1498
-            $sql.= " VALUES (".$user->id.",".$conf->entity.",";
1499
-            $sql.= " '".$db->escape($key)."','".$db->escape($value)."')";
1498
+            $sql .= " VALUES (".$user->id.",".$conf->entity.",";
1499
+            $sql .= " '".$db->escape($key)."','".$db->escape($value)."')";
1500 1500
 
1501 1501
             dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG);
1502
-            $result=$db->query($sql);
1503
-            if (! $result)
1502
+            $result = $db->query($sql);
1503
+            if (!$result)
1504 1504
             {
1505 1505
                 dol_print_error($db);
1506 1506
                 $db->rollback();
@@ -1526,7 +1526,7 @@  discard block
 block discarded – undo
1526 1526
  *	@param	Translate	$langs			Output language
1527 1527
  *	@return	string						Formated reduction
1528 1528
  */
1529
-function dol_print_reduction($reduction,$langs)
1529
+function dol_print_reduction($reduction, $langs)
1530 1530
 {
1531 1531
     $string = '';
1532 1532
     if ($reduction == 100)
@@ -1535,7 +1535,7 @@  discard block
 block discarded – undo
1535 1535
     }
1536 1536
     else
1537 1537
     {
1538
-    	$string = vatrate($reduction,true);
1538
+    	$string = vatrate($reduction, true);
1539 1539
     }
1540 1540
 
1541 1541
     return $string;
@@ -1549,7 +1549,7 @@  discard block
 block discarded – undo
1549 1549
  */
1550 1550
 function version_os()
1551 1551
 {
1552
-    $osversion=php_uname();
1552
+    $osversion = php_uname();
1553 1553
     return $osversion;
1554 1554
 }
1555 1555
 
@@ -1593,18 +1593,18 @@  discard block
 block discarded – undo
1593 1593
  *  @param  int		    $maxfilenamelength  Max length of value to show
1594 1594
  * 	@return	mixed			    			0 if no module is activated, or array(key=>label). For modules that need directory scan, key is completed with ":filename".
1595 1595
  */
1596
-function getListOfModels($db,$type,$maxfilenamelength=0)
1596
+function getListOfModels($db, $type, $maxfilenamelength = 0)
1597 1597
 {
1598
-    global $conf,$langs;
1599
-    $liste=array();
1600
-    $found=0;
1601
-    $dirtoscan='';
1598
+    global $conf, $langs;
1599
+    $liste = array();
1600
+    $found = 0;
1601
+    $dirtoscan = '';
1602 1602
 
1603 1603
     $sql = "SELECT nom as id, nom as lib, libelle as label, description as description";
1604
-    $sql.= " FROM ".MAIN_DB_PREFIX."document_model";
1605
-    $sql.= " WHERE type = '".$type."'";
1606
-    $sql.= " AND entity IN (0,".$conf->entity.")";
1607
-    $sql.= " ORDER BY description DESC";
1604
+    $sql .= " FROM ".MAIN_DB_PREFIX."document_model";
1605
+    $sql .= " WHERE type = '".$type."'";
1606
+    $sql .= " AND entity IN (0,".$conf->entity.")";
1607
+    $sql .= " ORDER BY description DESC";
1608 1608
 
1609 1609
     dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG);
1610 1610
     $resql = $db->query($sql);
@@ -1614,48 +1614,48 @@  discard block
 block discarded – undo
1614 1614
         $i = 0;
1615 1615
         while ($i < $num)
1616 1616
         {
1617
-            $found=1;
1617
+            $found = 1;
1618 1618
 
1619 1619
             $obj = $db->fetch_object($resql);
1620 1620
 
1621 1621
             // If this generation module needs to scan a directory, then description field is filled
1622 1622
             // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1623
-            if (! empty($obj->description))	// A list of directories to scan is defined
1623
+            if (!empty($obj->description))	// A list of directories to scan is defined
1624 1624
             {
1625 1625
                 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1626 1626
 
1627
-                $const=$obj->description;
1627
+                $const = $obj->description;
1628 1628
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1629
-                $dirtoscan= preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
1629
+                $dirtoscan = preg_replace('/[\r\n]+/', ',', trim($conf->global->$const));
1630 1630
 
1631
-		$listoffiles=array();
1631
+		$listoffiles = array();
1632 1632
 
1633 1633
                 // Now we add models found in directories scanned
1634
-                $listofdir=explode(',',$dirtoscan);
1635
-                foreach($listofdir as $key=>$tmpdir)
1634
+                $listofdir = explode(',', $dirtoscan);
1635
+                foreach ($listofdir as $key=>$tmpdir)
1636 1636
                 {
1637
-                    $tmpdir=trim($tmpdir);
1638
-                    $tmpdir=preg_replace('/DOL_DATA_ROOT/',DOL_DATA_ROOT,$tmpdir);
1639
-                    if (! $tmpdir) { unset($listofdir[$key]); continue; }
1637
+                    $tmpdir = trim($tmpdir);
1638
+                    $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir);
1639
+                    if (!$tmpdir) { unset($listofdir[$key]); continue; }
1640 1640
                     if (is_dir($tmpdir))
1641 1641
                     {
1642 1642
 			// all type of template is allowed
1643
-			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1644
-                        if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1643
+			$tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1644
+                        if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles);
1645 1645
                     }
1646 1646
                 }
1647 1647
 
1648 1648
                 if (count($listoffiles))
1649 1649
                 {
1650
-                    foreach($listoffiles as $record)
1650
+                    foreach ($listoffiles as $record)
1651 1651
                     {
1652
-                        $max=($maxfilenamelength?$maxfilenamelength:28);
1653
-                        $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
1652
+                        $max = ($maxfilenamelength ? $maxfilenamelength : 28);
1653
+                        $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle');
1654 1654
                     }
1655 1655
                 }
1656 1656
                 else
1657 1657
                 {
1658
-                    $liste[0]=$obj->label.': '.$langs->trans("None");
1658
+                    $liste[0] = $obj->label.': '.$langs->trans("None");
1659 1659
                 }
1660 1660
             }
1661 1661
             else
@@ -1664,14 +1664,14 @@  discard block
 block discarded – undo
1664 1664
                 {
1665 1665
                     global $_Avery_Labels;
1666 1666
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1667
-                    foreach($_Avery_Labels as $key => $val)
1667
+                    foreach ($_Avery_Labels as $key => $val)
1668 1668
                     {
1669
-                        $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
1669
+                        $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->lib).' '.$val['name'];
1670 1670
                     }
1671 1671
                 }
1672 1672
                 else    // Common usage
1673 1673
                 {
1674
-                    $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
1674
+                    $liste[$obj->id] = $obj->label ? $obj->label : $obj->lib;
1675 1675
                 }
1676 1676
             }
1677 1677
             $i++;
@@ -1700,10 +1700,10 @@  discard block
 block discarded – undo
1700 1700
 	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1701 1701
 
1702 1702
 		// Then we test if it is a private range
1703
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1703
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
1704 1704
 
1705 1705
 		// Then we test if it is a reserved range
1706
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1706
+		if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
1707 1707
 
1708 1708
 		return 1;
1709 1709
 	}
@@ -1718,12 +1718,12 @@  discard block
 block discarded – undo
1718 1718
  *  @param  string		$firstname		Firstname
1719 1719
  *	@return	string						Login
1720 1720
  */
1721
-function dol_buildlogin($lastname,$firstname)
1721
+function dol_buildlogin($lastname, $firstname)
1722 1722
 {
1723
-    $login=strtolower(dol_string_unaccent($firstname));
1724
-    $login.=($login?'.':'');
1725
-    $login.=strtolower(dol_string_unaccent($lastname));
1726
-    $login=dol_string_nospecial($login,''); // For special names
1723
+    $login = strtolower(dol_string_unaccent($firstname));
1724
+    $login .= ($login ? '.' : '');
1725
+    $login .= strtolower(dol_string_unaccent($lastname));
1726
+    $login = dol_string_nospecial($login, ''); // For special names
1727 1727
     return $login;
1728 1728
 }
1729 1729
 
@@ -1736,18 +1736,18 @@  discard block
 block discarded – undo
1736 1736
 {
1737 1737
     global $conf;
1738 1738
 
1739
-    $params=array();
1740
-    $proxyuse =(empty($conf->global->MAIN_PROXY_USE)?false:true);
1741
-    $proxyhost=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_HOST);
1742
-    $proxyport=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PORT);
1743
-    $proxyuser=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_USER);
1744
-    $proxypass=(empty($conf->global->MAIN_PROXY_USE)?false:$conf->global->MAIN_PROXY_PASS);
1745
-    $timeout  =(empty($conf->global->MAIN_USE_CONNECT_TIMEOUT)?10:$conf->global->MAIN_USE_CONNECT_TIMEOUT);               // Connection timeout
1746
-    $response_timeout=(empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT)?30:$conf->global->MAIN_USE_RESPONSE_TIMEOUT);    // Response timeout
1739
+    $params = array();
1740
+    $proxyuse = (empty($conf->global->MAIN_PROXY_USE) ?false:true);
1741
+    $proxyhost = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_HOST);
1742
+    $proxyport = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PORT);
1743
+    $proxyuser = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_USER);
1744
+    $proxypass = (empty($conf->global->MAIN_PROXY_USE) ?false:$conf->global->MAIN_PROXY_PASS);
1745
+    $timeout  = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout
1746
+    $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout
1747 1747
     //print extension_loaded('soap');
1748 1748
     if ($proxyuse)
1749 1749
     {
1750
-        $params=array('connection_timeout'=>$timeout,
1750
+        $params = array('connection_timeout'=>$timeout,
1751 1751
                       'response_timeout'=>$response_timeout,
1752 1752
                       'proxy_use'      => 1,
1753 1753
                       'proxy_host'     => $proxyhost,
@@ -1759,7 +1759,7 @@  discard block
 block discarded – undo
1759 1759
     }
1760 1760
     else
1761 1761
     {
1762
-        $params=array('connection_timeout'=>$timeout,
1762
+        $params = array('connection_timeout'=>$timeout,
1763 1763
                       'response_timeout'=>$response_timeout,
1764 1764
                       'proxy_use'      => 0,
1765 1765
                       'proxy_host'     => false,
@@ -1782,15 +1782,15 @@  discard block
 block discarded – undo
1782 1782
  * @param 	string	$option			More options
1783 1783
  * @return	string					URL of link to object id/type
1784 1784
  */
1785
-function dolGetElementUrl($objectid,$objecttype,$withpicto=0,$option='')
1785
+function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '')
1786 1786
 {
1787 1787
 	global $db, $conf, $langs;
1788 1788
 
1789
-	$ret='';
1789
+	$ret = '';
1790 1790
 
1791 1791
 	// Parse element/subelement (ex: project_task)
1792 1792
 	$module = $element = $subelement = $objecttype;
1793
-	if (preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
1793
+	if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs))
1794 1794
 	{
1795 1795
 		$module = $element = $regs[1];
1796 1796
 		$subelement = $regs[2];
@@ -1801,18 +1801,18 @@  discard block
 block discarded – undo
1801 1801
 	// To work with non standard path
1802 1802
 	if ($objecttype == 'facture' || $objecttype == 'invoice') {
1803 1803
 		$classpath = 'compta/facture/class';
1804
-		$module='facture';
1805
-		$subelement='facture';
1804
+		$module = 'facture';
1805
+		$subelement = 'facture';
1806 1806
 	}
1807 1807
 	if ($objecttype == 'commande' || $objecttype == 'order') {
1808 1808
 		$classpath = 'commande/class';
1809
-		$module='commande';
1810
-		$subelement='commande';
1809
+		$module = 'commande';
1810
+		$subelement = 'commande';
1811 1811
 	}
1812
-	if ($objecttype == 'propal')  {
1812
+	if ($objecttype == 'propal') {
1813 1813
 		$classpath = 'comm/propal/class';
1814 1814
 	}
1815
-	if ($objecttype == 'supplier_proposal')  {
1815
+	if ($objecttype == 'supplier_proposal') {
1816 1816
 		$classpath = 'supplier_proposal/class';
1817 1817
 	}
1818 1818
 	if ($objecttype == 'shipping') {
@@ -1827,33 +1827,33 @@  discard block
 block discarded – undo
1827 1827
 	}
1828 1828
 	if ($objecttype == 'contract') {
1829 1829
 		$classpath = 'contrat/class';
1830
-		$module='contrat';
1831
-		$subelement='contrat';
1830
+		$module = 'contrat';
1831
+		$subelement = 'contrat';
1832 1832
 	}
1833 1833
 	if ($objecttype == 'member') {
1834 1834
 		$classpath = 'adherents/class';
1835
-		$module='adherent';
1836
-		$subelement='adherent';
1835
+		$module = 'adherent';
1836
+		$subelement = 'adherent';
1837 1837
 	}
1838 1838
 	if ($objecttype == 'cabinetmed_cons') {
1839 1839
 		$classpath = 'cabinetmed/class';
1840
-		$module='cabinetmed';
1841
-		$subelement='cabinetmedcons';
1840
+		$module = 'cabinetmed';
1841
+		$subelement = 'cabinetmedcons';
1842 1842
 	}
1843 1843
 	if ($objecttype == 'fichinter') {
1844 1844
 		$classpath = 'fichinter/class';
1845
-		$module='ficheinter';
1846
-		$subelement='fichinter';
1845
+		$module = 'ficheinter';
1846
+		$subelement = 'fichinter';
1847 1847
 	}
1848 1848
 	if ($objecttype == 'task') {
1849 1849
 		$classpath = 'projet/class';
1850
-		$module='projet';
1851
-		$subelement='task';
1850
+		$module = 'projet';
1851
+		$subelement = 'task';
1852 1852
 	}
1853 1853
 	if ($objecttype == 'stock') {
1854 1854
 		$classpath = 'product/stock/class';
1855
-		$module='stock';
1856
-		$subelement='stock';
1855
+		$module = 'stock';
1856
+		$subelement = 'stock';
1857 1857
 	}
1858 1858
 
1859 1859
 	//print "objecttype=".$objecttype." module=".$module." subelement=".$subelement;
@@ -1861,34 +1861,34 @@  discard block
 block discarded – undo
1861 1861
 	$classfile = strtolower($subelement); $classname = ucfirst($subelement);
1862 1862
 	if ($objecttype == 'invoice_supplier') {
1863 1863
 		$classfile = 'fournisseur.facture';
1864
-		$classname='FactureFournisseur';
1864
+		$classname = 'FactureFournisseur';
1865 1865
 		$classpath = 'fourn/class';
1866
-		$module='fournisseur';
1866
+		$module = 'fournisseur';
1867 1867
 	}
1868
-	elseif ($objecttype == 'order_supplier')   {
1868
+	elseif ($objecttype == 'order_supplier') {
1869 1869
 		$classfile = 'fournisseur.commande';
1870
-		$classname='CommandeFournisseur';
1870
+		$classname = 'CommandeFournisseur';
1871 1871
 		$classpath = 'fourn/class';
1872
-		$module='fournisseur';
1872
+		$module = 'fournisseur';
1873 1873
 	}
1874
-	elseif ($objecttype == 'stock')   {
1874
+	elseif ($objecttype == 'stock') {
1875 1875
 		$classpath = 'product/stock/class';
1876
-		$classfile='entrepot';
1877
-		$classname='Entrepot';
1876
+		$classfile = 'entrepot';
1877
+		$classname = 'Entrepot';
1878 1878
 	}
1879
-	if (! empty($conf->$module->enabled))
1879
+	if (!empty($conf->$module->enabled))
1880 1880
 	{
1881
-		$res=dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1881
+		$res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php');
1882 1882
 		if ($res)
1883 1883
 		{
1884 1884
 			if (class_exists($classname))
1885 1885
 			{
1886 1886
 				$object = new $classname($db);
1887
-				$res=$object->fetch($objectid);
1887
+				$res = $object->fetch($objectid);
1888 1888
 				if ($res > 0) {
1889
-					$ret=$object->getNomUrl($withpicto,$option);
1890
-				} elseif($res==0) {
1891
-					$ret=$langs->trans('Deleted');
1889
+					$ret = $object->getNomUrl($withpicto, $option);
1890
+				} elseif ($res == 0) {
1891
+					$ret = $langs->trans('Deleted');
1892 1892
 				}
1893 1893
 				unset($object);
1894 1894
 			}
@@ -1909,12 +1909,12 @@  discard block
 block discarded – undo
1909 1909
  */
1910 1910
 function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent)
1911 1911
 {
1912
-	$totalnb=0;
1913
-	$listofid=array();
1914
-	$listofparentid=array();
1912
+	$totalnb = 0;
1913
+	$listofid = array();
1914
+	$listofparentid = array();
1915 1915
 
1916 1916
 	// Get list of all id in array listofid and all parents in array listofparentid
1917
-	$sql='SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1917
+	$sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree;
1918 1918
 	$resql = $db->query($sql);
1919 1919
 	if ($resql)
1920 1920
 	{
@@ -1923,8 +1923,8 @@  discard block
 block discarded – undo
1923 1923
 		while ($i < $num)
1924 1924
 		{
1925 1925
 			$obj = $db->fetch_object($resql);
1926
-			$listofid[]=$obj->rowid;
1927
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
1926
+			$listofid[] = $obj->rowid;
1927
+			if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id;
1928 1928
 			$i++;
1929 1929
 		}
1930 1930
 	}
@@ -1938,78 +1938,78 @@  discard block
 block discarded – undo
1938 1938
 		print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."<br>\n";
1939 1939
 
1940 1940
 		// Check loops on each other
1941
-		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid";	// So we update only records linked to themself
1941
+		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself
1942 1942
 		$resql = $db->query($sql);
1943 1943
 		if ($resql)
1944 1944
 		{
1945
-			$nb=$db->affected_rows($sql);
1945
+			$nb = $db->affected_rows($sql);
1946 1946
 			if ($nb > 0)
1947 1947
 			{
1948 1948
 				print '<br>Some record that were parent of themself were cleaned.';
1949 1949
 			}
1950 1950
 
1951
-			$totalnb+=$nb;
1951
+			$totalnb += $nb;
1952 1952
 		}
1953 1953
 		//else dol_print_error($db);
1954 1954
 
1955 1955
 		// Check other loops
1956
-		$listofidtoclean=array();
1957
-		foreach($listofparentid as $id => $pid)
1956
+		$listofidtoclean = array();
1957
+		foreach ($listofparentid as $id => $pid)
1958 1958
 		{
1959 1959
 			// Check depth
1960 1960
 			//print 'Analyse record id='.$id.' with parent '.$pid.'<br>';
1961 1961
 
1962
-			$cursor=$id; $arrayidparsed=array();	// We start from child $id
1962
+			$cursor = $id; $arrayidparsed = array(); // We start from child $id
1963 1963
 			while ($cursor > 0)
1964 1964
 			{
1965
-				$arrayidparsed[$cursor]=1;
1965
+				$arrayidparsed[$cursor] = 1;
1966 1966
 				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
1967 1967
 				{
1968 1968
 					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
1969 1969
 					unset($arrayidparsed);
1970
-					$listofidtoclean[$cursor]=$id;
1970
+					$listofidtoclean[$cursor] = $id;
1971 1971
 					break;
1972 1972
 				}
1973
-				$cursor=$listofparentid[$cursor];
1973
+				$cursor = $listofparentid[$cursor];
1974 1974
 			}
1975 1975
 
1976 1976
 			if (count($listofidtoclean)) break;
1977 1977
 		}
1978 1978
 
1979 1979
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1980
-		$sql.= " SET ".$fieldfkparent." = 0";
1981
-		$sql.= " WHERE rowid IN (".join(',',$listofidtoclean).")";	// So we update only records detected wrong
1980
+		$sql .= " SET ".$fieldfkparent." = 0";
1981
+		$sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong
1982 1982
 		$resql = $db->query($sql);
1983 1983
 		if ($resql)
1984 1984
 		{
1985
-			$nb=$db->affected_rows($sql);
1985
+			$nb = $db->affected_rows($sql);
1986 1986
 			if ($nb > 0)
1987 1987
 			{
1988 1988
 				// Removed orphelins records
1989 1989
 				print '<br>Some records were detected to have parent that is a child, we set them as root record for id: ';
1990
-				print join(',',$listofidtoclean);
1990
+				print join(',', $listofidtoclean);
1991 1991
 			}
1992 1992
 
1993
-			$totalnb+=$nb;
1993
+			$totalnb += $nb;
1994 1994
 		}
1995 1995
 		//else dol_print_error($db);
1996 1996
 
1997 1997
 		// Check and clean orphelins
1998 1998
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
1999
-		$sql.= " SET ".$fieldfkparent." = 0";
2000
-		$sql.= " WHERE ".$fieldfkparent." NOT IN (".join(',',$listofid).")";	// So we update only records linked to a non existing parent
1999
+		$sql .= " SET ".$fieldfkparent." = 0";
2000
+		$sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent
2001 2001
 		$resql = $db->query($sql);
2002 2002
 		if ($resql)
2003 2003
 		{
2004
-			$nb=$db->affected_rows($sql);
2004
+			$nb = $db->affected_rows($sql);
2005 2005
 			if ($nb > 0)
2006 2006
 			{
2007 2007
 				// Removed orphelins records
2008 2008
 				print '<br>Some orphelins were found and modified to be parent so records are visible again for id: ';
2009
-				print join(',',$listofid);
2009
+				print join(',', $listofid);
2010 2010
 			}
2011 2011
 
2012
-			$totalnb+=$nb;
2012
+			$totalnb += $nb;
2013 2013
 		}
2014 2014
 		//else dol_print_error($db);
2015 2015
 
@@ -2030,21 +2030,21 @@  discard block
 block discarded – undo
2030 2030
     $module = $element = $subelement = $element_type;
2031 2031
 
2032 2032
     // If we ask an resource form external module (instead of default path)
2033
-    if (preg_match('/^([^@]+)@([^@]+)$/i',$element_type,$regs))
2033
+    if (preg_match('/^([^@]+)@([^@]+)$/i', $element_type, $regs))
2034 2034
     {
2035 2035
         $element = $subelement = $regs[1];
2036 2036
         $module 	= $regs[2];
2037 2037
     }
2038 2038
 
2039 2039
     //print '<br>1. element : '.$element.' - module : '.$module .'<br>';
2040
-    if ( preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
2040
+    if (preg_match('/^([^_]+)_([^_]+)/i', $element, $regs))
2041 2041
     {
2042 2042
         $module = $element = $regs[1];
2043 2043
         $subelement = $regs[2];
2044 2044
     }
2045 2045
 
2046 2046
     // For compat
2047
-    if($element_type == "action") {
2047
+    if ($element_type == "action") {
2048 2048
         $classpath = 'comm/action/class';
2049 2049
         $subelement = 'Actioncomm';
2050 2050
         $module = 'agenda';
@@ -2053,18 +2053,18 @@  discard block
 block discarded – undo
2053 2053
     // To work with non standard path
2054 2054
     if ($element_type == 'facture' || $element_type == 'invoice') {
2055 2055
         $classpath = 'compta/facture/class';
2056
-        $module='facture';
2057
-        $subelement='facture';
2056
+        $module = 'facture';
2057
+        $subelement = 'facture';
2058 2058
     }
2059 2059
     if ($element_type == 'commande' || $element_type == 'order') {
2060 2060
         $classpath = 'commande/class';
2061
-        $module='commande';
2062
-        $subelement='commande';
2061
+        $module = 'commande';
2062
+        $subelement = 'commande';
2063 2063
     }
2064
-    if ($element_type == 'propal')  {
2064
+    if ($element_type == 'propal') {
2065 2065
         $classpath = 'comm/propal/class';
2066 2066
     }
2067
-    if ($element_type == 'supplier_proposal')  {
2067
+    if ($element_type == 'supplier_proposal') {
2068 2068
         $classpath = 'supplier_proposal/class';
2069 2069
     }
2070 2070
     if ($element_type == 'shipping') {
@@ -2079,45 +2079,45 @@  discard block
 block discarded – undo
2079 2079
     }
2080 2080
     if ($element_type == 'contract') {
2081 2081
         $classpath = 'contrat/class';
2082
-        $module='contrat';
2083
-        $subelement='contrat';
2082
+        $module = 'contrat';
2083
+        $subelement = 'contrat';
2084 2084
     }
2085 2085
     if ($element_type == 'member') {
2086 2086
         $classpath = 'adherents/class';
2087
-        $module='adherent';
2088
-        $subelement='adherent';
2087
+        $module = 'adherent';
2088
+        $subelement = 'adherent';
2089 2089
     }
2090 2090
     if ($element_type == 'cabinetmed_cons') {
2091 2091
         $classpath = 'cabinetmed/class';
2092
-        $module='cabinetmed';
2093
-        $subelement='cabinetmedcons';
2092
+        $module = 'cabinetmed';
2093
+        $subelement = 'cabinetmedcons';
2094 2094
     }
2095 2095
     if ($element_type == 'fichinter') {
2096 2096
         $classpath = 'fichinter/class';
2097
-        $module='ficheinter';
2098
-        $subelement='fichinter';
2097
+        $module = 'ficheinter';
2098
+        $subelement = 'fichinter';
2099 2099
     }
2100 2100
     if ($element_type == 'dolresource' || $element_type == 'resource') {
2101 2101
         $classpath = 'resource/class';
2102
-        $module='resource';
2103
-        $subelement='dolresource';
2102
+        $module = 'resource';
2103
+        $subelement = 'dolresource';
2104 2104
     }
2105 2105
     if ($element_type == 'propaldet') {
2106 2106
         $classpath = 'comm/propal/class';
2107
-        $module='propal';
2108
-        $subelement='propaleligne';
2107
+        $module = 'propal';
2108
+        $subelement = 'propaleligne';
2109 2109
     }
2110
-    if ($element_type == 'order_supplier')  {
2110
+    if ($element_type == 'order_supplier') {
2111 2111
         $classpath = 'fourn/class';
2112
-        $module='fournisseur';
2113
-        $subelement='commandefournisseur';
2114
-        $classfile='fournisseur.commande';
2112
+        $module = 'fournisseur';
2113
+        $subelement = 'commandefournisseur';
2114
+        $classfile = 'fournisseur.commande';
2115 2115
     }
2116
-    if ($element_type == 'invoice_supplier')  {
2116
+    if ($element_type == 'invoice_supplier') {
2117 2117
         $classpath = 'fourn/class';
2118
-        $module='fournisseur';
2119
-        $subelement='facturefournisseur';
2120
-        $classfile='fournisseur.facture';
2118
+        $module = 'fournisseur';
2119
+        $subelement = 'facturefournisseur';
2120
+        $classfile = 'fournisseur.facture';
2121 2121
     }
2122 2122
 
2123 2123
     if (!isset($classfile)) $classfile = strtolower($subelement);
@@ -2144,10 +2144,10 @@  discard block
 block discarded – undo
2144 2144
  * @param	ref     	$element_ref 	Element ref (Use this if element_id but not both)
2145 2145
  * @return 	int|object 					object || 0 || -1 if error
2146 2146
  */
2147
-function fetchObjectByElement($element_id, $element_type, $element_ref='')
2147
+function fetchObjectByElement($element_id, $element_type, $element_ref = '')
2148 2148
 {
2149 2149
     global $conf;
2150
-	global $db,$conf;
2150
+	global $db, $conf;
2151 2151
 
2152 2152
     $element_prop = getElementProperties($element_type);
2153 2153
     if (is_array($element_prop) && $conf->{$element_prop['module']}->enabled)
@@ -2174,11 +2174,11 @@  discard block
 block discarded – undo
2174 2174
  *  @return	string						RGB hex value (without # before). For example: 'FF00FF', '01FF02'
2175 2175
  *  @see	colorStringToArray
2176 2176
  */
2177
-function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2177
+function colorArrayToHex($arraycolor, $colorifnotfound = '888888')
2178 2178
 {
2179
-	if (! is_array($arraycolor)) return $colorifnotfound;
2179
+	if (!is_array($arraycolor)) return $colorifnotfound;
2180 2180
 	if (empty($arraycolor)) return $colorifnotfound;
2181
-	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2181
+	return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2]));
2182 2182
 }
2183 2183
 
2184 2184
 /**
@@ -2193,15 +2193,15 @@  discard block
 block discarded – undo
2193 2193
  */
2194 2194
 static function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2195 2195
     {
2196
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2197
-	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2198
-	if (! $tmp)
2196
+	if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is
2197
+	$tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg);
2198
+	if (!$tmp)
2199 2199
 	{
2200
-		$tmp=explode(',',$stringcolor);
2200
+		$tmp = explode(',', $stringcolor);
2201 2201
 		if (count($tmp) < 3) return $colorifnotfound;
2202 2202
 		return $tmp;
2203 2203
 	}
2204
-	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
2204
+	return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3]));
2205 2205
 }
2206 2206
 
2207 2207
 /**
@@ -2221,8 +2221,8 @@  discard block
 block discarded – undo
2221 2221
     foreach ($input as $key => $values) {
2222 2222
         $append = array();
2223 2223
 
2224
-        foreach($result as $product) {
2225
-            foreach($values as $item) {
2224
+        foreach ($result as $product) {
2225
+            foreach ($values as $item) {
2226 2226
                 $product[$key] = $item;
2227 2227
                 $append[] = $product;
2228 2228
             }
@@ -2243,8 +2243,8 @@  discard block
 block discarded – undo
2243 2243
  */
2244 2244
 function getModuleDirForApiClass($module)
2245 2245
 {
2246
-    $moduledirforclass=$module;
2247
-    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2246
+    $moduledirforclass = $module;
2247
+    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass);
2248 2248
 
2249 2249
     if ($module == 'contracts') {
2250 2250
     	$moduledirforclass = 'contrat';
@@ -2320,9 +2320,9 @@  discard block
 block discarded – undo
2320 2320
  * @param	$max	int	Between 0 and 255
2321 2321
  * @return String
2322 2322
  */
2323
-function random_color_part($min=0,$max=255)
2323
+function random_color_part($min = 0, $max = 255)
2324 2324
 {
2325
-    return str_pad( dechex( mt_rand( $min, $max) ), 2, '0', STR_PAD_LEFT);
2325
+    return str_pad(dechex(mt_rand($min, $max)), 2, '0', STR_PAD_LEFT);
2326 2326
 }
2327 2327
 
2328 2328
 /*
@@ -2332,8 +2332,8 @@  discard block
 block discarded – undo
2332 2332
  * @param	$max	int	Between 0 and 255
2333 2333
  * @return String
2334 2334
  */
2335
-function random_color($min=0, $max=255)
2335
+function random_color($min = 0, $max = 255)
2336 2336
 {
2337
-    return random_color_part($min, $max) . random_color_part($min, $max) . random_color_part($min, $max);
2337
+    return random_color_part($min, $max).random_color_part($min, $max).random_color_part($min, $max);
2338 2338
 }
2339 2339
 }
Please login to merge, or discard this patch.
Braces   +726 added lines, -379 removed lines patch added patch discarded remove patch
@@ -59,8 +59,7 @@  discard block
 block discarded – undo
59 59
                 $entity = "&#". $unicode . ';';
60 60
                 $decodedStr .= utf8_encode($entity);
61 61
                 $pos += 4;
62
-            }
63
-            else {
62
+            } else {
64 63
                 // we have an escaped ascii character
65 64
                 $hexVal = substr($source, $pos, 2);
66 65
                 $decodedStr .= chr(hexdec($hexVal));
@@ -101,7 +100,10 @@  discard block
 block discarded – undo
101 100
         {
102 101
             while (($file = readdir($handle))!==false)
103 102
             {
104
-                if (preg_match('/disabled/',$file)) continue;   // We discard module if it contains disabled into name.
103
+                if (preg_match('/disabled/',$file)) {
104
+                    continue;
105
+                }
106
+                // We discard module if it contains disabled into name.
105 107
 
106 108
                 if (is_dir($dirroot.'/'.$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && $file != 'includes')
107 109
                 {
@@ -133,8 +135,14 @@  discard block
 block discarded – undo
133 135
     	$outputlangs=$langs;
134 136
     }
135 137
 
136
-    if ($outputlangs->defaultlang == 'ca_CA') $selected='CAP4';        // Canada
137
-    if ($outputlangs->defaultlang == 'en_US') $selected='USLetter';    // US
138
+    if ($outputlangs->defaultlang == 'ca_CA') {
139
+        $selected='CAP4';
140
+    }
141
+    // Canada
142
+    if ($outputlangs->defaultlang == 'en_US') {
143
+        $selected='USLetter';
144
+    }
145
+    // US
138 146
     return $selected;
139 147
 }
140 148
 
@@ -159,29 +167,42 @@  discard block
 block discarded – undo
159 167
         {
160 168
             $content=file_get_contents($formfile);
161 169
             $isutf8=utf8_check($content);
162
-            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
163
-            elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
164
-            else print $content;
170
+            if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') {
171
+                print utf8_encode($content);
172
+            } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
173
+                print utf8_decode($content);
174
+            } else {
175
+                print $content;
176
+            }
165 177
             return true;
166
-        }
167
-        else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
178
+        } else {
179
+            dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
180
+        }
168 181
 
169 182
         if ($searchalt) {
170 183
             // Test si fichier dans repertoire de la langue alternative
171
-            if ($langs->defaultlang != "en_US") $formfilealt = $searchdir."/langs/en_US/".$filename;
172
-            else $formfilealt = $searchdir."/langs/fr_FR/".$filename;
184
+            if ($langs->defaultlang != "en_US") {
185
+                $formfilealt = $searchdir."/langs/en_US/".$filename;
186
+            } else {
187
+                $formfilealt = $searchdir."/langs/fr_FR/".$filename;
188
+            }
173 189
             dol_syslog('functions2::dol_print_file search alt file '.$formfilealt, LOG_DEBUG);
174 190
             //print 'getcwd='.getcwd().' htmlfilealt='.$formfilealt.' X '.file_exists(getcwd().'/'.$formfilealt);
175 191
             if (is_readable($formfilealt))
176 192
             {
177 193
                 $content=file_get_contents($formfilealt);
178 194
                 $isutf8=utf8_check($content);
179
-                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') print utf8_encode($content);
180
-                elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') print utf8_decode($content);
181
-                else print $content;
195
+                if (! $isutf8 && $conf->file->character_set_client == 'UTF-8') {
196
+                    print utf8_encode($content);
197
+                } elseif ($isutf8 && $conf->file->character_set_client == 'ISO-8859-1') {
198
+                    print utf8_decode($content);
199
+                } else {
200
+                    print $content;
201
+                }
182 202
                 return true;
183
-            }
184
-            else dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
203
+            } else {
204
+                dol_syslog('functions2::dol_print_file not found', LOG_DEBUG);
205
+            }
185 206
         }
186 207
     }
187 208
 
@@ -211,279 +232,460 @@  discard block
 block discarded – undo
211 232
     $deltadateforuser=round($deltadateforclient-$deltadateforserver);
212 233
     //print "x".$deltadateforserver." - ".$deltadateforclient." - ".$deltadateforuser;
213 234
 
214
-    if ($usetable) print '<table class="border centpercent">';
235
+    if ($usetable) {
236
+        print '<table class="border centpercent">';
237
+    }
215 238
 
216 239
     // Import key
217 240
     if (! empty($object->import_key))
218 241
     {
219
-        if ($usetable) print '<tr><td class="titlefield">';
242
+        if ($usetable) {
243
+            print '<tr><td class="titlefield">';
244
+        }
220 245
         print $langs->trans("ImportedWithSet");
221
-        if ($usetable) print '</td><td>';
222
-        else print ': ';
246
+        if ($usetable) {
247
+            print '</td><td>';
248
+        } else {
249
+            print ': ';
250
+        }
223 251
         print $object->import_key;
224
-        if ($usetable) print '</td></tr>';
225
-        else print '<br>';
252
+        if ($usetable) {
253
+            print '</td></tr>';
254
+        } else {
255
+            print '<br>';
256
+        }
226 257
     }
227 258
 
228 259
     // User creation (old method using already loaded object and not id is kept for backward compatibility)
229 260
     if (! empty($object->user_creation) || ! empty($object->user_creation_id))
230 261
     {
231
-        if ($usetable) print '<tr><td class="titlefield">';
262
+        if ($usetable) {
263
+            print '<tr><td class="titlefield">';
264
+        }
232 265
         print $langs->trans("CreatedBy");
233
-        if ($usetable) print '</td><td>';
234
-        else print ': ';
266
+        if ($usetable) {
267
+            print '</td><td>';
268
+        } else {
269
+            print ': ';
270
+        }
235 271
         if (is_object($object->user_creation))
236 272
         {
237
-        	if ($object->user_creation->id) print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
238
-        	else print $langs->trans("Unknown");
239
-        }
240
-        else
273
+        	if ($object->user_creation->id) {
274
+        	    print $object->user_creation->getNomUrl(1, '', 0, 0, 0);
275
+        	} else {
276
+        	    print $langs->trans("Unknown");
277
+        	}
278
+        } else
241 279
         {
242 280
             $userstatic=new User($db);
243 281
             $userstatic->fetch($object->user_creation_id ? $object->user_creation_id : $object->user_creation);
244
-            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
245
-        	else print $langs->trans("Unknown");
282
+            if ($userstatic->id) {
283
+                print $userstatic->getNomUrl(1, '', 0, 0, 0);
284
+            } else {
285
+        	    print $langs->trans("Unknown");
286
+        	}
246 287
         }
247
-        if ($usetable) print '</td></tr>';
248
-        else print '<br>';
288
+        if ($usetable) {
289
+            print '</td></tr>';
290
+        } else {
291
+            print '<br>';
292
+        }
249 293
     }
250 294
 
251 295
     // Date creation
252 296
     if (! empty($object->date_creation))
253 297
     {
254
-        if ($usetable) print '<tr><td class="titlefield">';
298
+        if ($usetable) {
299
+            print '<tr><td class="titlefield">';
300
+        }
255 301
         print $langs->trans("DateCreation");
256
-        if ($usetable) print '</td><td>';
257
-        else print ': ';
302
+        if ($usetable) {
303
+            print '</td><td>';
304
+        } else {
305
+            print ': ';
306
+        }
258 307
         print dol_print_date($object->date_creation, 'dayhour');
259
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
260
-        if ($usetable) print '</td></tr>';
261
-        else print '<br>';
308
+        if ($deltadateforuser) {
309
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_creation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
310
+        }
311
+        if ($usetable) {
312
+            print '</td></tr>';
313
+        } else {
314
+            print '<br>';
315
+        }
262 316
     }
263 317
 
264 318
     // User change (old method using already loaded object and not id is kept for backward compatibility)
265 319
     if (! empty($object->user_modification) || ! empty($object->user_modification_id))
266 320
     {
267
-        if ($usetable) print '<tr><td class="titlefield">';
321
+        if ($usetable) {
322
+            print '<tr><td class="titlefield">';
323
+        }
268 324
         print $langs->trans("ModifiedBy");
269
-        if ($usetable) print '</td><td>';
270
-        else print ': ';
325
+        if ($usetable) {
326
+            print '</td><td>';
327
+        } else {
328
+            print ': ';
329
+        }
271 330
         if (is_object($object->user_modification))
272 331
         {
273
-        	if ($object->user_modification->id) print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
274
-        	else print $langs->trans("Unknown");
275
-        }
276
-        else
332
+        	if ($object->user_modification->id) {
333
+        	    print $object->user_modification->getNomUrl(1, '', 0, 0, 0);
334
+        	} else {
335
+        	    print $langs->trans("Unknown");
336
+        	}
337
+        } else
277 338
         {
278 339
             $userstatic=new User($db);
279 340
             $userstatic->fetch($object->user_modification_id ? $object->user_modification_id : $object->user_modification);
280
-            if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
281
-        	else print $langs->trans("Unknown");
341
+            if ($userstatic->id) {
342
+                print $userstatic->getNomUrl(1, '', 0, 0, 0);
343
+            } else {
344
+        	    print $langs->trans("Unknown");
345
+        	}
282 346
         }
283
-        if ($usetable) print '</td></tr>';
284
-        else print '<br>';
347
+        if ($usetable) {
348
+            print '</td></tr>';
349
+        } else {
350
+            print '<br>';
351
+        }
285 352
     }
286 353
 
287 354
     // Date change
288 355
     if (! empty($object->date_modification))
289 356
     {
290
-        if ($usetable) print '<tr><td class="titlefield">';
357
+        if ($usetable) {
358
+            print '<tr><td class="titlefield">';
359
+        }
291 360
         print $langs->trans("DateLastModification");
292
-        if ($usetable) print '</td><td>';
293
-        else print ': ';
361
+        if ($usetable) {
362
+            print '</td><td>';
363
+        } else {
364
+            print ': ';
365
+        }
294 366
         print dol_print_date($object->date_modification, 'dayhour');
295
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
296
-        if ($usetable) print '</td></tr>';
297
-        else print '<br>';
367
+        if ($deltadateforuser) {
368
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_modification+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
369
+        }
370
+        if ($usetable) {
371
+            print '</td></tr>';
372
+        } else {
373
+            print '<br>';
374
+        }
298 375
     }
299 376
 
300 377
     // User validation (old method using already loaded object and not id is kept for backward compatibility)
301 378
     if (! empty($object->user_validation) || ! empty($object->user_validation_id))
302 379
     {
303
-        if ($usetable) print '<tr><td class="titlefield">';
380
+        if ($usetable) {
381
+            print '<tr><td class="titlefield">';
382
+        }
304 383
         print $langs->trans("ValidatedBy");
305
-        if ($usetable) print '</td><td>';
306
-        else print ': ';
384
+        if ($usetable) {
385
+            print '</td><td>';
386
+        } else {
387
+            print ': ';
388
+        }
307 389
         if (is_object($object->user_validation))
308 390
         {
309
-            if ($object->user_validation->id) print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
310
-        	else print $langs->trans("Unknown");
311
-        }
312
-        else
391
+            if ($object->user_validation->id) {
392
+                print $object->user_validation->getNomUrl(1, '', 0, 0, 0);
393
+            } else {
394
+        	    print $langs->trans("Unknown");
395
+        	}
396
+        } else
313 397
         {
314 398
             $userstatic=new User($db);
315 399
             $userstatic->fetch($object->user_validation_id ? $object->user_validation_id : $object->user_validation);
316
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
317
-        	else print $langs->trans("Unknown");
400
+			if ($userstatic->id) {
401
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
402
+			} else {
403
+        	    print $langs->trans("Unknown");
404
+        	}
318 405
         }
319
-        if ($usetable) print '</td></tr>';
320
-        else print '<br>';
406
+        if ($usetable) {
407
+            print '</td></tr>';
408
+        } else {
409
+            print '<br>';
410
+        }
321 411
     }
322 412
 
323 413
     // Date validation
324 414
     if (! empty($object->date_validation))
325 415
     {
326
-        if ($usetable) print '<tr><td class="titlefield">';
416
+        if ($usetable) {
417
+            print '<tr><td class="titlefield">';
418
+        }
327 419
         print $langs->trans("DateValidation");
328
-        if ($usetable) print '</td><td>';
329
-        else print ': ';
420
+        if ($usetable) {
421
+            print '</td><td>';
422
+        } else {
423
+            print ': ';
424
+        }
330 425
         print dol_print_date($object->date_validation, 'dayhour');
331
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
332
-        if ($usetable) print '</td></tr>';
333
-        else print '<br>';
426
+        if ($deltadateforuser) {
427
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_validation+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
428
+        }
429
+        if ($usetable) {
430
+            print '</td></tr>';
431
+        } else {
432
+            print '<br>';
433
+        }
334 434
     }
335 435
 
336 436
     // User approve (old method using already loaded object and not id is kept for backward compatibility)
337 437
     if (! empty($object->user_approve) || ! empty($object->user_approve_id))
338 438
     {
339
-        if ($usetable) print '<tr><td class="titlefield">';
439
+        if ($usetable) {
440
+            print '<tr><td class="titlefield">';
441
+        }
340 442
         print $langs->trans("ApprovedBy");
341
-        if ($usetable) print '</td><td>';
342
-        else print ': ';
443
+        if ($usetable) {
444
+            print '</td><td>';
445
+        } else {
446
+            print ': ';
447
+        }
343 448
         if (is_object($object->user_approve))
344 449
         {
345
-            if ($object->user_approve->id) print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
346
-        	else print $langs->trans("Unknown");
347
-        }
348
-        else
450
+            if ($object->user_approve->id) {
451
+                print $object->user_approve->getNomUrl(1, '', 0, 0, 0);
452
+            } else {
453
+        	    print $langs->trans("Unknown");
454
+        	}
455
+        } else
349 456
         {
350 457
             $userstatic=new User($db);
351 458
             $userstatic->fetch($object->user_approve_id ? $object->user_approve_id : $object->user_approve);
352
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
353
-        	else print $langs->trans("Unknown");
459
+			if ($userstatic->id) {
460
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
461
+			} else {
462
+        	    print $langs->trans("Unknown");
463
+        	}
354 464
         }
355
-        if ($usetable) print '</td></tr>';
356
-        else print '<br>';
465
+        if ($usetable) {
466
+            print '</td></tr>';
467
+        } else {
468
+            print '<br>';
469
+        }
357 470
     }
358 471
 
359 472
     // Date approve
360 473
     if (! empty($object->date_approve))
361 474
     {
362
-        if ($usetable) print '<tr><td class="titlefield">';
475
+        if ($usetable) {
476
+            print '<tr><td class="titlefield">';
477
+        }
363 478
         print $langs->trans("DateApprove");
364
-        if ($usetable) print '</td><td>';
365
-        else print ': ';
479
+        if ($usetable) {
480
+            print '</td><td>';
481
+        } else {
482
+            print ': ';
483
+        }
366 484
         print dol_print_date($object->date_approve, 'dayhour');
367
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
368
-        if ($usetable) print '</td></tr>';
369
-        else print '<br>';
485
+        if ($deltadateforuser) {
486
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
487
+        }
488
+        if ($usetable) {
489
+            print '</td></tr>';
490
+        } else {
491
+            print '<br>';
492
+        }
370 493
     }
371 494
 
372 495
     // User approve
373 496
     if (! empty($object->user_approve_id2))
374 497
     {
375
-        if ($usetable) print '<tr><td class="titlefield">';
498
+        if ($usetable) {
499
+            print '<tr><td class="titlefield">';
500
+        }
376 501
         print $langs->trans("ApprovedBy");
377
-        if ($usetable) print '</td><td>';
378
-        else print ': ';
502
+        if ($usetable) {
503
+            print '</td><td>';
504
+        } else {
505
+            print ': ';
506
+        }
379 507
         $userstatic=new User($db);
380 508
         $userstatic->fetch($object->user_approve_id2);
381
-        if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
382
-        else print $langs->trans("Unknown");
383
-        if ($usetable) print '</td></tr>';
384
-        else print '<br>';
509
+        if ($userstatic->id) {
510
+            print $userstatic->getNomUrl(1, '', 0, 0, 0);
511
+        } else {
512
+            print $langs->trans("Unknown");
513
+        }
514
+        if ($usetable) {
515
+            print '</td></tr>';
516
+        } else {
517
+            print '<br>';
518
+        }
385 519
     }
386 520
 
387 521
     // Date approve
388 522
     if (! empty($object->date_approve2))
389 523
     {
390
-        if ($usetable) print '<tr><td class="titlefield">';
524
+        if ($usetable) {
525
+            print '<tr><td class="titlefield">';
526
+        }
391 527
         print $langs->trans("DateApprove2");
392
-        if ($usetable) print '</td><td>';
393
-        else print ': ';
528
+        if ($usetable) {
529
+            print '</td><td>';
530
+        } else {
531
+            print ': ';
532
+        }
394 533
         print dol_print_date($object->date_approve2, 'dayhour');
395
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
396
-        if ($usetable) print '</td></tr>';
397
-        else print '<br>';
534
+        if ($deltadateforuser) {
535
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_approve2+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
536
+        }
537
+        if ($usetable) {
538
+            print '</td></tr>';
539
+        } else {
540
+            print '<br>';
541
+        }
398 542
     }
399 543
 
400 544
     // User close
401 545
     if (! empty($object->user_cloture))
402 546
     {
403
-        if ($usetable) print '<tr><td class="titlefield">';
547
+        if ($usetable) {
548
+            print '<tr><td class="titlefield">';
549
+        }
404 550
         print $langs->trans("ClosedBy");
405
-        if ($usetable) print '</td><td>';
406
-        else print ': ';
551
+        if ($usetable) {
552
+            print '</td><td>';
553
+        } else {
554
+            print ': ';
555
+        }
407 556
         if (is_object($object->user_cloture))
408 557
         {
409
-			if ($object->user_cloture->id) print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
410
-        	else print $langs->trans("Unknown");
411
-        }
412
-        else
558
+			if ($object->user_cloture->id) {
559
+			    print $object->user_cloture->getNomUrl(1, '', 0, 0, 0);
560
+			} else {
561
+        	    print $langs->trans("Unknown");
562
+        	}
563
+        } else
413 564
         {
414 565
             $userstatic=new User($db);
415 566
             $userstatic->fetch($object->user_cloture);
416
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
417
-        	else print $langs->trans("Unknown");
567
+			if ($userstatic->id) {
568
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
569
+			} else {
570
+        	    print $langs->trans("Unknown");
571
+        	}
418 572
         }
419
-        if ($usetable) print '</td></tr>';
420
-        else print '<br>';
573
+        if ($usetable) {
574
+            print '</td></tr>';
575
+        } else {
576
+            print '<br>';
577
+        }
421 578
     }
422 579
 
423 580
     // Date close
424 581
     if (! empty($object->date_cloture))
425 582
     {
426
-        if ($usetable) print '<tr><td class="titlefield">';
583
+        if ($usetable) {
584
+            print '<tr><td class="titlefield">';
585
+        }
427 586
         print $langs->trans("DateClosing");
428
-        if ($usetable) print '</td><td>';
429
-        else print ': ';
587
+        if ($usetable) {
588
+            print '</td><td>';
589
+        } else {
590
+            print ': ';
591
+        }
430 592
         print dol_print_date($object->date_cloture, 'dayhour');
431
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
432
-        if ($usetable) print '</td></tr>';
433
-        else print '<br>';
593
+        if ($deltadateforuser) {
594
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_cloture+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
595
+        }
596
+        if ($usetable) {
597
+            print '</td></tr>';
598
+        } else {
599
+            print '<br>';
600
+        }
434 601
     }
435 602
 
436 603
     // User conciliate
437 604
     if (! empty($object->user_rappro))
438 605
     {
439
-        if ($usetable) print '<tr><td class="titlefield">';
606
+        if ($usetable) {
607
+            print '<tr><td class="titlefield">';
608
+        }
440 609
         print $langs->trans("ConciliatedBy");
441
-        if ($usetable) print '</td><td>';
442
-        else print ': ';
610
+        if ($usetable) {
611
+            print '</td><td>';
612
+        } else {
613
+            print ': ';
614
+        }
443 615
         if (is_object($object->user_rappro))
444 616
         {
445
-			if ($object->user_rappro->id) print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
446
-        	else print $langs->trans("Unknown");
447
-        }
448
-        else
617
+			if ($object->user_rappro->id) {
618
+			    print $object->user_rappro->getNomUrl(1, '', 0, 0, 0);
619
+			} else {
620
+        	    print $langs->trans("Unknown");
621
+        	}
622
+        } else
449 623
         {
450 624
             $userstatic=new User($db);
451 625
             $userstatic->fetch($object->user_rappro);
452
-			if ($userstatic->id) print $userstatic->getNomUrl(1, '', 0, 0, 0);
453
-        	else print $langs->trans("Unknown");
626
+			if ($userstatic->id) {
627
+			    print $userstatic->getNomUrl(1, '', 0, 0, 0);
628
+			} else {
629
+        	    print $langs->trans("Unknown");
630
+        	}
454 631
         }
455
-        if ($usetable) print '</td></tr>';
456
-        else print '<br>';
632
+        if ($usetable) {
633
+            print '</td></tr>';
634
+        } else {
635
+            print '<br>';
636
+        }
457 637
     }
458 638
 
459 639
     // Date conciliate
460 640
     if (! empty($object->date_rappro))
461 641
     {
462
-        if ($usetable) print '<tr><td class="titlefield">';
642
+        if ($usetable) {
643
+            print '<tr><td class="titlefield">';
644
+        }
463 645
         print $langs->trans("DateConciliating");
464
-        if ($usetable) print '</td><td>';
465
-        else print ': ';
646
+        if ($usetable) {
647
+            print '</td><td>';
648
+        } else {
649
+            print ': ';
650
+        }
466 651
         print dol_print_date($object->date_rappro, 'dayhour');
467
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
468
-        if ($usetable) print '</td></tr>';
469
-        else print '<br>';
652
+        if ($deltadateforuser) {
653
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_rappro+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
654
+        }
655
+        if ($usetable) {
656
+            print '</td></tr>';
657
+        } else {
658
+            print '<br>';
659
+        }
470 660
     }
471 661
 
472 662
     // Date send
473 663
     if (! empty($object->date_envoi))
474 664
     {
475
-        if ($usetable) print '<tr><td class="titlefield">';
665
+        if ($usetable) {
666
+            print '<tr><td class="titlefield">';
667
+        }
476 668
         print $langs->trans("DateLastSend");
477
-        if ($usetable) print '</td><td>';
478
-        else print ': ';
669
+        if ($usetable) {
670
+            print '</td><td>';
671
+        } else {
672
+            print ': ';
673
+        }
479 674
         print dol_print_date($object->date_envoi, 'dayhour');
480
-        if ($deltadateforuser) print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
481
-        if ($usetable) print '</td></tr>';
482
-        else print '<br>';
675
+        if ($deltadateforuser) {
676
+            print ' '.$langs->trans("CurrentHour").' &nbsp; / &nbsp; '.dol_print_date($object->date_envoi+($deltadateforuser*3600),"dayhour").' &nbsp;'.$langs->trans("ClientHour");
677
+        }
678
+        if ($usetable) {
679
+            print '</td></tr>';
680
+        } else {
681
+            print '<br>';
682
+        }
483 683
     }
484 684
 
485
-    if ($usetable) print '</table>';
486
-}
685
+    if ($usetable) {
686
+        print '</table>';
687
+    }
688
+    }
487 689
 
488 690
 
489 691
 /**
@@ -512,8 +714,7 @@  discard block
 block discarded – undo
512 714
     if (checkdnsrr($domain, "MX"))
513 715
     {
514 716
         return true;
515
-    }
516
-    else
717
+    } else
517 718
     {
518 719
         return false;
519 720
     }
@@ -538,10 +739,14 @@  discard block
 block discarded – undo
538 739
     $urlregex = '';
539 740
 
540 741
     // SCHEME
541
-    if ($http) $urlregex .= "^(http:\/\/|https:\/\/)";
742
+    if ($http) {
743
+        $urlregex .= "^(http:\/\/|https:\/\/)";
744
+    }
542 745
 
543 746
     // USER AND PASS
544
-    if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
747
+    if ($pass) {
748
+        $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)";
749
+    }
545 750
 
546 751
     // HOSTNAME OR IP
547 752
     //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*";  // x allowed (ex. http://localhost, http://routerlogin)
@@ -550,13 +755,21 @@  discard block
 block discarded – undo
550 755
     //use only one of the above
551 756
 
552 757
     // PORT
553
-    if ($port) $urlregex .= "(\:[0-9]{2,5})";
758
+    if ($port) {
759
+        $urlregex .= "(\:[0-9]{2,5})";
760
+    }
554 761
     // PATH
555
-    if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
762
+    if ($path) {
763
+        $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/";
764
+    }
556 765
     // GET Query
557
-    if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
766
+    if ($query) {
767
+        $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)";
768
+    }
558 769
     // ANCHOR
559
-    if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
770
+    if ($anchor) {
771
+        $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$";
772
+    }
560 773
 
561 774
     // check
562 775
     if (preg_match('/'.$urlregex.'/i', $url))
@@ -604,9 +817,10 @@  discard block
 block discarded – undo
604 817
         $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain,'/').'/i', $newproto.strtolower($domain), $url);
605 818
 
606 819
         return $CleanUrl;
820
+    } else {
821
+        return $url;
822
+    }
607 823
     }
608
-    else return $url;
609
-}
610 824
 
611 825
 
612 826
 
@@ -623,7 +837,9 @@  discard block
 block discarded – undo
623 837
  */
624 838
 function dolObfuscateEmail($mail, $replace="*", $nbreplace=8, $nbdisplaymail=4, $nbdisplaydomain=3, $displaytld=true)
625 839
 {
626
-	if(!isValidEmail($mail))return '';
840
+	if(!isValidEmail($mail)) {
841
+	    return '';
842
+	}
627 843
 	$tab = explode('@', $mail);
628 844
 	$tab2 = explode('.',$tab[1]);
629 845
 	$string_replace = '';
@@ -685,7 +901,9 @@  discard block
 block discarded – undo
685 901
 function array2table($data,$tableMarkup=1,$tableoptions='',$troptions='',$tdoptions='')
686 902
 {
687 903
     $text='' ;
688
-    if($tableMarkup) $text = '<table '.$tableoptions.'>' ;
904
+    if($tableMarkup) {
905
+        $text = '<table '.$tableoptions.'>' ;
906
+    }
689 907
     foreach($data as $key => $item){
690 908
         if(is_array($item)){
691 909
             $text.=array2tr($item,$troptions,$tdoptions);
@@ -696,7 +914,9 @@  discard block
 block discarded – undo
696 914
             $text.= '</tr>' ;
697 915
         }
698 916
     }
699
-    if($tableMarkup) $text.= '</table>' ;
917
+    if($tableMarkup) {
918
+        $text.= '</table>' ;
919
+    }
700 920
     return $text ;
701 921
 }
702 922
 
@@ -720,15 +940,25 @@  discard block
 block discarded – undo
720 940
 {
721 941
     global $conf,$user;
722 942
 
723
-    if (! is_object($objsoc)) $valueforccc=$objsoc;
724
-    else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) $valueforccc=$objsoc->code_fournisseur;
725
-    else $valueforccc=$objsoc->code_client;
943
+    if (! is_object($objsoc)) {
944
+        $valueforccc=$objsoc;
945
+    } else if ($table == "commande_fournisseur" || $table == "facture_fourn" ) {
946
+        $valueforccc=$objsoc->code_fournisseur;
947
+    } else {
948
+        $valueforccc=$objsoc->code_client;
949
+    }
726 950
 
727 951
     $sharetable = $table;
728
-    if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function
952
+    if ($table == 'facture' || $table == 'invoice') {
953
+        $sharetable = 'invoicenumber';
954
+    }
955
+    // for getEntity function
729 956
 
730 957
     // Clean parameters
731
-    if ($date == '') $date=dol_now();	// We use local year and month of PHP server to search numbers
958
+    if ($date == '') {
959
+        $date=dol_now();
960
+    }
961
+    // We use local year and month of PHP server to search numbers
732 962
     // but we should use local year and month of user
733 963
 
734 964
     // For debugging
@@ -745,8 +975,7 @@  discard block
 block discarded – undo
745 975
         $masktri=$reg[1].(! empty($reg[2])?$reg[2]:'').(! empty($reg[3])?$reg[3]:'');
746 976
         $maskcounter=$reg[1];
747 977
         $hasglobalcounter=true;
748
-    }
749
-    else
978
+    } else
750 979
     {
751 980
         // setting some defaults so the rest of the code won't fail if there is a third party counter
752 981
         $masktri='00000';
@@ -756,7 +985,9 @@  discard block
 block discarded – undo
756 985
     $maskraz=-1;
757 986
     $maskoffset=0;
758 987
     $resetEveryMonth=false;
759
-    if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits';
988
+    if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) {
989
+        return 'ErrorCounterMustHaveMoreThan3Digits';
990
+    }
760 991
 
761 992
     // Extract value for third party mask counter
762 993
     if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
@@ -768,9 +999,12 @@  discard block
 block discarded – undo
768 999
         $maskrefclient_clientcode=substr($valueforccc,0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code where n is length in mask
769 1000
         $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
770 1001
         $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
771
-        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
772
-    }
773
-    else $maskrefclient='';
1002
+        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
1003
+            return 'ErrorCounterMustHaveMoreThan3Digits';
1004
+        }
1005
+    } else {
1006
+        $maskrefclient='';
1007
+    }
774 1008
 
775 1009
     // fail if there is neither a global nor a third party counter
776 1010
     if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
@@ -784,8 +1018,7 @@  discard block
 block discarded – undo
784 1018
         $masktype=$regType[1];
785 1019
         $masktype_value=substr(preg_replace('/^TE_/','',$objsoc->typent_code),0,dol_strlen($regType[1]));// get n first characters of thirdpaty typent_code (where n is length in mask)
786 1020
         $masktype_value=str_pad($masktype_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
787
-    }
788
-    else
1021
+    } else
789 1022
     {
790 1023
     	$masktype='';
791 1024
     	$masktype_value='';
@@ -795,13 +1028,14 @@  discard block
 block discarded – undo
795 1028
     if (preg_match('/\{(u+)\}/i',$mask,$regType))
796 1029
     {
797 1030
     	$lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
798
-    	if (is_object($objuser)) $lastname = $objuser->lastname;
1031
+    	if (is_object($objuser)) {
1032
+    	    $lastname = $objuser->lastname;
1033
+    	}
799 1034
 
800 1035
     	$maskuser=$regType[1];
801 1036
     	$maskuser_value=substr($lastname,0,dol_strlen($regType[1]));// get n first characters of user firstname (where n is length in mask)
802 1037
     	$maskuser_value=str_pad($maskuser_value,dol_strlen($regType[1]),"#",STR_PAD_RIGHT);				 // we fill on right with # to have same number of char than into mask
803
-    }
804
-    else
1038
+    } else
805 1039
     {
806 1040
     	$maskuser='';
807 1041
     	$maskuser_value='';
@@ -848,8 +1082,12 @@  discard block
 block discarded – undo
848 1082
     //var_dump($reg);
849 1083
 
850 1084
     // If an offset is asked
851
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
852
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1085
+    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) {
1086
+        $maskoffset=preg_replace('/^\+/','',$reg[2]);
1087
+    }
1088
+    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) {
1089
+        $maskoffset=preg_replace('/^\+/','',$reg[3]);
1090
+    }
853 1091
 
854 1092
     // Define $sqlwhere
855 1093
     $sqlwhere='';
@@ -857,14 +1095,21 @@  discard block
 block discarded – undo
857 1095
     $yearoffsettype=false;		// false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x
858 1096
 
859 1097
     // If a restore to zero after a month is asked we check if there is already a value for this year.
860
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))	$yearoffsettype = preg_replace('/^@/','',$reg[2]);
861
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))	$yearoffsettype = preg_replace('/^@/','',$reg[3]);
1098
+    if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) {
1099
+        $yearoffsettype = preg_replace('/^@/','',$reg[2]);
1100
+    }
1101
+    if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) {
1102
+        $yearoffsettype = preg_replace('/^@/','',$reg[3]);
1103
+    }
862 1104
 
863 1105
     //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype;
864
-    if (is_numeric($yearoffsettype) && $yearoffsettype >= 1)
865
-        $maskraz=$yearoffsettype; // For backward compatibility
866
-    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1))
867
-        $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
1106
+    if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) {
1107
+            $maskraz=$yearoffsettype;
1108
+    }
1109
+    // For backward compatibility
1110
+    else if ($yearoffsettype === '0' || (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) {
1111
+            $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START;
1112
+    }
868 1113
     //print "maskraz=".$maskraz;	// -1=no reset
869 1114
 
870 1115
     if ($maskraz > 0) {   // A reset is required
@@ -872,23 +1117,28 @@  discard block
 block discarded – undo
872 1117
             $maskraz = date('m', $date);
873 1118
             $resetEveryMonth = true;
874 1119
         }
875
-        if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1120
+        if ($maskraz > 12) {
1121
+            return 'ErrorBadMaskBadRazMonth';
1122
+        }
876 1123
 
877 1124
         // Define posy, posm and reg
878
-        if ($maskraz > 1)	// if reset is not first month, we need month and year into mask
1125
+        if ($maskraz > 1) {
1126
+            // if reset is not first month, we need month and year into mask
879 1127
         {
880
-            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
881
-            elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
882
-            else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
883
-
884
-            if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit';
885
-        }
886
-        else // if reset is for a specific month in year, we need year
1128
+            if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2;
1129
+        }
1130
+        $posm=3; } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; } else {
1131
+                return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1132
+            }
1133
+
1134
+            if (dol_strlen($reg[$posy]) < 2) {
1135
+                return 'ErrorCantUseRazWithYearOnOneDigit';
1136
+            }
1137
+        } else // if reset is for a specific month in year, we need year
887 1138
         {
888
-            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; }
889
-        	else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; }
890
-            else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; }
891
-            else return 'ErrorCantUseRazIfNoYearInMask';
1139
+            if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=3; $posm=2; } else if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=3; } else if (preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) { $posy=2; $posm=0; } else {
1140
+                return 'ErrorCantUseRazIfNoYearInMask';
1141
+            }
892 1142
         }
893 1143
         // Define length
894 1144
         $yearlen = $posy?dol_strlen($reg[$posy]):0;
@@ -906,9 +1156,11 @@  discard block
 block discarded – undo
906 1156
         $monthcomp=$maskraz;
907 1157
         $yearcomp=0;
908 1158
 
909
-        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// $yearoffsettype is - or +
1159
+        if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') {
1160
+            // $yearoffsettype is - or +
910 1161
         {
911
-        	$currentyear=date("Y", $date);
1162
+        	$currentyear=date("Y", $date);
1163
+        }
912 1164
         	$fiscaldate=dol_mktime('0','0','0',$maskraz,'1',$currentyear);
913 1165
         	$newyeardate=dol_mktime('0','0','0','1','1',$currentyear);
914 1166
         	$nextnewyeardate=dol_mktime('0','0','0','1','1',$currentyear+1);
@@ -918,21 +1170,32 @@  discard block
 block discarded – undo
918 1170
         	if ($date >= $fiscaldate)
919 1171
         	{
920 1172
         		// If before of next new year date
921
-        		if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset=1;
1173
+        		if ($date < $nextnewyeardate && $yearoffsettype == '+') {
1174
+        		    $yearoffset=1;
1175
+        		}
922 1176
         	}
923 1177
         	// If after or equal of current new year date
924
-        	else if ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset=-1;
1178
+        	else if ($date >= $newyeardate && $yearoffsettype == '-') {
1179
+        	    $yearoffset=-1;
1180
+        	}
925 1181
         }
926 1182
         // For backward compatibility
927 1183
         else if (date("m",$date) < $maskraz && empty($resetEveryMonth)) { $yearoffset=-1; }	// If current month lower that month of return to zero, year is previous year
928 1184
 
929
-        if ($yearlen == 4) $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
930
-        elseif ($yearlen == 2) $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
931
-        elseif ($yearlen == 1) $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
932
-        if ($monthcomp > 1 && empty($resetEveryMonth))	// Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
1185
+        if ($yearlen == 4) {
1186
+            $yearcomp=sprintf("%04d",date("Y",$date)+$yearoffset);
1187
+        } elseif ($yearlen == 2) {
1188
+            $yearcomp=sprintf("%02d",date("y",$date)+$yearoffset);
1189
+        } elseif ($yearlen == 1) {
1190
+            $yearcomp=substr(date("y",$date),2,1)+$yearoffset;
1191
+        }
1192
+        if ($monthcomp > 1 && empty($resetEveryMonth)) {
1193
+            // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0)
933 1194
         {
934
-            if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
935
-            elseif ($yearlen == 2) $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
1195
+            if ($yearlen == 4) $yearcomp1=sprintf("%04d",date("Y",$date)+$yearoffset+1);
1196
+        } elseif ($yearlen == 2) {
1197
+                $yearcomp1=sprintf("%02d",date("y",$date)+$yearoffset+1);
1198
+            }
936 1199
 
937 1200
             $sqlwhere.="(";
938 1201
             $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
@@ -941,13 +1204,11 @@  discard block
 block discarded – undo
941 1204
             $sqlwhere.=" (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp1."'";
942 1205
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") < '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."') ";
943 1206
             $sqlwhere.=')';
944
-        }
945
-		else if ($resetEveryMonth)
1207
+        } else if ($resetEveryMonth)
946 1208
 		{
947 1209
 			$sqlwhere.="(SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$yearcomp."'";
948 1210
             $sqlwhere.=" AND SUBSTRING(".$field.", ".$monthpos.", ".$monthlen.") = '".str_pad($monthcomp, $monthlen, '0', STR_PAD_LEFT)."')";
949
-		}
950
-        else   // reset is done on january
1211
+		} else   // reset is done on january
951 1212
         {
952 1213
             $sqlwhere.='(SUBSTRING('.$field.', '.$yearpos.', '.$yearlen.") = '".$yearcomp."')";
953 1214
         }
@@ -959,12 +1220,13 @@  discard block
 block discarded – undo
959 1220
     if (function_exists('mb_strrpos'))
960 1221
     	{
961 1222
     	$posnumstart=mb_strrpos($maskwithnocode,$maskcounter, 'UTF-8');
962
-	}
963
-	else
1223
+	} else
964 1224
 	{
965 1225
     	$posnumstart=strrpos($maskwithnocode,$maskcounter);
966 1226
 	}	// Pos of counter in final string (from 0 to ...)
967
-    if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence';
1227
+    if ($posnumstart < 0) {
1228
+        return 'ErrorBadMaskFailedToLocatePosOfSequence';
1229
+    }
968 1230
     $sqlstring='SUBSTRING('.$field.', '.($posnumstart+1).', '.dol_strlen($maskcounter).')';
969 1231
 
970 1232
     // Define $maskLike
@@ -977,9 +1239,15 @@  discard block
 block discarded – undo
977 1239
     $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
978 1240
     $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
979 1241
     $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),str_pad("",dol_strlen($maskcounter),"_"),$maskLike);
980
-    if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
981
-    if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
982
-    if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1242
+    if ($maskrefclient) {
1243
+        $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1244
+    }
1245
+    if ($masktype) {
1246
+        $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1247
+    }
1248
+    if ($maskuser) {
1249
+        $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1250
+    }
983 1251
     foreach($maskperso as $key => $val)
984 1252
     {
985 1253
     	$maskLike = str_replace(dol_string_nospecial($maskperso[$key]),$maskpersonew[$key],$maskLike);
@@ -991,12 +1259,18 @@  discard block
 block discarded – undo
991 1259
     $sql.= " FROM ".MAIN_DB_PREFIX.$table;
992 1260
     $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
993 1261
 	$sql.= " AND ".$field." NOT LIKE '(PROV%)'";
994
-    if ($bentityon) // only if entity enable
995
-    	$sql.= " AND entity IN (".getEntity($sharetable).")";
996
-    else if (! empty($forceentity))
997
-    	$sql.= " AND entity IN (".$forceentity.")";
998
-    if ($where) $sql.=$where;
999
-    if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1262
+    if ($bentityon) {
1263
+        // only if entity enable
1264
+    	$sql.= " AND entity IN (".getEntity($sharetable).")";
1265
+    } else if (! empty($forceentity)) {
1266
+        	$sql.= " AND entity IN (".$forceentity.")";
1267
+    }
1268
+    if ($where) {
1269
+        $sql.=$where;
1270
+    }
1271
+    if ($sqlwhere) {
1272
+        $sql.=' AND '.$sqlwhere;
1273
+    }
1000 1274
 
1001 1275
     //print $sql.'<br>';
1002 1276
     dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
@@ -1005,21 +1279,26 @@  discard block
 block discarded – undo
1005 1279
     {
1006 1280
         $obj = $db->fetch_object($resql);
1007 1281
         $counter = $obj->val;
1008
-    }
1009
-    else dol_print_error($db);
1282
+    } else {
1283
+        dol_print_error($db);
1284
+    }
1010 1285
 
1011 1286
     // Check if we must force counter to maskoffset
1012
-    if (empty($counter)) $counter=$maskoffset;
1013
-    else if (preg_match('/[^0-9]/i',$counter))
1287
+    if (empty($counter)) {
1288
+        $counter=$maskoffset;
1289
+    } else if (preg_match('/[^0-9]/i',$counter))
1014 1290
     {
1015 1291
     	$counter=0;
1016 1292
     	dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR);
1017
-    }
1018
-    else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter=$maskoffset;
1293
+    } else if ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) {
1294
+        $counter=$maskoffset;
1295
+    }
1019 1296
 
1020
-    if ($mode == 'last')	// We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1297
+    if ($mode == 'last') {
1298
+        // We found value for counter = last counter value. Now need to get corresponding ref of invoice.
1021 1299
     {
1022
-        $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1300
+        $counterpadded=str_pad($counter,dol_strlen($maskcounter),"0",STR_PAD_LEFT);
1301
+    }
1023 1302
 
1024 1303
         // Define $maskLike
1025 1304
         $maskLike = dol_string_nospecial($mask);
@@ -1031,34 +1310,48 @@  discard block
 block discarded – undo
1031 1310
         $maskLike = preg_replace('/\{mm\}/i','__',$maskLike);
1032 1311
         $maskLike = preg_replace('/\{dd\}/i','__',$maskLike);
1033 1312
         $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'),$counterpadded,$maskLike);
1034
-        if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1035
-        if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1036
-        if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1313
+        if ($maskrefclient) {
1314
+            $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'),str_pad("",dol_strlen($maskrefclient),"_"),$maskLike);
1315
+        }
1316
+        if ($masktype) {
1317
+            $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'),$masktype_value,$maskLike);
1318
+        }
1319
+        if ($maskuser) {
1320
+            $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'),$maskuser_value,$maskLike);
1321
+        }
1037 1322
 
1038 1323
         $ref='';
1039 1324
         $sql = "SELECT ".$field." as ref";
1040 1325
         $sql.= " FROM ".MAIN_DB_PREFIX.$table;
1041 1326
         $sql.= " WHERE ".$field." LIKE '".$maskLike."'";
1042 1327
     	$sql.= " AND ".$field." NOT LIKE '%PROV%'";
1043
-    	if ($bentityon) // only if entity enable
1044
-        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1045
-        else if (! empty($forceentity))
1046
-        	$sql.= " AND entity IN (".$forceentity.")";
1047
-        if ($where) $sql.=$where;
1048
-        if ($sqlwhere) $sql.=' AND '.$sqlwhere;
1328
+    	if ($bentityon) {
1329
+    	    // only if entity enable
1330
+        	$sql.= " AND entity IN (".getEntity($sharetable).")";
1331
+    	} else if (! empty($forceentity)) {
1332
+                	$sql.= " AND entity IN (".$forceentity.")";
1333
+        }
1334
+        if ($where) {
1335
+            $sql.=$where;
1336
+        }
1337
+        if ($sqlwhere) {
1338
+            $sql.=' AND '.$sqlwhere;
1339
+        }
1049 1340
 
1050 1341
         dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG);
1051 1342
         $resql=$db->query($sql);
1052 1343
         if ($resql)
1053 1344
         {
1054 1345
             $obj = $db->fetch_object($resql);
1055
-            if ($obj) $ref = $obj->ref;
1056
-        }
1057
-        else dol_print_error($db);
1346
+            if ($obj) {
1347
+                $ref = $obj->ref;
1348
+            }
1349
+        } else {
1350
+            dol_print_error($db);
1351
+        }
1058 1352
 
1059 1353
         $numFinal=$ref;
1060
-    }
1061
-    else if ($mode == 'next')
1354
+    } else if ($mode == 'next')
1062 1355
     {
1063 1356
         $counter++;
1064 1357
 
@@ -1074,7 +1367,9 @@  discard block
 block discarded – undo
1074 1367
 
1075 1368
             // Define $sqlstring
1076 1369
             $maskrefclient_posnumstart=strpos($maskwithnocode,$maskrefclient_maskcounter,strpos($maskwithnocode,$maskrefclient));	// Pos of counter in final string (from 0 to ...)
1077
-            if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask';
1370
+            if ($maskrefclient_posnumstart <= 0) {
1371
+                return 'ErrorBadMask';
1372
+            }
1078 1373
             $maskrefclient_sqlstring='SUBSTRING('.$field.', '.($maskrefclient_posnumstart+1).', '.dol_strlen($maskrefclient_maskcounter).')';
1079 1374
             //print "x".$sqlstring;
1080 1375
 
@@ -1096,12 +1391,20 @@  discard block
 block discarded – undo
1096 1391
             $maskrefclient_sql.= " FROM ".MAIN_DB_PREFIX.$table;
1097 1392
             //$sql.= " WHERE ".$field." not like '(%'";
1098 1393
             $maskrefclient_sql.= " WHERE ".$field." LIKE '".$maskrefclient_maskLike."'";
1099
-            if ($bentityon) // only if entity enable
1100
-            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1101
-            else if (! empty($forceentity))
1102
-            	$sql.= " AND entity IN (".$forceentity.")";
1103
-            if ($where) $maskrefclient_sql.=$where; //use the same optional where as general mask
1104
-            if ($sqlwhere) $maskrefclient_sql.=' AND '.$sqlwhere; //use the same sqlwhere as general mask
1394
+            if ($bentityon) {
1395
+                // only if entity enable
1396
+            	$maskrefclient_sql.= " AND entity IN (".getEntity($sharetable).")";
1397
+            } else if (! empty($forceentity)) {
1398
+                        	$sql.= " AND entity IN (".$forceentity.")";
1399
+            }
1400
+            if ($where) {
1401
+                $maskrefclient_sql.=$where;
1402
+            }
1403
+            //use the same optional where as general mask
1404
+            if ($sqlwhere) {
1405
+                $maskrefclient_sql.=' AND '.$sqlwhere;
1406
+            }
1407
+            //use the same sqlwhere as general mask
1105 1408
             $maskrefclient_sql.=' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode,$maskrefclient)+1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$maskrefclient_clientcode."')";
1106 1409
 
1107 1410
             dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG);
@@ -1110,10 +1413,13 @@  discard block
 block discarded – undo
1110 1413
             {
1111 1414
                 $maskrefclient_obj = $db->fetch_object($maskrefclient_resql);
1112 1415
                 $maskrefclient_counter = $maskrefclient_obj->val;
1113
-            }
1114
-            else dol_print_error($db);
1416
+            } else {
1417
+                dol_print_error($db);
1418
+            }
1115 1419
 
1116
-            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) $maskrefclient_counter=$maskrefclient_maskoffset;
1420
+            if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i',$maskrefclient_counter)) {
1421
+                $maskrefclient_counter=$maskrefclient_maskoffset;
1422
+            }
1117 1423
 			$maskrefclient_counter++;
1118 1424
         }
1119 1425
 
@@ -1121,13 +1427,14 @@  discard block
 block discarded – undo
1121 1427
         $numFinal = $mask;
1122 1428
 
1123 1429
         // We replace special codes except refclient
1124
-		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=')	// yearoffsettype is - or +, so we don't want current year
1430
+		if (! empty($yearoffsettype) && ! is_numeric($yearoffsettype) && $yearoffsettype != '=') {
1431
+		    // yearoffsettype is - or +, so we don't want current year
1125 1432
 		{
1126
-	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1433
+	        $numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date)+$yearoffset, $numFinal);
1434
+		}
1127 1435
         	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date)+$yearoffset, $numFinal);
1128 1436
         	$numFinal = preg_replace('/\{y\}/i',   substr(date("y",$date),1,1)+$yearoffset, $numFinal);
1129
-		}
1130
-		else	// we want yyyy to be current year
1437
+		} else	// we want yyyy to be current year
1131 1438
 		{
1132 1439
         	$numFinal = preg_replace('/\{yyyy\}/i',date("Y",$date), $numFinal);
1133 1440
         	$numFinal = preg_replace('/\{yy\}/i',  date("y",$date), $numFinal);
@@ -1184,7 +1491,9 @@  discard block
 block discarded – undo
1184 1491
 {
1185 1492
     $string = " ".$string;
1186 1493
      $ini = strpos($string,$start);
1187
-     if ($ini == 0) return "";
1494
+     if ($ini == 0) {
1495
+         return "";
1496
+     }
1188 1497
      $ini += strlen($start);
1189 1498
      $len = strpos($string,$end,$ini) - $ini;
1190 1499
      return substr($string,$ini,$len);
@@ -1208,8 +1517,7 @@  discard block
 block discarded – undo
1208 1517
         $masktri=$reg[1].(isset($reg[2])?$reg[2]:'').(isset($reg[3])?$reg[3]:'');
1209 1518
         $maskcounter=$reg[1];
1210 1519
         $hasglobalcounter=true;
1211
-    }
1212
-    else
1520
+    } else
1213 1521
     {
1214 1522
         // setting some defaults so the rest of the code won't fail if there is a third party counter
1215 1523
         $masktri='00000';
@@ -1218,7 +1526,9 @@  discard block
 block discarded – undo
1218 1526
 
1219 1527
     $maskraz=-1;
1220 1528
     $maskoffset=0;
1221
-    if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1529
+    if (dol_strlen($maskcounter) < 3) {
1530
+        return 'ErrorCounterMustHaveMoreThan3Digits';
1531
+    }
1222 1532
 
1223 1533
     // Extract value for third party mask counter
1224 1534
     if (preg_match('/\{(c+)(0*)\}/i',$mask,$regClientRef))
@@ -1230,9 +1540,12 @@  discard block
 block discarded – undo
1230 1540
         $maskrefclient_clientcode=substr('',0,dol_strlen($maskrefclient_maskclientcode));//get n first characters of client code to form maskrefclient_clientcode
1231 1541
         $maskrefclient_clientcode=str_pad($maskrefclient_clientcode,dol_strlen($maskrefclient_maskclientcode),"#",STR_PAD_RIGHT);//padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode
1232 1542
         $maskrefclient_clientcode=dol_string_nospecial($maskrefclient_clientcode);//sanitize maskrefclient_clientcode for sql insert and sql select like
1233
-        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits';
1234
-    }
1235
-    else $maskrefclient='';
1543
+        if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) {
1544
+            return 'ErrorCounterMustHaveMoreThan3Digits';
1545
+        }
1546
+    } else {
1547
+        $maskrefclient='';
1548
+    }
1236 1549
 
1237 1550
     // fail if there is neither a global nor a third party counter
1238 1551
     if (! $hasglobalcounter && ($maskrefclient_maskcounter == ''))
@@ -1254,21 +1567,35 @@  discard block
 block discarded – undo
1254 1567
     //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n<br>";
1255 1568
 
1256 1569
     // If an offset is asked
1257
-    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) $maskoffset=preg_replace('/^\+/','',$reg[2]);
1258
-    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) $maskoffset=preg_replace('/^\+/','',$reg[3]);
1570
+    if (! empty($reg[2]) && preg_match('/^\+/',$reg[2])) {
1571
+        $maskoffset=preg_replace('/^\+/','',$reg[2]);
1572
+    }
1573
+    if (! empty($reg[3]) && preg_match('/^\+/',$reg[3])) {
1574
+        $maskoffset=preg_replace('/^\+/','',$reg[3]);
1575
+    }
1259 1576
 
1260 1577
     // Define $sqlwhere
1261 1578
 
1262 1579
     // If a restore to zero after a month is asked we check if there is already a value for this year.
1263
-    if (! empty($reg[2]) && preg_match('/^@/',$reg[2]))  $maskraz=preg_replace('/^@/','',$reg[2]);
1264
-    if (! empty($reg[3]) && preg_match('/^@/',$reg[3]))  $maskraz=preg_replace('/^@/','',$reg[3]);
1580
+    if (! empty($reg[2]) && preg_match('/^@/',$reg[2])) {
1581
+        $maskraz=preg_replace('/^@/','',$reg[2]);
1582
+    }
1583
+    if (! empty($reg[3]) && preg_match('/^@/',$reg[3])) {
1584
+        $maskraz=preg_replace('/^@/','',$reg[3]);
1585
+    }
1265 1586
     if ($maskraz >= 0)
1266 1587
     {
1267
-        if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth';
1588
+        if ($maskraz > 12) {
1589
+            return 'ErrorBadMaskBadRazMonth';
1590
+        }
1268 1591
 
1269 1592
         // Define reg
1270
-        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1271
-        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) return 'ErrorCantUseRazIfNoYearInMask';
1593
+        if ($maskraz > 1 && ! preg_match('/^(.*)\{(y+)\}\{(m+)\}/i',$maskwithonlyymcode,$reg)) {
1594
+            return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask';
1595
+        }
1596
+        if ($maskraz <= 1 && ! preg_match('/^(.*)\{(y+)\}/i',$maskwithonlyymcode,$reg)) {
1597
+            return 'ErrorCantUseRazIfNoYearInMask';
1598
+        }
1272 1599
         //print "x".$maskwithonlyymcode." ".$maskraz;
1273 1600
     }
1274 1601
     //print "masktri=".$masktri." maskcounter=".$maskcounter." maskraz=".$maskraz." maskoffset=".$maskoffset."<br>\n";
@@ -1278,7 +1605,9 @@  discard block
 block discarded – undo
1278 1605
 
1279 1606
     // Check length
1280 1607
     $len=dol_strlen($maskwithnocode);
1281
-    if (dol_strlen($value) != $len) $result=-1;
1608
+    if (dol_strlen($value) != $len) {
1609
+        $result=-1;
1610
+    }
1282 1611
 
1283 1612
     // Define $maskLike
1284 1613
     /* seems not used
@@ -1359,29 +1688,37 @@  discard block
 block discarded – undo
1359 1688
      */
1360 1689
 
1361 1690
     // Definition du Jeudi de la semaine
1362
-    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) // Dimanche
1363
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1364
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) // du Lundi au Mercredi
1365
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1366
-    else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) // du Vendredi au Samedi
1367
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1368
-    else // Jeudi
1369
-    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1691
+    if (date("w",mktime(12,0,0,$mois,$jour,$annee))==0) {
1692
+        // Dimanche
1693
+    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-3*24*60*60;
1694
+    } else if (date("w",mktime(12,0,0,$mois,$jour,$annee))<4) {
1695
+        // du Lundi au Mercredi
1696
+    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)+(4-date("w",mktime(12,0,0,$mois,$jour,$annee)))*24*60*60;
1697
+    } else if (date("w",mktime(12,0,0,$mois,$jour,$annee))>4) {
1698
+        // du Vendredi au Samedi
1699
+    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee)-(date("w",mktime(12,0,0,$mois,$jour,$annee))-4)*24*60*60;
1700
+    } else {
1701
+        // Jeudi
1702
+    $jeudiSemaine = mktime(12,0,0,$mois,$jour,$annee);
1703
+    }
1370 1704
 
1371 1705
     // Definition du premier Jeudi de l'annee
1372
-    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) // Dimanche
1706
+    if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==0) {
1707
+        // Dimanche
1373 1708
     {
1374
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1375
-    }
1376
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) // du Lundi au Mercredi
1709
+        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+4*24*60*60;
1710
+    }
1711
+    } else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))<4) {
1712
+        // du Lundi au Mercredi
1377 1713
     {
1378
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1379
-    }
1380
-    else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) // du Vendredi au Samedi
1714
+        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(4-date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine))))*24*60*60;
1715
+    }
1716
+    } else if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))>4) {
1717
+        // du Vendredi au Samedi
1381 1718
     {
1382
-        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1383
-    }
1384
-    else // Jeudi
1719
+        $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine))+(7-(date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))-4))*24*60*60;
1720
+    }
1721
+    } else // Jeudi
1385 1722
     {
1386 1723
         $premierJeudiAnnee = mktime(12,0,0,1,1,date("Y",$jeudiSemaine));
1387 1724
     }
@@ -1402,8 +1739,7 @@  discard block
 block discarded – undo
1402 1739
         if (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==4 || (date("w",mktime(12,0,0,1,1,date("Y",$jeudiSemaine)))==3 && date("z",mktime(12,0,0,12,31,date("Y",$jeudiSemaine)))==365))
1403 1740
         {
1404 1741
             $numeroSemaine = 53;
1405
-        }
1406
-        else
1742
+        } else
1407 1743
         {
1408 1744
             $numeroSemaine = 1;
1409 1745
         }
@@ -1462,7 +1798,9 @@  discard block
 block discarded – undo
1462 1798
 function dol_set_user_param($db, $conf, &$user, $tab)
1463 1799
 {
1464 1800
     // Verification parametres
1465
-    if (count($tab) < 1) return -1;
1801
+    if (count($tab) < 1) {
1802
+        return -1;
1803
+    }
1466 1804
 
1467 1805
     $db->begin();
1468 1806
 
@@ -1474,7 +1812,9 @@  discard block
 block discarded – undo
1474 1812
     $i=0;
1475 1813
     foreach ($tab as $key => $value)
1476 1814
     {
1477
-        if ($i > 0) $sql.=',';
1815
+        if ($i > 0) {
1816
+            $sql.=',';
1817
+        }
1478 1818
         $sql.="'".$db->escape($key)."'";
1479 1819
         $i++;
1480 1820
     }
@@ -1508,8 +1848,7 @@  discard block
 block discarded – undo
1508 1848
             }
1509 1849
             $user->conf->$key = $value;
1510 1850
             //print "key=".$key." user->conf->key=".$user->conf->$key;
1511
-        }
1512
-        else
1851
+        } else
1513 1852
         {
1514 1853
             unset($user->conf->$key);
1515 1854
         }
@@ -1532,8 +1871,7 @@  discard block
 block discarded – undo
1532 1871
     if ($reduction == 100)
1533 1872
     {
1534 1873
         $string = $langs->transnoentities("Offered");
1535
-    }
1536
-    else
1874
+    } else
1537 1875
     {
1538 1876
     	$string = vatrate($reduction,true);
1539 1877
     }
@@ -1620,9 +1958,11 @@  discard block
 block discarded – undo
1620 1958
 
1621 1959
             // If this generation module needs to scan a directory, then description field is filled
1622 1960
             // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...).
1623
-            if (! empty($obj->description))	// A list of directories to scan is defined
1961
+            if (! empty($obj->description)) {
1962
+                // A list of directories to scan is defined
1624 1963
             {
1625
-                include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1964
+                include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1965
+            }
1626 1966
 
1627 1967
                 $const=$obj->description;
1628 1968
                 //irtoscan.=($dirtoscan?',':'').preg_replace('/[\r\n]+/',',',trim($conf->global->$const));
@@ -1641,7 +1981,9 @@  discard block
 block discarded – undo
1641 1981
                     {
1642 1982
 			// all type of template is allowed
1643 1983
 			$tmpfiles=dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0);
1644
-                        if (count($tmpfiles)) $listoffiles=array_merge($listoffiles,$tmpfiles);
1984
+                        if (count($tmpfiles)) {
1985
+                            $listoffiles=array_merge($listoffiles,$tmpfiles);
1986
+                        }
1645 1987
                     }
1646 1988
                 }
1647 1989
 
@@ -1652,40 +1994,41 @@  discard block
 block discarded – undo
1652 1994
                         $max=($maxfilenamelength?$maxfilenamelength:28);
1653 1995
                         $liste[$obj->id.':'.$record['fullname']]=dol_trunc($record['name'],$max,'middle');
1654 1996
                     }
1655
-                }
1656
-                else
1997
+                } else
1657 1998
                 {
1658 1999
                     $liste[0]=$obj->label.': '.$langs->trans("None");
1659 2000
                 }
1660
-            }
1661
-            else
2001
+            } else
1662 2002
             {
1663
-                if ($type == 'member' && $obj->lib == 'standard')   // Special case, if member template, we add variant per format
2003
+                if ($type == 'member' && $obj->lib == 'standard') {
2004
+                    // Special case, if member template, we add variant per format
1664 2005
                 {
1665
-                    global $_Avery_Labels;
2006
+                    global $_Avery_Labels;
2007
+                }
1666 2008
                     include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php';
1667 2009
                     foreach($_Avery_Labels as $key => $val)
1668 2010
                     {
1669 2011
                         $liste[$obj->id.':'.$key]=($obj->label?$obj->label:$obj->lib).' '.$val['name'];
1670 2012
                     }
1671
-                }
1672
-                else    // Common usage
2013
+                } else    // Common usage
1673 2014
                 {
1674 2015
                     $liste[$obj->id]=$obj->label?$obj->label:$obj->lib;
1675 2016
                 }
1676 2017
             }
1677 2018
             $i++;
1678 2019
         }
1679
-    }
1680
-    else
2020
+    } else
1681 2021
     {
1682 2022
         dol_print_error($db);
1683 2023
         return -1;
1684 2024
     }
1685 2025
 
1686
-    if ($found) return $liste;
1687
-    else return 0;
1688
-}
2026
+    if ($found) {
2027
+        return $liste;
2028
+    } else {
2029
+        return 0;
2030
+    }
2031
+    }
1689 2032
 
1690 2033
 /**
1691 2034
  * This function evaluates a string that should be a valid IPv4
@@ -1700,10 +2043,14 @@  discard block
 block discarded – undo
1700 2043
 	if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
1701 2044
 
1702 2045
 		// Then we test if it is a private range
1703
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2;
2046
+		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) {
2047
+		    return 2;
2048
+		}
1704 2049
 
1705 2050
 		// Then we test if it is a reserved range
1706
-		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0;
2051
+		if (! filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) {
2052
+		    return 0;
2053
+		}
1707 2054
 
1708 2055
 		return 1;
1709 2056
 	}
@@ -1756,8 +2103,7 @@  discard block
 block discarded – undo
1756 2103
                       'proxy_password' => $proxypass,
1757 2104
                       'trace'		   => 1
1758 2105
         );
1759
-    }
1760
-    else
2106
+    } else
1761 2107
     {
1762 2108
         $params=array('connection_timeout'=>$timeout,
1763 2109
                       'response_timeout'=>$response_timeout,
@@ -1864,14 +2210,12 @@  discard block
 block discarded – undo
1864 2210
 		$classname='FactureFournisseur';
1865 2211
 		$classpath = 'fourn/class';
1866 2212
 		$module='fournisseur';
1867
-	}
1868
-	elseif ($objecttype == 'order_supplier')   {
2213
+	} elseif ($objecttype == 'order_supplier')   {
1869 2214
 		$classfile = 'fournisseur.commande';
1870 2215
 		$classname='CommandeFournisseur';
1871 2216
 		$classpath = 'fourn/class';
1872 2217
 		$module='fournisseur';
1873
-	}
1874
-	elseif ($objecttype == 'stock')   {
2218
+	} elseif ($objecttype == 'stock')   {
1875 2219
 		$classpath = 'product/stock/class';
1876 2220
 		$classfile='entrepot';
1877 2221
 		$classname='Entrepot';
@@ -1891,8 +2235,9 @@  discard block
 block discarded – undo
1891 2235
 					$ret=$langs->trans('Deleted');
1892 2236
 				}
1893 2237
 				unset($object);
1894
-			}
1895
-			else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
2238
+			} else {
2239
+			    dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR);
2240
+			}
1896 2241
 		}
1897 2242
 	}
1898 2243
 	return $ret;
@@ -1924,11 +2269,12 @@  discard block
 block discarded – undo
1924 2269
 		{
1925 2270
 			$obj = $db->fetch_object($resql);
1926 2271
 			$listofid[]=$obj->rowid;
1927
-			if ($obj->parent_id > 0) $listofparentid[$obj->rowid]=$obj->parent_id;
2272
+			if ($obj->parent_id > 0) {
2273
+			    $listofparentid[$obj->rowid]=$obj->parent_id;
2274
+			}
1928 2275
 			$i++;
1929 2276
 		}
1930
-	}
1931
-	else
2277
+	} else
1932 2278
 	{
1933 2279
 		dol_print_error($db);
1934 2280
 	}
@@ -1963,9 +2309,11 @@  discard block
 block discarded – undo
1963 2309
 			while ($cursor > 0)
1964 2310
 			{
1965 2311
 				$arrayidparsed[$cursor]=1;
1966
-				if ($arrayidparsed[$listofparentid[$cursor]])	// We detect a loop. A record with a parent that was already into child
2312
+				if ($arrayidparsed[$listofparentid[$cursor]]) {
2313
+				    // We detect a loop. A record with a parent that was already into child
1967 2314
 				{
1968
-					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
2315
+					print 'Found a loop between id '.$id.' - '.$cursor.'<br>';
2316
+				}
1969 2317
 					unset($arrayidparsed);
1970 2318
 					$listofidtoclean[$cursor]=$id;
1971 2319
 					break;
@@ -1973,7 +2321,9 @@  discard block
 block discarded – undo
1973 2321
 				$cursor=$listofparentid[$cursor];
1974 2322
 			}
1975 2323
 
1976
-			if (count($listofidtoclean)) break;
2324
+			if (count($listofidtoclean)) {
2325
+			    break;
2326
+			}
1977 2327
 		}
1978 2328
 
1979 2329
 		$sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree;
@@ -2120,9 +2470,15 @@  discard block
 block discarded – undo
2120 2470
         $classfile='fournisseur.facture';
2121 2471
     }
2122 2472
 
2123
-    if (!isset($classfile)) $classfile = strtolower($subelement);
2124
-    if (!isset($classname)) $classname = ucfirst($subelement);
2125
-    if (!isset($classpath)) $classpath = $module.'/class';
2473
+    if (!isset($classfile)) {
2474
+        $classfile = strtolower($subelement);
2475
+    }
2476
+    if (!isset($classname)) {
2477
+        $classname = ucfirst($subelement);
2478
+    }
2479
+    if (!isset($classpath)) {
2480
+        $classpath = $module.'/class';
2481
+    }
2126 2482
 
2127 2483
     $element_properties = array(
2128 2484
         'module' => $module,
@@ -2176,8 +2532,12 @@  discard block
 block discarded – undo
2176 2532
  */
2177 2533
 function colorArrayToHex($arraycolor,$colorifnotfound='888888')
2178 2534
 {
2179
-	if (! is_array($arraycolor)) return $colorifnotfound;
2180
-	if (empty($arraycolor)) return $colorifnotfound;
2535
+	if (! is_array($arraycolor)) {
2536
+	    return $colorifnotfound;
2537
+	}
2538
+	if (empty($arraycolor)) {
2539
+	    return $colorifnotfound;
2540
+	}
2181 2541
 	return sprintf("%02s",dechex($arraycolor[0])).sprintf("%02s",dechex($arraycolor[1])).sprintf("%02s",dechex($arraycolor[2]));
2182 2542
 }
2183 2543
 
@@ -2193,12 +2553,17 @@  discard block
 block discarded – undo
2193 2553
  */
2194 2554
 static function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88))
2195 2555
     {
2196
-	if (is_array($stringcolor)) return $stringcolor;	// If already into correct output format, we return as is
2556
+	if (is_array($stringcolor)) {
2557
+	    return $stringcolor;
2558
+	}
2559
+	// If already into correct output format, we return as is
2197 2560
 	$tmp=preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/',$stringcolor,$reg);
2198 2561
 	if (! $tmp)
2199 2562
 	{
2200 2563
 		$tmp=explode(',',$stringcolor);
2201
-		if (count($tmp) < 3) return $colorifnotfound;
2564
+		if (count($tmp) < 3) {
2565
+		    return $colorifnotfound;
2566
+		}
2202 2567
 		return $tmp;
2203 2568
 	}
2204 2569
 	return array(hexdec($reg[1]),hexdec($reg[2]),hexdec($reg[3]));
@@ -2244,69 +2609,51 @@  discard block
 block discarded – undo
2244 2609
 function getModuleDirForApiClass($module)
2245 2610
 {
2246 2611
     $moduledirforclass=$module;
2247
-    if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2612
+    if ($moduledirforclass != 'api') {
2613
+        $moduledirforclass = preg_replace('/api$/i','',$moduledirforclass);
2614
+    }
2248 2615
 
2249 2616
     if ($module == 'contracts') {
2250 2617
     	$moduledirforclass = 'contrat';
2251
-    }
2252
-    elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2618
+    } elseif (in_array($module, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents'))) {
2253 2619
         $moduledirforclass = 'api';
2254
-    }
2255
-    elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
2620
+    } elseif ($module == 'contact' || $module == 'contacts' || $module == 'customer' || $module == 'thirdparty' || $module == 'thirdparties') {
2256 2621
         $moduledirforclass = 'societe';
2257
-    }
2258
-    elseif ($module == 'propale' || $module == 'proposals') {
2622
+    } elseif ($module == 'propale' || $module == 'proposals') {
2259 2623
         $moduledirforclass = 'comm/propal';
2260
-    }
2261
-    elseif ($module == 'agenda' || $module == 'agendaevents') {
2624
+    } elseif ($module == 'agenda' || $module == 'agendaevents') {
2262 2625
         $moduledirforclass = 'comm/action';
2263
-    }
2264
-    elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
2626
+    } elseif ($module == 'adherent' || $module == 'members' || $module == 'memberstypes' || $module == 'subscriptions') {
2265 2627
         $moduledirforclass = 'adherents';
2266
-    }
2267
-    elseif ($module == 'banque' || $module == 'bankaccounts') {
2628
+    } elseif ($module == 'banque' || $module == 'bankaccounts') {
2268 2629
         $moduledirforclass = 'compta/bank';
2269
-    }
2270
-    elseif ($module == 'category' || $module == 'categorie') {
2630
+    } elseif ($module == 'category' || $module == 'categorie') {
2271 2631
         $moduledirforclass = 'categories';
2272
-    }
2273
-    elseif ($module == 'order' || $module == 'orders') {
2632
+    } elseif ($module == 'order' || $module == 'orders') {
2274 2633
         $moduledirforclass = 'commande';
2275
-    }
2276
-    elseif ($module == 'shipments') {
2634
+    } elseif ($module == 'shipments') {
2277 2635
     	$moduledirforclass = 'expedition';
2278
-    }
2279
-    elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2636
+    } elseif ($module == 'facture' || $module == 'invoice' || $module == 'invoices') {
2280 2637
         $moduledirforclass = 'compta/facture';
2281
-    }
2282
-    elseif ($module == 'products') {
2638
+    } elseif ($module == 'products') {
2283 2639
         $moduledirforclass = 'product';
2284
-    }
2285
-    elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
2640
+    } elseif ($module == 'project' || $module == 'projects' || $module == 'tasks') {
2286 2641
         $moduledirforclass = 'projet';
2287
-    }
2288
-    elseif ($module == 'task') {
2642
+    } elseif ($module == 'task') {
2289 2643
         $moduledirforclass = 'projet';
2290
-    }
2291
-    elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
2644
+    } elseif ($module == 'stock' || $module == 'stockmovements' || $module == 'warehouses') {
2292 2645
         $moduledirforclass = 'product/stock';
2293
-    }
2294
-    elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2646
+    } elseif ($module == 'supplierproposals' || $module == 'supplierproposal' || $module == 'supplier_proposal') {
2295 2647
     	$moduledirforclass = 'supplier_proposal';
2296
-    }
2297
-    elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2648
+    } elseif ($module == 'fournisseur' || $module == 'supplierinvoices' || $module == 'supplierorders') {
2298 2649
         $moduledirforclass = 'fourn';
2299
-    }
2300
-    elseif ($module == 'expensereports') {
2650
+    } elseif ($module == 'expensereports') {
2301 2651
         $moduledirforclass = 'expensereport';
2302
-    }
2303
-    elseif ($module == 'users') {
2652
+    } elseif ($module == 'users') {
2304 2653
         $moduledirforclass = 'user';
2305
-    }
2306
-    elseif ($module == 'ficheinter' || $module == 'interventions') {
2654
+    } elseif ($module == 'ficheinter' || $module == 'interventions') {
2307 2655
     	$moduledirforclass = 'fichinter';
2308
-    }
2309
-    elseif ($module == 'tickets') {
2656
+    } elseif ($module == 'tickets') {
2310 2657
     	$moduledirforclass = 'ticket';
2311 2658
     }
2312 2659
 
Please login to merge, or discard this patch.
Helpers/NoValeConfig.php 3 patches
Indentation   +41 added lines, -41 removed lines patch added patch discarded remove patch
@@ -57,11 +57,11 @@  discard block
 block discarded – undo
57 57
 {
58 58
     $db=getDoliDBInstance($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
59 59
 
60
-	if ($db->error)
61
-	{
62
-		dol_print_error($db,"host=".$conf->db->host.", port=".$conf->db->port.", user=".$conf->db->user.", databasename=".$conf->db->name.", ".$db->error);
63
-		exit;
64
-	}
60
+    if ($db->error)
61
+    {
62
+        dol_print_error($db,"host=".$conf->db->host.", port=".$conf->db->port.", user=".$conf->db->user.", databasename=".$conf->db->name.", ".$db->error);
63
+        exit;
64
+    }
65 65
 }
66 66
 
67 67
 // Now database connexion is known, so we can forget password
@@ -80,19 +80,19 @@  discard block
 block discarded – undo
80 80
 // By default conf->entity is 1, but we change this if we ask another value.
81 81
 if (session_id() && ! empty($_SESSION["dol_entity"]))			// Entity inside an opened session
82 82
 {
83
-	$conf->entity = $_SESSION["dol_entity"];
83
+    $conf->entity = $_SESSION["dol_entity"];
84 84
 }
85 85
 else if (! empty($_ENV["dol_entity"]))							// Entity inside a CLI script
86 86
 {
87
-	$conf->entity = $_ENV["dol_entity"];
87
+    $conf->entity = $_ENV["dol_entity"];
88 88
 }
89 89
 else if (isset($_POST["loginfunction"]) && GETPOST("entity",'int'))	// Just after a login page
90 90
 {
91
-	$conf->entity = GETPOST("entity",'int');
91
+    $conf->entity = GETPOST("entity",'int');
92 92
 }
93 93
 else if (defined('DOLENTITY') && is_numeric(DOLENTITY))			// For public page with MultiCompany module
94 94
 {
95
-	$conf->entity = DOLENTITY;
95
+    $conf->entity = DOLENTITY;
96 96
 }
97 97
 
98 98
 // Sanitize entity
@@ -100,16 +100,16 @@  discard block
 block discarded – undo
100 100
 
101 101
 if (! defined('NOREQUIREDB'))
102 102
 {
103
-	//print "Will work with data into entity instance number '".$conf->entity."'";
103
+    //print "Will work with data into entity instance number '".$conf->entity."'";
104 104
 
105
-	// Here we read database (llx_const table) and define $conf->global->XXX var.
106
-	$conf->setValues($db);
105
+    // Here we read database (llx_const table) and define $conf->global->XXX var.
106
+    $conf->setValues($db);
107 107
 }
108 108
 
109 109
 // Overwrite database value
110 110
 if (! empty($conf->file->mailing_limit_sendbyweb))
111 111
 {
112
-	$conf->global->MAILING_LIMIT_SENDBYWEB = $conf->file->mailing_limit_sendbyweb;
112
+    $conf->global->MAILING_LIMIT_SENDBYWEB = $conf->file->mailing_limit_sendbyweb;
113 113
 }
114 114
 if (empty($conf->global->MAILING_LIMIT_SENDBYWEB))
115 115
 {
@@ -127,41 +127,41 @@  discard block
 block discarded – undo
127 127
 // If software has been locked. Only login $conf->global->MAIN_ONLY_LOGIN_ALLOWED is allowed.
128 128
 if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED))
129 129
 {
130
-	$ok=0;
131
-	if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) $ok=1;	// We let working pages if not logged and inside a web browser (login form, to allow login by admin)
132
-	elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;				// We let working pages that is a login submission (login submit, to allow login by admin)
133
-	elseif (defined('NOREQUIREDB'))   $ok=1;				// We let working pages that don't need database access (xxx.css.php)
134
-	elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok=1;	// We let working pages that ask to work even if only login enabled (logout.php)
135
-	elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;	// We let working if user is allowed admin
136
-	if (! $ok)
137
-	{
138
-		if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED)
139
-		{
140
-			print 'Sorry, your application is offline.'."\n";
141
-			print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
142
-			$nexturl=DOL_URL_ROOT.'/user/logout.php';
143
-			print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
144
-		}
145
-		else
146
-		{
147
-			print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
148
-			$nexturl=DOL_URL_ROOT.'/';
149
-			print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
150
-		}
151
-		exit;
152
-	}
130
+    $ok=0;
131
+    if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) $ok=1;	// We let working pages if not logged and inside a web browser (login form, to allow login by admin)
132
+    elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;				// We let working pages that is a login submission (login submit, to allow login by admin)
133
+    elseif (defined('NOREQUIREDB'))   $ok=1;				// We let working pages that don't need database access (xxx.css.php)
134
+    elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok=1;	// We let working pages that ask to work even if only login enabled (logout.php)
135
+    elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;	// We let working if user is allowed admin
136
+    if (! $ok)
137
+    {
138
+        if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED)
139
+        {
140
+            print 'Sorry, your application is offline.'."\n";
141
+            print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
142
+            $nexturl=DOL_URL_ROOT.'/user/logout.php';
143
+            print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
144
+        }
145
+        else
146
+        {
147
+            print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
148
+            $nexturl=DOL_URL_ROOT.'/';
149
+            print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
150
+        }
151
+        exit;
152
+    }
153 153
 }
154 154
 
155 155
 // Create object $mysoc (A thirdparty object that contains properties of companies managed by Dolibarr.
156 156
 if (! defined('NOREQUIREDB') && ! defined('NOREQUIRESOC'))
157 157
 {
158
-	require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
158
+    require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
159 159
 
160
-	$mysoc=new Societe($db);
161
-	$mysoc->setMysoc($conf);
160
+    $mysoc=new Societe($db);
161
+    $mysoc->setMysoc($conf);
162 162
 
163
-	// For some countries, we need to invert our address with customer address
164
-	if ($mysoc->country_code == 'DE' && ! isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT=1;
163
+    // For some countries, we need to invert our address with customer address
164
+    if ($mysoc->country_code == 'DE' && ! isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT=1;
165 165
 }
166 166
 
167 167
 
Please login to merge, or discard this patch.
Spacing   +34 added lines, -34 removed lines patch added patch discarded remove patch
@@ -32,7 +32,7 @@  discard block
 block discarded – undo
32 32
  * 				This script reads the conf file, init $lang, $db and and empty $user
33 33
  */
34 34
 
35
-require_once 'filefunc.inc.php';	// May have been already require by main.inc.php. But may not by scripts.
35
+require_once 'filefunc.inc.php'; // May have been already require by main.inc.php. But may not by scripts.
36 36
 
37 37
 
38 38
 
@@ -44,29 +44,29 @@  discard block
 block discarded – undo
44 44
 
45 45
 
46 46
 // Chargement des includes principaux de librairies communes
47
-if (! defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';		// Need 500ko memory
48
-if (! defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
49
-if (! defined('NOREQUIRESOC'))  require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
47
+if (!defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Need 500ko memory
48
+if (!defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php';
49
+if (!defined('NOREQUIRESOC'))  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
50 50
 
51 51
 
52 52
 
53 53
 /*
54 54
  * Object $db
55 55
  */
56
-if (! defined('NOREQUIREDB'))
56
+if (!defined('NOREQUIREDB'))
57 57
 {
58
-    $db=getDoliDBInstance($conf->db->type,$conf->db->host,$conf->db->user,$conf->db->pass,$conf->db->name,$conf->db->port);
58
+    $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port);
59 59
 
60 60
 	if ($db->error)
61 61
 	{
62
-		dol_print_error($db,"host=".$conf->db->host.", port=".$conf->db->port.", user=".$conf->db->user.", databasename=".$conf->db->name.", ".$db->error);
62
+		dol_print_error($db, "host=".$conf->db->host.", port=".$conf->db->port.", user=".$conf->db->user.", databasename=".$conf->db->name.", ".$db->error);
63 63
 		exit;
64 64
 	}
65 65
 }
66 66
 
67 67
 // Now database connexion is known, so we can forget password
68 68
 //unset($dolibarr_main_db_pass); 	// We comment this because this constant is used in a lot of pages
69
-unset($conf->db->pass);				// This is to avoid password to be shown in memory/swap dump
69
+unset($conf->db->pass); // This is to avoid password to be shown in memory/swap dump
70 70
 
71 71
 /*
72 72
  * Object $user
@@ -78,17 +78,17 @@  discard block
 block discarded – undo
78 78
  */
79 79
 
80 80
 // By default conf->entity is 1, but we change this if we ask another value.
81
-if (session_id() && ! empty($_SESSION["dol_entity"]))			// Entity inside an opened session
81
+if (session_id() && !empty($_SESSION["dol_entity"]))			// Entity inside an opened session
82 82
 {
83 83
 	$conf->entity = $_SESSION["dol_entity"];
84 84
 }
85
-else if (! empty($_ENV["dol_entity"]))							// Entity inside a CLI script
85
+else if (!empty($_ENV["dol_entity"]))							// Entity inside a CLI script
86 86
 {
87 87
 	$conf->entity = $_ENV["dol_entity"];
88 88
 }
89
-else if (isset($_POST["loginfunction"]) && GETPOST("entity",'int'))	// Just after a login page
89
+else if (isset($_POST["loginfunction"]) && GETPOST("entity", 'int'))	// Just after a login page
90 90
 {
91
-	$conf->entity = GETPOST("entity",'int');
91
+	$conf->entity = GETPOST("entity", 'int');
92 92
 }
93 93
 else if (defined('DOLENTITY') && is_numeric(DOLENTITY))			// For public page with MultiCompany module
94 94
 {
@@ -96,9 +96,9 @@  discard block
 block discarded – undo
96 96
 }
97 97
 
98 98
 // Sanitize entity
99
-if (! is_numeric($conf->entity)) $conf->entity=1;
99
+if (!is_numeric($conf->entity)) $conf->entity = 1;
100 100
 
101
-if (! defined('NOREQUIREDB'))
101
+if (!defined('NOREQUIREDB'))
102 102
 {
103 103
 	//print "Will work with data into entity instance number '".$conf->entity."'";
104 104
 
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
 }
108 108
 
109 109
 // Overwrite database value
110
-if (! empty($conf->file->mailing_limit_sendbyweb))
110
+if (!empty($conf->file->mailing_limit_sendbyweb))
111 111
 {
112 112
 	$conf->global->MAILING_LIMIT_SENDBYWEB = $conf->file->mailing_limit_sendbyweb;
113 113
 }
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
 {
116 116
     $conf->global->MAILING_LIMIT_SENDBYWEB = 25;
117 117
 }
118
-if (! empty($conf->file->mailing_limit_sendbycli))
118
+if (!empty($conf->file->mailing_limit_sendbycli))
119 119
 {
120 120
     $conf->global->MAILING_LIMIT_SENDBYCLI = $conf->file->mailing_limit_sendbycli;
121 121
 }
@@ -125,27 +125,27 @@  discard block
 block discarded – undo
125 125
 }
126 126
 
127 127
 // If software has been locked. Only login $conf->global->MAIN_ONLY_LOGIN_ALLOWED is allowed.
128
-if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED))
128
+if (!empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED))
129 129
 {
130
-	$ok=0;
131
-	if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) $ok=1;	// We let working pages if not logged and inside a web browser (login form, to allow login by admin)
132
-	elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;				// We let working pages that is a login submission (login submit, to allow login by admin)
133
-	elseif (defined('NOREQUIREDB'))   $ok=1;				// We let working pages that don't need database access (xxx.css.php)
134
-	elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok=1;	// We let working pages that ask to work even if only login enabled (logout.php)
135
-	elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;	// We let working if user is allowed admin
136
-	if (! $ok)
130
+	$ok = 0;
131
+	if ((!session_id() || !isset($_SESSION["dol_login"])) && !isset($_POST["username"]) && !empty($_SERVER["GATEWAY_INTERFACE"])) $ok = 1; // We let working pages if not logged and inside a web browser (login form, to allow login by admin)
132
+	elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working pages that is a login submission (login submit, to allow login by admin)
133
+	elseif (defined('NOREQUIREDB'))   $ok = 1; // We let working pages that don't need database access (xxx.css.php)
134
+	elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok = 1; // We let working pages that ask to work even if only login enabled (logout.php)
135
+	elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok = 1; // We let working if user is allowed admin
136
+	if (!$ok)
137 137
 	{
138 138
 		if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED)
139 139
 		{
140 140
 			print 'Sorry, your application is offline.'."\n";
141 141
 			print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
142
-			$nexturl=DOL_URL_ROOT.'/user/logout.php';
142
+			$nexturl = DOL_URL_ROOT.'/user/logout.php';
143 143
 			print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
144 144
 		}
145 145
 		else
146 146
 		{
147 147
 			print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
148
-			$nexturl=DOL_URL_ROOT.'/';
148
+			$nexturl = DOL_URL_ROOT.'/';
149 149
 			print 'Please try later or <a href="'.$nexturl.'">click here to change login user</a>...'."\n";
150 150
 		}
151 151
 		exit;
@@ -153,28 +153,28 @@  discard block
 block discarded – undo
153 153
 }
154 154
 
155 155
 // Create object $mysoc (A thirdparty object that contains properties of companies managed by Dolibarr.
156
-if (! defined('NOREQUIREDB') && ! defined('NOREQUIRESOC'))
156
+if (!defined('NOREQUIREDB') && !defined('NOREQUIRESOC'))
157 157
 {
158
-	require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
158
+	require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
159 159
 
160
-	$mysoc=new Societe($db);
160
+	$mysoc = new Societe($db);
161 161
 	$mysoc->setMysoc($conf);
162 162
 
163 163
 	// For some countries, we need to invert our address with customer address
164
-	if ($mysoc->country_code == 'DE' && ! isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT=1;
164
+	if ($mysoc->country_code == 'DE' && !isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT = 1;
165 165
 }
166 166
 
167 167
 
168 168
 // Set default language (must be after the setValues setting global $conf->global->MAIN_LANG_DEFAULT. Page main.inc.php will overwrite langs->defaultlang with user value later)
169
-if (! defined('NOREQUIRETRAN'))
169
+if (!defined('NOREQUIRETRAN'))
170 170
 {
171
-    $langcode=(GETPOST('lang','aZ09')?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
172
-    if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
171
+    $langcode = (GETPOST('lang', 'aZ09') ?GETPOST('lang', 'aZ09', 1) : (empty($conf->global->MAIN_LANG_DEFAULT) ? 'auto' : $conf->global->MAIN_LANG_DEFAULT));
172
+    if (defined('MAIN_LANG_DEFAULT')) $langcode = constant('MAIN_LANG_DEFAULT');
173 173
     $langs->setDefaultLang($langcode);
174 174
 }
175 175
 
176 176
 
177 177
 
178 178
 
179
-if (! defined('MAIN_LABEL_MENTION_NPR') ) define('MAIN_LABEL_MENTION_NPR','NPR');
179
+if (!defined('MAIN_LABEL_MENTION_NPR')) define('MAIN_LABEL_MENTION_NPR', 'NPR');
180 180
 
Please login to merge, or discard this patch.
Braces   +60 added lines, -26 removed lines patch added patch discarded remove patch
@@ -44,9 +44,16 @@  discard block
 block discarded – undo
44 44
 
45 45
 
46 46
 // Chargement des includes principaux de librairies communes
47
-if (! defined('NOREQUIREUSER')) require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';		// Need 500ko memory
48
-if (! defined('NOREQUIRETRAN')) require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
49
-if (! defined('NOREQUIRESOC'))  require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
47
+if (! defined('NOREQUIREUSER')) {
48
+    require_once DOL_DOCUMENT_ROOT .'/user/class/user.class.php';
49
+}
50
+// Need 500ko memory
51
+if (! defined('NOREQUIRETRAN')) {
52
+    require_once DOL_DOCUMENT_ROOT .'/core/class/translate.class.php';
53
+}
54
+if (! defined('NOREQUIRESOC')) {
55
+    require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
56
+}
50 57
 
51 58
 
52 59
 
@@ -78,25 +85,32 @@  discard block
 block discarded – undo
78 85
  */
79 86
 
80 87
 // By default conf->entity is 1, but we change this if we ask another value.
81
-if (session_id() && ! empty($_SESSION["dol_entity"]))			// Entity inside an opened session
88
+if (session_id() && ! empty($_SESSION["dol_entity"])) {
89
+    // Entity inside an opened session
82 90
 {
83
-	$conf->entity = $_SESSION["dol_entity"];
84
-}
85
-else if (! empty($_ENV["dol_entity"]))							// Entity inside a CLI script
91
+	$conf->entity = $_SESSION["dol_entity"];
92
+}
93
+} else if (! empty($_ENV["dol_entity"])) {
94
+    // Entity inside a CLI script
86 95
 {
87
-	$conf->entity = $_ENV["dol_entity"];
88
-}
89
-else if (isset($_POST["loginfunction"]) && GETPOST("entity",'int'))	// Just after a login page
96
+	$conf->entity = $_ENV["dol_entity"];
97
+}
98
+} else if (isset($_POST["loginfunction"]) && GETPOST("entity",'int')) {
99
+    // Just after a login page
90 100
 {
91
-	$conf->entity = GETPOST("entity",'int');
92
-}
93
-else if (defined('DOLENTITY') && is_numeric(DOLENTITY))			// For public page with MultiCompany module
101
+	$conf->entity = GETPOST("entity",'int');
102
+}
103
+} else if (defined('DOLENTITY') && is_numeric(DOLENTITY)) {
104
+    // For public page with MultiCompany module
94 105
 {
95
-	$conf->entity = DOLENTITY;
106
+	$conf->entity = DOLENTITY;
107
+}
96 108
 }
97 109
 
98 110
 // Sanitize entity
99
-if (! is_numeric($conf->entity)) $conf->entity=1;
111
+if (! is_numeric($conf->entity)) {
112
+    $conf->entity=1;
113
+}
100 114
 
101 115
 if (! defined('NOREQUIREDB'))
102 116
 {
@@ -128,11 +142,26 @@  discard block
 block discarded – undo
128 142
 if (! empty($conf->global->MAIN_ONLY_LOGIN_ALLOWED))
129 143
 {
130 144
 	$ok=0;
131
-	if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) $ok=1;	// We let working pages if not logged and inside a web browser (login form, to allow login by admin)
132
-	elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;				// We let working pages that is a login submission (login submit, to allow login by admin)
133
-	elseif (defined('NOREQUIREDB'))   $ok=1;				// We let working pages that don't need database access (xxx.css.php)
134
-	elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) $ok=1;	// We let working pages that ask to work even if only login enabled (logout.php)
135
-	elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) $ok=1;	// We let working if user is allowed admin
145
+	if ((! session_id() || ! isset($_SESSION["dol_login"])) && ! isset($_POST["username"]) && ! empty($_SERVER["GATEWAY_INTERFACE"])) {
146
+	    $ok=1;
147
+	}
148
+	// We let working pages if not logged and inside a web browser (login form, to allow login by admin)
149
+	elseif (isset($_POST["username"]) && $_POST["username"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) {
150
+	    $ok=1;
151
+	}
152
+	// We let working pages that is a login submission (login submit, to allow login by admin)
153
+	elseif (defined('NOREQUIREDB')) {
154
+	    $ok=1;
155
+	}
156
+	// We let working pages that don't need database access (xxx.css.php)
157
+	elseif (defined('EVEN_IF_ONLY_LOGIN_ALLOWED')) {
158
+	    $ok=1;
159
+	}
160
+	// We let working pages that ask to work even if only login enabled (logout.php)
161
+	elseif (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] == $conf->global->MAIN_ONLY_LOGIN_ALLOWED) {
162
+	    $ok=1;
163
+	}
164
+	// We let working if user is allowed admin
136 165
 	if (! $ok)
137 166
 	{
138 167
 		if (session_id() && isset($_SESSION["dol_login"]) && $_SESSION["dol_login"] != $conf->global->MAIN_ONLY_LOGIN_ALLOWED)
@@ -141,8 +170,7 @@  discard block
 block discarded – undo
141 170
 			print 'You are logged with user "'.$_SESSION["dol_login"].'" and only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
142 171
 			$nexturl=DOL_URL_ROOT.'/user/logout.php';
143 172
 			print 'Please try later or <a href="'.$nexturl.'">click here to disconnect and change login user</a>...'."\n";
144
-		}
145
-		else
173
+		} else
146 174
 		{
147 175
 			print 'Sorry, your application is offline. Only administrator user "'.$conf->global->MAIN_ONLY_LOGIN_ALLOWED.'" is allowed to connect for the moment.'."\n";
148 176
 			$nexturl=DOL_URL_ROOT.'/';
@@ -161,20 +189,26 @@  discard block
 block discarded – undo
161 189
 	$mysoc->setMysoc($conf);
162 190
 
163 191
 	// For some countries, we need to invert our address with customer address
164
-	if ($mysoc->country_code == 'DE' && ! isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $conf->global->MAIN_INVERT_SENDER_RECIPIENT=1;
165
-}
192
+	if ($mysoc->country_code == 'DE' && ! isset($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
193
+	    $conf->global->MAIN_INVERT_SENDER_RECIPIENT=1;
194
+	}
195
+	}
166 196
 
167 197
 
168 198
 // Set default language (must be after the setValues setting global $conf->global->MAIN_LANG_DEFAULT. Page main.inc.php will overwrite langs->defaultlang with user value later)
169 199
 if (! defined('NOREQUIRETRAN'))
170 200
 {
171 201
     $langcode=(GETPOST('lang','aZ09')?GETPOST('lang','aZ09',1):(empty($conf->global->MAIN_LANG_DEFAULT)?'auto':$conf->global->MAIN_LANG_DEFAULT));
172
-    if (defined('MAIN_LANG_DEFAULT')) $langcode=constant('MAIN_LANG_DEFAULT');
202
+    if (defined('MAIN_LANG_DEFAULT')) {
203
+        $langcode=constant('MAIN_LANG_DEFAULT');
204
+    }
173 205
     $langs->setDefaultLang($langcode);
174 206
 }
175 207
 
176 208
 
177 209
 
178 210
 
179
-if (! defined('MAIN_LABEL_MENTION_NPR') ) define('MAIN_LABEL_MENTION_NPR','NPR');
211
+if (! defined('MAIN_LABEL_MENTION_NPR') ) {
212
+    define('MAIN_LABEL_MENTION_NPR','NPR');
213
+}
180 214
 
Please login to merge, or discard this patch.
Helpers/login/functions_ldap.php 3 patches
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -34,190 +34,190 @@  discard block
 block discarded – undo
34 34
  */
35 35
 function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest)
36 36
 {
37
-	global $db,$conf,$langs;
38
-	global $_POST;
39
-	global $dolibarr_main_auth_ldap_host,$dolibarr_main_auth_ldap_port;
40
-	global $dolibarr_main_auth_ldap_version,$dolibarr_main_auth_ldap_servertype;
41
-	global $dolibarr_main_auth_ldap_login_attribute,$dolibarr_main_auth_ldap_dn;
42
-	global $dolibarr_main_auth_ldap_admin_login,$dolibarr_main_auth_ldap_admin_pass;
43
-	global $dolibarr_main_auth_ldap_filter;
44
-	global $dolibarr_main_auth_ldap_debug;
45
-
46
-	// Force master entity in transversal mode
47
-	$entity=$entitytotest;
48
-	if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $entity=1;
49
-
50
-	$login='';
51
-	$resultFetchUser='';
52
-
53
-	if (! function_exists("ldap_connect"))
54
-	{
55
-		dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP. LDAP functions are disabled on this PHP");
56
-		sleep(1);
57
-
58
-		// Load translation files required by the page
37
+    global $db,$conf,$langs;
38
+    global $_POST;
39
+    global $dolibarr_main_auth_ldap_host,$dolibarr_main_auth_ldap_port;
40
+    global $dolibarr_main_auth_ldap_version,$dolibarr_main_auth_ldap_servertype;
41
+    global $dolibarr_main_auth_ldap_login_attribute,$dolibarr_main_auth_ldap_dn;
42
+    global $dolibarr_main_auth_ldap_admin_login,$dolibarr_main_auth_ldap_admin_pass;
43
+    global $dolibarr_main_auth_ldap_filter;
44
+    global $dolibarr_main_auth_ldap_debug;
45
+
46
+    // Force master entity in transversal mode
47
+    $entity=$entitytotest;
48
+    if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $entity=1;
49
+
50
+    $login='';
51
+    $resultFetchUser='';
52
+
53
+    if (! function_exists("ldap_connect"))
54
+    {
55
+        dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP. LDAP functions are disabled on this PHP");
56
+        sleep(1);
57
+
58
+        // Load translation files required by the page
59 59
         $langs->loadLangs(array('main', 'other'));
60 60
 
61
-		$_SESSION["dol_loginmesg"]=$langs->trans("ErrorLDAPFunctionsAreDisabledOnThisPHP").' '.$langs->trans("TryAnotherConnectionMode");
62
-		return;
63
-	}
64
-
65
-	if ($usertotest)
66
-	{
67
-		dol_syslog("functions_ldap::check_user_password_ldap usertotest=".$usertotest." passwordtotest=".preg_replace('/./','*',$passwordtotest)." entitytotest=".$entitytotest);
68
-
69
-		// If test username/password asked, we define $test=false and $login var if ok, set $_SESSION["dol_loginmesg"] if ko
70
-		$ldaphost=$dolibarr_main_auth_ldap_host;
71
-		$ldapport=$dolibarr_main_auth_ldap_port;
72
-		$ldapversion=$dolibarr_main_auth_ldap_version;
73
-		$ldapservertype=(empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype);
74
-
75
-		$ldapuserattr=$dolibarr_main_auth_ldap_login_attribute;
76
-		$ldapdn=$dolibarr_main_auth_ldap_dn;
77
-		$ldapadminlogin=$dolibarr_main_auth_ldap_admin_login;
78
-		$ldapadminpass=$dolibarr_main_auth_ldap_admin_pass;
79
-		$ldapdebug=(empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug=="false" ? false : true);
80
-
81
-		if ($ldapdebug) print "DEBUG: Logging LDAP steps<br>\n";
82
-
83
-		require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php';
84
-		$ldap=new Ldap();
85
-		$ldap->server=explode(',',$ldaphost);
86
-		$ldap->serverPort=$ldapport;
87
-		$ldap->ldapProtocolVersion=$ldapversion;
88
-		$ldap->serverType=$ldapservertype;
89
-		$ldap->searchUser=$ldapadminlogin;
90
-		$ldap->searchPassword=$ldapadminpass;
91
-
92
-		if ($ldapdebug)
93
-		{
94
-			dol_syslog("functions_ldap::check_user_password_ldap Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType);
95
-			dol_syslog("functions_ldap::check_user_password_ldap uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword);
96
-			print "DEBUG: Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType."<br>\n";
97
-			print "DEBUG: uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword."<br>\n";
98
-		}
99
-
100
-		$resultFetchLdapUser=0;
101
-
102
-		// Define $userSearchFilter
103
-		$userSearchFilter = "";
104
-		if (empty($dolibarr_main_auth_ldap_filter)) {
105
-			$userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")";
106
-		} else {
107
-			$userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter);
108
-		}
109
-
110
-		// If admin login provided
111
-		// Code to get user in LDAP from an admin connection (may differ from user connection, done later)
112
-		if ($ldapadminlogin)
113
-		{
114
-			$result=$ldap->connect_bind();
115
-			if ($result > 0)
116
-			{
117
-				$resultFetchLdapUser = $ldap->fetch($usertotest,$userSearchFilter);
118
-				//dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='.$resultFetchLdapUser);
119
-				if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) // If ok but password need to be reset
120
-				{
121
-					dol_syslog('functions_ldap::check_user_password_ldap '.$usertotest.' must change password next logon');
122
-					if ($ldapdebug) print "DEBUG: User ".$usertotest." must change password<br>\n";
123
-					$ldap->close();
124
-					sleep(1);
125
-					$langs->load('ldap');
126
-					$_SESSION["dol_loginmesg"]=$langs->trans("YouMustChangePassNextLogon",$usertotest,$ldap->domainFQDN);
127
-					return '';
128
-				}
129
-			}
130
-			else
131
-			{
132
-				 if ($ldapdebug) print "DEBUG: ".$ldap->error."<br>\n";
133
-			}
134
-			$ldap->close();
135
-		}
136
-
137
-		// Forge LDAP user and password to test with them
138
-		// If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with
139
-		// admin login no exectued.
140
-		$ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn;  // Default dn (will work if LDAP accept a dn with login value inside)
141
-		// But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
142
-		// dn detected into ldapUserDN.
143
-		if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN;
144
-		$ldap->searchPassword=$passwordtotest;
145
-
146
-		// Test with this->seachUser and this->searchPassword
147
-		//print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit;
148
-		$result=$ldap->connect_bind();
149
-		if ($result > 0)
150
-		{
151
-			if ($result == 2)	// Connection is ok for user/pass into LDAP
152
-			{
153
-				dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
154
-				$login=$usertotest;
155
-
156
-				// ldap2dolibarr synchronisation
157
-				if ($login && ! empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')	// ldap2dolibarr synchronisation
158
-				{
159
-						dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
160
-
161
-						// On charge les attributs du user ldap
162
-						if ($ldapdebug) print "DEBUG: login ldap = ".$login."<br>\n";
163
-						$resultFetchLdapUser = $ldap->fetch($login,$userSearchFilter);
164
-
165
-						if ($ldapdebug) print "DEBUG: UACF = ".join(',',$ldap->uacf)."<br>\n";
166
-						if ($ldapdebug) print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset,'day')."<br>\n";
167
-						if ($ldapdebug) print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime,'day')."<br>\n";
168
-
169
-						// On recherche le user dolibarr en fonction de son SID ldap
170
-						$sid = $ldap->getObjectSid($login);
171
-						if ($ldapdebug) print "DEBUG: sid = ".$sid."<br>\n";
172
-
173
-						$usertmp=new User($db);
174
-						$resultFetchUser=$usertmp->fetch('',$login,$sid);
175
-						if ($resultFetchUser > 0)
176
-						{
177
-							dol_syslog("functions_ldap::check_user_password_ldap Sync user found user id=".$usertmp->id);
178
-							// On verifie si le login a change et on met a jour les attributs dolibarr
179
-
180
-							if ($usertmp->login != $ldap->login && $ldap->login)
181
-							{
182
-								$usertmp->login = $ldap->login;
183
-								$usertmp->update($usertmp);
184
-								// TODO Que faire si update echoue car on update avec un login deja existant.
185
-							}
186
-
187
-							//$resultUpdate = $usertmp->update_ldap2dolibarr($ldap);
188
-						}
189
-						unset($usertmp);
190
-				}
191
-
192
-				if (! empty($conf->multicompany->enabled))	// We must check entity (even if sync is not active)
193
-				{
194
-					global $mc;
195
-
196
-					$usertmp=new User($db);
197
-					$usertmp->fetch('',$login);
198
-					$ret=$mc->checkRight($usertmp->id, $entitytotest);
199
-					if ($ret < 0)
200
-					{
201
-						dol_syslog("functions_ldap::check_user_password_ldap Authentification ko entity '".$entitytotest."' not allowed for user '".$usertmp->id."'");
202
-						$login=''; // force authentication failure
203
-					}
204
-					unset($usertmp);
205
-				}
206
-			}
207
-			if ($result == 1)
208
-			{
209
-				dol_syslog("functions_ldap::check_user_password_ldap Authentification ko bad user/password for '".$usertotest."'");
210
-				sleep(1);
211
-
212
-				// Load translation files required by the page
61
+        $_SESSION["dol_loginmesg"]=$langs->trans("ErrorLDAPFunctionsAreDisabledOnThisPHP").' '.$langs->trans("TryAnotherConnectionMode");
62
+        return;
63
+    }
64
+
65
+    if ($usertotest)
66
+    {
67
+        dol_syslog("functions_ldap::check_user_password_ldap usertotest=".$usertotest." passwordtotest=".preg_replace('/./','*',$passwordtotest)." entitytotest=".$entitytotest);
68
+
69
+        // If test username/password asked, we define $test=false and $login var if ok, set $_SESSION["dol_loginmesg"] if ko
70
+        $ldaphost=$dolibarr_main_auth_ldap_host;
71
+        $ldapport=$dolibarr_main_auth_ldap_port;
72
+        $ldapversion=$dolibarr_main_auth_ldap_version;
73
+        $ldapservertype=(empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype);
74
+
75
+        $ldapuserattr=$dolibarr_main_auth_ldap_login_attribute;
76
+        $ldapdn=$dolibarr_main_auth_ldap_dn;
77
+        $ldapadminlogin=$dolibarr_main_auth_ldap_admin_login;
78
+        $ldapadminpass=$dolibarr_main_auth_ldap_admin_pass;
79
+        $ldapdebug=(empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug=="false" ? false : true);
80
+
81
+        if ($ldapdebug) print "DEBUG: Logging LDAP steps<br>\n";
82
+
83
+        require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php';
84
+        $ldap=new Ldap();
85
+        $ldap->server=explode(',',$ldaphost);
86
+        $ldap->serverPort=$ldapport;
87
+        $ldap->ldapProtocolVersion=$ldapversion;
88
+        $ldap->serverType=$ldapservertype;
89
+        $ldap->searchUser=$ldapadminlogin;
90
+        $ldap->searchPassword=$ldapadminpass;
91
+
92
+        if ($ldapdebug)
93
+        {
94
+            dol_syslog("functions_ldap::check_user_password_ldap Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType);
95
+            dol_syslog("functions_ldap::check_user_password_ldap uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword);
96
+            print "DEBUG: Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType."<br>\n";
97
+            print "DEBUG: uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword."<br>\n";
98
+        }
99
+
100
+        $resultFetchLdapUser=0;
101
+
102
+        // Define $userSearchFilter
103
+        $userSearchFilter = "";
104
+        if (empty($dolibarr_main_auth_ldap_filter)) {
105
+            $userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")";
106
+        } else {
107
+            $userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter);
108
+        }
109
+
110
+        // If admin login provided
111
+        // Code to get user in LDAP from an admin connection (may differ from user connection, done later)
112
+        if ($ldapadminlogin)
113
+        {
114
+            $result=$ldap->connect_bind();
115
+            if ($result > 0)
116
+            {
117
+                $resultFetchLdapUser = $ldap->fetch($usertotest,$userSearchFilter);
118
+                //dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='.$resultFetchLdapUser);
119
+                if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) // If ok but password need to be reset
120
+                {
121
+                    dol_syslog('functions_ldap::check_user_password_ldap '.$usertotest.' must change password next logon');
122
+                    if ($ldapdebug) print "DEBUG: User ".$usertotest." must change password<br>\n";
123
+                    $ldap->close();
124
+                    sleep(1);
125
+                    $langs->load('ldap');
126
+                    $_SESSION["dol_loginmesg"]=$langs->trans("YouMustChangePassNextLogon",$usertotest,$ldap->domainFQDN);
127
+                    return '';
128
+                }
129
+            }
130
+            else
131
+            {
132
+                    if ($ldapdebug) print "DEBUG: ".$ldap->error."<br>\n";
133
+            }
134
+            $ldap->close();
135
+        }
136
+
137
+        // Forge LDAP user and password to test with them
138
+        // If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with
139
+        // admin login no exectued.
140
+        $ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn;  // Default dn (will work if LDAP accept a dn with login value inside)
141
+        // But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
142
+        // dn detected into ldapUserDN.
143
+        if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN;
144
+        $ldap->searchPassword=$passwordtotest;
145
+
146
+        // Test with this->seachUser and this->searchPassword
147
+        //print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit;
148
+        $result=$ldap->connect_bind();
149
+        if ($result > 0)
150
+        {
151
+            if ($result == 2)	// Connection is ok for user/pass into LDAP
152
+            {
153
+                dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
154
+                $login=$usertotest;
155
+
156
+                // ldap2dolibarr synchronisation
157
+                if ($login && ! empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')	// ldap2dolibarr synchronisation
158
+                {
159
+                        dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
160
+
161
+                        // On charge les attributs du user ldap
162
+                        if ($ldapdebug) print "DEBUG: login ldap = ".$login."<br>\n";
163
+                        $resultFetchLdapUser = $ldap->fetch($login,$userSearchFilter);
164
+
165
+                        if ($ldapdebug) print "DEBUG: UACF = ".join(',',$ldap->uacf)."<br>\n";
166
+                        if ($ldapdebug) print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset,'day')."<br>\n";
167
+                        if ($ldapdebug) print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime,'day')."<br>\n";
168
+
169
+                        // On recherche le user dolibarr en fonction de son SID ldap
170
+                        $sid = $ldap->getObjectSid($login);
171
+                        if ($ldapdebug) print "DEBUG: sid = ".$sid."<br>\n";
172
+
173
+                        $usertmp=new User($db);
174
+                        $resultFetchUser=$usertmp->fetch('',$login,$sid);
175
+                        if ($resultFetchUser > 0)
176
+                        {
177
+                            dol_syslog("functions_ldap::check_user_password_ldap Sync user found user id=".$usertmp->id);
178
+                            // On verifie si le login a change et on met a jour les attributs dolibarr
179
+
180
+                            if ($usertmp->login != $ldap->login && $ldap->login)
181
+                            {
182
+                                $usertmp->login = $ldap->login;
183
+                                $usertmp->update($usertmp);
184
+                                // TODO Que faire si update echoue car on update avec un login deja existant.
185
+                            }
186
+
187
+                            //$resultUpdate = $usertmp->update_ldap2dolibarr($ldap);
188
+                        }
189
+                        unset($usertmp);
190
+                }
191
+
192
+                if (! empty($conf->multicompany->enabled))	// We must check entity (even if sync is not active)
193
+                {
194
+                    global $mc;
195
+
196
+                    $usertmp=new User($db);
197
+                    $usertmp->fetch('',$login);
198
+                    $ret=$mc->checkRight($usertmp->id, $entitytotest);
199
+                    if ($ret < 0)
200
+                    {
201
+                        dol_syslog("functions_ldap::check_user_password_ldap Authentification ko entity '".$entitytotest."' not allowed for user '".$usertmp->id."'");
202
+                        $login=''; // force authentication failure
203
+                    }
204
+                    unset($usertmp);
205
+                }
206
+            }
207
+            if ($result == 1)
208
+            {
209
+                dol_syslog("functions_ldap::check_user_password_ldap Authentification ko bad user/password for '".$usertotest."'");
210
+                sleep(1);
211
+
212
+                // Load translation files required by the page
213 213
                 $langs->loadLangs(array('main', 'other'));
214 214
 
215
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
216
-			}
217
-		}
218
-		else
219
-		{
220
-			/* Login failed. Return false, together with the error code and text from
215
+                $_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
216
+            }
217
+        }
218
+        else
219
+        {
220
+            /* Login failed. Return false, together with the error code and text from
221 221
              ** the LDAP server. The common error codes and reasons are listed below :
222 222
              ** (for iPlanet, other servers may differ)
223 223
              ** 19 - Account locked out (too many invalid login attempts)
@@ -225,24 +225,24 @@  discard block
 block discarded – undo
225 225
              ** 49 - Wrong password
226 226
              ** 53 - Account inactive (manually locked out by administrator)
227 227
              */
228
-			dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '".$usertotest."'");
229
-			if (is_resource($ldap->connection))    // If connection ok but bind ko
230
-			{
231
-				$ldap->ldapErrorCode = ldap_errno($ldap->connection);
232
-				$ldap->ldapErrorText = ldap_error($ldap->connection);
233
-				dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText);
234
-			}
235
-			sleep(2);      // Anti brut force protection
236
-
237
-			// Load translation files required by the page
228
+            dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '".$usertotest."'");
229
+            if (is_resource($ldap->connection))    // If connection ok but bind ko
230
+            {
231
+                $ldap->ldapErrorCode = ldap_errno($ldap->connection);
232
+                $ldap->ldapErrorText = ldap_error($ldap->connection);
233
+                dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText);
234
+            }
235
+            sleep(2);      // Anti brut force protection
236
+
237
+            // Load translation files required by the page
238 238
             $langs->loadLangs(array('main', 'other', 'errors'));
239 239
 ;
240
-			$_SESSION["dol_loginmesg"]=($ldap->error?$ldap->error:$langs->trans("ErrorBadLoginPassword"));
241
-		}
240
+            $_SESSION["dol_loginmesg"]=($ldap->error?$ldap->error:$langs->trans("ErrorBadLoginPassword"));
241
+        }
242 242
 
243
-		$ldap->close();
244
-	}
243
+        $ldap->close();
244
+    }
245 245
 
246
-	return $login;
246
+    return $login;
247 247
 }
248 248
 
Please login to merge, or discard this patch.
Spacing   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -32,25 +32,25 @@  discard block
 block discarded – undo
32 32
  * @param   int		$entitytotest   Number of instance (always 1 if module multicompany not enabled)
33 33
  * @return	string					Login if OK, '' if KO
34 34
  */
35
-function check_user_password_ldap($usertotest,$passwordtotest,$entitytotest)
35
+function check_user_password_ldap($usertotest, $passwordtotest, $entitytotest)
36 36
 {
37
-	global $db,$conf,$langs;
37
+	global $db, $conf, $langs;
38 38
 	global $_POST;
39
-	global $dolibarr_main_auth_ldap_host,$dolibarr_main_auth_ldap_port;
40
-	global $dolibarr_main_auth_ldap_version,$dolibarr_main_auth_ldap_servertype;
41
-	global $dolibarr_main_auth_ldap_login_attribute,$dolibarr_main_auth_ldap_dn;
42
-	global $dolibarr_main_auth_ldap_admin_login,$dolibarr_main_auth_ldap_admin_pass;
39
+	global $dolibarr_main_auth_ldap_host, $dolibarr_main_auth_ldap_port;
40
+	global $dolibarr_main_auth_ldap_version, $dolibarr_main_auth_ldap_servertype;
41
+	global $dolibarr_main_auth_ldap_login_attribute, $dolibarr_main_auth_ldap_dn;
42
+	global $dolibarr_main_auth_ldap_admin_login, $dolibarr_main_auth_ldap_admin_pass;
43 43
 	global $dolibarr_main_auth_ldap_filter;
44 44
 	global $dolibarr_main_auth_ldap_debug;
45 45
 
46 46
 	// Force master entity in transversal mode
47
-	$entity=$entitytotest;
48
-	if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $entity=1;
47
+	$entity = $entitytotest;
48
+	if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $entity = 1;
49 49
 
50
-	$login='';
51
-	$resultFetchUser='';
50
+	$login = '';
51
+	$resultFetchUser = '';
52 52
 
53
-	if (! function_exists("ldap_connect"))
53
+	if (!function_exists("ldap_connect"))
54 54
 	{
55 55
 		dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP. LDAP functions are disabled on this PHP");
56 56
 		sleep(1);
@@ -58,51 +58,51 @@  discard block
 block discarded – undo
58 58
 		// Load translation files required by the page
59 59
         $langs->loadLangs(array('main', 'other'));
60 60
 
61
-		$_SESSION["dol_loginmesg"]=$langs->trans("ErrorLDAPFunctionsAreDisabledOnThisPHP").' '.$langs->trans("TryAnotherConnectionMode");
61
+		$_SESSION["dol_loginmesg"] = $langs->trans("ErrorLDAPFunctionsAreDisabledOnThisPHP").' '.$langs->trans("TryAnotherConnectionMode");
62 62
 		return;
63 63
 	}
64 64
 
65 65
 	if ($usertotest)
66 66
 	{
67
-		dol_syslog("functions_ldap::check_user_password_ldap usertotest=".$usertotest." passwordtotest=".preg_replace('/./','*',$passwordtotest)." entitytotest=".$entitytotest);
67
+		dol_syslog("functions_ldap::check_user_password_ldap usertotest=".$usertotest." passwordtotest=".preg_replace('/./', '*', $passwordtotest)." entitytotest=".$entitytotest);
68 68
 
69 69
 		// If test username/password asked, we define $test=false and $login var if ok, set $_SESSION["dol_loginmesg"] if ko
70
-		$ldaphost=$dolibarr_main_auth_ldap_host;
71
-		$ldapport=$dolibarr_main_auth_ldap_port;
72
-		$ldapversion=$dolibarr_main_auth_ldap_version;
73
-		$ldapservertype=(empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype);
70
+		$ldaphost = $dolibarr_main_auth_ldap_host;
71
+		$ldapport = $dolibarr_main_auth_ldap_port;
72
+		$ldapversion = $dolibarr_main_auth_ldap_version;
73
+		$ldapservertype = (empty($dolibarr_main_auth_ldap_servertype) ? 'openldap' : $dolibarr_main_auth_ldap_servertype);
74 74
 
75
-		$ldapuserattr=$dolibarr_main_auth_ldap_login_attribute;
76
-		$ldapdn=$dolibarr_main_auth_ldap_dn;
77
-		$ldapadminlogin=$dolibarr_main_auth_ldap_admin_login;
78
-		$ldapadminpass=$dolibarr_main_auth_ldap_admin_pass;
79
-		$ldapdebug=(empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug=="false" ? false : true);
75
+		$ldapuserattr = $dolibarr_main_auth_ldap_login_attribute;
76
+		$ldapdn = $dolibarr_main_auth_ldap_dn;
77
+		$ldapadminlogin = $dolibarr_main_auth_ldap_admin_login;
78
+		$ldapadminpass = $dolibarr_main_auth_ldap_admin_pass;
79
+		$ldapdebug = (empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug == "false" ? false : true);
80 80
 
81 81
 		if ($ldapdebug) print "DEBUG: Logging LDAP steps<br>\n";
82 82
 
83 83
 		require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php';
84
-		$ldap=new Ldap();
85
-		$ldap->server=explode(',',$ldaphost);
86
-		$ldap->serverPort=$ldapport;
87
-		$ldap->ldapProtocolVersion=$ldapversion;
88
-		$ldap->serverType=$ldapservertype;
89
-		$ldap->searchUser=$ldapadminlogin;
90
-		$ldap->searchPassword=$ldapadminpass;
84
+		$ldap = new Ldap();
85
+		$ldap->server = explode(',', $ldaphost);
86
+		$ldap->serverPort = $ldapport;
87
+		$ldap->ldapProtocolVersion = $ldapversion;
88
+		$ldap->serverType = $ldapservertype;
89
+		$ldap->searchUser = $ldapadminlogin;
90
+		$ldap->searchPassword = $ldapadminpass;
91 91
 
92 92
 		if ($ldapdebug)
93 93
 		{
94
-			dol_syslog("functions_ldap::check_user_password_ldap Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType);
94
+			dol_syslog("functions_ldap::check_user_password_ldap Server:".join(',', $ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType);
95 95
 			dol_syslog("functions_ldap::check_user_password_ldap uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword);
96
-			print "DEBUG: Server:".join(',',$ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType."<br>\n";
96
+			print "DEBUG: Server:".join(',', $ldap->server).", Port:".$ldap->serverPort.", Protocol:".$ldap->ldapProtocolVersion.", Type:".$ldap->serverType."<br>\n";
97 97
 			print "DEBUG: uid/samacountname=".$ldapuserattr.", dn=".$ldapdn.", Admin:".$ldap->searchUser.", Pass:".$ldap->searchPassword."<br>\n";
98 98
 		}
99 99
 
100
-		$resultFetchLdapUser=0;
100
+		$resultFetchLdapUser = 0;
101 101
 
102 102
 		// Define $userSearchFilter
103 103
 		$userSearchFilter = "";
104 104
 		if (empty($dolibarr_main_auth_ldap_filter)) {
105
-			$userSearchFilter = "(" . $ldapuserattr . "=" . $usertotest . ")";
105
+			$userSearchFilter = "(".$ldapuserattr."=".$usertotest.")";
106 106
 		} else {
107 107
 			$userSearchFilter = str_replace('%1%', $usertotest, $dolibarr_main_auth_ldap_filter);
108 108
 		}
@@ -111,10 +111,10 @@  discard block
 block discarded – undo
111 111
 		// Code to get user in LDAP from an admin connection (may differ from user connection, done later)
112 112
 		if ($ldapadminlogin)
113 113
 		{
114
-			$result=$ldap->connect_bind();
114
+			$result = $ldap->connect_bind();
115 115
 			if ($result > 0)
116 116
 			{
117
-				$resultFetchLdapUser = $ldap->fetch($usertotest,$userSearchFilter);
117
+				$resultFetchLdapUser = $ldap->fetch($usertotest, $userSearchFilter);
118 118
 				//dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='.$resultFetchLdapUser);
119 119
 				if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) // If ok but password need to be reset
120 120
 				{
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
 					$ldap->close();
124 124
 					sleep(1);
125 125
 					$langs->load('ldap');
126
-					$_SESSION["dol_loginmesg"]=$langs->trans("YouMustChangePassNextLogon",$usertotest,$ldap->domainFQDN);
126
+					$_SESSION["dol_loginmesg"] = $langs->trans("YouMustChangePassNextLogon", $usertotest, $ldap->domainFQDN);
127 127
 					return '';
128 128
 				}
129 129
 			}
@@ -137,41 +137,41 @@  discard block
 block discarded – undo
137 137
 		// Forge LDAP user and password to test with them
138 138
 		// If LDAP need a dn with login like "uid=jbloggs,ou=People,dc=foo,dc=com", default dn may work even if previous code with
139 139
 		// admin login no exectued.
140
-		$ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn;  // Default dn (will work if LDAP accept a dn with login value inside)
140
+		$ldap->searchUser = $ldapuserattr."=".$usertotest.",".$ldapdn; // Default dn (will work if LDAP accept a dn with login value inside)
141 141
 		// But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
142 142
 		// dn detected into ldapUserDN.
143 143
 		if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN;
144
-		$ldap->searchPassword=$passwordtotest;
144
+		$ldap->searchPassword = $passwordtotest;
145 145
 
146 146
 		// Test with this->seachUser and this->searchPassword
147 147
 		//print $resultFetchLdapUser."-".$ldap->ldapUserDN."-".$ldap->searchUser.'-'.$ldap->searchPassword;exit;
148
-		$result=$ldap->connect_bind();
148
+		$result = $ldap->connect_bind();
149 149
 		if ($result > 0)
150 150
 		{
151 151
 			if ($result == 2)	// Connection is ok for user/pass into LDAP
152 152
 			{
153 153
 				dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
154
-				$login=$usertotest;
154
+				$login = $usertotest;
155 155
 
156 156
 				// ldap2dolibarr synchronisation
157
-				if ($login && ! empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')	// ldap2dolibarr synchronisation
157
+				if ($login && !empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')	// ldap2dolibarr synchronisation
158 158
 				{
159 159
 						dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
160 160
 
161 161
 						// On charge les attributs du user ldap
162 162
 						if ($ldapdebug) print "DEBUG: login ldap = ".$login."<br>\n";
163
-						$resultFetchLdapUser = $ldap->fetch($login,$userSearchFilter);
163
+						$resultFetchLdapUser = $ldap->fetch($login, $userSearchFilter);
164 164
 
165
-						if ($ldapdebug) print "DEBUG: UACF = ".join(',',$ldap->uacf)."<br>\n";
166
-						if ($ldapdebug) print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset,'day')."<br>\n";
167
-						if ($ldapdebug) print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime,'day')."<br>\n";
165
+						if ($ldapdebug) print "DEBUG: UACF = ".join(',', $ldap->uacf)."<br>\n";
166
+						if ($ldapdebug) print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset, 'day')."<br>\n";
167
+						if ($ldapdebug) print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime, 'day')."<br>\n";
168 168
 
169 169
 						// On recherche le user dolibarr en fonction de son SID ldap
170 170
 						$sid = $ldap->getObjectSid($login);
171 171
 						if ($ldapdebug) print "DEBUG: sid = ".$sid."<br>\n";
172 172
 
173
-						$usertmp=new User($db);
174
-						$resultFetchUser=$usertmp->fetch('',$login,$sid);
173
+						$usertmp = new User($db);
174
+						$resultFetchUser = $usertmp->fetch('', $login, $sid);
175 175
 						if ($resultFetchUser > 0)
176 176
 						{
177 177
 							dol_syslog("functions_ldap::check_user_password_ldap Sync user found user id=".$usertmp->id);
@@ -189,17 +189,17 @@  discard block
 block discarded – undo
189 189
 						unset($usertmp);
190 190
 				}
191 191
 
192
-				if (! empty($conf->multicompany->enabled))	// We must check entity (even if sync is not active)
192
+				if (!empty($conf->multicompany->enabled))	// We must check entity (even if sync is not active)
193 193
 				{
194 194
 					global $mc;
195 195
 
196
-					$usertmp=new User($db);
197
-					$usertmp->fetch('',$login);
198
-					$ret=$mc->checkRight($usertmp->id, $entitytotest);
196
+					$usertmp = new User($db);
197
+					$usertmp->fetch('', $login);
198
+					$ret = $mc->checkRight($usertmp->id, $entitytotest);
199 199
 					if ($ret < 0)
200 200
 					{
201 201
 						dol_syslog("functions_ldap::check_user_password_ldap Authentification ko entity '".$entitytotest."' not allowed for user '".$usertmp->id."'");
202
-						$login=''; // force authentication failure
202
+						$login = ''; // force authentication failure
203 203
 					}
204 204
 					unset($usertmp);
205 205
 				}
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 				// Load translation files required by the page
213 213
                 $langs->loadLangs(array('main', 'other'));
214 214
 
215
-				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
215
+				$_SESSION["dol_loginmesg"] = $langs->trans("ErrorBadLoginPassword");
216 216
 			}
217 217
 		}
218 218
 		else
@@ -232,12 +232,12 @@  discard block
 block discarded – undo
232 232
 				$ldap->ldapErrorText = ldap_error($ldap->connection);
233 233
 				dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText);
234 234
 			}
235
-			sleep(2);      // Anti brut force protection
235
+			sleep(2); // Anti brut force protection
236 236
 
237 237
 			// Load translation files required by the page
238 238
             $langs->loadLangs(array('main', 'other', 'errors'));
239 239
 ;
240
-			$_SESSION["dol_loginmesg"]=($ldap->error?$ldap->error:$langs->trans("ErrorBadLoginPassword"));
240
+			$_SESSION["dol_loginmesg"] = ($ldap->error ? $ldap->error : $langs->trans("ErrorBadLoginPassword"));
241 241
 		}
242 242
 
243 243
 		$ldap->close();
Please login to merge, or discard this patch.
Braces   +52 added lines, -24 removed lines patch added patch discarded remove patch
@@ -45,7 +45,9 @@  discard block
 block discarded – undo
45 45
 
46 46
 	// Force master entity in transversal mode
47 47
 	$entity=$entitytotest;
48
-	if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) $entity=1;
48
+	if (! empty($conf->multicompany->enabled) && ! empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) {
49
+	    $entity=1;
50
+	}
49 51
 
50 52
 	$login='';
51 53
 	$resultFetchUser='';
@@ -78,7 +80,9 @@  discard block
 block discarded – undo
78 80
 		$ldapadminpass=$dolibarr_main_auth_ldap_admin_pass;
79 81
 		$ldapdebug=(empty($dolibarr_main_auth_ldap_debug) || $dolibarr_main_auth_ldap_debug=="false" ? false : true);
80 82
 
81
-		if ($ldapdebug) print "DEBUG: Logging LDAP steps<br>\n";
83
+		if ($ldapdebug) {
84
+		    print "DEBUG: Logging LDAP steps<br>\n";
85
+		}
82 86
 
83 87
 		require_once DOL_DOCUMENT_ROOT.'/core/class/ldap.class.php';
84 88
 		$ldap=new Ldap();
@@ -116,20 +120,25 @@  discard block
 block discarded – undo
116 120
 			{
117 121
 				$resultFetchLdapUser = $ldap->fetch($usertotest,$userSearchFilter);
118 122
 				//dol_syslog('functions_ldap::check_user_password_ldap resultFetchLdapUser='.$resultFetchLdapUser);
119
-				if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) // If ok but password need to be reset
123
+				if ($resultFetchLdapUser > 0 && $ldap->pwdlastset == 0) {
124
+				    // If ok but password need to be reset
120 125
 				{
121
-					dol_syslog('functions_ldap::check_user_password_ldap '.$usertotest.' must change password next logon');
122
-					if ($ldapdebug) print "DEBUG: User ".$usertotest." must change password<br>\n";
126
+					dol_syslog('functions_ldap::check_user_password_ldap '.$usertotest.' must change password next logon');
127
+				}
128
+					if ($ldapdebug) {
129
+					    print "DEBUG: User ".$usertotest." must change password<br>\n";
130
+					}
123 131
 					$ldap->close();
124 132
 					sleep(1);
125 133
 					$langs->load('ldap');
126 134
 					$_SESSION["dol_loginmesg"]=$langs->trans("YouMustChangePassNextLogon",$usertotest,$ldap->domainFQDN);
127 135
 					return '';
128 136
 				}
129
-			}
130
-			else
137
+			} else
131 138
 			{
132
-				 if ($ldapdebug) print "DEBUG: ".$ldap->error."<br>\n";
139
+				 if ($ldapdebug) {
140
+				     print "DEBUG: ".$ldap->error."<br>\n";
141
+				 }
133 142
 			}
134 143
 			$ldap->close();
135 144
 		}
@@ -140,7 +149,9 @@  discard block
 block discarded – undo
140 149
 		$ldap->searchUser=$ldapuserattr."=".$usertotest.",".$ldapdn;  // Default dn (will work if LDAP accept a dn with login value inside)
141 150
 		// But if LDAP need a dn with name like "cn=Jhon Bloggs,ou=People,dc=foo,dc=com", previous part must have been executed to have
142 151
 		// dn detected into ldapUserDN.
143
-		if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) $ldap->searchUser = $ldap->ldapUserDN;
152
+		if ($resultFetchLdapUser && !empty($ldap->ldapUserDN)) {
153
+		    $ldap->searchUser = $ldap->ldapUserDN;
154
+		}
144 155
 		$ldap->searchPassword=$passwordtotest;
145 156
 
146 157
 		// Test with this->seachUser and this->searchPassword
@@ -148,27 +159,41 @@  discard block
 block discarded – undo
148 159
 		$result=$ldap->connect_bind();
149 160
 		if ($result > 0)
150 161
 		{
151
-			if ($result == 2)	// Connection is ok for user/pass into LDAP
162
+			if ($result == 2) {
163
+			    // Connection is ok for user/pass into LDAP
152 164
 			{
153
-				dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
165
+				dol_syslog("functions_ldap::check_user_password_ldap Authentification ok");
166
+			}
154 167
 				$login=$usertotest;
155 168
 
156 169
 				// ldap2dolibarr synchronisation
157
-				if ($login && ! empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr')	// ldap2dolibarr synchronisation
170
+				if ($login && ! empty($conf->ldap->enabled) && $conf->global->LDAP_SYNCHRO_ACTIVE == 'ldap2dolibarr') {
171
+				    // ldap2dolibarr synchronisation
158 172
 				{
159
-						dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
173
+						dol_syslog("functions_ldap::check_user_password_ldap Sync ldap2dolibarr");
174
+				}
160 175
 
161 176
 						// On charge les attributs du user ldap
162
-						if ($ldapdebug) print "DEBUG: login ldap = ".$login."<br>\n";
177
+						if ($ldapdebug) {
178
+						    print "DEBUG: login ldap = ".$login."<br>\n";
179
+						}
163 180
 						$resultFetchLdapUser = $ldap->fetch($login,$userSearchFilter);
164 181
 
165
-						if ($ldapdebug) print "DEBUG: UACF = ".join(',',$ldap->uacf)."<br>\n";
166
-						if ($ldapdebug) print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset,'day')."<br>\n";
167
-						if ($ldapdebug) print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime,'day')."<br>\n";
182
+						if ($ldapdebug) {
183
+						    print "DEBUG: UACF = ".join(',',$ldap->uacf)."<br>\n";
184
+						}
185
+						if ($ldapdebug) {
186
+						    print "DEBUG: pwdLastSet = ".dol_print_date($ldap->pwdlastset,'day')."<br>\n";
187
+						}
188
+						if ($ldapdebug) {
189
+						    print "DEBUG: badPasswordTime = ".dol_print_date($ldap->badpwdtime,'day')."<br>\n";
190
+						}
168 191
 
169 192
 						// On recherche le user dolibarr en fonction de son SID ldap
170 193
 						$sid = $ldap->getObjectSid($login);
171
-						if ($ldapdebug) print "DEBUG: sid = ".$sid."<br>\n";
194
+						if ($ldapdebug) {
195
+						    print "DEBUG: sid = ".$sid."<br>\n";
196
+						}
172 197
 
173 198
 						$usertmp=new User($db);
174 199
 						$resultFetchUser=$usertmp->fetch('',$login,$sid);
@@ -189,9 +214,11 @@  discard block
 block discarded – undo
189 214
 						unset($usertmp);
190 215
 				}
191 216
 
192
-				if (! empty($conf->multicompany->enabled))	// We must check entity (even if sync is not active)
217
+				if (! empty($conf->multicompany->enabled)) {
218
+				    // We must check entity (even if sync is not active)
193 219
 				{
194
-					global $mc;
220
+					global $mc;
221
+				}
195 222
 
196 223
 					$usertmp=new User($db);
197 224
 					$usertmp->fetch('',$login);
@@ -214,8 +241,7 @@  discard block
 block discarded – undo
214 241
 
215 242
 				$_SESSION["dol_loginmesg"]=$langs->trans("ErrorBadLoginPassword");
216 243
 			}
217
-		}
218
-		else
244
+		} else
219 245
 		{
220 246
 			/* Login failed. Return false, together with the error code and text from
221 247
              ** the LDAP server. The common error codes and reasons are listed below :
@@ -226,9 +252,11 @@  discard block
 block discarded – undo
226 252
              ** 53 - Account inactive (manually locked out by administrator)
227 253
              */
228 254
 			dol_syslog("functions_ldap::check_user_password_ldap Authentification ko failed to connect to LDAP for '".$usertotest."'");
229
-			if (is_resource($ldap->connection))    // If connection ok but bind ko
255
+			if (is_resource($ldap->connection)) {
256
+			    // If connection ok but bind ko
230 257
 			{
231
-				$ldap->ldapErrorCode = ldap_errno($ldap->connection);
258
+				$ldap->ldapErrorCode = ldap_errno($ldap->connection);
259
+			}
232 260
 				$ldap->ldapErrorText = ldap_error($ldap->connection);
233 261
 				dol_syslog("functions_ldap::check_user_password_ldap ".$ldap->ldapErrorCode." ".$ldap->ldapErrorText);
234 262
 			}
Please login to merge, or discard this patch.
Helpers/login/functions_forceuser.php 3 patches
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -34,16 +34,16 @@
 block discarded – undo
34 34
  */
35 35
 function check_user_password_forceuser($usertotest,$passwordtotest,$entitytotest)
36 36
 {
37
-	// Variable dolibarr_auto_user must be defined in conf.php file
38
-	global $dolibarr_auto_user;
37
+    // Variable dolibarr_auto_user must be defined in conf.php file
38
+    global $dolibarr_auto_user;
39 39
 
40
-	dol_syslog("functions_forceuser::check_user_password_forceuser");
40
+    dol_syslog("functions_forceuser::check_user_password_forceuser");
41 41
 
42
-	$login=$dolibarr_auto_user;
43
-	if (empty($login)) $login='auto';
42
+    $login=$dolibarr_auto_user;
43
+    if (empty($login)) $login='auto';
44 44
 
45
-	if ($_SESSION["dol_loginmesg"]) $login='';
45
+    if ($_SESSION["dol_loginmesg"]) $login='';
46 46
 
47
-	dol_syslog("functions_forceuser::check_user_password_forceuser ok. forced user = ".$login);
48
-	return $login;
47
+    dol_syslog("functions_forceuser::check_user_password_forceuser ok. forced user = ".$login);
48
+    return $login;
49 49
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -32,17 +32,17 @@
 block discarded – undo
32 32
  * @param   int		$entitytotest   Number of instance (always 1 if module multicompany not enabled)
33 33
  * @return	string					Login if OK, '' if KO
34 34
  */
35
-function check_user_password_forceuser($usertotest,$passwordtotest,$entitytotest)
35
+function check_user_password_forceuser($usertotest, $passwordtotest, $entitytotest)
36 36
 {
37 37
 	// Variable dolibarr_auto_user must be defined in conf.php file
38 38
 	global $dolibarr_auto_user;
39 39
 
40 40
 	dol_syslog("functions_forceuser::check_user_password_forceuser");
41 41
 
42
-	$login=$dolibarr_auto_user;
43
-	if (empty($login)) $login='auto';
42
+	$login = $dolibarr_auto_user;
43
+	if (empty($login)) $login = 'auto';
44 44
 
45
-	if ($_SESSION["dol_loginmesg"]) $login='';
45
+	if ($_SESSION["dol_loginmesg"]) $login = '';
46 46
 
47 47
 	dol_syslog("functions_forceuser::check_user_password_forceuser ok. forced user = ".$login);
48 48
 	return $login;
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -40,9 +40,13 @@
 block discarded – undo
40 40
 	dol_syslog("functions_forceuser::check_user_password_forceuser");
41 41
 
42 42
 	$login=$dolibarr_auto_user;
43
-	if (empty($login)) $login='auto';
43
+	if (empty($login)) {
44
+	    $login='auto';
45
+	}
44 46
 
45
-	if ($_SESSION["dol_loginmesg"]) $login='';
47
+	if ($_SESSION["dol_loginmesg"]) {
48
+	    $login='';
49
+	}
46 50
 
47 51
 	dol_syslog("functions_forceuser::check_user_password_forceuser ok. forced user = ".$login);
48 52
 	return $login;
Please login to merge, or discard this patch.
Helpers/login/functions_http.php 2 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -12,13 +12,13 @@
 block discarded – undo
12 12
 */
13 13
 function check_user_password_http($usertotest,$passwordtotest,$entitytotest)
14 14
 {
15
-	DolUtils::dol_syslog("functions_http::check_user_password_http _SERVER[REMOTE_USER]=" . (empty($_SERVER["REMOTE_USER"]) ? '' : $_SERVER["REMOTE_USER"]));
15
+    DolUtils::dol_syslog("functions_http::check_user_password_http _SERVER[REMOTE_USER]=" . (empty($_SERVER["REMOTE_USER"]) ? '' : $_SERVER["REMOTE_USER"]));
16 16
 
17 17
     $login='';
18
-	if (! empty($_SERVER["REMOTE_USER"]))
19
-	{
20
-		$login=$_SERVER["REMOTE_USER"];
21
-	}
18
+    if (! empty($_SERVER["REMOTE_USER"]))
19
+    {
20
+        $login=$_SERVER["REMOTE_USER"];
21
+    }
22 22
 
23
-	return $login;
23
+    return $login;
24 24
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -10,14 +10,14 @@
 block discarded – undo
10 10
  * @param   int		$entitytotest   Number of instance (always 1 if module multicompany not enabled)
11 11
  * @return	string					Login if OK, '' if KO
12 12
 */
13
-function check_user_password_http($usertotest,$passwordtotest,$entitytotest)
13
+function check_user_password_http($usertotest, $passwordtotest, $entitytotest)
14 14
 {
15
-	DolUtils::dol_syslog("functions_http::check_user_password_http _SERVER[REMOTE_USER]=" . (empty($_SERVER["REMOTE_USER"]) ? '' : $_SERVER["REMOTE_USER"]));
15
+	DolUtils::dol_syslog("functions_http::check_user_password_http _SERVER[REMOTE_USER]=".(empty($_SERVER["REMOTE_USER"]) ? '' : $_SERVER["REMOTE_USER"]));
16 16
 
17
-    $login='';
18
-	if (! empty($_SERVER["REMOTE_USER"]))
17
+    $login = '';
18
+	if (!empty($_SERVER["REMOTE_USER"]))
19 19
 	{
20
-		$login=$_SERVER["REMOTE_USER"];
20
+		$login = $_SERVER["REMOTE_USER"];
21 21
 	}
22 22
 
23 23
 	return $login;
Please login to merge, or discard this patch.