024f04bfed4bf0bce17388b592f25fbd7d7facdb
[atutor.git] / mods / basiclti / launch / ims-blti / blti.php
1 <?php
2
3 require_once 'OAuth.php';
4
5 // Returns true if this is a Basic LTI message
6 // with minimum values to meet the protocol
7 function is_basic_lti_request() {
8    $good_message_type = $_REQUEST["lti_message_type"] == "basic-lti-launch-request";
9    $good_lti_version = $_REQUEST["lti_version"] == "LTI-1p0";
10    $resource_link_id = $_REQUEST["resource_link_id"];
11    if ($good_message_type and $good_lti_version and isset($resource_link_id) ) return(true);
12    return false;
13 }
14
15 /**
16  * A Trivial memory-based store - no support for tokens
17  */
18 class TrivialOAuthDataStore extends OAuthDataStore {
19     private $consumers = array();
20
21     function add_consumer($consumer_key, $consumer_secret) {
22         $this->consumers[$consumer_key] = $consumer_secret;
23     }
24
25     function lookup_consumer($consumer_key) {
26         if ( strpos($consumer_key, "http://" ) === 0 ) {
27             $consumer = new OAuthConsumer($consumer_key,"secret", NULL);
28             return $consumer;
29         }
30         if ( $this->consumers[$consumer_key] ) {
31             $consumer = new OAuthConsumer($consumer_key,$this->consumers[$consumer_key], NULL);
32             return $consumer;
33         }
34         return NULL;
35     }
36
37     function lookup_token($consumer, $token_type, $token) {
38         return new OAuthToken($consumer, "");
39     }
40
41     // Return NULL if the nonce has not been used
42     // Return $nonce if the nonce was previously used
43     function lookup_nonce($consumer, $token, $nonce, $timestamp) {
44         // Should add some clever logic to keep nonces from
45         // being reused - for no we are really trusting
46         // that the timestamp will save us
47         return NULL;
48     }
49
50     function new_request_token($consumer) {
51         return NULL;
52     }
53
54     function new_access_token($token, $consumer) {
55         return NULL;
56     }
57 }
58
59
60 // Basic LTI Class that does the setup and provides utility
61 // functions
62 class BLTI {
63
64     public $valid = false;
65     public $complete = false;
66     public $message = false;
67     public $basestring = false;
68     public $info = false;
69     public $row = false;
70     public $context_id = false;  // Override context_id
71
72     function __construct($parm=false, $usesession=true, $doredirect=true) {
73
74         // If this request is not an LTI Launch, either
75         // give up or try to retrieve the context from session
76         if ( ! is_basic_lti_request() ) {
77             if ( $usesession === false ) return;  
78             if ( strlen(session_id()) > 0 ) {
79                 $row = $_SESSION['_basiclti_lti_row'];
80                 if ( isset($row) ) $this->row = $row;
81                 $context_id = $_SESSION['_basiclti_lti_context_id'];
82                 if ( isset($context_id) ) $this->context_id = $context_id;
83                 $info = $_SESSION['_basic_lti_context'];
84                 if ( isset($info) ) {
85                     $this->info = $info;
86                     $this->valid = true;
87                     return;
88                 }
89                 $this->message = "Could not find context in session";
90                 return;
91             }
92             $this->message = "Session not available";
93             return;
94         }
95
96         // Insure we have a valid launch
97         if ( empty($_REQUEST["oauth_consumer_key"]) ) {
98             $this->message = "Missing oauth_consumer_key in request";
99             return;
100         }
101         $oauth_consumer_key = $_REQUEST["oauth_consumer_key"];
102
103         // Find the secret - either form the parameter as a string or
104         // look it up in a database from parameters we are given
105         $secret = false;
106         $row = false;
107         if ( is_string($parm) ) {
108             $secret = $parm;
109         } else if ( ! is_array($parm) ) {
110             $this->message = "Constructor requires a secret or database information.";
111             return;
112         } else {
113                 global $addslashes;
114             $sql = 'SELECT * FROM '.$parm['table'].' WHERE '.
115                 ($parm['key_column'] ? $parm['key_column'] : 'oauth_consumer_key').
116                 '='.
117                 "'".$addslashes($oauth_consumer_key)."'";
118             $result = mysql_query($sql);
119             $num_rows = mysql_num_rows($result);
120             if ( $num_rows != 1 ) {
121                 $this->message = "Your consumer is not authorized oauth_consumer_key=".$oauth_consumer_key;
122                 return;
123             } else {
124                 while ($row = mysql_fetch_assoc($result)) {
125                     $secret = $row[$parms['secret_column']?$parms['secret_column']:'secret'];
126                     $context_id = $row[$parms['context_column']?$parms['context_column']:'context_id'];
127                     if ( $context_id ) $this->context_id = $context_id;
128                     $this->row = $row;
129                     break;
130                 }
131                 if ( ! is_string($secret) ) {
132                     $this->message = "Could not retrieve secret oauth_consumer_key=".$oauth_consumer_key;
133                     return;
134                 }
135             }
136         }
137
138         // Verify the message signature
139         $store = new TrivialOAuthDataStore();
140         $store->add_consumer($oauth_consumer_key, $secret);
141
142         $server = new OAuthServer($store);
143
144         $method = new OAuthSignatureMethod_HMAC_SHA1();
145         $server->add_signature_method($method);
146         $request = OAuthRequest::from_request();
147         
148         $this->basestring = $request->get_signature_base_string();
149
150         try {
151             $server->verify_request($request);
152             $this->valid = true;
153         } catch (Exception $e) {
154             $this->message = $e->getMessage();
155             return;
156         }
157
158         // Store the launch information in the session for later
159         $newinfo = array();
160         foreach($_POST as $key => $value ) {
161             if ( $key == "basiclti_submit" ) continue;
162             if ( strpos($key, "oauth_") === false ) {
163                 $newinfo[$key] = $value;
164                 continue;
165             }
166             if ( $key == "oauth_consumer_key" ) {
167                 $newinfo[$key] = $value;
168                 continue;
169             }
170         }
171
172         $this->info = $newinfo;
173         if ( $usesession == true and strlen(session_id()) > 0 ) {
174              $_SESSION['_basic_lti_context'] = $this->info;
175              unset($_SESSION['_basiclti_lti_row']);
176              unset($_SESSION['_basiclti_lti_context_id']);
177              if ( $this->row ) $_SESSION['_basiclti_lti_row'] = $this->row;
178              if ( $this->context_id ) $_SESSION['_basiclti_lti_context_id'] = $this->context_id;
179         }
180
181         if ( $this->valid && $doredirect ) {
182             $this->redirect();
183             $this->complete = true;
184         }
185     }
186
187     function addSession($location) {
188         if ( ini_get('session.use_cookies') == 0 ) {
189             if ( strpos($location,'?') > 0 ) {
190                $location = $location . '&';
191             } else {
192                $location = $location . '?';
193             }
194             $location = $location . session_name() . '=' . session_id();
195         }
196         return $location;
197     }
198
199     function isInstructor() {
200         $roles = $this->info['roles'];
201         $roles = strtolower($roles);
202         if ( ! ( strpos($roles,"instructor") === false ) ) return true;
203         if ( ! ( strpos($roles,"administrator") === false ) ) return true;
204         return false;
205     }
206
207     function getUserEmail() {
208         $email = $this->info['lis_person_contact_email_primary'];
209         if ( strlen($email) > 0 ) return $email;
210         # Sakai Hack
211         $email = $this->info['lis_person_contact_emailprimary'];
212         if ( strlen($email) > 0 ) return $email;
213         return false;
214     }
215
216     function getUserShortName() {
217         $email = $this->getUserEmail();
218         $givenname = $this->info['lis_person_name_given'];
219         $familyname = $this->info['lis_person_name_family'];
220         $fullname = $this->info['lis_person_name_full'];
221         if ( strlen($email) > 0 ) return $email;
222         if ( strlen($givenname) > 0 ) return $givenname;
223         if ( strlen($familyname) > 0 ) return $familyname;
224         return $this->getUserName();
225     }
226   
227     function getUserName() {
228         $givenname = $this->info['lis_person_name_given'];
229         $familyname = $this->info['lis_person_name_family'];
230         $fullname = $this->info['lis_person_name_full'];
231         if ( strlen($fullname) > 0 ) return $fullname;
232         if ( strlen($familyname) > 0 and strlen($givenname) > 0 ) return $givenname + $familyname;
233         if ( strlen($givenname) > 0 ) return $givenname;
234         if ( strlen($familyname) > 0 ) return $familyname;
235         return $this->getUserEmail();
236     }
237
238     function getUserKey() {
239         $oauth = $this->info['oauth_consumer_key'];
240         $id = $this->info['user_id'];
241         if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
242         return false;
243     }
244
245     function getUserImage() {
246         $image = $this->info['user_image'];
247         if ( strlen($image) > 0 ) return $image;
248         $email = $this->getUserEmail();
249         if ( $email === false ) return false;
250         $size = 40;
251         $grav_url = $_SERVER['HTTPS'] ? 'https://' : 'http://';
252         $grav_url = $grav_url . "www.gravatar.com/avatar.php?gravatar_id=".md5( strtolower($email) )."&size=".$size;
253         return $grav_url;
254     }
255
256     function getResourceKey() {
257         $oauth = $this->info['oauth_consumer_key'];
258         $id = $this->info['resource_link_id'];
259         if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
260         return false;
261     }
262
263     function getResourceTitle() {
264         $title = $this->info['resource_link_title'];
265         if ( strlen($title) > 0 ) return $title;
266         return false;
267     }
268
269     function getConsumerKey() {
270         $oauth = $this->info['oauth_consumer_key'];
271         return $oauth;
272     }
273
274     function getCourseKey() {
275         if ( $this->context_id ) return $this->context_id;
276         $oauth = $this->info['oauth_consumer_key'];
277         $id = $this->info['context_id'];
278         if ( strlen($id) > 0 and strlen($oauth) > 0 ) return $oauth . ':' . $id;
279         return false;
280     }
281
282     function getCourseName() {
283         $label = $this->info['context_label'];
284         $title = $this->info['context_title'];
285         $id = $this->info['context_id'];
286         if ( strlen($label) > 0 ) return $label;
287         if ( strlen($title) > 0 ) return $title;
288         if ( strlen($id) > 0 ) return $id;
289         return false;
290     }
291
292     // TODO: Add javasript version if headers are already sent
293     function redirect() {
294             $host = $_SERVER['HTTP_HOST'];
295             $uri = $_SERVER['PHP_SELF'];
296             $location = $_SERVER['HTTPS'] ? 'https://' : 'http://';
297             $location = $location . $host . $uri;
298             $location = $this->addSession($location);
299             header("Location: $location");
300     }
301
302     function dump() { 
303         if ( ! $this->valid or $this->info == false ) return "Context not valid\n";
304         $ret = "";
305         if ( $this->isInstructor() ) {
306             $ret .= "isInstructor() = true\n";
307         } else {
308             $ret .= "isInstructor() = false\n";
309         }
310         $ret .= "getUserKey() = ".$this->getUserKey()."\n";
311         $ret .= "getUserEmail() = ".$this->getUserEmail()."\n";
312         $ret .= "getUserShortName() = ".$this->getUserShortName()."\n";
313         $ret .= "getUserName() = ".$this->getUserName()."\n";
314         $ret .= "getUserImage() = ".$this->getUserImage()."\n";
315         $ret .= "getResourceKey() = ".$this->getResourceKey()."\n";
316         $ret .= "getResourceTitle() = ".$this->getResourceTitle()."\n";
317         $ret .= "getCourseName() = ".$this->getCourseName()."\n";
318         $ret .= "getCourseKey() = ".$this->getCourseKey()."\n";
319         $ret .= "getConsumerKey() = ".$this->getConsumerKey()."\n";
320         return $ret;
321     }
322
323 }
324
325 ?>