public function cacheTestAction()
 {
     $classHelper = new ClassHelper();
     $studentIds = $classHelper->allStudents();
     //$studentIds = ["John Logie Baird"];
     // Calculate an overall mastery score for these units, as well as an average for concepts over the past 2 weeks
     $units = ["1", "2", "3", "4", "recent"];
     // Go through each student and calculate unit mastery scores
     foreach ($studentIds as $studentId) {
         // See if we've already scored mastery scores for this student on the current day (this script just runs multiple times, until a better method to get around 60 second execution time limit is devised)
         $lastHistory = StudentMasteryHistory::findFirst(["email = '{$studentId}'", "order" => "time_stored DESC"]);
         if (!$lastHistory) {
         }
         echo "last history is false";
         if (gettype($lastHistory)) {
             if (date("Y-m-d") == date("Y-m-d", strtotime($lastHistory->time_stored))) {
                 echo "    History already saved today for {$studentId}\n";
                 continue;
             }
         }
     }
 }
 public function dailyMasteryAction()
 {
     $config = $this->getDI()->getShared('config');
     if (!isset($_GET["p"])) {
         die("No history saver password provided.");
     }
     if ($_GET["p"] != $config->historySaverPassword) {
         die("Invalid history saver password provided.");
     }
     ini_set('max_execution_time', 300);
     set_time_limit(300);
     // We want to time this
     $startTime = microtime(true);
     $debug = false;
     $classHelper = new ClassHelper();
     $masteryHelper = new MasteryHelper();
     $studentIds = $classHelper->allStudents();
     //$studentIds = ["John Logie Baird"];
     // Calculate an overall mastery score for these units, as well as an average for concepts over the past 2 weeks
     $units = ["1", "2", "3", "4", "recent"];
     // Go through each student and calculate unit mastery scores
     foreach ($studentIds as $studentId) {
         // See if we've already scored mastery scores for this student on the current day (this script just runs multiple times, until a better method to get around 60 second execution time limit is devised)
         $studentId = str_replace("'", "", $studentId);
         $lastHistory = StudentMasteryHistory::findFirst(["email = '{$studentId}'", "order" => "time_stored DESC"]);
         if (date("Y-m-d") == date("Y-m-d", strtotime($lastHistory->time_stored))) {
             echo "    History already saved today for {$studentId}\n";
             continue;
         }
         $scores = [];
         foreach ($units as $unit) {
             // We fetch recent concepts differently from the rest of the units
             if ($unit == "recent") {
                 $concepts = MappingHelper::conceptsWithin2Weeks();
             } else {
                 $concepts = MappingHelper::conceptsInUnit($unit);
             }
             $unitScore = 0;
             foreach ($concepts as $c) {
                 $unitScore += $masteryHelper::calculateConceptMasteryScore($studentId, $c, $debug);
             }
             $unitScore = $unitScore / count($concepts);
             $scores[$unit] = $unitScore;
         }
         if ($debug) {
             echo "Scores for student {$studentId} \n";
             print_r($scores);
         }
         $history = new StudentMasteryHistory();
         $history->email = $studentId;
         $history->unit1 = $scores["1"];
         $history->unit2 = $scores["2"];
         $history->unit3 = $scores["3"];
         $history->unit4 = $scores["4"];
         $history->recent_average = $scores["recent"];
         if ($history->create() == false) {
             echo "*** Error saving mastery history for {$studentId}\n";
         } else {
             echo "    Successfully saved history for {$studentId}\n";
         }
     }
     // Print total time taken
     $endTime = microtime(true);
     echo "Execution time: " . ($endTime - $startTime) . " seconds\n";
 }
 public function studentsAction($start, $finish)
 {
     $this->view->disable();
     // Get our context (this takes care of starting the session, too)
     $context = $this->getDI()->getShared('ltiContext');
     if (!$context->valid) {
         echo '[{"error":"Invalid lti context"}]';
         return;
     }
     $timeArray[] = 280;
     $classHelper = new ClassHelper();
     $masteryHelper = new MasteryHelper();
     $statementHelper = new StatementHelper();
     $recent_concepts = MappingHelper::conceptsWithin2Weeks();
     $students = $classHelper->allStudents();
     //		$students = ["John Logie Baird","me"];
     $studentInfo = [];
     $maxCount = 0;
     //count($students)
     for ($i = $start; $i < $finish; $i++) {
         $startTime = microtime(true);
         $studentAverages = StudentMasteryHistory::findFirst(["conditions" => "email = ?1", "bind" => array(1 => $students[$i]), "order" => 'time_stored DESC']);
         // For second parameter of what to query, see http://php.net/manual/en/mongocollection.find.php
         $visStatements = $statementHelper->getStatements("visualization", ['statement.actor.name' => $students[$i]], ['statement.object.id' => true]);
         $hints = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/showed-hint'], ['statement.object.id' => true]);
         $showAnswer = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/showed-answer'], ['statement.object.id' => true]);
         $questionsAnswered = $statementHelper->getStatements("openassessments", ['statement.actor.name' => $students[$i], 'statement.verb.id' => 'http://adlnet.gov/expapi/verbs/answered'], ['statement.object.id' => true, 'statement.context.extensions' => true]);
         $hintsShowed = $hints["cursor"]->count();
         $answersShowed = $showAnswer["cursor"]->count();
         $high = 0;
         $medium = 0;
         $low = 0;
         $attempts = $questionsAnswered["cursor"]->count();
         $correct = 0;
         foreach ($questionsAnswered["cursor"] as $confidenceCheck) {
             $confidenceCheck = StatementHelper::replaceHtmlEntity($confidenceCheck, true);
             if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/correct'] == true) {
                 $correct++;
             }
             if (array_key_exists('http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level', $confidenceCheck['statement']['context']['extensions'])) {
                 if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "high") {
                     $high++;
                 }
                 if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "medium") {
                     $medium++;
                 }
                 if ($confidenceCheck['statement']['context']['extensions']['http://byuopenanalytics.byu.edu/expapi/extensions/confidence_level'] == "low") {
                     $low++;
                 }
             }
         }
         $commonConfidence = max($high, $medium, $low);
         if ($commonConfidence == $high) {
             $medianConfidence = "High";
         } else {
             if ($commonConfidence == $medium) {
                 $medianConfidence = "Medium";
             } else {
                 $medianConfidence = "Low";
             }
         }
         $count = $visStatements["cursor"]->count();
         $escapedString = str_replace("'", "", $students[$i]);
         //	echo $escapedString;
         $lastHistory = VideoHistory::findFirst(["student = '{$escapedString}'", "order" => "time_stored DESC"]);
         $vidPercent = $lastHistory->vidpercentage;
         if ($count > $maxCount && $students[$i] != 'John Logie Baird') {
             $maxCount = $count;
         }
         if (!is_object($studentAverages)) {
             $newStudent = ["name" => $students[$i], "average" => 0, "count" => $count, "vPercentage" => $vidPercent, "correct" => $correct, "attempts" => $attempts, "hintsShowed" => $hintsShowed, "answersShowed" => $answersShowed, "confidence" => $medianConfidence];
         } else {
             $newStudent = ["name" => $studentAverages->email, "average" => $studentAverages->recent_average, "count" => $count, "vPercentage" => $vidPercent, "correct" => $correct, "attempts" => $attempts, "hintsShowed" => $hintsShowed, "answersShowed" => $answersShowed, "confidence" => $medianConfidence];
         }
         if ($students[$i] != 'John Logie Baird' && $students[$i] != 'Bob Bodily') {
             $studentInfo[] = $newStudent;
         }
         $endTime = microtime(true);
         $timeArray[$i] = $endTime - $startTime;
         //echo "Execution time: " . ($endTime - $startTime) ." seconds\n";
     }
     $avg = 0;
     foreach ($timeArray as $time) {
         $avg += $time;
     }
     $avg = $avg / 280;
     //	echo "Average Time: ".$avg." seconds\n";
     //Sorts the students by their recent mastery average, from highest to lowest.
     usort($studentInfo, function ($student1, $student2) {
         return $student1["average"] <= $student2["average"];
     });
     $firstRow = ["max" => $maxCount];
     array_unshift($studentInfo, $firstRow);
     echo json_encode($studentInfo);
 }
 public function time_graphAction($weeks = "all", $debug = false)
 {
     $this->view->disable();
     // Get our context (this takes care of starting the session, too)
     $context = $this->getDI()->getShared('ltiContext');
     if (!$context->valid) {
         echo '[{"error":"Invalid lti context"}]';
         return;
     }
     $email = $context->getUserName();
     // Fetch skill history items for the current student
     $historyResults = StudentMasteryHistory::find(["email = '{$email}'", "order" => 'time_stored DESC']);
     $historyPoints = [];
     foreach ($historyResults as $day) {
         // Scores are saved at 3am, so they actually correspond to the previous day
         $formattedDate = date('M j', strtotime('-1 day', strtotime($day->time_stored)));
         $historyPoints[] = [$formattedDate, round($day->unit1 * 100) / 100, round($day->unit2 * 100) / 100, round($day->unit3 * 100) / 100, round($day->unit4 * 100) / 100];
         //$historyPoints []= [$formattedDate, rand(0,100) / 10, rand(0,100) / 10];
     }
     // In case it gets saved multiple times, eliminate duplicates
     $historyPoints = array_unique($historyPoints, SORT_REGULAR);
     // Get the amount of data requested:
     switch ($weeks) {
         case "2":
             $historyPoints = array_slice($historyPoints, 0, 14);
             break;
         case "4":
             $historyPoints = array_slice($historyPoints, 0, 28);
             break;
         default:
             break;
     }
     //	echo json_encode($historyPoints);
     // Put it in correct order
     $historyPoints = array_reverse($historyPoints);
     //print_r($historyPoints);
     if ($debug) {
         print_r($historyPoints);
     }
     // Output data as csv so that we only have to send header information once
     if (!$debug) {
         header("Content-Type: text/csv");
     }
     $output = fopen("php://output", "w");
     // Header row
     fputcsv($output, ["date", "Unit 1", "Unit 2", "Unit 3", "Unit 4"]);
     foreach ($historyPoints as $row) {
         fputcsv($output, $row);
         // here you can change delimiter/enclosure
     }
     fclose($output);
 }