aboutsummaryrefslogtreecommitdiff
path: root/engine/lib/api.php
blob: d04a7029b53c70b1cc064482ff19572f1aba6d48 (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
<?php
	/**
	 * Elgg API
	 * Functions and objects which make up the API engine.
	 * 
	 * @package Elgg
	 * @subpackage Core
	 * @license http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU Public License version 2
	 * @author Marcus Povey <marcus@dushka.co.uk>
	 * @copyright Curverider Ltd 2008
	 * @link http://elgg.org/
	 */
	
	// Result classes /////////////////////////////////////////////////////////////////////////

	/**
	 * @class GenericResult Result superclass.
	 * @author Marcus Povey <marcus@dushka.co.uk>
	 */
	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 toStdClass()
		{
			global $ERRORS, $CONFIG, $PAM_HANDLER_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)) && ($CONFIG->debug == true))
			{
				if (count($ERRORS))
					$result->runtime_errors = $ERRORS;
					
				if (count($PAM_HANDLER_MSG))
					$result->pam = $PAM_HANDLER_MSG;
			}

			return $result;
		}
	}
	
	/**
	 * @class SuccessResult
	 * Generic success result class, extend if you want to do something special.
	 * @author Marcus Povey <marcus@dushka.co.uk>
	 */
	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);
		}
	}
	
	/**
	 * @class ErrorResult
	 * The error result class.
	 * @author Marcus Povey <marcus@dushka.co.uk>
	 */
	class ErrorResult extends GenericResult
	{
		public static $RESULT_FAIL 		= -1 ; // Fail with no specific code

		public static $RESULT_FAIL_APIKEY_DISABLED = -30;
		public static $RESULT_FAIL_APIKEY_INACTIVE = -31;
		public static $RESULT_FAIL_APIKEY_INVALID = -32;
		
		public static $RESULT_FAIL_AUTHTOKEN = -20; // Invalid, expired or missing auth token

		public function ErrorResult($message, $code = "", Exception $exception = NULL)
		{
			if ($code == "")
				$code = GenericResult::$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);
		}
	}

	// API Call functions /////////////////////////////////////////////////////////////////////	
	
	/** 
	 * An array holding methods.
	 * The structure of this is 
	 * 	$METHODS = array (
	 * 		"api.method" => array (
	 * 			"function" = 'my_function_callback'
	 * 			"call_method" = 'GET' | 'POST'
	 * 			"parameters" = array (
	 * 				"variable" = array ( // NB, the order is the same as defined by your function callback
	 * 					type => 'int' | 'bool' | 'float' | 'string'
	 * 					required => true (default) | false  
	 * 				)
	 * 			)
	 * 			"require_auth" => true (default) | false
	 * 			"description" => "Some human readable description"
	 * 		)
	 *  )
	 */
	$METHODS = array();
	
	/**
	 * Get the request method.
	 */
	function get_call_method()
	{
		return $_SERVER['REQUEST_METHOD'];
	}
	
	/**
	 * 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("No site ID has been specified.");
		
		$time = time();
		
		$user = get_data_row("SELECT * from {$CONFIG->dbprefix}users_apisessions where token='$token' and site_guid=$site and expires>$time");
		if ($user)
			return $user->user_id;
		
		return false;
	}
	
	/**
	 * Expose an arbitrary function as an api call.
	 * 
	 * Limitations: Currently can not expose functions which expect objects or arrays.
	 * 
	 * @param string $method The api name to expose this as, eg "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 $call_method Define what call method should be used for this function.
	 * @param bool $require_auth Whether this requires a user authentication token or not (default is true)
	 * @param string $description Optional human readable description of the function.
	 * @return bool
	 */
	function expose_function($method, $function, array $parameters = NULL, $call_method = "GET", $require_auth = true, $description = "")
	{
		global $METHODS;
		
		if (
			($method!="") &&
			($function!="")
		)
		{
			$METHODS[$method] = array();
				
			$METHODS[$method]["function"] = $function;
			
			if ($parameters!=NULL)
				$METHODS[$method]["parameters"] = $parameters;
				
			$call_method = strtoupper($call_method);
			switch ($call_method)
			{
				case 'POST' : $METHODS[$method]["call_method"] = 'POST'; break;
				case 'GET' : $METHODS[$method]["call_method"] = 'GET'; break;
				default : 
					throw new InvalidParameterException("Unrecognised call method '$call_method'");
			}
				
			$METHODS[$method]["description"] = $description;
			
			$METHODS[$method]["require_auth"] = $require_auth;
			
			return true;
		}
		
		return false;	
	}
	
	/**
	 * Executes a method.
	 * A method is a function which you have previously exposed using expose_function.
	 *
	 * @param string $method Method, e.g. "foo.bar"
	 * @param array $parameters Array of parameters in the format "variable" => "value", thse will be sanitised before being fed to your handler.
	 * @param string $token The authentication token to authorise this method call.
	 * @return GenericResult The result of the execution.
	 * @throws APIException, SecurityException
	 */
	function execute_method($method, array $parameters, $token = "")
	{
		global $METHODS, $CONFIG;
		
		// Sanity check
		$method = sanitise_string($method); 
		$token = sanitise_string($token); 
		
		// See if we can find the method handler
		if ((isset($METHODS[$method]["function"])) && (is_callable($METHODS[$method]["function"])))
		{
			// See if this is being made with the right call method
			if (strcmp(get_call_method(), $METHODS[$method]["call_method"])==0)
			{
				$serialised_parameters = "";
				
				$validated_userid = validate_user_token($CONFIG->site_id, $token); 
			
				if ((!$METHODS[$method]["require_auth"]) || ($validated_userid) || (isloggedin()))
				{
					// If we have parameters then we need to sanitise the parameters.
					if ((isset($METHODS[$method]["parameters"])) && (is_array($METHODS[$method]["parameters"]))) 
					{
						foreach ($METHODS[$method]["parameters"] as $key => $value)
						{
							if (
								(is_array($value)) 			// Check that this is an array
								&& (isset($value['type']))		// Check we have a type defined
							)
							{
								// Check that the variable is present in the request
	
								if (
									(!isset($parameters[$key])) &&				// No parameter
									((!isset($value['required'])) || ($value['required']!=true)) // and not optional
								)
									throw new APIException("Missing parameter $key in method $method");
								else
								{
									// Avoid debug error
									if (isset($parameters[$key]))
									{
										// Set variables casting to type.	
										switch (strtolower($value['type']))
										{
											case 'int':
											case 'integer' : $serialised_parameters .= "," . (int)trim($parameters[$key]); break;
											case 'bool':
											case 'boolean': 
														if (strcasecmp(trim($parameters[$key]), "false")==0) 
															$parameters[$key]='';
																
														$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':
															$array = "array(";
															
															if (is_array($parameters[$key]))
															{
																foreach ($parameters[$key] as $k => $v)
																{
																	$k = sanitise_string($k);
																	$v = sanitise_string($v);
																	
																	$array .= "'$k'=>'$v',";
																}
																
																$array = trim($array,",");
															}
															else
																throw APIException("$key does not appear to be an array.");
																
															$array .= ")";
															
															$serialised_parameters .= $array;
														break;
				
											default : throw new APIException("Unrecognised type in cast {$value['type']} for variable '$key' in method '$method'");
										}
									}
								}
							}
							else
								throw new APIException("Invalid parameter found for '$key' in method '$method'.");
						}
					}
					
					// Execute function: Construct function and calling parameters
					$function = $METHODS[$method]["function"];
					$serialised_parameters = trim($serialised_parameters, ", ");
					
					$result = eval("return $function($serialised_parameters);");
				
					// Sanity check result
					if ($result instanceof GenericResult) // If this function returns an api result itself, just return it
						return $result; 
						
					if ($result === FALSE)
						throw new APIException("$function($serialised_parameters) has a parsing error.");
						
					if ($result ===  NULL)
						throw new APIException("$function($serialised_parameters) returned no value."); // If no value
					
					return SuccessResult::getInstance($result); // Otherwise assume that the call was successful and return it as a success object.	
				}
				else
					throw new SecurityException("Authentication token either missing, invalid or expired.", GenericResult::$RESULT_FAIL_AUTHTOKEN); 
			}	
			else
				throw new CallException("$method must be called using '{$METHODS[$method]["call_method"]}'");
		}
		
		// Return an error if not found
		throw new APIException("Method call '$method' has not been implemented."); 
	}
		
	// System functions ///////////////////////////////////////////////////////////////////////
	
	/**
	 * Simple api to return a list of all api's installed on the system.
	 */
	function list_all_apis()
	{
		global $METHODS;
		return $METHODS;
	}
	
	// Expose some system api functions
	expose_function("system.api.list", "list_all_apis", NULL, "GET", false, "List all available API calls on the system.");

	
	// PAM AUTH HMAC functions ////////////////////////////////////////////////////////////////
	
	/**
	 * 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("Algorithm '$algo' is not supported or has been disabled.");
	}
	
	/**
	 * 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 = "")
	{
		$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.
	 * 
	 * TODO : REWRITE TO NOT USE ZEND
	 * 
	 * @param $hmac The hmac string.
	 * @return bool True if replay detected, false if not.
	 */
	function cache_hmac_check_replay($hmac)
	{
		global $CONFIG;

		$cache_dir = $CONFIG->cache_path;
		if (!$cache_dir)
			throw new ConfigurationException("Cache directory 'cache_path' not set.");
			
		$cache = new ElggFileCache($cache_dir, 90000); // cache lifetime is 25 hours (see time window in get_and_validate_api_headers() )
		
		if (!$result = $cache->load($hmac))
		{
			$cache->save($hmac, $hmac);
			
			return false;
		}
		
		return true;
	}
	
	/**
	 * Find an API User's details based on the provided public api key.
	 *
	 * @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");	
	}
	
	/**
	 * 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 = $_SERVER['REQUEST_METHOD'];
		if (($result->method != "GET") && ($result->method!= "POST")) // Only allow these methods
			throw new APIException("Request method must be GET or POST");

		$result->api_key = $_SERVER['HTTP_X_ELGG_APIKEY'];
		if ($result->api_key == "")
			throw new APIException("Missing X-Elgg-apikey HTTP header");
		
		$result->hmac = $_SERVER['HTTP_X_ELGG_HMAC'];
		if ($result->hmac == "")
			throw new APIException("Missing X-Elgg-hmac header");
		
		$result->hmac_algo = $_SERVER['HTTP_X_ELGG_HMAC_ALGO'];
		if ($result->hmac_algo == "")
			throw new APIException("Missing X-Elgg-hmac-algo header");
		
		$result->time = $_SERVER['HTTP_X_ELGG_TIME'];
		if ($result->time == "") 
			throw new APIException("Missing X-Elgg-time header"); 
		if (($result->time<(microtime(true)-86400.00)) || ($result->time>(microtime(true)+86400.00))) // Basic timecheck, think about making this smaller if we get loads of users and the cache gets really big.
			throw new APIException("X-Elgg-time is too far in the past or future");
		
		$result->get_variables = $_SERVER['QUERY_STRING'];
		if ($result->get_variables == "")
			throw new APIException("No data on the query string");

		if ($result->method=="POST")
		{
			$result->posthash = $_SERVER['HTTP_X_ELGG_POSTHASH'];
			if ($result->posthash == "") 
				throw new APIException("Missing X-Elgg-posthash header");
			
			$result->posthash_algo = $_SERVER['HTTP_X_ELGG_POSTHASH_ALGO'];
			if ($result->posthash_algo == "") 
				throw new APIException("Missing X-Elgg-posthash_algo header");
				
			$result->content_type = $_SERVER['CONTENT_TYPE'];
			if ($result->content_type == "")
				throw new APIException("Missing content type for post data");
		}
		
		return $result;
	}
	
	/**
	 * Return a sanitised form of the POST data sent to the script
	 *
	 * @return string
	 */
	function get_post_data()
	{
		global $GLOBALS;
		
		return $GLOBALS['HTTP_RAW_POST_DATA'];	
	}
	
	// PAM functions //////////////////////////////////////////////////////////////////////////
	
	$PAM_HANDLERS = array(); 
	$PAM_HANDLER_MSG = array(); // Messages
	
	/**
	 * Register a method of authenticating an incoming API request.
	 * This function registers a PAM handler which is a function that matches the desciption pam_handler_name() 
	 * and returns either 'true' if an incoming api request was authorised, false or throws an exception if not.
	 * 
	 * The handlers are tried in turn until one of them successfully authenticates the session.
	 * 
	 * This architecture lets an administrator choose what methods to accept for API authentication or 
	 *
	 * @param unknown_type $handler
	 */
	function register_api_pam_handler($handler)
	{
		global $PAM_HANDLERS;
		
		if (is_callable($handler))
		{
			$PAM_HANDLERS[$handler] = $handler;
			return true;
		}
		
		return false;
	}
	
	/**
	 * Magically authenticate an API session using one of the registered methods.
	 * 
	 * This function will return true if authentication was possible, otherwise it'll throw an exception.
	 * 
	 * If $CONFIG->debug is set then additional debug information will be returned.
	 */
	function api_pam_authenticate()
	{
		global $PAM_HANDLERS, $PAM_HANDLER_MSG;
		global $CONFIG;
		
		$dbg_msgs = array();

		foreach ($PAM_HANDLERS as $k => $v)
		{
			try {
				// Execute the handler 
				if ($v())
				{
					// Explicitly returned true
					$PAM_HANDLER_MSG[$k] = "Authenticated!";

					return true;
				}
				else
					$PAM_HANDLER_MSG[$k] = "Not Authenticated.";
			} 
			catch (Exception $e)
			{
				$PAM_HANDLER_MSG[$k] = "$e";
			}	
		}
		
		// Got this far, so no methods could be found to authenticate the session
		throw new SecurityException("No authentication methods were found that could authenticate this request.");
	}
	
	/**
	 * See if the user has a valid login sesson.
	 */
	function pam_auth_session()
	{
		return isloggedin();
	}
	
	/**
	 * Secure authentication through headers and HMAC.
	 */
	function pam_auth_hmac()
	{
		global $CONFIG;
		
		$api_header = get_and_validate_api_headers(); // Get api header
		$api_user = get_api_user($CONFIG->site_id, $api_header->api_key); // Pull API user details
	
		if ($api_user)
		{
			// Get the secret key
			$secret_key = $api_user->secret;
		
			// Validate HMAC
			$hmac = calculate_hmac($api_header->hmac_algo, 
					$api_header->time, 
					$api_header->api_key, 
					$secret_key, 
					$api_header->get_variables, 
					$api_header->method == 'POST' ? $api_header->posthash : "");
				
			if (strcmp(
				$api_header->hmac,
				$hmac	
			)==0)
			{
				// Now make sure this is not a replay
				if (!cache_hmac_check_replay($hmac)) 
				{
					// 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("POST data hash is invalid - Expected $calculated_posthash but got {$api_header->posthash}.");
					}
					
					// If we've passed all the checks so far then we can be reasonably certain that the request is authentic, so return this fact to the PAM engine.
					return true;
				}
				else
					throw new SecurityException("Packet signature already seen.");
			}
			else 
				throw new SecurityException("HMAC is invalid.  {$api_header->hmac} != [calc]$hmac = {$api_header->hmac_algo}(**SECRET KEY**, time:{$api_header->time}, apikey:{$api_header->api_key}, get_vars:{$api_header->get_variables}" . ($api_header->method=="POST"? "posthash:$api_header->posthash}" : ")"));
		}
		else
			throw new SecurityException("Invalid or missing API Key.",ErrorResult::$RESULT_FAIL_APIKEY_INVALID);
			
		return false;
	}
	
	// Output functions ///////////////////////////////////////////////////////////////////////
	
	$API_OUTPUT_FUNCTIONS = array();
	
	/**
	 * Register an API output handler.
	 * This function is used by the system and the plugins to register an output encoding method for 
	 * returning API results.
	 * 
	 * @param string $form The format string, eg 'xml' or 'php'
	 * @param string $function The function, which must be in the format function_name(stdClass $result) and return a string.
	 * @return bool
	 */
	function register_api_outputhandler($form, $function)
	{
		global $API_OUTPUT_FUNCTIONS;
		
		if ( ($form!="") && ($function!=""))
		{
			$API_OUTPUT_FUNCTIONS[$form] = $function;
			
			return true;
		}
		
		return false;
	}

	/**
	 * Output the result, with the given fault.
	 * 
	 * @param GenericResult $result Result object.
	 * @param string $format The format
	 * @return string
	 */
	function output_result(GenericResult $result, $format)
	{
		global $API_OUTPUT_FUNCTIONS;
	
		if (
			(array_key_exists($format, $API_OUTPUT_FUNCTIONS)) &&
			(is_callable($API_OUTPUT_FUNCTIONS[$format]))
		)
			return $API_OUTPUT_FUNCTIONS[$format]($result->toStdClass());
			
		// We got here, so no output format was found. Output an error
		$result = print_r($result->toStdClass(), true);	
			
		return <<< END
<html>
<head><title>Something went wrong...</title></head>
<body>
	<h1>API Output Error</h1>	
	<p>Something went badly wrong while outputting the result of your request in '$format' format. The result and any errors are displayed in 
	raw text below.</p>
	<pre>
$result
</pre>
</body>
</html>
END;
	}
	
	
	function xml_result_handler(stdClass $result)
	{
		header("Content-Type: text/xml");
		return serialise_object_to_xml($result, "elgg");
	}
	
	function php_result_handler(stdClass $result)
	{
		return serialize($result);
	}
	
	function json_result_handler(stdClass $result)
	{
		return json_encode($result);
	}
	
	function csv_result_handler(stdClass $result)
	{
		throw new NotImplementedException("CSV View currently not implemented");
	}
	
	// Register some format handlers
	register_api_outputhandler('xml', 'xml_result_handler');
	register_api_outputhandler('php', 'php_result_handler');
	register_api_outputhandler('json', 'json_result_handler');
	register_api_outputhandler('csv', 'csv_result_handler');
	
	
	// 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);
			
		echo output_result(
			ErrorResult::getInstance(
				$exception->getMessage(), 
				$exception->getCode() == 0 ? ErrorResult::$RESULT_FAIL : $exception->getCode(), 
				$exception),
				
			get_input('format','php') // Attempt to get the requested format if passed.
		);
	}
	
?>