You are here

function quiz_start_actions in Quiz 5

Same name and namespace in other branches
  1. 5.2 quiz.module \quiz_start_actions()
  2. 6.6 quiz.module \quiz_start_actions()
  3. 6.2 quiz.module \quiz_start_actions()
  4. 6.3 quiz.module \quiz_start_actions()
  5. 6.5 quiz.module \quiz_start_actions()

Actions to take place at the start of a quiz

Parameters

$uid: User ID

$nid: Quiz node ID

Return value

integer Returns quiz_result rid, or false if there is an error.

1 call to quiz_start_actions()
quiz_take_quiz in ./quiz.module
Handles quiz taking

File

./quiz.module, line 740
Quiz Module

Code

function quiz_start_actions($uid, $nid) {

  // get the quiz node
  $quiz = node_load($nid);

  // make sure this is available
  if (!$quiz->quiz_always == 1) {

    // compare current gm time to open and close dates (which should still be in gm time)
    if (gmmktime() >= $quiz->quiz_close || gmmktime() < $quiz->quiz_open) {
      drupal_set_message(t('This @quiz is not currently available.', array(
        '@quiz' => QUIZ_NAME,
      )), 'status');
      if (!user_access('create quiz')) {
        return FALSE;
      }
    }
  }

  // get the results
  global $user;
  $results = _quiz_get_results($quiz->nid, $user->uid);

  // Check to see if the user alredy passed this quiz
  // but only perform this check if it is a registered user
  if ($user->uid) {
    $passed = FALSE;
    foreach ($results as $next) {
      $score = quiz_calculate_score($next['rid']);
      if ($score['percentage_score'] >= $quiz->pass_rate) {
        $passed = TRUE;
        break;
      }
    }
    if ($passed == TRUE) {
      drupal_set_message(t('You have already passed this @quiz.', array(
        '@quiz' => QUIZ_NAME,
      )), 'status');

      // Allow quiz creators to test their quizzes
      if (!user_access('create quiz')) {
        return FALSE;
      }
    }
  }

  // Validate number of takes if we have a registered user
  if ($user->uid && $quiz->takes != 0) {

    //$result = db_result(db_query('SELECT COUNT(rid) AS count FROM {quiz_result} WHERE uid = %d AND quiz_nid = %d', $uid, $nid));
    $times = count($results);
    if ($times >= $quiz->takes) {
      drupal_set_message(t('You have already taken this @quiz %d times.', array(
        '@quiz' => QUIZ_NAME,
        '%d' => $times,
      )), 'status');

      // Allow quiz creators to test their quizzes
      if (!user_access('create quiz')) {
        return FALSE;
      }
    }
  }

  // Insert quiz_results record
  $rid = db_next_id('{quiz_results}_rid');
  $now = time();
  $result = db_query("INSERT INTO {quiz_result} (rid, quiz_nid, uid, time_start) VALUES (%d, %d, %d, %d)", $rid, $nid, $uid, $now);
  if ($result) {
    return $rid;
  }
  else {
    drupal_set_message(t('There was a problem starting the @quiz. Please try again later.', array(
      '@quiz' => QUIZ_NAME,
    ), 'error'));
    return FALSE;
  }
}