Exemplo n.º 1
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;
}
Exemplo n.º 2
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;
}
Exemplo n.º 3
0
                <input type="radio" id="modify_kb_no" name="modify_kb" value="0" /><label for="modify_kb_no">' . $LANG['no'] . '</label>
            </span>
        </div>
    </div>

    <div style="float:left;width:100%;">
        <label for="kb_description" class="label">' . $LANG['description'] . '</label>
        <textarea rows="5" name="kb_description" id="kb_description" class="input"></textarea>
    </div>

    <div style="float:left;width:100%;margin-top:15px;">
        <label for="kb_associated_to" class="label">' . $LANG['associate_kb_to_items'] . '</label>
        <select id="kb_associated_to" class="multiselect" multiple="multiple" name="kb_associated_to[]" style="width: 860px; height: 150px;">';
//get list of available items
$items_id_list = array();
$rows = DB::query("SELECT i.id as id, i.restricted_to as restricted_to, i.perso as perso, i.label as label, i.description as description, i.pw as pw, i.login as login, i.anyone_can_modify as anyone_can_modify,\n                    l.date as date,\n                    n.renewal_period as renewal_period\n                FROM " . prefix_table("items") . " as i\n                INNER JOIN " . prefix_table("nested_tree") . " as n ON (i.id_tree = n.id)\n                INNER JOIN " . prefix_table("log_items") . " as l ON (i.id = l.id_item)\n                WHERE i.inactif = %i\n                AND (l.action = %s OR (l.action = %s AND l.raison LIKE %s))\n                ORDER BY i.label ASC, l.date DESC", '0', 'at_creation', 'at_modification', 'at_pw :%');
foreach ($rows as $reccord) {
    if (!in_array($reccord['id'], $items_id_list) && !empty($reccord['label'])) {
        echo '
        <option value="' . $reccord['id'] . '">' . $reccord['label'] . '</option>';
        array_push($items_id_list, $reccord['id']);
    }
}
echo '
        </select>
    </div>
</div>';
//DELETE DIALOG
echo '
<div id="div_kb_delete" style="display:none;">
    <p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;">&nbsp;</span>' . $LANG['confirm_deletion'] . '</p>
Exemplo n.º 4
0
 DB::$encoding = $encoding;
 DB::$error_handler = 'db_error_handler';
 $link = mysqli_connect($server, $user, $pass, $database, $port);
 $link->set_charset($encoding);
 // check session validity
 $data = DB::queryfirstrow("SELECT timestamp, code, item_id FROM " . prefix_table("otv") . "\n        WHERE id = %i", intval($_GET['otv_id']));
 if ($data['timestamp'] == $_GET['stamp'] && $data['code'] == $_GET['code'] && $data['item_id'] == $_GET['item_id']) {
     // otv is too old
     if ($data['timestamp'] < time() - $_SESSION['settings']['otv_expiration_period'] * 86400) {
         $html = "Link is too old!";
     } else {
         $dataItem = DB::queryfirstrow("SELECT *\n                FROM " . prefix_table("items") . " as i\n                INNER JOIN " . prefix_table("log_items") . " as l ON (l.id_item = i.id)\n                WHERE i.id = %i AND l.action = %s", intval($_GET['item_id']), 'at_creation');
         // get data
         $pw = cryption($dataItem['pw'], SALT, $dataItem['pw_iv'], "decrypt");
         // get key for original pw
         $originalKey = DB::queryfirstrow("SELECT rand_key FROM `" . prefix_table("keys") . "`\n                WHERE `sql_table` = %s AND `id` = %i", 'items', intval($_GET['item_id']));
         // unsalt previous pw
         $pw = substr($pw, strlen($originalKey['rand_key']));
         $label = $dataItem['label'];
         $email = $dataItem['email'];
         $url = $dataItem['url'];
         $description = preg_replace('/(?<!\\r)\\n+(?!\\r)/', '', strip_tags($dataItem['description'], $k['allowedTags']));
         $login = str_replace('"', '&quot;', $dataItem['login']);
         // display data
         $html = "<div style='margin:30px;'>" . "<div style='font-size:20px;font-weight:bold;'>Welcome to One-Time item view page.</div>" . "<div style='font-style:italic;'>Here are the details of the Item that has been shared to you</div>" . "<div style='margin-top:10px;'><table>" . "<tr><td>Label:</td><td>" . $label . "</td</tr>" . "<tr><td>Password:</td><td>" . $pw . "</td</tr>" . "<tr><td>Description:</td><td>" . $description . "</td</tr>" . "<tr><td>login:</td><td>" . $login . "</td</tr>" . "<tr><td>URL:</td><td>" . $url . "</td</tr>" . "</table></div>" . "<div style='margin-top:30px;'>Copy carefully the data you need. This page is only visible once.</div>" . "</div>";
         // delete entry
         //DB::delete(prefix_table("otv"), "id = %i", intval($_GET['otv_id']));
         // display
         echo $html;
     }
 } else {
Exemplo n.º 5
0
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);
$link->set_charset($encoding);
//load main functions needed
require_once 'sources/main.functions.php';
// Load CORE
require_once $_SESSION['settings']['cpassman_dir'] . '/sources/core.php';
/* DEFINE WHAT LANGUAGE TO USE */
if (!isset($_SESSION['user_id']) && isset($_GET['language'])) {
    // case of user has change language in the login page
    $dataLanguage = DB::queryFirstRow("SELECT flag, name\n        FROM " . prefix_table("languages") . "\n        WHERE name = %s", $_GET['language']);
    $_SESSION['user_language'] = $dataLanguage['name'];
    $_SESSION['user_language_flag'] = $dataLanguage['flag'];
} elseif (!isset($_SESSION['user_id']) && !isset($_POST['language']) && !isset($_SESSION['user_language'])) {
    //get default language
    $dataLanguage = DB::queryFirstRow("SELECT m.valeur AS valeur, l.flag AS flag\n        FROM " . prefix_table("misc") . " AS m\n        INNER JOIN " . prefix_table("languages") . " AS l ON (m.valeur = l.name)\n        WHERE m.type=%s_type AND m.intitule=%s_intitule", array('type' => "admin", 'intitule' => "default_language"));
    if (empty($dataLanguage['valeur'])) {
        $_SESSION['user_language'] = "english";
        $_SESSION['user_language_flag'] = "us.png";
    } else {
        $_SESSION['user_language'] = $dataLanguage['valeur'];
        $_SESSION['user_language_flag'] = $dataLanguage['flag'];
    }
} elseif (isset($_SESSION['settings']['default_language']) && !isset($_SESSION['user_language'])) {
    $_SESSION['user_language'] = $_SESSION['settings']['default_language'];
} elseif (isset($_POST['language'])) {
    $_SESSION['user_language'] = filter_var($_POST['language'], FILTER_SANITIZE_STRING);
} elseif (!isset($_SESSION['user_language']) || empty($_SESSION['user_language'])) {
    if (isset($_POST['language'])) {
        $_SESSION['user_language'] = filter_var($_POST['language'], FILTER_SANITIZE_STRING);
    } elseif (isset($_SESSION['settings']['default_language'])) {
Exemplo n.º 6
0
} else {
    require_once 'main.functions.php';
    // connect to DB
    include $_SESSION['settings']['cpassman_dir'] . '/includes/config/settings.php';
    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);
    // get file key
    $result = DB::queryfirstrow("SELECT file FROM " . prefix_table("files") . " WHERE id=%i", $_GET['fileid']);
    // Open the file
    $fp = fopen($_SESSION['settings']['path_to_upload_folder'] . '/' . $result['file'], 'rb');
    // should we decrypt the attachment?
    if (isset($_SESSION['settings']['enable_attachment_encryption']) && $_SESSION['settings']['enable_attachment_encryption'] == 1) {
        include $_SESSION['settings']['cpassman_dir'] . '/includes/config/settings.php';
        // Prepare encryption options
        $iv = substr(md5("<X" . SALT, true), 0, 8);
        $key = substr(md5("-üØ" . SALT, true) . md5("-üÙ" . SALT, true), 0, 24);
        $opts = array('iv' => $iv, 'key' => $key);
        // Add the Mcrypt stream filter
        stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
    }
    // Read the file contents
    fpassthru($fp);
}
Exemplo n.º 7
0
         */
        case "user_edit_login":
            // Check KEY
            if ($_POST['key'] != $_SESSION['key']) {
                // error
                exit;
            }
            DB::update(prefix_table("users"), array('login' => $_POST['login'], 'name' => $_POST['name'], 'lastname' => $_POST['lastname']), "id = %i", $_POST['id']);
            break;
    }
} elseif (!empty($_POST['newValue'])) {
    $value = explode('_', $_POST['id']);
    DB::update(prefix_table("users"), array($value[0] => $_POST['newValue']), "id = %i", $value[1]);
    // update LOG
    logEvents('user_mngt', 'at_user_new_' . $value[0] . ':' . $value[1], $_SESSION['user_id'], $_SESSION['login'], $_POST['id']);
    // refresh SESSION if requested
    if ($value[0] == "treeloadstrategy") {
        $_SESSION['user_settings']['treeloadstrategy'] = $_POST['newValue'];
    }
    // Display info
    echo $_POST['newValue'];
} elseif (isset($_POST['newadmin'])) {
    $id = explode('_', $_POST['id']);
    DB::update(prefix_table("users"), array('admin' => $_POST['newadmin']), "id = %i", $id[1]);
    // Display info
    if ($_POST['newadmin'] == "1") {
        echo "Oui";
    } else {
        echo "Non";
    }
}
Exemplo n.º 8
0
             } else {
                 $encrypt = cryption($pw, SALT, "", "encrypt");
             }
             //ADD item
             DB::insert(prefix_table("items"), array('label' => stripslashes($item[KP_TITLE]), 'description' => stripslashes(str_replace($lineEndSeparator, '<br />', $item[KP_NOTES])), 'pw' => $encrypt['string'], 'pw_iv' => $encrypt['iv'], 'url' => stripslashes($item[KP_URL]), 'id_tree' => $folderId, 'login' => stripslashes($item[KP_USERNAME]), 'anyone_can_modify' => $_POST['import_kps_anyone_can_modify'] == "true" ? 1 : 0));
             $newId = DB::insertId();
             //if asked, anyone in role can modify
             if (isset($_POST['import_kps_anyone_can_modify_in_role']) && $_POST['import_kps_anyone_can_modify_in_role'] == "true") {
                 foreach ($_SESSION['arr_roles'] as $role) {
                     DB::insert(prefix_table("restriction_to_roles"), array('role_id' => $role['id'], 'item_id' => $newId));
                 }
             }
             //Add log
             DB::insert(prefix_table("log_items"), array('id_item' => $newId, 'date' => time(), 'id_user' => $_SESSION['user_id'], 'action' => 'at_creation', 'raison' => 'at_import'));
             //Add entry to cache table
             DB::insert(prefix_table("cache"), array('id' => $newId, 'label' => stripslashes($item[KP_TITLE]), 'description' => stripslashes(str_replace($lineEndSeparator, '<br />', $item[KP_NOTES])), 'id_tree' => $folderId, 'perso' => $personalFolder == 0 ? 0 : 1, 'login' => stripslashes($item[KP_USERNAME]), 'folder' => $data['title'], 'author' => $_SESSION['user_id']));
             //show
             //$text .= '- '.addslashes($item[2]).'<br />';
             //increment number of imported items
             $nbItemsImported++;
         } else {
             $results .= " - Skipped\n";
         }
     }
 }
 //if no new items them inform
 /*if ($nbItemsImported == 0) {
       $text .= $LANG['none'].'<br />';
   }*/
 //SHow finished
 $text .= "Folders imported: {$nbFoldersImported}<br />";
Exemplo n.º 9
0
                    <th title="' . $LANG['gestionnaire'] . '"><img src="includes/images/user-worker.png" /></th>
                    <th title="' . $LANG['read_only_account'] . '"><img src="includes/images/user_read_only.png" /></th>
                    <th title="' . $LANG['can_create_root_folder'] . '"><img src="includes/images/folder-network.png" /></th>
                    ', isset($_SESSION['settings']['enable_pf_feature']) && $_SESSION['settings']['enable_pf_feature'] == 1 ? '<th title="' . $LANG['enable_personal_folder'] . '"><img src="includes/images/folder-open-document-text.png" /></th>' : '', '
                    <th title="' . $LANG['user_action'] . '"><img src="includes/images/user-locked.png" /></th>
                    <th title="' . $LANG['pw_change'] . '"><img src="includes/images/lock__pencil.png" /></th>
                    <th title="' . $LANG['email_change'] . '"><img src="includes/images/mail.png" /></th>
                    <th title="' . $LANG['logs'] . '"><img src="includes/images/log.png" /></th>
					', isset($_SESSION['settings']['2factors_authentication']) && $_SESSION['settings']['2factors_authentication'] == 1 ? '<th title="' . $LANG['send_ga_code'] . '"><img src="includes/images/telephone.png" /></th>' : '', '
                </tr>
            </thead>
            <tbody>';
$listAvailableUsers = $listAdmins = "";
$x = 0;
// Get through all users
$rows = DB::query("SELECT * FROM " . prefix_table("users") . " ORDER BY login ASC");
foreach ($rows as $reccord) {
    // Get list of allowed functions
    $listAlloFcts = "";
    if ($reccord['admin'] != 1) {
        if (count($rolesList) > 0) {
            foreach ($rolesList as $fonction) {
                if (in_array($fonction['id'], explode(";", $reccord['fonction_id']))) {
                    $listAlloFcts .= '<img src="includes/images/arrow-000-small.png" />' . @htmlspecialchars($fonction['title'], ENT_COMPAT, "UTF-8") . '<br />';
                }
            }
        }
        if (empty($listAlloFcts)) {
            $listAlloFcts = '<img src="includes/images/error.png" title="' . $LANG['user_alarm_no_function'] . '" />';
        }
    }
Exemplo n.º 10
0
function recursiveTree($nodeId)
{
    global $completTree, $ret_json, $listFoldersLimitedKeys, $listRestrictedFoldersForItemsKeys, $tree, $LANG;
    // Be sure that user can only see folders he/she is allowed to
    if (!in_array($completTree[$nodeId]->id, $_SESSION['forbiden_pfs']) || in_array($completTree[$nodeId]->id, $_SESSION['groupes_visibles']) || in_array($completTree[$nodeId]->id, $listFoldersLimitedKeys) || in_array($completTree[$nodeId]->id, $listRestrictedFoldersForItemsKeys)) {
        $displayThisNode = false;
        $hide_node = false;
        $nbChildrenItems = 0;
        // Check if any allowed folder is part of the descendants of this node
        $nodeDescendants = $tree->getDescendants($completTree[$nodeId]->id, true, false, true);
        foreach ($nodeDescendants as $node) {
            // manage tree counters
            if (isset($_SESSION['settings']['tree_counters']) && $_SESSION['settings']['tree_counters'] == 1) {
                DB::query("SELECT * FROM " . prefix_table("items") . "\n                    WHERE inactif=%i AND id_tree = %i", 0, $node);
                $nbChildrenItems += DB::count();
            }
            if (in_array($node, array_merge($_SESSION['groupes_visibles'], $_SESSION['list_restricted_folders_for_items'])) || @in_array($node, $listFoldersLimitedKeys) || @in_array($node, $listRestrictedFoldersForItemsKeys)) {
                $displayThisNode = true;
            }
        }
        if ($displayThisNode == true) {
            $hide_node = $show_but_block = $eye_icon = false;
            $text = $title = "";
            // get info about current folder
            DB::query("SELECT * FROM " . prefix_table("items") . "\n                WHERE inactif=%i AND id_tree = %i", 0, $completTree[$nodeId]->id);
            $itemsNb = DB::count();
            // If personal Folder, convert id into user name
            if ($completTree[$nodeId]->title == $_SESSION['user_id'] && $completTree[$nodeId]->nlevel == 1) {
                $completTree[$nodeId]->title = $_SESSION['login'];
            }
            // if required, separate the json answer for each folder
            if (!empty($ret_json)) {
                $ret_json .= ", ";
            }
            // prepare json return for current node
            if ($completTree[$nodeId]->parent_id == 0) {
                $parent = "#";
            } else {
                $parent = "li_" . $completTree[$nodeId]->parent_id;
            }
            // special case for READ-ONLY folder
            if ($_SESSION['user_read_only'] == true && !in_array($completTree[$nodeId]->id, $_SESSION['personal_folders'])) {
                $eye_icon = true;
                $title = $LANG['read_only_account'];
            }
            $text .= str_replace("&", "&amp;", $completTree[$nodeId]->title);
            $restricted = "0";
            $folderClass = "folder";
            if (in_array($completTree[$nodeId]->id, $_SESSION['groupes_visibles'])) {
                if (in_array($completTree[$nodeId]->id, $_SESSION['read_only_folders'])) {
                    $text = "<i class='fa fa-eye'></i>&nbsp;" . $text;
                    $title = $LANG['read_only_account'];
                    $restricted = 1;
                    $folderClass = "folder_not_droppable";
                }
                $text .= ' (<span class=\'items_count\' id=\'itcount_' . $completTree[$nodeId]->id . '\'>' . $itemsNb . '</span>';
                // display tree counters
                if (isset($_SESSION['settings']['tree_counters']) && $_SESSION['settings']['tree_counters'] == 1) {
                    $text .= '|' . $nbChildrenItems . '|' . (count($nodeDescendants) - 1);
                }
                $text .= ')';
            } elseif (in_array($completTree[$nodeId]->id, $listFoldersLimitedKeys)) {
                $restricted = "1";
                $text .= ' (<span class=\'items_count\' id=\'itcount_' . $completTree[$nodeId]->id . '">' . count($_SESSION['list_folders_limited'][$completTree[$nodeId]->id]) . '</span>';
            } elseif (in_array($completTree[$nodeId]->id, $listRestrictedFoldersForItemsKeys)) {
                $restricted = "1";
                $text .= ' (<span class=\'items_count\' id=\'itcount_' . $completTree[$nodeId]->id . '">' . count($_SESSION['list_restricted_folders_for_items'][$completTree[$nodeId]->id]) . '</span>';
            } else {
                $restricted = "1";
                $folderClass = "folder_not_droppable";
                if (isset($_SESSION['settings']['show_only_accessible_folders']) && $_SESSION['settings']['show_only_accessible_folders'] == 1) {
                    // folder is not visible
                    $hide_node = true;
                } else {
                    // folder is visible but not accessible by user
                    $show_but_block = true;
                }
            }
            // json
            if ($hide_node == false && $show_but_block == false) {
                $ret_json .= '{' . '"id":"li_' . $completTree[$nodeId]->id . '"' . ', "parent":"' . $parent . '"' . ', "text":"' . ($eye_icon == true ? "<i class='fa fa-eye'></i>&nbsp;" : "") . $text . '"' . ', "li_attr":{"class":"jstreeopen", "title":"ID [' . $completTree[$nodeId]->id . '] ' . $title . '"}' . ', "a_attr":{"id":"fld_' . $completTree[$nodeId]->id . '", "class":"' . $folderClass . '" , "onclick":"ListerItems(\'' . $completTree[$nodeId]->id . '\', \'' . $restricted . '\', 0)", "ondblclick":"LoadTreeNode(\'' . $completTree[$nodeId]->id . '\')"}' . '}';
            } else {
                if ($show_but_block == true) {
                    $ret_json .= '{' . '"id":"li_' . $completTree[$nodeId]->id . '"' . ', "parent":"' . $parent . '"' . ', "text":"<i class=\'fa fa-close mi-red\'></i>&nbsp;' . $text . '"' . ', "li_attr":{"class":"", "title":"ID [' . $completTree[$nodeId]->id . '] ' . $LANG['no_access'] . '"}' . '}';
                }
            }
            foreach ($completTree[$nodeId]->children as $child) {
                recursiveTree($child);
            }
        }
    }
}
Exemplo n.º 11
0
                array_push($arrFields, array($field['id'], addslashes($field['title'])));
            }
        }
        // store the categories
        array_push($_SESSION['item_fields'], array($record['id'], addslashes($record['title']), $arrFields));
    }
}
/*
* CHECK IF SENDING ANONYMOUS STATS
*/
if (isset($_SESSION['settings']['send_stats']) && $_SESSION['settings']['send_stats'] == 1 && isset($_SESSION['settings']['send_stats_time']) && !isset($_SESSION['temporary']['send_stats_done'])) {
    if ($_SESSION['settings']['send_stats_time'] + $k['one_month_seconds'] <= time()) {
        teampassStats();
        $_SESSION['temporary']['send_stats_done'] = true;
        //permits to test only once by session
    }
}
/*
**
*/
$_SESSION['temporary']['user_can_printout'] = false;
if (isset($_SESSION['settings']['roles_allowed_to_print']) && isset($_SESSION['user_roles']) && (!isset($_SESSION['temporary']['user_can_printout']) || empty($_SESSION['temporary']['user_can_printout']))) {
    foreach (explode(";", $_SESSION['settings']['roles_allowed_to_print']) as $role) {
        if (in_array($role, $_SESSION['user_roles'])) {
            $_SESSION['temporary']['user_can_printout'] = true;
        }
    }
}
/* CHECK NUMBER OF USER ONLINE */
DB::query("SELECT * FROM " . prefix_table("users") . " WHERE timestamp>=%i", time() - 600);
$_SESSION['nb_users_online'] = DB::count();
Exemplo n.º 12
0
            if ($_POST['key'] != $_SESSION['key']) {
                echo '[ { "error" : "key_not_conform" } ]';
                break;
            }
            $ret = DB::queryfirstrow("SELECT k.id AS id, k.label AS label, k.description AS description, k.category_id AScategory_id, k.author_id AS author_id, k.anyone_can_modify AS anyone_can_modify, u.login AS login, c.category AS category\n                FROM " . prefix_table("kb") . " AS k\n                INNER JOIN " . prefix_table("kb_categories") . " AS c ON (c.id = k.category_id)\n                INNER JOIN " . prefix_table("users") . " AS u ON (u.id = k.author_id)\n                WHERE k.id = %i", $_POST['id']);
            //select associated items
            $rows = DB::query("SELECT item_id FROM " . prefix_table("kb") . "_items WHERE kb_id = %i", $_POST['id']);
            $arrOptions = array();
            foreach ($rows as $record) {
                //echo '$("#kb_associated_to option[value='.$record['item_id'].']").attr("selected","selected");';
                array_push($arrOptions, $record['item_id']);
            }
            $arrOutput = array("label" => $ret['label'], "category" => $ret['category'], "description" => $ret['description'], "anyone_can_modify" => $ret['anyone_can_modify'], "options" => $arrOptions);
            echo json_encode($arrOutput, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
            break;
            /**
             * Delete the KB
             */
        /**
         * Delete the KB
         */
        case "delete_kb":
            // Check KEY
            if ($_POST['key'] != $_SESSION['key']) {
                echo '[ { "error" : "key_not_conform" } ]';
                break;
            }
            DB::delete(prefix_table("kb"), "id=%i", $_POST['id']);
            break;
    }
}
Exemplo n.º 13
0
            break;
            // CASE where to authorize an ITEM creation without respecting the complexity
        // CASE where to authorize an ITEM creation without respecting the complexity
        case "modif_droit_autorisation_sans_complexite":
            /* do checks */
            require_once $_SESSION['settings']['cpassman_dir'] . '/sources/checks.php';
            if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_folders")) {
                $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
                //not allowed page
                include $_SESSION['settings']['cpassman_dir'] . '/error.php';
                exit;
            }
            // send query
            DB::update(prefix_table("nested_tree"), array('bloquer_creation' => $_POST['droit']), "id = %i", $_POST['id']);
            break;
            // CASE where to authorize an ITEM modification without respecting the complexity
        // CASE where to authorize an ITEM modification without respecting the complexity
        case "modif_droit_modification_sans_complexite":
            /* do checks */
            require_once $_SESSION['settings']['cpassman_dir'] . '/sources/checks.php';
            if (!checkUser($_SESSION['user_id'], $_SESSION['key'], "manage_folders")) {
                $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
                //not allowed page
                include $_SESSION['settings']['cpassman_dir'] . '/error.php';
                exit;
            }
            // send query
            DB::update(prefix_table("nested_tree"), array('bloquer_modification' => $_POST['droit']), "id = %i", $_POST['id']);
            break;
    }
}
Exemplo n.º 14
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');
}
Exemplo n.º 15
0
    <div id="tabs-2">
        <!-- Prepare a list of all folders that the user can choose -->
        <div style="margin-top:10px;" id="keypass_import_options">
            <label><b>' . $LANG['import_keepass_to_folder'] . '</b></label>&nbsp;
            <select id="import_keepass_items_to">
                <option value="0">' . $LANG['root'] . '</option>';
//Load Tree
$tree = new SplClassLoader('Tree\\NestedTree', './includes/libraries');
$tree->register();
$tree = new Tree\NestedTree\NestedTree($pre . 'nested_tree', 'id', 'parent_id', 'title');
$folders = $tree->getDescendants();
// show list of all folders
foreach ($folders as $t) {
    if (in_array($t->id, $_SESSION['groupes_visibles'])) {
        if (is_numeric($t->title)) {
            $user = DB::queryfirstrow("SELECT login FROM " . prefix_table("users") . " WHERE id = %i", $t->title);
            $t->title = $user['login'];
            $t->id = $t->id . "-perso";
        }
        $ident = "&nbsp;&nbsp;";
        for ($x = 1; $x < $t->nlevel; $x++) {
            $ident .= "&nbsp;&nbsp;";
        }
        if (isset($_GET['folder_id']) && $_GET['folder_id'] == $t->id) {
            $selected = " selected";
        } else {
            $selected = "";
        }
        if ($prevLevel < $t->nlevel) {
            echo '<option value="' . $t->id . '"' . $selected . '>' . $ident . $t->title . '</option>';
        } elseif ($prevLevel == $t->nlevel) {
Exemplo n.º 16
0
    <input type="hidden" id="selected_row" />';
// dialogboxes
echo '
    <div id="category_confirm" style="display:none;">
        <span id="category_confirm_text"></span>?
    </div>';
echo '
    <div id="add_new_field" style="display:none;">
        ' . $LANG['new_field_title'] . '<input type="text" id="new_field_title" style="width: 200px; margin-left:20px;" />
    </div>';
echo '
    <div id="category_in_folder" style="display:none;">
        ' . $LANG['select_folders_for_category'] . '
        &nbsp;&quot;<span style="font-weight:bold;" id="catInFolder_title"></span>&quot;&nbsp;:
        <br />
        <div style="text-align:center; margin-top:10px;">
        <select id="cat_folders_selection" multiple size="12">';
$folders = $tree->getDescendants();
foreach ($folders as $folder) {
    DB::query("SELECT * FROM " . prefix_table("nested_tree") . "\n                WHERE personal_folder = %i AND id = %i", '0', $folder->id);
    $counter = DB::count();
    if ($counter > 0) {
        echo '
                <option value="' . $folder->id . '">' . str_replace("&", "&amp;", $folder->title) . '</option>';
    }
}
echo '
        </div>
        <div id="catInFolder_wait" class="ui-state-focus ui-corner-all" style="display:none;padding:2px;margin:5px 0 5px 0;">' . $LANG['please_wait'] . '...</div>
    </div>';
require_once 'admin.settings.load.php';
Exemplo n.º 17
0
            if ($_POST['logType'] == "items_logs") {
                DB::query("SELECT * FROM " . prefix_table("log_items") . " WHERE action=%s " . "AND date BETWEEN %i AND %i", "at_shown", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
                $nbElements = DB::count();
                // Delete
                //                 DB::delete(prefix_table("log_items"), "action=%s AND date BETWEEN %i AND %i",
                //                     "at_shown",
                //                     intval(strtotime($_POST['purgeFrom'])),
                //                     intval(strtotime($_POST['purgeTo']))
                //                 );
            } elseif ($_POST['logType'] == "connections_logs") {
                DB::query("SELECT * FROM " . prefix_table("log_items") . " WHERE action=%s " . "AND date BETWEEN %i AND %i", "user_connection", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
                $nbElements = DB::count();
                // Delete
                DB::delete(prefix_table("log_items"), "action=%s AND date BETWEEN %i AND %i", "user_connection", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
            } elseif ($_POST['logType'] == "errors_logs") {
                DB::query("SELECT * FROM " . prefix_table("log_items") . " WHERE action=%s " . "AND date BETWEEN %i AND %i", "error", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
                $nbElements = DB::count();
                // Delete
                DB::delete(prefix_table("log_items"), "action=%s AND date BETWEEN %i AND %i", "error", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
            } elseif ($_POST['logType'] == "copy_logs") {
                DB::query("SELECT * FROM " . prefix_table("log_items") . " WHERE action=%s " . "AND date BETWEEN %i AND %i", "at_copy", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
                $nbElements = DB::count();
                // Delete
                DB::delete(prefix_table("log_items"), "action=%s AND date BETWEEN %i AND %i", "at_copy", intval(strtotime($_POST['purgeFrom'])), intval(strtotime($_POST['purgeTo'])));
            }
            echo '[{"status" : "ok", "nb":"' . $nbElements . '"}]';
        } else {
            echo '[{"status" : "nok"}]';
        }
        break;
}
Exemplo n.º 18
0
     // manage tree counters
     if (isset($_SESSION['settings']['tree_counters']) && $_SESSION['settings']['tree_counters'] == 1) {
         DB::query("SELECT * FROM " . prefix_table("items") . "\n                    WHERE inactif=%i AND id_tree = %i", 0, $node);
         $nbChildrenItems += DB::count();
     }
     if (in_array($node, array_merge($_SESSION['groupes_visibles'], $_SESSION['list_restricted_folders_for_items'])) || in_array($node, $listFoldersLimitedKeys) || in_array($node, $listRestrictedFoldersForItemsKeys)) {
         $displayThisNode = true;
         //break;
     }
 }
 if ($displayThisNode == true) {
     $ident = "";
     for ($x = 1; $x < $folder->nlevel; $x++) {
         $ident .= "&nbsp;&nbsp;";
     }
     DB::query("SELECT * FROM " . prefix_table("items") . "\n                WHERE inactif=%i AND id_tree = %i", 0, $folder->id);
     $itemsNb = DB::count();
     // get 1st folder
     if (empty($firstGroup)) {
         $firstGroup = $folder->id;
     }
     // If personal Folder, convert id into user name
     if ($folder->title == $_SESSION['user_id'] && $folder->nlevel == 1) {
         $folder->title = $_SESSION['login'];
     }
     // resize title if necessary
     if (strlen($folder->title) > 20) {
         $fldTitle = substr(str_replace("&", "&amp;", $folder->title), 0, 17) . "...";
     } else {
         $fldTitle = str_replace("&", "&amp;", $folder->title);
     }
Exemplo n.º 19
0
function rest_get()
{
    $_SESSION['user_id'] = "'api'";
    if (!@count($GLOBALS['request']) == 0) {
        $request_uri = $GLOBALS['_SERVER']['REQUEST_URI'];
        preg_match('/\\/api(\\/index.php|)\\/(.*)\\?apikey=(.*)/', $request_uri, $matches);
        if (count($matches) == 0) {
            rest_error('REQUEST_SENT_NOT_UNDERSTANDABLE');
        }
        $GLOBALS['request'] = explode('/', $matches[2]);
    }
    if (apikey_checker($GLOBALS['apikey'])) {
        global $server, $user, $pass, $database, $pre, $link;
        teampass_connect();
        $rand_key = teampass_get_randkey();
        $category_query = "";
        if ($GLOBALS['request'][0] == "read") {
            if ($GLOBALS['request'][1] == "category") {
                // get ids
                if (strpos($GLOBALS['request'][2], ",") > 0) {
                    $condition = "id_tree IN %ls";
                    $condition_value = explode(',', $GLOBALS['request'][2]);
                } else {
                    $condition = "id_tree = %s";
                    $condition_value = $GLOBALS['request'][2];
                }
                DB::debugMode(false);
                /* load folders */
                $response = DB::query("SELECT id,parent_id,title,nleft,nright,nlevel FROM " . prefix_table("nested_tree") . " WHERE parent_id=%i ORDER BY `title` ASC", $GLOBALS['request'][2]);
                $rows = array();
                $i = 0;
                foreach ($response as $row) {
                    /*$json['folders'][$i]['id'] = $row['id'];
                      $json['folders'][$i]['parent_id'] = $row['parent_id'];
                      $json['folders'][$i]['title'] = $row['title'];
                      $json['folders'][$i]['nleft'] = $row['nleft'];
                      $json['folders'][$i]['nright'] = $row['nright'];
                      $json['folders'][$i]['nlevel'] = $row['nlevel'];*/
                    $i++;
                    $response = DB::query("SELECT id,label,login,pw FROM " . prefix_table("items") . " WHERE id_tree=%i", $row['id']);
                    foreach ($response as $data) {
                        // get ITEM random key
                        $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                        // prepare output
                        $id = $data['id'];
                        $json[$id]['label'] = utf8_encode($data['label']);
                        $json[$id]['login'] = utf8_encode($data['login']);
                        $json[$id]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                    }
                }
            } elseif ($GLOBALS['request'][1] == "items") {
                // only accepts numeric
                $array_items = explode(',', $GLOBALS['request'][2]);
                $items_list = "";
                foreach ($array_items as $item) {
                    if (!is_numeric($item)) {
                        rest_error('ITEM_MALFORMED');
                    }
                }
                if (count($array_items) > 1 && count($array_items) < 5) {
                    foreach ($array_items as $item) {
                        if (empty($items_list)) {
                            $items_list = $item;
                        } else {
                            $items_list .= "," . $item;
                        }
                    }
                } elseif (count($array_items) == 1) {
                    $items_list = $item;
                } else {
                    rest_error('NO_ITEM');
                }
                $response = DB::query("select id,label,login,pw,id_tree from " . prefix_table("items") . " where id IN %ls", $items_list);
                foreach ($response as $data) {
                    // get ITEM random key
                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                    // prepare output
                    $id = $data['id'];
                    $json[$id]['label'] = utf8_encode($data['label']);
                    $json[$id]['login'] = utf8_encode($data['login']);
                    $json[$id]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                }
            }
            if (isset($json) && $json) {
                echo json_encode($json);
            } else {
                rest_error('EMPTY');
            }
        } elseif ($GLOBALS['request'][0] == "find") {
            if ($GLOBALS['request'][1] == "item") {
                $array_category = explode(';', $GLOBALS['request'][2]);
                $item = $GLOBALS['request'][3];
                foreach ($array_category as $category) {
                    if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $category, $result)) {
                        rest_error('CATEGORY_MALFORMED');
                    }
                }
                if (!preg_match_all("/^([\\w\\:\\'\\-\\sàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+)\$/i", $item, $result)) {
                    rest_error('ITEM_MALFORMED');
                } elseif (empty($item) || count($array_category) == 0) {
                    rest_error('MALFORMED');
                }
                if (count($array_category) > 1 && count($array_category) < 5) {
                    for ($i = count($array_category); $i > 0; $i--) {
                        $slot = $i - 1;
                        if (!$slot) {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = 0";
                        } else {
                            $category_query .= "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[$slot] . "' AND parent_id = (";
                        }
                    }
                    for ($i = 1; $i < count($array_category); $i++) {
                        $category_query .= ")";
                    }
                } elseif (count($array_category) == 1) {
                    $category_query = "select id from " . prefix_table("nested_tree") . " where title LIKE '" . $array_category[0] . "' AND parent_id = 0";
                } else {
                    rest_error('NO_CATEGORY');
                }
                DB::debugMode(false);
                $response = DB::query("select id,label,login,pw,id_tree\n                    from " . prefix_table("items") . "\n                    where id_tree = (%s)\n                    and label LIKE %ss", $category_query, $item);
                foreach ($response as $data) {
                    // get ITEM random key
                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                    // prepare output
                    $json['id'] = utf8_encode($data['id']);
                    $json['label'] = utf8_encode($data['label']);
                    $json['login'] = utf8_encode($data['login']);
                    $json['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                    $json['folder_id'] = $data['id_tree'];
                    $json['status'] = utf8_encode("OK");
                }
                if (isset($json) && $json) {
                    echo json_encode($json);
                } else {
                    rest_error('EMPTY');
                }
            }
        } elseif ($GLOBALS['request'][0] == "add") {
            if ($GLOBALS['request'][1] == "item") {
                // get item definition
                $array_item = explode(';', $GLOBALS['request'][2]);
                if (count($array_item) != 9) {
                    rest_error('BADDEFINITION');
                }
                $item_label = $array_item[0];
                $item_pwd = $array_item[1];
                $item_desc = $array_item[2];
                $item_folder_id = $array_item[3];
                $item_login = $array_item[4];
                $item_email = $array_item[5];
                $item_url = $array_item[6];
                $item_tags = $array_item[7];
                $item_anyonecanmodify = $array_item[8];
                // added so one can sent data including the http or https !
                // anyway we have to urlencode this data
                $item_url = urldecode($item_url);
                // same for the email
                $item_email = urldecode($item_email);
                // do some checks
                if (!empty($item_label) && !empty($item_pwd) && !empty($item_folder_id)) {
                    // Check length
                    if (strlen($item_pwd) > 50) {
                        rest_error('BADDEFINITION');
                    }
                    // Check Folder ID
                    DB::query("SELECT * FROM " . prefix_table("nested_tree") . " WHERE id = %i", $item_folder_id);
                    $counter = DB::count();
                    if ($counter == 0) {
                        rest_error('BADDEFINITION');
                    }
                    // check if element doesn't already exist
                    DB::query("SELECT * FROM " . prefix_table("items") . " WHERE label = %s AND inactif = %i", addslashes($item_label), "0");
                    $counter = DB::count();
                    if ($counter != 0) {
                        $itemExists = 1;
                        // prevent the error if the label already exists
                        // so lets just add the time() as a random factor
                        $item_label .= " (" . time() . ")";
                    } else {
                        $itemExists = 0;
                    }
                    if ($itemExists == 0) {
                        // prepare password and generate random key
                        $randomKey = substr(md5(rand() . rand()), 0, 15);
                        $item_pwd = $randomKey . $item_pwd;
                        $item_pwd = encrypt($item_pwd);
                        if (empty($item_pwd)) {
                            rest_error('BADDEFINITION');
                        }
                        // ADD item
                        try {
                            DB::insert(prefix_table("items"), array("label" => $item_label, "description" => $item_desc, "pw" => $item_pwd, "email" => $item_email, "url" => $item_url, "id_tree" => intval($item_folder_id), "login" => $item_login, "inactif" => 0, "restricted_to" => "", "perso" => 0, "anyone_can_modify" => intval($item_anyonecanmodify)));
                            $newID = DB::InsertId();
                            // Store generated key
                            DB::insert(prefix_table("keys"), array("sql_table" => "items", "id" => $newID, "rand_key" => $randomKey));
                            // log
                            DB::insert(prefix_table("log_items"), array("id_item" => $newID, "date" => time(), "id_user" => "9999999", "action" => "at_creation"));
                            // Add tags
                            $tags = explode(' ', $item_tags);
                            foreach ((array) $tags as $tag) {
                                if (!empty($tag)) {
                                    DB::insert(prefix_table("tags"), array("item_id" => $newID, "tag" => strtolower($tag)));
                                }
                            }
                            // Update CACHE table
                            DB::insert(prefix_table("cache"), array("id" => $newID, "label" => $item_label, "description" => $item_desc, "tags" => $item_tags, "id_tree" => $item_folder_id, "perso" => "0", "restricted_to" => "", "login" => $item_login, "folder" => "", "author" => "9999999"));
                            echo '{"status":"item added"}';
                        } catch (PDOException $ex) {
                            echo '<br />' . $ex->getMessage();
                        }
                    } else {
                        rest_error('BADDEFINITION');
                    }
                } else {
                    rest_error('BADDEFINITION');
                }
            }
        } elseif ($GLOBALS['request'][0] == "auth") {
            /*
             ** FOR SECURITY PURPOSE, it is mandatory to use SSL to connect your teampass instance. The user password is not encrypted!
             **
             **
             ** Expected call format: .../api/index.php/auth/<PROTOCOL>/<URL>/<login>/<password>?apikey=<VALID API KEY>
             ** Example: https://127.0.0.1/teampass/api/index.php/auth/http/www.zadig-tge.adp.com/U1/test/76?apikey=chahthait5Aidood6johh6Avufieb6ohpaixain
             ** RESTRICTIONS:
             **              - <PROTOCOL>        ==> http|https|ftp|...
             **              - <URL>             ==> encode URL without protocol (example: http://www.teampass.net becomes www.teampass.net)
             **              - <login>           ==> user's login
             **              - <password>        ==> currently clear password
             **
             ** RETURNED ANSWER:
             **              - format sent back is JSON
             **              - Example: {"<item_id>":{"label":"<pass#1>","login":"******","pw":"<pwd#1>"},"<item_id>":{"label":"<pass#2>","login":"******","pw":"<pwd#2>"}}
             **
             */
            // get user credentials
            if (isset($GLOBALS['request'][3]) && isset($GLOBALS['request'][4])) {
                // get url
                if (isset($GLOBALS['request'][1]) && isset($GLOBALS['request'][2])) {
                    // is user granted?
                    $user = DB::queryFirstRow("SELECT `id`, `pw`, `groupes_interdits`, `groupes_visibles`, `fonction_id` FROM " . $pre . "users WHERE login = %s", $GLOBALS['request'][3]);
                    if (crypt($GLOBALS['request'][4], $user['pw']) == $user['pw']) {
                        // define the restriction of "id_tree" of this user
                        $userDef = DB::queryOneColumn('folder_id', "SELECT DISTINCT folder_id \n                            FROM " . prefix_table("roles_values") . "\n                            WHERE type IN ('R', 'W') ", empty($user['groupes_interdits']) ? "" : "\n                            AND folder_id NOT IN (" . str_replace(";", ",", $user['groupes_interdits']) . ")", " \n                            AND role_id IN %ls \n                            GROUP BY folder_id", explode(";", $user['groupes_interdits']));
                        // complete with "groupes_visibles"
                        foreach (explode(";", $user['groupes_visibles']) as $v) {
                            array_push($userDef, $v);
                        }
                        // find the item associated to the url
                        $response = DB::query("SELECT id, label, login, pw, id_tree, restricted_to\n                            FROM " . prefix_table("items") . " \n                            WHERE url LIKE %s\n                            AND id_tree IN (" . implode(",", $userDef) . ")\n                            ORDER BY id DESC", $GLOBALS['request'][1] . "://" . urldecode($GLOBALS['request'][2] . '%'));
                        $counter = DB::count();
                        if ($counter > 0) {
                            $json = "";
                            foreach ($response as $data) {
                                // check if item visible
                                if (empty($data['restricted_to']) || $data['restricted_to'] != "" && in_array($user['id'], explode(";", $data['restricted_to']))) {
                                    // get ITEM random key
                                    $data_tmp = DB::queryFirstRow("SELECT rand_key FROM " . prefix_table("keys") . " WHERE id = %i", $data['id']);
                                    // prepare export
                                    $json[$data['id']]['label'] = utf8_encode($data['label']);
                                    $json[$data['id']]['login'] = utf8_encode($data['login']);
                                    $json[$data['id']]['pw'] = teampass_decrypt_pw($data['pw'], SALT, $data_tmp['rand_key']);
                                }
                            }
                            // prepare answer. If no access then inform
                            if (empty($json)) {
                                rest_error('AUTH_NO_DATA');
                            } else {
                                echo json_encode($json);
                            }
                        } else {
                            rest_error('AUTH_NO_DATA');
                        }
                    } else {
                        rest_error('AUTH_NOT_GRANTED');
                    }
                } else {
                    rest_error('AUTH_NO_URL');
                }
            } else {
                rest_error('AUTH_NO_IDENTIFIER');
            }
        } else {
            rest_error('METHOD');
        }
    }
}
Exemplo n.º 20
0
if (!isset($_POST['key']) || $_POST['key'] != $_SESSION['key']) {
    echo prepareExchangedData(array("error" => "ERR_KEY_NOT_CORRECT"), "encode");
    break;
}
// Do asked action
if (isset($_POST['type'])) {
    switch ($_POST['type']) {
        /*
         * CASE
         * log if item's password is shown
         */
        case "item_password_shown":
            if (isset($_SESSION['settings']['log_accessed']) && $_SESSION['settings']['log_accessed'] == 1) {
                DB::insert(prefix_table("log_items"), array('id_item' => $_POST['id_item'], 'date' => time(), 'id_user' => $_SESSION['user_id'], 'action' => 'at_password_shown'));
            }
            break;
            /*
             * CASE
             * log if item's password is copied
             */
        /*
         * CASE
         * log if item's password is copied
         */
        case "item_password_copied":
            if (isset($_SESSION['settings']['log_accessed']) && $_SESSION['settings']['log_accessed'] == 1) {
                DB::insert(prefix_table("log_items"), array('id_item' => $_POST['id_item'], 'date' => time(), 'id_user' => $_SESSION['user_id'], 'action' => 'at_password_copied'));
            }
            break;
    }
}
Exemplo n.º 21
0
    ';
} else {
    echo '
    <table id="t_items" style="empty-cells:show;width:100%;" cellspacing="0" cellpadding="5">
        <thead><tr>
            <th style="width:55px;"></th>
            <th style="min-width:15%;">' . $LANG['label'] . '</th>
            <th style="min-width:50%;">' . $LANG['description'] . '</th>
            <th style="min-width:20%;">' . $LANG['group'] . '</th>
        </tr></thead>
        <tbody>';
    //Get favourites
    $cpt = 0;
    foreach ($_SESSION['favourites'] as $fav) {
        if (!empty($fav)) {
            $data = DB::queryFirstRow("SELECT i.label, i.description, i.id, i.id_tree, t.title\n                FROM " . prefix_table("items") . " as i\n                INNER JOIN " . prefix_table("nested_tree") . " as t ON (t.id = i.id_tree)\n                WHERE i.id = %i", $fav);
            if (!empty($data['label'])) {
                echo '
                    <tr class="ligne' . $cpt % 2 . '">
                        <td>
                            <img src="includes/images/key__arrow.png" onClick="javascript:window.location.href = \'index.php?page=items&amp;group=' . $data['id_tree'] . '&amp;id=' . $data['id'] . '\';" style="cursor:pointer;" />
                            &nbsp;
                            <img src="includes/images/favourite_delete.png" onClick="prepare_delete_fav(\'' . $data['id'] . '\');" style="cursor:pointer;" title="' . $LANG['item_menu_del_from_fav'] . '" />
                        </td>
                        <td align="left">' . stripslashes($data['label']) . '</td>
                        <td align="center">' . stripslashes($data['description']) . '</td>
                        <td align="center">', $data['title'] == $_SESSION['user_id'] ? $_SESSION['login'] : $data['title'], '</td>
                    </tr>';
                $cpt++;
            }
        }
Exemplo n.º 22
0
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);
$link->set_charset($encoding);
// manage action required
if (!empty($_POST['type'])) {
    switch ($_POST['type']) {
        #CASE adding a new function
        case "del_fav":
            //Get actual favourites
            $data = DB::queryfirstrow("SELECT favourites FROM " . prefix_table("users") . " WHERE id = %i", $_SESSION['user_id']);
            $tmp = explode(";", $data['favourites']);
            $favs = "";
            $tab_favs = array();
            //redefine new list of favourites
            foreach ($tmp as $f) {
                if (!empty($f) && $f != $_POST['id']) {
                    if (empty($favs)) {
                        $favs = $f;
                    } else {
                        $favs = ';' . $f;
                    }
                    array_push($tab_favs, $f);
                }
            }
            //update user's account
            DB::update(prefix_table("users"), array('favourites' => $favs), "id = %i", $_SESSION['user_id']);
            //update session
            $_SESSION['favourites'] = $tab_favs;
            break;
    }
}
Exemplo n.º 23
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'] = ".";
    }
}
Exemplo n.º 24
0
    echo 'document.getElementById("res_step1_error").innerHTML = ' . '"File settings.php does not exist in folder includes/! ' . 'If it is an upgrade, it should be there, otherwise select install!";';
    echo 'document.getElementById("loader").style.display = "none";';
    exit;
}
require_once '../includes/config/settings.php';
require_once '../sources/main.functions.php';
require_once '../sources/SplClassLoader.php';
$finish = 0;
$next = "";
// init on 1st task to be done
//Update CACHE table -> this will be the last task during update
if ($_POST['type'] == "reload_cache_table" || empty($_POST['type'])) {
    //Load Tree
    $tree = new SplClassLoader('Tree\\NestedTree', '../includes/libraries');
    $tree->register();
    $tree = new Tree\NestedTree\NestedTree(prefix_table("nested_tree"), 'id', 'parent_id', 'title');
    $dbTmp = mysqli_connect($_SESSION['db_host'], $_SESSION['db_login'], $_SESSION['db_pw'], $_SESSION['db_bdd'], $_SESSION['db_port']);
    // truncate table
    mysqli_query($dbTmp, "TRUNCATE TABLE " . $_SESSION['tbl_prefix'] . "cache");
    // reload table
    $rows = mysqli_query($dbTmp, "SELECT *\n\t\tFROM " . $_SESSION['tbl_prefix'] . "items as i\n\t\tINNER JOIN " . $_SESSION['tbl_prefix'] . "log_items as l ON (l.id_item = i.id)\n\t\tAND l.action = 'at_creation'\n\t\tAND i.inactif = 0");
    foreach ($rows as $record) {
        // Get all TAGS
        $tags = "";
        $itemTags = mysqli_query($dbTmp, "SELECT tag FROM " . $_SESSION['tbl_prefix'] . "tags WHERE item_id=" . intval($record['id']));
        $itemTags = mysqli_fetch_array($itemTags);
        foreach ($itemTags as $itemTag) {
            if (!empty($itemTag['tag'])) {
                $tags .= $itemTag['tag'] . " ";
            }
        }
Exemplo n.º 25
0
     fclose($outstream);
     // send back and continue
     echo '[{"loop":"true", "number":"' . $objNumber . '", "file":"' . $_SESSION['settings']['path_to_files_folder'] . $html_file . '" , "file_link":"' . $_SESSION['settings']['url_to_files_folder'] . $html_file . '"}]';
     break;
     //CASE export in HTML format - Iteration loop
 //CASE export in HTML format - Iteration loop
 case "export_to_html_format_loop":
     // do checks ... if fails, return an error
     if (!isset($_POST['idTree']) || !isset($_POST['idsList'])) {
         echo '[{"error":"true"}]';
         break;
     }
     $full_listing = array();
     include $_SESSION['settings']['cpassman_dir'] . '/includes/include.php';
     require_once $_SESSION['settings']['cpassman_dir'] . '/includes/libraries/encryption/GibberishAES/GibberishAES.php';
     $rows = DB::query("SELECT i.id as id, i.url as url, i.perso as perso, i.label as label, i.description as description, i.pw as pw, i.login as login, i.id_tree as id_tree,\n               l.date as date, i.pw_iv as pw_iv,\n               n.renewal_period as renewal_period\n            FROM " . prefix_table("items") . " as i\n            INNER JOIN " . prefix_table("nested_tree") . " as n ON (i.id_tree = n.id)\n            INNER JOIN " . prefix_table("log_items") . " as l ON (i.id = l.id_item)\n            WHERE i.inactif = %i\n            AND i.id_tree= %i\n            AND (l.action = %s OR (l.action = %s AND l.raison LIKE %s))\n            ORDER BY i.label ASC, l.date DESC", "0", intval($_POST['idTree']), "at_creation", "at_modification", "at_pw :%");
     //AND i.id_tree IN (".implode(',', $list).")
     foreach ($rows as $record) {
         //exclude all results except the first one returned by query
         if (empty($id_managed) || $id_managed != $record['id']) {
             // decrypt PW
             if (!empty($_POST['salt_key']) && isset($_POST['salt_key'])) {
                 $pw = cryption($record['pw'], mysqli_escape_string($link, stripslashes($_POST['salt_key'])), $record['pw_iv'], "decrypt");
             } else {
                 $pw = cryption($record['pw'], SALT, $record['pw_iv'], "decrypt");
             }
             array_push($full_listing, array('id_tree' => $record['id_tree'], 'id' => $record['id'], 'label' => $record['label'], 'description' => addslashes(str_replace(array(";", "<br />"), array("|", "\n\r"), mysqli_escape_string($link, stripslashes(utf8_decode($record['description']))))), 'pw' => $pw, 'login' => $record['login'], 'url' => $record['url'], 'perso' => $record['perso']));
             $i++;
             array_push($items_id_list, $record['id']);
         }
         $id_managed = $record['id'];
Exemplo n.º 26
0
             DB::delete(prefix_table("suggestion"), "id = %i", $_POST['id']);
             echo '[ { "status" : "done" } ]';
         } else {
             echo '[ { "status" : "error_when_updating" } ]';
         }
     } else {
         // add as Item
         DB::insert(prefix_table("items"), array('label' => $suggestion['label'], 'description' => $suggestion['description'], 'pw' => $suggestion['pw'], 'id_tree' => $suggestion['folder_id'], 'inactif' => '0', 'perso' => '0', 'anyone_can_modify' => '0', 'pw_iv' => $suggestion['pw_iv']));
         $newID = DB::insertId();
         if (is_numeric($newID)) {
             // update log
             DB::insert(prefix_table("log_items"), array('id_item' => $newID, 'date' => time(), 'id_user' => $suggestion['author_id'], 'action' => 'at_creation'));
             // update cache table
             updateCacheTable("add_value", $newID);
             // delete suggestion
             DB::delete(prefix_table("suggestion"), "id = %i", $_POST['id']);
             echo '[ { "status" : "done" } ]';
         } else {
             echo '[ { "status" : "error_when_creating" } ]';
         }
     }
     break;
 case "get_complexity_level":
     // Check KEY
     if ($_POST['key'] != $_SESSION['key']) {
         echo '[ { "error" : "key_not_conform" } ]';
         break;
     }
     $data = DB::queryfirstrow("SELECT valeur FROM " . $pre . "misc WHERE intitule = %s AND type = %s", $_POST['folder_id'], "complex");
     if (isset($data['valeur']) && (!empty($data['valeur']) || $data['valeur'] == 0)) {
         $complexity = $_SESSION['settings']['pwComplexity'][$data['valeur']][1];
Exemplo n.º 27
0
    die('Hacking attempt...');
}
/* do checks */
require_once $_SESSION['settings']['cpassman_dir'] . '/sources/checks.php';
if (!checkUser($_SESSION['user_id'], $_SESSION['key'], curPage())) {
    $_SESSION['error']['code'] = ERR_NOT_ALLOWED;
    //not allowed page
    include $_SESSION['settings']['cpassman_dir'] . '/error.php';
    exit;
}
//load help
require_once $_SESSION['settings']['cpassman_dir'] . '/includes/language/' . $_SESSION['user_language'] . '_admin_help.php';
require_once $_SESSION['settings']['cpassman_dir'] . '/sources/main.functions.php';
//Get full list of groups
$arr_groups = array();
$rows = DB::query("SELECT id,title FROM " . prefix_table("nested_tree"));
foreach ($rows as $reccord) {
    $arr_groups[$reccord['id']] = $reccord['title'];
}
//display
echo '
<div class="title ui-widget-content ui-corner-all">
    ' . $LANG['admin_functions'] . '&nbsp;&nbsp;
    <button title="' . $LANG['add_role_tip'] . '" onclick="OpenDialog(\'add_new_role\')" class="button">
        <img src="includes/images/user--plus.png" alt="" />
    </button>
    <button title="' . $LANG['refresh_matrix'] . '" onclick="refresh_roles_matrix()" class="button">
        <img src="includes/images/arrow_refresh.png" alt="" />
    </button>
</div>
<div style="line-height:20px;" align="center">
Exemplo n.º 28
0
 $expired_item = 0;
 if ($_SESSION['settings']['activate_expiration'] == 1) {
     $expirationFlag = '<i class="fa fa-flag mi-green"></i>&nbsp;';
     if ($record['renewal_period'] > 0 && $record['date'] + $record['renewal_period'] * $k['one_month_seconds'] < time()) {
         $expirationFlag = '<i class="fa fa-flag mi-red"></i>&nbsp;';
         $expired_item = 1;
     }
 }
 // list of restricted users
 $restricted_users_array = explode(';', $record['restricted_to']);
 $itemPw = $itemLogin = "";
 $displayItem = $need_sk = $canMove = $item_is_restricted_to_role = 0;
 // TODO: Element is restricted to a group. Check if element can be seen by user
 // => récupérer un tableau contenant les roles associés à cet ID (a partir table restriction_to_roles)
 $user_is_included_in_role = 0;
 $roles = DB::query("SELECT role_id FROM " . prefix_table("restriction_to_roles") . " WHERE item_id=%i", $record['id']);
 if (count($roles) > 0) {
     $item_is_restricted_to_role = 1;
     foreach ($roles as $val) {
         if (in_array($val['role_id'], $_SESSION['user_roles'])) {
             $user_is_included_in_role = 1;
             break;
         }
     }
 }
 // Manage the restricted_to variable
 if (isset($_POST['restricted'])) {
     $restrictedTo = $_POST['restricted'];
 } else {
     $restrictedTo = "";
 }
Exemplo n.º 29
0
                            $title = $LANG['no_access'];
                            $label = '<i class="fa fa-hand-stop-o"></i>';
                        }
                        if (in_array($node->id, $_SESSION['read_only_folders']) || !in_array($node->id, $_SESSION['groupes_visibles'])) {
                            $texte .= '<td align=\'center\' style=\'text-align:center;background-color:' . $couleur . '\' id=\'tm_cell_' . $i . '\' title=\'' . $title . '\'>' . $label . '</td>';
                        } else {
                            $texte .= '<td align=\'center\' style=\'text-align:center;background-color:' . $couleur . '\' onclick=\'openRightsDialog(' . $role . ',' . $node->id . ',' . $i . ',"' . $allowed . '")\' id=\'tm_cell_' . $i . '\' title=\'' . $title . '\'>' . $label . '</td>';
                        }
                        $i++;
                    }
                    $texte .= '</tr>';
                }
            }
            $texte .= '</tbody></table>';
            $return_values = array("new_table" => $texte, "all" => $roles_count, "next" => $next, "previous" => $previous);
            //Check if is UTF8. IF not send Error
            /*if (!isUTF8($texte)) {
                  $return_values = array("error" => $LANG['error_string_not_utf8']);
              }*/
            $return_values = json_encode($return_values, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
            //return data
            echo $return_values;
            break;
    }
} elseif (!empty($_POST['edit_fonction'])) {
    $id = explode('_', $_POST['id']);
    //Update DB
    DB::update(prefix_table("roles_title"), array('title' => mysqli_escape_string($link, stripslashes(utf8_decode($_POST['edit_fonction'])))), "id = %i", $id[1]);
    //Show value
    echo $_POST['edit_fonction'];
}
Exemplo n.º 30
0
     }
 }
 // special Cases
 if ($dataReceived['field'] == "cpassman_url") {
     // update also jsUrl for CSFP protection
     $jsUrl = $dataReceived['value'] . '/includes/libraries/csrfp/js/csrfprotector.js';
     $csrfp_file = "../includes/libraries/csrfp/libs/csrfp.config.php";
     $data = file_get_contents($csrfp_file);
     $posJsUrl = strpos($data, '"jsUrl" => "');
     $posEndLine = strpos($data, '",', $posJsUrl);
     $line = substr($data, $posJsUrl, $posEndLine - $posJsUrl + 2);
     $newdata = str_replace($line, '"jsUrl" => "' . $jsUrl . '",', $data);
     file_put_contents($csrfp_file, $newdata);
 } else {
     if ($dataReceived['field'] == "restricted_to_input" && $dataReceived['value'] == "0") {
         DB::update(prefix_table("misc"), array('valeur' => 0), "type = %s AND intitule = %s", $type, 'restricted_to_roles');
     }
 }
 /* else
    if ($dataReceived['field'] == "use_md5_password_as_salt" && $dataReceived['value'] == "0") {
        // in case this option is changed, we need to warn the users to adapt
        $rows = DB::query(
            "SELECT id FROM ".prefix_table("users")."
            WHERE admin != %i",
            "",
            "1"
        );
        foreach ($rows as $record) {
            DB::update(
                prefix_table("users"),
                array(