dolibarr 21.0.0-alpha
context.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2023-2024 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
26require_once __DIR__ . '/controller.class.php';
27require_once __DIR__ . '/webPortalTheme.class.php';
28
33{
39 private static $_instance = null;
40
44 public $db;
45
49 public $title;
50
54 public $desc;
55
59 public $meta_title;
60
64 public $meta_desc;
65
70 public $appliName;
71
75 public $controller;
76
80 public $controller_found = false;
81
85 private $controllers = array();
86
90 public $controllerInstance;
91
96 public $error;
97
101 public $errors = array();
102
106 public $action;
107
111 public $tplDir;
112
116 public $tplPath;
117
121 public $topMenu;
122
126 public $rootUrl;
127
131 public $menu_active = array();
132
136 public $eventMessages = array();
137
141 public $tokenKey = 'token';
142
147 public $object;
148
152 public $logged_user = null;
153
157 public $logged_thirdparty = null;
158
162 public $logged_member = null;
163
167 public $logged_partnership = null;
168
172 public $theme;
173
174
180 private function __construct()
181 {
182 global $conf, $db;
183
184 $this->db = $db;
185
186 $this->tplDir = __DIR__ . '/../';
187
188 $this->getControllerUrl();
189
190 $this->topMenu = new stdClass();
191
192 $this->tplPath = realpath(__DIR__ . '/../../public/webportal/tpl');
193
194 $this->controller = GETPOST('controller', 'aZ09'); // for security, limited to 'aZ09'
195 $this->action = GETPOST('action', 'aZ09');// for security, limited to 'aZ09'
196
197 if (empty($this->controller)) {
198 $this->controller = 'default';
199 }
200
201 $this->appliName = getDolGlobalString('WEBPORTAL_TITLE', getDolGlobalString('MAIN_INFO_SOCIETE_NOM'));
202
203 //$this->generateNewToken();
204
205 $this->initController();
206
207 // Init de l'url de base
208 $this->rootUrl = self::getRootConfigUrl();
209
210
211 $this->theme = new WebPortalTheme();
212 }
213
219 public static function getInstance()
220 {
221 if (is_null(self::$_instance)) {
222 self::$_instance = new Context();
223 }
224
225 return self::$_instance;
226 }
227
233 public function initController()
234 {
235 global $db;
236
237 $defaultControllersPath = __DIR__ . '/../controllers/';
238
239 // define controllers definition
240 $this->addControllerDefinition('login', $defaultControllersPath . 'login.controller.class.php', 'LoginController');
241 $this->addControllerDefinition('default', $defaultControllersPath . 'default.controller.class.php', 'DefaultController');
242 $this->addControllerDefinition('document', $defaultControllersPath . 'document.controller.class.php', 'DocumentController');
243 $this->addControllerDefinition('propallist', $defaultControllersPath . 'propallist.controller.class.php', 'PropalListController');
244 $this->addControllerDefinition('orderlist', $defaultControllersPath . 'orderlist.controller.class.php', 'OrderListController');
245 $this->addControllerDefinition('invoicelist', $defaultControllersPath . 'invoicelist.controller.class.php', 'InvoiceListController');
246 $this->addControllerDefinition('membercard', $defaultControllersPath . 'membercard.controller.class.php', 'MemberCardController');
247 $this->addControllerDefinition('partnershipcard', $defaultControllersPath . 'partnershipcard.controller.class.php', 'PartnershipCardController');
248
249 // call triggers
250 //include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
251 //$interface=new Interfaces($db);
252 //$interface->run_triggers('WebPortalInitController', $this, $logged_user, $langs, $conf);
253
254 // search for controller
255 $this->controllerInstance = new Controller();
256 if (isset($this->controllers[$this->controller]) && file_exists($this->controllers[$this->controller]->path)) {
257 require_once $this->controllers[$this->controller]->path;
258
259 if (class_exists($this->controllers[$this->controller]->class)) {
260 $this->controllerInstance = new $this->controllers[$this->controller]->class();
261 $this->setControllerFound();
262 }
263 }
264 }
265
274 public function addControllerDefinition($controller, $path, $className)
275 {
276 $fileName = basename($path);
277 $needle = '.controller.class.php';
278 $length = strlen($needle);
279 $isControllerFile = $length > 0 ? substr($fileName, -$length) === $needle : true;
280 if (!$isControllerFile) {
281 $this->setError('Error: controller definition ' . $fileName);
282 return false;
283 }
284
285 $this->controllers[$controller] = new stdClass();
286 $this->controllers[$controller]->path = $path;
287 $this->controllers[$controller]->class = $className;
288
289 return true;
290 }
291
297 public function setControllerFound()
298 {
299 $this->controller_found = true;
300 }
301
307 public static function getRootConfigUrl()
308 {
309 global $conf;
310
311 // Init de l'url de base
312 if (getDolGlobalString('WEBPORTAL_ROOT_URL')) {
313 $rootUrl = getDolGlobalString('WEBPORTAL_ROOT_URL');
314 if (substr($rootUrl, -1) !== '/') {
315 $rootUrl .= '/';
316 }
317 } else {
318 $rootUrl = dol_buildpath('/public/webportal/', 2);
319 }
320
321 return $rootUrl;
322 }
323
333 public function getRootUrl($controller = '', $moreParams = '', $addToken = true)
334 {
335 return self::getControllerUrl($controller, $moreParams, $addToken);
336 }
337
346 public function getControllerUrl($controller = '', $moreParams = '', $addToken = true)
347 {
348 // TODO : addToken parameter on auto to detect (create or edit) action and add token on url
349 $url = $this->rootUrl;
350
351 if (empty($controller)) {
352 // because can be called without params to get only rootUrl
353 return $url;
354 }
355
356 $Tparams = array();
357
358 $Tparams['controller'] = $controller;
359
360 if (!empty($addToken)) {
361 $Tparams[$this->tokenKey] = $this->newToken();
362 }
363
364 return self::getPublicControllerUrl($controller, $moreParams, $Tparams);
365 }
366
377 public static function getPublicControllerUrl($controller = '', $moreParams = '', $Tparams = array())
378 {
379 $url = self::getRootConfigUrl();
380
381 if (empty($controller)) {
382 // because can be called without params to get only rootUrl
383 return $url;
384 }
385
386 $Tparams['controller'] = $controller;
387
388 // if $moreParams is an array
389 if (!empty($moreParams) && is_array($moreParams)) {
390 if (isset($moreParams['controller'])) {
391 unset($moreParams['controller']);
392 }
393 if (!empty($moreParams)) {
394 foreach ($moreParams as $paramKey => $paramVal) {
395 $Tparams[$paramKey] = $paramVal;
396 }
397 }
398 }
399
400 if (!empty($Tparams)) {
401 $TCompiledAttr = array();
402 foreach ($Tparams as $key => $value) {
403 $TCompiledAttr[] = $key . '=' . $value;
404 }
405 $url .= '?' . implode("&", $TCompiledAttr);
406 }
407
408 // if $moreParams is a string
409 if (!empty($moreParams) && !is_array($moreParams)) {
410 if (empty($Tparams)) {
411 if ($moreParams[0] !== '?') {
412 $url .= '?';
413 }
414 if ($moreParams[0] === '&') {
415 $moreParams = substr($moreParams, 1);
416 }
417 }
418 $url .= $moreParams;
419 }
420
421 return $url;
422 }
423
431 public static function urlOrigin($withRequestUri = true, $use_forwarded_host = false)
432 {
433 $s = $_SERVER;
434
435 $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on');
436 $sp = strtolower($s['SERVER_PROTOCOL']);
437 $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
438 $port = $s['SERVER_PORT'];
439 $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':' . $port;
440 $host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
441 $host = isset($host) ? $host : $s['SERVER_NAME'] . $port;
442
443 $url = $protocol . '://' . $host;
444
445 if ($withRequestUri) {
446 $url .= $s['REQUEST_URI'];
447 }
448
449 return $url;
450 }
451
457 public function userIsLog()
458 {
459 if (!empty($_SESSION["webportal_logged_thirdparty_account_id"])) {
460 return true;
461 } else {
462 return false;
463 }
464 }
465
472 public function menuIsActive($menuName)
473 {
474 return in_array($menuName, $this->menu_active);
475 }
476
483 public function setError($errors)
484 {
485 if (!is_array($errors)) {
486 $errors = array($errors);
487 }
488 if (!isset($_SESSION['webportal_errors'])) {
489 $_SESSION['webportal_errors'] = array();
490 }
491 foreach ($errors as $msg) {
492 if (!in_array($msg, $_SESSION['webportal_errors'])) {
493 $_SESSION['webportal_errors'][] = $msg;
494 }
495 }
496 }
497
503 public function getErrors()
504 {
505 if (!empty($_SESSION['webportal_errors'])) {
506 $this->errors = array_values($_SESSION['webportal_errors']);
507 return count($this->errors);
508 }
509
510 return 0;
511 }
512
518 public function clearErrors()
519 {
520 unset($_SESSION['webportal_errors']);
521 $this->errors = array();
522 }
523
532 public function setEventMessage($mesgs, $style = 'mesgs')
533 {
534 $TAcceptedStyle = array('mesgs', 'warnings', 'errors');
535
536 if (!in_array($style, $TAcceptedStyle)) {
537 $style = 'mesgs';
538 }
539
540 if (!is_array($mesgs)) {
541 $mesgs = array($mesgs);
542 }
543 if (!isset($_SESSION['webportal_events'])) {
544 $_SESSION['webportal_events'] = array(
545 'mesgs' => array(), 'warnings' => array(), 'errors' => array()
546 );
547 }
548
549 foreach ($mesgs as $msg) {
550 if (!in_array($msg, $_SESSION['webportal_events'][$style])) {
551 $_SESSION['webportal_events'][$style][] = $msg;
552 }
553 }
554 }
555
565 public function setEventMessages($mesg, $mesgs, $style = 'mesgs')
566 {
567 if (empty($mesg) && empty($mesgs)) {
568 dol_syslog(__METHOD__ . ' Try to add a message in stack, but value to add is empty message', LOG_WARNING);
569 } else {
570 if (!in_array((string) $style, array('mesgs', 'warnings', 'errors'))) {
571 dol_print_error(null, 'Bad parameter style=' . $style . ' for setEventMessages');
572 }
573 if (empty($mesgs)) {
574 $this->setEventMessage($mesg, $style);
575 } else {
576 if (!empty($mesg) && !in_array($mesg, $mesgs)) {
577 $this->setEventMessage($mesg, $style); // Add message string if not already into array
578 }
579 $this->setEventMessage($mesgs, $style);
580 }
581 }
582 }
583
589 public function loadEventMessages()
590 {
591 if (!empty($_SESSION['webportal_events'])) {
592 $this->eventMessages = $_SESSION['webportal_events'];
593 return 1;
594 }
595
596 return 0;
597 }
598
604 public function clearEventMessages()
605 {
606 unset($_SESSION['webportal_events']);
607 $this->eventMessages = array();
608 }
609
617 public function newToken()
618 {
619 return newToken();
620 }
621
627 protected function generateNewToken()
628 {
629 $currentToken = $this->newToken();
630 // Creation of a token against CSRF vulnerabilities
631 if (!defined('NOTOKENRENEWAL') || empty($currentToken)) {
632 // Rolling token at each call ($_SESSION['token'] contains token of previous page)
633 if (isset($_SESSION['newtoken'])) {
634 $_SESSION['token'] = $_SESSION['newtoken'];
635 }
636
637 // Save what will be next token. Into forms, we will add param $context->newToken();
638 $token = dol_hash(uniqid((string) mt_rand(), true)); // Generate
639 $_SESSION['newtoken'] = $token;
640
641 return $token;
642 } else {
643 return $this->newToken();
644 }
645 }
646
652 public function getUrlToken()
653 {
654 $token = $this->newToken();
655 if ($token) {
656 return '&' . $this->tokenKey . '=' . $this->newToken();
657 }
658
659 return null;
660 }
661
667 public function getFormToken()
668 {
669 $token = $this->newToken();
670 if ($token) {
671 return '<input type="hidden" name="' . $this->tokenKey . '" value="' . $this->newToken() . '" />';
672 }
673
674 return null;
675 }
676
684 public function getThirdPartyAccountFromLogin($login, $pass)
685 {
686 $id = 0;
687
688 $sql = "SELECT sa.rowid as id, sa.pass_crypted";
689 $sql .= " FROM " . $this->db->prefix() . "societe_account as sa";
690 $sql .= " WHERE BINARY sa.login = '" . $this->db->escape($login) . "'"; // case sensitive
691 //$sql .= " AND BINARY sa.pass_crypted = '" . $this->db->escape($pass) . "'"; // case sensitive
692 $sql .= " AND sa.site = 'dolibarr_portal'";
693 $sql .= " AND sa.status = 1";
694 $sql .= " AND sa.entity IN (" . getEntity('societe') . ")";
695
696 dol_syslog(__METHOD__ . ' Try to find the third-party account id for login"' . $login . '" and site="dolibarr_portal"', LOG_DEBUG);
697 $result = $this->db->query($sql);
698 if ($result) {
699 if ($this->db->num_rows($result) == 1) {
700 $passok = false;
701 $obj = $this->db->fetch_object($result);
702 if ($obj) {
703 $passcrypted = $obj->pass_crypted;
704
705 // Check crypted password
706 $cryptType = '';
707 if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) {
708 $cryptType = getDolGlobalString('DATABASE_PWD_ENCRYPTED');
709 }
710
711 // By default, we use default setup for encryption rule
712 if (!in_array($cryptType, array('auto'))) {
713 $cryptType = 'auto';
714 }
715
716 // Check crypted password according to crypt algorithm
717 if ($cryptType == 'auto') {
718 if ($passcrypted && dol_verifyHash($pass, $passcrypted, '0')) {
719 $passok = true;
720 }
721 }
722
723 // Password ok ?
724 if ($passok) {
725 $id = $obj->id;
726 } else {
727 dol_syslog(__METHOD__ .' Authentication KO bad password for ' . $login . ', cryptType=' . $cryptType, LOG_NOTICE);
728 sleep(1); // Brut force protection. Must be same delay when login is not valid
729 return -3;
730 }
731 }
732 } else {
733 dol_syslog(__METHOD__ . ' Many third-party account found for login"' . $login . '" and site="dolibarr_portal"', LOG_ERR);
734 return -2;
735 }
736 } else {
737 $this->error = $this->db->lasterror();
738 return -1;
739 }
740
741 return $id;
742 }
743}
$id
Definition account.php:39
Class Context.
static urlOrigin($withRequestUri=true, $use_forwarded_host=false)
Url origin.
generateNewToken()
Generate new token.
menuIsActive($menuName)
Is menu enabled ?
getErrors()
Get errors.
static getInstance()
Singleton method to create one instance of this object.
$object
Current object of page.
clearEventMessages()
Clear event messages.
getFormToken()
Get token input for form.
newToken()
Return the value of token currently saved into session with name 'newToken'.
setError($errors)
Set errors.
userIsLog()
Check if user is logged.
getUrlToken()
Get token url.
addControllerDefinition($controller, $path, $className)
Add controller definition.
initController()
Init controller.
getRootUrl($controller='', $moreParams='', $addToken=true)
Get root url.
static getPublicControllerUrl($controller='', $moreParams='', $Tparams=array())
Generate public controller URL Used for external link (like email or web page) so remove token and co...
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
getThirdPartyAccountFromLogin($login, $pass)
Try to find the third-party account id from.
setControllerFound()
Set controller found.
getControllerUrl($controller='', $moreParams='', $addToken=true)
Get controller url according to context.
static getRootConfigUrl()
Get WebPortal root url.
$appliName
The application name.
setEventMessage($mesgs, $style='mesgs')
Set event messages in dol_events session object.
__construct()
Constructor.
loadEventMessages()
Load event messages.
clearErrors()
Clear errors.
Class to manage pages.
Class WebPortalTheme.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_verifyHash($chain, $hash, $type='0')
Compute a hash and compare it to the given one For backward compatibility reasons,...
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.