Passed
Push — master ( 65bdac...4e88da )
by Alxarafe
32:38
created

DolUtils::GETPOST()   F

Complexity

Conditions 141
Paths > 20000

Size

Total Lines 354
Code Lines 224

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 141
eloc 224
nc 2070163
nop 6
dl 0
loc 354
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2000-2007	Rodolphe Quiedeville			<[email protected]>
3
 * Copyright (C) 2003		Jean-Louis Bergamo			<[email protected]>
4
 * Copyright (C) 2004-2018	Laurent Destailleur			<[email protected]>
5
 * Copyright (C) 2004		Sebastien Di Cintio			<[email protected]>
6
 * Copyright (C) 2004		Benoit Mortier				<[email protected]>
7
 * Copyright (C) 2004		Christophe Combelles			<[email protected]>
8
 * Copyright (C) 2005-2017	Regis Houssin				<[email protected]>
9
 * Copyright (C) 2008		Raphael Bertrand (Resultic)	<[email protected]>
10
 * Copyright (C) 2010-2018	Juanjo Menent				<[email protected]>
11
 * Copyright (C) 2013		Cédric Salvador				<[email protected]>
12
 * Copyright (C) 2013-2017	Alexandre Spangaro			<[email protected]>
13
 * Copyright (C) 2014		Cédric GROSS					<[email protected]>
14
 * Copyright (C) 2014-2015	Marcos García				<[email protected]>
15
 * Copyright (C) 2015		Jean-François Ferry			<[email protected]>
16
 * Copyright (C) 2018       Frédéric France             <[email protected]>
17
 * Copyright (C) 2018-2019  Alxarafe                    <[email protected]>
18
 *
19
 * This program is free software; you can redistribute it and/or modify
20
 * it under the terms of the GNU General Public License as published by
21
 * the Free Software Foundation; either version 3 of the License, or
22
 * (at your option) any later version.
23
 *
24
 * This program is distributed in the hope that it will be useful,
25
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
26
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27
 * GNU General Public License for more details.
28
 *
29
 * You should have received a copy of the GNU General Public License
30
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
31
 * or see http://www.gnu.org/
32
 */
33
namespace Alixar\Helpers;
34
35
// include_once DOL_BASE_PATH . '/core/lib/json.lib.php';
36
use Alixar\Helpers\Security;
37
use Mobile_Detect;
38
39
class DolUtils
40
{
41
42
    /**
43
     * Function to return value of a static property when class
44
     * name is dynamically defined (not hard coded).
45
     * This is because $myclass::$myvar works from PHP 5.3.0+ only
46
     *
47
     * @param	string 	$class		Class name
48
     * @param 	string 	$member		Name of property
49
     * @return 	mixed				Return value of static property
50
     * @deprecated Dolibarr now requires 5.3.0+, use $class::$property syntax
51
     * @see https://php.net/manual/language.oop5.static.php
52
     */
53
    static function getStaticMember($class, $member)
54
    {
55
        dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
56
57
        // This part is deprecated. Uncomment if for php 5.2.*, and comment next isset class::member
58
        /* if (version_compare(phpversion(), '5.3.0', '<'))
59
          {
60
          if (is_object($class)) $class = get_class($class);
61
          $classObj = new ReflectionClass($class);
62
          $result = null;
63
64
          $found=0;
65
          foreach($classObj->getStaticProperties() as $prop => $value)
66
          {
67
          if ($prop == $member)
68
          {
69
          $result = $value;
70
          $found++;
71
          break;
72
          }
73
          }
74
75
          if ($found) return $result;
76
          } */
77
78
        if (isset($class::$member))
0 ignored issues
show
Bug introduced by alxarafe
The property member does not exist on string.
Loading history...
79
            return $class::$member;
80
        dol_print_error('', 'Try to get a static member "' . $member . '" in class "' . $class . '" that does not exists or is not static.');
81
        return null;
82
    }
83
84
    /**
85
     * Return a DoliDB instance (database handler).
86
     *
87
     * @param   string	$type		Type of database (mysql, pgsql...)
88
     * @param	string	$host		Address of database server
89
     * @param	string	$user		Nom de l'utilisateur autorise
90
     * @param	string	$pass		Mot de passe
91
     * @param	string	$name		Nom de la database
92
     * @param	int		$port		Port of database server
93
     * @return	DoliDB				A DoliDB instance
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Helpers\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
94
     */
95
    static function getDoliDBInstance($type, $host, $user, $pass, $name, $port)
96
    {
97
        require_once DOL_BASE_PATH . "/core/db/" . $type . '.class.php';
98
99
        $class = 'DoliDB' . ucfirst($type);
100
        $dolidb = new $class($type, $host, $user, $pass, $name, $port);
101
        return $dolidb;
102
    }
103
104
    /**
105
     * 	Get list of entity id to use.
106
     *
107
     * 	@param	string	$element		Current element
108
     * 									'societe', 'socpeople', 'actioncomm', 'agenda', 'resource',
109
     * 									'product', 'productprice', 'stock',
110
     * 									'propal', 'supplier_proposal', 'invoice', 'facture_fourn', 'payment_various',
111
     * 									'categorie', 'bank_account', 'bank_account', 'adherent', 'user',
112
     * 									'commande', 'commande_fournisseur', 'expedition', 'intervention', 'survey',
113
     * 									'contract', 'tax', 'expensereport', 'holiday', 'multicurrency', 'project',
114
     * 									'email_template', 'event', 'donation'
115
     * 									'c_paiement', 'c_payment_term', ...
116
     * 	@param	int		$shared			0=Return id of current entity only,
117
     * 									1=Return id of current entity + shared entities (default)
118
     *  @param	object	$currentobject	Current object if needed
119
     * 	@return	mixed				Entity id(s) to use
120
     */
121
    static function getEntity($element, $shared = 1, $currentobject = null)
122
    {
123
        //// global Globals::$conf, $mc;
124
125
        if (is_object($mc)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $mc seems to be never defined.
Loading history...
126
            return $mc->getEntity($element, $shared, $currentobject);
127
        } else {
128
            $out = '';
129
            $addzero = array('user', 'usergroup', 'c_email_templates', 'email_template', 'default_values');
130
            if (in_array($element, $addzero))
131
                $out .= '0,';
132
            $out .= Globals::$conf->entity;
133
            return $out;
134
        }
135
    }
136
137
    /**
138
     * Return information about user browser
139
     *
140
     * Returns array with the following format:
141
     * array(
142
     *  'browsername' => Browser name (firefox|chrome|iceweasel|epiphany|safari|opera|ie|unknown)
143
     *  'browserversion' => Browser version. Empty if unknown
144
     *  'browseros' => Set with mobile OS (android|blackberry|ios|palm|symbian|webos|maemo|windows|unknown)
145
     *  'layout' => (tablet|phone|classic)
146
     *  'phone' => empty if not mobile, (android|blackberry|ios|palm|unknown) if mobile
147
     *  'tablet' => true/false
148
     * )
149
     *
150
     * @param string $user_agent Content of $_SERVER["HTTP_USER_AGENT"] variable
151
     * @return	array Check function documentation
152
     */
153
    static function getBrowserInfo($user_agent)
154
    {
155
        //include_once BASE_PATH . '/vendor/mobiledetect/mobiledetectlib/Mobile_Detect.php';
156
157
        $name = 'unknown';
158
        $version = '';
159
        $os = 'unknown';
160
        $phone = '';
161
162
        $detectmobile = new Mobile_Detect(null, $user_agent);
163
        $tablet = $detectmobile->isTablet();
164
165
        if ($detectmobile->isMobile()) {
166
167
            $phone = 'unknown';
168
169
            // If phone/smartphone, we set phone os name.
170
            if ($detectmobile->is('AndroidOS')) {
171
                $os = $phone = 'android';
172
            } elseif ($detectmobile->is('BlackBerryOS')) {
173
                $os = $phone = 'blackberry';
174
            } elseif ($detectmobile->is('iOS')) {
175
                $os = 'ios';
176
                $phone = 'iphone';
177
            } elseif ($detectmobile->is('PalmOS')) {
178
                $os = $phone = 'palm';
179
            } elseif ($detectmobile->is('SymbianOS')) {
180
                $os = 'symbian';
181
            } elseif ($detectmobile->is('webOS')) {
182
                $os = 'webos';
183
            } elseif ($detectmobile->is('MaemoOS')) {
184
                $os = 'maemo';
185
            } elseif ($detectmobile->is('WindowsMobileOS') || $detectmobile->is('WindowsPhoneOS')) {
186
                $os = 'windows';
187
            }
188
        }
189
190
        // OS
191
        if (preg_match('/linux/i', $user_agent)) {
192
            $os = 'linux';
193
        } elseif (preg_match('/macintosh/i', $user_agent)) {
194
            $os = 'macintosh';
195
        } elseif (preg_match('/windows/i', $user_agent)) {
196
            $os = 'windows';
197
        }
198
199
        // Name
200
        if (preg_match('/firefox(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
201
            $name = 'firefox';
202
            $version = $reg[2];
203
        } elseif (preg_match('/edge(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
204
            $name = 'edge';
205
            $version = $reg[2];
206
        } elseif (preg_match('/chrome(\/|\s)([\d\.]+)/i', $user_agent, $reg)) {
207
            $name = 'chrome';
208
            $version = $reg[2];
209
        }    // we can have 'chrome (Mozilla...) chrome x.y' in one string
210
        elseif (preg_match('/chrome/i', $user_agent, $reg)) {
211
            $name = 'chrome';
212
        } elseif (preg_match('/iceweasel/i', $user_agent)) {
213
            $name = 'iceweasel';
214
        } elseif (preg_match('/epiphany/i', $user_agent)) {
215
            $name = 'epiphany';
216
        } elseif (preg_match('/safari(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
217
            $name = 'safari';
218
            $version = $reg[2];
219
        } // Safari is often present in string for mobile but its not.
220
        elseif (preg_match('/opera(\/|\s)([\d\.]*)/i', $user_agent, $reg)) {
221
            $name = 'opera';
222
            $version = $reg[2];
223
        } elseif (preg_match('/(MSIE\s([0-9]+\.[0-9]))|.*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
224
            $name = 'ie';
225
            $version = end($reg);
226
        }    // MS products at end
227
        elseif (preg_match('/(Windows NT\s([0-9]+\.[0-9])).*(Trident\/[0-9]+.[0-9];.*rv:([0-9]+\.[0-9]+))/i', $user_agent, $reg)) {
228
            $name = 'ie';
229
            $version = end($reg);
230
        }    // MS products at end
231
        elseif (preg_match('/l(i|y)n(x|ks)(\(|\/|\s)*([\d\.]+)/i', $user_agent, $reg)) {
232
            $name = 'lynxlinks';
233
            $version = $reg[4];
234
        }
235
236
        if ($tablet) {
237
            $layout = 'tablet';
238
        } elseif ($phone) {
239
            $layout = 'phone';
240
        } else {
241
            $layout = 'classic';
242
        }
243
244
        return array(
245
            'browsername' => $name,
246
            'browserversion' => $version,
247
            'browseros' => $os,
248
            'layout' => $layout,
249
            'phone' => $phone,
250
            'tablet' => $tablet
251
        );
252
    }
253
254
    /**
255
     *  Function called at end of web php process
256
     *
257
     *  @return	void
258
     */
259
    static function dol_shutdown()
260
    {
261
       // global Globals::$conf, $user, $langs, $db;
262
        $disconnectdone = false;
263
        $depth = 0;
264
        if (is_object($db) && !empty($db->connected)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $db seems to be never defined.
Loading history...
265
            $depth = $db->transaction_opened;
266
            $disconnectdone = $db->close();
267
        }
268
        dol_syslog("--- End access to " . $_SERVER["PHP_SELF"] . (($disconnectdone && $depth) ? ' (Warn: db disconnection forced, transaction depth was ' . $depth . ')' : ''), (($disconnectdone && $depth) ? LOG_WARNING : LOG_INFO));
269
    }
270
271
    /**
272
     * Return true if we are in a context of submitting a parameter
273
     *
274
     * @param 	string	$paramname		Name or parameter to test
275
     * @return 	boolean					True if we have just submit a POST or GET request with the parameter provided (even if param is empty)
276
     */
277
    static function GETPOSTISSET($paramname)
278
    {
279
        return (isset($_POST[$paramname]) || isset($_GET[$paramname]));
280
    }
281
282
    /**
283
     *  Return value of a param into GET or POST supervariable.
284
     *  Use the property $user->default_values[path]['creatform'] and/or $user->default_values[path]['filters'] and/or $user->default_values[path]['sortorder']
285
     *  Note: The property $user->default_values is loaded by main.php when loading the user.
286
     *
287
     *  @param  string  $paramname   Name of parameter to found
288
     *  @param  string  $check	     Type of check
289
     *                               ''=no check (deprecated)
290
     *                               'none'=no check (only for param that should have very rich content)
291
     *                               'int'=check it's numeric (integer or float)
292
     *                               'intcomma'=check it's integer+comma ('1,2,3,4...')
293
     *                               'alpha'=check it's text and sign
294
     *                               'aZ'=check it's a-z only
295
     *                               'aZ09'=check it's simple alpha string (recommended for keys)
296
     *                               'array'=check it's array
297
     *                               'san_alpha'=Use filter_var with FILTER_SANITIZE_STRING (do not use this for free text string)
298
     *                               'nohtml', 'alphanohtml'=check there is no html content
299
     *                               'custom'= custom filter specify $filter and $options)
300
     *  @param	int		$method	     Type of method (0 = get then post, 1 = only get, 2 = only post, 3 = post then get, 4 = post then get then cookie)
301
     *  @param  int     $filter      Filter to apply when $check is set to 'custom'. (See http://php.net/manual/en/filter.filters.php for détails)
302
     *  @param  mixed   $options     Options to pass to filter_var when $check is set to 'custom'
303
     *  @param	string	$noreplace	 Force disable of replacement of __xxx__ strings.
304
     *  @return string|string[]      Value found (string or array), or '' if check fails
305
     */
306
    static function GETPOST($paramname, $check = 'none', $method = 0, $filter = null, $options = null, $noreplace = 0)
307
    {
308
       // global $mysoc, $user, Globals::$conf;
309
310
        if (empty($paramname))
311
            return 'BadFirstParameterForDolUtils::GETPOST';
312
        if (empty($check)) {
313
            dol_syslog("Deprecated use of DolUtils::GETPOST, called with 1st param = " . $paramname . " and 2nd param is '', when calling page " . $_SERVER["PHP_SELF"], LOG_WARNING);
314
        // Enable this line to know who call the DolUtils::GETPOST with '' $check parameter.
315
        //var_dump(debug_backtrace()[0]);
316
        }
317
318
        if (empty($method))
319
            $out = isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_POST[$paramname]) ? $_POST[$paramname] : '');
320
        elseif ($method == 1)
321
            $out = isset($_GET[$paramname]) ? $_GET[$paramname] : '';
322
        elseif ($method == 2)
323
            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : '';
324
        elseif ($method == 3)
325
            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : '');
326
        elseif ($method == 4)
327
            $out = isset($_POST[$paramname]) ? $_POST[$paramname] : (isset($_GET[$paramname]) ? $_GET[$paramname] : (isset($_COOKIE[$paramname]) ? $_COOKIE[$paramname] : ''));
328
        else
329
            return 'BadThirdParameterForDolUtils::GETPOST';
330
331
        if (empty($method) || $method == 3 || $method == 4) {
332
            $relativepathstring = $_SERVER["PHP_SELF"];
333
            // Clean $relativepathstring
334
            if (constant('DOL_BASE_URI'))
335
                $relativepathstring = preg_replace('/^' . preg_quote(constant('DOL_BASE_URI'), '/') . '/', '', $relativepathstring);
336
            $relativepathstring = preg_replace('/^\//', '', $relativepathstring);
337
            $relativepathstring = preg_replace('/^custom\//', '', $relativepathstring);
338
            //var_dump($relativepathstring);
339
            //var_dump($user->default_values);
340
            // Code for search criteria persistence.
341
            // Retrieve values if restore_lastsearch_values
342
            if (!empty($_GET['restore_lastsearch_values'])) {        // Use $_GET here and not DolUtils::GETPOST
343
                if (!empty($_SESSION['lastsearch_values_' . $relativepathstring])) { // If there is saved values
344
                    $tmp = json_decode($_SESSION['lastsearch_values_' . $relativepathstring], true);
345
                    if (is_array($tmp)) {
346
                        foreach ($tmp as $key => $val) {
347
                            if ($key == $paramname) { // We are on the requested parameter
348
                                $out = $val;
349
                                break;
350
                            }
351
                        }
352
                    }
353
                }
354
                // If there is saved contextpage, page or limit
355
                if ($paramname == 'contextpage' && !empty($_SESSION['lastsearch_contextpage_' . $relativepathstring])) {
356
                    $out = $_SESSION['lastsearch_contextpage_' . $relativepathstring];
357
                } elseif ($paramname == 'page' && !empty($_SESSION['lastsearch_page_' . $relativepathstring])) {
358
                    $out = $_SESSION['lastsearch_page_' . $relativepathstring];
359
                } elseif ($paramname == 'limit' && !empty($_SESSION['lastsearch_limit_' . $relativepathstring])) {
360
                    $out = $_SESSION['lastsearch_limit_' . $relativepathstring];
361
                }
362
            }
363
            // Else, retreive default values if we are not doing a sort
364
            elseif (!isset($_GET['sortfield'])) { // If we did a click on a field to sort, we do no apply default values. Same if option MAIN_ENABLE_DEFAULT_VALUES is not set
365
                if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
366
                    // Search default value from $object->field
367
                   // global $object;
368
                    if (is_object($object) && isset($object->fields[$paramname]['default'])) {
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $object seems to be never defined.
Loading history...
369
                        $out = $object->fields[$paramname]['default'];
370
                    }
371
                }
372
                if (!empty(Globals::$conf->global->MAIN_ENABLE_DEFAULT_VALUES)) {
373
                    if (!empty($_GET['action']) && $_GET['action'] == 'create' && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
374
                        // Now search in setup to overwrite default values
375
                        if (!empty($user->default_values)) {  // $user->default_values defined from menu 'Setup - Default values'
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $user seems to be never defined.
Loading history...
376
                            if (isset($user->default_values[$relativepathstring]['createform'])) {
377
                                foreach ($user->default_values[$relativepathstring]['createform'] as $defkey => $defval) {
378
                                    $qualified = 0;
379
                                    if ($defkey != '_noquery_') {
380
                                        $tmpqueryarraytohave = explode('&', $defkey);
381
                                        $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
382
                                        $foundintru = 0;
383
                                        foreach ($tmpqueryarraytohave as $tmpquerytohave) {
384
                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
385
                                                $foundintru = 1;
386
                                        }
387
                                        if (!$foundintru)
388
                                            $qualified = 1;
389
                                        //var_dump($defkey.'-'.$qualified);
390
                                    } else
391
                                        $qualified = 1;
392
393
                                    if ($qualified) {
394
                                        //var_dump($user->default_values[$relativepathstring][$defkey]['createform']);
395
                                        if (isset($user->default_values[$relativepathstring]['createform'][$defkey][$paramname])) {
396
                                            $out = $user->default_values[$relativepathstring]['createform'][$defkey][$paramname];
397
                                            break;
398
                                        }
399
                                    }
400
                                }
401
                            }
402
                        }
403
                    }
404
                    // Management of default search_filters and sort order
405
                    //elseif (preg_match('/list.php$/', $_SERVER["PHP_SELF"]) && ! empty($paramname) && ! isset($_GET[$paramname]) && ! isset($_POST[$paramname]))
406
                    elseif (!empty($paramname) && !isset($_GET[$paramname]) && !isset($_POST[$paramname])) {
407
                        if (!empty($user->default_values)) {  // $user->default_values defined from menu 'Setup - Default values'
408
                            //var_dump($user->default_values[$relativepathstring]);
409
                            if ($paramname == 'sortfield' || $paramname == 'sortorder') {   // Sorted on which fields ? ASC or DESC ?
410
                                if (isset($user->default_values[$relativepathstring]['sortorder'])) { // Even if paramname is sortfield, data are stored into ['sortorder...']
411
                                    foreach ($user->default_values[$relativepathstring]['sortorder'] as $defkey => $defval) {
412
                                        $qualified = 0;
413
                                        if ($defkey != '_noquery_') {
414
                                            $tmpqueryarraytohave = explode('&', $defkey);
415
                                            $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
416
                                            $foundintru = 0;
417
                                            foreach ($tmpqueryarraytohave as $tmpquerytohave) {
418
                                                if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
419
                                                    $foundintru = 1;
420
                                            }
421
                                            if (!$foundintru)
422
                                                $qualified = 1;
423
                                            //var_dump($defkey.'-'.$qualified);
424
                                        } else
425
                                            $qualified = 1;
426
427
                                        if ($qualified) {
428
                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
429
                                            foreach ($user->default_values[$relativepathstring]['sortorder'][$defkey] as $key => $val) {
430
                                                if ($out)
431
                                                    $out .= ', ';
432
                                                if ($paramname == 'sortfield') {
433
                                                    $out .= dol_string_nospecial($key, '', $forbidden_chars_to_replace);
434
                                                }
435
                                                if ($paramname == 'sortorder') {
436
                                                    $out .= dol_string_nospecial($val, '', $forbidden_chars_to_replace);
437
                                                }
438
                                            }
439
                                            //break;	// No break for sortfield and sortorder so we can cumulate fields (is it realy usefull ?)
440
                                        }
441
                                    }
442
                                }
443
                            } elseif (isset($user->default_values[$relativepathstring]['filters'])) {
444
                                foreach ($user->default_values[$relativepathstring]['filters'] as $defkey => $defval) { // $defkey is a querystring like 'a=b&c=d', $defval is key of user
445
                                    $qualified = 0;
446
                                    if ($defkey != '_noquery_') {
447
                                        $tmpqueryarraytohave = explode('&', $defkey);
448
                                        $tmpqueryarraywehave = explode('&', dol_string_nohtmltag($_SERVER['QUERY_STRING']));
449
                                        $foundintru = 0;
450
                                        foreach ($tmpqueryarraytohave as $tmpquerytohave) {
451
                                            if (!in_array($tmpquerytohave, $tmpqueryarraywehave))
452
                                                $foundintru = 1;
453
                                        }
454
                                        if (!$foundintru)
455
                                            $qualified = 1;
456
                                        //var_dump($defkey.'-'.$qualified);
457
                                    } else
458
                                        $qualified = 1;
459
460
                                    if ($qualified) {
461
                                        if (isset($_POST['sall']) || isset($_POST['search_all']) || isset($_GET['sall']) || isset($_GET['search_all'])) {
462
                                            // We made a search from quick search menu, do we still use default filter ?
463
                                            if (empty(Globals::$conf->global->MAIN_DISABLE_DEFAULT_FILTER_FOR_QUICK_SEARCH)) {
464
                                                $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
465
                                                $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
466
                                            }
467
                                        } else {
468
                                            $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ";", "=");  // we accept _, -, . and ,
469
                                            $out = dol_string_nospecial($user->default_values[$relativepathstring]['filters'][$defkey][$paramname], '', $forbidden_chars_to_replace);
470
                                        }
471
                                        break;
472
                                    }
473
                                }
474
                            }
475
                        }
476
                    }
477
                }
478
            }
479
        }
480
481
        // Substitution variables for DolUtils::GETPOST (used to get final url with variable parameters or final default value with variable paramaters)
482
        // Example of variables: __DAY__, __MONTH__, __YEAR__, __MYCOMPANY_COUNTRY_ID__, __USER_ID__, ...
483
        // We do this only if var is a GET. If it is a POST, may be we want to post the text with vars as the setup text.
484
        if (!is_array($out) && empty($_POST[$paramname]) && empty($noreplace)) {
485
            $maxloop = 20;
486
            $loopnb = 0;    // Protection against infinite loop
487
            while (preg_match('/__([A-Z0-9]+_?[A-Z0-9]+)__/i', $out, $reg) && ($loopnb < $maxloop)) {    // Detect '__ABCDEF__' as key 'ABCDEF' and '__ABC_DEF__' as key 'ABC_DEF'. Detection is also correct when 2 vars are side by side.
488
                $loopnb++;
489
                $newout = '';
490
491
                if ($reg[1] == 'DAY') {
492
                    $tmp = dol_getdate(dol_now(), true);
493
                    $newout = $tmp['mday'];
494
                } elseif ($reg[1] == 'MONTH') {
495
                    $tmp = dol_getdate(dol_now(), true);
496
                    $newout = $tmp['mon'];
497
                } elseif ($reg[1] == 'YEAR') {
498
                    $tmp = dol_getdate(dol_now(), true);
499
                    $newout = $tmp['year'];
500
                } elseif ($reg[1] == 'PREVIOUS_DAY') {
501
                    $tmp = dol_getdate(dol_now(), true);
502
                    $tmp2 = dol_get_prev_day($tmp['mday'], $tmp['mon'], $tmp['year']);
503
                    $newout = $tmp2['day'];
504
                } elseif ($reg[1] == 'PREVIOUS_MONTH') {
505
                    $tmp = dol_getdate(dol_now(), true);
506
                    $tmp2 = dol_get_prev_month($tmp['mon'], $tmp['year']);
507
                    $newout = $tmp2['month'];
508
                } elseif ($reg[1] == 'PREVIOUS_YEAR') {
509
                    $tmp = dol_getdate(dol_now(), true);
510
                    $newout = ($tmp['year'] - 1);
511
                } elseif ($reg[1] == 'NEXT_DAY') {
512
                    $tmp = dol_getdate(dol_now(), true);
513
                    $tmp2 = dol_get_next_day($tmp['mday'], $tmp['mon'], $tmp['year']);
514
                    $newout = $tmp2['day'];
515
                } elseif ($reg[1] == 'NEXT_MONTH') {
516
                    $tmp = dol_getdate(dol_now(), true);
517
                    $tmp2 = dol_get_next_month($tmp['mon'], $tmp['year']);
518
                    $newout = $tmp2['month'];
519
                } elseif ($reg[1] == 'NEXT_YEAR') {
520
                    $tmp = dol_getdate(dol_now(), true);
521
                    $newout = ($tmp['year'] + 1);
522
                } elseif ($reg[1] == 'MYCOMPANY_COUNTRY_ID' || $reg[1] == 'MYCOUNTRY_ID' || $reg[1] == 'MYCOUNTRYID') {
523
                    $newout = $mysoc->country_id;
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $mysoc seems to be never defined.
Loading history...
524
                } elseif ($reg[1] == 'USER_ID' || $reg[1] == 'USERID') {
525
                    $newout = $user->id;
526
                } elseif ($reg[1] == 'USER_SUPERVISOR_ID' || $reg[1] == 'SUPERVISOR_ID' || $reg[1] == 'SUPERVISORID') {
527
                    $newout = $user->fk_user;
528
                } elseif ($reg[1] == 'ENTITY_ID' || $reg[1] == 'ENTITYID') {
529
                    $newout = Globals::$conf->entity;
530
                } else
531
                    $newout = '';     // Key not found, we replace with empty string
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
                    
565
//var_dump('__'.$reg[1].'__ -> '.$newout);
566
                $out = preg_replace('/__' . preg_quote($reg[1], '/') . '__/', $newout, $out);
567
            }
568
        }
569
570
        // Check is done after replacement
571
        switch ($check) {
572
            case 'none':
573
                break;
574
            case 'int':    // Check param is a numeric value (integer but also float or hexadecimal)
575
                if (!is_numeric($out)) {
576
                    $out = '';
577
                }
578
                break;
579
            case 'intcomma':
580
                if (preg_match('/[^0-9,-]+/i', $out))
581
                    $out = '';
582
                break;
583
            case 'alpha':
584
                if (!is_array($out)) {
585
                    $out = trim($out);
586
                    // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
587
                    // '../' is dangerous because it allows dir transversals
588
                    if (preg_match('/"/', $out))
589
                        $out = '';
590
                    else if (preg_match('/\.\.\//', $out))
591
                        $out = '';
592
                }
593
                break;
594
            case 'san_alpha':
595
                $out = filter_var($out, FILTER_SANITIZE_STRING);
596
                break;
597
            case 'aZ':
598
                if (!is_array($out)) {
599
                    $out = trim($out);
600
                    if (preg_match('/[^a-z]+/i', $out))
601
                        $out = '';
602
                }
603
                break;
604
            case 'aZ09':
605
                if (!is_array($out)) {
606
                    $out = trim($out);
607
                    if (preg_match('/[^a-z0-9_\-\.]+/i', $out))
608
                        $out = '';
609
                }
610
                break;
611
            case 'aZ09comma':  // great to sanitize sortfield or sortorder params that can be t.abc,t.def_gh
612
                if (!is_array($out)) {
613
                    $out = trim($out);
614
                    if (preg_match('/[^a-z0-9_\-\.,]+/i', $out))
615
                        $out = '';
616
                }
617
                break;
618
            case 'array':
619
                if (!is_array($out) || empty($out))
620
                    $out = array();
621
                break;
622
            case 'nohtml':  // Recommended for most scalar parameters
623
                $out = dol_string_nohtmltag($out, 0);
624
                break;
625
            case 'alphanohtml': // Recommended for search parameters
626
                if (!is_array($out)) {
627
                    $out = trim($out);
628
                    // '"' is dangerous because param in url can close the href= or src= and add javascript functions.
629
                    // '../' is dangerous because it allows dir transversals
630
                    if (preg_match('/"/', $out))
631
                        $out = '';
632
                    else if (preg_match('/\.\.\//', $out))
633
                        $out = '';
634
                    $out = dol_string_nohtmltag($out);
635
                }
636
                break;
637
            case 'custom':
638
                if (empty($filter))
639
                    return 'BadFourthParameterForDolUtils::GETPOST';
640
                $out = filter_var($out, $filter, $options);
641
                break;
642
        }
643
644
        // Code for search criteria persistence.
645
        // Save data into session if key start with 'search_' or is 'smonth', 'syear', 'month', 'year'
646
        if (empty($method) || $method == 3 || $method == 4) {
647
            if (preg_match('/^search_/', $paramname) || in_array($paramname, array('sortorder', 'sortfield'))) {
648
                //var_dump($paramname.' - '.$out.' '.$user->default_values[$relativepathstring]['filters'][$paramname]);
649
                // We save search key only if $out not empty that means:
650
                // - posted value not empty, or
651
                // - if posted value is empty and a default value exists that is not empty (it means we did a filter to an empty value when default was not).
652
653
                if ($out != '') {  // $out = '0' or 'abc', it is a search criteria to keep
654
                    $user->lastsearch_values_tmp[$relativepathstring][$paramname] = $out;
655
                }
656
            }
657
        }
658
659
        return $out;
660
    }
661
662
    /**
663
     *  Return a prefix to use for this Dolibarr instance, for session/cookie names or email id.
664
     *  The prefix for session is unique in a web context only and is unique for instance and avoid conflict
665
     *  between multi-instances, even when having two instances with one root dir or two instances in virtual servers.
666
     *  The prefix for email is unique if MAIL_PREFIX_FOR_EMAIL_ID is set to a value, otherwise value may be same than other instance.
667
     *
668
     *  @param  string  $mode                   '' (prefix for session name) or 'email' (prefix for email id)
669
     *  @return	string                          A calculated prefix
670
     */
671
    static function dol_getprefix($mode = '')
672
    {
673
        // If prefix is for email
674
        if ($mode == 'email') {
675
            if (empty(Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID)) {
676
                return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
677
            }
678
            // If MAIL_PREFIX_FOR_EMAIL_ID is set (a value initialized with a random value is recommended)
679
            if (Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID != 'SERVER_NAME') {
680
                return Globals::$conf->global->MAIL_PREFIX_FOR_EMAIL_ID;
681
            }
682
            if (isset($_SERVER["SERVER_NAME"])) {
683
                return $_SERVER["SERVER_NAME"];
684
            }
685
686
            return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
687
        }
688
689
        if (isset($_SERVER["SERVER_NAME"]) && isset($_SERVER["DOCUMENT_ROOT"])) {
690
            return Security::dol_hash($_SERVER["SERVER_NAME"] . $_SERVER["DOCUMENT_ROOT"] . DOL_DOCUMENT_ROOT . DOL_BASE_URI);
691
692
            // Use this for a "readable" cookie name
693
            //return dol_sanitizeFileName($_SERVER["SERVER_NAME"].$_SERVER["DOCUMENT_ROOT"].DOL_DOCUMENT_ROOT.DOL_BASE_URI);
694
        }
695
        return Security::dol_hash(DOL_DOCUMENT_ROOT . DOL_BASE_URI);
696
    }
697
698
    /**
699
     * 	Make an include_once using default root and alternate root if it fails.
700
     *  To link to a core file, use include(DOL_DOCUMENT_ROOT.'/pathtofile')
701
     *  To link to a module file from a module file, use include './mymodulefile';
702
     *  To link to a module file from a core file, then this function can be used (call by hook / trigger / speciales pages)
703
     *
704
     * 	@param	string	$relpath	Relative path to file (Ie: mydir/myfile, ../myfile, ...)
705
     * 	@param	string	$classname	Class name (deprecated)
706
     *  @return bool                True if load is a success, False if it fails
707
     */
708
    static function dol_include_once($relpath, $classname = '')
709
    {
710
       // global Globals::$conf, $langs, $user, $mysoc;   // Do not remove this. They must be defined for files we include. Other globals var must be retreived with $GLOBALS['var']
711
712
        $fullpath = dol_buildpath($relpath);
713
714
        if (!file_exists($fullpath)) {
715
            dol_syslog('functions::dol_include_once Tried to load unexisting file: ' . $relpath, LOG_ERR);
716
            return false;
717
        }
718
719
        if (!empty($classname) && !class_exists($classname)) {
720
            return include $fullpath;
721
        } else {
722
            return include_once $fullpath;
723
        }
724
    }
725
726
    /**
727
     * 	Return path of url or filesystem. Can check into alternate dir or alternate dir + main dir depending on value of $returnemptyifnotfound.
728
     *
729
     * 	@param	string	$path						Relative path to file (if mode=0) or relative url (if mode=1). Ie: mydir/myfile, ../myfile
730
     *  @param	int		$type						0=Used for a Filesystem path, 1=Used for an URL path (output relative), 2=Used for an URL path (output full path using same host that current url), 3=Used for an URL path (output full path using host defined into $dolibarr_main_url_root of conf file)
731
     *  @param	int		$returnemptyifnotfound		0:If $type==0 and if file was not found into alternate dir, return default path into main dir (no test on it)
732
     *  											1:If $type==0 and if file was not found into alternate dir, return empty string
733
     *  											2:If $type==0 and if file was not found into alternate dir, test into main dir, return default path if found, empty string if not found
734
     *  @return string								Full filesystem path (if path=0), Full url path (if mode=1)
735
     */
736
    static function dol_buildpath($path, $type = 0, $returnemptyifnotfound = 0)
737
    {
738
       // global Globals::$conf;
739
740
        $path = preg_replace('/^\//', '', $path);
741
742
        if ($type == 0 /* empty($type) */) { // For a filesystem path
743
//$res = DOL_BASE_PATH . '' . $path;  // Standard default path
744
            $res = DOL_BASE_PATH . '/' . $path;  // Standard default path
745
            if (isset(Globals::$conf->file->dol_document_root)) {
746
                foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
747
                    if ($key == 'main') {
748
                        continue;
749
                    }
750
                    if (file_exists($dirroot . '/' . $path)) {
751
                        $res = $dirroot . '/' . $path;
752
                        return $res;
753
                    }
754
                }
755
            }
756
            if ($returnemptyifnotfound) {        // Not found into alternate dir
757
                if ($returnemptyifnotfound == 1 || !file_exists($res))
758
                    return '';
759
            }
760
        }
761
        else {    // For an url path
762
// We try to get local path of file on filesystem from url
763
// Note that trying to know if a file on disk exist by forging path on disk from url
764
// works only for some web server and some setup. This is bugged when
765
// using proxy, rewriting, virtual path, etc...
766
            $res = '';
767
            if ($type == 1) {
768
                $res = /* DOL_BASE_URI */ DOL_BASE_URI . '/' . $path;   // Standard value
769
            }
770
            if ($type == 2) {
771
                $res = /* DOL_MAIN_URL_ROOT */ DOL_BASE_PATH . '/' . $path;  // Standard value
772
            }
773
            if ($type == 3) {
774
                $res = DOL_BASE_URI . '/' . $path;
775
            }
776
777
            foreach (Globals::$conf->file->dol_document_root as $key => $dirroot) { // ex: array(["main"]=>"/home/main/htdocs", ["alt0"]=>"/home/dirmod/htdocs", ...)
778
                if ($key == 'main') {
779
                    if ($type == 3) {
780
                       // global $dolibarr_main_url_root;
781
                        // Define $urlwithroot
782
783
                        // $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
784
                        $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim(DOL_BASE_URI));
785
786
                        $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
787
                        //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
788
789
                        $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . '/' . $path;     // Test on start with http is for old conf syntax
790
                    }
791
                    continue;
792
                }
793
                preg_match('/^([^\?]+(\.css\.php|\.css|\.js\.php|\.js|\.png|\.jpg|\.php)?)/i', $path, $regs);    // Take part before '?'
794
                if (!empty($regs[1])) {
795
                    //print $key.'-'.$dirroot.'/'.$path.'-'.$conf->file->dol_url_root[$type].'<br>'."\n";
796
                    if (file_exists($dirroot . '/' . $regs[1])) {
797
                        if ($type == 1) {
798
                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_BASE_URI) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
799
                        }
800
                        if ($type == 2) {
801
                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : DOL_MAIN_URL_ROOT) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;
802
                        }
803
                        if ($type == 3) {
804
                           // global $dolibarr_main_url_root;
805
                            // Define $urlwithroot
806
                            $urlwithouturlroot = preg_replace('/' . preg_quote(DOL_BASE_URI, '/') . '$/i', '', trim($dolibarr_main_url_root));
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $dolibarr_main_url_root seems to be never defined.
Loading history...
807
                            $urlwithroot = $urlwithouturlroot . DOL_BASE_URI;  // This is to use external domain name found into config file
808
                            //$urlwithroot=DOL_MAIN_URL_ROOT;					// This is to use same domain name than current
809
810
                            $res = (preg_match('/^http/i', Globals::$conf->file->dol_url_root[$key]) ? '' : $urlwithroot) . Globals::$conf->file->dol_url_root[$key] . '/' . $path;     // Test on start with http is for old conf syntax
811
                        }
812
                        break;
813
                    }
814
                }
815
            }
816
        }
817
818
        return $res;
819
    }
820
821
    /**
822
     * 	Create a clone of instance of object (new instance with same value for properties)
823
     *  With native = 0: Property that are reference are also new object (true clone). This means $this->db is not valid.
824
     *  With native = 1: Use PHP clone. Property that are reference are same pointer. This means $this->db is still valid.
825
     *
826
     * 	@param	object	$object		Object to clone
827
     *  @param	int		$native		Native method or true method
828
     * 	@return object				Object clone
829
     *  @see https://php.net/manual/language.oop5.cloning.php
830
     */
831
    static function dol_clone($object, $native = 0)
832
    {
833
//dol_syslog(__FUNCTION__ . " is deprecated", LOG_WARNING);
834
835
        if (empty($native)) {
836
            $myclone = unserialize(serialize($object));
837
        } else {
838
            $myclone = clone $object;     // PHP clone is a shallow copy only, not a real clone, so properties of references will keep references (refer to the same target/variable)
839
        }
840
841
        return $myclone;
842
    }
843
844
    /**
845
     * 	Optimize a size for some browsers (phone, smarphone, ...)
846
     *
847
     * 	@param	int		$size		Size we want
848
     * 	@param	string	$type		Type of optimizing:
849
     * 								'' = function used to define a size for truncation
850
     * 								'width' = function is used to define a width
851
     * 	@return int					New size after optimizing
852
     */
853
    static function dol_size($size, $type = '')
854
    {
855
        //global Globals::$conf;
856
        if (empty(Globals::$conf->dol_optimize_smallscreen))
857
            return $size;
858
        if ($type == 'width' && $size > 250)
859
            return 250;
860
        else
861
            return 10;
862
    }
863
864
    /**
865
     * 	Clean a string to use it as a file name
866
     *
867
     * 	@param	string	$str            String to clean
868
     * 	@param	string	$newstr			String to replace bad chars with
869
     *  @param	int	    $unaccent		1=Remove also accent (default), 0 do not remove them
870
     * 	@return string          		String cleaned (a-zA-Z_)
871
     *
872
     * 	@see        	dol_string_nospecial, dol_string_unaccent, dol_sanitizePathName
873
     */
874
    static function dol_sanitizeFileName($str, $newstr = '_', $unaccent = 1)
875
    {
876
        $filesystem_forbidden_chars = array('<', '>', '/', '\\', '?', '*', '|', '"', '°');
877
        return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
878
    }
879
880
    /**
881
     * 	Clean a string to use it as a path name
882
     *
883
     * 	@param	string	$str            String to clean
884
     * 	@param	string	$newstr			String to replace bad chars with
885
     *  @param	int	    $unaccent		1=Remove also accent (default), 0 do not remove them
886
     * 	@return string          		String cleaned (a-zA-Z_)
887
     *
888
     * 	@see        	dol_string_nospecial, dol_string_unaccent, dol_sanitizeFileName
889
     */
890
    static function dol_sanitizePathName($str, $newstr = '_', $unaccent = 1)
891
    {
892
        $filesystem_forbidden_chars = array('<', '>', '?', '*', '|', '"', '°');
893
        return dol_string_nospecial($unaccent ? dol_string_unaccent($str) : $str, $newstr, $filesystem_forbidden_chars);
894
    }
895
896
    /**
897
     * 	Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName
898
     *
899
     * 	@param	string	$str			String to clean
900
     * 	@return string   	       		Cleaned string
901
     *
902
     * 	@see    		dol_sanitizeFilename, dol_string_nospecial
903
     */
904
    static function dol_string_unaccent($str)
905
    {
906
        if (utf8_check($str)) {
907
// See http://www.utf8-chartable.de/
908
            $string = rawurlencode($str);
909
            $replacements = array(
910
                '%C3%80' => 'A', '%C3%81' => 'A', '%C3%82' => 'A', '%C3%83' => 'A', '%C3%84' => 'A', '%C3%85' => 'A',
911
                '%C3%88' => 'E', '%C3%89' => 'E', '%C3%8A' => 'E', '%C3%8B' => 'E',
912
                '%C3%8C' => 'I', '%C3%8D' => 'I', '%C3%8E' => 'I', '%C3%8F' => 'I',
913
                '%C3%92' => 'O', '%C3%93' => 'O', '%C3%94' => 'O', '%C3%95' => 'O', '%C3%96' => 'O',
914
                '%C3%99' => 'U', '%C3%9A' => 'U', '%C3%9B' => 'U', '%C3%9C' => 'U',
915
                '%C3%A0' => 'a', '%C3%A1' => 'a', '%C3%A2' => 'a', '%C3%A3' => 'a', '%C3%A4' => 'a', '%C3%A5' => 'a',
916
                '%C3%A7' => 'c',
917
                '%C3%A8' => 'e', '%C3%A9' => 'e', '%C3%AA' => 'e', '%C3%AB' => 'e',
918
                '%C3%AC' => 'i', '%C3%AD' => 'i', '%C3%AE' => 'i', '%C3%AF' => 'i',
919
                '%C3%B1' => 'n',
920
                '%C3%B2' => 'o', '%C3%B3' => 'o', '%C3%B4' => 'o', '%C3%B5' => 'o', '%C3%B6' => 'o',
921
                '%C3%B9' => 'u', '%C3%BA' => 'u', '%C3%BB' => 'u', '%C3%BC' => 'u',
922
                '%C3%BF' => 'y'
923
            );
924
            $string = strtr($string, $replacements);
925
            return rawurldecode($string);
926
        } else {
927
// See http://www.ascii-code.com/
928
            $string = strtr(
929
                $str, "\xC0\xC1\xC2\xC3\xC4\xC5\xC7
930
			\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1
931
			\xD2\xD3\xD4\xD5\xD8\xD9\xDA\xDB\xDD
932
			\xE0\xE1\xE2\xE3\xE4\xE5\xE7\xE8\xE9\xEA\xEB
933
			\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF8
934
			\xF9\xFA\xFB\xFC\xFD\xFF", "AAAAAAC
935
			EEEEIIIIDN
936
			OOOOOUUUY
937
			aaaaaaceeee
938
			iiiidnooooo
939
			uuuuyy"
940
            );
941
            $string = strtr($string, array("\xC4" => "Ae", "\xC6" => "AE", "\xD6" => "Oe", "\xDC" => "Ue", "\xDE" => "TH", "\xDF" => "ss", "\xE4" => "ae", "\xE6" => "ae", "\xF6" => "oe", "\xFC" => "ue", "\xFE" => "th"));
942
            return $string;
943
        }
944
    }
945
946
    /**
947
     * 	Clean a string from all punctuation characters to use it as a ref or login.
948
     *  This is a more complete static function than dol_sanitizeFileName.
949
     *
950
     * 	@param	string	$str            	String to clean
951
     * 	@param	string	$newstr				String to replace forbidden chars with
952
     *  @param  array	$badcharstoreplace  List of forbidden characters
953
     * 	@return string          			Cleaned string
954
     *
955
     * 	@see    		dol_sanitizeFilename, dol_string_unaccent
956
     */
957
    static function dol_string_nospecial($str, $newstr = '_', $badcharstoreplace = '')
958
    {
959
        $forbidden_chars_to_replace = array(" ", "'", "/", "\\", ":", "*", "?", "\"", "<", ">", "|", "[", "]", ",", ";", "=", '°');  // more complete than dol_sanitizeFileName
960
        $forbidden_chars_to_remove = array();
961
        if (is_array($badcharstoreplace))
962
            $forbidden_chars_to_replace = $badcharstoreplace;
963
//$forbidden_chars_to_remove=array("(",")");
964
965
        return str_replace($forbidden_chars_to_replace, $newstr, str_replace($forbidden_chars_to_remove, "", $str));
966
    }
967
968
    /**
969
     * Encode string for xml usage
970
     *
971
     * @param 	string	$string		String to encode
972
     * @return	string				String encoded
973
     */
974
    static function dolEscapeXML($string)
975
    {
976
        return strtr($string, array('\'' => '&apos;', '"' => '&quot;', '&' => '&amp;', '<' => '&lt;', '>' => '&gt;'));
977
    }
978
979
    /**
980
     *  Returns text escaped for inclusion into javascript code
981
     *
982
     *  @param      string		$stringtoescape		String to escape
983
     *  @param		int		$mode				0=Escape also ' and " into ', 1=Escape ' but not " for usage into 'string', 2=Escape " but not ' for usage into "string", 3=Escape ' and " with \
984
     *  @param		int		$noescapebackslashn	0=Escape also \n. 1=Do not escape \n.
985
     *  @return     string     		 				Escaped string. Both ' and " are escaped into ' if they are escaped.
986
     */
987
    static function dol_escape_js($stringtoescape, $mode = 0, $noescapebackslashn = 0)
988
    {
989
// escape quotes and backslashes, newlines, etc.
990
        $substitjs = array("&#039;" => "\\'", "\r" => '\\r');
991
//$substitjs['</']='<\/';	// We removed this. Should be useless.
992
        if (empty($noescapebackslashn)) {
993
            $substitjs["\n"] = '\\n';
994
            $substitjs['\\'] = '\\\\';
995
        }
996
        if (empty($mode)) {
997
            $substitjs["'"] = "\\'";
998
            $substitjs['"'] = "\\'";
999
        } else if ($mode == 1)
1000
            $substitjs["'"] = "\\'";
1001
        else if ($mode == 2) {
1002
            $substitjs['"'] = '\\"';
1003
        } else if ($mode == 3) {
1004
            $substitjs["'"] = "\\'";
1005
            $substitjs['"'] = "\\\"";
1006
        }
1007
        return strtr($stringtoescape, $substitjs);
1008
    }
1009
1010
    /**
1011
     *  Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields.
1012
     *
1013
     *  @param      string		$stringtoescape		String to escape
1014
     *  @param		int			$keepb				1=Preserve b tags (otherwise, remove them)
1015
     *  @param      int         $keepn              1=Preserve \r\n strings (otherwise, replace them with escaped value)
1016
     *  @return     string     				 		Escaped string
1017
     *  @see		dol_string_nohtmltag, dol_string_nospecial, dol_string_unaccent
1018
     */
1019
    static function dol_escape_htmltag($stringtoescape, $keepb = 0, $keepn = 0)
1020
    {
1021
// escape quotes and backslashes, newlines, etc.
1022
        $tmp = html_entity_decode($stringtoescape, ENT_COMPAT, 'UTF-8');  // TODO Use htmlspecialchars_decode instead, that make only required change for html tags
1023
        if (!$keepb)
1024
            $tmp = strtr($tmp, array("<b>" => '', '</b>' => ''));
1025
        if (!$keepn)
1026
            $tmp = strtr($tmp, array("\r" => '\\r', "\n" => '\\n'));
1027
        return htmlentities($tmp, ENT_COMPAT, 'UTF-8');      // TODO Use htmlspecialchars instead, that make only required change for html tags
1028
    }
1029
1030
    /**
1031
     * Convert a string to lower. Never use strtolower because it does not works with UTF8 strings.
1032
     *
1033
     * @param 	string		$utf8_string		String to encode
1034
     * @return 	string							String converted
1035
     */
1036
    static function dol_strtolower($utf8_string)
1037
    {
1038
        return mb_strtolower($utf8_string, "UTF-8");
1039
    }
1040
1041
    /**
1042
     * Convert a string to upper. Never use strtolower because it does not works with UTF8 strings.
1043
     *
1044
     * @param 	string		$utf8_string		String to encode
1045
     * @return 	string							String converted
1046
     */
1047
    static function dol_strtoupper($utf8_string)
1048
    {
1049
        return mb_strtoupper($utf8_string, "UTF-8");
1050
    }
1051
1052
    /**
1053
     * 	Write log message into outputs. Possible outputs can be:
1054
     * 	SYSLOG_HANDLERS = ["mod_syslog_file"]  		file name is then defined by SYSLOG_FILE
1055
     * 	SYSLOG_HANDLERS = ["mod_syslog_syslog"]  	facility is then defined by SYSLOG_FACILITY
1056
     *  Warning, syslog functions are bugged on Windows, generating memory protection faults. To solve
1057
     *  this, use logging to files instead of syslog (see setup of module).
1058
     *  Note: If constant 'SYSLOG_FILE_NO_ERROR' defined, we never output any error message when writing to log fails.
1059
     *  Note: You can get log message into html sources by adding parameter &logtohtml=1 (constant MAIN_LOGTOHTML must be set)
1060
     *  This static function works only if syslog module is enabled.
1061
     * 	This must not use any call to other static function calling dol_syslog (avoid infinite loop).
1062
     *
1063
     * 	@param  string		$message				Line to log. ''=Show nothing
1064
     *  @param  int			$level					Log level
1065
     * 												On Windows LOG_ERR=4, LOG_WARNING=5, LOG_NOTICE=LOG_INFO=6, LOG_DEBUG=6 si define_syslog_variables ou PHP 5.3+, 7 si dolibarr
1066
     * 												On Linux   LOG_ERR=3, LOG_WARNING=4, LOG_INFO=6, LOG_DEBUG=7
1067
     *  @param	int			$ident					1=Increase ident of 1, -1=Decrease ident of 1
1068
     *  @param	string		$suffixinfilename		When output is a file, append this suffix into default log filename.
1069
     *  @param	string		$restricttologhandler	Output log only for this log handler
1070
     *  @return	void
1071
     */
1072
    static function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = '', $restricttologhandler = '')
1073
    {
1074
       // global Globals::$conf, $user;
1075
// If syslog module enabled
1076
        if (empty(Globals::$conf->syslog->enabled))
1077
            return;
1078
1079
        if ($ident < 0) {
1080
            foreach (Globals::$conf->loghandlers as $loghandlerinstance) {
1081
                $loghandlerinstance->setIdent($ident);
1082
            }
1083
        }
1084
1085
        if (!empty($message)) {
1086
// Test log level
1087
            $logLevels = array(LOG_EMERG, LOG_ALERT, LOG_CRIT, LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, LOG_DEBUG);
1088
            if (!in_array($level, $logLevels, true)) {
1089
                throw new Exception('Incorrect log level');
0 ignored issues
show
Bug introduced by alxarafe
The type Alixar\Helpers\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
1090
            }
1091
            if ($level > Globals::$conf->global->SYSLOG_LEVEL)
1092
                return;
1093
1094
            $message = preg_replace('/password=\'[^\']*\'/', 'password=\'hidden\'', $message); // protection to avoid to have value of password in log
1095
// If adding log inside HTML page is required
1096
            if (!empty($_REQUEST['logtohtml']) && (!empty(Globals::$conf->global->MAIN_ENABLE_LOG_TO_HTML) || !empty(Globals::$conf->global->MAIN_LOGTOHTML))) {   // MAIN_LOGTOHTML kept for backward compatibility
1097
                Globals::$conf->logbuffer[] = dol_print_date(time(), "%Y-%m-%d %H:%M:%S") . " " . $message;
1098
            }
1099
1100
//TODO: Remove this. MAIN_ENABLE_LOG_INLINE_HTML should be deprecated and use a log handler dedicated to HTML output
1101
// If html log tag enabled and url parameter log defined, we show output log on HTML comments
1102
            if (!empty(Globals::$conf->global->MAIN_ENABLE_LOG_INLINE_HTML) && !empty($_GET["log"])) {
1103
                print "\n\n<!-- Log start\n";
1104
                print $message . "\n";
1105
                print "Log end -->\n";
1106
            }
1107
1108
            $data = array(
1109
                'message' => $message,
1110
                'script' => (isset($_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF'], '.php') : false),
1111
                'level' => $level,
1112
                'user' => ((is_object($user) && $user->id) ? $user->login : false),
0 ignored issues
show
Comprehensibility Best Practice introduced by alxarafe
The variable $user seems to be never defined.
Loading history...
1113
                'ip' => false
1114
            );
1115
1116
// This is when server run behind a reverse proxy
1117
            if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
1118
                $data['ip'] = $_SERVER['HTTP_X_FORWARDED_FOR'] . (empty($_SERVER["REMOTE_ADDR"]) ? '' : '->' . $_SERVER['REMOTE_ADDR']);
1119
// This is when server run normally on a server
1120
            else if (!empty($_SERVER["REMOTE_ADDR"]))
1121
                $data['ip'] = $_SERVER['REMOTE_ADDR'];
1122
// This is when PHP session is ran inside a web server but not inside a client request (example: init code of apache)
1123
            else if (!empty($_SERVER['SERVER_ADDR']))