aboutsummaryrefslogtreecommitdiff
path: root/engine/lib/api.php
blob: f2424c76644c189afebe430efec7783d9c7dbcf5 (plain)
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
<?php
/**
 * Elgg API
 * Functions and objects which make up the API engine.
 *
 * @package Elgg
 * @subpackage Core
 * @author Curverider Ltd <info@elgg.com>
 * @link http://elgg.org/
 */

// Result classes /////////////////////////////////////////////////////////////////////////

/**
 * GenericResult Result superclass.
 *
 * @author Curverider Ltd <info@elgg.com>
 * @package Elgg
 * @subpackage Core
 */
abstract class GenericResult {
	/**
	 * The status of the result.
	 * @var int
	 */
	private $status_code;

	/**
	 * Message returned along with the status which is almost always an error message.
	 * This must be human readable, understandable and localised.
	 * @var string
	 */
	private $message;

	/**
	 * Result store.
	 * Attach result specific informaton here.
	 *
	 * @var mixed. Should probably be an object of some sort.
	 */
	private $result;

	/**
	 * Set a status code and optional message.
	 *
	 * @param int $status The status code.
	 * @param string $message The message.
	 */
	protected function setStatusCode($status, $message = "") {
		$this->status_code = $status;
		$this->message = $message;
	}

	/**
	 * Set the result.
	 *
	 * @param mixed $result
	 */
	protected function setResult($result) {
		$this->result = $result;
	}

	protected function getStatusCode() {
		return $this->status_code;
	}

	protected function getStatusMessage() {
		return $this->message;
	}

	protected function getResult() {
		return $this->result;
	}

	/**
	 * Serialise to a standard class.
	 *
	 * DEVNOTE: The API is only interested in data, we can not easily serialise
	 * custom classes without the need for 1) the other side being PHP, 2) you need to have the class
	 * definition installed, 3) its the right version!
	 *
	 * Therefore, I'm not bothering.
	 *
	 * Override this to include any more specific information, however api results should be attached to the
	 * class using setResult().
	 *
	 * if $CONFIG->debug is set then additional information about the runtime environment and authentication will be
	 * returned.
	 *
	 * @return stdClass Object containing the serialised result.
	 */
	public function export() {
		global $ERRORS, $CONFIG, $_PAM_HANDLERS_MSG;

		$result = new stdClass;

		$result->status = $this->getStatusCode();
		if ($this->getStatusMessage()!="") {
			$result->message = $this->getStatusMessage();
		}

		$resultdata = $this->getResult();
		if (isset($resultdata)) {
			$result->result = $resultdata;
		}

		if (isset($CONFIG->debug)) {
			if (count($ERRORS)) {
				$result->runtime_errors = $ERRORS;
			}

			if (count($_PAM_HANDLERS_MSG)) {
				$result->pam = $_PAM_HANDLERS_MSG;
			}
		}

		return $result;
	}
}

/**
 * SuccessResult
 * Generic success result class, extend if you want to do something special.
 *
 * @author Curverider Ltd <info@elgg.com>
 * @package Elgg
 * @subpackage Core
 */
class SuccessResult extends GenericResult {
	public static $RESULT_SUCCESS = 0;  // Do not change this from 0

	public function SuccessResult($result) {
		$this->setResult($result);
		$this->setStatusCode(SuccessResult::$RESULT_SUCCESS);
	}

	public static function getInstance($result) {
		// Return a new error object.
		return new SuccessResult($result);
	}
}

/**
 * ErrorResult
 * The error result class.
 *
 * @author Curverider Ltd <info@elgg.com>
 * @package Elgg
 * @subpackage Core
 */
class ErrorResult extends GenericResult {
	// Fail with no specific code
	public static $RESULT_FAIL = -1 ;

	public static $RESULT_FAIL_APIKEY_DISABLED = -30;
	public static $RESULT_FAIL_APIKEY_INACTIVE = -31;
	public static $RESULT_FAIL_APIKEY_INVALID = -32;

	// Invalid, expired or missing auth token
	public static $RESULT_FAIL_AUTHTOKEN = -20;

	public function ErrorResult($message, $code = "", Exception $exception = NULL) {
		if ($code == "") {
			$code = ErrorResult::$RESULT_FAIL;
		}

		if ($exception!=NULL) {
			$this->setResult($exception->__toString());
		}

		$this->setStatusCode($code, $message);
	}

	/**
	 * Get a new instance of the ErrorResult.
	 *
	 * @param string $message
	 * @param int $code
	 * @param Exception $exception Optional exception for generating a stack trace.
	 */
	public static function getInstance($message, $code = "", Exception $exception = NULL) {
		// Return a new error object.
		return new ErrorResult($message, $code, $exception);
	}
}

// Caching of HMACs ///////////////////////////////////////////////////////////////////////

/**
 * ElggHMACCache
 * Store cached data in a temporary database, only used by the HMAC stuff.
 *
 * @author Curverider Ltd <info@elgg.com>
 * @package Elgg
 * @subpackage API
 */
class ElggHMACCache extends ElggCache {
	/**
	 * Set the Elgg cache.
	 *
	 * @param int $max_age Maximum age in seconds, 0 if no limit.
	 */
	function __construct($max_age = 0) {
		$this->set_variable("max_age", $max_age);
	}

	/**
	 * Save a key
	 *
	 * @param string $key
	 * @param string $data
	 * @return boolean
	 */
	public function save($key, $data) {
		global $CONFIG;

		$key = sanitise_string($key);
		$time = time();

		return insert_data("INSERT into {$CONFIG->dbprefix}hmac_cache (hmac, ts) VALUES ('$key', '$time')");
	}

	/**
	 * Load a key
	 *
	 * @param string $key
	 * @param int $offset
	 * @param int $limit
	 * @return string
	 */
	public function load($key, $offset = 0, $limit = null) {
		global $CONFIG;

		$key = sanitise_string($key);

		$row = get_data_row("SELECT * from {$CONFIG->dbprefix}hmac_cache where hmac='$key'");
		if ($row) {
			return $row->hmac;
		}

		return false;
	}

	/**
	 * Invalidate a given key.
	 *
	 * @param string $key
	 * @return bool
	 */
	public function delete($key) {
		global $CONFIG;

		$key = sanitise_string($key);

		return delete_data("DELETE from {$CONFIG->dbprefix}hmac_cache where hmac='$key'");
	}

	/**
	 * Clear out all the contents of the cache.
	 *
	 * Not currently implemented in this cache type.
	 */
	public function clear() {
		return true;
	}

	/**
	 * Clean out old stuff.
	 *
	 */
	public function __destruct() {
		global $CONFIG;

		$time = time();
		$age = (int)$this->get_variable("max_age");

		$expires = $time-$age;

		delete_data("DELETE from {$CONFIG->dbprefix}hmac_cache where ts<$expires");
	}
}

// Primary Services API Server functions /////////////////////////////////////////////////////////////////////

/**
 * A global array holding API methods.
 * The structure of this is
 * 	$API_METHODS = array (
 * 		$method => array (
 * 			"function" = 'my_function_callback'
 * 			"call_method" = 'GET' | 'POST'
 * 			"parameters" = array (
 * 				"variable" = array ( // NB, the order should be the same as the function callback
 * 					type => 'int' | 'bool' | 'float' | 'string'
 * 					required => true (default) | false
 * 				)
 * 			)
 * 			"require_api_auth" => true | false (default)
 * 			"require_user_auth" => true | false (default)
 * 			"description" => "Some human readable description"
 * 		)
 *  )
 */
$API_METHODS = array();

/**
 * Expose a function as a services api call.
 *
 * Limitations: Currently can not expose functions which expect objects.
 *
 * @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, with optional parameters last.
 * This array should be in the format
 *   "variable" = array (
 * 					type => 'int' | 'bool' | 'float' | 'string' | 'array'
 * 					required => true (default) | false
 * 	 )
 * @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
 */
function 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 == "")) {
		throw new InvalidParameterException(elgg_echo('InvalidParameterException:APIMethodOrFunctionNotSet'));	
	}
	
	// does not check whether this method has already been exposed - good idea?
	$API_METHODS[$method] = array();

	// does not check whether callable - done in execute_method()
	$API_METHODS[$method]["function"] = $function;

	if ($parameters != NULL && !is_array($parameters)) {
		throw new InvalidParameterException(sprintf(elgg_echo('InvalidParameterException:APIParametersNotArray'), $method));	
	}
	
	if ($parameters != NULL) {
		// ensure the required flag is set correctly in default case
		foreach ($parameters as $key => $value) {
			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 :
			throw new InvalidParameterException(sprintf(elgg_echo('InvalidParameterException:UnrecognisedHttpMethod'), $call_method, $method));
	}

	$API_METHODS[$method]["description"] = $description;

	$API_METHODS[$method]["require_api_auth"] = $require_api_auth;

	$API_METHODS[$method]["require_user_auth"] = $require_user_auth;

	return true;
}

/**
 * Unregister an API method
 * @param $method The api name that was exposed  
 */
function unexpose_function($method) {
	global $API_METHODS;
	
	if (isset($API_METHODS[$method])) {
		unset($API_METHODS[$method]);
	}
}

/**
 * Check that the method call has the proper API and user authentication
 * @return bool
 */
function authenticate_method($method) {
	global $API_METHODS;
	
	// method must be exposed
	if (!isset($API_METHODS[$method])) {
		throw new APIException(sprintf(elgg_echo('APIException:MethodCallNotImplemented'), $method));
	}
	
	// make sure that POST variables are available if relevant
	if (get_call_method() === 'POST') {
		include_post_data();
	}
	
	// check API authentication if required
	if ($API_METHODS[$method]["require_api_auth"] == true) {
		if (api_authenticate() == false) {
			throw new APIException(elgg_echo('APIException:APIAuthenticationFailed'));
		}
	}
	
	// check user authentication if required
	if ($API_METHODS[$method]["require_user_auth"] == true) {
		if (pam_authenticate() == false) {
			throw new APIException(elgg_echo('APIException:UserAuthenticationFailed'));
		}
	}
	
	return true;
}

$API_AUTH_HANDLERS = array();

/**
 * Register an API authorization handler
 * 
 * @param $handler
 * @param $importance
 * @return bool
 */
function register_api_auth_handler($handler, $importance = "sufficient") {
	global $API_AUTH_HANDLERS;

	if (is_callable($handler)) {
		$API_AUTH_HANDLERS[$handler] = new stdClass;

		$API_AUTH_HANDLERS[$handler]->handler = $handler;
		$API_AUTH_HANDLERS[$handler]->importance = strtolower($importance);

		return true;
	}

	return false;	
}

/**
 * Authenticate an API method call
 * 
 * @return bool
 */
function api_authenticate() {
	global $API_AUTH_HANDLERS;

	$authenticated = false;

	foreach ($API_AUTH_HANDLERS as $k => $v) {
		$handler = $v->handler;
		$importance = $v->importance;

		try {
			// Execute the handler
			if ($handler()) {
				$authenticated = true;
			} else {
				// If this is required then abort.
				if ($importance == 'required') {
					return false;
				}
			}
		} catch (Exception $e) {
			// If this is required then abort.
			if ($importance == 'required') {
				return false;
			}
		}
	}

	return $authenticated;
}

/**
 * Executes a method.
 * A method is a function which you have previously exposed using expose_function.
 *
 * @param string $method Method, e.g. "foo.bar"
 * @return GenericResult The result of the execution.
 * @throws APIException, SecurityException
 */
function execute_method($method) {
	global $API_METHODS, $CONFIG;

	// method must be exposed
	if (!isset($API_METHODS[$method])) {
		throw new APIException(sprintf(elgg_echo('APIException:MethodCallNotImplemented'), $method));
	}

	// function must be callable 
	if (!(isset($API_METHODS[$method]["function"])) || !(is_callable($API_METHODS[$method]["function"]))) {
		throw new APIException(sprintf(elgg_echo('APIException:FunctionDoesNotExist'), $method));
	}
	
	// check http call method
	if (strcmp(get_call_method(), $API_METHODS[$method]["call_method"]) != 0) {
		throw new CallException(sprintf(elgg_echo('CallException:InvalidCallMethod'), $method, $API_METHODS[$method]["call_method"]));
	}
	
	$parameters = get_parameters_for_method($method);
	
	if (verify_parameters($method, $parameters) == false) {
		// error
		return false;
	}
	
	$serialised_parameters = serialise_parameters($method, $parameters);
	
	// Execute function: Construct function and calling parameters
	$function = $API_METHODS[$method]["function"];
	$serialised_parameters = trim($serialised_parameters, ", ");

	$result = eval("return $function($serialised_parameters);");

	// Sanity check result
	// If this function returns an api result itself, just return it
	if ($result instanceof GenericResult) {
		return $result;
	}

	if ($result === false) {
		throw new APIException(sprintf(elgg_echo('APIException:FunctionParseError'), $function, $serialised_parameters));
	}

	if ($result ===  NULL) {
		// If no value
		throw new APIException(sprintf(elgg_echo('APIException:FunctionNoReturn'), $function, $serialised_parameters));
	}

	// Otherwise assume that the call was successful and return it as a success object.
	return SuccessResult::getInstance($result);
}

/**
 * Get the request method.
 */
function get_call_method() {
	return $_SERVER['REQUEST_METHOD'];
}

/**
 * This function analyses all expected parameters for a given method
 * 
 * This function sanitizes the input parameters and returns them in
 * an associated array. 
 *
 * @param string $method The method
 * @return array containing parameters as key => value 
 */
function get_parameters_for_method($method) {
	global $API_METHODS;

	$sanitised = array();
	
	// if there are parameters, sanitize them
	if (isset($API_METHODS[$method]['parameters'])) {
		foreach ($API_METHODS[$method]['parameters'] as $k => $v) {
			$v = get_input($k); // Make things go through the sanitiser
			if ($v !== '') {
				$sanitised[$k] = $v;
			}
		}
	}
		
	return $sanitised;
}


function get_post_data() {
	global $GLOBALS;
		
	$postdata = '';
	if (isset($GLOBALS['HTTP_RAW_POST_DATA']))
		$postdata = $GLOBALS['HTTP_RAW_POST_DATA'];

	// Attempt another method to return post data (incase always_populate_raw_post_data is switched off)
	if (!$postdata) {
		$postdata = file_get_contents('php://input');
	}
	
	return $postdata;
}

/**
 * This fixes the post parameters that are munged due to page handler
 */
function include_post_data() {
	
	$postdata = get_post_data();
	
	if (isset($postdata)) {
		parse_str($postdata, $query_arr);
		if (is_array($query_arr)) {
			foreach($query_arr as $name => $val) {
				set_input($name, $val);
			}			
		}
	}
}

/**
 * Verify that the required parameters are present
 * @param $method
 * @param $parameters
 * @return true on success or exception
 */
function verify_parameters($method, $parameters) {
	global $API_METHODS;
	
	// are there any parameters for this method
	if (!(isset($API_METHODS[$method]["parameters"]))) {
		return true; // no so return
	}

	// check that the parameters were registered correctly and all required ones are there
	foreach ($API_METHODS[$method]['parameters'] as $key => $value) {
		// must be array to describe parameter in expose and type must be defined
		if (!is_array($value) || !isset($value['type'])) {
			throw new APIException(sprintf(elgg_echo('APIException:InvalidParameter'), $key, $method));
		}
				
		// Check that the variable is present in the request if required
		$is_param_required = !isset($value['required']) || $value['required'];
		if ($is_param_required && !array_key_exists($key, $parameters)) {
			throw new APIException(sprintf(elgg_echo('APIException:MissingParameterInMethod'), $key, $method));
		}
	}
	
	return true;
}

/**
 * Serialize an array of parameters for an API method call
 * 
 * @param $method
 * @param $parameters
 * @return unknown_type
 */
function serialise_parameters($method, $parameters) {
	global $API_METHODS;
	
	// are there any parameters for this method
	if (!(isset($API_METHODS[$method]["parameters"]))) {
		return ''; // if not, return
	}
	
	$serialised_parameters = "";
	foreach ($API_METHODS[$method]['parameters'] as $key => $value) {

		// avoid warning on parameters that are not required and not present
		if (!isset($parameters[$key])) {
			continue;
		}
		
		// Set variables casting to type.	
		switch (strtolower($value['type']))
		{
			case 'int':
			case 'integer' : 
				$serialised_parameters .= "," . (int)trim($parameters[$key]); 
				break;
			case 'bool':
			case 'boolean': 
				// change word false to boolean false
				if (strcasecmp(trim($parameters[$key]), "false") == 0) { 
					$parameters[$key] = false;
				}
				
				$serialised_parameters .= "," . (bool)trim($parameters[$key]); 
				break;
			case 'string': 
				$serialised_parameters .= ",'" .  (string)mysql_real_escape_string(trim($parameters[$key])) . "'"; 
				break;
			case 'float': 
				$serialised_parameters .= "," . (float)trim($parameters[$key]); 
				break;
			case 'array':
				// we can handle an array of strings, maybe ints, definitely not booleans or other arrays										
				$array = "array(";
				if (!is_array($parameters[$key]))
				{
					throw APIException(sprintf(elgg_echo('APIException:ParameterNotArray'), $key));
				}
							
				foreach ($parameters[$key] as $k => $v)
				{
					$k = sanitise_string($k);
					$v = sanitise_string($v);
								
					$array .= "'$k'=>'$v',";
				}
							
				$array = trim($array,",");
								
				$array .= ")";
							
				$serialised_parameters .= $array;
				break;
			default: 
				throw new APIException(sprintf(elgg_echo('APIException:UnrecognisedTypeCast'), $value['type'], $key, $method));
		}
	}
	
	return $serialised_parameters;
}

// API authorization handlers /////////////////////////////////////////////////////////////////////

/**
 * Confirm that the call includes a valid API key
 * @return true if good API key - otherwise throws exception
 */
function api_auth_key() {
	global $CONFIG;
	
	// check that an API key is present
	$api_key = get_input('api_key');
	if ($api_key == "") {
		throw new APIException(elgg_echo('APIException:MissingAPIKey'));
	}
	
	// check that it is active
	$api_user = get_api_user($CONFIG->site_id, $api_key);
	if (!$api_user) {
		throw new APIException(elgg_echo('APIException:MissingAPIKey'));
	}
	
	return trigger_plugin_hook('api_key', 'use', $api_key, true);
}


/**
 * 
 * @return true if success - otherwise throws exception
 */
function api_auth_hmac() {
	global $CONFIG;

	// Get api header
	$api_header = get_and_validate_api_headers();

	// Pull API user details
	$api_user = get_api_user($CONFIG->site_id, $api_header->api_key);

	if (!$api_user) {
		throw new SecurityException(elgg_echo('SecurityException:InvalidAPIKey'), ErrorResult::$RESULT_FAIL_APIKEY_INVALID);
	}
	
	// Get the secret key
	$secret_key = $api_user->secret;

	// get the query string
	$query = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1);
	
	// calculate expected HMAC
	$hmac = calculate_hmac(	$api_header->hmac_algo,
							$api_header->time,
							$api_header->api_key,
							$secret_key,
							$params,
							$api_header->method == 'POST' ? $api_header->posthash : "");

	
	if (!(strcmp($api_header->hmac, $hmac) == 0) && !($api_header->hmac) && !($hmac)) {
		throw new SecurityException("HMAC is invalid.  {$api_header->hmac} != [calc]$hmac");
	}
	
	// Now make sure this is not a replay
	if (cache_hmac_check_replay($hmac)) {
		throw new SecurityException(elgg_echo('SecurityException:DupePacket'));
	}
	
	// Validate post data
	if ($api_header->method=="POST") {
		$postdata = get_post_data();
		$calculated_posthash = calculate_posthash($postdata, $api_header->posthash_algo);

		if (strcmp($api_header->posthash, $calculated_posthash)!=0) {
			throw new SecurityException(sprintf(elgg_echo('SecurityException:InvalidPostHash'), $calculated_posthash, $api_header->posthash));
		}
	}

	return true;
}

// HMAC /////////////////////////////////////////////////////////////////////

/**
 * This function looks at the super-global variable $_SERVER and extracts the various
 * header variables needed to pass to the validation functions after performing basic validation.
 *
 * @return stdClass Containing all the values.
 * @throws APIException Detailing any error.
 */
function get_and_validate_api_headers() {
	$result = new stdClass;

	$result->method = get_call_method();
	// Only allow these methods
	if (($result->method != "GET") && ($result->method != "POST")) {
		throw new APIException(elgg_echo('APIException:NotGetOrPost'));
	}

	$result->api_key = $_SERVER['HTTP_X_ELGG_APIKEY'];
	if ($result->api_key == "") {
		throw new APIException(elgg_echo('APIException:MissingAPIKey'));
	}

	$result->hmac = $_SERVER['HTTP_X_ELGG_HMAC'];
	if ($result->hmac == "") {
		throw new APIException(elgg_echo('APIException:MissingHmac'));
	}

	$result->hmac_algo = $_SERVER['HTTP_X_ELGG_HMAC_ALGO'];
	if ($result->hmac_algo == "") {
		throw new APIException(elgg_echo('APIException:MissingHmacAlgo'));
	}

	$result->time = $_SERVER['HTTP_X_ELGG_TIME'];
	if ($result->time == "") {
		throw new APIException(elgg_echo('APIException:MissingTime'));
	}

	// Basic timecheck, think about making this smaller if we get loads of users and the cache gets really big.
	if (($result->time<(microtime(true)-86400.00)) || ($result->time>(microtime(true)+86400.00))) {
		throw new APIException(elgg_echo('APIException:TemporalDrift'));
	}

	if ($result->method == "POST") {
		$result->posthash = $_SERVER['HTTP_X_ELGG_POSTHASH'];
		if ($result->posthash == "") {
			throw new APIException(elgg_echo('APIException:MissingPOSTHash'));
		}

		$result->posthash_algo = $_SERVER['HTTP_X_ELGG_POSTHASH_ALGO'];
		if ($result->posthash_algo == "") {
			throw new APIException(elgg_echo('APIException:MissingPOSTAlgo'));
		}

		$result->content_type = $_SERVER['CONTENT_TYPE'];
		if ($result->content_type == "") {
			throw new APIException(elgg_echo('APIException:MissingContentType'));
		}
	}

	return $result;
}

/**
 * Map various algorithms to their PHP equivs.
 * This also gives us an easy way to disable algorithms.
 *
 * @param string $algo The algorithm
 * @return string The php algorithm
 * @throws APIException if an algorithm is not supported.
 */
function map_api_hash($algo) {
	$algo = strtolower(sanitise_string($algo));
	$supported_algos = array(
		"md5" => "md5",	// TODO: Consider phasing this out
		"sha" => "sha1", // alias for sha1
		"sha1" => "sha1",
		"sha256" => "sha256"
	);

	if (array_key_exists($algo, $supported_algos)) {
		return $supported_algos[$algo];
	}

	throw new APIException(sprintf(elgg_echo('APIException:AlgorithmNotSupported'), $algo));
}

/**
 * Calculate the HMAC for the query.
 * This function signs an api request using the information provided and is then verified by
 * searunner.
 *
 * @param $algo string The HMAC algorithm used as stored in X-Searunner-hmac-algo.
 * @param $time string String representation of unix time as stored in X-Searunner-time.
 * @param $api_key string Your api key.
 * @param $secret string Your secret key.
 * @param $get_variables string URLEncoded string representation of the get variable parameters, eg "format=php&method=searunner.test".
 * @param $post_hash string Optional sha1 hash of the post data.
 * @return string The HMAC string.
 */
function calculate_hmac($algo, $time, $api_key, $secret_key, $get_variables, $post_hash = "") {
	global $CONFIG;

	elgg_log("HMAC Parts: $algo, $time, $api_key, $secret_key, $get_variables, $post_hash");

	$ctx = hash_init(map_api_hash($algo), HASH_HMAC, $secret_key);

	hash_update($ctx, trim($time));
	hash_update($ctx, trim($api_key));
	hash_update($ctx, trim($get_variables));
	if (trim($post_hash)!="") {
		hash_update($ctx, trim($post_hash));
	}

	return hash_final($ctx);
}

/**
 * Calculate a hash for some post data.
 *
 * TODO: Work out how to handle really large bits of data.
 *
 * @param $postdata string The post data.
 * @param $algo string The algorithm used.
 * @return string The hash.
 */
function calculate_posthash($postdata, $algo) {
	$ctx = hash_init(map_api_hash($algo));

	hash_update($ctx, $postdata);

	return hash_final($ctx);
}

/**
 * This function will do two things. Firstly it verifys that a $hmac hasn't been seen before, and
 * secondly it will add the given hmac to the cache.
 *
 * @param $hmac The hmac string.
 * @return bool True if replay detected, false if not.
 */
function cache_hmac_check_replay($hmac) {
	// cache lifetime is 25 hours (see time window in get_and_validate_api_headers() )
	$cache = new ElggHMACCache(90000);

	if (!$cache->load($hmac)) {
		$cache->save($hmac, $hmac);

		return false;
	}

	return true;
}

// API key functions /////////////////////////////////////////////////////////////////////

/**
 * Find an API User's details based on the provided public api key. These users are not users in the traditional sense.
 *
 * @param int $site_guid The GUID of the site.
 * @param string $api_key The API Key
 * @return mixed stdClass representing the database row or false.
 */
function get_api_user($site_guid, $api_key) {
	global $CONFIG;

	$api_key = sanitise_string($api_key);
	$site_guid = (int)$site_guid;

	return get_data_row("SELECT * from {$CONFIG->dbprefix}api_users where api_key='$api_key' and site_guid=$site_guid and active=1");
}

/**
 * Revoke an api user key.
 *
 * @param int $site_guid The GUID of the site.
 * @param string $api_key The API Key (public).
 */
function remove_api_user($site_guid, $api_key) {
	global $CONFIG;

	$keypair = get_api_user($site_guid, $api_key);
	if ($keypair) {
		return delete_data("DELETE from {$CONFIG->dbprefix}api_users where id={$keypair->id}");
	}

	return false;
}

/**
 * Generate a new API user for a site, returning a new keypair on success.
 *
 * @param int $site_guid The GUID of the site.
 */
function create_api_user($site_guid) {
	global $CONFIG;

	$site_guid = (int)$site_guid;

	$public = sha1(rand().$site_guid.microtime());
	$secret = sha1(rand().$site_guid.microtime().$public);

	$insert = insert_data("INSERT into {$CONFIG->dbprefix}api_users
		(site_guid, api_key, secret) values
		($site_guid, '$public', '$secret')");

	if ($insert) {
		return get_api_user($site_guid, $public);
	}

	return false;
}

// User Authorization functions ////////////////////////////////////////////////////////////////

/**
 * Check the user token
 * This examines whether an authentication token is present and returns true if
 * it is present and is valid. The user gets logged in so with the current
 * session code of Elgg, that user will be logged out of all other sessions.
 *
 * @param unknown_type $credentials
 * @return bool
 */
function pam_auth_usertoken($credentials = NULL) {
	global $CONFIG;

	$token = get_input('auth_token');

	$validated_userid = validate_user_token($CONFIG->site_id, $token);

	if ($validated_userid) {
		$u = get_entity($validated_userid);

		// Could we get the user?
		if (!$u) {
			return false;
		}

		// Not an elgg user
		if ( (!$u instanceof ElggUser)) {
			return false;
		}

		// User is banned
		if ($u->isBanned()) {
			return false;
		}

		// Fail if we couldn't log the user in
		if (!login($u)) {
			return false;
		}
		
		return true;
	}

	return false;
}

/**
 * See if the user has a valid login sesson.
 */
function pam_auth_session($credentials = NULL) {
	return isloggedin();
}

/**
 * Obtain a token for a user.
 *
 * @param string $username The username
 * @param string $password The password
 */
function obtain_user_token($username, $password) {
	global $CONFIG;

	$site = $CONFIG->site_id;
	$user = get_user_by_username($username);
	$time = time();
	$time += 60*60; // token is good for one hour
	$token = md5(rand(). microtime() . $username . $password . $time . $site);

	if (!$user) {
		return false;
	}

	if (insert_data("INSERT into {$CONFIG->dbprefix}users_apisessions
				(user_guid, site_guid, token, expires) values
				({$user->guid}, $site, '$token', '$time') on duplicate key update token='$token', expires='$time'")) {
		return $token;
	}

	return false;
}

/**
 * Validate a token against a given site.
 *
 * A token registered with one site can not be used from a different apikey(site), so be aware of this
 * during development.
 *
 * @param int $site The ID of the site
 * @param string $token The Token.
 * @return mixed The user id attached to the token or false.
 */
function validate_user_token($site, $token) {
	global $CONFIG;

	$site = (int)$site;
	$token = sanitise_string($token);

	if (!$site) {
		throw new ConfigurationException(elgg_echo('ConfigurationException:NoSiteID'));
	}

	$time = time();

	$user = get_data_row("SELECT * from {$CONFIG->dbprefix}users_apisessions
		where token='$token' and site_guid=$site and $time < expires");

	if ($user) {
		return $user->user_guid;
	}

	return false;
}

// Client api functions ///////////////////////////////////////////////////////////////////

/**
 * Utility function to serialise a header array into its text representation.
 *
 * @param $headers array The array of headers "key" => "value"
 * @return string
 */
function serialise_api_headers(array $headers) {
	$headers_str = "";

	foreach ($headers as $k => $v) {
		$headers_str .= trim($k) . ": " . trim($v) . "\r\n";
	}

	return trim($headers_str);
}

/**
 * Send a raw API call to an elgg api endpoint.
 *
 * @param array $keys The api keys.
 * @param string $url URL of the endpoint.
 * @param array $call Associated array of "variable" => "value"
 * @param string $method GET or POST
 * @param string $post_data The post data
 * @param string $content_type The content type
 * @return stdClass The unserialised response object
 */
function send_api_call(array $keys, $url, array $call, $method = 'GET', $post_data = '', $content_type = 'application/octet-stream') {
	global $CONFIG;

	$headers = array();
	$encoded_params = array();

	$method = strtoupper($method);
	switch (strtoupper($method)) {
		case 'GET' :
		case 'POST' :
			break;
		default:
			$msg = sprintf(elgg_echo('NotImplementedException:CallMethodNotImplemented'), $method);
			throw new NotImplementedException($msg);
	}

	// Time
	$time = microtime(true);

	// URL encode all the parameters, ensuring auth_token (if present) is at the end!
	foreach ($call as $k => $v){
		if ($k!='auth_token') {
			$encoded_params[] = urlencode($k).'='.urlencode($v);
		}
	}

	if ($call['auth_token']) {
		$encoded_params[] = urlencode('auth_token').'='.urlencode($call['auth_token']);
	}

	$params = implode('&', $encoded_params);

	// Put together the query string
	$url = $url . "?" . $params;

	// Construct headers
	$posthash = "";
	if ($method == 'POST') {
		$posthash = calculate_posthash($post_data, 'md5');
	}

	if ((isset($keys['public'])) && (isset($keys['private']))) {
		$headers['X-Elgg-apikey'] = $keys['public'];
		$headers['X-Elgg-time'] = $time;
		$headers['X-Elgg-hmac-algo'] = 'sha1';
		$headers['X-Elgg-hmac'] = calculate_hmac('sha1',
			$time,
			$keys['public'],
			$keys['private'],
			$params,
			$posthash
		);
	}
	if ($method == 'POST') {
		$headers['X-Elgg-posthash'] = $posthash;
		$headers['X-Elgg-posthash-algo'] = 'md5';

		$headers['Content-type'] = $content_type;
		$headers['Content-Length'] = strlen($post_data);
	}

	// Opt array
	$http_opts = array(
		'method' => $method,
		'header' => serialise_api_headers($headers)
	);
	if ($method == 'POST') {
		$http_opts['content'] = $post_data;
	}

	$opts = array('http' => $http_opts);

	// Send context
	$context = stream_context_create($opts);

	// Send the query and get the result and decode.
	elgg_log("APICALL: $url");
	$results = file_get_contents($url, false, $context);

	return $results;
}

/**
 * Send a GET call
 *
 * @param string $url URL of the endpoint.
 * @param array $call Associated array of "variable" => "value"
 * @param array $keys The keys dependant on chosen authentication method
 * @return stdClass The unserialised response object
 */
function send_api_get_call($url, array $call, array $keys) {
	return send_api_call($keys, $url, $call);
}

/**
 * Send a GET call
 *
 * @param string $url URL of the endpoint.
 * @param array $call Associated array of "variable" => "value"
 * @param array $keys The keys dependant on chosen authentication method
 * @param string $post_data The post data
 * @param string $content_type The content type
 * @return stdClass The unserialised response object
 */
function send_api_post_call($url, array $call, array $keys, $post_data, $content_type = 'application/octet-stream') {
	return send_api_call($keys, $url, $call, 'POST', $post_data, $content_type);
}

/**
 * Return a key array suitable for the API client using the standard authentication method based on api-keys and secret keys.
 *
 * @param string $secret_key Your secret key
 * @param string $api_key Your api key
 */
function get_standard_api_key_array($secret_key, $api_key) {
	return array('public' => $api_key, 'private' => $secret_key);
}

// System functions ///////////////////////////////////////////////////////////////////////

/**
 * Simple api to return a list of all api's installed on the system.
 */
function list_all_apis() {
	global $API_METHODS;
	
	// sort first
	ksort($API_METHODS);
	
	return $API_METHODS;
}

/**
 * The auth.gettoken API.
 * This API call lets a user log in, returning an authentication token which can be used
 * in leu of a username and password login from then on.
 *
 * @param string username Username
 * @param string password Clear text password
 */
function auth_gettoken($username, $password) {
	if (authenticate($username, $password)) {
		$token = obtain_user_token($username, $password);
		if ($token) {
			return $token;
		}
	}

	throw new SecurityException(elgg_echo('SecurityException:authenticationfailed'));
}

// Error handler functions ////////////////////////////////////////////////////////////////

/** Define a global array of errors */
$ERRORS = array();

/**
 * PHP Error handler function.
 * This function acts as a wrapper to catch and report PHP error messages.
 *
 * @see http://uk3.php.net/set-error-handler
 * @param unknown_type $errno
 * @param unknown_type $errmsg
 * @param unknown_type $filename
 * @param unknown_type $linenum
 * @param unknown_type $vars
 */
function __php_api_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
	global $ERRORS;

	$error = date("Y-m-d H:i:s (T)") . ": \"" . $errmsg . "\" in file " . $filename . " (line " . $linenum . ")";

	switch ($errno) {
		case E_USER_ERROR:
			error_log("ERROR: " . $error);
			$ERRORS[] = "ERROR: " .$error;

			// Since this is a fatal error, we want to stop any further execution but do so gracefully.
			throw new Exception("ERROR: " . $error);
			break;

		case E_WARNING :
		case E_USER_WARNING :
			error_log("WARNING: " . $error);
			$ERRORS[] = "WARNING: " .$error;
			break;

		default:
			error_log("DEBUG: " . $error);
			$ERRORS[] = "DEBUG: " .$error;
	}
}

/**
 * PHP Exception handler.
 * This is a generic exception handler for PHP exceptions. This will catch any
 * uncaught exception and return it as an ErrorResult in the requested format.
 *
 * @param Exception $exception
 */
function __php_api_exception_handler($exception) {

	error_log("*** FATAL EXCEPTION (API) *** : " . $exception);

	$code   = $exception->getCode() == 0 ? ErrorResult::$RESULT_FAIL : $exception->getCode(); 
	$result = new ErrorResult($exception->getMessage(), $code, NULL);
	
	page_draw($exception->getMessage(), elgg_view("api/output", array("result" => $result)));
}

// Initialisation /////////////////////////////////////////////////////////////

/**
 * Register a page handler for the various API endpoints.
 *
 * @param array $page
 */
function api_endpoint_handler($page) {
	global $CONFIG;

	// Which view
	if ($page[1]) {
		elgg_set_viewtype($page[1]);
	}

	// Which endpoint
	if ($page[0]) {
		switch ($page[0]) {
			case 'rest' :
			default : include($CONFIG->path . "services/api/rest.php");
		}
	}
}

/**
 * Unit tests for API 
 */
function api_unit_test($hook, $type, $value, $params) {
	global $CONFIG;
	$value[] = $CONFIG->path . 'engine/tests/services/api.php';
	return $value;
}

/**
 * Initialise the API subsystem.
 *
 */
function api_init() {
	// Register a page handler, so we can have nice URLs
	register_page_handler('api','api_endpoint_handler');
	
	register_plugin_hook('unit_test', 'system', 'api_unit_test');
	
	// expose the list of api methods
	expose_function("system.api.list", "list_all_apis", NULL, elgg_echo("system.api.list"), "GET", false, false);
	
	// The authentication token api
	expose_function("auth.gettoken", 
					"auth_gettoken", array(
											'username' => array ('type' => 'string'),
											'password' => array ('type' => 'string'),
											), 
					elgg_echo('auth.gettoken'), 
					'POST', 
					false, 
					false);
}


register_elgg_event_handler('init','system','api_init');