/**
  * Connection
  */
 private function connect()
 {
     \DB::$host = $this->host;
     \DB::$port = $this->port;
     \DB::$encoding = $this->encoding;
     \DB::$dbName = $this->dbName;
     \DB::$user = $this->user;
     \DB::$password = $this->password;
 }
Ejemplo n.º 2
0
function teampass_connect()
{
    global $server, $user, $pass, $database, $pre, $link;
    require_once "../includes/settings.php";
    require_once '../includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
}
Ejemplo n.º 3
0
function updateSettings($setting, $val, $type = '')
{
    global $server, $user, $pass, $database, $pre, $port, $encoding;
    if (empty($type)) {
        $type = 'admin';
    }
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    // Connect to database
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    // Check if setting is already in DB. If NO then insert, if YES then update.
    $data = DB::query("SELECT * FROM " . prefix_table("misc") . "\n        WHERE type = %s AND intitule = %s", $type, $setting);
    $counter = DB::count();
    if ($counter == 0) {
        DB::insert(prefix_table("misc"), array('valeur' => $val, 'type' => $type, 'intitule' => $setting));
        // in case of stats enabled, add the actual time
        if ($setting == 'send_stats') {
            DB::insert(prefix_table("misc"), array('valeur' => time(), 'type' => $type, 'intitule' => $setting . '_time'));
        }
    } else {
        DB::update(prefix_table("misc"), array('valeur' => $val), "type = %s AND intitule = %s", $type, $setting);
        // in case of stats enabled, update the actual time
        if ($setting == 'send_stats') {
            // Check if previous time exists, if not them insert this value in DB
            $data_time = DB::query("SELECT * FROM " . prefix_table("misc") . "\n                WHERE type = %s AND intitule = %s", $type, $setting . '_time');
            $counter = DB::count();
            if ($counter == 0) {
                DB::insert(prefix_table("misc"), array('valeur' => 0, 'type' => $type, 'intitule' => $setting . '_time'));
            } else {
                DB::update(prefix_table("misc"), array('valeur' => 0), "type = %s AND intitule = %s", $type, $setting);
            }
        }
    }
    $_SESSION['settings'][$setting] = $val;
}
Ejemplo n.º 4
0
function checkUser($userId, $userKey, $pageVisited)
{
    global $pagesRights;
    if (empty($userId) || empty($pageVisited) || empty($userKey)) {
        return false;
    }
    if (!is_array($pageVisited)) {
        $pageVisited = array($pageVisited);
    }
    include $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    require_once 'main.functions.php';
    // Connect to mysql server
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    // load user's data
    $data = DB::queryfirstrow("SELECT login, key_tempo, admin, gestionnaire FROM " . prefix_table("users") . " WHERE id = %i", $userId);
    // check if user exists and tempo key is coherant
    if (empty($data['login']) || empty($data['key_tempo']) || $data['key_tempo'] != $userKey) {
        return false;
    }
    // check if user is allowed to see this page
    if (empty($data['admin']) && empty($data['gestionnaire']) && !IsInArray($pageVisited, $pagesRights['user'])) {
        return false;
    } else {
        if (empty($data['admin']) && !empty($data['gestionnaire']) && !IsInArray($pageVisited, $pagesRights['manager'])) {
            return false;
        } else {
            if (!empty($data['admin']) && !IsInArray($pageVisited, $pagesRights['admin'])) {
                return false;
            }
        }
    }
    return true;
}
Ejemplo n.º 5
0
 public function __construct($parts = array())
 {
     // Initialize
     global $config, $template;
     // Set variables
     if ($config['is_setup'] == 1 && preg_match("/^admin/", trim($_GET['route'], '/'))) {
         $panel = 'admin';
         $require_login = true;
     } else {
         $panel = 'public';
         $require_login = false;
     }
     // Check IP restrictions
     if ($panel == 'admin' && isset($config['ipallow']) && $config['ipallow'] != '') {
         $ok = false;
         $ips = explode("\n", $config['ipallow']);
         foreach ($ips as $ip) {
             if (preg_match("/^{$ip}/", $_SERVER['REMOTE_ADDR'])) {
                 $ok = true;
                 break;
             }
         }
         if ($ok === false) {
             echo "Access dened by IP restrictions.";
             exit(0);
         }
     }
     // Continue setup, if needed
     if (DBNAME == '' && isset($_POST['submit']) && $_POST['submit'] == tr('Continue to Next Step')) {
         // Initialize
         $template = new template('admin/setup/first_time2');
         require_once SITE_PATH . '/data/lib/sqlparser.php';
         // Check database connection
         if (!mysqli_connect($_POST['dbhost'], $_POST['dbuser'], $_POST['dbpass'], $_POST['dbname'], $_POST['dbport'])) {
             $template->add_message("Unable to connect to mySQL database using information supplied.  Please double check the mySQL information, and try again.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/config.php')) {
             $template->add_message("Unable to write to file at /data/config.php.  Please change file permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/backups')) {
             $template->add_message("Unable to write to directory at /data/backups/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/log')) {
             $template->add_message("Unable to write to directory at /data/log/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         if (!is_writeable(SITE_PATH . '/data/tpl_c')) {
             $template->add_message("Unable to write to directory at /data/tpl_c/.  Please change directory permissions appropriately, and reload the page.", 'error');
         }
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time';
             echo $template->parse();
             exit(0);
         }
         // Define MeekroDB settings
         DB::$dbName = $_POST['dbname'];
         DB::$user = $_POST['dbuser'];
         DB::$password = $_POST['dbpass'];
         DB::$host = $_POST['dbhost'];
         DB::$port = $_POST['dbport'];
         // Parse sql
         $sql_lines = SqlParser::parse(file_get_contents(SITE_PATH . '/data/sql/install.sql'));
         foreach ($sql_lines as $line) {
             DB::query($line);
         }
         // Save config.php file
         $conf = "<?php\n";
         $conf .= "define('DBNAME', '" . $_POST['dbname'] . "');\n";
         $conf .= "define('DBUSER', '" . $_POST['dbuser'] . "');\n";
         $conf .= "define('DBPASS', '" . $_POST['dbpass'] . "');\n";
         $conf .= "define('DBHOST', '" . $_POST['dbhost'] . "');\n";
         $conf .= "define('DBPORT', '" . $_POST['dbport'] . "');\n";
         $conf .= "define('COOKIE_NAME', '" . generate_random_string(6) . "');\n";
         $conf .= "define('ENCRYPT_PASS', '" . generate_random_string(32) . "');\n";
         $conf .= "define('TESTNET', 0);\n";
         $conf .= "?>\n";
         // Save config file
         file_put_contents(SITE_PATH . '/data/config.php', $conf);
         // Parse template
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '2') {
         // Initialize
         $template = new template('admin/setup/first_time3');
         if (strlen($_POST['username']) < 4) {
             $template->add_message('Administrator username must be at least 4 characters in length.', 'error');
         }
         // Create user
         $user = new user();
         $user->create(1);
         // Update config vars
         update_config_var('site_name', $_POST['site_name']);
         update_config_var('company_name', $_POST['company_name']);
         // Check for errors
         if ($template->has_errors == 1) {
             $template->route = 'admin/setup/first_time2';
         } else {
             // Login
             $auth = new auth();
             $auth->login('admin', false);
         }
         echo $template->parse();
         exit(0);
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '3') {
         // Initialize
         $template = new template('admin/setup/first_time4');
         // Update config vars
         update_config_var('btc_rpc_host', $_POST['btc_rpc_host']);
         update_config_var('btc_rpc_user', $_POST['btc_rpc_user']);
         update_config_var('btc_rpc_pass', $_POST['btc_rpc_pass']);
         update_config_var('btc_rpc_port', $_POST['btc_rpc_port']);
         // Test connection
         $client = new transaction();
         if (!$client->get_info()) {
             $template->route = 'admin/setup/first_time3';
             $template->add_message('Unable to connect to RPC using the provided settings.  Please check the connection information, restart bitcoind, and try again.  If you have just started bitcoind for the first time, you will need to wait a while for all blocks to download before continuing.', 'error');
             $template->parse();
             exit(0);
         }
         // Parse template
         echo $template->parse();
         exit(0);
         // Complete setup, if needed
     } elseif ($config['is_setup'] != '1' && isset($_POST['_setup_step']) && $_POST['_setup_step'] == '4') {
         // Initialize
         $template = new template('admin/setup/first_time5');
         // Update config vars
         update_config_var('is_setup', '1');
         // Get exchange date
         $rate = get_coin_exchange_rate($config['currency']);
         if ($rate != 0) {
             update_config_var('exchange_rate', $rate);
         }
         // Add wallet
         $bip32 = new bip32();
         $bip32->add_wallet();
         // Display template
         if ($template->has_errors != 1) {
             //$template->add_message("Successfully completed first time setup.");
         }
         echo $template->parse();
         exit(0);
     }
     // Check if setup
     if ($config['is_setup'] == 0) {
         $template = new template('admin/setup/first_time');
         echo $template->parse();
         exit(0);
     }
     // Check login
     $auth = new auth();
     if ($userid = $auth->check_login($panel, $require_login)) {
         define('LOGIN', true);
         $GLOBALS['userid'] = $userid;
     } else {
         define('LOGIN', false);
         $GLOBALS['userid'] = 0;
     }
     // Check admin permission, if needed
     if ($panel == 'admin') {
         $group_id = DB::queryFirstField("SELECT group_id FROM users WHERE id = %d", $GLOBALS['userid']);
         if ($group_id != 1) {
             trigger_error("You do not have permission to access this area.", E_USER_ERROR);
         }
     }
     // Parse template
     $template = new template();
     echo $template->parse();
     // Exit
     exit(0);
 }
Ejemplo n.º 6
0
<?php

require_once 'db/db.class.php';
include 'config.php';
DB::$host = $MYSQL_SERVER;
DB::$port = $MYSQL_PORT;
DB::$user = $MYSQL_USER;
DB::$password = $MYSQL_PASSWORD;
DB::$dbName = $MYSQL_DATABASE;
DB::$encoding = 'utf8_general_ci';
function connect()
{
    global $MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE;
    $link = mysqli_connect($MYSQL_SERVER, $MYSQL_USER, $MYSQL_PASSWORD);
    if (!$link) {
        die('Could not connect: ' . mysql_error());
    }
    mysqli_set_charset($link, 'UTF-8');
    if (!mysqli_select_db($link, $MYSQL_DATABASE)) {
        echo 'Could not select database';
        exit;
    }
    return $link;
}
Ejemplo n.º 7
0
/**
 * send statistics about your usage of cPassMan.
 * This helps the creator to evaluate the usage you have of the tool.
 */
function teampassStats()
{
    global $server, $user, $pass, $database, $pre, $port, $encoding;
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    // connect to the server
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    // Prepare stats to be sent
    // Count no FOLDERS
    DB::query("SELECT * FROM " . prefix_table("nested_tree") . "");
    $dataFolders = DB::count();
    // Count no USERS
    $dataUsers = DB::query("SELECT * FROM " . $pre . "users");
    $dataUsers = DB::count();
    // Count no ITEMS
    $dataItems = DB::query("SELECT * FROM " . $pre . "items");
    $dataItems = DB::count();
    // Get info about installation
    $dataSystem = array();
    $rows = DB::query("SELECT valeur,intitule FROM " . $pre . "misc\n        WHERE type = %s\n        AND intitule = %ls", 'admin', array('enable_pf_feature', 'log_connections', 'cpassman_version'));
    foreach ($rows as $record) {
        if ($record['intitule'] == 'enable_pf_feature') {
            $dataSystem['enable_pf_feature'] = $record['valeur'];
        } elseif ($record['intitule'] == 'cpassman_version') {
            $dataSystem['cpassman_version'] = $record['valeur'];
        } elseif ($record['intitule'] == 'log_connections') {
            $dataSystem['log_connections'] = $record['valeur'];
        }
    }
    // Get the actual stats.
    $statsToSend = array('uid' => md5(SALT), 'time_added' => time(), 'users' => $dataUsers[0], 'folders' => $dataFolders[0], 'items' => $dataItems[0], 'cpm_version' => $dataSystem['cpassman_version'], 'enable_pf_feature' => $dataSystem['enable_pf_feature'], 'log_connections' => $dataSystem['log_connections']);
    // Encode all the data, for security.
    foreach ($statsToSend as $k => $v) {
        $statsToSend[$k] = urlencode($k) . '=' . urlencode($v);
    }
    // Turn this into the query string!
    $statsToSend = implode('&', $statsToSend);
    fopen("http://www.teampass.net/files/cpm_stats/collect_stats.php?" . $statsToSend, 'r');
    // update the actual time
    DB::update($pre . "misc", array('valeur' => time()), "type = %s AND intitule = %s", 'admin', 'send_stats_time');
}
Ejemplo n.º 8
0
function logItems($id, $item, $id_user, $action, $login = "", $raison = NULL, $raison_iv = NULL)
{
    global $server, $user, $pass, $database, $pre, $port, $encoding;
    // include librairies & connect to DB
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    DB::insert(prefix_table("log_items"), array('id_item' => $id, 'date' => time(), 'id_user' => $id_user, 'action' => $action, 'raison' => $raison, 'raison_iv' => $raison_iv));
    if (isset($_SESSION['settings']['syslog_enable']) && $_SESSION['settings']['syslog_enable'] == 1) {
        send_syslog("The Item " . $item . " was " . $action . " by " . $login . " " . $raison, "teampass", "php", $_SESSION['settings']['syslog_host'], $_SESSION['settings']['syslog_port']);
    }
}
Ejemplo n.º 9
0
<?php

/* ========================================================
 * Project:     PandaHat
 * Author:      Panda_M
 * Created:     2015-11-08
 * Modified:    2015-11-08
 * ========================================================
 */
//TODO: Replace hard-coded login with access to config file.
require_once 'meekrodb.2.3.class.php';
DB::$user = '******';
DB::$password = '******';
DB::$dbName = 'panda_hat';
DB::$host = 'ix-trusty.cs.uoregon.edu';
DB::$port = '3022';
//DEBUG:
//echo 'configuredb.php has finished configuring (no connection until 1st query).' . '<br>';
/*
echo '
<html> <head> <title>SomeTitle</title> </head>
       <body bgcolor="white"> <hr> A Header. </hr> </body>

       </html>
       ';
*/
Ejemplo n.º 10
0
/**
 * handleConfigFile()
 *
 * permits to handle the Teampass config file
 * $action accepts "rebuild" and "update"
 */
function handleConfigFile($action, $field = null, $value = null)
{
    global $server, $user, $pass, $database, $pre, $port, $encoding;
    $tp_config_file = "../includes/config/tp.config.php";
    // include librairies & connect to DB
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    if (!file_exists($tp_config_file) || $action == "rebuild") {
        // perform a copy
        if (file_exists($tp_config_file)) {
            if (!copy($tp_config_file, $tp_config_file . '.' . date("Y_m_d_His", time()))) {
                return "ERROR: Could not copy file '" . $tp_config_file . "'";
            }
        }
        // regenerate
        $data = array();
        $data[0] = "<?php\n";
        $data[1] = "global \$SETTINGS;\n";
        $data[2] = "\$SETTINGS = array (\n";
        $rows = DB::query("SELECT * FROM " . prefix_table("misc") . " WHERE type=%s", "admin");
        foreach ($rows as $record) {
            array_push($data, "    '" . $record['intitule'] . "' => '" . $record['valeur'] . "',\n");
        }
        array_push($data, ");");
        $dat = array_unique($data);
    } else {
        if ($action == "update" && !empty($field)) {
            $data = file($tp_config_file);
            $x = 0;
            $bFound = false;
            foreach ($data as $line) {
                if (stristr($line, ");")) {
                    break;
                }
                if (stristr($line, "'" . $field . "' => '")) {
                    $data[$x] = "    '" . $field . "' => '" . $value . "',\n";
                    $bFound = true;
                    break;
                }
                $x++;
            }
            if ($bFound === false) {
                $data[$x - 1] = "    '" . $field . "' => '" . $value . "',\n";
            }
        } else {
            // ERROR
        }
    }
    // update file
    file_put_contents($tp_config_file, implode('', $data));
    return true;
}
Ejemplo n.º 11
0
<?php

// Using meekrodb for connection and better security
require_once 'includes/MeekroDB/meekrodb.2.1.class.php';
if ($db_port == '') {
    $db_port = '3306';
}
DB::$user = $db_user;
DB::$password = $db_password;
DB::$dbName = $db_Name;
$dbTable = $db_Table;
DB::$port = $db_port;
// the sql for indfex.php is in dbFunctions.php
Ejemplo n.º 12
0
	text-decoration: underline;
}
.table {
border:solid 1px #336699;
}
</style>


<?php 
require_once 'includes/MeekroDB/meekrodb.2.1.class.php';
DB::debugMode();
DB::$user = '******';
DB::$password = '******';
DB::$dbName = 'a1-sales';
$dbTable = 'customers';
DB::$port = '3307';
$mysqli_result = DB::queryRaw("SELECT * FROM " . $dbTable);
$row = $mysqli_result->fetch_assoc();
$field_cnt = count($row);
echo "FieldCount = " . $field_cnt . "<br>";
$columns = DB::columnList('customers');
echo "COPY THIS STRING FOR THE FIELD NAMES: ";
foreach ($columns as $column) {
    echo "{$column}\n,";
}
echo "<br>";
/* Get field information for all columns */
$finfo = $mysqli_result->fetch_fields();
echo "1) length is the Max-length allowed in that field" . "<br>";
echo "2) Max-length is the longest string in that field" . "<br>";
echo "3) Type is the mySQLi Field Tyoe" . "<br>";
Ejemplo n.º 13
0
ini_set('pcre.backtrack_limit', '4M');
// Register autoload function
spl_autoload_register('autoload_class');
// Security checks
//security_checks();
// Load needed files
require_once "data/config.php";
require_once "data/lib/functions.php";
require_once "data/lib/db/meekrodb.2.3.class.php";
require_once "data/lib/smarty/Smarty.class.php";
// Define database connection info (MeekroDB) -- connects to database upon first query
DB::$dbName = DBNAME;
DB::$user = DBUSER;
DB::$password = DBPASS;
DB::$host = DBHOST;
DB::$port = DBPORT;
// Load, if setup complete
$config = array('is_setup' => '0');
if (DBNAME != '') {
    $result = DB::query("SELECT name,value FROM config");
    foreach ($result as $row) {
        $config[$row['name']] = $row['value'];
    }
    // Set default time zone
    date_default_timezone_set($config['timezone']);
}
// Set error handler
set_error_handler('error', E_ALL);
// Define registry
$registry = new stdClass();
/////////////////////////////////////////////////////////////////////////////
Ejemplo n.º 14
0
<?php

DB::$user = $app->config('db.user');
DB::$password = $app->config('db.password');
DB::$dbName = $app->config('db.name');
DB::$host = $app->config('db.host');
DB::$port = $app->config('db.port');
DB::$encoding = $app->config('db.encoding');
Ejemplo n.º 15
0
function identifyUser($sentData)
{
    global $debugLdap, $debugDuo, $k;
    include $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
    header("Content-type: text/html; charset=utf-8");
    error_reporting(E_ERROR);
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
    require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
    if ($debugDuo == 1) {
        $dbgDuo = fopen($_SESSION['settings']['path_to_files_folder'] . "/duo.debug.txt", "a");
    }
    /*
    if (empty($sentData) && isset($_COOKIE['TeamPassC'])) {
    	$sentData = prepareExchangedData($_COOKIE['TeamPassC'], "encode");
    	setcookie('TeamPassC', "", time()-3600);
    }
    */
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Content of data sent '" . $sentData . "'\n");
    }
    // connect to the server
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
    DB::$host = $server;
    DB::$user = $user;
    DB::$password = $pass;
    DB::$dbName = $database;
    DB::$port = $port;
    DB::$encoding = $encoding;
    DB::$error_handler = 'db_error_handler';
    $link = mysqli_connect($server, $user, $pass, $database, $port);
    $link->set_charset($encoding);
    //Load AES
    $aes = new SplClassLoader('Encryption\\Crypt', '../includes/libraries');
    $aes->register();
    // load passwordLib library
    $pwdlib = new SplClassLoader('PasswordLib', '../includes/libraries');
    $pwdlib->register();
    $pwdlib = new PasswordLib\PasswordLib();
    // User's language loading
    $k['langage'] = @$_SESSION['user_language'];
    require_once $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '.php';
    // decrypt and retreive data in JSON format
    $dataReceived = prepareExchangedData($sentData, "decode");
    // Prepare variables
    $passwordClear = htmlspecialchars_decode($dataReceived['pw']);
    $passwordOldEncryption = encryptOld(htmlspecialchars_decode($dataReceived['pw']));
    $username = htmlspecialchars_decode($dataReceived['login']);
    $logError = "";
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Starting authentication of '" . $username . "'\n");
    }
    // GET SALT KEY LENGTH
    if (strlen(SALT) > 32) {
        $_SESSION['error']['salt'] = true;
    }
    $_SESSION['user_language'] = $k['langage'];
    $ldapConnection = false;
    /* LDAP connection */
    if ($debugLdap == 1) {
        // create temp file
        $dbgLdap = fopen($_SESSION['settings']['path_to_files_folder'] . "/ldap.debug.txt", "w");
        fputs($dbgLdap, "Get all LDAP params : \n" . 'mode : ' . $_SESSION['settings']['ldap_mode'] . "\n" . 'type : ' . $_SESSION['settings']['ldap_type'] . "\n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'search_base : ' . $_SESSION['settings']['ldap_search_base'] . "\n" . 'bind_dn : ' . $_SESSION['settings']['ldap_bind_dn'] . "\n" . 'bind_passwd : ' . $_SESSION['settings']['ldap_bind_passwd'] . "\n" . 'user_attribute : ' . $_SESSION['settings']['ldap_user_attribute'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "LDAP status: " . $_SESSION['settings']['ldap_mode'] . "\n");
    }
    if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username != "admin") {
        //Multiple Domain Names
        if (strpos(html_entity_decode($username), '\\') == true) {
            $ldap_suffix = "@" . substr(html_entity_decode($username), 0, strpos(html_entity_decode($username), '\\'));
            $username = substr(html_entity_decode($username), strpos(html_entity_decode($username), '\\') + 1);
        }
        if ($_SESSION['settings']['ldap_type'] == 'posix-search') {
            $ldapconn = ldap_connect($_SESSION['settings']['ldap_domain_controler']);
            if ($debugLdap == 1) {
                fputs($dbgLdap, "LDAP connection : " . ($ldapconn ? "Connected" : "Failed") . "\n");
            }
            ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
            if ($ldapconn) {
                $ldapbind = ldap_bind($ldapconn, $_SESSION['settings']['ldap_bind_dn'], $_SESSION['settings']['ldap_bind_passwd']);
                if ($debugLdap == 1) {
                    fputs($dbgLdap, "LDAP bind : " . ($ldapbind ? "Bound" : "Failed") . "\n");
                }
                if ($ldapbind) {
                    $filter = "(&(" . $_SESSION['settings']['ldap_user_attribute'] . "={$username})(objectClass=posixAccount))";
                    $result = ldap_search($ldapconn, $_SESSION['settings']['ldap_search_base'], $filter, array('dn'));
                    if ($debugLdap == 1) {
                        fputs($dbgLdap, 'Search filter : ' . $filter . "\n" . 'Results : ' . print_r(ldap_get_entries($ldapconn, $result), true) . "\n");
                    }
                    if (ldap_count_entries($ldapconn, $result)) {
                        // try auth
                        $result = ldap_get_entries($ldapconn, $result);
                        $user_dn = $result[0]['dn'];
                        $ldapbind = ldap_bind($ldapconn, $user_dn, $passwordClear);
                        if ($ldapbind) {
                            $ldapConnection = true;
                        } else {
                            $ldapConnection = false;
                        }
                    }
                } else {
                    $ldapConnection = false;
                }
            } else {
                $ldapConnection = false;
            }
        } else {
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Get all ldap params : \n" . 'base_dn : ' . $_SESSION['settings']['ldap_domain_dn'] . "\n" . 'account_suffix : ' . $_SESSION['settings']['ldap_suffix'] . "\n" . 'domain_controllers : ' . $_SESSION['settings']['ldap_domain_controler'] . "\n" . 'use_ssl : ' . $_SESSION['settings']['ldap_ssl'] . "\n" . 'use_tls : ' . $_SESSION['settings']['ldap_tls'] . "\n*********\n\n");
            }
            $adldap = new SplClassLoader('LDAP\\adLDAP', '../includes/libraries');
            $adldap->register();
            // Posix style LDAP handles user searches a bit differently
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $ldap_suffix = ',' . $_SESSION['settings']['ldap_suffix'] . ',' . $_SESSION['settings']['ldap_domain_dn'];
            } elseif ($_SESSION['settings']['ldap_type'] == 'windows' and $ldap_suffix == '') {
                //Multiple Domain Names
                $ldap_suffix = $_SESSION['settings']['ldap_suffix'];
            }
            $adldap = new LDAP\adLDAP\adLDAP(array('base_dn' => $_SESSION['settings']['ldap_domain_dn'], 'account_suffix' => $ldap_suffix, 'domain_controllers' => explode(",", $_SESSION['settings']['ldap_domain_controler']), 'use_ssl' => $_SESSION['settings']['ldap_ssl'], 'use_tls' => $_SESSION['settings']['ldap_tls']));
            if ($debugLdap == 1) {
                fputs($dbgLdap, "Create new adldap object : " . $adldap->get_last_error() . "\n\n\n");
                //Debug
            }
            // openLDAP expects an attribute=value pair
            if ($_SESSION['settings']['ldap_type'] == 'posix') {
                $auth_username = $_SESSION['settings']['ldap_user_attribute'] . '=' . $username;
            } else {
                $auth_username = $username;
            }
            // authenticate the user
            if ($adldap->authenticate($auth_username, html_entity_decode($passwordClear))) {
                $ldapConnection = true;
                //update user's password
                $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
                DB::update(prefix_table('users'), array('pw' => $data['pw']), "login=%s", $username);
            } else {
                $ldapConnection = false;
            }
            if ($debugLdap == 1) {
                fputs($dbgLdap, "After authenticate : " . $adldap->get_last_error() . "\n\n\n" . "ldap status : " . $ldapConnection . "\n\n\n");
                //Debug
            }
        }
    } else {
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2) {
            // nothing
        }
    }
    // Check if user exists
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists: " . $counter . "\n");
    }
    // Check PSK
    if (isset($_SESSION['settings']['psk_authentication']) && $_SESSION['settings']['psk_authentication'] == 1 && $data['admin'] != 1) {
        $psk = htmlspecialchars_decode($dataReceived['psk']);
        $pskConfirm = htmlspecialchars_decode($dataReceived['psk_confirm']);
        if (empty($psk)) {
            echo '[{"value" : "psk_required"}]';
            exit;
        } elseif (empty($data['psk'])) {
            if (empty($pskConfirm)) {
                echo '[{"value" : "bad_psk_confirmation"}]';
                exit;
            } else {
                $_SESSION['my_sk'] = $psk;
            }
        } elseif ($pwdlib->verifyPasswordHash($psk, $data['psk']) === true) {
            echo '[{"value" : "bad_psk"}]';
            exit;
        }
    }
    $proceedIdentification = false;
    if ($counter > 0) {
        $proceedIdentification = true;
    } elseif ($counter == 0 && $ldapConnection == true && isset($_SESSION['settings']['ldap_elusers']) && $_SESSION['settings']['ldap_elusers'] == 0) {
        // If LDAP enabled, create user in CPM if doesn't exist
        $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
        // create passwordhash
        DB::insert(prefix_table('users'), array('login' => $username, 'pw' => $data['pw'], 'email' => "", 'admin' => '0', 'gestionnaire' => '0', 'personal_folder' => $_SESSION['settings']['enable_pf_feature'] == "1" ? '1' : '0', 'fonction_id' => '0', 'groupes_interdits' => '0', 'groupes_visibles' => '0', 'last_pw_change' => time(), 'user_language' => $_SESSION['settings']['default_language']));
        $newUserId = DB::insertId();
        // Create personnal folder
        if ($_SESSION['settings']['enable_pf_feature'] == "1") {
            DB::insert(prefix_table("nested_tree"), array('parent_id' => '0', 'title' => $newUserId, 'bloquer_creation' => '0', 'bloquer_modification' => '0', 'personal_folder' => '1'));
        }
        // Get info for user
        //$sql = "SELECT * FROM ".prefix_table("users")." WHERE login = '******'";
        //$row = $db->query($sql);
        $proceedIdentification = true;
    }
    // Check if user exists (and has been created in case of new LDAP user)
    $data = DB::queryFirstRow("SELECT * FROM " . prefix_table("users") . " WHERE login=%s_login", array('login' => $username));
    $counter = DB::count();
    if ($counter == 0) {
        echo '[{"value" : "user_not_exists", "text":""}]';
        exit;
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "USer exists (confirm): " . $counter . "\n");
    }
    // check GA code
    if (isset($_SESSION['settings']['2factors_authentication']) && $_SESSION['settings']['2factors_authentication'] == 1 && $username != "admin") {
        if (isset($dataReceived['GACode']) && !empty($dataReceived['GACode'])) {
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/FixedBitNotation.php";
            include_once $_SESSION['settings']['cpassman_dir'] . "/includes/libraries/Authentication/GoogleAuthenticator/GoogleAuthenticator.php";
            $g = new Authentication\GoogleAuthenticator\GoogleAuthenticator();
            if ($g->checkCode($data['ga'], $dataReceived['GACode'])) {
                $proceedIdentification = true;
            } else {
                $proceedIdentification = false;
                $logError = "ga_code_wrong";
            }
        } else {
            $proceedIdentification = false;
            $logError = "ga_code_wrong";
        }
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "Proceed with Ident: " . $proceedIdentification . "\n");
    }
    if ($proceedIdentification === true) {
        // User exists in the DB
        //$data = $db->fetchArray($row);
        //v2.1.17 -> change encryption for users password
        if ($passwordOldEncryption == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = bCrypt($passwordClear, COST);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        if (crypt($passwordClear, $data['pw']) == $data['pw'] && !empty($data['pw'])) {
            //update user's password
            $data['pw'] = $pwdlib->createPasswordHash($passwordClear);
            DB::update(prefix_table('users'), array('pw' => $data['pw']), "id=%i", $data['id']);
        }
        // check the given password
        if ($pwdlib->verifyPasswordHash($passwordClear, $data['pw']) === true) {
            $userPasswordVerified = true;
        } else {
            $userPasswordVerified = false;
        }
        if ($debugDuo == 1) {
            fputs($dbgDuo, "User's password verified: " . $userPasswordVerified . "\n");
        }
        // Can connect if
        // 1- no LDAP mode + user enabled + pw ok
        // 2- LDAP mode + user enabled + ldap connection ok + user is not admin
        // 3-  LDAP mode + user enabled + pw ok + usre is admin
        // This in order to allow admin by default to connect even if LDAP is activated
        if (isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 0 && $userPasswordVerified == true && $data['disabled'] == 0 || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 2 && $ldapConnection == true && $data['disabled'] == 0 && $username != "admin" || isset($_SESSION['settings']['ldap_mode']) && $_SESSION['settings']['ldap_mode'] == 1 && $username == "admin" && $userPasswordVerified == true && $data['disabled'] == 0) {
            $_SESSION['autoriser'] = true;
            // Generate a ramdom ID
            $key = $pwdlib->getRandomToken(50);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "User's token: " . $key . "\n");
            }
            // Log into DB the user's connection
            if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                logEvents('user_connection', 'connection', $data['id']);
            }
            // Save account in SESSION
            $_SESSION['login'] = stripslashes($username);
            $_SESSION['name'] = stripslashes($data['name']);
            $_SESSION['lastname'] = stripslashes($data['lastname']);
            $_SESSION['user_id'] = $data['id'];
            $_SESSION['user_admin'] = $data['admin'];
            $_SESSION['user_manager'] = $data['gestionnaire'];
            $_SESSION['user_read_only'] = $data['read_only'];
            $_SESSION['last_pw_change'] = $data['last_pw_change'];
            $_SESSION['last_pw'] = $data['last_pw'];
            $_SESSION['can_create_root_folder'] = $data['can_create_root_folder'];
            $_SESSION['key'] = $key;
            $_SESSION['personal_folder'] = $data['personal_folder'];
            $_SESSION['user_language'] = $data['user_language'];
            $_SESSION['user_email'] = $data['email'];
            $_SESSION['user_ga'] = $data['ga'];
            $_SESSION['user_avatar'] = $data['avatar'];
            $_SESSION['user_avatar_thumb'] = $data['avatar_thumb'];
            $_SESSION['user_upgrade_needed'] = $data['upgrade_needed'];
            // manage session expiration
            $serverTime = time();
            if ($dataReceived['TimezoneOffset'] > 0) {
                $userTime = $serverTime + $dataReceived['TimezoneOffset'];
            } else {
                $userTime = $serverTime;
            }
            $_SESSION['fin_session'] = $userTime + $dataReceived['duree_session'] * 60;
            /* If this option is set user password MD5 is used as personal SALTKey */
            if (isset($_SESSION['settings']['use_md5_password_as_salt']) && $_SESSION['settings']['use_md5_password_as_salt'] == 1) {
                $_SESSION['my_sk'] = md5($passwordClear);
                setcookie("TeamPass_PFSK_" . md5($_SESSION['user_id']), encrypt($_SESSION['my_sk'], ""), time() + 60 * 60 * 24 * $_SESSION['settings']['personal_saltkey_cookie_duration'], '/');
            }
            @syslog(LOG_WARNING, "User logged in - " . $_SESSION['user_id'] . " - " . date("Y/m/d H:i:s") . " {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']})");
            if (empty($data['last_connexion'])) {
                $_SESSION['derniere_connexion'] = time();
            } else {
                $_SESSION['derniere_connexion'] = $data['last_connexion'];
            }
            if (!empty($data['latest_items'])) {
                $_SESSION['latest_items'] = explode(';', $data['latest_items']);
            } else {
                $_SESSION['latest_items'] = array();
            }
            if (!empty($data['favourites'])) {
                $_SESSION['favourites'] = explode(';', $data['favourites']);
            } else {
                $_SESSION['favourites'] = array();
            }
            if (!empty($data['groupes_visibles'])) {
                $_SESSION['groupes_visibles'] = @implode(';', $data['groupes_visibles']);
            } else {
                $_SESSION['groupes_visibles'] = array();
            }
            if (!empty($data['groupes_interdits'])) {
                $_SESSION['groupes_interdits'] = @implode(';', $data['groupes_interdits']);
            } else {
                $_SESSION['groupes_interdits'] = array();
            }
            // User's roles
            $_SESSION['fonction_id'] = $data['fonction_id'];
            $_SESSION['user_roles'] = explode(";", $data['fonction_id']);
            // build array of roles
            $_SESSION['user_pw_complexity'] = 0;
            $_SESSION['arr_roles'] = array();
            foreach (array_filter(explode(';', $_SESSION['fonction_id'])) as $role) {
                $resRoles = DB::queryFirstRow("SELECT title, complexity FROM " . prefix_table("roles_title") . " WHERE id=%i", $role);
                $_SESSION['arr_roles'][$role] = array('id' => $role, 'title' => $resRoles['title']);
                // get highest complexity
                if ($_SESSION['user_pw_complexity'] < $resRoles['complexity']) {
                    $_SESSION['user_pw_complexity'] = $resRoles['complexity'];
                }
            }
            // build complete array of roles
            $_SESSION['arr_roles_full'] = array();
            $rows = DB::query("SELECT id, title FROM " . prefix_table("roles_title") . " ORDER BY title ASC");
            foreach ($rows as $record) {
                $_SESSION['arr_roles_full'][$record['id']] = array('id' => $record['id'], 'title' => $record['title']);
            }
            // Set some settings
            $_SESSION['user']['find_cookie'] = false;
            $_SESSION['settings']['update_needed'] = "";
            // Update table
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'timestamp' => time(), 'disabled' => 0, 'no_bad_attempts' => 0, 'session_end' => $_SESSION['fin_session'], 'psk' => $pwdlib->createPasswordHash(htmlspecialchars_decode($psk))), "id=%i", $data['id']);
            if ($debugDuo == 1) {
                fputs($dbgDuo, "Preparing to identify the user rights\n");
            }
            // Get user's rights
            identifyUserRights($data['groupes_visibles'], $_SESSION['groupes_interdits'], $data['admin'], $data['fonction_id'], false);
            // Get some more elements
            $_SESSION['screenHeight'] = $dataReceived['screenHeight'];
            // Get last seen items
            $_SESSION['latest_items_tab'][] = "";
            foreach ($_SESSION['latest_items'] as $item) {
                if (!empty($item)) {
                    $data = DB::queryFirstRow("SELECT id,label,id_tree FROM " . prefix_table("items") . " WHERE id=%i", $item);
                    $_SESSION['latest_items_tab'][$item] = array('id' => $item, 'label' => $data['label'], 'url' => 'index.php?page=items&amp;group=' . $data['id_tree'] . '&amp;id=' . $item);
                }
            }
            // send back the random key
            $return = $dataReceived['randomstring'];
            // Send email
            if (isset($_SESSION['settings']['enable_send_email_on_user_login']) && $_SESSION['settings']['enable_send_email_on_user_login'] == 1 && $_SESSION['user_admin'] != 1) {
                // get all Admin users
                $receivers = "";
                $rows = DB::query("SELECT email FROM " . prefix_table("users") . " WHERE admin = %i", 1);
                foreach ($rows as $record) {
                    if (empty($receivers)) {
                        $receivers = $record['email'];
                    } else {
                        $receivers = "," . $record['email'];
                    }
                }
                // Add email to table
                DB::insert(prefix_table("emails"), array('timestamp' => time(), 'subject' => $LANG['email_subject_on_user_login'], 'body' => str_replace(array('#tp_user#', '#tp_date#', '#tp_time#'), array(" " . $_SESSION['login'], date($_SESSION['settings']['date_format'], $_SESSION['derniere_connexion']), date($_SESSION['settings']['time_format'], $_SESSION['derniere_connexion'])), $LANG['email_body_on_user_login']), 'receivers' => $receivers, 'status' => "not sent"));
            }
        } elseif ($data['disabled'] == 1) {
            // User and password is okay but account is locked
            $return = "user_is_locked";
        } else {
            // User exists in the DB but Password is false
            // check if user is locked
            $userIsLocked = 0;
            $nbAttempts = intval($data['no_bad_attempts'] + 1);
            if ($_SESSION['settings']['nb_bad_authentication'] > 0 && intval($_SESSION['settings']['nb_bad_authentication']) < $nbAttempts) {
                $userIsLocked = 1;
                // log it
                if (isset($_SESSION['settings']['log_connections']) && $_SESSION['settings']['log_connections'] == 1) {
                    logEvents('user_locked', 'connection', $data['id']);
                }
            }
            DB::update(prefix_table('users'), array('key_tempo' => $_SESSION['key'], 'last_connexion' => time(), 'disabled' => $userIsLocked, 'no_bad_attempts' => $nbAttempts), "id=%i", $data['id']);
            // What return shoulb we do
            if ($userIsLocked == 1) {
                $return = "user_is_locked";
            } elseif ($_SESSION['settings']['nb_bad_authentication'] == 0) {
                $return = "false";
            } else {
                $return = $nbAttempts;
            }
        }
    } else {
        $return = "false";
    }
    if ($debugDuo == 1) {
        fputs($dbgDuo, "\n\n----\n" . "Identified : " . $return . "\n");
    }
    echo '[{"value" : "' . $return . '", "user_admin":"', isset($_SESSION['user_admin']) ? $_SESSION['user_admin'] : "", '", "initial_url" : "' . @$_SESSION['initial_url'] . '",
            "error" : "' . $logError . '"}]';
    $_SESSION['initial_url'] = "";
    if ($_SESSION['settings']['cpassman_dir'] == "..") {
        $_SESSION['settings']['cpassman_dir'] = ".";
    }
}
Ejemplo n.º 16
0
    //not allowed page
    include $_SESSION['settings']['cpassman_dir'] . '/error.php';
    exit;
}
include $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '.php';
include $_SESSION['settings']['cpassman_dir'] . '/includes/settings.php';
header("Content-type: text/html; charset=utf-8");
require_once 'main.functions.php';
require_once $_SESSION['settings']['cpassman_dir'] . '/sources/SplClassLoader.php';
//Connect to DB
require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/Database/Meekrodb/db.class.php';
DB::$host = $server;
DB::$user = $user;
DB::$password = $pass;
DB::$dbName = $database;
DB::$port = $port;
DB::$encoding = $encoding;
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);
$link->set_charset($encoding);
//Build tree
$tree = new SplClassLoader('Tree\\NestedTree', $_SESSION['settings']['cpassman_dir'] . '/includes/libraries');
$tree->register();
$tree = new Tree\NestedTree\NestedTree($pre . 'nested_tree', 'id', 'parent_id', 'title');
if (!empty($_POST['type'])) {
    switch ($_POST['type']) {
        #CASE adding a new role
        case "add_new_role":
            //Check if role already exist : No similar roles
            $tmp = DB::query("SELECT * FROM " . prefix_table("roles_title") . " WHERE title = %s", stripslashes($_POST['name']));
            $counter = DB::count();
Ejemplo n.º 17
0
    $out[] = "";
    if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
        echo implode("\n", $out);
    } else {
        echo implode("<br>\n", $out);
    }
    debug_print_backtrace();
    die;
}
function meekrodb_debugmode_handler($params)
{
    echo "QUERY: " . $params['query'] . " [" . $params['runtime'] . " ms]";
    if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
        echo "\n";
    } else {
        echo "<br>\n";
    }
}
class MeekroDBEval
{
    public $text = '';
    function __construct($text)
    {
        $this->text = $text;
    }
}
DB::$host = $mysql_host;
DB::$port = $mysql_port;
DB::$user = $mysql_user;
DB::$password = $mysql_pass;
DB::$dbName = $mysql_db;