function displayAllUsers()
{
    $usersDAO = new UsersDAO(MaBD::getInstance());
    $users = $usersDAO->getAll();
    foreach ($users as $user) {
        displayUser($user);
    }
}
Example #2
0
 public static function FindByUsername($username)
 {
     $vo_Query = new Users(array("username" => $username));
     $a_Results = UsersDAO::search($vo_Query);
     if (sizeof($a_Results) != 1) {
         return NULL;
     }
     return array_pop($a_Results);
 }
Example #3
0
 /**
  *
  */
 public function testViewProblemInAContestDetailsValid()
 {
     // Get a contest
     $contestData = ContestsFactory::createContest();
     // Get a user to be the author
     $author = UserFactory::createUser();
     // Get a problem
     $problemData = ProblemsFactory::createProblem(null, null, 1, $author);
     // Add the problem to the contest
     ContestsFactory::addProblemToContest($problemData, $contestData);
     // Get a user for our scenario
     $contestant = UserFactory::createUser();
     // Prepare our request
     $r = new Request();
     $r["contest_alias"] = $contestData["request"]["alias"];
     $r["problem_alias"] = $problemData["request"]["alias"];
     // Log in the user
     $r["auth_token"] = $this->login($contestant);
     // Explicitly join contest
     ContestController::apiOpen($r);
     // Call api
     $response = ProblemController::apiDetails($r);
     // Get problem and contest from DB to check it
     $problemDAO = ProblemsDAO::getByAlias($problemData["request"]["alias"]);
     $contestDAO = ContestsDAO::getByAlias($contestData["request"]["alias"]);
     $contestantsDAO = UsersDAO::search(new Users(array("username" => $contestant->getUsername())));
     $contestantDAO = $contestantsDAO[0];
     // Assert data
     $this->assertEquals($response["title"], $problemDAO->getTitle());
     $this->assertEquals($response["alias"], $problemDAO->getAlias());
     $this->assertEquals($response["validator"], $problemDAO->getValidator());
     $this->assertEquals($response["time_limit"], $problemDAO->getTimeLimit());
     $this->assertEquals($response["memory_limit"], $problemDAO->getMemoryLimit());
     $this->assertEquals($response["problemsetter"]['username'], $author->username);
     $this->assertEquals($response["problemsetter"]['name'], $author->name);
     $this->assertEquals($response["source"], $problemDAO->getSource());
     $this->assertContains("<h1>Entrada</h1>", $response["problem_statement"]);
     $this->assertEquals($response["order"], $problemDAO->getOrder());
     $this->assertEquals($response["score"], 0);
     // Default data
     $this->assertEquals(0, $problemDAO->getVisits());
     $this->assertEquals(0, $problemDAO->getSubmissions());
     $this->assertEquals(0, $problemDAO->getAccepted());
     $this->assertEquals(0, $problemDAO->getDifficulty());
     // Verify that we have an empty array of runs
     $this->assertEquals(0, count($response["runs"]));
     // Verify that problem was marked as Opened
     $problem_opened = ContestProblemOpenedDAO::getByPK($contestDAO->getContestId(), $problemDAO->getProblemId(), $contestantDAO->getUserId());
     $this->assertNotNull($problem_opened);
     // Verify open time
     $this->assertEquals(Utils::GetPhpUnixTimestamp(), Utils::GetPhpUnixTimestamp($problem_opened->getOpenTime()));
 }
 public function testUserNameCollision()
 {
     $salt = time();
     // Test users should not exist
     $this->assertNull(UsersDAO::FindByUsername('A' . $salt));
     $this->assertNull(UsersDAO::FindByUsername('A' . $salt . '1'));
     $this->assertNull(UsersDAO::FindByUsername('A' . $salt . '2'));
     // Create collision
     $c = new SessionController();
     $c->LoginViaGoogle('A' . $salt . '@isp1.com');
     $c->LoginViaGoogle('A' . $salt . '@isp2.com');
     $c->LoginViaGoogle('A' . $salt . '@isp3.com');
     $this->assertNotNull(UsersDAO::FindByUsername('A' . $salt));
     $this->assertNotNull(UsersDAO::FindByUsername('A' . $salt . '1'));
     $this->assertNotNull(UsersDAO::FindByUsername('A' . $salt . '2'));
 }
 public function testShouldRefuseMultipleRequestsInShortInterval()
 {
     $user_data = UserFactory::generateUser();
     $r = new Request(array('email' => $user_data['email']));
     $response = ResetController::apiCreate($r);
     try {
         ResetController::apiCreate($r);
     } catch (InvalidParameterException $expected) {
         $message = $expected->getMessage();
     }
     $this->assertEquals('passwordResetMinWait', $message);
     // time travel
     $reset_sent_at = ApiUtils::GetStringTime(time() - PASSWORD_RESET_MIN_WAIT - 1);
     $user = UsersDAO::FindByEmail($user_data['email']);
     $user->setResetSentAt($reset_sent_at);
     UsersDAO::save($user);
     ResetController::apiCreate($r);
 }
Example #6
0
 /**
  * Resolves the target user for the API. If a username is provided in
  * the request, then we use that one. Otherwise, we use currently logged-in
  * user.
  *
  * Request must be authenticated before this function is called.
  *
  * @param Request $r
  * @return Users
  * @throws InvalidDatabaseOperationException
  * @throws NotFoundException
  */
 protected static function resolveTargetUser(Request $r)
 {
     // By default use current user
     $user = $r['current_user'];
     if (!is_null($r['username'])) {
         Validators::isStringNonEmpty($r['username'], 'username');
         try {
             $user = UsersDAO::FindByUsername($r['username']);
             if (is_null($user)) {
                 throw new InvalidParameterException('parameterNotFound', 'Username');
             }
         } catch (ApiException $e) {
             throw $e;
         } catch (Exception $e) {
             throw new InvalidDatabaseOperationException($e);
         }
     }
     return $user;
 }
 /**
  * Gets the user that solved more problems during last month
  * 
  * @global type $conn
  * @param string (date) $firstDay
  * @return null|Users
  */
 public static function calculateCoderOfTheMonth($firstDay)
 {
     $endTime = $firstDay;
     $startTime = null;
     $lastMonth = intval(date('m')) - 1;
     if ($lastMonth === 0) {
         // First month of the year, we need to check into last month of last year.
         $lastYear = intval(date('Y')) - 1;
         $startTime = date($lastYear . '-12-01');
     } else {
         $startTime = date('Y-' . $lastMonth . '-01');
     }
     $sql = "\n\t\t\tSELECT\n\t\t\t\tusername, name, up.user_id, COUNT(ps.problem_id) ProblemsSolved, SUM(ROUND(100 / LOG(2, ps.accepted+1) , 0)) score\n\t\t\tFROM\n\t\t\t\t(\n\t\t\t\t\tSELECT DISTINCT\n\t\t\t\t\t\tr.user_id, r.problem_id\n\t\t\t\t\tFROM\n\t\t\t\t\t\tRuns r\n\t\t\t\t\tWHERE\n\t\t\t\t\t\tr.verdict = 'AC' AND r.test = 0 AND \n\t\t\t\t\t\tr.time >= ? AND \n\t\t\t\t\t\tr.time <= ?\n\t\t\t\t) AS up\n\t\t\tINNER JOIN\n\t\t\t\tProblems ps ON ps.problem_id = up.problem_id and ps.public = 1\n\t\t\tINNER JOIN\n\t\t\t\tUsers u ON u.user_id = up.user_id \n\t\t\tGROUP BY\n\t\t\t\tuser_id\n\t\t\tORDER BY\n\t\t\t\tscore DESC\n\t\t\tLIMIT 1\n\t\t";
     $val = array($startTime, $endTime);
     global $conn;
     $rs = $conn->GetRow($sql, $val);
     if (count($rs) == 0) {
         return NULL;
     }
     $totalCount = $rs['ProblemsSolved'];
     $user = UsersDAO::getByPK($rs['user_id']);
     $score = $rs['score'];
     return array("totalCount" => $totalCount, "user" => $user, "score" => $score);
 }
Example #8
0
 /**
  * Verifies a user and returns its DAO
  *
  * @param Users $user
  * @return type
  */
 public static function verifyUser(Users $user)
 {
     UserController::apiVerifyEmail(new Request(array('id' => $user->getVerificationId())));
     // Get user from db again to pick up verification changes
     return UsersDAO::FindByUsername($user->getUsername());
 }
}
// end of handle submit
// initialize page
$checksDAO = new ChecksDAO();
if (isset($check_id)) {
    $check_row = $checksDAO->getCheckByID($check_id);
    if (!$check_row) {
        // invalid check id
        $msg->addError('INVALID_CHECK_ID');
        require AC_INCLUDE_PATH . 'header.inc.php';
        $msg->printAll();
        require AC_INCLUDE_PATH . 'footer.inc.php';
        exit;
    }
    // get author name
    $usersDAO = new UsersDAO();
    $user_name = $usersDAO->getUserName($check_row['user_id']);
    if ($user_name != '') {
        $savant->assign('author', $user_name);
    }
    $check_pass_example_rows = $checkExamplesDAO->getByCheckIDAndType($check_id, AC_CHECK_EXAMPLE_PASS);
    $check_fail_example_rows = $checkExamplesDAO->getByCheckIDAndType($check_id, AC_CHECK_EXAMPLE_FAIL);
    $check_example_row['pass_example_desc'] = $check_pass_example_rows[0]['description'];
    $check_example_row['pass_example'] = $check_pass_example_rows[0]['content'];
    $check_example_row['fail_example_desc'] = $check_fail_example_rows[0]['description'];
    $check_example_row['fail_example'] = $check_fail_example_rows[0]['content'];
    $savant->assign('check_row', $check_row);
    $savant->assign('pre_rows', $checkPrerequisitesDAO->getPreChecksByCheckID($check_id));
    $savant->assign('next_rows', $testPassDAO->getNextChecksByCheckID($check_id));
    $savant->assign('guideline_rows', $guidelinesDAO->getEnabledGuidelinesByCheckID($check_id));
    $savant->assign('check_example_row', $check_example_row);
                }
            } else {
                if ($usersDAO->Update($_GET['id'], $_POST['user_group_id'], $_POST['login'], $_POST['email'], $_POST['first_name'], $_POST['last_name'], $_POST['status'])) {
                    $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
                    header('Location: index.php');
                    exit;
                }
            }
        }
    }
}
// end of handle submit
// initialize page
$userGroupsDAO = new UserGroupsDAO();
if (isset($_GET['id'])) {
    $usersDAO = new UsersDAO();
    $savant->assign('user_row', $usersDAO->getUserByID($_GET['id']));
    $savant->assign('show_password', false);
} else {
    $savant->assign('show_password', true);
}
/*****************************/
/* template starts down here */
global $onload;
$onload = 'document.form.login.focus();';
$savant->assign('show_user_group', true);
$savant->assign('show_status', true);
$savant->assign('all_user_groups', $userGroupsDAO->getAll());
$savant->assign('title', _AC('create_edit_user'));
$savant->assign('submit_button_text', _AC('save'));
$savant->assign('show_captcha', false);
Example #11
0
function optUsersTypes()
{
    $USER = UsersDAO::userLoged();
    $html = "";
    $read = new Read();
    $read->ExeRead('a.users_types', "WHERE a.status = 1 AND (a.id = :type OR :type = 1 OR a.permissoes LIKE CONCAT('%[',:type,']%')) ORDER BY a.id ASC", array('type' => $USER->getId()));
    foreach ($read->getResult() as $v) {
        $html .= "<option value='{$v['id']}'>{$v['title']}</option>";
    }
    return $html;
}
Example #12
0
/*                                                                      */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/
//// unset $_SESSION['user_id'] to avoid page redirecting in vitals.inc.php
//if (isset($_SESSION['user_id']))
//{
//	$_SESSION['current_user'] = $_SESSION['user_id'];
//	unset($_SESSION['user_id']);
//}
define('TR_INCLUDE_PATH', '../include/');
require TR_INCLUDE_PATH . 'vitals.inc.php';
require_once TR_INCLUDE_PATH . 'classes/DAO/UsersDAO.class.php';
require_once TR_INCLUDE_PATH . 'classes/DAO/OAuthServerTokensDAO.class.php';
$usersDAO = new UsersDAO();
$oAuthServerTokensDAO = new OAuthServerTokensDAO();
// Validation input parameters
if ($_REQUEST['oauth_token'] == '') {
    echo 'error=' . urlencode('Empty oauth token');
    exit;
}
$token_row = $oAuthServerTokensDAO->getByTokenAndType($_REQUEST['oauth_token'], 'request');
if (!is_array($token_row)) {
    echo 'error=' . urlencode('Invalid oauth token');
    exit;
}
// $_SESSION['token'] is used to encrypt the password from web form
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = sha1(mt_rand() . microtime(TRUE));
}
Example #13
0
/************************************************************************/
/* AChecker                                                             */
/************************************************************************/
/* Copyright (c) 2008 - 2011                                            */
/* Inclusive Design Institute                                           */
/*                                                                      */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/
// $Id$
define('AC_INCLUDE_PATH', 'include/');
require AC_INCLUDE_PATH . 'vitals.inc.php';
require_once AC_INCLUDE_PATH . 'classes/DAO/UsersDAO.class.php';
$usersDAO = new UsersDAO();
// $_SESSION['token'] is used to encrypt the password from web form
if (!isset($_SESSION['token'])) {
    $_SESSION['token'] = sha1(mt_rand() . microtime(TRUE));
}
if (isset($_POST['submit'])) {
    $user_id = $usersDAO->Validate($addslashes($_POST['form_login']), $addslashes($_POST['form_password_hidden']));
    if (!$user_id) {
        $msg->addError('INVALID_LOGIN');
    } else {
        if ($usersDAO->getStatus($user_id) == AC_STATUS_DISABLED) {
            $msg->addError('ACCOUNT_DISABLED');
        } else {
            if ($usersDAO->getStatus($user_id) == AC_STATUS_UNCONFIRMED) {
                $msg->addError('ACCOUNT_UNCONFIRMED');
            } else {
 /**
  * Test that we are able to submit a problem without testplan
  */
 public function testValidProblemNoTestplan()
 {
     // Get the problem data
     $problemData = ProblemsFactory::getRequest(OMEGAUP_RESOURCES_ROOT . 'triangulos.zip');
     $r = $problemData['request'];
     $problemAuthor = $problemData['author'];
     // Login user
     $r['auth_token'] = $this->login($problemAuthor);
     // Get File Uploader Mock and tell Omegaup API to use it
     FileHandler::SetFileUploader($this->createFileUploaderMock());
     // Call the API
     $response = ProblemController::apiCreate($r);
     // Validate
     // Verify response
     $this->assertEquals('ok', $response['status']);
     $this->assertEquals('cases/1.in', $response['uploaded_files'][0]);
     // Verify data in DB
     $problem_mask = new Problems();
     $problem_mask->setTitle($r['title']);
     $problems = ProblemsDAO::search($problem_mask);
     // Check that we only retreived 1 element
     $this->assertEquals(1, count($problems));
     $problem = $problems[0];
     // Verify contest was found
     $this->assertNotNull($problem);
     $this->assertNotNull($problem->getProblemId());
     // Verify DB data
     $this->assertEquals($r['title'], $problem->getTitle());
     $this->assertEquals(substr($r['title'], 0, 32), $problem->getAlias());
     $this->assertEquals($r['validator'], $problem->getValidator());
     $this->assertEquals($r['time_limit'], $problem->getTimeLimit());
     $this->assertEquals($r['memory_limit'], $problem->getMemoryLimit());
     $this->assertEquals($r['order'], $problem->getOrder());
     $this->assertEquals($r['source'], $problem->getSource());
     // Verify author username -> author id conversion
     $user = UsersDAO::getByPK($problem->getAuthorId());
     $this->assertEquals($user->getUsername(), $r['author_username']);
     // Verify problem contents were copied
     $targetpath = PROBLEMS_PATH . DIRECTORY_SEPARATOR . $problem->getAlias() . DIRECTORY_SEPARATOR;
     $this->assertFileExists($targetpath . 'cases');
     $this->assertFileExists($targetpath . 'statements' . DIRECTORY_SEPARATOR . 'es.html');
     // Default data
     $this->assertEquals(0, $problem->getVisits());
     $this->assertEquals(0, $problem->getSubmissions());
     $this->assertEquals(0, $problem->getAccepted());
     $this->assertEquals(0, $problem->getDifficulty());
 }
Example #15
0
 /**
  * Updates the main email of the current user
  *
  * @param Request $r
  */
 public static function apiUpdateMainEmail(Request $r)
 {
     self::authenticateRequest($r);
     Validators::isEmail($r['email'], 'email');
     try {
         // Update email
         $email = EmailsDAO::getByPK($r['current_user']->getMainEmailId());
         $email->setEmail($r['email']);
         EmailsDAO::save($email);
         // Add verification_id if not there
         if ($r['current_user']->getVerified() == '0') {
             self::$log->info('User not verified.');
             if ($r['current_user']->getVerificationId() == null) {
                 self::$log->info('User does not have verification id. Generating.');
                 try {
                     $r['current_user']->setVerificationId(self::randomString(50));
                     UsersDAO::save($r['current_user']);
                 } catch (Exception $e) {
                     // best effort, eat exception
                 }
             }
         }
     } catch (Exception $e) {
         // If duplicate in DB
         if (strpos($e->getMessage(), '1062') !== false) {
             throw new DuplicatedEntryInDatabaseException('mailInUse');
         } else {
             throw new InvalidDatabaseOperationException($e);
         }
     }
     // Delete profile cache
     Cache::deleteFromCache(Cache::USER_PROFILE, $r['current_user']->getUsername());
     // Send verification email
     $r['user'] = $r['current_user'];
     self::sendVerificationEmail($r);
     return array('status' => 'ok');
 }
    }
    if (isset($_GET['gg'])) {
        $guidelineGroupsDAO->Delete($_GET['gg']);
    }
    header('Location: create_edit_guideline.php?id=' . $gid);
    exit;
}
// interface display
if (!isset($gid)) {
    // create guideline
    $checksDAO = new ChecksDAO();
    $savant->assign('author', $_current_user->getUserName());
} else {
    // edit existing guideline
    $checksDAO = new ChecksDAO();
    $rows = $guidelinesDAO->getGuidelineByIDs($gid);
    // get author name
    $usersDAO = new UsersDAO();
    $user_name = $usersDAO->getUserName($rows[0]['user_id']);
    if (!$user_name) {
        $user_name = _AC('author_not_exist');
    }
    $savant->assign('gid', $gid);
    $savant->assign('row', $rows[0]);
    $savant->assign('author', $user_name);
    $savant->assign('checksDAO', $checksDAO);
}
if (isset($_current_user)) {
    $savant->assign('is_admin', $_current_user->isAdmin());
}
$savant->display('guideline/create_edit_guideline.tmpl.php');
 private static function validateUpdateRequest($r)
 {
     $user = UsersDAO::FindByEmail($r['email']);
     $reset_token = $r['reset_token'];
     $password = $r['password'];
     $password_confirmation = $r['password_confirmation'];
     if (is_null($user) || is_null($reset_token) || is_null($password) || is_null($password_confirmation)) {
         throw new InvalidParameterException('invalidParameters');
     }
     if ($user->reset_digest !== hash('sha1', $reset_token)) {
         throw new InvalidParameterException('invalidResetToken');
     }
     if ($password !== $password_confirmation) {
         throw new InvalidParameterException('passwordMismatch');
     }
     SecurityTools::testStrongPassword($password);
     $seconds = time() - strtotime($user->reset_sent_at);
     if ($seconds > PASSWORD_RESET_TIMEOUT) {
         throw new InvalidParameterException('passwordResetResetExpired');
     }
 }
 /**
  * Entry point for Problem runs API
  *
  * @param Request $r
  * @throws InvalidFilesystemOperationException
  * @throws InvalidDatabaseOperationException
  */
 public static function apiRuns(Request $r)
 {
     // Get user
     self::authenticateRequest($r);
     // Validate request
     self::validateRuns($r);
     $response = array();
     if ($r['show_all']) {
         if (!Authorization::CanEditProblem($r['current_user_id'], $r['problem'])) {
             throw new ForbiddenAccessException();
         }
         if (!is_null($r['username'])) {
             try {
                 $r['user'] = UsersDAO::FindByUsername($r['username']);
             } catch (Exception $e) {
                 throw new NotFoundException('userNotFound');
             }
         }
         try {
             $runs = RunsDAO::GetAllRuns(null, $r['status'], $r['verdict'], $r['problem']->problem_id, $r['language'], !is_null($r['user']) ? $r['user']->user_id : null, $r['offset'], $r['rowcount']);
             $result = array();
             foreach ($runs as $run) {
                 $run['time'] = (int) $run['time'];
                 $run['score'] = round((double) $run['score'], 4);
                 if ($run['contest_score'] != null) {
                     $run['contest_score'] = round((double) $run['contest_score'], 2);
                 }
                 array_push($result, $run);
             }
             $response['runs'] = $result;
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
     } else {
         $keyrun = new Runs(array('user_id' => $r['current_user_id'], 'problem_id' => $r['problem']->getProblemId()));
         // Get all the available runs
         try {
             $runs_array = RunsDAO::search($keyrun);
             // Create array of relevant columns for list of runs
             $relevant_columns = array('guid', 'language', 'status', 'verdict', 'runtime', 'penalty', 'memory', 'score', 'contest_score', 'time', 'submit_delay');
             // Add each filtered run to an array
             $response['runs'] = array();
             if (count($runs_array) >= 0) {
                 $runs_filtered_array = array();
                 foreach ($runs_array as $run) {
                     $filtered = $run->asFilteredArray($relevant_columns);
                     $filtered['time'] = strtotime($filtered['time']);
                     $filtered['username'] = $r['current_user']->username;
                     $filtered['alias'] = $r['problem']->alias;
                     array_push($response['runs'], $filtered);
                 }
             }
         } catch (Exception $e) {
             // Operation failed in the data layer
             throw new InvalidDatabaseOperationException($e);
         }
     }
     $response['status'] = 'ok';
     return $response;
 }
Example #19
0
             exit;
         }
     }
 } else {
     $msg->addError(array('EMPTY_FIELDS', _AC('password')));
     header('Location: change_email.php');
     exit;
 }
 // email check
 if ($_POST['email'] == '') {
     $msg->addError(array('EMPTY_FIELDS', _AC('email')));
 } else {
     if (!preg_match("/^[a-z0-9\\._-]+@+[a-z0-9\\._-]+\\.+[a-z]{2,6}\$/i", $_POST['email'])) {
         $msg->addError('EMAIL_INVALID');
     }
     $usersDAO = new UsersDAO();
     $row = $usersDAO->getUserByEmail($_POST['email']);
     if ($row['user_id'] > 0 && $row['user_id'] != $_SESSION['user_id']) {
         $msg->addError('EMAIL_EXISTS');
     }
 }
 if (!$msg->containsErrors()) {
     if (defined('AC_EMAIL_CONFIRMATION') && AC_EMAIL_CONFIRMATION) {
         //send confirmation email
         $row = $_current_user->getInfo();
         if ($row['email'] != $_POST['email']) {
             $code = substr(md5($_POST['email'] . $row['creation_date'] . $_SESSION['user_id']), 0, 10);
             $confirmation_link = AC_BASE_HREF . 'confirm.php?id=' . $_SESSION['user_id'] . SEP . 'e=' . urlencode($_POST['email']) . SEP . 'm=' . $code;
             /* send the email confirmation message: */
             require AC_INCLUDE_PATH . 'classes/phpmailer/acheckermailer.class.php';
             $mail = new ACheckerMailer();
Example #20
0
<?php

/************************************************************************/
/* AContent                                                             */
/************************************************************************/
/* Copyright (c) 2010                                                   */
/* Inclusive Design Institute                                           */
/*                                                                      */
/* This program is free software. You can redistribute it and/or        */
/* modify it under the terms of the GNU General Public License          */
/* as published by the Free Software Foundation.                        */
/************************************************************************/
define('TR_INCLUDE_PATH', '../include/');
include TR_INCLUDE_PATH . 'vitals.inc.php';
include_once TR_INCLUDE_PATH . 'classes/DAO/UsersDAO.class.php';
$usersDAO = new UsersDAO();
$ids = explode(',', $_REQUEST['id']);
if (isset($_POST['submit_no'])) {
    $msg->addFeedback('CANCELLED');
    header('Location: index.php');
    exit;
} else {
    if (isset($_POST['submit_yes'])) {
        foreach ($ids as $id) {
            $usersDAO->Delete($id);
        }
        $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
        header('Location: index.php');
        exit;
    }
}
 public function LoginViaFacebook()
 {
     //ok, the user does not have any auth token
     //if he wants to test facebook login
     //Facebook must send me the state=something
     //query, so i dont have to be testing
     //facebook sessions on every single petition
     //made from the front-end
     if (!isset($_GET['state'])) {
         return false;
     }
     //if that is not true, may still be logged with
     //facebook, lets test that
     $facebook = self::getFacebookInstance();
     // Get User ID
     $fb_user = $facebook->getUser();
     if ($fb_user == 0) {
         self::$log->info('FB session unavailable.');
         return false;
     }
     // We may or may not have this data based on whether the user is logged in.
     // If we have a $fb_user id here, it means we know the user is logged into
     // Facebook, but we don't know if the access token is valid. An access
     // token is invalid if the user logged out of Facebook.
     try {
         // Proceed knowing you have a logged in user who's authenticated.
         $fb_user_profile = $facebook->api('/me');
     } catch (FacebookApiException $e) {
         $fb_user = null;
         self::$log->error('FacebookException:' . $e);
         return false;
     }
     //ok we know the user is logged in,
     //lets look for his information on the database
     //if there is none, it means that its the first
     //time the user has been here, lets register his info
     self::$log->info('User is logged in via facebook !!');
     $results = UsersDAO::FindByEmail($fb_user_profile['email']);
     if (!is_null($results)) {
         //user has been here before with facebook!
         $vo_User = $results;
         self::$log->info('user has been here before with facebook!');
     } else {
         // The user has never been here before, let's register him
         // I have a problem with this:
         $username = self::getUniqueUsernameFromEmail($fb_user_profile['email']);
         // Even if the user gave us his/her email, we should not
         // just go ahead and assume its ok to share with the world
         // maybe we could do:
         // $username = str_replace(" ", "_", $fb_user_profile["name"] ),
         UserController::$permissionKey = uniqid();
         $r = new Request(array('name' => $fb_user_profile['name'], 'username' => $username, 'email' => $fb_user_profile['email'], 'facebook_user_id' => $fb_user_profile['id'], 'password' => null, 'permission_key' => UserController::$permissionKey, 'ignore_password' => true));
         try {
             $res = UserController::apiCreate($r);
         } catch (ApiException $e) {
             self::$log->error('Unable to login via Facebook ' . $e);
             return false;
         }
         $vo_User = UsersDAO::getByPK($res['user_id']);
     }
     //since we got here, this user does not have
     //any auth token, lets give him one
     //so we dont have to call facebook to see
     //if he is still logged in, and he can call
     //the api
     $this->RegisterSession($vo_User);
 }
Example #22
0
}
// end of parsing parameters
// initialize defaults for the ones not set or not set right but with default values
if ($output != 'html' && $output != 'rest') {
    $output = DEFAULT_WEB_SERVICE_OUTPUT;
}
// end of initialization
// validate parameters
if ($uri == '') {
    $errors[] = 'AC_ERROR_EMPTY_URI';
}
if ($web_service_id == '') {
    $errors[] = 'AC_ERROR_EMPTY_WEB_SERVICE_ID';
} else {
    // validate web service id
    $usersDAO = new UsersDAO();
    $user_row = $usersDAO->getUserByWebServiceID($web_service_id);
    if (!$user_row) {
        $errors[] = 'AC_ERROR_INVALID_WEB_SERVICE_ID';
    } else {
        $user_id = $user_row['user_id'];
    }
}
if (!is_array($decisions)) {
    $errors[] = 'AC_ERROR_SEQUENCEID_NOT_GIVEN';
}
// return errors
if (is_array($errors)) {
    if ($output == 'rest') {
        echo RESTWebServiceOutput::generateErrorRpt($errors);
    } else {
 /**
  * Details of a scoreboard. Returns a list with all contests that belong to
  * the given scoreboard_alias
  * 
  * @param Request $r
  */
 public static function apiDetails(Request $r)
 {
     self::validateGroupScoreboard($r);
     $response = array();
     // Fill contests
     $response["contests"] = array();
     $response["ranking"] = array();
     try {
         $groupScoreboardContestKey = new GroupsScoreboardsContests(array("group_scoreboard_id" => $r["scoreboard"]->group_scoreboard_id));
         $r["gscs"] = GroupsScoreboardsContestsDAO::search($groupScoreboardContestKey);
         $i = 0;
         $contest_params = array();
         foreach ($r["gscs"] as $gsc) {
             $contest = ContestsDAO::getByPK($gsc->contest_id);
             $response["contests"][$i] = $contest->asArray();
             $response["contests"][$i]["only_ac"] = $gsc->only_ac;
             $response["contests"][$i]["weight"] = $gsc->weight;
             // Fill contest params to pass to scoreboardMerge
             $contest_params[$contest->alias] = array("only_ac" => $gsc->only_ac == 0 ? false : true, "weight" => $gsc->weight);
             $i++;
         }
     } catch (ApiException $ex) {
         throw $ex;
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     $r["contest_params"] = $contest_params;
     // Fill details of this scoreboard
     $response["scoreboard"] = $r["scoreboard"]->asArray();
     // If we have contests, calculate merged&filtered scoreboard
     if (count($response["contests"]) > 0) {
         // Get merged scoreboard
         $r["contest_aliases"] = "";
         foreach ($response["contests"] as $contest) {
             $r["contest_aliases"] .= $contest["alias"] . ",";
         }
         $r["contest_aliases"] = rtrim($r["contest_aliases"], ",");
         try {
             $groupUsers = GroupsUsersDAO::search(new GroupsUsers(array("group_id" => $r["scoreboard"]->group_id)));
             $r["usernames_filter"] = "";
             foreach ($groupUsers as $groupUser) {
                 $user = UsersDAO::getByPK($groupUser->user_id);
                 $r["usernames_filter"] .= $user->username . ",";
             }
             $r["usernames_filter"] = rtrim($r["usernames_filter"], ",");
         } catch (Exception $ex) {
             throw new InvalidDatabaseOperationException($ex);
         }
         $mergedScoreboardResponse = ContestController::apiScoreboardMerge($r);
         $response["ranking"] = $mergedScoreboardResponse["ranking"];
     }
     $response["status"] = "ok";
     return $response;
 }
 /**
  * Admin can verify users only with username
  */
 public function testUsernameVerificationByAdmin()
 {
     // User to be verified
     $user = UserFactory::createUser(null, null, null, false);
     // Admin will verify $user
     $admin = UserFactory::createAdminUser();
     // Call api using admin
     $response = UserController::apiVerifyEmail(new Request(array('auth_token' => $this->login($admin), 'usernameOrEmail' => $user->getUsername())));
     // Get user from db again to pick up verification changes
     $userdb = UsersDAO::FindByUsername($user->getUsername());
     $this->assertEquals(1, $userdb->getVerified());
     $this->assertEquals('ok', $response['status']);
 }
Example #25
0
 /**
  * Details of a group (users in a group)
  * 
  * @param Request $r
  */
 public static function apiDetails(Request $r)
 {
     self::validateGroupAndOwner($r);
     $response = array();
     $response["group"] = array();
     $response["users"] = array();
     $response["scoreboards"] = array();
     try {
         $response["group"] = $r["group"]->asArray();
         $userGroups = GroupsUsersDAO::search(new GroupsUsers(array("group_id" => $r["group"]->group_id)));
         foreach ($userGroups as $userGroup) {
             $r["user"] = UsersDAO::getByPK($userGroup->user_id);
             $userProfile = UserController::getProfile($r);
             $response["users"][] = $userProfile;
         }
         $scoreboards = GroupsScoreboardsDAO::search(new GroupsScoreboards(array("group_id" => $r["group"]->group_id)));
         foreach ($scoreboards as $scoreboard) {
             $response["scoreboards"][] = $scoreboard->asArray();
         }
     } catch (Exception $ex) {
         throw new InvalidDatabaseOperationException($ex);
     }
     $response["status"] = "ok";
     return $response;
 }
Example #26
0
 /**
  * Logins with empty passwords in DB are disabled
  *
  * @expectedException LoginDisabledException
  */
 public function testLoginDisabled()
 {
     // User to be verified
     $user = UserFactory::createUser();
     // Force empty password
     $user->setPassword('');
     UsersDAO::save($user);
     $this->login($user);
 }
Example #27
0
 /**
  * Test update main email api
  */
 public function testUpdateMainEmail()
 {
     $user = UserFactory::createUser();
     $r = new Request(array("auth_token" => self::login($user), "email" => "*****@*****.**"));
     $response = UserController::apiUpdateMainEmail($r);
     // Check email in db
     $user_in_db = UsersDAO::FindByEmail("*****@*****.**");
     $this->assertEquals($user->getUserId(), $user_in_db->getUserId());
 }
Example #28
0
if (isset($_POST['submit'])) {
    /* password check: password is verified front end by javascript. here is to handle the errors from javascript */
    if ($_POST['password_error'] != "") {
        $pwd_errors = explode(",", $_POST['password_error']);
        foreach ($pwd_errors as $pwd_error) {
            if ($pwd_error == "missing_password") {
                $missing_fields[] = _AT('password');
            } else {
                $msg->addError($pwd_error);
            }
        }
    }
    if (!$msg->containsErrors()) {
        // insert into the db.
        $password = $addslashes($_POST['form_password_hidden']);
        $usersDAO = new UsersDAO();
        if (!$usersDAO->setPassword($_GET['id'], $password)) {
            require TR_INCLUDE_PATH . 'header.inc.php';
            $msg->printErrors('DB_NOT_UPDATED');
            require TR_INCLUDE_PATH . 'footer.inc.php';
            exit;
        }
        // send email to user
        $user_row = $usersDAO->getUserByID($_GET['id']);
        $tmp_message = _AT('password_change_msg') . "\n\n";
        $tmp_message .= _AT('web_site') . ' : ' . TR_BASE_HREF . "\n";
        $tmp_message .= _AT('login_name') . ' : ' . $user_row['login'] . "\n";
        require TR_INCLUDE_PATH . 'classes/phpmailer/transformablemailer.class.php';
        $mail = new TransformableMailer();
        $mail->From = $_config['contact_email'];
        $mail->AddAddress($user_row['email']);
Example #29
0
	$glossary_manifest_xml = $ims_template_xml['glossary'];
} else {
	$glossary_manifest_xml = '';
}
*/
ob_start();
print_organizations($top_content_parent_id, $content, 0, '', array(), $toc_html);
//Exoprt Forum:
print_resources_forum();
$organizations_str = ob_get_contents();
ob_end_clean();
// end of modified by Cindy Qi Li on Jan 12, 2010
/* append the Organizations and Resources to the imsmanifest */
$imsmanifest_xml .= str_replace(array('{ORGANIZATIONS}', '{GLOSSARY}', '{RESOURCES}', '{TEST_ITEMS}', '{COURSE_TITLE}'), array($organizations_str, $glossary_manifest_xml, $resources, $test_xml_items, $ims_course_title), $ims_template_xml['final']);
// generate the vcard for the instructor/author
$usersDAO = new UsersDAO();
$row = $usersDAO->getUserByID($instructor_id);
//$sql = "SELECT first_name, last_name, email, website, login, phone FROM ".TABLE_PREFIX."members WHERE member_id=$instructor_id";
//$result = mysql_query($sql, $db);
$vcard = new vCard();
if (isset($row)) {
    $vcard->setName($row['last_name'], $row['first_name'], $row['login']);
    $vcard->setEmail($row['email']);
    $vcard->setNote('Originated from an AContent at ' . TR_BASE_HREF . '. See ATutor.ca for additional information.');
    $vcard->setURL($row['website']);
    $imsmanifest_xml = str_replace('{VCARD}', $vcard->getVCard(), $imsmanifest_xml);
} else {
    $imsmanifest_xml = str_replace('{VCARD}', '', $imsmanifest_xml);
}
/* save the imsmanifest.xml file */
$zipfile->add_file($imsmanifest_xml, 'imsmanifest.xml');
Example #30
0
 /**
  * Returns ALL users participating in a contest
  *
  * @param Request $r
  * @return array
  * @throws InvalidDatabaseOperationException
  */
 public static function apiUsers(Request $r)
 {
     // Authenticate request
     self::authenticateRequest($r);
     Validators::isStringNonEmpty($r["contest_alias"], "contest_alias");
     try {
         $contest = ContestsDAO::getByAlias($r["contest_alias"]);
     } catch (Exception $e) {
         throw new InvalidDatabaseOperationException($e);
     }
     if (!Authorization::IsContestAdmin($r["current_user_id"], $contest)) {
         throw new ForbiddenAccessException();
     }
     // Get users from DB
     $contest_user_key = new ContestsUsers();
     $contest_user_key->setContestId($contest->getContestId());
     try {
         $db_results = ContestsUsersDAO::search($contest_user_key);
     } catch (Exception $e) {
         // Operation failed in the data layer
         throw new InvalidDatabaseOperationException($e);
     }
     $users = array();
     // Add all users to an array
     foreach ($db_results as $result) {
         $user_id = $result->getUserId();
         $user = UsersDAO::getByPK($user_id);
         $users[] = array("user_id" => $user_id, "username" => $user->getUsername(), 'access_time' => $result->access_time, 'country' => $user->getCountryId());
     }
     $response = array();
     $response["users"] = $users;
     $response["status"] = "ok";
     return $response;
 }