PageRenderTime 265ms CodeModel.GetById 141ms app.highlight 11ms RepoModel.GetById 109ms app.codeStats 1ms

/htdocs/core/lib/security2.lib.php

https://bitbucket.org/speedealing/speedealing
PHP | 260 lines | 156 code | 35 blank | 69 comment | 32 complexity | ce82d864ea4991bff440b814eee5392a MD5 | raw file
  1<?php
  2
  3/* Copyright (C) 2008-2011 Laurent Destailleur  <eldy@users.sourceforge.net>
  4 * Copyright (C) 2008-2012 Regis Houssin        <regis.houssin@capnetworks.com>
  5 * Copyright (C) 2011-2012 Herve Prot           <herve.prot@symeos.com>
  6 *
  7 * This program is free software; you can redistribute it and/or modify
  8 * it under the terms of the GNU General Public License as published by
  9 * the Free Software Foundation; either version 3 of the License, or
 10 * (at your option) any later version.
 11 *
 12 * This program is distributed in the hope that it will be useful,
 13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 15 * GNU General Public License for more details.
 16 *
 17 * You should have received a copy of the GNU General Public License
 18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 19 * or see http://www.gnu.org/
 20 */
 21
 22/**
 23 *  Return user/group account of web server
 24 *
 25 *  @param	string	$mode       'user' or 'group'
 26 *  @return string				Return user or group of web server
 27 */
 28function dol_getwebuser($mode) {
 29    $t = '?';
 30    if ($mode == 'user')
 31        $t = getenv('APACHE_RUN_USER');   // $_ENV['APACHE_RUN_USER'] is empty
 32    if ($mode == 'group')
 33        $t = getenv('APACHE_RUN_GROUP');
 34    return $t;
 35}
 36
 37/**
 38 * Show Dolibarr default login page.
 39 * Part of this code is also duplicated into main.inc.php::top_htmlhead
 40 *
 41 * @param		Translate	$langs		Lang object (must be initialized by a new).
 42 * @param		Conf		$conf		Conf object
 43 * @param		Societe		$mysoc		Company object
 44 * @return		void
 45 */
 46function dol_loginfunction($langs, $conf, $mysoc) {
 47    global $dolibarr_main_demo;
 48    global $hookmanager;
 49
 50    // Instantiate hooks of thirdparty module only if not already define
 51    $hookmanager->initHooks(array('mainloginpage'));
 52
 53    $langcode = (GETPOST('lang') ? ((is_object($langs) && $langs->defaultlang) ? $langs->defaultlang : 'auto') : GETPOST('lang'));
 54    $langs->setDefaultLang($langcode);
 55
 56    $langs->load("main");
 57    $langs->load("other");
 58    $langs->load("help");
 59    $langs->load("admin");
 60
 61    $main_authentication = $conf->file->main_authentication;
 62    $session_name = session_name();
 63
 64    $dol_url_root = DOL_URL_ROOT;
 65
 66    $php_self = $_SERVER['PHP_SELF'];
 67    $php_self.= $_SERVER["QUERY_STRING"] ? '?' . $_SERVER["QUERY_STRING"] : '';
 68
 69    // Title
 70    $title = 'Speedealing ' . DOL_VERSION;
 71
 72    // Select templates
 73    $template_dir = DOL_DOCUMENT_ROOT . "/core/tpl/";
 74
 75    $conf->css = "/theme/" . (GETPOST('theme') ? GETPOST('theme', 'alpha') : $conf->theme) . "/style.css.php?lang=" . $langs->defaultlang;
 76    $conf_css = DOL_URL_ROOT . $conf->css;
 77
 78    // Set cookie for timeout management
 79    $prefix = dol_getprefix();
 80    $sessiontimeout = 'DOLSESSTIMEOUT_' . $prefix;
 81    if (!empty($conf->global->MAIN_SESSION_TIMEOUT))
 82        setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", '', 0);
 83
 84    if (GETPOST('urlfrom', 'alpha'))
 85        $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha');
 86    else
 87        unset($_SESSION["urlfrom"]);
 88
 89    // Show logo (search in order: small company logo, large company logo, theme logo, common logo)
 90    $width = 0;
 91
 92    // Home message
 93    if (!empty($conf->global->MAIN_HOME)) {
 94        $i = 0;
 95        while (preg_match('/__\(([a-zA-Z]+)\)__/i', $conf->global->MAIN_HOME, $reg) && $i < 100) {
 96            $conf->global->MAIN_HOME = preg_replace('/__\(' . $reg[1] . '\)__/i', $langs->trans($reg[1]), $conf->global->MAIN_HOME);
 97            $i++;
 98        }
 99    }
100    $main_home = (!empty($conf->global->MAIN_HOME) ? dol_htmlcleanlastbr($conf->global->MAIN_HOME) : '');
101
102    // Google AD
103    $main_google_ad_client = ((!empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) ? 1 : 0);
104
105    $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : '');
106    $favicon = DOL_URL_ROOT . '/theme/' . $conf->theme . '/img/favicon.ico';
107    $jquerytheme = 'smoothness';
108
109    include $template_dir . 'login.tpl.php'; // To use native PHP
110
111
112    $_SESSION["dol_loginmesg"] = '';
113}
114
115/**
116 *  Fonction pour initialiser un salt pour la fonction crypt.
117 *
118 *  @param		int		$type		2=>renvoi un salt pour cryptage DES
119 * 									12=>renvoi un salt pour cryptage MD5
120 * 									non defini=>renvoi un salt pour cryptage par defaut
121 * 	@return		string				Salt string
122 */
123function makesalt($type = CRYPT_SALT_LENGTH) {
124    dol_syslog("makesalt type=" . $type);
125    switch ($type) {
126        case 12: // 8 + 4
127            $saltlen = 8;
128            $saltprefix = '$1$';
129            $saltsuffix = '$';
130            break;
131        case 8:  // 8 (Pour compatibilite, ne devrait pas etre utilise)
132            $saltlen = 8;
133            $saltprefix = '$1$';
134            $saltsuffix = '$';
135            break;
136        case 2:  // 2
137        default:  // by default, fall back on Standard DES (should work everywhere)
138            $saltlen = 2;
139            $saltprefix = '';
140            $saltsuffix = '';
141            break;
142    }
143    $salt = '';
144    while (dol_strlen($salt) < $saltlen)
145        $salt.=chr(mt_rand(64, 126));
146
147    $result = $saltprefix . $salt . $saltsuffix;
148    dol_syslog("makesalt return=" . $result);
149    return $result;
150}
151
152/**
153 *  Encode or decode database password in config file
154 *
155 *  @param   	int		$level   	Encode level: 0 no encoding, 1 encoding
156 * 	@return		int					<0 if KO, >0 if OK
157 */
158function encodedecode_dbpassconf($level = 0) {
159    dol_syslog("encodedecode_dbpassconf level=" . $level, LOG_DEBUG);
160    $config = '';
161    $passwd = '';
162    $passwd_crypted = '';
163
164    if ($fp = fopen(DOL_DOCUMENT_ROOT . '/conf/conf.php', 'r')) {
165        while (!feof($fp)) {
166            $buffer = fgets($fp, 4096);
167
168            $lineofpass = 0;
169
170            if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { // Old way to save crypted value
171                $val = trim($reg[1]); // This also remove CR/LF
172                $val = preg_replace('/^["\']/', '', $val);
173                $val = preg_replace('/["\'][\s;]*$/', '', $val);
174                if (!empty($val)) {
175                    $passwd_crypted = $val;
176                    $val = dol_decode($val);
177                    $passwd = $val;
178                    $lineofpass = 1;
179                }
180            } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) {
181                $val = trim($reg[1]); // This also remove CR/LF
182                $val = preg_replace('/^["\']/', '', $val);
183                $val = preg_replace('/["\'][\s;]*$/', '', $val);
184                if (preg_match('/crypted:/i', $buffer)) {
185                    $val = preg_replace('/crypted:/i', '', $val);
186                    $passwd_crypted = $val;
187                    $val = dol_decode($val);
188                    $passwd = $val;
189                } else {
190                    $passwd = $val;
191                    $val = dol_encode($val);
192                    $passwd_crypted = $val;
193                }
194                $lineofpass = 1;
195            }
196
197            // Output line
198            if ($lineofpass) {
199                // Add value at end of file
200                if ($level == 0) {
201                    $config .= '$dolibarr_main_db_pass=\'' . $passwd . '\';' . "\n";
202                }
203                if ($level == 1) {
204                    $config .= '$dolibarr_main_db_pass=\'crypted:' . $passwd_crypted . '\';' . "\n";
205                }
206
207                //print 'passwd = '.$passwd.' - passwd_crypted = '.$passwd_crypted;
208                //exit;
209            } else {
210                $config .= $buffer;
211            }
212        }
213        fclose($fp);
214
215        // Write new conf file
216        $file = DOL_DOCUMENT_ROOT . '/conf/conf.php';
217        if ($fp = @fopen($file, 'w')) {
218            fputs($fp, $config);
219            fclose($fp);
220            // It's config file, so we set read permission for creator only.
221            // Should set permission to web user and groups for users used by batch
222            //@chmod($file, octdec('0600'));
223
224            return 1;
225        } else {
226            dol_syslog("encodedecode_dbpassconf Failed to open conf.php file for writing", LOG_WARNING);
227            return -1;
228        }
229    } else {
230        dol_syslog("encodedecode_dbpassconf Failed to read conf.php", LOG_ERR);
231        return -2;
232    }
233}
234
235/**
236 * Return a generated password using default module
237 *
238 * @param		boolean		$generic		true=Create generic password (a MD5 string), false=Use the configured password generation module
239 * @return		string						New value for password
240 */
241function getRandomPassword($generic = false) {
242    global $db, $conf, $langs, $user;
243
244    $generated_password = '';
245    if ($generic)
246        $generated_password = dol_hash(mt_rand());
247    else if ($conf->global->USER_PASSWORD_GENERATED) {
248        $nomclass = "modGeneratePass" . ucfirst($conf->global->USER_PASSWORD_GENERATED);
249        $nomfichier = $nomclass . ".class.php";
250        //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass;
251        require_once(DOL_DOCUMENT_ROOT . "/core/modules/security/generate/" . $nomfichier);
252        $genhandler = new $nomclass($db, $conf, $langs, $user);
253        $generated_password = $genhandler->getNewGeneratedPassword();
254        unset($genhandler);
255    }
256
257    return $generated_password;
258}
259
260?>