コード例 #1
0
ファイル: doAuthorize.php プロジェクト: tamtrong/testlink
/** 
 * authorization function verifies login & password and set user session data 
 * return map
 *
 */
function doAuthorize(&$db, $login, $pwd)
{
    $result = array('status' => tl::ERROR, 'msg' => null);
    $_SESSION['locale'] = TL_DEFAULT_LOCALE;
    if (!is_null($pwd) && !is_null($login)) {
        $user = new tlUser();
        $user->login = $login;
        $login_exists = $user->readFromDB($db, tlUser::USER_O_SEARCH_BYLOGIN) >= tl::OK;
        if ($login_exists) {
            $password_check = auth_does_password_match($user, $pwd);
            if ($password_check->status_ok && $user->isActive) {
                // 20051007 MHT Solved  0000024 Session confusion
                // Disallow two sessions within one browser
                if (isset($_SESSION['currentUser']) && !is_null($_SESSION['currentUser'])) {
                    $result['msg'] = lang_get('login_msg_session_exists1') . ' <a style="color:white;" href="logout.php">' . lang_get('logout_link') . '</a>' . lang_get('login_msg_session_exists2');
                } else {
                    //Setting user's session information
                    $_SESSION['currentUser'] = $user;
                    $_SESSION['lastActivity'] = time();
                    global $g_tlLogger;
                    $g_tlLogger->endTransaction();
                    $g_tlLogger->startTransaction();
                    setUserSession($db, $user->login, $user->dbID, $user->globalRoleID, $user->emailAddress, $user->locale, null);
                    $result['status'] = tl::OK;
                }
            } else {
                logAuditEvent(TLS("audit_login_failed", $login, $_SERVER['REMOTE_ADDR']), "LOGIN_FAILED", $user->dbID, "users");
            }
        }
    }
    return $result;
}
コード例 #2
0
/** 
 * authorization function verifies login & password and set user session data 
 * return map
 *
 */
function doAuthorize(&$db, $login, $pwd)
{
    $result = array('status' => tl::ERROR, 'msg' => null);
    $_SESSION['locale'] = TL_DEFAULT_LOCALE;
    if (!is_null($pwd) && !is_null($login)) {
        $user = new tlUser();
        $user->login = $login;
        $login_exists = $user->readFromDB($db, tlUser::USER_O_SEARCH_BYLOGIN) >= tl::OK;
        if ($login_exists) {
            $check = auth_does_password_match($user, $pwd);
            if (!$check->status_ok) {
                $result = array('status' => tl::ERROR, 'msg' => $check->msg);
            }
            if ($check->status_ok && $user->isActive) {
                // Need to do set COOKIE following Mantis model
                $auth_cookie_name = config_get('auth_cookie');
                $expireOnBrowserClose = false;
                setcookie($auth_cookie_name, $user->getSecurityCookie(), $expireOnBrowserClose, '/');
                // Disallow two sessions within one browser
                if (isset($_SESSION['currentUser']) && !is_null($_SESSION['currentUser'])) {
                    $result['msg'] = lang_get('login_msg_session_exists1') . ' <a style="color:white;" href="logout.php">' . lang_get('logout_link') . '</a>' . lang_get('login_msg_session_exists2');
                } else {
                    // Setting user's session information
                    $_SESSION['currentUser'] = $user;
                    $_SESSION['lastActivity'] = time();
                    $user->setUserSession($db);
                    global $g_tlLogger;
                    $g_tlLogger->endTransaction();
                    $g_tlLogger->startTransaction();
                    // setUserSession($db,$user->login, $user->dbID,$user->globalRoleID,$user->emailAddress, $user->locale,null);
                    $result['status'] = tl::OK;
                }
            } else {
                logAuditEvent(TLS("audit_login_failed", $login, $_SERVER['REMOTE_ADDR']), "LOGIN_FAILED", $user->dbID, "users");
            }
        }
    }
    return $result;
}
コード例 #3
0
ファイル: doAuthorize.php プロジェクト: mokal/DCN_TestLink
/** 
 * for SSL Cliente Certificate we can not check password but
 * 1. login exists
 * 2. SSL context exist
 *
 * return map
 *
 */
function doSSOClientCertificate(&$dbHandler, $apache_mod_ssl_env, $authCfg = null)
{
    global $g_tlLogger;
    $result = array('status' => tl::ERROR, 'msg' => null);
    if (!isset($apache_mod_ssl_env['SSL_PROTOCOL'])) {
        return $result;
    }
    // With this we trust SSL is enabled => go ahead with login control
    $authCfg = is_null($authCfg) ? config_get('authentication') : $authCfg;
    $login = $apache_mod_ssl_env[$authCfg['SSO_uid_field']];
    if (!is_null($login)) {
        $user = new tlUser();
        $user->login = $login;
        $login_exists = $user->readFromDB($dbHandler, tlUser::USER_O_SEARCH_BYLOGIN) >= tl::OK;
        if ($login_exists && $user->isActive) {
            // Need to do set COOKIE following Mantis model
            $auth_cookie_name = config_get('auth_cookie');
            $expireOnBrowserClose = false;
            setcookie($auth_cookie_name, $user->getSecurityCookie(), $expireOnBrowserClose, '/');
            // Disallow two sessions within one browser
            if (isset($_SESSION['currentUser']) && !is_null($_SESSION['currentUser'])) {
                $result['msg'] = lang_get('login_msg_session_exists1') . ' <a style="color:white;" href="logout.php">' . lang_get('logout_link') . '</a>' . lang_get('login_msg_session_exists2');
            } else {
                // Setting user's session information
                $_SESSION['currentUser'] = $user;
                $_SESSION['lastActivity'] = time();
                $g_tlLogger->endTransaction();
                $g_tlLogger->startTransaction();
                setUserSession($dbHandler, $user->login, $user->dbID, $user->globalRoleID, $user->emailAddress, $user->locale, null);
                $result['status'] = tl::OK;
            }
        } else {
            logAuditEvent(TLS("audit_login_failed", $login, $_SERVER['REMOTE_ADDR']), "LOGIN_FAILED", $user->dbID, "users");
        }
    }
    return $result;
}
コード例 #4
0
ファイル: resultsImport.php プロジェクト: mokal/DCN_TestLink
function saveImportedResultData(&$db, $resultData, $context)
{
    if (!$resultData) {
        return;
    }
    $debugMsg = ' FUNCTION: ' . __FUNCTION__;
    $tables = tlObjectWithDB::getDBTables(array('executions', 'execution_bugs'));
    $l18n = array('import_results_tc_not_found' => '', 'import_results_invalid_result' => '', 'tproject_id_not_found' => '', 'import_results_ok' => '');
    foreach ($l18n as $key => $value) {
        $l18n[$key] = lang_get($key);
    }
    // Get Column definitions to get size dinamically instead of create constants
    $columnDef = array();
    $adodbObj = $db->get_dbmgr_object();
    $columnDef['execution_bugs'] = $adodbObj->MetaColumns($tables['execution_bugs']);
    $keySet = array_keys($columnDef['execution_bugs']);
    foreach ($keySet as $keyName) {
        if (($keylow = strtolower($keyName)) != $keyName) {
            $columnDef['execution_bugs'][$keylow] = $columnDef['execution_bugs'][$keyName];
            unset($columnDef['execution_bugs'][$keyName]);
        }
    }
    $user = new tlUser($context->userID);
    $user->readFromDB($db);
    $tcase_mgr = new testcase($db);
    $resulstCfg = config_get('results');
    $tcaseCfg = config_get('testcase_cfg');
    $resultMap = array();
    $tplan_mgr = null;
    $tc_qty = sizeof($resultData);
    if ($tc_qty) {
        $tplan_mgr = new testplan($db);
        $tproject_mgr = new testproject($db);
        $build_mgr = new build_mgr($db);
    }
    // Need to do checks on common settings
    //
    // test project exists
    //
    // test plan id:
    //              belongs to target test project
    //              is active
    // build id:
    //          belongs to target test plan
    //          is open
    //
    // platform id:
    //          is linked  to target test plan
    //
    // execution type if not present -> set to MANUAL
    //          if presente is valid i.e. inside the TL domain
    //
    $checks = array();
    $checks['status_ok'] = true;
    $checks['msg'] = null;
    $dummy = null;
    if (!is_null($context->tprojectID) && intval($context->tprojectID) > 0) {
        $dummy = array($tproject_mgr->get_by_id($context->tprojectID, array('output' => 'existsByID')));
    } else {
        if (!is_null($context->tprojectName)) {
            $dummy = $tproject_mgr->get_by_name($context->tprojectName, null, array('output' => 'existsByName'));
        }
    }
    $checks['status_ok'] = !is_null($dummy);
    if (!$checks['status_ok']) {
        $checks['msg'][] = sprintf($l18n['tproject_id_not_found'], $context->tprojectID);
    }
    if (!$checks['status_ok']) {
        foreach ($checks['msg'] as $warning) {
            $resultMap[] = array($warning);
        }
    }
    if ($doIt = $checks['status_ok']) {
        $context->tprojectID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    $dummy = null;
    if (!is_null($context->tplanID) && intval($context->tplanID) > 0) {
        $dummy = $tplan_mgr->get_by_id($context->tplanID, array('output' => 'minimun'));
        if (!is_null($dummy)) {
            $dummy['id'] = $context->tplanID;
        }
    } else {
        if (!is_null($context->tplanName)) {
            $dummy = $tplan_mgr->get_by_name($context->tplanName, $context->tprojectID, array('output' => 'minimun'));
            if (!is_null($dummy)) {
                $dummy = $dummy[0];
            }
        }
    }
    if (!is_null($dummy)) {
        $context->tplanID = $dummy['id'];
    }
    if (intval($context->tprojectID) <= 0 && intval($context->tplanID) > 0) {
        $dummy = $tplan_mgr->tree_manager->get_node_hierarchy_info($context->tplanID);
        $context->tprojectID = $dummy['parent_id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    $dummy = null;
    $tplan_mgr->platform_mgr->setTestProjectID($context->tprojectID);
    if (!is_null($context->platformID) && intval($context->platformID) > 0) {
        $dummy = array($tplan_mgr->platform_mgr->getByID($context->platformID));
    } else {
        if (property_exists($context, 'platformName') && !is_null($context->platformName)) {
            if (!is_null($xx = $tplan_mgr->platform_mgr->getID($context->platformName))) {
                $dummy = array(0 => array('id' => $xx));
            }
        }
    }
    if (!is_null($dummy)) {
        $context->platformID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    $optGB = array('tplan_id' => $context->tplanID, 'output' => 'minimun');
    $dummy = null;
    if (!is_null($context->buildID) && intval($context->buildID) > 0) {
        $dummy = array($build_mgr->get_by_id($context->buildID, $optGB));
    } else {
        if (!is_null($context->buildName)) {
            $dummy = $build_mgr->get_by_name($context->buildName, $optGB);
        }
    }
    if (!is_null($dummy)) {
        $context->buildID = $dummy[0]['id'];
    }
    // --------------------------------------------------------------------
    // --------------------------------------------------------------------
    for ($idx = 0; $doIt && $idx < $tc_qty; $idx++) {
        $tester_id = 0;
        $tester_name = '';
        $using_external_id = false;
        $message = null;
        $status_ok = true;
        $tcase_exec = $resultData[$idx];
        // New attribute "execution type" makes old XML import files incompatible
        // Important NOTICE:
        // tcase_exec is passed BY REFERENCE to allow check_exec_values()change execution type if needed
        //
        $checks = check_exec_values($db, $tcase_mgr, $user_mgr, $tcaseCfg, $tcase_exec, $columnDef['execution_bugs']);
        $status_ok = $checks['status_ok'];
        if ($status_ok) {
            $tcase_id = $checks['tcase_id'];
            $tcase_external_id = trim($tcase_exec['tcase_external_id']);
            $tester_id = $checks['tester_id'];
            // external_id has precedence over internal id
            $using_external_id = $tcase_external_id != "";
        } else {
            foreach ($checks['msg'] as $warning) {
                $resultMap[] = array($warning);
            }
        }
        if ($status_ok) {
            $tcase_identity = $using_external_id ? $tcase_external_id : $tcase_id;
            $result_code = strtolower($tcase_exec['result']);
            $result_is_acceptable = isset($resulstCfg['code_status'][$result_code]) ? true : false;
            $notes = $tcase_exec['notes'];
            $message = null;
            $info_on_case = $tplan_mgr->getLinkInfo($context->tplanID, $tcase_id, $context->platformID);
            if (is_null($info_on_case)) {
                $message = sprintf($l18n['import_results_tc_not_found'], $tcase_identity);
            } else {
                if (!$result_is_acceptable) {
                    $message = sprintf($l18n['import_results_invalid_result'], $tcase_identity, $tcase_exec['result']);
                } else {
                    $info_on_case = current($info_on_case);
                    $tcversion_id = $info_on_case['tcversion_id'];
                    $version = $info_on_case['version'];
                    $notes = $db->prepare_string(trim($notes));
                    // N.B.: db_now() returns an string ready to be used in an SQL insert
                    //       example '2008-09-04', while $tcase_exec["timestamp"] => 2008-09-04
                    //
                    $execution_ts = $tcase_exec['timestamp'] != '' ? "'" . $tcase_exec["timestamp"] . "'" : $db->db_now();
                    if ($tester_id != 0) {
                        $tester_name = $tcase_exec['tester'];
                    } else {
                        $tester_name = $user->login;
                        $tester_id = $context->userID;
                    }
                    $addExecDuration = strlen($tcase_exec['execution_duration']) > 0 && is_numeric($tcase_exec['execution_duration']);
                    $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['executions']} (build_id,tester_id,status,testplan_id," . " tcversion_id,execution_ts,notes,tcversion_number,platform_id,execution_type" . ($addExecDuration ? ',execution_duration' : '') . ")" . " VALUES ({$context->buildID}, {$tester_id},'{$result_code}',{$context->tplanID}, " . " {$tcversion_id},{$execution_ts},'{$notes}', {$version}, " . " {$context->platformID}, {$tcase_exec['execution_type']}" . ($addExecDuration ? ",{$tcase_exec['execution_duration']}" : '') . ")";
                    $db->exec_query($sql);
                    if (isset($tcase_exec['bug_id']) && !is_null($tcase_exec['bug_id']) && is_array($tcase_exec['bug_id'])) {
                        $execution_id = $db->insert_id($tables['executions']);
                        foreach ($tcase_exec['bug_id'] as $bug_id) {
                            $bug_id = trim($bug_id);
                            $sql = " /* {$debugMsg} */ " . " SELECT execution_id AS check_qty FROM  {$tables['execution_bugs']} " . " WHERE bug_id = '{$bug_id}' AND execution_id={$execution_id} ";
                            $rs = $db->get_recordset($sql);
                            if (is_null($rs)) {
                                $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['execution_bugs']} (bug_id,execution_id)" . " VALUES ('" . $db->prepare_string($bug_id) . "', {$execution_id} )";
                                $db->exec_query($sql);
                            }
                        }
                    }
                    $message = sprintf($l18n['import_results_ok'], $tcase_identity, $version, $tester_name, $resulstCfg['code_status'][$result_code], $execution_ts);
                }
            }
        }
        if (!is_null($message)) {
            $resultMap[] = array($message);
        }
    }
    return $resultMap;
}
コード例 #5
0
 function get_accessible_for_user($user_id, $output_type = 'map', $order_by = null)
 {
     $my['order_by'] = is_null($order_by) ? config_get('gui')->tprojects_combo_order_by : $order_by;
     $items = array();
     // Get default role
     $sql = " SELECT id,role_id FROM {$this->tables['users']} where id={$user_id}";
     $user_info = $this->db->get_recordset($sql);
     $role_id = $user_info[0]['role_id'];
     $sql = " SELECT nodes_hierarchy.name,testprojects.*\n \t          FROM {$this->tables['nodes_hierarchy']} nodes_hierarchy\n \t          JOIN {$this->object_table} testprojects ON nodes_hierarchy.id=testprojects.id\n\t          LEFT OUTER JOIN {$this->tables['user_testproject_roles']} user_testproject_roles\n\t\t        ON testprojects.id = user_testproject_roles.testproject_id AND\n\t\t \t      user_testproject_roles.user_id = {$user_id} WHERE 1=1 ";
     // Private test project
     if ($role_id != TL_ROLES_ADMIN) {
         if ($role_id != TL_ROLES_NO_RIGHTS) {
             // $sql .=  "(role_id IS NULL OR role_id != ".TL_ROLES_NO_RIGHTS.")";
             // (A AND (B OR C) ) OR (NOT A AND C)
             $sql .= " AND ";
             $sql_public = " ( is_public = 1 AND (role_id IS NULL OR role_id != " . TL_ROLES_NO_RIGHTS . ") )";
             $sql_private = " ( is_public = 0 AND role_id != " . TL_ROLES_NO_RIGHTS . ") ";
             $sql .= " ( {$sql_public}  OR {$sql_private} ) ";
         } else {
             // User need specific role
             $sql .= " AND (role_id IS NOT NULL AND role_id != " . TL_ROLES_NO_RIGHTS . ")";
         }
     }
     $userObj = new tlUser($user_id);
     $userObj->readFromDB($this->db);
     if ($userObj->hasRight($this->db, 'mgt_modify_product') != 'yes') {
         $sql .= " AND active=1 ";
     }
     $sql .= $my['order_by'];
     if ($output_type == 'array_of_map') {
         $items = $this->db->get_recordset($sql);
         $this->parseTestProjectRecordset($items);
         $do_post_process = 0;
     } else {
         $arrTemp = $this->db->fetchRowsIntoMap($sql, 'id');
         $do_post_process = 1;
     }
     if ($do_post_process && sizeof($arrTemp)) {
         switch ($output_type) {
             case 'map':
                 foreach ($arrTemp as $id => $row) {
                     $noteActive = '';
                     if (!$row['active']) {
                         $noteActive = TL_INACTIVE_MARKUP;
                     }
                     $items[$id] = $noteActive . $row['name'];
                 }
                 break;
             case 'map_of_map':
                 foreach ($arrTemp as $id => $row) {
                     $items[$id] = array('name' => $row['name'], 'active' => $row['active']);
                 }
                 break;
         }
     }
     return $items;
 }
コード例 #6
0
ファイル: tlUser.class.php プロジェクト: viglesiasce/tl_RC1
 public static function doesUserExist(&$db, $login)
 {
     $user = new tlUser();
     $user->login = $login;
     if ($user->readFromDB($db, self::USER_O_SEARCH_BYLOGIN) >= tl::OK) {
         return $user->dbID;
     }
     return null;
 }
コード例 #7
0
ファイル: common.php プロジェクト: mweyamutsvene/testlink
/**
 *
 */
function setUpEnvForRemoteAccess(&$dbHandler, $apikey, $rightsCheck = null, $opt = null)
{
    $my = array('opt' => array('setPaths' => false, 'clearSession' => false));
    $my['opt'] = array_merge($my['opt'], (array) $opt);
    if ($my['opt']['clearSession']) {
        $_SESSION = null;
    }
    doSessionStart($my['opt']['setPaths']);
    if (isset($_SESSION['locale']) && !is_null($_SESSION['locale'])) {
        setDateTimeFormats($_SESSION['locale']);
    }
    doDBConnect($dbHandler);
    $user = tlUser::getByAPIKey($dbHandler, $apikey);
    if (count($user) == 1) {
        $_SESSION['lastActivity'] = time();
        $userObj = new tlUser(key($user));
        $userObj->readFromDB($dbHandler);
        $_SESSION['currentUser'] = $userObj;
        $_SESSION['userID'] = $userObj->dbID;
        $_SESSION['locale'] = $userObj->locale;
        // if user do this:
        // 1. login to test link
        // 2. get direct link and open in new tab or new window while still logged
        // 3. logout
        // If user refresh tab / window open on (2), because on (3) we destroyed
        // session we have loose basehref, and we are not able to recreate it.
        // Without basehref we are not able to get CSS, JS, etc.
        // In this situation we destroy session, this way user is forced to login
        // again in one of two ways
        // a. using the direct link
        // b. using traditional login
        // In both way we assure that behaivour will be OK.
        //
        if (!isset($_SESSION['basehref'])) {
            session_unset();
            session_destroy();
            if (property_exists($rightsCheck, 'redirect_target') && !is_null($rightsCheck->redirect_target)) {
                redirect($rightsCheck->redirect_target);
            } else {
                // best guess for all features that live on ./lib/results/
                redirect("../../login.php?note=logout");
            }
            exit;
        }
        if (!is_null($rightsCheck)) {
            checkUserRightsFor($dbHandler, $rightsCheck, true);
        }
    }
}
コード例 #8
0
ファイル: users.inc.php プロジェクト: tamtrong/testlink
/**
 * reset user password in DB
 * 
 * @param resource &$db reference to database handler
 * @param integer $userID 
 * @param string &$errorMsg reference to error message
 * 
 * @return integer result status code
 */
function resetPassword(&$db, $userID, &$errorMsg)
{
    $errorMsg = '';
    $user = new tlUser($userID);
    $result = $user->readFromDB($db);
    if ($result >= tl::OK) {
        $result = tlUser::E_EMAILLENGTH;
        if ($user->emailAddress != "") {
            $newPassword = tlUser::generatePassword(8, 4);
            $result = $user->setPassword($newPassword);
            if ($result >= tl::OK) {
                // BUGID 3396
                $msgBody = lang_get('your_password_is') . "\n\n" . $newPassword . "\n\n" . lang_get('contact_admin');
                $mail_op = @email_send(config_get('from_email'), $user->emailAddress, lang_get('mail_passwd_subject'), $msgBody);
                if ($mail_op->status_ok) {
                    $result = $user->writePasswordToDB($db);
                    // BUGID 3396
                } else {
                    $result = tl::ERROR;
                    $errorMsg = $mail_op->msg;
                }
            }
        }
    }
    $errorMsg = $errorMsg != "" ? $errorMsg : getUserErrorMessage($result);
    return $result;
}
コード例 #9
0
        // need to know if auth method for user allows reset
        $user = new tlUser(intval($userID));
        $user->readFromDB($db);
        if (tlUser::isPasswordMgtExternal($user->authentication, $user->authentication)) {
            $gui->external_password_mgmt = 1;
            $gui->password_mgmt_feedback = sprintf(lang_get('password_mgmt_feedback'), trim($args->login));
        }
    }
}
if (!$gui->external_password_mgmt && $userID) {
    echo __LINE__;
    $result = resetPassword($db, $userID);
    $gui->note = $result['msg'];
    if ($result['status'] >= tl::OK) {
        $user = new tlUser($userID);
        if ($user->readFromDB($db) >= tl::OK) {
            logAuditEvent(TLS("audit_pwd_reset_requested", $user->login), "PWD_RESET", $userID, "users");
        }
        redirect(TL_BASE_HREF . "login.php?note=lost");
        exit;
    } else {
        if ($result['status'] == tlUser::E_EMAILLENGTH) {
            $gui->note = lang_get('mail_empty_address');
        } else {
            if ($note != "") {
                $gui->note = getUserErrorMessage($result['status']);
            }
        }
    }
}
$smarty = new TLSmarty();
コード例 #10
0
ファイル: resultsImport.php プロジェクト: tamtrong/testlink
function saveImportedResultData(&$db, $resultData, $context)
{
    if (!$resultData) {
        return;
    }
    $debugMsg = ' FUNCTION: ' . __FUNCTION__;
    $tables = tlObjectWithDB::getDBTables(array('executions', 'execution_bugs'));
    $l18n = array('import_results_tc_not_found' => '', 'import_results_invalid_result' => '', 'tproject_id_not_found' => '', 'import_results_ok' => '');
    foreach ($l18n as $key => $value) {
        $l18n[$key] = lang_get($key);
    }
    // Get Column definitions to get size dinamically instead of create constants
    $columnDef = array();
    $adodbObj = $db->get_dbmgr_object();
    $columnDef['execution_bugs'] = $adodbObj->MetaColumns($tables['execution_bugs']);
    $keySet = array_keys($columnDef['execution_bugs']);
    foreach ($keySet as $keyName) {
        if (($keylow = strtolower($keyName)) != $keyName) {
            $columnDef['execution_bugs'][$keylow] = $columnDef['execution_bugs'][$keyName];
            unset($columnDef['execution_bugs'][$keyName]);
        }
    }
    $user = new tlUser($context->userID);
    $user->readFromDB($db);
    $tcase_mgr = new testcase($db);
    $resulstCfg = config_get('results');
    $tcaseCfg = config_get('testcase_cfg');
    $resultMap = array();
    $tplan_mgr = null;
    $tc_qty = sizeof($resultData);
    if ($tc_qty) {
        $tplan_mgr = new testplan($db);
        $tproject_mgr = new testproject($db);
    }
    // Need to do checks on common settings
    //
    // test project exists
    //
    // test plan id:
    //              belongs to target test project
    //              is active
    // build id:
    //          belongs to target test plan
    //          is open
    //
    // platform id:
    //          is linked  to target test plan
    //
    $checks['status_ok'] = true;
    $checks['msg'] = null;
    $dummy = $tproject_mgr->get_by_id($context->tprojectID);
    $checks['status_ok'] = !is_null($dummy);
    if (!$checks['status_ok']) {
        $checks['msg'][] = sprintf($l19n['tproject_id_not_found'], $context->tprojectID);
    }
    // if( $checks['status_ok'] )
    // {
    //
    // }
    if (!$checks['status_ok']) {
        foreach ($checks['msg'] as $warning) {
            $resultMap[] = array($warning);
        }
    }
    $doIt = $checks['status_ok'];
    // --------------------------------------------------------------------
    for ($idx = 0; $doIt && $idx < $tc_qty; $idx++) {
        $tester_id = 0;
        $tester_name = '';
        $using_external_id = false;
        $message = null;
        $status_ok = true;
        $tcase_exec = $resultData[$idx];
        $checks = check_exec_values($db, $tcase_mgr, $user_mgr, $tcaseCfg, $tcase_exec, $columnDef['execution_bugs']);
        $status_ok = $checks['status_ok'];
        if ($status_ok) {
            $tcase_id = $checks['tcase_id'];
            $tcase_external_id = trim($tcase_exec['tcase_external_id']);
            $tester_id = $checks['tester_id'];
            // external_id has precedence over internal id
            $using_external_id = $tcase_external_id != "";
        } else {
            foreach ($checks['msg'] as $warning) {
                $resultMap[] = array($warning);
            }
        }
        if ($status_ok) {
            $tcase_identity = $using_external_id ? $tcase_external_id : $tcase_id;
            $result_code = strtolower($tcase_exec['result']);
            $result_is_acceptable = isset($resulstCfg['code_status'][$result_code]) ? true : false;
            $notes = $tcase_exec['notes'];
            $message = null;
            $filters = array('tcase_id' => $tcase_id, 'build_id' => $context->buildID, 'platform_id' => $context->platformID);
            $linked_cases = $tplan_mgr->get_linked_tcversions($context->tplanID, $filters);
            $info_on_case = $linked_cases[$tcase_id];
            if (!$linked_cases) {
                $message = sprintf($l18n['import_results_tc_not_found'], $tcase_identity);
            } else {
                if (!$result_is_acceptable) {
                    $message = sprintf($l18n['import_results_invalid_result'], $tcase_identity, $tcase_exec['result']);
                } else {
                    $tcversion_id = $info_on_case['tcversion_id'];
                    $version = $info_on_case['version'];
                    $notes = $db->prepare_string(trim($notes));
                    // N.B.: db_now() returns an string ready to be used in an SQL insert
                    //       example '2008-09-04', while $tcase_exec["timestamp"] => 2008-09-04
                    //
                    $execution_ts = $tcase_exec['timestamp'] != '' ? "'" . $tcase_exec["timestamp"] . "'" : $db->db_now();
                    if ($tester_id != 0) {
                        $tester_name = $tcase_exec['tester'];
                    } else {
                        $tester_name = $user->login;
                        $tester_id = $context->userID;
                    }
                    // BUGID 3543 - added execution_type
                    $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['executions']} (build_id,tester_id,status,testplan_id," . " tcversion_id,execution_ts,notes,tcversion_number,platform_id,execution_type)" . " VALUES ({$context->buildID}, {$tester_id},'{$result_code}',{$context->tplanID}, " . " {$tcversion_id},{$execution_ts},'{$notes}', {$version}, " . " {$context->platformID}, {$tcase_exec['execution_type']})";
                    $db->exec_query($sql);
                    // BUGID 3331
                    if (isset($tcase_exec['bug_id'])) {
                        $execution_id = $db->insert_id($tables['executions']);
                        foreach ($tcase_exec['bug_id'] as $bug_id) {
                            $bug_id = trim($bug_id);
                            $sql = " /* {$debugMsg} */ " . " SELECT execution_id AS check_qty FROM  {$tables['execution_bugs']} " . " WHERE bug_id = '{$bug_id}' AND execution_id={$execution_id} ";
                            $rs = $db->get_recordset($sql);
                            if (is_null($rs)) {
                                $sql = " /* {$debugMsg} */ " . " INSERT INTO {$tables['execution_bugs']} (bug_id,execution_id)" . " VALUES ('" . $db->prepare_string($bug_id) . "', {$execution_id} )";
                                $db->exec_query($sql);
                            }
                        }
                    }
                    $message = sprintf($l18n['import_results_ok'], $tcase_identity, $version, $tester_name, $resulstCfg['code_status'][$result_code], $execution_ts);
                }
            }
        }
        if (!is_null($message)) {
            $resultMap[] = array($message);
        }
    }
    return $resultMap;
}
function saveImportedTCData(&$db, $tcData, $tproject_id, $container_id, $userID, $kwMap, $duplicatedLogic = array('hitCriteria' => 'name', 'actionOnHit' => null))
{
    static $messages;
    static $fieldSizeCfg;
    static $feedbackMsg;
    static $tcase_mgr;
    static $tproject_mgr;
    static $req_spec_mgr;
    static $req_mgr;
    static $safeSizeCfg;
    static $linkedCustomFields;
    static $tprojectHas;
    static $reqSpecSet;
    static $getVersionOpt;
    static $userObj;
    if (!$tcData) {
        return;
    }
    // $tprojectHas = array('customFields' => false, 'reqSpec' => false);
    $hasCustomFieldsInfo = false;
    $hasRequirements = false;
    if (is_null($messages)) {
        $feedbackMsg = array();
        $messages = array();
        $fieldSizeCfg = config_get('field_size');
        $tcase_mgr = new testcase($db);
        $tproject_mgr = new testproject($db);
        $req_spec_mgr = new requirement_spec_mgr($db);
        $req_mgr = new requirement_mgr($db);
        $userObj = new tlUser();
        $k2l = array('already_exists_updated', 'original_name', 'testcase_name_too_long', 'start_warning', 'end_warning', 'testlink_warning', 'hit_with_same_external_ID');
        foreach ($k2l as $k) {
            $messages[$k] = lang_get($k);
        }
        $messages['start_feedback'] = $messages['start_warning'] . "\n" . $messages['testlink_warning'] . "\n";
        $messages['cf_warning'] = lang_get('no_cf_defined_can_not_import');
        $messages['reqspec_warning'] = lang_get('no_reqspec_defined_can_not_import');
        $feedbackMsg['cfield'] = lang_get('cf_value_not_imported_missing_cf_on_testproject');
        $feedbackMsg['tcase'] = lang_get('testcase');
        $feedbackMsg['req'] = lang_get('req_not_in_req_spec_on_tcimport');
        $feedbackMsg['req_spec'] = lang_get('req_spec_ko_on_tcimport');
        // because name can be changed automatically during item creation
        // to avoid name conflict adding a suffix automatically generated,
        // is better to use a max size < max allowed size
        $safeSizeCfg = new stdClass();
        $safeSizeCfg->testcase_name = $fieldSizeCfg->testcase_name * 0.8;
        // Get CF with scope design time and allowed for test cases linked to this test project
        $linkedCustomFields = $tcase_mgr->cfield_mgr->get_linked_cfields_at_design($tproject_id, 1, null, 'testcase', null, 'name');
        $tprojectHas['customFields'] = !is_null($linkedCustomFields);
        $reqSpecSet = $tproject_mgr->getReqSpec($tproject_id, null, array('RSPEC.id', 'NH.name AS title', 'RSPEC.doc_id as rspec_doc_id', 'REQ.req_doc_id'), 'req_doc_id');
        $tprojectHas['reqSpec'] = !is_null($reqSpecSet) && count($reqSpecSet) > 0;
        $getVersionOpt = array('output' => 'minimun');
        $tcasePrefix = $tproject_mgr->getTestCasePrefix($tproject_id);
    }
    $resultMap = array();
    $tc_qty = sizeof($tcData);
    $userIDCache = array();
    for ($idx = 0; $idx < $tc_qty; $idx++) {
        $tc = $tcData[$idx];
        $name = $tc['name'];
        $summary = $tc['summary'];
        $steps = $tc['steps'];
        // I've changed value to use when order has not been provided
        // from testcase:DEFAULT_ORDER to a counter, because with original solution
        // an issue arise with 'save execution and go next'
        // if use has not provided order I think is OK TestLink make any choice.
        $node_order = isset($tc['node_order']) ? intval($tc['node_order']) : $idx + 1;
        $internalid = $tc['internalid'];
        $preconditions = $tc['preconditions'];
        $exec_type = isset($tc['execution_type']) ? $tc['execution_type'] : TESTCASE_EXECUTION_TYPE_MANUAL;
        $importance = isset($tc['importance']) ? $tc['importance'] : MEDIUM;
        $externalid = $tc['externalid'];
        if (intval($externalid) <= 0) {
            $externalid = null;
        }
        $personID = $userID;
        if (!is_null($tc['author_login'])) {
            if (isset($userIDCache[$tc['author_login']])) {
                $personID = $userIDCache[$tc['author_login']];
            } else {
                $userObj->login = $tc['author_login'];
                if ($userObj->readFromDB($db, tlUser::USER_O_SEARCH_BYLOGIN) == tl::OK) {
                    $personID = $userObj->dbID;
                }
                // I will put always a valid userID on this cache,
                // this way if author_login does not exit, and is used multiple times
                // i will do check for existence JUST ONCE.
                $userIDCache[$tc['author_login']] = $personID;
            }
        }
        $name_len = tlStringLen($name);
        if ($name_len > $fieldSizeCfg->testcase_name) {
            // Will put original name inside summary
            $xx = $messages['start_feedback'];
            $xx .= sprintf($messages['testcase_name_too_long'], $name_len, $fieldSizeCfg->testcase_name) . "\n";
            $xx .= $messages['original_name'] . "\n" . $name . "\n" . $messages['end_warning'] . "\n";
            $summary = nl2br($xx) . $summary;
            $name = tlSubStr($name, 0, $safeSizeCfg->testcase_name);
        }
        $kwIDs = null;
        if (isset($tc['keywords']) && $tc['keywords']) {
            $kwIDs = implode(",", buildKeywordList($kwMap, $tc['keywords']));
        }
        $doCreate = true;
        if ($duplicatedLogic['actionOnHit'] == 'update_last_version') {
            switch ($duplicatedLogic['hitCriteria']) {
                case 'name':
                    $info = $tcase_mgr->getDuplicatesByName($name, $container_id);
                    break;
                case 'internalID':
                    $dummy = $tcase_mgr->tree_manager->get_node_hierarchy_info($internalid, $container_id);
                    if (!is_null($dummy)) {
                        $info = null;
                        $info[$internalid] = $dummy;
                    }
                    break;
                case 'externalID':
                    $info = $tcase_mgr->get_by_external($externalid, $container_id);
                    break;
            }
            if (!is_null($info)) {
                $tcase_qty = count($info);
                switch ($tcase_qty) {
                    case 1:
                        $doCreate = false;
                        $tcase_id = key($info);
                        $last_version = $tcase_mgr->get_last_version_info($tcase_id, $getVersionOpt);
                        $tcversion_id = $last_version['id'];
                        $ret = $tcase_mgr->update($tcase_id, $tcversion_id, $name, $summary, $preconditions, $steps, $personID, $kwIDs, $node_order, $exec_type, $importance);
                        $ret['id'] = $tcase_id;
                        $ret['tcversion_id'] = $tcversion_id;
                        $resultMap[] = array($name, $messages['already_exists_updated']);
                        break;
                    case 0:
                        $doCreate = true;
                        break;
                    default:
                        $doCreate = false;
                        break;
                }
            }
        }
        if ($doCreate) {
            // Want to block creation of with existent EXTERNAL ID, if containers ARE DIFFERENT.
            $item_id = intval($tcase_mgr->getInternalID($externalid, array('tproject_id' => $tproject_id)));
            if ($item_id > 0) {
                // who is his parent ?
                $owner = $tcase_mgr->getTestSuite($item_id);
                if ($owner != $container_id) {
                    // Get full path of existent Test Cases
                    $stain = $tcase_mgr->tree_manager->get_path($item_id, null, 'name');
                    $n = count($stain);
                    $stain[$n - 1] = $tcasePrefix . config_get('testcase_cfg')->glue_character . $externalid . ':' . $stain[$n - 1];
                    $stain = implode('/', $stain);
                    $resultMap[] = array($name, $messages['hit_with_same_external_ID'] . $stain);
                    $doCreate = false;
                }
            }
        }
        if ($doCreate) {
            $createOptions = array('check_duplicate_name' => testcase::CHECK_DUPLICATE_NAME, 'action_on_duplicate_name' => $duplicatedLogic['actionOnHit'], 'external_id' => $externalid);
            if ($ret = $tcase_mgr->create($container_id, $name, $summary, $preconditions, $steps, $personID, $kwIDs, $node_order, testcase::AUTOMATIC_ID, $exec_type, $importance, $createOptions)) {
                $resultMap[] = array($name, $ret['msg']);
            }
        }
    }
    return $resultMap;
}
コード例 #12
0
     }
     if ($op['status_ok']) {
         $gui->id = $args->testsuiteID;
         $gui->page_title = lang_get('container_title_testsuite');
         $gui->refreshTree = $args->refreshTree;
         $identity = new stdClass();
         $identity->id = $args->testsuiteID;
         $identity->tproject_id = $args->tproject_id;
         $tsuite_mgr->show($smarty, $gui, $identity);
     } else {
         // $userInput is used to maintain data filled by user if there is
         // a problem with test suite name.
         $userInput = $_REQUEST;
         if ($gui->midAirCollision = $op['reason'] == 'midAirCollision') {
             $foe = new tlUser($op['more']['updater_id']);
             $foe->readFromDB($db);
             $gui->midAirCollisionMsg['main'] = sprintf(lang_get('collision_detected_some_one_else'), $op['more']['modification_ts'], $foe->login, $foe->emailAddress);
             $gui->midAirCollisionMsg['details'] = sprintf(lang_get('collision_detected_choices'), $foe->login);
         }
         renderTestSuiteForManagement($smarty, $args, $gui, $tsuite_mgr, $keywordSet, $userInput);
     }
     break;
 case 'do_move_tcase_set':
     moveTestCases($smarty, $template_dir, $tsuite_mgr, $tree_mgr, $args);
     break;
 case 'do_copy_tcase_set':
     $op = copyTestCases($smarty, $template_dir, $tsuite_mgr, $tcase_mgr, $args);
     $refreshTree = $op['refreshTree'];
     moveTestCasesViewer($db, $smarty, $tproject_mgr, $tree_mgr, $args, $op['userfeedback']);
     break;
 case 'delete_testcases':
コード例 #13
0
ファイル: users.inc.php プロジェクト: JacekKarwas/smutek
/**
 * reset user password in DB
 * 
 * @param resource &$db reference to database handler
 * @param integer $userID 
 * @param string $newPasswordSendMethod, default 'send_password_by_mail'
 * 
 * @return hash
 *         status: integer result status code
 *         password: new password
 *         msg: error message (if any)  
 */
function resetPassword(&$db, $userID, $passwordSendMethod = 'send_password_by_mail')
{
    $retval = array('status' => tl::OK, 'password' => '', 'msg' => '');
    $user = new tlUser($userID);
    $retval['status'] = $user->readFromDB($db);
    // Reset can be done ONLY if user authentication method allows it.
    $doIt = false;
    if ($retval['status'] >= tl::OK) {
        $cfg = config_get('authentication');
        $cfg = $cfg['domain'];
        $doIt = isset($cfg[$user->authentication]) && $cfg[$user->authentication]['allowPasswordManagement'];
    }
    if ($doIt) {
        $retval['status'] = tlUser::E_EMAILLENGTH;
        if (trim($user->emailAddress) != "") {
            $newPassword = tlUser::generatePassword(8, 4);
            $retval['status'] = $user->setPassword($newPassword, $cfg[$user->authentication]);
            if ($retval['status'] >= tl::OK) {
                $retval['password'] = $newPassword;
                $mail_op = new stdClass();
                $mail_op->status_ok = false;
                if ($passwordSendMethod == 'send_password_by_mail') {
                    $msgBody = lang_get('your_password_is') . "\n\n" . $newPassword . "\n\n" . lang_get('contact_admin');
                    $mail_op = @email_send(config_get('from_email'), $user->emailAddress, lang_get('mail_passwd_subject'), $msgBody);
                }
                if ($mail_op->status_ok || $passwordSendMethod == 'display_on_screen') {
                    $retval['status'] = $user->writePasswordToDB($db);
                } else {
                    $retval['status'] = tl::ERROR;
                    $retval['msg'] = $mail_op->msg;
                }
            }
        }
    }
    $retval['msg'] = $retval['msg'] != "" ? $retval['msg'] : getUserErrorMessage($retval['status']);
    return $retval;
}
コード例 #14
0
ファイル: usersView.php プロジェクト: tamtrong/testlink
testlinkInitPage($db, false, false, "checkRights");
$templateCfg = templateConfiguration();
$args = init_args();
$grants = getGrantsForUserMgmt($db, $args->currentUser);
$sqlResult = null;
$action = null;
$user_feedback = '';
$orderBy = new stdClass();
$orderBy->type = 'order_by_login';
$orderBy->dir = array('order_by_login_dir' => 'asc');
switch ($args->operation) {
    case 'disable':
        // user cannot disable => inactivate itself
        if ($args->user_id != $args->currentUserID) {
            $user = new tlUser($args->user_id);
            $sqlResult = $user->readFromDB($db);
            if ($sqlResult >= tl::OK) {
                $userLogin = $user->login;
                $sqlResult = $user->setActive($db, 0);
                if ($sqlResult >= tl::OK) {
                    logAuditEvent(TLS("audit_user_disabled", $user->login), "DISABLE", $args->user_id, "users");
                    $user_feedback = sprintf(lang_get('user_disabled'), $userLogin);
                }
            }
        }
        if ($sqlResult != tl::OK) {
            $user_feedback = lang_get('error_user_not_disabled');
        }
        $orderBy->type = $args->user_order_by;
        $orderBy->dir = $args->order_by_dir;
        break;
コード例 #15
0
ファイル: common.php プロジェクト: tamtrong/testlink
/** 
 * Verify if user is log in. Redirect to login page if not.
 * 
 * @param integer $db DB identifier 
 * @param boolean $redirect if true (default) redirects user to login page, otherwise returns true/false as login status
 **/
function checkSessionValid(&$db, $redirect = true)
{
    $isValidSession = false;
    if (isset($_SESSION['userID']) && $_SESSION['userID'] > 0) {
        /** @TODO martin: 
        		    Talk with Andreas to understand:
        		    1. advantages of this approach
        		    2. do we need to recreate it every time ? why ?
        		   
        		 * a) store just data -not all object
        		 * b) do not read again and again the same data from DB
        		 * c) this function check JUST session validity
        		 **/
        $now = time();
        $lastActivity = $_SESSION['lastActivity'];
        if ($now - $lastActivity <= config_get("sessionInactivityTimeout") * 60) {
            $_SESSION['lastActivity'] = $now;
            $user = new tlUser($_SESSION['userID']);
            $user->readFromDB($db);
            $_SESSION['currentUser'] = $user;
            $isValidSession = true;
        }
    }
    if (!$isValidSession && $redirect) {
        $ip = $_SERVER["REMOTE_ADDR"];
        tLog('Invalid session from ' . $ip . '. Redirected to login page.', 'INFO');
        $fName = "login.php";
        $baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
        while (!file_exists($baseDir . DIRECTORY_SEPARATOR . $fName)) {
            $fName = "../" . $fName;
        }
        redirect($fName . "?note=expired", "top.location");
        exit;
    }
    return $isValidSession;
}
コード例 #16
0
 /**
  * Generate the API Key
  *
  * @param struct $args
  * @param string $args["user"]
  * @param string $args["pass"]
  * @return string
  * @access public
  */
 public function generateAPIKey($args)
 {
     $this->_setArgs($args);
     $login = $this->args[self::$userParamName];
     $pwd = $this->args['pass'];
     $user = new tlUser();
     $user->login = $login;
     $login_exists = $user->readFromDB($this->dbObj, tlUser::USER_O_SEARCH_BYLOGIN) >= tl::OK;
     $checkBD = $user->comparePassword($pwd) == tl::OK;
     $checkLDAP = ldap_authenticate($login, $pwd);
     if ($checkBD or $checkLDAP->status_ok) {
         $user_id = tlUser::doesUserExist($this->dbObj, $login);
         if (is_null($user_id)) {
             $this->errors[] = new IXR_Error(NO_USER_BY_THIS_LOGIN, 'This is a valid user, but is not on TestLink DB');
         } else {
             $op = new stdClass();
             $op->status = tl::OK;
             $op->user_feedback = null;
             $APIKey = new APIKey();
             $ak = $APIKey->getAPIKey($user_id);
             if (!is_null($ak)) {
                 return $ak;
             }
             if ($APIKey->addKeyForUser($user_id) >= tl::OK) {
                 return $APIKey->getAPIKey($user_id);
             } else {
                 $this->errors[] = new IXR_Error(NO_DEV_KEY, NO_DEV_KEY_STR);
             }
         }
     } else {
         $this->errors[] = new IXR_Error(INVALID_AUTH, INVALID_AUTH_STR);
     }
     return $this->errors;
 }
コード例 #17
0
ファイル: userInfo.php プロジェクト: moraesmv/testlink-code
 * @copyright 	2007-2011, TestLink community 
 * @version    	CVS: $Id: userInfo.php,v 1.34 2011/01/10 15:38:55 asimon83 Exp $
 * @link 		http://www.teamst.org/index.php
 *
 *
 * @internal Revisions:
 *	20101008 - Julian - reload navBar after changing personal data (localization)
 */
require_once '../../config.inc.php';
require_once 'users.inc.php';
require_once '../../lib/api/APIKey.php';
testlinkInitPage($db);
$templateCfg = templateConfiguration();
$args = init_args();
$user = new tlUser($args->userID);
$user->readFromDB($db);
$gui = new stdClass();
$gui->tproject_id = $args->tproject_id;
$gui->update_title_bar = 0;
$gui->external_password_mgmt = tlUser::isPasswordMgtExternal();
$gui->mgt_view_events = $user->hasRight($db, "mgt_view_events", $gui->tproject_id);
$op = new stdClass();
$op->auditMsg = null;
$op->user_feedback = null;
$op->status = tl::OK;
$doUpdate = false;
switch ($args->doAction) {
    case 'editUser':
        $doUpdate = true;
        foreach ($args->user as $key => $value) {
            $user->{$key} = $value;
コード例 #18
0
 * @since 1.9.9
 * 
 */
require_once "../../config.inc.php";
require_once 'exttable.class.php';
require_once "users.inc.php";
testlinkInitPage($db, false, false, "checkRights");
$smarty = new TLSmarty();
$templateCfg = templateConfiguration();
list($args, $gui) = initEnv($db);
switch ($args->operation) {
    case 'disable':
        // user cannot disable => inactivate itself
        if ($args->user_id != $args->currentUserID) {
            $user = new tlUser($args->user_id);
            $gui->result = $user->readFromDB($db);
            if ($gui->result >= tl::OK) {
                $gui->result = $user->setActive($db, 0);
                if ($gui->result >= tl::OK) {
                    logAuditEvent(TLS("audit_user_disabled", $user->login), "DISABLE", $args->user_id, "users");
                    $gui->user_feedback = sprintf(lang_get('user_disabled'), $user->login);
                }
            }
        }
        if ($gui->result != tl::OK) {
            $gui->user_feedback = lang_get('error_user_not_disabled');
        }
        break;
    default:
        break;
}
コード例 #19
0
ファイル: configCheck.php プロジェクト: mokal/DCN_TestLink
/**
 * checks if the default password for the admin accout is still set
 *
 * @return boolean returns true if the default password for the admin account is set, 
 *         false else
 * @author Andreas Morsing 
 **/
function checkForAdminDefaultPwd(&$db)
{
    $passwordHasDefaultValue = false;
    $user = new tlUser();
    $user->login = "******";
    if ($user->readFromDB($db, tlUser::USER_O_SEARCH_BYLOGIN) >= tl::OK && $user->comparePassword("admin") >= tl::OK) {
        $passwordHasDefaultValue = true;
    }
    return $passwordHasDefaultValue;
}
コード例 #20
0
ファイル: common.php プロジェクト: moraesmv/testlink-code
/** 
 * Verify if Session is valid,
 * Redirect to login page if not.
 * 
 * @param integer $db DB handler
 * @param boolean $redirect if true (default) redirects user to login page, 
 * 							  otherwise returns true/false as login status
 **/
function checkSessionValid(&$db, $redirect = true)
{
    $isValidSession = false;
    if (isset($_SESSION['userID']) && $_SESSION['userID'] > 0) {
        $now = time();
        $renewSession = $now - $_SESSION['lastActivity'] <= config_get("sessionInactivityTimeout") * 60;
        if ($renewSession) {
            $_SESSION['lastActivity'] = $now;
            // Because this method is called each time we access a page,
            // is OK to re-read user info, to update all info than can be changed like roles and rights.
            // What we are done with user object in session, IMHO is some sort of BAD Global coupling
            // We are illuding ourselve we are using cached data but is not RIGHT.
            $user = new tlUser($_SESSION['userID']);
            $user->readFromDB($db);
            $_SESSION['currentUser'] = $user;
            $isValidSession = true;
        }
    }
    if (!$isValidSession && $redirect) {
        $ip = $_SERVER["REMOTE_ADDR"];
        tLog('Invalid session from ' . $ip . '. Redirected to login page.', 'INFO');
        $fName = "login.php";
        $baseDir = dirname($_SERVER['SCRIPT_FILENAME']);
        while (!file_exists($baseDir . DIRECTORY_SEPARATOR . $fName)) {
            $fName = "../" . $fName;
        }
        $destination = "&destination=" . urlencode($_SERVER['REQUEST_URI']);
        redirect($fName . "?note=expired" . $destination, "top.location");
        exit;
    }
    return $isValidSession;
}