-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathOpenTokSDK.php
executable file
·210 lines (178 loc) · 8.84 KB
/
OpenTokSDK.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
<?PHP
/**
* OpenTok PHP Library
* http://www.tokbox.com/
*
* Copyright (c) 2011, TokBox, Inc.
* 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.
*/
require_once 'API_Config.php';
require_once 'OpenTokSession.php';
require_once 'OpenTokArchive.php';
//Generic OpenTok exception. Read the message to get more details
class OpenTokException extends Exception { };
//OpenTok exception related to authentication. Most likely an issue with your API key or secret
class AuthException extends OpenTokException { };
//OpenTok exception related to the HTTP request. Most likely due to a server error. (HTTP 500 error)
class RequestException extends OpenTokException { };
class RoleConstants {
const SUBSCRIBER = "subscriber"; //Can only subscribe
const PUBLISHER = "publisher"; //Can publish, subscribe, and signal
const MODERATOR = "moderator"; //Can do the above along with forceDisconnect and forceUnpublish
};
class OpenTokSDK {
private $api_key;
private $api_secret;
public function __construct($api_key, $api_secret) {
$this->api_key = $api_key;
$this->api_secret = trim($api_secret);
}
/** - Generate a token
*
* $session_id - If session_id is not blank, this token can only join the call with the specified session_id.
* $role - One of the constants defined in RoleConstants. Default is publisher, look in the documentation to learn more about roles.
* $expire_time - Optional timestamp to change when the token expires. See documentation on token for details.
*/
public function generate_token($session_id='', $role='', $expire_time=NULL, $connection_data='') {
$create_time = time();
$nonce = microtime(true) . mt_rand();
if(!$role) {
$role = RoleConstants::PUBLISHER;
} else if (!in_array($role, array(RoleConstants::SUBSCRIBER,
RoleConstants::PUBLISHER, RoleConstants::MODERATOR))) {
throw new OpenTokException("unknown role $role");
}
$data_string = "session_id=$session_id&create_time=$create_time&role=$role&nonce=$nonce";
if(!is_null($expire_time)) {
if(!is_numeric($expire_time))
throw new OpenTokException("Expire time must be a number");
if($expire_time < $create_time)
throw new OpenTokException("Expire time must be in the future");
if($expire_time > $create_time + 604800)
throw new OpenTokException("Expire time must be in the next 7 days");
$data_string .= "&expire_time=$expire_time";
}
if($connection_data != '') {
if(strlen($connection_data) > 1000)
throw new OpenTokException("Connection data must be less than 1000 characters");
$data_string .= "&connection_data=" . urlencode($connection_data);
}
$sig = $this->_sign_string($data_string, $this->api_secret);
$api_key = $this->api_key;
return "T1==" . base64_encode("partner_id=$api_key&sig=$sig:$data_string");
}
/**
* Creates a new session.
* $location - IP address to geolocate the call around.
* $properties - Optional array, keys are defined in SessionPropertyConstants
*/
public function create_session($location='', $properties=array()) {
$properties["location"] = $location;
$properties["api_key"] = $this->api_key;
$createSessionResult = $this->_do_request("/session/create", $properties);
$createSessionXML = @simplexml_load_string($createSessionResult, 'SimpleXMLElement', LIBXML_NOCDATA);
if(!$createSessionXML) {
throw new OpenTokException("Failed to create session: Invalid response from server");
}
$errors = $createSessionXML->xpath("//error");
if($errors) {
$errMsg = $errors[0]->xpath("//@message");
if($errMsg) {
$errMsg = (string)$errMsg[0]['message'];
} else {
$errMsg = "Unknown error";
}
throw new AuthException("Error " . $createSessionXML->error['code'] ." ". $createSessionXML->error->children()->getName() . ": " . $errMsg );
}
if(!isset($createSessionXML->Session->session_id)) {
echo"<pre>";print_r($createSessionXML);echo"</pre>";
throw new OpenTokException("Failed to create session.");
}
$sessionId = $createSessionXML->Session->session_id;
return new OpenTokSession($sessionId, null);
}
public function get_archive_manifest($archiveId, $token) {
$auth = array('type' => 'token', 'token' => $token);
$archiveManifestResult = $this->_do_request("/archive/getmanifest/$archiveId", array(), $auth);
$archiveManifestXML = @simplexml_load_string($archiveManifestResult, 'SimpleXMLElement', LIBXML_NOCDATA);
if(!$archiveManifestXML) {
throw new OpenTokException("Failed to load manifest file associated with archive $archiveId");
}
return OpenTokArchive::parseManifest($archiveManifestXML);
}
//////////////////////////////////////////////
//Signing functions, request functions, and other utility functions needed for the OpenTok
//Server API. Developers should not edit below this line. Do so at your own risk.
//////////////////////////////////////////////
protected function _sign_string($string, $secret) {
return hash_hmac("sha1", $string, $secret);
}
protected function _do_request($url, $data, $auth = array('type' => 'partner')) {
$url = API_Config::API_SERVER . $url;
$dataString = "";
foreach($data as $key => $value){
$value = urlencode($value);
$dataString .= "$key=$value&";
}
$dataString = rtrim($dataString,"&");
switch($auth['type']) {
case 'token':
$authString = "X-TB-TOKEN-AUTH: ".$auth['token'];
break;
case 'partner':
default:
$authString = "X-TB-PARTNER-AUTH: $this->api_key:$this->api_secret";
break;
}
//Use file_get_contents if curl is not available for PHP
if(function_exists("curl_init")) {
$ch = curl_init();
$api_key = $this->api_key;
$api_secret = $this->api_secret;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_HTTPHEADER, Array($authString));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
$res = curl_exec($ch);
if(curl_errno($ch)) {
throw new RequestException('Request error: ' . curl_error($ch));
}
curl_close($ch);
}
else {
if (function_exists("file_get_contents")) {
$context_source = array ('http' => array (
'method' => 'POST',
'header'=> Array("Content-type: application/x-www-form-urlencoded", $authString, "Content-Length: " . strlen($dataString), 'content' => $dataString)
)
);
$context = stream_context_create($context_source);
$res = @file_get_contents( $url ,false, $context);
}
else{
throw new RequestException("Your PHP installion neither supports the file_get_contents method nor cURL. Please enable one of these functions so that you can make API calls.");
}
}
return $res;
}
}