-
Notifications
You must be signed in to change notification settings - Fork 2
/
xapi.php
119 lines (92 loc) · 2.6 KB
/
xapi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
/**
* Xapi.
*/
class Xapi {
/**
* Constructor.
*/
public function __construct($endpoint, $username, $password) {
$this->endpoint=$endpoint;
$this->username=$username;
$this->password=$password;
}
/**
* Get statements.
*
* Spec for params:
*
* https://github.com/adlnet/xAPI-Spec/blob/master/xAPI.md#stmtapiget
*/
public function getStatements($params=NULL) {
if (!$params)
$params=array();
$url=$this->endpoint;
if (substr($url,-1)!="/")
$url.="/";
$url.="statements";
if (isset($params["agentEmail"])) {
$params["agent"]=json_encode(array(
"mbox"=>"mailto:".$params["agentEmail"]
));
unset($params["agentEmail"]);
}
$query=http_build_query($params);
/*print_r($query);
exit;*/
$url.="?".$query;
$headers=array(
"Content-Type: application/json",
"X-Experience-API-Version: 1.0.1",
);
$userpwd=$this->username.":".$this->password;
$curl=curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl,CURLOPT_USERPWD,$userpwd);
$res=curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code!=200) {
echo $res;
throw new Exception("Unable to connect to xapi",$code);
}
$decoded=json_decode($res,TRUE);
if (!$decoded || !array_key_exists("statements",$decoded))
throw new Exception("Bad response from xapi endpoint.");
return $decoded["statements"];
}
/**
* Put statement.
*/
public function putStatement($statement) {
$content=json_encode($statement);
$url=$this->endpoint;
if (substr($url,-1)!="/")
$url.="/";
$url.="statements";
$headers=array(
"Content-Type: application/json",
"X-Experience-API-Version: 1.0.1",
);
$userpwd=$this->username.":".$this->password;
$curl=curl_init();
curl_setopt($curl,CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($curl,CURLOPT_HTTPHEADER,$headers);
curl_setopt($curl,CURLOPT_USERPWD,$userpwd);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$content);
$res=curl_exec($curl);
$decoded=json_decode($res,TRUE);
$code=curl_getinfo($curl,CURLINFO_HTTP_CODE);
if ($code!=200 || sizeof($decoded)!=1 || strlen($decoded[0])!=36) {
//throw new Exception($res);
if (in_array("message",$decoded) && $decoded["message"])
throw new Exception($decoded["message"]);
if (is_string($res))
throw new Exception($res);
throw new Exception("Unknown error");
}
}
}