This repository has been archived by the owner on Nov 15, 2018. It is now read-only.
forked from manlui/elgg_with_rest_api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstart.php
431 lines (368 loc) · 13.2 KB
/
start.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<?php
/**
* Elgg web services API plugin
*/
elgg_register_event_handler('init', 'system', 'ws_init');
function ws_init() {
$lib_dir = __DIR__ . "/lib";
elgg_register_library('elgg:ws', "$lib_dir/web_services.php");
elgg_register_library('elgg:ws:api_user', "$lib_dir/api_user.php");
elgg_register_library('elgg:ws:client', "$lib_dir/client.php");
elgg_register_library('elgg:ws:tokens', "$lib_dir/tokens.php");
elgg_register_library('elgg:ws:core', "$lib_dir/core.php");
elgg_register_library('elgg:ws:user', "$lib_dir/user.php");
elgg_register_library('elgg:ws:message', "$lib_dir/message.php");
elgg_register_library('elgg:ws:likes', "$lib_dir/likes.php");
elgg_register_library('elgg:ws:wire', "$lib_dir/wire.php");
elgg_register_library('elgg:ws:image', "$lib_dir/image.php");
elgg_register_library('elgg:ws:gcm_register', "$lib_dir/gcm_register.php");
elgg_register_library('elgg:ws:file', "$lib_dir/file.php");
elgg_register_library('elgg:ws:site', "$lib_dir/site.php");
elgg_register_library('elgg:ws:auth', "$lib_dir/auth.php");
elgg_register_library('elgg:ws:blog', "$lib_dir/blog.php");
elgg_register_library('elgg:ws:album', "$lib_dir/album.php");
elgg_register_library('elgg:ws:bookmark', "$lib_dir/bookmark.php");
elgg_register_library('elgg:ws:group', "$lib_dir/group.php");
elgg_register_library('elgg:ws:activity', "$lib_dir/activity.php");
elgg_load_library('elgg:ws:api_user');
elgg_load_library('elgg:ws:tokens');
elgg_load_library('elgg:ws:core');
elgg_load_library('elgg:ws:user');
elgg_load_library('elgg:ws:message');
elgg_load_library('elgg:ws:likes');
elgg_load_library('elgg:ws:wire');
elgg_load_library('elgg:ws:image');
elgg_load_library('elgg:ws:gcm_register');
elgg_load_library('elgg:ws:file');
elgg_load_library('elgg:ws:site');
elgg_load_library('elgg:ws:auth');
elgg_load_library('elgg:ws:blog');
elgg_load_library('elgg:ws:album');
elgg_load_library('elgg:ws:bookmark');
elgg_load_library('elgg:ws:group');
elgg_load_library('elgg:ws:activity');
elgg_register_page_handler('services', 'ws_page_handler');
// Register a service handler for the default web services
// The name rest is a misnomer as they are not RESTful
elgg_ws_register_service_handler('rest', 'ws_rest_handler');
// expose the list of api methods
elgg_ws_expose_function("system.api.list", "list_all_apis", null,
elgg_echo("system.api.list"), "GET", false, false);
// The authentication token api
elgg_ws_expose_function(
"auth.gettoken",
"auth_gettoken",
array(
'username' => array ('type' => 'string'),
'password' => array ('type' => 'string'),
),
elgg_echo('auth.gettoken'),
'POST',
false,
false
);
elgg_register_plugin_hook_handler('unit_test', 'system', 'ws_unit_test');
elgg_register_plugin_hook_handler('send', 'notification:site', 'mobile_notifications_send');
elgg_register_plugin_hook_handler('rest:output', 'system.api.list', 'ws_system_api_list_hook');
}
/**
* Send an Mobile notification
*
* @param string $hook Hook name
* @param string $type Hook type
* @param bool $result Has anyone sent a message yet?
* @param array $params Hook parameters
* @return bool
* @access private
*/
function mobile_notifications_send($hook, $type, $result, $params) {
// Sender and Recipient Information to get name and username
$message = $params['notification'];
$sender = $message->getSender();
$recipient = $message->getRecipient();
//Send GCN to Mobile
include_once elgg_get_plugins_path().'web_services/lib/GCM.php';
$gcm = new GCM();
$result = $gcm->setup_message($sender->name, $sender->username, $recipient->name, $recipient->username, $message->subject, $message->body);
if ($result) {
error_log("Message sent successfully");
} else {
error_log("Failed to send message");
}
}
/**
* Handle a web service request
*
* Handles requests of format: http://site/services/api/handler/response_format/request
* The first element after 'services/api/' is the service handler name as
* registered by {@link register_service_handler()}.
*
* The remaining string is then passed to the {@link service_handler()}
* which explodes by /, extracts the first element as the response format
* (viewtype), and then passes the remaining array to the service handler
* function registered by {@link register_service_handler()}.
*
* If a service handler isn't found, a 404 header is sent.
*
* @param array $segments URL segments
* @return bool
*/
function ws_page_handler($segments) {
elgg_load_library('elgg:ws');
if (!isset($segments[0]) || $segments[0] != 'api') {
return false;
}
array_shift($segments);
$handler = array_shift($segments);
$request = implode('/', $segments);
service_handler($handler, $request);
return true;
}
/**
* A global array holding API methods.
* The structure of this is
* $API_METHODS = array (
* $method => array (
* "description" => "Some human readable description"
* "function" = 'my_function_callback'
* "parameters" = array (
* "variable" = array ( // the order should be the same as the function callback
* type => 'int' | 'bool' | 'float' | 'string'
* required => true (default) | false
* default => value // optional
* )
* )
* "call_method" = 'GET' | 'POST'
* "require_api_auth" => true | false (default)
* "require_user_auth" => true | false (default)
* )
* )
*/
global $API_METHODS;
$API_METHODS = array();
/** Define a global array of errors */
global $ERRORS;
$ERRORS = array();
/**
* Expose a function as a web service.
*
* Limitations: Currently cannot expose functions which expect objects.
* It also cannot handle arrays of bools or arrays of arrays.
* Also, input will be filtered to protect against XSS attacks through the web services.
*
* @param string $method The api name to expose - for example "myapi.dosomething"
* @param string $function Your function callback.
* @param array $parameters (optional) List of parameters in the same order as in
* your function. Default values may be set for parameters which
* allow REST api users flexibility in what parameters are passed.
* Generally, optional parameters should be after required
* parameters.
*
* This array should be in the format
* "variable" = array (
* type => 'int' | 'bool' | 'float' | 'string' | 'array'
* required => true (default) | false
* default => value (optional)
* )
* @param string $description (optional) human readable description of the function.
* @param string $call_method (optional) Define what http method must be used for
* this function. Default: GET
* @param bool $require_api_auth (optional) (default is false) Does this method
* require API authorization? (example: API key)
* @param bool $require_user_auth (optional) (default is false) Does this method
* require user authorization?
*
* @return bool
* @throws InvalidParameterException
*/
function elgg_ws_expose_function($method, $function, array $parameters = NULL, $description = "",
$call_method = "GET", $require_api_auth = false, $require_user_auth = false) {
global $API_METHODS;
if (($method == "") || ($function == "")) {
$msg = elgg_echo('InvalidParameterException:APIMethodOrFunctionNotSet');
throw new InvalidParameterException($msg);
}
// does not check whether this method has already been exposed - good idea?
$API_METHODS[$method] = array();
$API_METHODS[$method]["description"] = $description;
// does not check whether callable - done in execute_method()
$API_METHODS[$method]["function"] = $function;
if ($parameters != NULL) {
if (!is_array($parameters)) {
$msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
throw new InvalidParameterException($msg);
}
// catch common mistake of not setting up param array correctly
$first = current($parameters);
if (!is_array($first)) {
$msg = elgg_echo('InvalidParameterException:APIParametersArrayStructure', array($method));
throw new InvalidParameterException($msg);
}
}
if ($parameters != NULL) {
// ensure the required flag is set correctly in default case for each parameter
foreach ($parameters as $key => $value) {
// check if 'required' was specified - if not, make it true
if (!array_key_exists('required', $value)) {
$parameters[$key]['required'] = true;
}
}
$API_METHODS[$method]["parameters"] = $parameters;
}
$call_method = strtoupper($call_method);
switch ($call_method) {
case 'POST' :
$API_METHODS[$method]["call_method"] = 'POST';
break;
case 'GET' :
$API_METHODS[$method]["call_method"] = 'GET';
break;
default :
$msg = elgg_echo('InvalidParameterException:UnrecognisedHttpMethod',
array($call_method, $method));
throw new InvalidParameterException($msg);
}
$API_METHODS[$method]["require_api_auth"] = $require_api_auth;
$API_METHODS[$method]["require_user_auth"] = $require_user_auth;
return true;
}
/**
* Unregister a web services method
*
* @param string $method The api name that was exposed
* @return void
*/
function elgg_ws_unexpose_function($method) {
global $API_METHODS;
if (isset($API_METHODS[$method])) {
unset($API_METHODS[$method]);
}
}
/**
* Simple api to return a list of all api's installed on the system.
*
* @return array
* @access private
*/
function list_all_apis() {
global $API_METHODS;
// sort first
ksort($API_METHODS);
return $API_METHODS;
}
/**
* Registers a web services handler
*
* @param string $handler Web services type
* @param string $function Your function name
*
* @return bool Depending on success
*/
function elgg_ws_register_service_handler($handler, $function) {
global $CONFIG;
if (!isset($CONFIG->servicehandler)) {
$CONFIG->servicehandler = array();
}
if (is_callable($function, true)) {
$CONFIG->servicehandler[$handler] = $function;
return true;
}
return false;
}
/**
* Remove a web service
* To replace a web service handler, register the desired handler over the old on
* with register_service_handler().
*
* @param string $handler web services type
* @return void
*/
function elgg_ws_unregister_service_handler($handler) {
global $CONFIG;
if (isset($CONFIG->servicehandler, $CONFIG->servicehandler[$handler])) {
unset($CONFIG->servicehandler[$handler]);
}
}
/**
* REST API handler
*
* @return void
* @access private
*
* @throws SecurityException|APIException
*/
function ws_rest_handler() {
$viewtype = elgg_get_viewtype();
if (!elgg_view_exists('api/output', $viewtype)) {
header("HTTP/1.0 400 Bad Request");
header("Content-type: text/plain");
echo "Missing view 'api/output' in viewtype '$viewtype'.";
if (in_array($viewtype, ['xml', 'php'])) {
echo "\nEnable the 'data_views' plugin to add this view.";
}
exit;
}
elgg_load_library('elgg:ws');
// Register the error handler
error_reporting(E_ALL);
set_error_handler('_php_api_error_handler');
// Register a default exception handler
set_exception_handler('_php_api_exception_handler');
// plugins should return true to control what API and user authentication handlers are registered
if (elgg_trigger_plugin_hook('rest', 'init', null, false) == false) {
// for testing from a web browser, you can use the session PAM
// do not use for production sites!!
//register_pam_handler('pam_auth_session');
// user token can also be used for user authentication
register_pam_handler('pam_auth_usertoken');
// simple API key check
register_pam_handler('api_auth_key', "sufficient", "api");
// hmac
register_pam_handler('api_auth_hmac', "sufficient", "api");
}
// Get parameter variables
$method = get_input('method');
$result = null;
// this will throw an exception if authentication fails
authenticate_method($method);
$result = execute_method($method);
if (!($result instanceof GenericResult)) {
throw new APIException(elgg_echo('APIException:ApiResultUnknown'));
}
// Output the result
echo elgg_view_page($method, elgg_view("api/output", array("result" => $result)));
}
/**
* Unit tests for web services
*
* @param string $hook unit_test
* @param string $type system
* @param mixed $value Array of tests
* @param mixed $params Params
*
* @return array
* @access private
*/
function ws_unit_test($hook, $type, $value, $params) {
elgg_load_library('elgg:ws');
elgg_load_library('elgg:ws:client');
$value[] = dirname(__FILE__) . '/tests/ElggCoreWebServicesApiTest.php';
return $value;
}
/**
* Filters system API list to remove PHP internal function names
*
* @param string $hook "rest:output"
* @param string $type "system.api.list"
* @param array $return API list
* @param array $params Method params
* @return array
*/
function ws_system_api_list_hook($hook, $type, $return, $params) {
if (!empty($return) && is_array($return)) {
foreach($return as $method => $settings) {
unset($return[$method]['function']);
}
}
return $return;
}