From 35f668444f68db1b489db2875f3d7d1114848151 Mon Sep 17 00:00:00 2001
From: David Paul <dpaul4@une.edu.au>
Date: Tue, 22 Mar 2022 15:53:17 +1100
Subject: [PATCH] Upgrade to newer versions of libraries and switch to Monaco
 code editor

---
 .gitignore            |   5 +-
 LICENSE               |   2 +-
 automarker_client.py  |  54 ++-
 automarker_server.py  |   4 +
 bower.json            |  28 --
 exercise.py           |  48 ++-
 grade.php             |   2 +-
 index.php             | 172 +++++----
 lti_util/LICENSE      |  23 ++
 lti_util/OAuth.php    | 809 ++++++++++++++++++++++++++++++++++++++
 lti_util/lti_util.php | 880 ++++++++++++++++++++++++++++++++++++++++++
 package.json          |  12 +
 readme.md             |   4 +-
 13 files changed, 1912 insertions(+), 131 deletions(-)
 delete mode 100644 bower.json
 create mode 100644 lti_util/LICENSE
 create mode 100644 lti_util/OAuth.php
 create mode 100644 lti_util/lti_util.php
 create mode 100644 package.json

diff --git a/.gitignore b/.gitignore
index 933c8f9..387ba84 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,4 +25,7 @@ Network Trash Folder
 Temporary Items
 .apdisk
 
-bower_components/*
+node_modules/*
+package-lock.json
+
+__pycache__/*
diff --git a/LICENSE b/LICENSE
index 7485c99..337f038 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,6 +1,6 @@
 MIT License
 
-Copyright (c) 2016 David John Paul
+Copyright (c) 2016-2022 David John Paul
 
 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
diff --git a/automarker_client.py b/automarker_client.py
index 6a03287..1b62d02 100644
--- a/automarker_client.py
+++ b/automarker_client.py
@@ -3,10 +3,13 @@ from browser import alert
 from browser import document
 from browser import html
 from browser import window
+
+
 jq = window.jQuery.noConflict(True)
 window.jq = jq;
 editor = window.editor
 
+
 def echo_prompt(prompt = ""):
     """Function to make prompt to input appear properly"""
     print(prompt, end = "")
@@ -14,17 +17,27 @@ def echo_prompt(prompt = ""):
     print(value, end="\n")
     return value
 
+
+def fake_input(prompt = ""):
+    """Function that avoids input by directly reading standard input, and also echos the prompt"""
+    print(prompt, end = "")
+    value = sys.stdin.readline()
+    print(value, end = "\n")
+    return value
+
+
 class Output:
     """Writes output to #output"""
     def write(self, *args):
         for arg in args:
             jq("#output").val(jq("#output").val() + arg)
 
+
 def display_exercise(exercise):
     """Displays the given exercise"""
     window.exercise.html = exercise.title
     window.instructions.html = exercise.instructions
-    window.editor.setValue(exercise.code, -1)
+    window.editor.setValue(exercise.code)
     window.tests.clear()
     for test_id in range(len(exercise.tests)):
         test = exercise.tests[test_id]
@@ -35,8 +48,9 @@ def display_exercise(exercise):
         list_element.bind("click", show_test)
         list_element.bind("dblclick", run_test)
         window.tests <= list_element
-    jq("#output-row").addClass("hidden")
-    jq("#test-row").addClass("hidden")
+    jq("#output-row").addClass("visually-hidden")
+    jq("#test-row").addClass("visually-hidden")
+
 
 def update_tests(remove_active = False):
     """Checks if all tests have passed, removing the active class if requested"""
@@ -56,32 +70,38 @@ def update_tests(remove_active = False):
     if all_passed:
         jq("#grade").removeClass("disabled")
 
+
 def display_test(id):
     """Displays the test with the given id"""
     update_tests(True)
-    jq("#output-row").addClass("hidden")
-    jq("#test-row").removeClass("hidden")
+    jq("#output-row").addClass("visually-hidden")
+    jq("#test-row").removeClass("visually-hidden")
     jq("#test_%d" % id).addClass("active")
     test = exercise.tests[id]
     jq("#expected").val(test.expected_output)
     jq("#actual").val(test.actual_output)
     jq("#input").val(test.input)
+    window.updateDiff()
+
 
 def show_test(ev):
     """Displays the test that was selected"""
     id = int(ev.target.id[len("test_"):])
     display_test(id)
 
+
 def run_test(ev):
     """Runs the test that was selected"""
     id = int(ev.target.id[len("test_"):])
     execute_test(exercise.tests[id])
     display_test(id)
 
+
 def get_code():
     """Gets the code currently in the editor"""
     return window.editor.getValue()
 
+
 def display_checks(code):
     """Displays alerts for any check that fails - returns True if all checks pass, False otherwise"""
     for check in exercise.checks:
@@ -91,54 +111,62 @@ def display_checks(code):
             return False
     return True
 
+
 def execute_test(test):
     """Runs the code to complete a test"""
     code = get_code()
     if not display_checks(code):
         return
-    test.run(code, echo_prompt)
+    test.run(code, fake_input)
     update_tests()
 
+
 def execute_run(*args):
     """Runs the code for the user to interact with"""
-    jq("#test-row").addClass("hidden")
-    jq("#output-row").removeClass("hidden")
+    jq("#test-row").addClass("visually-hidden")
+    jq("#output-row").removeClass("visually-hidden")
     jq("#output").val("")
     code = get_code()
     execute(code, output, output, sys.stdin, echo_prompt)
 
+
 def execute_tests(*args):
     """Executes each test for the exercise"""
     code = get_code()
     if not display_checks(code):
         return
-    exercise.run(code, echo_prompt)
+    exercise.run(code, fake_input)
     display_test(0)
 
+
 def grade_code():
     if jq("#grade").hasClass("disabled"):
         alert("Run all tests successfully to allow grade upload")
     else:
         window.submitGrade();
 
+
 def code_change(*args):
     """Handles any time the code changes - test results become invalid"""
     jq("#warning").text("")
-    jq("#output-row").addClass("hidden")
-    jq("#test-row").addClass("hidden")
+    jq("#output-row").addClass("visually-hidden")
+    jq("#test-row").addClass("visually-hidden")
     for test in exercise.tests:
         test.actual_output = ""
     update_tests(True)
 
+
+
+
 output = Output()
 
-exercise = get_exercise(window.exercise_id)
 window.exercise.html = "No Exercise Specified"
 window.instructions.html = "No exercise was specified, or the exercise is unavailable. Please contact your instructor."
+exercise = get_exercise(window.exercise_id)
 display_exercise(exercise)
 
 document["run"].bind("click", execute_run)
 document["test-all"].bind("click", execute_tests)
 document["grade"].bind("click", grade_code)
 
-editor.on("input", code_change)
+editor.onDidChangeModelContent(code_change)
diff --git a/automarker_server.py b/automarker_server.py
index abd86fc..8ed77a4 100644
--- a/automarker_server.py
+++ b/automarker_server.py
@@ -2,6 +2,7 @@ from exercise import *
 from exercises import *
 import sys
 
+
 def get_exercise(id = 0):
     """Loads the exercise to be completed"""
     try:
@@ -13,14 +14,17 @@ def get_exercise(id = 0):
     
     return exercises[id]
 
+
 original_input = input
 
+
 def output_input(prompt = ""):
     """A function to output the value that is input before it is returned."""
     value = original_input(prompt)
     print(value)
     return value
 
+
 if __name__ == "__main__":
     exercise_id = sys.argv[-2]
     exercise = get_exercise(exercise_id)
diff --git a/bower.json b/bower.json
deleted file mode 100644
index aea232e..0000000
--- a/bower.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
-  "name": "python-automarker",
-  "authors": [
-    "David Paul <david@davidjohnpaul.com>"
-  ],
-  "description": "A Python 3 AutoMarker",
-  "main": "",
-  "keywords": [
-    "python",
-    "automarker"
-  ],
-  "license": "MIT",
-  "homepage": "https://bitbucket.org/davidjohnpaul/automarker",
-  "ignore": [
-    "**/.*",
-    "node_modules",
-    "bower_components",
-    "test",
-    "tests"
-  ],
-  "dependencies": {
-    "bootstrap": "^3.3.6",
-    "ace": "git://github.com/ajaxorg/ace-builds.git#^1.2.3",
-    "pythonauto": "https://github.com/csev/pythonauto.git",
-    "html5shiv": "^3.7.3",
-    "Brython-3.3.0.tar": "https://github.com/brython-dev/brython/releases/download/3.3.0/Brython-3.3.0.tar.gz"
-  }
-}
diff --git a/exercise.py b/exercise.py
index d869d46..1973931 100644
--- a/exercise.py
+++ b/exercise.py
@@ -5,8 +5,9 @@ import traceback
 # Pattern to remove Traceback from before an exec call
 error_pattern = ".*?\$exec_\d+.*? "
 regex_error = re.compile(error_pattern, re.DOTALL)
-  
-def execute(code, stdout = sys.stdout, stderr = sys.stderr, stdin = sys.stdin, input = input):
+
+
+def execute(code, stdout = sys.stdout, stderr = sys.stderr, stdin = sys.stdin, new_input = input):
     """Executes the given code, with standard output and standard error going to the given values"""
     old_stdout = sys.stdout
     old_stderr = sys.stderr
@@ -18,35 +19,38 @@ def execute(code, stdout = sys.stdout, stderr = sys.stderr, stdin = sys.stdin, i
 
     try:
         available_vars = {}
-        available_vars["input"] = input
+        available_vars["input"] = new_input
         exec(code, available_vars)
         return True
     except Exception as exc:
-        msg = traceback.format_exc()
-        msg = regex_error.sub("", msg, 1)
-        print(msg)
+        exc.filename = "automarker.py"
+        traceback.print_exception(exc)
         return False
     finally:
         sys.stdout = old_stdout
         sys.stderr = old_stderr
         sys.stdin = old_stdin
 
+
 class Test:
     """A test to run over the given code"""
 
-    def __init__(self, name, expected_output = "", input = ""):
+
+    def __init__(self, name, expected_output = "", test_input = ""):
         """Gives the test the give name, expected output, and input that it will provide when run"""
         self.name = name
         self.expected_output = expected_output
         self.actual_output = ""
-        self.input = input
+        self.input = test_input
         self.remaining_input = ""
 
+
     def write(self, *args):
         """Writes the output to the test object"""
         for arg in args:
             self.actual_output += arg
 
+
     def read(self, *args):
         """Reads the input from the test object"""
         if len(self.remaining_input) <= 0:
@@ -55,32 +59,38 @@ class Test:
         self.remaining_input = self.remaining_input[1:]
         return ret_val
 
+
     def readline(self, *args):
         """Reads the input from the test object"""
         remaining = self.remaining_input.partition("\n")
         self.remaining_input = remaining[2]
         return remaining[0]
 
+
     def close(self, *args):
         """Allow Test to be stdin"""
         pass
 
-    def run(self, code, input = input):
+
+    def run(self, code, new_input = input):
         """Executes this test, returning True if the test passes (False otherwise)"""
         self.remaining_input = self.input
         self.actual_output = ""
-        execute(code, self, self, self, input)
+        execute(code, self, self, self, new_input)
         return self.actual_output == self.expected_output
 
+
 class Check:
     """Performs a check on the code"""
-    
+
+
     def __init__(self, text, regex, ensure_no_match = False):
         """Sets the text and the pattern to match"""
         self.text = text
         self.regex = re.compile(regex)
         self.ensure_no_match = ensure_no_match
-    
+
+
     def check(self, code):
         """Ensures this check succeeds"""
         match = self.regex.search(code)
@@ -88,9 +98,11 @@ class Check:
             return self.ensure_no_match
         return not self.ensure_no_match
 
+
 class Exercise:
     """The exercise to be completed"""
 
+
     def __init__(self, title, instructions = "", code = "", tests = [], checks = []):
         """Sets the title, instructions, initial code, tests, and checks to be performed to complete this exercise"""
         self.title = title
@@ -98,6 +110,8 @@ class Exercise:
         self.code = code
         self.tests = tests
         self.checks = checks
+        self.filename = "Exercise"
+
 
     def run_checks(self, code):
         """Ensures all checks pass on the given code, returning True if all checks succeed (False otherwise)"""
@@ -106,13 +120,15 @@ class Exercise:
             all_succeeded = check.check(code) and all_succeeded
         return all_succeeded
 
-    def run_tests(self, code, input = input):
+
+    def run_tests(self, code, new_input = input):
         """Runs all tests in this exercise, returning True if all succeed (False otherwise)"""
         all_succeeded = True
         for test in self.tests:
-            all_succeeded = test.run(code, input) and all_succeeded
+            all_succeeded = test.run(code, new_input) and all_succeeded
         return all_succeeded
 
-    def run(self, code, input = input):
+
+    def run(self, code, new_input = input):
         """Runs all checks and, if they succeed, all tests, returning True if all checks and tests succeed (False otherwise)"""
-        return self.run_checks(code) and self.run_tests(code, input)
+        return self.run_checks(code) and self.run_tests(code, new_input)
diff --git a/grade.php b/grade.php
index e19381d..2e35689 100644
--- a/grade.php
+++ b/grade.php
@@ -1,6 +1,6 @@
 <?php
 # Based on https://github.com/csev/pythonauto/blob/master/grade.php
-require_once('bower_components/pythonauto/util/lti_util.php');
+require_once('lti_util/lti_util.php');
 session_start();
 
 if (isset($_REQUEST["exercise"]) && preg_match("/^\d+$/", $_REQUEST["exercise"])) {
diff --git a/index.php b/index.php
index 39e8bd0..2229928 100644
--- a/index.php
+++ b/index.php
@@ -1,104 +1,128 @@
 <?php
 session_start();
-require_once("bower_components/pythonauto/util/lti_util.php");
+require_once("lti_util/lti_util.php");
 ?>
 <!DOCTYPE html>
 <html>
   <head>
     <title>Python Automarker</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <link href="bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
-    <link href="css/automarker.css" rel="stylesheet" media="screen">
+    <link href="node_modules/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen" />
+    <link href="css/automarker.css" rel="stylesheet" media="screen" />
     <!--[if lt IE 9]>
-      <script src="bower_components/html5shiv/dist/html5shiv-printshiv.min.js"></script>
+      <script src="node_modules/html5shiv/dist/html5shiv-printshiv.min.js"></script>
     <![endif]-->
-    <script type="text/javascript" src="bower_components/jquery/dist/jquery.min.js"></script>
-    <script type="text/javascript" src="bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
-    <script type="text/javascript" src="bower_components/Brython3.3.0.tar/brython.js"></script>
-    <script type="text/javascript" src="bower_components/Brython3.3.0.tar/brython_stdlib.js"></script>
-    <script type="text/javascript" src="bower_components/ace/src-min-noconflict/ace.js"></script>
+    <script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
+    <script type="text/javascript" src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
+    <script type="text/javascript" src="node_modules/brython/brython.min.js"></script>
+    <script type="text/javascript" src="node_modules/brython/brython_stdlib.js"></script>
+    <script type="text/javascript" src="node_modules/monaco-editor/min/vs/loader.js"></script>
     <script type="text/javascript">
       exercise_id = <?php echo isset($_REQUEST["exercise_id"]) ? $_REQUEST["exercise_id"] : 0; ?>;
+      editor = document.getElementById('editor');
       jQuery(document).ready(function() {
-        editor = ace.edit("editor");
-        editor.session.setMode("ace/mode/python");
-        editor.$blockScrolling = Infinity;
-        brython();
+        require.config({ paths: { vs: 'node_modules/monaco-editor/min/vs' } });
+        require(['vs/editor/editor.main'], function () {
+          editor = monaco.editor.create(document.getElementById('editor'), {value: "", language: 'python', minimap: {enabled: false}});
+          diffEditor = monaco.editor.createDiffEditor(document.getElementById('diffEditor'));
+          brython();
+        });
       });
     </script>
   </head>
 
   <body class="container">
-    <div class="row" id="header-row">
-      <div class="col-md-12 panel-primary">
-        <h1 id="exercise" class="panel-heading">Loading...</h1>
-        <p id="instructions" class="panel-body">Loading...</p>
-      </div>
-    </div>
-
-    <div class="row" id="code-row">
-      <div class="col-md-8">
-        <pre id="editor" style="height: 240px;"></pre>
-      </div>
-      <div class="col-md-4">
-        <h3 class="text-center">Tests</h3>
-        <div id="tests" class="list-group"></div>
-      </div>
-    </div>
 
-    <div class="row" id="controls-row">
-      <div class="col-md-12 text-center">
-        <div class="form-group">
-          <button id="run" class="btn">Run</button>
-          <button id="test-all" type="button" class="btn">Run Tests</button>
-          <button id="grade" type="button" class="btn disabled">Grade</button>
-          <span id="nograde" class="hidden">Connect through a LMS to submit grade information</span>
+    <div class="accordian col-md-12" id="accordianMain">
+      <!-- Instructions -->
+      <div class="accordian-item">
+        <h2 class="accordian-header" id="headingOne">
+          <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
+            <h1 id="exercise">Loading...</h1>
+          </button>
+        </h2>
+        <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#accordionMain">
+          <div class="accordion-body">
+            <span id="instructions">Loading...</span>
+          </div>
         </div>
       </div>
-    </div>
 
-    <div class="row">
-      <div class="col-md-12 text-center">
-        <span id="warning"></span>
-      </div>
-    </div>
+       <!-- Code -->
+       <div class="accordion-item">
+         <h2 class="accordion-header" id="headingTwo">
+           <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo">
+             Code
+           </button>
+         </h2>
+         <div id="collapseTwo" class="accordion-collapse collapse show" aria-labelledby="headingTwo" data-bs-parent="#accordionMain">
+           <div class="accordion-body">
+             <div id="editor" style="height: 400px;"></div>
+             <div class="form-group text-center">
+               <button id="run" class="btn btn-secondary">Run</button>
+               <button id="test-all" type="button" class="btn btn-primary">Run Tests</button>
+               <button id="grade" type="button" class="btn btn-success disabled">Grade</button>
+               <span id="nograde" class="visually-hidden">Connect through a LMS to submit grade information</span>
+             </div>
+             <div><span id="warning"></span></div>
+             <div class="visually-hidden" id="output-row">
+                 <h3>Output</h3>
+                 <div class="form-group">
+                   <textarea id="output" readonly class="form-control"></textarea>
+                 </div>
+           </div>
+         </div>
+       </div>
 
-    <div class="row hidden" id="output-row">
-      <div class="col-md-12">
-        <h3 class="text-center">Output</h3>
-        <div id="container" style="width: 100%"></div>
-        <textarea id="output" readonly class="form-control" style="height: 240px"></textarea>
-      </div>
-    </div>
+       <!-- Tests -->
+       <div class="accordion-item">
+         <h2 class="accordion-header" id="headingThree">
+           <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseThree" aria-expanded="true" aria-controlls="collapseThree">
+             Tests
+           </button>
+         </h2>
+         <div id="collapseThree" class="accordion-collapse collapse show" aria-labelledby="headingThree" data-bs-parent="#accordionMain">
+           <div class="accordion-body">
+             <div id="tests" class="list-group"></div>
 
-    <div class="row hidden" id="test-row">
-      <div class="col-md-12 text-center">
-        <h3>Expected Output</h3>
-        <div class="form-group">
-          <textarea id="expected" readonly class="form-control"></textarea>
-        </div>
+             <div class="visually-hidden" id="test-row">
+                 <h3>Comparison of Expected and Actual Output</h3>
+                 <div class="form-group">
+                   <div id="diffEditor" style="height:400px; width: 800px;" class="form-control"></div>
+                 </div>
 
-        <h3>Actual Output</h3>
-        <div class="form-group">
-          <textarea id="actual" readonly class="form-control"></textarea>
-        </div>
+                 <h3>Expected Output</h3>
+                 <div class="form-group">
+                   <textarea id="expected" readonly class="form-control"></textarea>
+                 </div>
 
-        <h3>Test Input</h3>
-        <div class="form-group">
-          <textarea id="input" readonly class="form-control"></textarea>
-        </div>
-      </div>
+                <h3>Actual Output</h3>
+                <div class="form-group">
+                  <textarea id="actual" readonly class="form-control"></textarea>
+                </div>
+
+                <h3>Test Input</h3>
+                <div class="form-group">
+                  <textarea id="input" readonly class="form-control"></textarea>
+                </div>
+
+              </div>
+            </div>
+           </div>
+         </div>
+       </div>
     </div>
 
-    <script type="text/python" src="automarker_client.py"></script>
     <script type="text/javascript">
       submission_url = '';
       redirect_url = '';
 <?php
   if (!is_lti_request()) {
-    echo "    jQuery('#grade').addClass('hidden');\n";
-    echo "    jQuery('#nograde').removeClass('hidden');\n";
+    echo "jQuery(document).ready(function() {\n";
+    echo "    jQuery('#grade').addClass('visually-hidden');\n";
+    echo "    jQuery('#nograde').removeClass('visually-hidden');\n";
     echo "    jQuery('#nograde').show();\n";
+    echo "});\n";
   } else {
     $oauth_consumer_key = "";
     $oauth_consumer_secret = "";
@@ -111,9 +135,11 @@ require_once("bower_components/pythonauto/util/lti_util.php");
     }
     $context = new BLTI($oauth_consumer_secret, true, false);
     if (!$context->valid) {
-      echo "    jQuery('#grade').addClass('hidden');\n";
-      echo "    jQuery('#nograde').removeClass('hidden');\n";
+      echo "  jQuery(document).ready(function() {\n";
+      echo "    jQuery('#grade').addClass('visually-hidden');\n";
+      echo "    jQuery('#nograde').removeClass('visually-hidden');\n";
       echo "    jQuery('#nograde').show();\n";
+      echo "  });\n";
     } else {
       echo "    submission_url = '" . $context->addSession("grade.php") . "';\n";
       if (isset($_POST['launch_presentation_return_url'])) {
@@ -142,6 +168,14 @@ require_once("bower_components/pythonauto/util/lti_util.php");
           alert("Connect through a LMS to submit grade information");
         }
       }
+
+      function updateDiff() {
+        diffEditor.setModel({
+          original: monaco.editor.createModel(document.getElementById("expected").value, "text/plain"),
+          modified: monaco.editor.createModel(document.getElementById("actual").value, "text/plain")
+        });
+      }
     </script>
+    <script type="text/python" src="automarker_client.py"></script>
   </body>
 </html>
diff --git a/lti_util/LICENSE b/lti_util/LICENSE
new file mode 100644
index 0000000..16c6444
--- /dev/null
+++ b/lti_util/LICENSE
@@ -0,0 +1,23 @@
+The MIT License
+
+Copyright (c) 2007 Andy Smith
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+
diff --git a/lti_util/OAuth.php b/lti_util/OAuth.php
new file mode 100644
index 0000000..a5490b0
--- /dev/null
+++ b/lti_util/OAuth.php
@@ -0,0 +1,809 @@
+<?php
+// vim: foldmethod=marker
+
+$OAuth_last_computed_siguature = false;
+
+/* Generic exception class
+ */
+class OAuthException extends Exception {
+  // pass
+}
+
+class OAuthConsumer {
+  public $key;
+  public $secret;
+
+  function __construct($key, $secret, $callback_url=NULL) {
+    $this->key = $key;
+    $this->secret = $secret;
+    $this->callback_url = $callback_url;
+  }
+
+  function __toString() {
+    return "OAuthConsumer[key=$this->key,secret=$this->secret]";
+  }
+}
+
+class OAuthToken {
+  // access tokens and request tokens
+  public $key;
+  public $secret;
+
+  /**
+   * key = the token
+   * secret = the token secret
+   */
+  function __construct($key, $secret) {
+    $this->key = $key;
+    $this->secret = $secret;
+  }
+
+  /**
+   * generates the basic string serialization of a token that a server
+   * would respond to request_token and access_token calls with
+   */
+  function to_string() {
+    return "oauth_token=" .
+           OAuthUtil::urlencode_rfc3986($this->key) .
+           "&oauth_token_secret=" .
+           OAuthUtil::urlencode_rfc3986($this->secret);
+  }
+
+  function __toString() {
+    return $this->to_string();
+  }
+}
+
+class OAuthSignatureMethod {
+  public function check_signature(&$request, $consumer, $token, $signature) {
+    $built = $this->build_signature($request, $consumer, $token);
+    return $built == $signature;
+  }
+}
+
+class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
+  function get_name() {
+    return "HMAC-SHA1";
+  }
+
+  public function build_signature($request, $consumer, $token) {
+    global $OAuth_last_computed_signature;
+    $OAuth_last_computed_signature = false;
+
+    $base_string = $request->get_signature_base_string();
+    $request->base_string = $base_string;
+
+    $key_parts = array(
+      $consumer->secret,
+      ($token) ? $token->secret : ""
+    );
+
+    $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
+    $key = implode('&', $key_parts);
+
+    $computed_signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
+    $OAuth_last_computed_signature = $computed_signature;
+    return $computed_signature;
+  }
+
+}
+
+class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
+  public function get_name() {
+    return "PLAINTEXT";
+  }
+
+  public function build_signature($request, $consumer, $token) {
+    $sig = array(
+      OAuthUtil::urlencode_rfc3986($consumer->secret)
+    );
+
+    if ($token) {
+      array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
+    } else {
+      array_push($sig, '');
+    }
+
+    $raw = implode("&", $sig);
+    // for debug purposes
+    $request->base_string = $raw;
+
+    return OAuthUtil::urlencode_rfc3986($raw);
+  }
+}
+
+class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
+  public function get_name() {
+    return "RSA-SHA1";
+  }
+
+  protected function fetch_public_cert(&$request) {
+    // not implemented yet, ideas are:
+    // (1) do a lookup in a table of trusted certs keyed off of consumer
+    // (2) fetch via http using a url provided by the requester
+    // (3) some sort of specific discovery code based on request
+    //
+    // either way should return a string representation of the certificate
+    throw Exception("fetch_public_cert not implemented");
+  }
+
+  protected function fetch_private_cert(&$request) {
+    // not implemented yet, ideas are:
+    // (1) do a lookup in a table of trusted certs keyed off of consumer
+    //
+    // either way should return a string representation of the certificate
+    throw Exception("fetch_private_cert not implemented");
+  }
+
+  public function build_signature(&$request, $consumer, $token) {
+    $base_string = $request->get_signature_base_string();
+    $request->base_string = $base_string;
+
+    // Fetch the private key cert based on the request
+    $cert = $this->fetch_private_cert($request);
+
+    // Pull the private key ID from the certificate
+    $privatekeyid = openssl_get_privatekey($cert);
+
+    // Sign using the key
+    $ok = openssl_sign($base_string, $signature, $privatekeyid);
+
+    // Release the key resource
+    openssl_free_key($privatekeyid);
+
+    return base64_encode($signature);
+  }
+
+  public function check_signature(&$request, $consumer, $token, $signature) {
+    $decoded_sig = base64_decode($signature);
+
+    $base_string = $request->get_signature_base_string();
+
+    // Fetch the public key cert based on the request
+    $cert = $this->fetch_public_cert($request);
+
+    // Pull the public key ID from the certificate
+    $publickeyid = openssl_get_publickey($cert);
+
+    // Check the computed signature against the one passed in the query
+    $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
+
+    // Release the key resource
+    openssl_free_key($publickeyid);
+
+    return $ok == 1;
+  }
+}
+
+class OAuthRequest {
+  private $parameters;
+  private $http_method;
+  private $http_url;
+  // for debug purposes
+  public $base_string;
+  public static $version = '1.0';
+  public static $POST_INPUT = 'php://input';
+
+  function __construct($http_method, $http_url, $parameters=NULL) {
+    @$parameters or $parameters = array();
+    $this->parameters = $parameters;
+    $this->http_method = $http_method;
+    $this->http_url = $http_url;
+  }
+
+
+  /**
+   * attempt to build up a request from what was passed to the server
+   */
+  public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
+    $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
+              ? 'http'
+              : 'https';
+    $port = "";
+    if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" &&
+        strpos(':', $_SERVER['HTTP_HOST']) < 0 ) {
+      $port =  ':' . $_SERVER['SERVER_PORT'] ;
+    }
+    @$http_url or $http_url = $scheme .
+                              '://' . $_SERVER['HTTP_HOST'] .
+                              $port .
+                              $_SERVER['REQUEST_URI'];
+    @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
+
+    // We weren't handed any parameters, so let's find the ones relevant to
+    // this request.
+    // If you run XML-RPC or similar you should use this to provide your own
+    // parsed parameter-list
+    if (!$parameters) {
+      // Find request headers
+      $request_headers = OAuthUtil::get_headers();
+
+      // Parse the query-string to find GET parameters
+      $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
+
+      $ourpost = $_POST;
+      // Deal with magic_quotes
+      // http://www.php.net/manual/en/security.magicquotes.disabling.php
+      //if ( get_magic_quotes_gpc() ) {
+      //   $outpost = array();
+      //   foreach ($_POST as $k => $v) {
+      //      $v = stripslashes($v);
+      //      $ourpost[$k] = $v;
+      //   }
+      //}
+     // Add POST Parameters if they exist
+      $parameters = array_merge($parameters, $ourpost);
+
+      // We have a Authorization-header with OAuth data. Parse the header
+      // and add those overriding any duplicates from GET or POST
+      if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
+        $header_parameters = OAuthUtil::split_header(
+          $request_headers['Authorization']
+        );
+        $parameters = array_merge($parameters, $header_parameters);
+      }
+
+    }
+
+    return new OAuthRequest($http_method, $http_url, $parameters);
+  }
+
+  /**
+   * pretty much a helper function to set up the request
+   */
+  public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
+    @$parameters or $parameters = array();
+    $defaults = array("oauth_version" => OAuthRequest::$version,
+                      "oauth_nonce" => OAuthRequest::generate_nonce(),
+                      "oauth_timestamp" => OAuthRequest::generate_timestamp(),
+                      "oauth_consumer_key" => $consumer->key);
+    if ($token)
+      $defaults['oauth_token'] = $token->key;
+
+    $parameters = array_merge($defaults, $parameters);
+
+    // Parse the query-string to find and add GET parameters
+    $parts = parse_url($http_url);
+    if ( $parts['query'] ) {
+      $qparms = OAuthUtil::parse_parameters($parts['query']);
+      $parameters = array_merge($qparms, $parameters);
+    }
+     
+
+    return new OAuthRequest($http_method, $http_url, $parameters);
+  }
+
+  public function set_parameter($name, $value, $allow_duplicates = true) {
+    if ($allow_duplicates && isset($this->parameters[$name])) {
+      // We have already added parameter(s) with this name, so add to the list
+      if (is_scalar($this->parameters[$name])) {
+        // This is the first duplicate, so transform scalar (string)
+        // into an array so we can add the duplicates
+        $this->parameters[$name] = array($this->parameters[$name]);
+      }
+
+      $this->parameters[$name][] = $value;
+    } else {
+      $this->parameters[$name] = $value;
+    }
+  }
+
+  public function get_parameter($name) {
+    return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
+  }
+
+  public function get_parameters() {
+    return $this->parameters;
+  }
+
+  public function unset_parameter($name) {
+    unset($this->parameters[$name]);
+  }
+
+  /**
+   * The request parameters, sorted and concatenated into a normalized string.
+   * @return string
+   */
+  public function get_signable_parameters() {
+    // Grab all parameters
+    $params = $this->parameters;
+
+    // Remove oauth_signature if present
+    // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
+    if (isset($params['oauth_signature'])) {
+      unset($params['oauth_signature']);
+    }
+
+    return OAuthUtil::build_http_query($params);
+  }
+
+  /**
+   * Returns the base string of this request
+   *
+   * The base string defined as the method, the url
+   * and the parameters (normalized), each urlencoded
+   * and the concated with &.
+   */
+  public function get_signature_base_string() {
+    $parts = array(
+      $this->get_normalized_http_method(),
+      $this->get_normalized_http_url(),
+      $this->get_signable_parameters()
+    );
+
+    $parts = OAuthUtil::urlencode_rfc3986($parts);
+
+    return implode('&', $parts);
+  }
+
+  /**
+   * just uppercases the http method
+   */
+  public function get_normalized_http_method() {
+    return strtoupper($this->http_method);
+  }
+
+  /**
+   * parses the url and rebuilds it to be
+   * scheme://host/path
+   */
+  public function get_normalized_http_url() {
+    $parts = parse_url($this->http_url);
+
+    $port = @$parts['port'];
+    $scheme = $parts['scheme'];
+    $host = $parts['host'];
+    $path = @$parts['path'];
+
+    $port or $port = ($scheme == 'https') ? '443' : '80';
+
+    if (($scheme == 'https' && $port != '443')
+        || ($scheme == 'http' && $port != '80')) {
+      $host = "$host:$port";
+    }
+    return "$scheme://$host$path";
+  }
+
+  /**
+   * builds a url usable for a GET request
+   */
+  public function to_url() {
+    $post_data = $this->to_postdata();
+    $out = $this->get_normalized_http_url();
+    if ($post_data) {
+      $out .= '?'.$post_data;
+    }
+    return $out;
+  }
+
+  /**
+   * builds the data one would send in a POST request
+   */
+  public function to_postdata() {
+    return OAuthUtil::build_http_query($this->parameters);
+  }
+
+  /**
+   * builds the Authorization: header
+   */
+  public function to_header() {
+    $out ='Authorization: OAuth realm=""';
+    $total = array();
+    foreach ($this->parameters as $k => $v) {
+      if (substr($k, 0, 5) != "oauth") continue;
+      if (is_array($v)) {
+        throw new OAuthException('Arrays not supported in headers');
+      }
+      $out .= ',' .
+              OAuthUtil::urlencode_rfc3986($k) .
+              '="' .
+              OAuthUtil::urlencode_rfc3986($v) .
+              '"';
+    }
+    return $out;
+  }
+
+  public function __toString() {
+    return $this->to_url();
+  }
+
+
+  public function sign_request($signature_method, $consumer, $token) {
+    $this->set_parameter(
+      "oauth_signature_method",
+      $signature_method->get_name(),
+      false
+    );
+    $signature = $this->build_signature($signature_method, $consumer, $token);
+    $this->set_parameter("oauth_signature", $signature, false);
+  }
+
+  public function build_signature($signature_method, $consumer, $token) {
+    $signature = $signature_method->build_signature($this, $consumer, $token);
+    return $signature;
+  }
+
+  /**
+   * util function: current timestamp
+   */
+  private static function generate_timestamp() {
+    return time();
+  }
+
+  /**
+   * util function: current nonce
+   */
+  private static function generate_nonce() {
+    $mt = microtime();
+    $rand = mt_rand();
+
+    return md5($mt . $rand); // md5s look nicer than numbers
+  }
+}
+
+class OAuthServer {
+  protected $timestamp_threshold = 300; // in seconds, five minutes
+  protected $version = 1.0;             // hi blaine
+  protected $signature_methods = array();
+
+  protected $data_store;
+
+  function __construct($data_store) {
+    $this->data_store = $data_store;
+  }
+
+  public function add_signature_method($signature_method) {
+    $this->signature_methods[$signature_method->get_name()] =
+      $signature_method;
+  }
+
+  // high level functions
+
+  /**
+   * process a request_token request
+   * returns the request token on success
+   */
+  public function fetch_request_token(&$request) {
+    $this->get_version($request);
+
+    $consumer = $this->get_consumer($request);
+
+    // no token required for the initial token request
+    $token = NULL;
+
+    $this->check_signature($request, $consumer, $token);
+
+    $new_token = $this->data_store->new_request_token($consumer);
+
+    return $new_token;
+  }
+
+  /**
+   * process an access_token request
+   * returns the access token on success
+   */
+  public function fetch_access_token(&$request) {
+    $this->get_version($request);
+
+    $consumer = $this->get_consumer($request);
+
+    // requires authorized request token
+    $token = $this->get_token($request, $consumer, "request");
+
+
+    $this->check_signature($request, $consumer, $token);
+
+    $new_token = $this->data_store->new_access_token($token, $consumer);
+
+    return $new_token;
+  }
+
+  /**
+   * verify an api call, checks all the parameters
+   */
+  public function verify_request(&$request) {
+    global $OAuth_last_computed_signature;
+    $OAuth_last_computed_signature = false;
+    $this->get_version($request);
+    $consumer = $this->get_consumer($request);
+    $token = $this->get_token($request, $consumer, "access");
+    $this->check_signature($request, $consumer, $token);
+    return array($consumer, $token);
+  }
+
+  // Internals from here
+  /**
+   * version 1
+   */
+  private function get_version(&$request) {
+    $version = $request->get_parameter("oauth_version");
+    if (!$version) {
+      $version = 1.0;
+    }
+    if ($version && $version != $this->version) {
+      throw new OAuthException("OAuth version '$version' not supported");
+    }
+    return $version;
+  }
+
+  /**
+   * figure out the signature with some defaults
+   */
+  private function get_signature_method(&$request) {
+    $signature_method =
+        @$request->get_parameter("oauth_signature_method");
+    if (!$signature_method) {
+      $signature_method = "PLAINTEXT";
+    }
+    if (!in_array($signature_method,
+                  array_keys($this->signature_methods))) {
+      throw new OAuthException(
+        "Signature method '$signature_method' not supported " .
+        "try one of the following: " .
+        implode(", ", array_keys($this->signature_methods))
+      );
+    }
+    return $this->signature_methods[$signature_method];
+  }
+
+  /**
+   * try to find the consumer for the provided request's consumer key
+   */
+  private function get_consumer(&$request) {
+    $consumer_key = @$request->get_parameter("oauth_consumer_key");
+    if (!$consumer_key) {
+      throw new OAuthException("Invalid consumer key");
+    }
+
+    $consumer = $this->data_store->lookup_consumer($consumer_key);
+    if (!$consumer) {
+      throw new OAuthException("Invalid consumer");
+    }
+
+    return $consumer;
+  }
+
+  /**
+   * try to find the token for the provided request's token key
+   */
+  private function get_token(&$request, $consumer, $token_type="access") {
+    $token_field = @$request->get_parameter('oauth_token');
+    if ( !$token_field) return false;
+    $token = $this->data_store->lookup_token(
+      $consumer, $token_type, $token_field
+    );
+    if (!$token) {
+      throw new OAuthException("Invalid $token_type token: $token_field");
+    }
+    return $token;
+  }
+
+  /**
+   * all-in-one function to check the signature on a request
+   * should guess the signature method appropriately
+   */
+  private function check_signature(&$request, $consumer, $token) {
+    // this should probably be in a different method
+    global $OAuth_last_computed_signature;
+    $OAuth_last_computed_signature = false;
+
+    $timestamp = @$request->get_parameter('oauth_timestamp');
+    $nonce = @$request->get_parameter('oauth_nonce');
+
+    $this->check_timestamp($timestamp);
+    $this->check_nonce($consumer, $token, $nonce, $timestamp);
+
+    $signature_method = $this->get_signature_method($request);
+
+    $signature = $request->get_parameter('oauth_signature');
+    $valid_sig = $signature_method->check_signature(
+      $request,
+      $consumer,
+      $token,
+      $signature
+    );
+
+    if (!$valid_sig) {
+      $ex_text = "Invalid signature";
+      if ( $OAuth_last_computed_signature ) {
+          $ex_text = $ex_text . " ours= $OAuth_last_computed_signature yours=$signature";
+      }
+      throw new OAuthException($ex_text);
+    }
+  }
+
+  /**
+   * check that the timestamp is new enough
+   */
+  private function check_timestamp($timestamp) {
+    // verify that timestamp is recentish
+    $now = time();
+    if ($now - $timestamp > $this->timestamp_threshold) {
+      throw new OAuthException(
+        "Expired timestamp, yours $timestamp, ours $now"
+      );
+    }
+  }
+
+  /**
+   * check that the nonce is not repeated
+   */
+  private function check_nonce($consumer, $token, $nonce, $timestamp) {
+    // verify that the nonce is uniqueish
+    $found = $this->data_store->lookup_nonce(
+      $consumer,
+      $token,
+      $nonce,
+      $timestamp
+    );
+    if ($found) {
+      throw new OAuthException("Nonce already used: $nonce");
+    }
+  }
+
+}
+
+class OAuthDataStore {
+  function lookup_consumer($consumer_key) {
+    // implement me
+  }
+
+  function lookup_token($consumer, $token_type, $token) {
+    // implement me
+  }
+
+  function lookup_nonce($consumer, $token, $nonce, $timestamp) {
+    // implement me
+  }
+
+  function new_request_token($consumer) {
+    // return a new token attached to this consumer
+  }
+
+  function new_access_token($token, $consumer) {
+    // return a new access token attached to this consumer
+    // for the user associated with this token if the request token
+    // is authorized
+    // should also invalidate the request token
+  }
+
+}
+
+class OAuthUtil {
+  public static function urlencode_rfc3986($input) {
+  if (is_array($input)) {
+    return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
+  } else if (is_scalar($input)) {
+    return str_replace(
+      '+',
+      ' ',
+      str_replace('%7E', '~', rawurlencode($input))
+    );
+  } else {
+    return '';
+  }
+}
+
+
+  // This decode function isn't taking into consideration the above
+  // modifications to the encoding process. However, this method doesn't
+  // seem to be used anywhere so leaving it as is.
+  public static function urldecode_rfc3986($string) {
+    return urldecode($string);
+  }
+
+  // Utility function for turning the Authorization: header into
+  // parameters, has to do some unescaping
+  // Can filter out any non-oauth parameters if needed (default behaviour)
+  public static function split_header($header, $only_allow_oauth_parameters = true) {
+    $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
+    $offset = 0;
+    $params = array();
+    while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
+      $match = $matches[0];
+      $header_name = $matches[2][0];
+      $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
+      if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
+        $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
+      }
+      $offset = $match[1] + strlen($match[0]);
+    }
+
+    if (isset($params['realm'])) {
+      unset($params['realm']);
+    }
+
+    return $params;
+  }
+
+  // helper to try to sort out headers for people who aren't running apache
+  public static function get_headers() {
+    if (function_exists('apache_request_headers')) {
+      // we need this to get the actual Authorization: header
+      // because apache tends to tell us it doesn't exist
+      return apache_request_headers();
+    }
+    // otherwise we don't have apache and are just going to have to hope
+    // that $_SERVER actually contains what we need
+    $out = array();
+    foreach ($_SERVER as $key => $value) {
+      if (substr($key, 0, 5) == "HTTP_") {
+        // this is chaos, basically it is just there to capitalize the first
+        // letter of every word that is not an initial HTTP and strip HTTP
+        // code from przemek
+        $key = str_replace(
+          " ",
+          "-",
+          ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
+        );
+        $out[$key] = $value;
+      }
+    }
+    return $out;
+  }
+
+  // This function takes a input like a=b&a=c&d=e and returns the parsed
+  // parameters like this
+  // array('a' => array('b','c'), 'd' => 'e')
+  public static function parse_parameters( $input ) {
+    if (!isset($input) || !$input) return array();
+
+    $pairs = explode('&', $input);
+
+    $parsed_parameters = array();
+    foreach ($pairs as $pair) {
+      $split = explode('=', $pair, 2);
+      $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
+      $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
+
+      if (isset($parsed_parameters[$parameter])) {
+        // We have already recieved parameter(s) with this name, so add to the list
+        // of parameters with this name
+
+        if (is_scalar($parsed_parameters[$parameter])) {
+          // This is the first duplicate, so transform scalar (string) into an array
+          // so we can add the duplicates
+          $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
+        }
+
+        $parsed_parameters[$parameter][] = $value;
+      } else {
+        $parsed_parameters[$parameter] = $value;
+      }
+    }
+    return $parsed_parameters;
+  }
+
+  public static function build_http_query($params) {
+    if (!$params) return '';
+
+    // Urlencode both keys and values
+    $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
+    $values = OAuthUtil::urlencode_rfc3986(array_values($params));
+    $params = array_combine($keys, $values);
+
+    // Parameters are sorted by name, using lexicographical byte value ordering.
+    // Ref: Spec: 9.1.1 (1)
+    uksort($params, 'strcmp');
+
+    $pairs = array();
+    foreach ($params as $parameter => $value) {
+      if (is_array($value)) {
+        // If two or more parameters share the same name, they are sorted by their value
+        // Ref: Spec: 9.1.1 (1)
+        natsort($value);
+        foreach ($value as $duplicate_value) {
+          $pairs[] = $parameter . '=' . $duplicate_value;
+        }
+      } else {
+        $pairs[] = $parameter . '=' . $value;
+      }
+    }
+    // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
+    // Each name-value pair is separated by an '&' character (ASCII code 38)
+    return implode('&', $pairs);
+  }
+}
+
+?>
+
diff --git a/lti_util/lti_util.php b/lti_util/lti_util.php
new file mode 100644
index 0000000..c6c6f05
--- /dev/null
+++ b/lti_util/lti_util.php
@@ -0,0 +1,880 @@
+<?php
+
+require_once 'OAuth.php';
+
+// Returns true if this is a Basic LTI message
+// with minimum values to meet the protocol
+function is_lti_request() {
+   $good_message_type = $_REQUEST["lti_message_type"] == "basic-lti-launch-request";
+   $good_lti_version = $_REQUEST["lti_version"] == "LTI-1p0";
+   $resource_link_id = $_REQUEST["resource_link_id"];
+   if ($good_message_type and $good_lti_version and isset($resource_link_id) ) return(true);
+   return false;
+}
+
+// Basic LTI Class that does the setup and provides utility
+// functions
+class BLTI {
+
+    public $valid = false;
+    public $complete = false;
+    public $message = false;
+    public $basestring = false;
+    public $info = false;
+    public $row = false;
+    public $context_id = false;  // Override context_id
+    public $consumer_id = false;
+    public $user_id = false;
+    public $course_id = false;
+    public $resource_id = false;
+
+    function __construct($parm=false, $usesession=true, $doredirect=true) {
+
+        // If this request is not an LTI Launch, either
+        // give up or try to retrieve the context from session
+        if ( ! is_lti_request() ) {
+            if ( $usesession === false ) return;
+            if ( strlen(session_id()) > 0 ) {
+                $row = $_SESSION['_lti_row'];
+                if ( isset($row) ) $this->row = $row;
+                $context_id = $_SESSION['_lti_context_id'];
+                if ( isset($context_id) ) $this->context_id = $context_id;
+                $info = $_SESSION['_lti_context'];
+                if ( isset($info) ) {
+                    $this->info = $info;
+                    $this->valid = true;
+                    return;
+                }
+                $this->message = "Could not find context in session";
+                return;
+            }
+            $this->message = "Session not available";
+            return;
+        }
+
+        // Insure we have a valid launch
+        if ( empty($_REQUEST["oauth_consumer_key"]) ) {
+            $this->message = "Missing oauth_consumer_key in request";
+            return;
+        }
+        $oauth_consumer_key = $_REQUEST["oauth_consumer_key"];
+
+        // Find the secret - either form the parameter as a string or
+        // look it up in a database from parameters we are given
+        $secret = false;
+        $row = false;
+        if ( is_string($parm) ) {
+            $secret = $parm;
+        } else if ( ! is_array($parm) ) {
+            $this->message = "Constructor requires a secret or database information.";
+            return;
+        } else {
+            $sql = 'SELECT * FROM '.$parm['table'].' WHERE '.
+                ($parm['key_column'] ? $parm['key_column'] : 'oauth_consumer_key').
+                '='.
+                "'".mysql_real_escape_string($oauth_consumer_key)."'";
+            $result = mysql_query($sql);
+            $num_rows = mysql_num_rows($result);
+            if ( $num_rows != 1 ) {
+                $this->message = "Your consumer is not authorized oauth_consumer_key=".$oauth_consumer_key;
+                return;
+            } else {
+                while ($row = mysql_fetch_assoc($result)) {
+                    $secret = $row[$parms['secret_column']?$parms['secret_column']:'secret'];
+                    $context_id = $row[$parms['context_column']?$parms['context_column']:'context_id'];
+                    if ( $context_id ) $this->context_id = $context_id;
+                    $this->row = $row;
+                    break;
+                }
+                if ( ! is_string($secret) ) {
+                    $this->message = "Could not retrieve secret oauth_consumer_key=".$oauth_consumer_key;
+                    return;
+                }
+            }
+        }
+
+        // Verify the message signature
+        $store = new TrivialOAuthDataStore();
+        $store->add_consumer($oauth_consumer_key, $secret);
+
+        $server = new OAuthServer($store);
+
+        $method = new OAuthSignatureMethod_HMAC_SHA1();
+        $server->add_signature_method($method);
+        $request = OAuthRequest::from_request();
+
+        $this->basestring = $request->get_signature_base_string();
+
+        try {
+            $server->verify_request($request);
+            $this->valid = true;
+        } catch (Exception $e) {
+            $this->message = $e->getMessage();
+            return;
+        }
+
+        // Store the launch information in the session for later
+        $newinfo = array();
+        foreach($_POST as $key => $value ) {
+            if ( $key == "basiclti_submit" ) continue;
+            if ( strpos($key, "oauth_") === false ) {
+                $newinfo[$key] = $value;
+                continue;
+            }
+            if ( $key == "oauth_consumer_key" ) {
+                $newinfo[$key] = $value;
+                continue;
+            }
+        }
+
+        $this->info = $newinfo;
+        if ( $usesession == true and strlen(session_id()) > 0 ) {
+             $_SESSION['_lti_context'] = $this->info;
+             unset($_SESSION['_lti_row']);
+             unset($_SESSION['_lti_context_id']);
+             if ( $this->row ) $_SESSION['_lti_row'] = $this->row;
+             if ( $this->context_id ) $_SESSION['_lti_context_id'] = $this->context_id;
+        }
+
+        if ( $this->valid && $doredirect ) {
+            $this->redirect();
+            $this->complete = true;
+        }
+    }
+
+    function addSession($location) {
+        if ( ini_get('session.use_cookies') == 0 ) {
+            if ( strpos($location,'?') > 0 ) {
+               $location = $location . '&';
+            } else {
+               $location = $location . '?';
+            }
+            $location = $location . session_name() . '=' . session_id();
+        }
+        return $location;
+    }
+
+    function isInstructor() {
+        $roles = $this->info['roles'];
+        $roles = strtolower($roles);
+        if ( ! ( strpos($roles,"instructor") === false ) ) return true;
+        if ( ! ( strpos($roles,"administrator") === false ) ) return true;
+        return false;
+    }
+
+    function getUserEmail() {
+        $email = $this->info['lis_person_contact_email_primary'];
+        if ( strlen($email) > 0 ) return $email;
+        # Sakai Hack
+        $email = $this->info['lis_person_contact_emailprimary'];
+        if ( strlen($email) > 0 ) return $email;
+        return false;
+    }
+
+    function getUserShortName() {
+        $email = $this->getUserEmail();
+        $givenname = $this->info['lis_person_name_given'];
+        $familyname = $this->info['lis_person_name_family'];
+        $fullname = $this->info['lis_person_name_full'];
+        if ( strlen($email) > 0 ) return $email;
+        if ( strlen($givenname) > 0 ) return $givenname;
+        if ( strlen($familyname) > 0 ) return $familyname;
+        return $this->getUserName();
+    }
+
+    function getUserName() {
+        $givenname = $this->info['lis_person_name_given'];
+        $familyname = $this->info['lis_person_name_family'];
+        $fullname = $this->info['lis_person_name_full'];
+        if ( strlen($fullname) > 0 ) return $fullname;
+        if ( strlen($familyname) > 0 and strlen($givenname) > 0 ) return $givenname + $familyname;
+        if ( strlen($givenname) > 0 ) return $givenname;
+        if ( strlen($familyname) > 0 ) return $familyname;
+        return $this->getUserEmail();
+    }
+
+    // Name spaced
+    function getUserKey() {
+        $oauth = $this->info['oauth_consumer_key'];
+        $id = $this->info['user_id'];
+        if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
+        return false;
+    }
+
+    // Un-Namespaced
+    function getUserLKey() {
+        $id = $this->info['user_id'];
+        if ( strlen($id) > 0 ) return $id;
+        return false;
+    }
+
+    function setUserID($new_id) {
+        $this->user_id = $new_id;
+    }
+
+    function getUserID() {
+        return $this->user_id;
+    }
+
+    function getUserImage() {
+        $image = $this->info['user_image'];
+        if ( strlen($image) > 0 ) return $image;
+        $email = $this->getUserEmail();
+        if ( $email === false ) return false;
+        $size = 40;
+        $grav_url = $_SERVER['HTTPS'] ? 'https://' : 'http://';
+        $grav_url = $grav_url . "www.gravatar.com/avatar.php?gravatar_id=".md5( strtolower($email) )."&size=".$size;
+        return $grav_url;
+    }
+
+    function getResourceKey() {
+        $oauth = $this->info['oauth_consumer_key'];
+        $id = $this->info['resource_link_id'];
+        if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
+        return false;
+    }
+
+    function getResourceLKey() {
+        $id = $this->info['resource_link_id'];
+        if ( strlen($id) > 0 ) return $id;
+        return false;
+    }
+
+    function setResourceID($new_id) {
+        $this->resource_id = $new_id;
+    }
+
+    function getResourceID() {
+        return $this->resource_id;
+    }
+
+    function getResourceTitle() {
+        $title = $this->info['resource_link_title'];
+        if ( strlen($title) > 0 ) return $title;
+        return false;
+    }
+
+    function getConsumerKey() {
+        $oauth = $this->info['oauth_consumer_key'];
+        return $oauth;
+    }
+
+    function setConsumerID($new_id) {
+        $this->consumer_id = $new_id;
+    }
+
+    function getConsumerID() {
+        return $this->consumer_id;
+    }
+
+    function getCourseLKey() {
+        if ( $this->context_id ) return $this->context_id;
+        $id = $this->info['context_id'];
+        if ( strlen($id) > 0 ) return $id;
+        return false;
+    }
+
+    function getCourseKey() {
+        if ( $this->context_id ) return $this->context_id;
+        $oauth = $this->info['oauth_consumer_key'];
+        $id = $this->info['context_id'];
+        if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
+        return false;
+    }
+
+    function setCourseID($new_id) {
+        $this->course_id = $new_id;
+    }
+
+    function getCourseID() {
+        return $this->course_id;
+    }
+
+    function getCourseName() {
+        $label = $this->info['context_label'];
+        $title = $this->info['context_title'];
+        $id = $this->info['context_id'];
+        if ( strlen($label) > 0 ) return $label;
+        if ( strlen($title) > 0 ) return $title;
+        if ( strlen($id) > 0 ) return $id;
+        return false;
+    }
+
+    function getCSS() {
+        $list = $this->info['launch_presentation_css_url'];
+        if ( strlen($list) < 1 ) return array();
+        return explode(',',$list);
+    }
+
+    function getReturnURL() {
+        $url = $this->info['launch_presentation_return_url'];
+        if ( strlen($url) > 0 ) return $url;
+        return false;
+    }
+
+    function getOutcomeService() {
+        $retval = $this->info['lis_outcome_service_url'];
+        if ( strlen($retval) > 1 ) return $retval;
+        return false;
+    }
+
+    function getOutcomeSourceDID() {
+        $retval = $this->info['lis_result_sourcedid'];
+        if ( strlen($retval) > 1 ) return $retval;
+        return false;
+    }
+
+    function redirect($url=false) {
+        if ( $url === false ) {
+      $host = $_SERVER['HTTP_HOST'];
+      $uri = $_SERVER['PHP_SELF'];
+      $location = $_SERVER['HTTPS'] ? 'https://' : 'http://';
+      $location = $location . $host . $uri;
+    } else {
+      $location = $url;
+    }
+
+    if ( headers_sent() ) {
+      echo('<a href="'.htmlentities($location).'">Continue</a>'."\n");
+    } else {
+        $location = htmlentities($this->addSession($location));
+      header("Location: $location");
+    }
+    }
+
+    function dump() {
+        if ( ! $this->valid or $this->info == false ) return "Context not valid\n";
+        $ret = "";
+        if ( $this->isInstructor() ) {
+            $ret .= "isInstructor() = true\n";
+        } else {
+            $ret .= "isInstructor() = false\n";
+        }
+        $ret .= "getConsumerKey() = ".$this->getConsumerKey()."\n";
+        $ret .= "getUserLKey() = ".$this->getUserLKey()."\n";
+        $ret .= "getUserKey() = ".$this->getUserKey()."\n";
+        $ret .= "getUserID() = ".$this->getUserID()."\n";
+        $ret .= "getUserEmail() = ".$this->getUserEmail()."\n";
+        $ret .= "getUserShortName() = ".$this->getUserShortName()."\n";
+        $ret .= "getUserName() = ".$this->getUserName()."\n";
+        $ret .= "getUserImage() = ".$this->getUserImage()."\n";
+        $ret .= "getResourceKey() = ".$this->getResourceKey()."\n";
+        $ret .= "getResourceID() = ".$this->getResourceID()."\n";
+        $ret .= "getResourceTitle() = ".$this->getResourceTitle()."\n";
+        $ret .= "getCourseName() = ".$this->getCourseName()."\n";
+        $ret .= "getCourseKey() = ".$this->getCourseKey()."\n";
+        $ret .= "getCourseID() = ".$this->getCourseID()."\n";
+        $ret .= "getOutcomeSourceDID() = ".$this->getOutcomeSourceDID()."\n";
+        $ret .= "getOutcomeService() = ".$this->getOutcomeService()."\n";
+        return $ret;
+    }
+
+}
+
+/**
+ * A Trivial memory-based store - no support for tokens
+ */
+class TrivialOAuthDataStore extends OAuthDataStore {
+    private $consumers = array();
+
+    function add_consumer($consumer_key, $consumer_secret) {
+        $this->consumers[$consumer_key] = $consumer_secret;
+    }
+
+    function lookup_consumer($consumer_key) {
+        if ( strpos($consumer_key, "http://" ) === 0 ) {
+            $consumer = new OAuthConsumer($consumer_key,"secret", NULL);
+            return $consumer;
+        }
+        if ( $this->consumers[$consumer_key] ) {
+            $consumer = new OAuthConsumer($consumer_key,$this->consumers[$consumer_key], NULL);
+            return $consumer;
+        }
+        return NULL;
+    }
+
+    function lookup_token($consumer, $token_type, $token) {
+        return new OAuthToken($consumer, "");
+    }
+
+    // Return NULL if the nonce has not been used
+    // Return $nonce if the nonce was previously used
+    function lookup_nonce($consumer, $token, $nonce, $timestamp) {
+        // Should add some clever logic to keep nonces from
+        // being reused - for no we are really trusting
+  // that the timestamp will save us
+        return NULL;
+    }
+
+    function new_request_token($consumer) {
+        return NULL;
+    }
+
+    function new_access_token($token, $consumer) {
+        return NULL;
+    }
+}
+
+function signParameters($oldparms, $endpoint, $method, $oauth_consumer_key, $oauth_consumer_secret,
+    $submit_text = false, $org_id = false, $org_desc = false)
+{
+    global $last_base_string;
+    $parms = $oldparms;
+    if ( ! isset($parms["lti_version"]) ) $parms["lti_version"] = "LTI-1p0";
+    if ( ! isset($parms["lti_message_type"]) ) $parms["lti_message_type"] = "basic-lti-launch-request";
+    if ( ! isset($parms["oauth_callback"]) ) $parms["oauth_callback"] = "about:blank";
+    if ( $org_id ) $parms["tool_consumer_instance_guid"] = $org_id;
+    if ( $org_desc ) $parms["tool_consumer_instance_description"] = $org_desc;
+    if ( $submit_text ) $parms["ext_submit"] = $submit_text;
+
+    $test_token = '';
+
+    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
+    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
+
+    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
+    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
+
+    // Pass this back up "out of band" for debugging
+    $last_base_string = $acc_req->get_signature_base_string();
+
+    $newparms = $acc_req->get_parameters();
+
+  // Don't want to pull GET parameters into POST data so
+    // manually pull back the oauth_ parameters
+  foreach($newparms as $k => $v ) {
+        if ( strpos($k, "oauth_") === 0 ) {
+            $parms[$k] = $v;
+        }
+    }
+
+    return $parms;
+}
+
+  function postLaunchHTML($newparms, $endpoint, $debug=false, $iframeattr=false) {
+    global $last_base_string;
+    $r = "<div id=\"ltiLaunchFormSubmitArea\">\n";
+    if ( $iframeattr ) {
+        $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" target=\"basicltiLaunchFrame\" encType=\"application/x-www-form-urlencoded\">\n" ;
+    } else {
+        $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n" ;
+    }
+    $submit_text = $newparms['ext_submit'];
+    foreach($newparms as $key => $value ) {
+        $key = htmlspecialchars($key);
+        $value = htmlspecialchars($value);
+        if ( $key == "ext_submit" ) {
+            $r .= "<input type=\"submit\" name=\"";
+        } else {
+            $r .= "<input type=\"hidden\" name=\"";
+        }
+        $r .= $key;
+        $r .= "\" value=\"";
+        $r .= $value;
+        $r .= "\"/>\n";
+    }
+    if ( $debug ) {
+        $r .= "<script language=\"javascript\"> \n";
+        $r .= "  //<![CDATA[ \n" ;
+        $r .= "function basicltiDebugToggle() {\n";
+        $r .= "    var ele = document.getElementById(\"basicltiDebug\");\n";
+        $r .= "    if(ele.style.display == \"block\") {\n";
+        $r .= "        ele.style.display = \"none\";\n";
+        $r .= "    }\n";
+        $r .= "    else {\n";
+        $r .= "        ele.style.display = \"block\";\n";
+        $r .= "    }\n";
+        $r .= "} \n";
+        $r .= "  //]]> \n" ;
+        $r .= "</script>\n";
+        $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
+        $r .= get_string("toggle_debug_data","basiclti")."</a>\n";
+        $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
+        $r .=  "<b>".get_string("basiclti_endpoint","basiclti")."</b><br/>\n";
+        $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
+        $r .=  "<b>".get_string("basiclti_parameters","basiclti")."</b><br/>\n";
+        foreach($newparms as $key => $value ) {
+            $key = htmlspecialchars($key);
+            $value = htmlspecialchars($value);
+            $r .= "$key = $value<br/>\n";
+        }
+        $r .= "&nbsp;<br/>\n";
+        $r .= "<p><b>".get_string("basiclti_base_string","basiclti")."</b><br/>\n".$last_base_string."</p>\n";
+        $r .= "</div>\n";
+    }
+    $r .= "</form>\n";
+    if ( $iframeattr ) {
+        $r .= "<iframe name=\"basicltiLaunchFrame\"  id=\"basicltiLaunchFrame\" src=\"\"\n";
+        $r .= $iframeattr . ">\n<p>".get_string("frames_required","basiclti")."</p>\n</iframe>\n";
+    }
+    if ( ! $debug ) {
+        $ext_submit = "ext_submit";
+        $ext_submit_text = $submit_text;
+        $r .= " <script type=\"text/javascript\"> \n" .
+            "  //<![CDATA[ \n" .
+            "    document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
+            "    nei = document.createElement('input');\n" .
+            "    nei.setAttribute('type', 'hidden');\n" .
+            "    nei.setAttribute('name', '".$ext_submit."');\n" .
+            "    nei.setAttribute('value', '".$ext_submit_text."');\n" .
+            "    document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
+            "    document.ltiLaunchForm.submit(); \n" .
+            "  //]]> \n" .
+            " </script> \n";
+    }
+    $r .= "</div>\n";
+    return $r;
+}
+
+/* This is a bit of homage to Moodle's pattern of internationalisation */
+function get_string($key,$bundle) {
+    return $key;
+}
+
+function do_post_request($url, $data, $optional_headers = null)
+{
+  $params = array('http' => array(
+              'method' => 'POST',
+              'content' => $data
+            ));
+
+  if ($optional_headers !== null) {
+     $header = $optional_headers . "\r\n";
+  }
+  // $header = $header . "Content-type: application/x-www-form-urlencoded\r\n";
+  $params['http']['header'] = $header;
+  $ctx = stream_context_create($params);
+  $fp = @fopen($url, 'rb', false, $ctx);
+  if (!$fp) {
+    throw new Exception("Problem with $url, $php_errormsg");
+  }
+  $response = @stream_get_contents($fp);
+  if ($response === false) {
+    throw new Exception("Problem reading data from $url, $php_errormsg");
+  }
+  return $response;
+}
+
+
+  // Parse a descriptor
+  function launchInfo($xmldata) {
+    $xml = new SimpleXMLElement($xmldata);
+    if ( ! $xml ) {
+       echo("Error parsing Descriptor XML\n");
+       return;
+    }
+    $launch_url = $xml->secure_launch_url[0];
+    if ( ! $launch_url ) $launch_url = $xml->launch_url[0];
+    if ( $launch_url ) $launch_url = (string) $launch_url;
+    $custom = array();
+    if ( $xml->custom[0]->parameter )
+    foreach ( $xml->custom[0]->parameter as $resource) {
+      $key = (string) $resource['key'];
+      $key = strtolower($key);
+      $nk = "";
+      for($i=0; $i < strlen($key); $i++) {
+        $ch = substr($key,$i,1);
+        if ( $ch >= "a" && $ch <= "z" ) $nk .= $ch;
+        else if ( $ch >= "0" && $ch <= "9" ) $nk .= $ch;
+        else $nk .= "_";
+      }
+      $value = (string) $resource;
+      $custom["custom_".$nk] = $value;
+    }
+    return array("launch_url" => $launch_url, "custom" => $custom ) ;
+  }
+
+  function curPageURL() {
+    $pageURL = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
+             ? 'http'
+             : 'https';
+    $pageURL .= "://";
+    $pageURL .= $_SERVER['HTTP_HOST'];
+    //$pageURL .= $_SERVER['REQUEST_URI'];
+    $pageURL .= $_SERVER['PHP_SELF'];
+    return $pageURL;
+  }
+
+
+function getLastOAuthBodyBaseString() {
+    global $LastOAuthBodyBaseString;
+    return $LastOAuthBodyBaseString;
+}
+
+function getLastOAuthBodyHashInfo() {
+    global $LastOAuthBodyHashInfo;
+    return $LastOAuthBodyHashInfo;
+}
+
+
+function getOAuthKeyFromHeaders()
+{
+    $request_headers = OAuthUtil::get_headers();
+    // print_r($request_headers);
+
+    if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
+        $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
+
+        // echo("HEADER PARMS=\n");
+        // print_r($header_parameters);
+        return $header_parameters['oauth_consumer_key'];
+    }
+    return false;
+}
+
+function handleOAuthBodyPOST($oauth_consumer_key, $oauth_consumer_secret)
+{
+    $request_headers = OAuthUtil::get_headers();
+    // print_r($request_headers);
+
+    // Must reject application/x-www-form-urlencoded
+    if ($request_headers['Content-Type'] == 'application/x-www-form-urlencoded' ) {
+        throw new Exception("OAuth request body signing must not use application/x-www-form-urlencoded");
+    }
+
+    if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
+        $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
+
+        // echo("HEADER PARMS=\n");
+        // print_r($header_parameters);
+        $oauth_body_hash = $header_parameters['oauth_body_hash'];
+        // echo("OBH=".$oauth_body_hash."\n");
+    }
+
+    if ( ! isset($oauth_body_hash)  ) {
+        throw new Exception("OAuth request body signing requires oauth_body_hash body");
+    }
+
+    // Verify the message signature
+    $store = new TrivialOAuthDataStore();
+    $store->add_consumer($oauth_consumer_key, $oauth_consumer_secret);
+
+    $server = new OAuthServer($store);
+
+    $method = new OAuthSignatureMethod_HMAC_SHA1();
+    $server->add_signature_method($method);
+    $request = OAuthRequest::from_request();
+
+    global $LastOAuthBodyBaseString;
+    $LastOAuthBodyBaseString = $request->get_signature_base_string();
+    // echo($LastOAuthBodyBaseString."\n");
+
+    try {
+        $server->verify_request($request);
+    } catch (Exception $e) {
+        $message = $e->getMessage();
+        throw new Exception("OAuth signature failed: " . $message);
+    }
+
+    $postdata = file_get_contents('php://input');
+    // echo($postdata);
+
+    $hash = base64_encode(sha1($postdata, TRUE));
+
+    global $LastOAuthBodyHashInfo;
+  $LastOAuthBodyHashInfo = "hdr_hash=$oauth_body_hash body_len=".strlen($postdata)." body_hash=$hash";
+
+    if ( $hash != $oauth_body_hash ) {
+        throw new Exception("OAuth oauth_body_hash mismatch");
+    }
+
+    return $postdata;
+}
+
+function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
+{
+    $hash = base64_encode(sha1($body, TRUE));
+
+    $parms = array('oauth_body_hash' => $hash);
+
+    $test_token = '';
+    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
+    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
+
+    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
+    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
+
+    // Pass this back up "out of band" for debugging
+    global $LastOAuthBodyBaseString;
+    $LastOAuthBodyBaseString = $acc_req->get_signature_base_string();
+    // echo($LastOAuthBodyBaseString."\n");
+
+    $header = $acc_req->to_header();
+    $header = $header . "\r\nContent-Type: " . $content_type . "\r\n";
+
+    $params = array('http' => array(
+        'method' => 'POST',
+        'content' => $body,
+        'header' => $header
+        ));
+
+    $ctx = stream_context_create($params);
+    try {
+        $fp = @fopen($endpoint, 'r', false, $ctx);
+    } catch (Exception $e) {
+        $fp = false;
+    }
+    if ($fp) {
+        $response = @stream_get_contents($fp);
+    } else {  // Try CURL
+        $headers = explode("\r\n",$header);
+        $response = sendXmlOverPost($endpoint, $body, $headers);
+    }
+
+    if ($response === false) {
+        throw new Exception("Problem reading data from $endpoint, $php_errormsg");
+    }
+    return $response;
+}
+
+function sendXmlOverPost($url, $xml, $header) {
+  if ( ! function_exists('curl_init') ) return false;
+  $ch = curl_init();
+  curl_setopt($ch, CURLOPT_URL, $url);
+
+  // For xml, change the content-type.
+  curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
+
+  curl_setopt($ch, CURLOPT_POST, 1);
+  curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
+
+  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // ask for results to be returned
+/*
+  if(CurlHelper::checkHttpsURL($url)) {
+    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
+    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
+  }
+*/
+
+  // Send to remote and return data to caller.
+  $result = curl_exec($ch);
+  curl_close($ch);
+  return $result;
+}
+
+/*  $postBody = str_replace(
+      array('SOURCEDID', 'GRADE', 'OPERATION','MESSAGE'),
+      array($sourcedid, $_REQUEST['grade'], $operation, uniqid()),
+      getPOXGradeRequest());
+*/
+
+function getPOXGradeRequest() {
+    return '<?xml version = "1.0" encoding = "UTF-8"?>
+<imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
+  <imsx_POXHeader>
+    <imsx_POXRequestHeaderInfo>
+      <imsx_version>V1.0</imsx_version>
+      <imsx_messageIdentifier>MESSAGE</imsx_messageIdentifier>
+    </imsx_POXRequestHeaderInfo>
+  </imsx_POXHeader>
+  <imsx_POXBody>
+    <OPERATION>
+      <resultRecord>
+        <sourcedGUID>
+          <sourcedId>SOURCEDID</sourcedId>
+        </sourcedGUID>
+        <result>
+          <resultScore>
+            <language>en-us</language>
+            <textString>GRADE</textString>
+          </resultScore>
+        </result>
+      </resultRecord>
+    </OPERATION>
+  </imsx_POXBody>
+</imsx_POXEnvelopeRequest>';
+}
+
+/*  $postBody = str_replace(
+      array('SOURCEDID', 'OPERATION','MESSAGE'),
+      array($sourcedid, $operation, uniqid()),
+      getPOXRequest());
+*/
+function getPOXRequest() {
+    return '<?xml version = "1.0" encoding = "UTF-8"?>
+<imsx_POXEnvelopeRequest xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
+  <imsx_POXHeader>
+    <imsx_POXRequestHeaderInfo>
+      <imsx_version>V1.0</imsx_version>
+      <imsx_messageIdentifier>MESSAGE</imsx_messageIdentifier>
+    </imsx_POXRequestHeaderInfo>
+  </imsx_POXHeader>
+  <imsx_POXBody>
+    <OPERATION>
+      <resultRecord>
+        <sourcedGUID>
+          <sourcedId>SOURCEDID</sourcedId>
+        </sourcedGUID>
+      </resultRecord>
+    </OPERATION>
+  </imsx_POXBody>
+</imsx_POXEnvelopeRequest>';
+}
+
+/*     sprintf(getPOXResponse(),uniqid(),'success', "Score read successfully",$message_ref,$body);
+*/
+
+function getPOXResponse() {
+    return '<?xml version="1.0" encoding="UTF-8"?>
+<imsx_POXEnvelopeResponse xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
+    <imsx_POXHeader>
+        <imsx_POXResponseHeaderInfo>
+            <imsx_version>V1.0</imsx_version>
+            <imsx_messageIdentifier>%s</imsx_messageIdentifier>
+            <imsx_statusInfo>
+                <imsx_codeMajor>%s</imsx_codeMajor>
+                <imsx_severity>status</imsx_severity>
+                <imsx_description>%s</imsx_description>
+                <imsx_messageRefIdentifier>%s</imsx_messageRefIdentifier>
+            </imsx_statusInfo>
+        </imsx_POXResponseHeaderInfo>
+    </imsx_POXHeader>
+    <imsx_POXBody>%s
+    </imsx_POXBody>
+</imsx_POXEnvelopeResponse>';
+}
+
+function replaceResultRequest($grade, $sourcedid, $endpoint, $oauth_consumer_key, $oauth_consumer_secret) {
+    $method="POST";
+    $content_type = "application/xml";
+    $operation = 'replaceResultRequest';
+    $postBody = str_replace(
+        array('SOURCEDID', 'GRADE', 'OPERATION','MESSAGE'),
+        array($sourcedid, $grade, $operation, uniqid()),
+        getPOXGradeRequest());
+
+    $response = sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $postBody);
+    return parseResponse($response);
+}
+
+function parseResponse($response) {
+    $retval = Array();
+    try {
+        $xml = new SimpleXMLElement($response);
+        $imsx_header = $xml->imsx_POXHeader->children();
+        $parms = $imsx_header->children();
+        $status_info = $parms->imsx_statusInfo;
+        $retval['imsx_codeMajor'] = (string) $status_info->imsx_codeMajor;
+        $retval['imsx_severity'] = (string) $status_info->imsx_severity;
+        $retval['imsx_description'] = (string) $status_info->imsx_description;
+        $retval['imsx_messageIdentifier'] = (string) $parms->imsx_messageIdentifier;
+        $imsx_body = $xml->imsx_POXBody->children();
+        $operation = $imsx_body->getName();
+        $retval['response'] = $operation;
+        $parms = $imsx_body->children();
+    } catch (Exception $e) {
+        throw new Exception('Error: Unable to parse XML response' . $e->getMessage());
+    }
+
+    if ( $operation == 'readResultResponse' ) {
+       try {
+           $retval['language'] =(string) $parms->result->resultScore->language;
+           $retval['textString'] = (string) $parms->result->resultScore->textString;
+       } catch (Exception $e) {
+            throw new Exception("Error: Body parse error: ".$e->getMessage());
+       }
+    }
+    return $retval;
+}
+?>
+
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..88a5633
--- /dev/null
+++ b/package.json
@@ -0,0 +1,12 @@
+{
+  "name": "python-automarker",
+  "version": "3.0.0",
+  "description": "A Python automarker developed for COSC110 at the University of New England, Australia",
+  "dependencies": {
+    "bootstrap": "^5.1.3",
+    "brython": "^3.10.5",
+    "html5shiv": "^3.7.3",
+    "jquery": "^3.6.0",
+    "monaco-editor": "^0.32.1"
+  }
+}
diff --git a/readme.md b/readme.md
index fb50d7d..87445c7 100644
--- a/readme.md
+++ b/readme.md
@@ -2,7 +2,7 @@
 
 An [LTI](http://www.imsglobal.org/activity/learning-tools-interoperability)-based Python autograder similar to [pythonauto](https://github.com/csev/pythonauto), but using [Brython](http://http://brython.info/) to support Python 3.
 
-This is a very simple project, requiring PHP support on the server-side. All dependencies are managed by [Bower](https://bower.io/), so after cloning you should run `bower install`.
+This project requires PHP support on the server-side. All dependencies are managed by [npm](https://www.npmjs.com/), so after cloning you should run `npm install`.
 
 Before connecting through an [LMS](https://en.wikipedia.org/wiki/Learning_Management_System), you should edit `index.php` to change the `$oauth_consumer_secret` to something unique for your installation.
 
@@ -10,4 +10,4 @@ Using that consumer secret in your LMS, you can then link to `index.php?exercise
 
 Students can then click the links to launch the exercises and, once all tests have been passed, they are able to submit their code for grading. By default, grading is client-side only, though you can enable server-side checking by editing `test_code.sh` - note that you should only run this as an unprivileged user, since it allows testing of arbitrary Python code.
 
-You can also visit the exercises outside of an LMS. Testing will still work, though submission of grades is disabled. A [practical demonstration is available](https://turing.une.edu.au/~cosc110/automarker/index.php?exercise_id=1).
\ No newline at end of file
+You can also visit the exercises outside of an LMS. Testing will still work, though submission of grades is disabled. A [practical demonstration is available](https://turing.une.edu.au/~cosc110/automarker/index.php?exercise_id=1).
-- 
GitLab