Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Adding oauth body code (from Chuck), implemented outcome services (on…

…ly replaceResult tested)
  • Loading branch information...
commit b9b2e7bbf821a9b451f5ac84b7b7f00c8365ae94 1 parent aa6eca6
scriby authored September 09, 2011
158  mod/lti/OAuthBody.php
... ...
@@ -0,0 +1,158 @@
  1
+<?php
  2
+// This file is part of BasicLTI4Moodle
  3
+//
  4
+// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
  5
+// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
  6
+// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
  7
+// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
  8
+// are already supporting or going to support BasicLTI. This project Implements the consumer
  9
+// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
  10
+// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
  11
+// at the GESSI research group at UPC.
  12
+// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
  13
+// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
  14
+// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
  15
+//
  16
+// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
  17
+// of the Universitat Politecnica de Catalunya http://www.upc.edu
  18
+// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
  19
+//
  20
+// OAuthBody.php is distributed under the MIT License
  21
+//
  22
+// The MIT License
  23
+//
  24
+// Copyright (c) 2007 Andy Smith
  25
+//
  26
+// Permission is hereby granted, free of charge, to any person obtaining a copy
  27
+// of this software and associated documentation files (the "Software"), to deal
  28
+// in the Software without restriction, including without limitation the rights
  29
+// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30
+// copies of the Software, and to permit persons to whom the Software is
  31
+// furnished to do so, subject to the following conditions:
  32
+//
  33
+// The above copyright notice and this permission notice shall be included in
  34
+// all copies or substantial portions of the Software.
  35
+//
  36
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37
+// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38
+// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39
+// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40
+// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41
+// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  42
+// THE SOFTWARE.
  43
+//
  44
+// Moodle is free software: you can redistribute it and/or modify
  45
+// it under the terms of the GNU General Public License as published by
  46
+// the Free Software Foundation, either version 3 of the License, or
  47
+// (at your option) any later version.
  48
+//
  49
+// Moodle is distributed in the hope that it will be useful,
  50
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
  51
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  52
+// GNU General Public License for more details.
  53
+//
  54
+// You should have received a copy of the GNU General Public License
  55
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  56
+
  57
+require_once($CFG->dirroot . '/mod/lti/OAuth.php');
  58
+require_once($CFG->dirroot . '/mod/lti/TrivialStore.php');
  59
+
  60
+function getOAuthKeyFromHeaders() 
  61
+{
  62
+    $request_headers = OAuthUtil::get_headers();
  63
+    // print_r($request_headers);
  64
+
  65
+    if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
  66
+        $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
  67
+
  68
+        // echo("HEADER PARMS=\n");
  69
+        // print_r($header_parameters);
  70
+        return $header_parameters['oauth_consumer_key'];
  71
+    }
  72
+    return false;
  73
+}
  74
+ 
  75
+function handleOAuthBodyPOST($oauth_consumer_key, $oauth_consumer_secret) 
  76
+{
  77
+    $request_headers = OAuthUtil::get_headers();
  78
+    // print_r($request_headers);
  79
+
  80
+    // Must reject application/x-www-form-urlencoded
  81
+    if ($request_headers['Content-type'] == 'application/x-www-form-urlencoded' ) {
  82
+        throw new Exception("OAuth request body signing must not use application/x-www-form-urlencoded");
  83
+    }
  84
+
  85
+    if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
  86
+        $header_parameters = OAuthUtil::split_header($request_headers['Authorization']);
  87
+
  88
+        // echo("HEADER PARMS=\n");
  89
+        // print_r($header_parameters);
  90
+        $oauth_body_hash = $header_parameters['oauth_body_hash'];
  91
+        // echo("OBH=".$oauth_body_hash."\n");
  92
+    }
  93
+
  94
+    if ( ! isset($oauth_body_hash)  ) {
  95
+        throw new Exception("OAuth request body signing requires oauth_body_hash body");
  96
+    }
  97
+
  98
+    // Verify the message signature
  99
+    $store = new TrivialOAuthDataStore();
  100
+    $store->add_consumer($oauth_consumer_key, $oauth_consumer_secret);
  101
+
  102
+    $server = new OAuthServer($store);
  103
+
  104
+    $method = new OAuthSignatureMethod_HMAC_SHA1();
  105
+    $server->add_signature_method($method);
  106
+    $request = OAuthRequest::from_request();
  107
+
  108
+    try {
  109
+        $server->verify_request($request);
  110
+    } catch (Exception $e) {
  111
+        $message = $e->getMessage();
  112
+        throw new Exception("OAuth signature failed: " . $message);
  113
+    }
  114
+
  115
+    $postdata = file_get_contents('php://input');
  116
+    // echo($postdata);
  117
+
  118
+    $hash = base64_encode(sha1($postdata, TRUE));
  119
+
  120
+    if ( $hash != $oauth_body_hash ) {
  121
+        throw new Exception("OAuth oauth_body_hash mismatch");
  122
+    }
  123
+
  124
+    return $postdata;
  125
+}
  126
+
  127
+function sendOAuthBodyPOST($method, $endpoint, $oauth_consumer_key, $oauth_consumer_secret, $content_type, $body)
  128
+{
  129
+    $hash = base64_encode(sha1($body, TRUE));
  130
+
  131
+    $parms = array('oauth_body_hash' => $hash);
  132
+
  133
+    $test_token = '';
  134
+    $hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
  135
+    $test_consumer = new OAuthConsumer($oauth_consumer_key, $oauth_consumer_secret, NULL);
  136
+
  137
+    $acc_req = OAuthRequest::from_consumer_and_token($test_consumer, $test_token, $method, $endpoint, $parms);
  138
+    $acc_req->sign_request($hmac_method, $test_consumer, $test_token);
  139
+
  140
+    $header = $acc_req->to_header();
  141
+    $header = $header . "\r\nContent-type: " . $content_type . "\r\n";
  142
+
  143
+    $params = array('http' => array(
  144
+        'method' => 'POST',
  145
+        'content' => $body,
  146
+	'header' => $header
  147
+        ));
  148
+    $ctx = stream_context_create($params);
  149
+    $fp = @fopen($endpoint, 'rb', false, $ctx);
  150
+    if (!$fp) {
  151
+        throw new Exception("Problem with $endpoint, $php_errormsg");
  152
+    }
  153
+    $response = @stream_get_contents($fp);
  154
+    if ($response === false) {
  155
+        throw new Exception("Problem reading data from $endpoint, $php_errormsg");
  156
+    }
  157
+    return $response;
  158
+}
1,835  mod/lti/locallib.php
... ...
@@ -1,910 +1,925 @@
1  
-<?php
2  
-// This file is part of BasicLTI4Moodle
3  
-//
4  
-// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
5  
-// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
6  
-// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
7  
-// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
8  
-// are already supporting or going to support BasicLTI. This project Implements the consumer
9  
-// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
10  
-// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
11  
-// at the GESSI research group at UPC.
12  
-// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
13  
-// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
14  
-// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
15  
-//
16  
-// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
17  
-// of the Universitat Politecnica de Catalunya http://www.upc.edu
18  
-// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
19  
-//
20  
-// Moodle is free software: you can redistribute it and/or modify
21  
-// it under the terms of the GNU General Public License as published by
22  
-// the Free Software Foundation, either version 3 of the License, or
23  
-// (at your option) any later version.
24  
-//
25  
-// Moodle is distributed in the hope that it will be useful,
26  
-// but WITHOUT ANY WARRANTY; without even the implied warranty of
27  
-// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28  
-// GNU General Public License for more details.
29  
-//
30  
-// You should have received a copy of the GNU General Public License
31  
-// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
32  
-
33  
-/**
34  
- * This file contains the library of functions and constants for the basiclti module
35  
- *
36  
- * @package lti
37  
- * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
38  
- *  marc.alier@upc.edu
39  
- * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
40  
- *
41  
- * @author Marc Alier
42  
- * @author Jordi Piguillem
43  
- * @author Nikolas Galanis
44  
- *
45  
- * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46  
- */
47  
-
48  
-defined('MOODLE_INTERNAL') || die;
49  
-
50  
-require_once($CFG->dirroot.'/mod/lti/OAuth.php');
51  
-
52  
-define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
53  
-
54  
-define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
55  
-define('LTI_LAUNCH_CONTAINER_EMBED', 2);
56  
-define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
57  
-define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
58  
-
59  
-define('LTI_TOOL_STATE_ANY', 0);
60  
-define('LTI_TOOL_STATE_CONFIGURED', 1);
61  
-define('LTI_TOOL_STATE_PENDING', 2);
62  
-define('LTI_TOOL_STATE_REJECTED', 3);
63  
-
64  
-define('LTI_SETTING_NEVER', 0);
65  
-define('LTI_SETTING_ALWAYS', 1);
66  
-define('LTI_SETTING_DEFAULT', 2);
67  
-
68  
-/**
69  
- * Prints a Basic LTI activity
70  
- *
71  
- * $param int $basicltiid       Basic LTI activity id
72  
- */
73  
-function lti_view($instance, $makeobject=false) {
74  
-    global $PAGE, $CFG;
75  
-
76  
-    if(empty($instance->typeid)){
77  
-        $tool = lti_get_tool_by_url_match($instance->toolurl);
78  
-        if($tool){
79  
-            $typeid = $tool->id;
80  
-        } else {
81  
-            $typeid = null;
82  
-        }
83  
-    } else {
84  
-        $typeid = $instance->typeid;
85  
-    }
86  
-    
87  
-    if($typeid){
88  
-        $typeconfig = lti_get_type_config($typeid);
89  
-    } else {
90  
-        //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
91  
-        $typeconfig = (array)$instance;
92  
-        
93  
-        $typeconfig['sendname'] = $instance->instructorchoicesendname;
94  
-        $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
95  
-        $typeconfig['customparameters'] = $instance->instructorcustomparameters;
96  
-    }
97  
-    
98  
-    //Default the organizationid if not specified
99  
-    if(empty($typeconfig['organizationid'])){
100  
-        $urlparts = parse_url($CFG->wwwroot);
101  
-        
102  
-        $typeconfig['organizationid'] = $urlparts['host'];
103  
-    }
104  
-    
105  
-    $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
106  
-    $key = !empty($instance->resourcekey) ? $instance->resourcekey : $typeconfig['resourcekey'];
107  
-    $secret = !empty($instance->password) ? $instance->password : $typeconfig['password'];
108  
-    $orgid = $typeconfig['organizationid'];
109  
-    /* Suppress this for now - Chuck
110  
-    $orgdesc = $typeconfig['organizationdescr'];
111  
-    */
112  
-
113  
-    $course = $PAGE->course;
114  
-    $requestparams = lti_build_request($instance, $typeconfig, $course);
115  
-
116  
-    // Make sure we let the tool know what LMS they are being called from
117  
-    $requestparams["ext_lms"] = "moodle-2";
118  
-
119  
-    // Add oauth_callback to be compliant with the 1.0A spec
120  
-    $requestparams["oauth_callback"] = "about:blank";
121  
-
122  
-    $submittext = get_string('press_to_submit', 'lti');
123  
-    $parms = sign_parameters($requestparams, $endpoint, "POST", $key, $secret, $submittext, $orgid /*, $orgdesc*/);
124  
-
125  
-    $debuglaunch = ( $instance->debuglaunch == 1 );
126  
-    
127  
-    $content = post_launch_html($parms, $endpoint, $debuglaunch);
128  
-    
129  
-    echo $content;
130  
-}
131  
-
132  
-/**
133  
- * This function builds the request that must be sent to the tool producer
134  
- *
135  
- * @param object    $instance       Basic LTI instance object
136  
- * @param object    $typeconfig     Basic LTI tool configuration
137  
- * @param object    $course         Course object
138  
- *
139  
- * @return array    $request        Request details
140  
- */
141  
-function lti_build_request($instance, $typeconfig, $course) {
142  
-    global $USER, $CFG;
143  
-
144  
-    $context = get_context_instance(CONTEXT_COURSE, $course->id);
145  
-    $role = lti_get_ims_role($USER, $context);
146  
-
147  
-    $locale = $course->lang;
148  
-    if ( strlen($locale) < 1 ) {
149  
-         $locale = $CFG->lang;
150  
-    }
151  
-
152  
-    $requestparams = array(
153  
-        "resource_link_id" => $instance->id,
154  
-        "resource_link_title" => $instance->name,
155  
-        "resource_link_description" => $instance->intro,
156  
-        "user_id" => $USER->id,
157  
-        "roles" => $role,
158  
-        "context_id" => $course->id,
159  
-        "context_label" => $course->shortname,
160  
-        "context_title" => $course->fullname,
161  
-        "launch_presentation_locale" => $locale,
162  
-    );
163  
-
164  
-    $placementsecret = $typeconfig['servicesalt'];
165  
-    if ( isset($placementsecret) ) {
166  
-        $suffix = ':::' . $USER->id . ':::' . $instance->id;
167  
-        $plaintext = $placementsecret . $suffix;
168  
-        $hashsig = hash('sha256', $plaintext, false);
169  
-        $sourcedid = $hashsig . $suffix;
170  
-    }
171  
-
172  
-    if ( isset($placementsecret) &&
173  
-         ( $typeconfig['acceptgrades'] == 1 ||
174  
-         ( $typeconfig['acceptgrades'] == 2 && $instance->instructorchoiceacceptgrades == 1 ) ) ) {
175  
-        $requestparams["lis_result_sourcedid"] = $sourcedid;
176  
-        $requestparams["ext_ims_lis_basic_outcome_url"] = $CFG->wwwroot.'/mod/lti/service.php';
177  
-    }
178  
-
179  
-    if ( isset($placementsecret) &&
180  
-         ( $typeconfig['allowroster'] == 1 ||
181  
-         ( $typeconfig['allowroster'] == 2 && $instance->instructorchoiceallowroster == 1 ) ) ) {
182  
-        $requestparams["ext_ims_lis_memberships_id"] = $sourcedid;
183  
-        $requestparams["ext_ims_lis_memberships_url"] = $CFG->wwwroot.'/mod/lti/service.php';
184  
-    }
185  
-
186  
-    // Send user's name and email data if appropriate
187  
-    if ( $typeconfig['sendname'] == 1 ||
188  
-         ( $typeconfig['sendname'] == 2 && $instance->instructorchoicesendname == 1 ) ) {
189  
-        $requestparams["lis_person_name_given"] =  $USER->firstname;
190  
-        $requestparams["lis_person_name_family"] =  $USER->lastname;
191  
-        $requestparams["lis_person_name_full"] =  $USER->firstname." ".$USER->lastname;
192  
-    }
193  
-
194  
-    if ( $typeconfig['sendemailaddr'] == 1 ||
195  
-         ( $typeconfig['sendemailaddr'] == 2 && $instance->instructorchoicesendemailaddr == 1 ) ) {
196  
-        $requestparams["lis_person_contact_email_primary"] = $USER->email;
197  
-    }
198  
-
199  
-    // Concatenate the custom parameters from the administrator and the instructor
200  
-    // Instructor parameters are only taken into consideration if the administrator
201  
-    // has giver permission
202  
-    $customstr = $typeconfig['customparameters'];
203  
-    $instructorcustomstr = $instance->instructorcustomparameters;
204  
-    $custom = array();
205  
-    $instructorcustom = array();
206  
-    if ($customstr) {
207  
-        $custom = split_custom_parameters($customstr);
208  
-    }
209  
-    if (!isset($typeconfig['allowinstructorcustom']) || $typeconfig['allowinstructorcustom'] == 0) {
210  
-        $requestparams = array_merge($custom, $requestparams);
211  
-    } else {
212  
-        if ($instructorcustomstr) {
213  
-            $instructorcustom = split_custom_parameters($instructorcustomstr);
214  
-        }
215  
-        foreach ($instructorcustom as $key => $val) {
216  
-            if (array_key_exists($key, $custom)) {
217  
-                // Ignore the instructor's parameter
218  
-            } else {
219  
-                $custom[$key] = $val;
220  
-            }
221  
-        }
222  
-        $requestparams = array_merge($custom, $requestparams);
223  
-    }
224  
-
225  
-    return $requestparams;
226  
-}
227  
-
228  
-/**
229  
- * Splits the custom parameters field to the various parameters
230  
- *
231  
- * @param string $customstr     String containing the parameters
232  
- *
233  
- * @return Array of custom parameters
234  
- */
235  
-function split_custom_parameters($customstr) {
236  
-    $textlib = textlib_get_instance();
237  
-
238  
-    $lines = preg_split("/[\n;]/", $customstr);
239  
-    $retval = array();
240  
-    foreach ($lines as $line) {
241  
-        $pos = strpos($line, "=");
242  
-        if ( $pos === false || $pos < 1 ) {
243  
-            continue;
244  
-        }
245  
-        $key = trim($textlib->substr($line, 0, $pos));
246  
-        $val = trim($textlib->substr($line, $pos+1));
247  
-        $key = map_keyname($key);
248  
-        $retval['custom_'.$key] = $val;
249  
-    }
250  
-    return $retval;
251  
-}
252  
-
253  
-/**
254  
- * Used for building the names of the different custom parameters
255  
- *
256  
- * @param string $key   Parameter name
257  
- *
258  
- * @return string       Processed name
259  
- */
260  
-function map_keyname($key) {
261  
-    $textlib = textlib_get_instance();
262  
-
263  
-    $newkey = "";
264  
-    $key = $textlib->strtolower(trim($key));
265  
-    foreach (str_split($key) as $ch) {
266  
-        if ( ($ch >= 'a' && $ch <= 'z') || ($ch >= '0' && $ch <= '9') ) {
267  
-            $newkey .= $ch;
268  
-        } else {
269  
-            $newkey .= '_';
270  
-        }
271  
-    }
272  
-    return $newkey;
273  
-}
274  
-
275  
-/**
276  
- * Returns the IMS user role in a given context
277  
- *
278  
- * This function queries Moodle for an user role and
279  
- * returns the correspondant IMS role
280  
- *
281  
- * @param StdClass $user          Moodle user instance
282  
- * @param StdClass $context       Moodle context
283  
- *
284  
- * @return string                 IMS Role
285  
- *
286  
- */
287  
-function lti_get_ims_role($user, $context) {
288  
-
289  
-    $roles = get_user_roles($context, $user->id);
290  
-    $rolesname = array();
291  
-    foreach ($roles as $role) {
292  
-        $rolesname[] = $role->shortname;
293  
-    }
294  
-
295  
-    if (in_array('admin', $rolesname) || in_array('coursecreator', $rolesname)) {
296  
-        return get_string('imsroleadmin', 'lti');
297  
-    }
298  
-
299  
-    if (in_array('editingteacher', $rolesname) || in_array('teacher', $rolesname)) {
300  
-        return get_string('imsroleinstructor', 'lti');
301  
-    }
302  
-
303  
-    return get_string('imsrolelearner', 'lti');
304  
-}
305  
-
306  
-/**
307  
- * Returns configuration details for the tool
308  
- *
309  
- * @param int $typeid   Basic LTI tool typeid
310  
- *
311  
- * @return array        Tool Configuration
312  
- */
313  
-function lti_get_type_config($typeid) {
314  
-    global $DB;
315  
-
316  
-    $typeconfig = array();
317  
-    $configs = $DB->get_records('lti_types_config', array('typeid' => $typeid));
318  
-    if (!empty($configs)) {
319  
-        foreach ($configs as $config) {
320  
-            $typeconfig[$config->name] = $config->value;
321  
-        }
322  
-    }
323  
-    return $typeconfig;
324  
-}
325  
-
326  
-function lti_get_tools_by_url($url, $state){
327  
-    $domain = lti_get_domain_from_url($url);
328  
-    
329  
-    return lti_get_tools_by_domain($domain, $state);
330  
-}
331  
-
332  
-function lti_get_tools_by_domain($domain, $state = null, $courseid = null){
333  
-    global $DB, $SITE;
334  
-    
335  
-    $filters = array('tooldomain' => $domain);
336  
-    
337  
-    $statefilter = '';
338  
-    $coursefilter = '';
339  
-    
340  
-    if($state){
341  
-        $statefilter = 'AND state = :state';
342  
-    }
343  
-  
344  
-    if($courseid && $courseid != $SITE->id){
345  
-        $coursefilter = 'OR course = :courseid';
346  
-    }
347  
-    
348  
-    $query = <<<QUERY
349  
-        SELECT * FROM {lti_types}
350  
-        WHERE
351  
-            tooldomain = :tooldomain
352  
-        AND (course = :siteid $coursefilter)
353  
-        $statefilter
354  
-QUERY;
355  
-    
356  
-    return $DB->get_records_sql($query, array(
357  
-        'courseid' => $courseid, 
358  
-        'siteid' => $SITE->id, 
359  
-        'tooldomain' => $domain, 
360  
-        'state' => $state
361  
-    ));
362  
-}
363  
-
364  
-/**
365  
- * Returns all basicLTI tools configured by the administrator
366  
- *
367  
- */
368  
-function lti_filter_get_types() {
369  
-    global $DB;
370  
-
371  
-    return $DB->get_records('lti_types');
372  
-}
373  
-
374  
-function lti_get_types_for_add_instance(){
375  
-    global $DB;
376  
-    $admintypes = $DB->get_records('lti_types', array('coursevisible' => 1));
377  
-    
378  
-    $types = array();
379  
-    $types[0] = get_string('automatic', 'lti');
380  
-    
381  
-    foreach($admintypes as $type) {
382  
-        $types[$type->id] = $type->name;
383  
-    }
384  
-    
385  
-    return $types;
386  
-}
387  
-
388  
-function lti_get_domain_from_url($url){
389  
-    $matches = array();
390  
-    
391  
-    if(preg_match(LTI_URL_DOMAIN_REGEX, $url, $matches)){
392  
-        return $matches[1];
393  
-    }
394  
-}
395  
-
396  
-function lti_get_tool_by_url_match($url, $courseid = null, $state = LTI_TOOL_STATE_CONFIGURED){
397  
-    $possibletools = lti_get_tools_by_url($url, $state, $courseid);
398  
-    
399  
-    return lti_get_best_tool_by_url($url, $possibletools);
400  
-}
401  
-
402  
-function lti_get_url_thumbprint($url){
403  
-    $urlparts = parse_url(strtolower($url));
404  
-    if(!isset($urlparts['path'])){
405  
-        $urlparts['path'] = '';
406  
-    }
407  
-    
408  
-    if(substr($urlparts['host'], 0, 3) === 'www'){
409  
-        $urllparts['host'] = substr(3);
410  
-    }
411  
-    
412  
-    return $urllower = $urlparts['host'] . '/' . $urlparts['path'];
413  
-}
414  
-
415  
-function lti_get_best_tool_by_url($url, $tools){
416  
-    if(count($tools) === 0){
417  
-        return null;
418  
-    }
419  
-    
420  
-    $urllower = lti_get_url_thumbprint($url);
421  
-    
422  
-    foreach($tools as $tool){
423  
-        $tool->_matchscore = 0;
424  
-         
425  
-        $toolbaseurllower = lti_get_url_thumbprint($tool->baseurl);
426  
-        
427  
-        if($urllower === $toolbaseurllower){
428  
-            //100 points for exact match
429  
-            $tool->_matchscore += 100;
430  
-        } else if(substr($urllower, 0, strlen($toolbaseurllower)) === $toolbaseurllower){
431  
-            //50 points if it starts with the base URL
432  
-            $tool->_matchscore += 50;
433  
-        }
434  
-    }
435  
-    
436  
-    $bestmatch = array_reduce($tools, function($value, $tool){
437  
-        if($tool->_matchscore > $value->_matchscore){
438  
-            return $tool;
439  
-        } else {
440  
-            return $value;
441  
-        }
442  
-        
443  
-    }, (object)array('_matchscore' => -1));
444  
-    
445  
-    //None of the tools are suitable for this URL
446  
-    if($bestmatch->_matchscore <= 0){
447  
-        return null;
448  
-    }
449  
-    
450  
-    return $bestmatch;
451  
-}
452  
-
453  
-/**
454  
- * Prints the various configured tool types
455  
- *
456  
- */
457  
-function lti_filter_print_types() {
458  
-    global $CFG;
459  
-
460  
-    $types = lti_filter_get_types();
461  
-    if (!empty($types)) {
462  
-        echo '<ul>';
463  
-        foreach ($types as $type) {
464  
-            echo '<li>'.
465  
-            $type->name.
466  
-            '<span class="commands">'.
467  
-            '<a class="editing_update" href="typessettings.php?action=update&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Update">'.
468  
-            '<img class="iconsmall" alt="Update" src="'.$CFG->wwwroot.'/pix/t/edit.gif"/>'.
469  
-            '</a>'.
470  
-            '<a class="editing_delete" href="typessettings.php?action=delete&amp;id='.$type->id.'&amp;sesskey='.sesskey().'" title="Delete">'.
471  
-            '<img class="iconsmall" alt="Delete" src="'.$CFG->wwwroot.'/pix/t/delete.gif"/>'.
472  
-            '</a>'.
473  
-            '</span>'.
474  
-            '</li>';
475  
-
476  
-        }
477  
-        echo '</ul>';
478  
-    } else {
479  
-        echo '<div class="message">';
480  
-        echo get_string('notypes', 'lti');
481  
-        echo '</div>';
482  
-    }
483  
-}
484  
-
485  
-/**
486  
- * Delete a Basic LTI configuration
487  
- *
488  
- * @param int $id   Configuration id
489  
- */
490  
-function lti_delete_type($id) {
491  
-    global $DB;
492  
-
493  
-    //We should probably just copy the launch URL to the tool instances in this case... using a single query
494  
-    /*
495  
-    $instances = $DB->get_records('lti', array('typeid' => $id));
496  
-    foreach ($instances as $instance) {
497  
-        $instance->typeid = 0;
498  
-        $DB->update_record('lti', $instance);
499  
-    }*/
500  
-
501  
-    $DB->delete_records('lti_types', array('id' => $id));
502  
-    $DB->delete_records('lti_types_config', array('typeid' => $id));
503  
-}
504  
-
505  
-function lti_set_state_for_type($id, $state){
506  
-    global $DB;
507  
-    
508  
-    $DB->update_record('lti_types', array('id' => $id, 'state' => $state));
509  
-}
510  
-
511  
-/**
512  
- * Transforms a basic LTI object to an array
513  
- *
514  
- * @param object $ltiobject    Basic LTI object
515  
- *
516  
- * @return array Basic LTI configuration details
517  
- */
518  
-function lti_get_config($ltiobject) {
519  
-    $typeconfig = array();
520  
-    $typeconfig = (array)$ltiobject;
521  
-    $additionalconfig = lti_get_type_config($ltiobject->typeid);
522  
-    $typeconfig = array_merge($typeconfig, $additionalconfig);
523  
-    return $typeconfig;
524  
-}
525  
-
526  
-/**
527  
- *
528  
- * Generates some of the tool configuration based on the instance details
529  
- *
530  
- * @param int $id
531  
- *
532  
- * @return Instance configuration
533  
- *
534  
- */
535  
-function lti_get_type_config_from_instance($id) {
536  
-    global $DB;
537  
-
538  
-    $instance = $DB->get_record('lti', array('id' => $id));
539  
-    $config = lti_get_config($instance);
540  
-
541  
-    $type = new stdClass();
542  
-    $type->lti_fix = $id;
543  
-    if (isset($config['toolurl'])) {
544  
-        $type->lti_toolurl = $config['toolurl'];
545  
-    }
546  
-    if (isset($config['instructorchoicesendname'])) {
547  
-        $type->lti_sendname = $config['instructorchoicesendname'];
548  
-    }
549  
-    if (isset($config['instructorchoicesendemailaddr'])) {
550  
-        $type->lti_sendemailaddr = $config['instructorchoicesendemailaddr'];
551  
-    }
552  
-    if (isset($config['instructorchoiceacceptgrades'])) {
553  
-        $type->lti_acceptgrades = $config['instructorchoiceacceptgrades'];
554  
-    }
555  
-    if (isset($config['instructorchoiceallowroster'])) {
556  
-        $type->lti_allowroster = $config['instructorchoiceallowroster'];
557  
-    }
558  
-
559  
-    if (isset($config['instructorcustomparameters'])) {
560  
-        $type->lti_allowsetting = $config['instructorcustomparameters'];
561  
-    }
562  
-    return $type;
563  
-}
564  
-
565  
-/**
566  
- * Generates some of the tool configuration based on the admin configuration details
567  
- *
568  
- * @param int $id
569  
- *
570  
- * @return Configuration details
571  
- */
572  
-function lti_get_type_type_config($id) {
573  
-    global $DB;
574  
-
575  
-    $basicltitype = $DB->get_record('lti_types', array('id' => $id));
576  
-    $config = lti_get_type_config($id);
577  
-
578  
-    $type->lti_typename = $basicltitype->name;
579  
-    
580  
-    $type->lti_toolurl = $basicltitype->baseurl;
581  
-    
582  
-    if (isset($config['resourcekey'])) {
583  
-        $type->lti_resourcekey = $config['resourcekey'];
584  
-    }
585  
-    if (isset($config['password'])) {
586  
-        $type->lti_password = $config['password'];
587  
-    }
588  
-
589  
-    if (isset($config['sendname'])) {
590  
-        $type->lti_sendname = $config['sendname'];
591  
-    }
592  
-    if (isset($config['instructorchoicesendname'])){
593  
-        $type->lti_instructorchoicesendname = $config['instructorchoicesendname'];
594  
-    }
595  
-    if (isset($config['sendemailaddr'])){
596  
-        $type->lti_sendemailaddr = $config['sendemailaddr'];
597  
-    }
598  
-    if (isset($config['instructorchoicesendemailaddr'])){
599  
-        $type->lti_instructorchoicesendemailaddr = $config['instructorchoicesendemailaddr'];
600  
-    }
601  
-    if (isset($config['acceptgrades'])){
602  
-        $type->lti_acceptgrades = $config['acceptgrades'];
603  
-    }
604  
-    if (isset($config['instructorchoiceacceptgrades'])){
605  
-        $type->lti_instructorchoiceacceptgrades = $config['instructorchoiceacceptgrades'];
606  
-    }
607  
-    if (isset($config['allowroster'])){
608  
-        $type->lti_allowroster = $config['allowroster'];
609  
-    }
610  
-    if (isset($config['instructorchoiceallowroster'])){
611  
-        $type->lti_instructorchoiceallowroster = $config['instructorchoiceallowroster'];
612  
-    }
613  
-
614  
-    if (isset($config['customparameters'])) {
615  
-        $type->lti_customparameters = $config['customparameters'];
616  
-    }
617  
-
618  
-    if (isset($config['organizationid'])) {
619  
-        $type->lti_organizationid = $config['organizationid'];
620  
-    }
621  
-    if (isset($config['organizationurl'])) {
622  
-        $type->lti_organizationurl = $config['organizationurl'];
623  
-    }
624  
-    if (isset($config['organizationdescr'])) {
625  
-        $type->lti_organizationdescr = $config['organizationdescr'];
626  
-    }
627  
-    if (isset($config['launchcontainer'])) {
628  
-        $type->lti_launchcontainer = $config['launchcontainer'];
629  
-    }
630  
-    
631  
-    if (isset($config['coursevisible'])) {
632  
-        $type->lti_coursevisible = $config['coursevisible'];
633  
-    }
634  
-    
635  
-    if (isset($config['debuglaunch'])) {
636  
-        $type->lti_debuglaunch = $config['debuglaunch'];
637  
-    }
638  
-    
639  
-    if (isset($config['module_class_type'])) {
640  
-            $type->lti_module_class_type = $config['module_class_type'];
641  
-    }
642  
-
643  
-    return $type;
644  
-}
645  
-
646  
-function lti_prepare_type_for_save($type, $config){
647  
-    $type->baseurl = $config->lti_toolurl;
648  
-    $type->tooldomain = lti_get_domain_from_url($config->lti_toolurl);
649  
-    $type->name = $config->lti_typename;
650  
-    
651  
-    $type->coursevisible = !empty($config->lti_coursevisible) ? $config->lti_coursevisible : 0;
652  
-    $config->lti_coursevisible = $type->coursevisible;
653  
-    
654  
-    $type->timemodified = time();
655  
-    
656  
-    unset ($config->lti_typename);
657  
-    unset ($config->lti_toolurl);
658  
-}
659  
-
660  
-function lti_update_type($type, $config){
661  
-    global $DB;
662  
-    
663  
-    lti_prepare_type_for_save($type, $config);
664  
-    
665  
-    if ($DB->update_record('lti_types', $type)) {
666  
-        foreach ($config as $key => $value) {
667  
-            if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
668  
-                $record = new StdClass();
669  
-                $record->typeid = $type->id;
670  
-                $record->name = substr($key, 4);
671  
-                $record->value = $value;
672  
-                
673  
-                lti_update_config($record);
674  
-            }
675  
-        }
676  
-    }
677  
-}
678  
-
679  
-function lti_add_type($type, $config){
680  
-    global $USER, $SITE, $DB;
681  
-    
682  
-    lti_prepare_type_for_save($type, $config);
683  
-    
684  
-    if(!isset($type->state)){
685  
-        $type->state = LTI_TOOL_STATE_PENDING;
686  
-    }
687  
-    
688  
-    if(!isset($type->timecreated)){
689  
-        $type->timecreated = time();
690  
-    }
691  
-    
692  
-    if(!isset($type->createdby)){
693  
-        $type->createdby = $USER->id;
694  
-    }
695  
-    
696  
-    if(!isset($type->course)){
697  
-        $type->course = $SITE->id;
698  
-    }
699  
-    
700  
-    //Create a salt value to be used for signing passed data to extension services
701  
-    $config->lti_servicesalt = uniqid('', true);
702  
-
703  
-    $id = $DB->insert_record('lti_types', $type);
704  
-
705  
-    if ($id) {
706  
-        foreach ($config as $key => $value) {
707  
-            if (substr($key, 0, 4)=='lti_' && !is_null($value)) {
708  
-                $record = new StdClass();
709  
-                $record->typeid = $id;
710  
-                $record->name = substr($key, 4);
711  
-                $record->value = $value;
712  
-
713  
-                lti_add_config($record);
714  
-            }
715  
-        }
716  
-    }
717  
-}
718  
-
719  
-/**
720  
- * Add a tool configuration in the database
721  
- *
722  
- * @param $config   Tool configuration
723  
- *
724  
- * @return int Record id number
725  
- */
726  
-function lti_add_config($config) {
727  
-    global $DB;
728  
-
729  
-    return $DB->insert_record('lti_types_config', $config);
730  
-}
731  
-
732  
-/**
733  
- * Updates a tool configuration in the database
734  
- *
735  
- * @param $config   Tool configuration
736  
- *
737  
- * @return Record id number
738  
- */
739  
-function lti_update_config($config) {
740  
-    global $DB;
741  
-
742  
-    $return = true;
743  
-    $old = $DB->get_record('lti_types_config', array('typeid' => $config->typeid, 'name' => $config->name));
744  
-    
745  
-    if ($old) {
746  
-        $config->id = $old->id;
747  
-        $return = $DB->update_record('lti_types_config', $config);
748  
-    } else {
749  
-        $return = $DB->insert_record('lti_types_config', $config);
750  
-    }
751  
-    return $return;
752  
-}
753  
-
754  
-/**
755  
- * Signs the petition to launch the external tool using OAuth
756  
- *
757  
- * @param $oldparms     Parameters to be passed for signing
758  
- * @param $endpoint     url of the external tool
759  
- * @param $method       Method for sending the parameters (e.g. POST)
760  
- * @param $oauth_consumoer_key          Key
761  
- * @param $oauth_consumoer_secret       Secret
762  
- * @param $submittext  The text for the submit button
763  
- * @param $orgid       LMS name
764  
- * @param $orgdesc     LMS key
765  
- */
766  
-function sign_parameters($oldparms, $endpoint, $method, $oauthconsumerkey, $oauthconsumersecret, $submittext, $orgid /*, $orgdesc*/) {
767  
-    global $lastbasestring;
768  
-    $parms = $oldparms;
769  
-    $parms["lti_version"] = "LTI-1p0";
770  
-    $parms["lti_message_type"] = "basic-lti-launch-request";
771  
-    if ( $orgid ) {
772  
-        $parms["tool_consumer_instance_guid"] = $orgid;
773  
-    }
774  
-    /* Suppress this for now - Chuck
775  
-    if ( $orgdesc ) $parms["tool_consumer_instance_description"] = $orgdesc;
776  
-    */
777  
-    $parms["ext_submit"] = $submittext;
778  
-
779  
-    $testtoken = '';
780  
-
781  
-    $hmacmethod = new OAuthSignatureMethod_HMAC_SHA1();
782  
-    $testconsumer = new OAuthConsumer($oauthconsumerkey, $oauthconsumersecret, null);
783  
-
784  
-    $accreq = OAuthRequest::from_consumer_and_token($testconsumer, $testtoken, $method, $endpoint, $parms);
785  
-    $accreq->sign_request($hmacmethod, $testconsumer, $testtoken);
786  
-
787  
-    // Pass this back up "out of band" for debugging
788  
-    $lastbasestring = $accreq->get_signature_base_string();
789  
-
790  
-    $newparms = $accreq->get_parameters();
791  
-
792  
-    return $newparms;
793  
-}
794  
-
795  
-/**
796  
- * Posts the launch petition HTML
797  
- *
798  
- * @param $newparms     Signed parameters
799  
- * @param $endpoint     URL of the external tool
800  
- * @param $debug        Debug (true/false)
801  
- */
802  
-function post_launch_html($newparms, $endpoint, $debug=false) {
803  
-    global $lastbasestring;
804  
-    
805  
-    $r = "<form action=\"".$endpoint."\" name=\"ltiLaunchForm\" id=\"ltiLaunchForm\" method=\"post\" encType=\"application/x-www-form-urlencoded\">\n";
806  
-    
807  
-    $submittext = $newparms['ext_submit'];
808  
-
809  
-    // Contruct html for the launch parameters
810  
-    foreach ($newparms as $key => $value) {
811  
-        $key = htmlspecialchars($key);
812  
-        $value = htmlspecialchars($value);
813  
-        if ( $key == "ext_submit" ) {
814  
-            $r .= "<input type=\"submit\" name=\"";
815  
-        } else {
816  
-            $r .= "<input type=\"hidden\" name=\"";
817  
-        }
818  
-        $r .= $key;
819  
-        $r .= "\" value=\"";
820  
-        $r .= $value;
821  
-        $r .= "\"/>\n";
822  
-    }
823  
-
824  
-    if ( $debug ) {
825  
-        $r .= "<script language=\"javascript\"> \n";
826  
-        $r .= "  //<![CDATA[ \n";
827  
-        $r .= "function basicltiDebugToggle() {\n";
828  
-        $r .= "    var ele = document.getElementById(\"basicltiDebug\");\n";
829  
-        $r .= "    if(ele.style.display == \"block\") {\n";
830  
-        $r .= "        ele.style.display = \"none\";\n";
831  
-        $r .= "    }\n";
832  
-        $r .= "    else {\n";
833  
-        $r .= "        ele.style.display = \"block\";\n";
834  
-        $r .= "    }\n";
835  
-        $r .= "} \n";
836  
-        $r .= "  //]]> \n";
837  
-        $r .= "</script>\n";
838  
-        $r .= "<a id=\"displayText\" href=\"javascript:basicltiDebugToggle();\">";
839  
-        $r .= get_string("toggle_debug_data", "lti")."</a>\n";
840  
-        $r .= "<div id=\"basicltiDebug\" style=\"display:none\">\n";
841  
-        $r .=  "<b>".get_string("basiclti_endpoint", "lti")."</b><br/>\n";
842  
-        $r .= $endpoint . "<br/>\n&nbsp;<br/>\n";
843  
-        $r .=  "<b>".get_string("basiclti_parameters", "lti")."</b><br/>\n";
844  
-        foreach ($newparms as $key => $value) {
845  
-            $key = htmlspecialchars($key);
846  
-            $value = htmlspecialchars($value);
847  
-            $r .= "$key = $value<br/>\n";
848  
-        }
849  
-        $r .= "&nbsp;<br/>\n";
850  
-        $r .= "<p><b>".get_string("basiclti_base_string", "lti")."</b><br/>\n".$lastbasestring."</p>\n";
851  
-        $r .= "</div>\n";
852  
-    }
853  
-    $r .= "</form>\n";
854  
-
855  
-    if ( ! $debug ) {
856  
-        $ext_submit = "ext_submit";
857  
-        $ext_submit_text = $submittext;
858  
-        $r .= " <script type=\"text/javascript\"> \n" .
859  
-            "  //<![CDATA[ \n" .
860  
-            "    document.getElementById(\"ltiLaunchForm\").style.display = \"none\";\n" .
861  
-            "    nei = document.createElement('input');\n" .
862  
-            "    nei.setAttribute('type', 'hidden');\n" .
863  
-            "    nei.setAttribute('name', '".$ext_submit."');\n" .
864  
-            "    nei.setAttribute('value', '".$ext_submit_text."');\n" .
865  
-            "    document.getElementById(\"ltiLaunchForm\").appendChild(nei);\n" .
866  
-            "    document.ltiLaunchForm.submit(); \n" .
867  
-            "  //]]> \n" .
868  
-            " </script> \n";
869  
-    }
870  
-    return $r;
871  
-}
872  
-
873  
-/**
874  
- * Returns a link with info about the state of the basiclti submissions
875  
- *
876  
- * This is used by view_header to put this link at the top right of the page.
877  
- * For teachers it gives the number of submitted assignments with a link
878  
- * For students it gives the time of their submission.
879  
- * This will be suitable for most assignment types.
880  
- *
881  
- * @global object
882  
- * @global object
883  
- * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
884  
- * @return string
885  
- */
886  
-function submittedlink($cm, $allgroups=false) {
887  
-    global $CFG;
888  
-
889  
-    $submitted = '';
890  
-    $urlbase = "{$CFG->wwwroot}/mod/lti/";
891  
-
892  
-    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
893  
-    if (has_capability('mod/lti:grade', $context)) {
894  
-        if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
895  
-            $group = 0;
896  
-        } else {
897  
-            $group = groups_get_activity_group($cm);
898  
-        }
899  
-
900  
-        $submitted = '<a href="'.$urlbase.'submissions.php?id='.$cm->id.'">'.
901  
-                     get_string('viewsubmissions', 'lti').'</a>';
902  
-    } else {
903  
-        if (isloggedin()) {
904  
-            // TODO Insert code for students if needed
905  
-        }
906  
-    }
907  
-
908  
-    return $submitted;
909  
-}
910  
-
  1
+<?php
  2
+// This file is part of BasicLTI4Moodle
  3
+//
  4
+// BasicLTI4Moodle is an IMS BasicLTI (Basic Learning Tools for Interoperability)
  5
+// consumer for Moodle 1.9 and Moodle 2.0. BasicLTI is a IMS Standard that allows web
  6
+// based learning tools to be easily integrated in LMS as native ones. The IMS BasicLTI
  7
+// specification is part of the IMS standard Common Cartridge 1.1 Sakai and other main LMS
  8
+// are already supporting or going to support BasicLTI. This project Implements the consumer
  9
+// for Moodle. Moodle is a Free Open source Learning Management System by Martin Dougiamas.
  10
+// BasicLTI4Moodle is a project iniciated and leaded by Ludo(Marc Alier) and Jordi Piguillem
  11
+// at the GESSI research group at UPC.
  12
+// SimpleLTI consumer for Moodle is an implementation of the early specification of LTI
  13
+// by Charles Severance (Dr Chuck) htp://dr-chuck.com , developed by Jordi Piguillem in a
  14
+// Google Summer of Code 2008 project co-mentored by Charles Severance and Marc Alier.
  15
+//
  16
+// BasicLTI4Moodle is copyright 2009 by Marc Alier Forment, Jordi Piguillem and Nikolas Galanis
  17
+// of the Universitat Politecnica de Catalunya http://www.upc.edu
  18
+// Contact info: Marc Alier Forment granludo @ gmail.com or marc.alier @ upc.edu
  19
+//
  20
+// Moodle is free software: you can redistribute it and/or modify
  21
+// it under the terms of the GNU General Public License as published by
  22
+// the Free Software Foundation, either version 3 of the License, or
  23
+// (at your option) any later version.
  24
+//
  25
+// Moodle is distributed in the hope that it will be useful,
  26
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
  27
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28
+// GNU General Public License for more details.
  29
+//
  30
+// You should have received a copy of the GNU General Public License
  31
+// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  32
+
  33
+/**
  34
+ * This file contains the library of functions and constants for the basiclti module
  35
+ *
  36
+ * @package lti
  37
+ * @copyright 2009 Marc Alier, Jordi Piguillem, Nikolas Galanis
  38
+ *  marc.alier@upc.edu
  39
+ * @copyright 2009 Universitat Politecnica de Catalunya http://www.upc.edu
  40
+ *
  41
+ * @author Marc Alier
  42
+ * @author Jordi Piguillem
  43
+ * @author Nikolas Galanis
  44
+ *
  45
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46
+ */
  47
+
  48
+defined('MOODLE_INTERNAL') || die;
  49
+
  50
+require_once($CFG->dirroot.'/mod/lti/OAuth.php');
  51
+
  52
+define('LTI_URL_DOMAIN_REGEX', '/(?:https?:\/\/)?(?:www\.)?([^\/]+)(?:\/|$)/i');
  53
+
  54
+define('LTI_LAUNCH_CONTAINER_DEFAULT', 1);
  55
+define('LTI_LAUNCH_CONTAINER_EMBED', 2);
  56
+define('LTI_LAUNCH_CONTAINER_EMBED_NO_BLOCKS', 3);
  57
+define('LTI_LAUNCH_CONTAINER_WINDOW', 4);
  58
+
  59
+define('LTI_TOOL_STATE_ANY', 0);
  60
+define('LTI_TOOL_STATE_CONFIGURED', 1);
  61
+define('LTI_TOOL_STATE_PENDING', 2);
  62
+define('LTI_TOOL_STATE_REJECTED', 3);
  63
+
  64
+define('LTI_SETTING_NEVER', 0);
  65
+define('LTI_SETTING_ALWAYS', 1);
  66
+define('LTI_SETTING_DEFAULT', 2);
  67
+
  68
+/**
  69
+ * Prints a Basic LTI activity
  70
+ *
  71
+ * $param int $basicltiid       Basic LTI activity id
  72
+ */
  73
+function lti_view($instance, $makeobject=false) {
  74
+    global $PAGE, $CFG;
  75
+
  76
+    if(empty($instance->typeid)){
  77
+        $tool = lti_get_tool_by_url_match($instance->toolurl);
  78
+        if($tool){
  79
+            $typeid = $tool->id;
  80
+        } else {
  81
+            $typeid = null;
  82
+        }
  83
+    } else {
  84
+        $typeid = $instance->typeid;
  85
+    }
  86
+    
  87
+    if($typeid){
  88
+        $typeconfig = lti_get_type_config($typeid);
  89
+    } else {
  90
+        //There is no admin configuration for this tool. Use configuration in the lti instance record plus some defaults.
  91
+        $typeconfig = (array)$instance;
  92
+        
  93
+        $typeconfig['sendname'] = $instance->instructorchoicesendname;
  94
+        $typeconfig['sendemailaddr'] = $instance->instructorchoicesendemailaddr;
  95
+        $typeconfig['customparameters'] = $instance->instructorcustomparameters;
  96
+    }
  97
+    
  98
+    //Default the organizationid if not specified
  99
+    if(empty($typeconfig['organizationid'])){
  100
+        $urlparts = parse_url($CFG->wwwroot);
  101
+        
  102
+        $typeconfig['organizationid'] = $urlparts['host'];
  103
+    }
  104
+    
  105
+    $endpoint = !empty($instance->toolurl) ? $instance->toolurl : $typeconfig['toolurl'];
  106
+    $key = !empty($instance->resourcekey) ? $instance->resourcekey : $typeconfig['resourcekey'];
  107
+    $secret = !empty($instance->password) ? $instance->password : $typeconfig['password'];
  108
+    $orgid = $typeconfig['organizationid'];
  109
+    /* Suppress this for now - Chuck
  110
+    $orgdesc = $typeconfig['organizationdescr'];
  111
+    */
  112
+
  113
+    $course = $PAGE->course;
  114
+    $requestparams = lti_build_request($instance, $typeconfig, $course);
  115
+
  116
+    // Make sure we let the tool know what LMS they are being called from
  117
+    $requestparams["ext_lms"] = "moodle-2";
  118
+
  119
+    // Add oauth_callback to be compliant with the 1.0A spec
  120
+    $requestparams["oauth_callback"] = "about:blank";
  121
+
  122
+    $submittext = get_string('press_to_submit', 'lti');
  123
+    $parms = sign_parameters($requestparams, $endpoint, "POST", $key, $secret, $submittext, $orgid /*, $orgdesc*/);