Passed
Push — EXTRACT_CLASSES ( ae6b5c...83d77a )
by Rafael
60:14 queued 23:58
created

Context   F

Complexity

Total Complexity 91

Size/Duplication

Total Lines 688
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 225
dl 0
loc 688
rs 2
c 0
b 0
f 0
wmc 91

24 Methods

Rating   Name   Duplication   Size   Complexity  
B setEventMessages() 0 15 7
A getRootConfigUrl() 0 15 3
A getInstance() 0 7 2
C getPublicControllerUrl() 0 45 14
F urlOrigin() 0 19 12
A generateNewToken() 0 17 4
A getControllerUrl() 0 19 3
A clearEventMessages() 0 4 1
A setError() 0 11 5
A getErrors() 0 8 2
A setEventMessage() 0 20 6
A initController() 0 29 4
A addControllerDefinition() 0 16 3
A getUrlToken() 0 8 2
A newToken() 0 3 1
A clearErrors() 0 4 1
A menuIsActive() 0 3 1
A getRootUrl() 0 3 1
A loadEventMessages() 0 8 2
A setControllerFound() 0 3 1
B getThirdPartyAccountFromLogin() 0 58 10
A userIsLog() 0 6 2
A getFormToken() 0 8 2
A __construct() 0 32 2

How to fix   Complexity   

Complex Class

Complex classes like Context often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Context, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/* Copyright (C) 2023-2024  Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2024       Frédéric France             <[email protected]>
5
 * Copyright (C) 2024		MDW							<[email protected]>
6
 * Copyright (C) 2024       Rafael San José             <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
namespace Dolibarr\Code\WebPortal\Classes;
23
24
use DoliDB;
25
26
/**
27
* \file       htdocs/webportal/class/context.class.php
28
* \ingroup    webportal
29
* \brief      File of context class for WebPortal
30
*/
31
32
require_once __DIR__ . '/controller.class.php';
33
require_once __DIR__ . '/webPortalTheme.class.php';
34
35
/**
36
 * Class Context
37
 */
38
class Context
39
{
40
    /**
41
     * @var Context Singleton
42
     * @access private
43
     * @static
44
     */
45
    private static $_instance = null;
46
47
    /**
48
     * @var DoliDb  $db     Database handler
49
     */
50
    public $db;
51
52
    /**
53
     * @var string
54
     */
55
    public $title;
56
57
    /**
58
     * @var string
59
     */
60
    public $desc;
61
62
    /**
63
     * @var string
64
     */
65
    public $meta_title;
66
67
    /**
68
     * @var string
69
     */
70
    public $meta_desc;
71
72
    /**
73
     * The application name
74
     * @var string $appliName
75
     */
76
    public $appliName;
77
78
    /**
79
     * @var string
80
     */
81
    public $controller;
82
83
    /**
84
     * @var boolean
85
     */
86
    public $controller_found = false;
87
88
    /**
89
     * @var stdClass[]
90
     */
91
    private $controllers = array();
92
93
    /**
94
     * @var Controller $controllerInstance
95
     */
96
    public $controllerInstance;
97
98
    /**
99
     * for internal error msg
100
     * @var string error
101
     */
102
    public $error;
103
104
    /**
105
     * @var array errors
106
     */
107
    public $errors = array();
108
109
    /**
110
     * @var string Action
111
     */
112
    public $action;
113
114
    public $tplDir;
115
    public $tplPath;
116
    public $topMenu;
117
118
    public $rootUrl;
119
120
    public $menu_active = array();
121
122
    public $eventMessages = array();
123
124
    public $tokenKey = 'token';
125
126
    /**
127
     * Current object of page
128
     * @var object $object
129
     */
130
    public $object;
131
132
    /**
133
     * @var CommonObject Logged user
134
     */
135
    public $logged_user = null;
136
137
    /**
138
     * @var CommonObject Logged third-party
139
     */
140
    public $logged_thirdparty = null;
141
142
    /**
143
     * @var CommonObject Logged member
144
     */
145
    public $logged_member = null;
146
147
    /**
148
     * @var CommonObject Logged partnership
149
     */
150
    public $logged_partnership = null;
151
152
153
    /**
154
     * @var WebPortalTheme Theme data
155
     */
156
    public $theme;
157
158
159
    /**
160
     * Constructor
161
     *
162
     * @return  void
163
     */
164
    private function __construct()
165
    {
166
        global $conf, $db;
167
168
        $this->db = $db;
169
170
        $this->tplDir = __DIR__ . '/../';
171
172
        $this->getControllerUrl();
173
174
        $this->topMenu = new stdClass();
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\WebPortal\Classes\stdClass was not found. Did you mean stdClass? If so, make sure to prefix the type with \.
Loading history...
175
176
        $this->tplPath = realpath(__DIR__ . '/../../public/webportal/tpl');
177
178
        $this->controller = GETPOST('controller', 'aZ09'); // for security, limited to 'aZ09'
0 ignored issues
show
Documentation Bug introduced by
It seems like GETPOST('controller', 'aZ09') can also be of type array or array or array. However, the property $controller is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
179
        $this->action = GETPOST('action', 'aZ09');// for security, limited to 'aZ09'
0 ignored issues
show
Documentation Bug introduced by
It seems like GETPOST('action', 'aZ09') can also be of type array or array or array. However, the property $action is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
180
181
        if (empty($this->controller)) {
182
            $this->controller = 'default';
183
        }
184
185
        $this->appliName = getDolGlobalString('WEBPORTAL_TITLE', getDolGlobalString('MAIN_INFO_SOCIETE_NOM'));
186
187
        //$this->generateNewToken();
188
189
        $this->initController();
190
191
        // Init de l'url de base
192
        $this->rootUrl = self::getRootConfigUrl();
193
194
195
        $this->theme = new WebPortalTheme();
196
    }
197
198
    /**
199
     * Singleton method to create one instance of this object
200
     *
201
     * @return  Context Instance
202
     */
203
    public static function getInstance()
204
    {
205
        if (is_null(self::$_instance)) {
206
            self::$_instance = new Context();
207
        }
208
209
        return self::$_instance;
210
    }
211
212
    /**
213
     * Init controller
214
     *
215
     * @return  void
216
     */
217
    public function initController()
218
    {
219
        global $db;
220
221
        $defaultControllersPath = __DIR__ . '/../controllers/';
222
223
        // define controllers definition
224
        $this->addControllerDefinition('login', $defaultControllersPath . 'login.controller.class.php', 'LoginController');
225
        $this->addControllerDefinition('default', $defaultControllersPath . 'default.controller.class.php', 'DefaultController');
226
        $this->addControllerDefinition('document', $defaultControllersPath . 'document.controller.class.php', 'DocumentController');
227
        $this->addControllerDefinition('propallist', $defaultControllersPath . 'propallist.controller.class.php', 'PropalListController');
228
        $this->addControllerDefinition('orderlist', $defaultControllersPath . 'orderlist.controller.class.php', 'OrderListController');
229
        $this->addControllerDefinition('invoicelist', $defaultControllersPath . 'invoicelist.controller.class.php', 'InvoiceListController');
230
        $this->addControllerDefinition('membercard', $defaultControllersPath . 'membercard.controller.class.php', 'MemberCardController');
231
        $this->addControllerDefinition('partnershipcard', $defaultControllersPath . 'partnershipcard.controller.class.php', 'PartnershipCardController');
232
233
        // call triggers
234
        //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
235
        //$interface=new Interfaces($db);
236
        //$interface->run_triggers('WebPortalInitController', $this, $logged_user, $langs, $conf);
237
238
        // search for controller
239
        $this->controllerInstance = new Controller();
240
        if (isset($this->controllers[$this->controller]) && file_exists($this->controllers[$this->controller]->path)) {
241
            require_once $this->controllers[$this->controller]->path;
242
243
            if (class_exists($this->controllers[$this->controller]->class)) {
244
                $this->controllerInstance = new $this->controllers[$this->controller]->class();
245
                $this->setControllerFound();
246
            }
247
        }
248
    }
249
250
    /**
251
     * Add controller definition
252
     *
253
     * @param   string  $controller     Name
254
     * @param   string  $path           Path
255
     * @param   string  $className      Class name
256
     * @return  bool
257
     */
258
    public function addControllerDefinition($controller, $path, $className)
259
    {
260
        $fileName = basename($path);
261
        $needle = '.controller.class.php';
262
        $length = strlen($needle);
263
        $isControllerFile = $length > 0 ? substr($fileName, -$length) === $needle : true;
264
        if (!$isControllerFile) {
265
            $this->setError('Error: controller definition ' . $fileName);
266
            return false;
267
        }
268
269
        $this->controllers[$controller] = new stdClass();
270
        $this->controllers[$controller]->path = $path;
271
        $this->controllers[$controller]->class = $className;
272
273
        return true;
274
    }
275
276
    /**
277
     * Set controller found
278
     *
279
     * @return  void
280
     */
281
    public function setControllerFound()
282
    {
283
        $this->controller_found = true;
284
    }
285
286
    /**
287
     * Get WebPortal root url
288
     *
289
     * @return  string  Web Portal root url
290
     */
291
    public static function getRootConfigUrl()
292
    {
293
        global $conf;
294
295
        // Init de l'url de base
296
        if (getDolGlobalString('WEBPORTAL_ROOT_URL')) {
297
            $rootUrl = getDolGlobalString('WEBPORTAL_ROOT_URL');
298
            if (substr($rootUrl, -1) !== '/') {
299
                $rootUrl .= '/';
300
            }
301
        } else {
302
            $rootUrl = dol_buildpath('/public/webportal/', 2);
303
        }
304
305
        return $rootUrl;
306
    }
307
308
    /**
309
     * Get root url
310
     *
311
     * @param   string          $controller     Controller name
312
     * @param   string|array    $moreParams     More parameters
313
     * @param   bool            $addToken       Add token hash only if $controller is set
314
     * @return  string
315
     * @deprecated see getControllerUrl()
316
     */
317
    public function getRootUrl($controller = '', $moreParams = '', $addToken = true)
318
    {
319
        return self::getControllerUrl($controller, $moreParams, $addToken);
320
    }
321
322
    /**
323
     * Get controller url according to context
324
     *
325
     * @param   string          $controller     Controller name
326
     * @param   string|array    $moreParams     More parameters
327
     * @param   bool            $addToken       Add token hash only if controller is set
328
     * @return  string
329
     */
330
    public function getControllerUrl($controller = '', $moreParams = '', $addToken = true)
331
    {
332
        // TODO : addToken parameter on auto to detect (create or edit) action and add token on url
333
        $url = $this->rootUrl;
334
335
        if (empty($controller)) {
336
            // because can be called without params to get only rootUrl
337
            return $url;
338
        }
339
340
        $Tparams = array();
341
342
        $Tparams['controller'] = $controller;
343
344
        if (!empty($addToken)) {
345
            $Tparams[$this->tokenKey] = $this->newToken();
346
        }
347
348
        return self::getPublicControllerUrl($controller, $moreParams, $Tparams);
349
    }
350
351
    /**
352
     * Generate public controller URL
353
     * Used for external link (like email or web page)
354
     * so remove token and contextual behavior associate with current user
355
     *
356
     * @param   string          $controller             Controller
357
     * @param   string|array    $moreParams             More parameters
358
     * @param   array           $Tparams                Parameters
359
     * @return  string
360
     */
361
    public static function getPublicControllerUrl($controller = '', $moreParams = '', $Tparams = array())
362
    {
363
        $url = self::getRootConfigUrl();
364
365
        if (empty($controller)) {
366
            // because can be called without params to get only rootUrl
367
            return $url;
368
        }
369
370
        $Tparams['controller'] = $controller;
371
372
        // if $moreParams is an array
373
        if (!empty($moreParams) && is_array($moreParams)) {
374
            if (isset($moreParams['controller'])) {
375
                unset($moreParams['controller']);
376
            }
377
            if (!empty($moreParams)) {
378
                foreach ($moreParams as $paramKey => $paramVal) {
379
                    $Tparams[$paramKey] = $paramVal;
380
                }
381
            }
382
        }
383
384
        if (!empty($Tparams)) {
385
            $TCompiledAttr = array();
386
            foreach ($Tparams as $key => $value) {
387
                $TCompiledAttr[] = $key . '=' . $value;
388
            }
389
            $url .= '?' . implode("&", $TCompiledAttr);
390
        }
391
392
        // if $moreParams is a string
393
        if (!empty($moreParams) && !is_array($moreParams)) {
394
            if (empty($Tparams)) {
395
                if ($moreParams[0] !== '?') {
396
                    $url .= '?';
397
                }
398
                if ($moreParams[0] === '&') {
399
                    $moreParams = substr($moreParams, 1);
400
                }
401
            }
402
            $url .= $moreParams;
403
        }
404
405
        return $url;
406
    }
407
408
    /**
409
     * Url origin
410
     *
411
     * @param   bool    $withRequestUri         With request URI
412
     * @param   bool    $use_forwarded_host     Use formatted host
413
     * @return  string
414
     */
415
    public static function urlOrigin($withRequestUri = true, $use_forwarded_host = false)
416
    {
417
        $s = $_SERVER;
418
419
        $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on');
420
        $sp = strtolower($s['SERVER_PROTOCOL']);
421
        $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
422
        $port = $s['SERVER_PORT'];
423
        $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
424
        $host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
425
        $host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
426
427
        $url = $protocol . '://' . $host;
428
429
        if ($withRequestUri) {
430
            $url .= $s['REQUEST_URI'];
431
        }
432
433
        return $url;
434
    }
435
436
    /**
437
     * Check if user is logged
438
     *
439
     * @return  bool
440
     */
441
    public function userIsLog()
442
    {
443
        if (!empty($_SESSION["webportal_logged_thirdparty_account_id"])) {
444
            return true;
445
        } else {
446
            return false;
447
        }
448
    }
449
450
    /**
451
     * Is menu enabled ?
452
     *
453
     * @param   string  $menuName   Menu name
454
     * @return  bool
455
     */
456
    public function menuIsActive($menuName)
457
    {
458
        return in_array($menuName, $this->menu_active);
459
    }
460
461
    /**
462
     * Set errors
463
     *
464
     * @param   array   $errors     Errors
465
     * @return  void
466
     */
467
    public function setError($errors)
468
    {
469
        if (!is_array($errors)) {
470
            $errors = array($errors);
471
        }
472
        if (!isset($_SESSION['webportal_errors'])) {
473
            $_SESSION['webportal_errors'] = array();
474
        }
475
        foreach ($errors as $msg) {
476
            if (!in_array($msg, $_SESSION['webportal_errors'])) {
477
                $_SESSION['webportal_errors'][] = $msg;
478
            }
479
        }
480
    }
481
482
    /**
483
     * Get errors
484
     *
485
     * @return  int
486
     */
487
    public function getErrors()
488
    {
489
        if (!empty($_SESSION['webportal_errors'])) {
490
            $this->errors = array_values($_SESSION['webportal_errors']);
491
            return count($this->errors);
492
        }
493
494
        return 0;
495
    }
496
497
    /**
498
     * Clear errors
499
     *
500
     * @return  void
501
     */
502
    public function clearErrors()
503
    {
504
        unset($_SESSION['webportal_errors']);
505
        $this->errors = array();
506
    }
507
508
    /**
509
     * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
510
     * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
511
     *
512
     * @param   string|string[] $mesgs  Message string or array
513
     * @param   string          $style  Which style to use ('mesgs' by default, 'warnings', 'errors')
514
     * @return  void
515
     */
516
    public function setEventMessage($mesgs, $style = 'mesgs')
517
    {
518
        $TAcceptedStyle = array('mesgs', 'warnings', 'errors');
519
520
        if (!in_array($style, $TAcceptedStyle)) {
521
            $style = 'mesgs';
522
        }
523
524
        if (!is_array($mesgs)) {
525
            $mesgs = array($mesgs);
526
        }
527
        if (!isset($_SESSION['webportal_events'])) {
528
            $_SESSION['webportal_events'] = array(
529
                'mesgs' => array(), 'warnings' => array(), 'errors' => array()
530
            );
531
        }
532
533
        foreach ($mesgs as $msg) {
534
            if (!in_array($msg, $_SESSION['webportal_events'][$style])) {
535
                $_SESSION['webportal_events'][$style][] = $msg;
536
            }
537
        }
538
    }
539
540
    /**
541
     * Set event messages in dol_events session object. Will be output by calling dol_htmloutput_events.
542
     * Note: Calling dol_htmloutput_events is done into pages by standard llxFooter() function.
543
     *
544
     * @param   string      $mesg   Message string
545
     * @param   array|null  $mesgs  Message array
546
     * @param   string      $style  Which style to use ('mesgs' by default, 'warnings', 'errors')
547
     * @return  void
548
     */
549
    public function setEventMessages($mesg, $mesgs, $style = 'mesgs')
550
    {
551
        if (empty($mesg) && empty($mesgs)) {
552
            dol_syslog(__METHOD__ . ' Try to add a message in stack, but value to add is empty message', LOG_WARNING);
553
        } else {
554
            if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
555
                dol_print_error('', 'Bad parameter style=' . $style . ' for setEventMessages');
556
            }
557
            if (empty($mesgs)) {
558
                $this->setEventMessage($mesg, $style);
559
            } else {
560
                if (!empty($mesg) && !in_array($mesg, $mesgs)) {
561
                    $this->setEventMessage($mesg, $style); // Add message string if not already into array
562
                }
563
                $this->setEventMessage($mesgs, $style);
564
            }
565
        }
566
    }
567
568
    /**
569
     * Load event messages
570
     *
571
     * @return  int
572
     */
573
    public function loadEventMessages()
574
    {
575
        if (!empty($_SESSION['webportal_events'])) {
576
            $this->eventMessages = $_SESSION['webportal_events'];
577
            return 1;
578
        }
579
580
        return 0;
581
    }
582
583
    /**
584
     * Clear event messages
585
     *
586
     * @return  void
587
     */
588
    public function clearEventMessages()
589
    {
590
        unset($_SESSION['webportal_events']);
591
        $this->eventMessages = array();
592
    }
593
594
    /**
595
     * Return the value of token currently saved into session with name 'newToken'.
596
     * This token must be sent by any POST as it will be used by next page for comparison with value in session.
597
     * This token depends on controller
598
     *
599
     * @return  string
600
     */
601
    public function newToken()
602
    {
603
        return newToken();
604
    }
605
606
    /**
607
     * Generate new token.
608
     * @deprecated see main
609
     * @return  string
610
     */
611
    protected function generateNewToken()
612
    {
613
        $currentToken = $this->newToken();
614
        // Creation of a token against CSRF vulnerabilities
615
        if (!defined('NOTOKENRENEWAL') || empty($currentToken)) {
616
            // Rolling token at each call ($_SESSION['token'] contains token of previous page)
617
            if (isset($_SESSION['newtoken'])) {
618
                $_SESSION['token'] = $_SESSION['newtoken'];
619
            }
620
621
            // Save what will be next token. Into forms, we will add param $context->newToken();
622
            $token = dol_hash(uniqid((string) mt_rand(), true)); // Generate
623
            $_SESSION['newtoken'] = $token;
624
625
            return $token;
626
        } else {
627
            return $this->newToken();
628
        }
629
    }
630
631
    /**
632
     * Get token url
633
     *
634
     * @return  string|null
635
     */
636
    public function getUrlToken()
637
    {
638
        $token = $this->newToken();
639
        if ($token) {
640
            return '&' . $this->tokenKey . '=' . $this->newToken();
641
        }
642
643
        return null;
644
    }
645
646
    /**
647
     * Get token input for form
648
     *
649
     * @return  string|null
650
     */
651
    public function getFormToken()
652
    {
653
        $token = $this->newToken();
654
        if ($token) {
655
            return '<input type="hidden" name="' . $this->tokenKey . '" value="' . $this->newToken() . '" />';
656
        }
657
658
        return null;
659
    }
660
661
    /**
662
     * Try to find the third-party account id from
663
     *
664
     * @param   string  $login      Login
665
     * @param   string  $pass       Password
666
     * @return  int     Third-party account id || <0 if error
667
     */
668
    public function getThirdPartyAccountFromLogin($login, $pass)
669
    {
670
        $id = 0;
671
672
        $sql = "SELECT sa.rowid as id, sa.pass_crypted";
673
        $sql .= " FROM " . $this->db->prefix() . "societe_account as sa";
674
        $sql .= " WHERE BINARY sa.login = '" . $this->db->escape($login) . "'"; // case sensitive
675
        //$sql .= " AND BINARY sa.pass_crypted = '" . $this->db->escape($pass) . "'"; // case sensitive
676
        $sql .= " AND sa.site = 'dolibarr_portal'";
677
        $sql .= " AND sa.status = 1";
678
        $sql .= " AND sa.entity IN (" . getEntity('societe') . ")";
679
680
        dol_syslog(__METHOD__ . ' Try to find the third-party account id for login"' . $login . '" and site="dolibarr_portal"', LOG_DEBUG);
681
        $result = $this->db->query($sql);
682
        if ($result) {
683
            if ($this->db->num_rows($result) == 1) {
684
                $passok = false;
685
                $obj = $this->db->fetch_object($result);
686
                if ($obj) {
687
                    $passcrypted = $obj->pass_crypted;
688
689
                    // Check crypted password
690
                    $cryptType = '';
691
                    if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
692
                        $cryptType = getDolGlobalString('DATABASE_PWD_ENCRYPTED');
693
                    }
694
695
                    // By default, we use default setup for encryption rule
696
                    if (!in_array($cryptType, array('auto'))) {
697
                        $cryptType = 'auto';
698
                    }
699
700
                    // Check crypted password according to crypt algorithm
701
                    if ($cryptType == 'auto') {
702
                        if ($passcrypted && dol_verifyHash($pass, $passcrypted, '0')) {
703
                            $passok = true;
704
                        }
705
                    }
706
707
                    // Password ok ?
708
                    if ($passok) {
709
                        $id = $obj->id;
710
                    } else {
711
                        dol_syslog(__METHOD__ . ' Authentication KO bad password for ' . $login . ', cryptType=' . $cryptType, LOG_NOTICE);
712
                        sleep(1); // Brut force protection. Must be same delay when login is not valid
713
                        return -3;
714
                    }
715
                }
716
            } else {
717
                dol_syslog(__METHOD__ . ' Many third-party account found for login"' . $login . '" and site="dolibarr_portal"', LOG_ERR);
718
                return -2;
719
            }
720
        } else {
721
            $this->error = $this->db->lasterror();
722
            return -1;
723
        }
724
725
        return $id;
726
    }
727
}
728