Index: sandbox/2.4.1-3/prototype/services/OpenLDAP.php
===================================================================
--- sandbox/2.4.1-3/prototype/services/OpenLDAP.php	(revision 5804)
+++ sandbox/2.4.1-3/prototype/services/OpenLDAP.php	(revision 6351)
@@ -13,5 +13,5 @@
 	if( !isset($criteria["limit"]) )
 		$criteria["limit"] = $this->limit;
-        
+      
 	$sr =  ldap_search( $this->con , $this->config['context'] , self::parseCriteria($criteria , $map) , self::parseJustthese($justthese, $map) , 0 , $criteria["limit"]); 
 	if(!$sr) return false; 
@@ -156,5 +156,5 @@
         $as = array_shift( $filter );
 	$op = self::parseOperator( $as );
-                
+
 	if( is_array($filter[0]) )
 	{
Index: sandbox/2.4.1-3/prototype/services/PostgreSQL.php
===================================================================
--- sandbox/2.4.1-3/prototype/services/PostgreSQL.php	(revision 6145)
+++ sandbox/2.4.1-3/prototype/services/PostgreSQL.php	(revision 6351)
@@ -197,6 +197,7 @@
 		    $val[] = '\''.addslashes($v).'\'';
 	    }
-	    
-	    return '('.implode(',', $ind).') VALUES ('.implode(',', $val).') RETURNING '.$map['id'].' as id';
+
+//	    return '('.implode(',', $ind).') VALUES ('.implode(',', $val).') RETURNING '.$map['id'].' as id';	    
+	    return '('.implode(',', $ind).') VALUES ('.implode(',', $val).') RETURNING id';	    
     }
 	
@@ -306,4 +307,5 @@
 	    case 'or': return( $op );
 	    case 'in': return array( $op );
+	    case '!in': return array( 'NOT IN' );
 	    case '^': return array( 'like', '%',  '' );
 	    case '$': return array( 'like',  '', '%' );
Index: sandbox/2.4.1-3/prototype/me.php
===================================================================
--- sandbox/2.4.1-3/prototype/me.php	(revision 5399)
+++ sandbox/2.4.1-3/prototype/me.php	(revision 6351)
@@ -4,4 +4,5 @@
 
 $me = Controller::read(array('concept' => 'user', 'service' => 'OpenLDAP'  , 'id' => Config::me('uidNumber')));
+$me['token'] = $_SESSION['oauth']['access_token'];
 
 echo json_encode( $me );
Index: sandbox/2.4.1-3/prototype/library/oauth2/LICENSE.txt
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/LICENSE.txt	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/LICENSE.txt	(revision 6351)
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2010 Tim Ridgely <tim@opendining.net>
+
+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.
Index: sandbox/2.4.1-3/prototype/library/oauth2/tests/All_OAuth2_Tests.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/tests/All_OAuth2_Tests.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/tests/All_OAuth2_Tests.php	(revision 6351)
@@ -0,0 +1,29 @@
+<?php
+
+/**
+ * Static test suite.
+ */
+
+class All_OAuth2_Tests extends PHPUnit_Framework_TestSuite {
+  
+  /**
+   * Constructs the test suite handler.
+   */
+  public function __construct() {
+    $this->setName ( 'OAuth2Suite' );
+
+    foreach (glob(__DIR__.'/*Test.php') as $filename) {
+      require $filename;
+      $class = basename($filename, '.php');
+      $this->addTestSuite($class);
+    }
+  }
+  
+  /**
+   * Creates the suite.
+   */
+  public static function suite() {
+    return new self ();
+  }
+}
+
Index: sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2Test.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2Test.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2Test.php	(revision 6351)
@@ -0,0 +1,453 @@
+<?php
+require __DIR__ . '/../lib/OAuth2.php';
+require __DIR__ . '/../lib/IOAuth2Storage.php';
+require __DIR__ . '/../lib/IOAuth2GrantCode.php';
+
+/**
+ * OAuth2 test case.
+ */
+class OAuth2Test extends PHPUnit_Framework_TestCase {
+  
+  /**
+   * @var OAuth2
+   */
+  private $fixture;
+  
+  /**
+   * The actual token ID is irrelevant, so choose one:
+   * @var string
+   */
+  private $tokenId = 'my_token';
+  
+  /**
+   * Tests OAuth2->verifyAccessToken() with a missing token
+   */
+  public function testVerifyAccessTokenWithNoParam() {
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $scope = null;
+    $this->setExpectedException('OAuth2AuthenticateException');
+    $this->fixture->verifyAccessToken('', $scope);
+  }
+  
+  /**
+   * Tests OAuth2->verifyAccessToken() with a invalid token
+   */
+  public function testVerifyAccessTokenInvalidToken() {
+    
+    // Set up the mock storage to say this token does not exist
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $mockStorage->expects($this->once())
+      ->method('getAccessToken')
+      ->will($this->returnValue(false));
+      
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $scope = null;
+    $this->setExpectedException('OAuth2AuthenticateException');
+    $this->fixture->verifyAccessToken($this->tokenId, $scope);
+  }
+  
+  /**
+   * Tests OAuth2->verifyAccessToken() with a malformed token
+   * 
+   * @dataProvider generateMalformedTokens
+   */
+  public function testVerifyAccessTokenMalformedToken($token) {
+    
+    // Set up the mock storage to say this token does not exist
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $mockStorage->expects($this->once())
+      ->method('getAccessToken')
+      ->will($this->returnValue($token));
+      
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $scope = null;
+    $this->setExpectedException('OAuth2AuthenticateException');
+    $this->fixture->verifyAccessToken($this->tokenId, $scope);
+  }
+  
+	/**
+   * Tests OAuth2->verifyAccessToken() with different expiry dates
+   * 
+   * @dataProvider generateExpiryTokens
+   */
+  public function testVerifyAccessTokenCheckExpiry($token, $expectedToPass) {
+    
+    // Set up the mock storage to say this token does not exist
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $mockStorage->expects($this->once())
+      ->method('getAccessToken')
+      ->will($this->returnValue($token));
+      
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $scope = null;
+    
+    
+    // When valid, we just want any sort of token
+    if ($expectedToPass) { 
+      $actual = $this->fixture->verifyAccessToken($this->tokenId, $scope);
+      $this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
+      $this->assertInternalType('array', $actual);
+    }
+    else {
+      $this->setExpectedException('OAuth2AuthenticateException');
+      $this->fixture->verifyAccessToken($this->tokenId, $scope);
+    }
+  }
+  
+	/**
+   * Tests OAuth2->verifyAccessToken() with different scopes
+   * 
+   * @dataProvider generateScopes
+   */
+  public function testVerifyAccessTokenCheckScope($scopeRequired, $token, $expectedToPass) {
+    
+    // Set up the mock storage to say this token does not exist
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $mockStorage->expects($this->once())
+      ->method('getAccessToken')
+      ->will($this->returnValue($token));
+      
+    $this->fixture = new OAuth2($mockStorage);
+    
+    // When valid, we just want any sort of token
+    if ($expectedToPass) {
+      $actual = $this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
+      $this->assertNotEmpty($actual, "verifyAccessToken() was expected to PASS, but it failed");
+      $this->assertInternalType('array', $actual);
+    }
+    else {
+      $this->setExpectedException('OAuth2AuthenticateException');
+      $this->fixture->verifyAccessToken($this->tokenId, $scopeRequired);
+    }
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken() for missing data
+   * 
+   * @dataProvider generateEmptyDataForGrant
+   */
+  public function testGrantAccessTokenMissingData($inputData, $authHeaders) {
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $this->setExpectedException('OAuth2ServerException');
+    $this->fixture->grantAccessToken($inputData, $authHeaders);
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken()
+   * 
+   * Tests the different ways client credentials can be provided.
+   */
+  public function testGrantAccessTokenCheckClientCredentials() {
+    $mockStorage = $this->getMock('IOAuth2Storage');
+    $mockStorage->expects($this->any())
+      ->method('checkClientCredentials')
+      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
+    $this->fixture = new OAuth2($mockStorage);
+    
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE);
+    $authHeaders = array();
+    
+    // First, confirm that an non-client related error is thrown:
+    try {
+      $this->fixture->grantAccessToken($inputData, $authHeaders);
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    } catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
+    }
+
+    // Confirm Auth header
+    $authHeaders = array('PHP_AUTH_USER' => 'dev-abc', 'PHP_AUTH_PW' => 'pass');
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'dev-abc'); // When using auth, client_id must match
+    try {
+      $this->fixture->grantAccessToken($inputData, $authHeaders);
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    } catch ( OAuth2ServerException $e ) {
+      $this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
+    }
+    
+    // Confirm GET/POST
+    $authHeaders = array();
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'dev-abc', 'client_secret' => 'foo'); // When using auth, client_id must match
+    try {
+      $this->fixture->grantAccessToken($inputData, $authHeaders);
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    } catch ( OAuth2ServerException $e ) {
+      $this->assertNotEquals(OAuth2::ERROR_INVALID_CLIENT, $e->getMessage());
+    }
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken() with Auth code grant
+   * 
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeMandatoryParams() {
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'a', 'client_secret' => 'b');
+    $fakeAuthCode = array('client_id' => $inputData['client_id'], 'redirect_uri' => '/foo', 'expires' => time() + 60);
+    $fakeAccessToken = array('access_token' => 'abcde');
+    
+    // Ensure redirect URI and auth-code is mandatory
+    try {
+      $this->fixture = new OAuth2($mockStorage);
+      $this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, true); // Only required when this is set
+      $this->fixture->grantAccessToken($inputData + array('code' => 'foo'), array());
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    } catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
+    }
+    try {
+      $this->fixture = new OAuth2($mockStorage);
+      $this->fixture->grantAccessToken($inputData + array('redirect_uri' => 'foo'), array());
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    } catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_INVALID_REQUEST, $e->getMessage());
+    }
+  }
+  
+   /**
+   * Tests OAuth2->grantAccessToken() with Auth code grant
+   * 
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeNoToken() {
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'a', 'client_secret' => 'b', 'redirect_uri' => 'foo', 'code'=> 'foo');
+    
+    // Ensure missing auth code raises an error
+    try {
+      $this->fixture = new OAuth2($mockStorage);
+      $this->fixture->grantAccessToken($inputData + array(), array());
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    }
+    catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
+    }
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken() with checks the redirect URI
+   * 
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeRedirectChecked() {
+    $inputData = array('redirect_uri' => 'http://www.crossdomain.com/my/subdir', 'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code'=> 'foo');
+    $storedToken = array('redirect_uri' => 'http://www.example.com', 'client_id' => 'my_little_app', 'expires' => time() + 60);
+    
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $mockStorage->expects($this->any())
+      ->method('getAuthCode')
+      ->will($this->returnValue($storedToken));
+      
+    // Ensure that the redirect_uri is checked
+    try {
+      $this->fixture = new OAuth2($mockStorage);
+      $this->fixture->grantAccessToken($inputData, array());
+      
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    }
+    catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_REDIRECT_URI_MISMATCH, $e->getMessage());
+    }
+  }
+  
+	/**
+   * Tests OAuth2->grantAccessToken() with checks the client ID is matched
+   * 
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeClientIdChecked() {
+    $inputData = array('client_id' => 'another_app', 'grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'redirect_uri' => 'http://www.example.com/my/subdir', 'client_secret' => 'b', 'code'=> 'foo');
+    $storedToken = array('client_id' => 'my_little_app', 'redirect_uri' => 'http://www.example.com', 'expires' => time() + 60);
+    
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $mockStorage->expects($this->any())
+      ->method('getAuthCode')
+      ->will($this->returnValue($storedToken));
+      
+    // Ensure the client ID is checked
+    try {
+      $this->fixture = new OAuth2($mockStorage);
+      $this->fixture->grantAccessToken($inputData, array());
+      
+      $this->fail('The expected exception OAuth2ServerException was not thrown');
+    }
+    catch ( OAuth2ServerException $e ) {
+      $this->assertEquals(OAuth2::ERROR_INVALID_GRANT, $e->getMessage());
+    }
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken() with implicit
+   * 
+   */
+  public function testGrantAccessTokenWithGrantImplicit() {
+    $this->markTestIncomplete ( "grantAccessToken test not implemented" );
+    
+    $this->fixture->grantAccessToken(/* parameters */);
+  }
+  
+	/**
+   * Tests OAuth2->grantAccessToken() with user credentials
+   * 
+   */
+  public function testGrantAccessTokenWithGrantUser() {
+    $this->markTestIncomplete ( "grantAccessToken test not implemented" );
+    
+    $this->fixture->grantAccessToken(/* parameters */);
+  }
+  
+  
+	/**
+   * Tests OAuth2->grantAccessToken() with client credentials
+   * 
+   */
+  public function testGrantAccessTokenWithGrantClient() {
+    $this->markTestIncomplete ( "grantAccessToken test not implemented" );
+    
+    $this->fixture->grantAccessToken(/* parameters */);
+  }
+  
+	/**
+   * Tests OAuth2->grantAccessToken() with refresh token
+   * 
+   */
+  public function testGrantAccessTokenWithGrantRefresh() {
+    $this->markTestIncomplete ( "grantAccessToken test not implemented" );
+    
+    $this->fixture->grantAccessToken(/* parameters */);
+  }
+  
+	/**
+   * Tests OAuth2->grantAccessToken() with extension
+   * 
+   */
+  public function testGrantAccessTokenWithGrantExtension() {
+    $this->markTestIncomplete ( "grantAccessToken test not implemented" );
+    
+    $this->fixture->grantAccessToken(/* parameters */);
+  }
+  
+  /**
+   * Tests OAuth2->getAuthorizeParams()
+   */
+  public function testGetAuthorizeParams() {
+    // TODO Auto-generated OAuth2Test->testGetAuthorizeParams()
+    $this->markTestIncomplete ( "getAuthorizeParams test not implemented" );
+    
+    $this->fixture->getAuthorizeParams(/* parameters */);
+  
+  }
+  
+  /**
+   * Tests OAuth2->finishClientAuthorization()
+   */
+  public function testFinishClientAuthorization() {
+    // TODO Auto-generated OAuth2Test->testFinishClientAuthorization()
+    $this->markTestIncomplete ( "finishClientAuthorization test not implemented" );
+    
+    $this->fixture->finishClientAuthorization(/* parameters */);
+  
+  }
+
+  // Utility methods
+  
+  /**
+   * 
+   * @param string $interfaceName
+   */
+  protected function createBaseMock($interfaceName) {
+    $mockStorage = $this->getMock($interfaceName);
+    $mockStorage->expects($this->any())
+      ->method('checkClientCredentials')
+      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
+    $mockStorage->expects($this->any())
+      ->method('checkRestrictedGrantType')
+      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
+      
+     return $mockStorage;
+  }
+  
+  // Data Providers below:
+  
+  /**
+   * Dataprovider for testVerifyAccessTokenMalformedToken().
+   * 
+   * Produces malformed access tokens
+   */
+  public function generateMalformedTokens() {
+    return array(
+      array(array()), // an empty array as a token
+      array(array('expires' => 5)), // missing client_id
+      array(array('client_id' => 6)), // missing expires
+      array(array('something' => 6)), // missing both 'expires' and 'client_id'
+    );
+  }
+  
+  /**
+   * Dataprovider for testVerifyAccessTokenCheckExpiry().
+   * 
+   * Produces malformed access tokens
+   */
+  public function generateExpiryTokens() {
+    return array(
+      array(array('client_id' => 'blah', 'expires' => time() - 30),                 FALSE), // 30 seconds ago should fail
+      array(array('client_id' => 'blah', 'expires' => time() - 1),                  FALSE), // now-ish should fail
+      array(array('client_id' => 'blah', 'expires' => 0),                           FALSE), // 1970 should fail
+      array(array('client_id' => 'blah', 'expires' => time() + 30),                 TRUE),  // 30 seconds in the future should be valid
+      array(array('client_id' => 'blah', 'expires' => time() + 86400),              TRUE),  // 1 day in the future should be valid
+      array(array('client_id' => 'blah', 'expires' => time() + (365 * 86400)),      TRUE),  // 1 year should be valid
+      array(array('client_id' => 'blah', 'expires' => time() + (10 * 365 * 86400)), TRUE),  // 10 years should be valid
+    );
+  }
+  
+  /**
+   * Dataprovider for testVerifyAccessTokenCheckExpiry().
+   * 
+   * Produces malformed access tokens
+   */
+  public function generateScopes() {
+    $baseToken = array('client_id' => 'blah', 'expires' => time() + 60);
+    
+    return array(
+      array(null,   $baseToken + array(),                               TRUE), // missing scope is valif
+      array(null,   $baseToken + array('scope' => null),                TRUE), // null scope is valid
+      array('',     $baseToken + array('scope' => ''),                  TRUE), // empty scope is valid
+      array('read', $baseToken + array('scope' => 'read'),              TRUE), // exact same scope is valid
+      array('read', $baseToken + array('scope' => ' read '),            TRUE), // exact same scope is valid
+      array(' read ', $baseToken + array('scope' => 'read'),            TRUE), // exact same scope is valid
+      array('read', $baseToken + array('scope' => 'read write delete'), TRUE), // contains scope 
+      array('read', $baseToken + array('scope' => 'write read delete'), TRUE), // contains scope 
+      array('read', $baseToken + array('scope' => 'delete write read'), TRUE), // contains scope
+      
+      // Invalid combinations
+      array('read', $baseToken + array('scope' => 'write'),            FALSE),
+      array('read', $baseToken + array('scope' => 'apple banana'),     FALSE),
+      array('read', $baseToken + array('scope' => 'apple read-write'), FALSE),
+      array('read', $baseToken + array('scope' => 'apple read,write'), FALSE),
+      array('read', $baseToken + array('scope' => null),               FALSE),
+      array('read', $baseToken + array('scope' => ''),                 FALSE),
+    );
+  }
+  
+  /**
+   * Provider for OAuth2->grantAccessToken()
+   */
+  public function generateEmptyDataForGrant() {
+    return array(
+      array(
+        array(), array()
+      ),
+      array(
+        array(), array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE) // grant_type in auth headers should be ignored
+      ),
+      array(
+        array('not_grant_type' => 5), array()
+      ),
+    );
+  }
+}
+
Index: sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2OutputTest.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2OutputTest.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/tests/OAuth2OutputTest.php	(revision 6351)
@@ -0,0 +1,72 @@
+<?php
+require __DIR__ . '/../lib/OAuth2.php';
+require __DIR__ . '/../lib/IOAuth2Storage.php';
+require __DIR__ . '/../lib/IOAuth2GrantCode.php';
+
+/**
+ * OAuth2 test cases that invovle capturing output.
+ */
+class OAuth2OutputTest extends PHPUnit_Extensions_OutputTestCase {
+  
+  /**
+   * @var OAuth2
+   */
+  private $fixture;
+  
+  /**
+   * Tests OAuth2->grantAccessToken() with successful Auth code grant
+   * 
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeSuccess() {
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'redirect_uri' => 'http://www.example.com/my/subdir', 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code'=> 'foo');
+    $storedToken = array('redirect_uri' => 'http://www.example.com', 'client_id' => 'my_little_app', 'expires' => time() + 60);
+    
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $mockStorage->expects($this->any())
+      ->method('getAuthCode')
+      ->will($this->returnValue($storedToken));
+      
+    // Successful token grant will return a JSON encoded token:
+    $this->expectOutputRegex('/{"access_token":".*","expires_in":\d+,"token_type":"bearer"/');
+    $this->fixture = new OAuth2($mockStorage);
+    $this->fixture->grantAccessToken($inputData, array());
+  }
+  
+  /**
+   * Tests OAuth2->grantAccessToken() with successful Auth code grant, but without redreict_uri in the input
+   */
+  public function testGrantAccessTokenWithGrantAuthCodeSuccessWithoutRedirect() {
+    $inputData = array('grant_type' => OAuth2::GRANT_TYPE_AUTH_CODE, 'client_id' => 'my_little_app', 'client_secret' => 'b', 'code'=> 'foo');
+    $storedToken = array('redirect_uri' => 'http://www.example.com', 'client_id' => 'my_little_app', 'expires' => time() + 60);
+    
+    $mockStorage = $this->createBaseMock('IOAuth2GrantCode');
+    $mockStorage->expects($this->any())
+      ->method('getAuthCode')
+      ->will($this->returnValue($storedToken));
+      
+    // Successful token grant will return a JSON encoded token:
+    $this->expectOutputRegex('/{"access_token":".*","expires_in":\d+,"token_type":"bearer"/');
+    $this->fixture = new OAuth2($mockStorage);
+    $this->fixture->setVariable(OAuth2::CONFIG_ENFORCE_INPUT_REDIRECT, false); 
+    $this->fixture->grantAccessToken($inputData, array());
+  }
+  
+// Utility methods
+  
+  /**
+   * 
+   * @param string $interfaceName
+   */
+  protected function createBaseMock($interfaceName) {
+    $mockStorage = $this->getMock($interfaceName);
+    $mockStorage->expects($this->any())
+      ->method('checkClientCredentials')
+      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
+    $mockStorage->expects($this->any())
+      ->method('checkRestrictedGrantType')
+      ->will($this->returnValue(TRUE)); // Always return true for any combination of user/pass
+      
+     return $mockStorage;
+  }
+  
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/CHANGELOG.txt
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/CHANGELOG.txt	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/CHANGELOG.txt	(revision 6351)
@@ -0,0 +1,98 @@
+oauth2-php revision xxx, xxxx-xx-xx (development version)
+----------------------
+
+oauth2-php revision 23, 2011-01-25
+----------------------
+* introduce Drupal style getVariable() and setVariable, replace legacy
+  variable get/set functions.
+* remove hardcode PHP display_error and errror_reporting, as this should
+  be manually implement within 3rd party integration.
+* make verbose error as configurable and default disable, as this should
+  be manually enable within 3rd party integration.
+* add lib/OAuth2Client.inc and lib/OAuth2Exception.inc for client-side
+  implementation.
+
+oauth2-php revision 21, 2010-12-18
+----------------------
+* cleanup tabs and trailing whitespace at the end.
+* remove server/examples/mongo/lib/oauth.php and
+  server/examples/pdo/lib/oauth.php, so only keep single copy as
+  lib /oauth.php.
+* issue #5: Wrong variable name in get_access_token() in pdo_oatuh.php.
+* issue #6: mysql_create_tables.sql should allow scope to be NULL.
+* issue #7: authorize_client_response_type() is never used.
+* issue #9: Change "redirect_uri" filtering from FILTER_VALIDATE_URL to
+  FILTER_SANITIZE_URL.
+* better coding syntax for error() and callback_error().
+* better pdo_oauth2.php variable naming with change to
+  mysql_create_tables.sql.
+* change REGEX_CLIENT_ID as 3-32 characters long, so will work with md5()
+  result directly.
+* debug linkage to oauth2.php during previous commit.
+* debug redirect_uri check for AUTH_CODE_GRANT_TYPE, clone from
+  get_authorize_params().
+* update mysql_create_tables.sql with phpmyadmin export format.
+* rename library files, prepare for adding client-side implementation.
+* code cleanup with indent and spacing.
+* code cleanup true/false/null with TRUE/FALSE/NULL.
+* rename constants with OAUTH2_ prefix, prevent 3rd party integration
+  conflict.
+* remove HTTP 400 response constant, as useless refer to draft v10.
+* merge ERROR_INVALID_CLIENT_ID and ERROR_UNAUTHORIZED_CLIENT as
+  OAUTH2_ERROR_INVALID_CLIENT, as refer to that of draft v9 to v10 changes.
+* improve constants comment with doxygen syntax.
+* update class function call naming.
+* coding style clean up.
+* update part of documents.
+* change expirseRefreshToken() as unsetRefreshToken().
+* update token and auth code generation as md5() result, simpler for manual
+  debug with web browser.
+* update all documents.
+* restructure @ingroup.
+* rename checkRestrictedClientResponseTypes() as
+  checkRestrictedAuthResponseType().
+* rename checkRestrictedClientGrantTypes() as checkRestrictedGrantType().
+* rename error() as errorJsonResponse().
+* rename errorCallback() as errorDoRedirectUriCallback().
+* rename send401Unauthorized() as errorWWWAuthenticateResponseHeader(),
+  update support with different HTTP status code.
+* update __construct() with array input.
+* update finishClientAuthorization() with array input.
+* add get/set functions for $access_token_lifetime, $auth_code_lifetime and
+  $refresh_token_lifetime.
+* fix a lots of typos.
+* document all sample server implementation.
+* more documents.
+* add config.doxy for doxygen default setup.
+* add MIT LICENSE.txt.
+* add CHANGELOG.txt.
+
+oauth2-php revision 9, 2010-09-04
+----------------------
+- fixes for issues #2 and #4, updates oauth lib in the example folders to
+  the latest version in the 'lib' folder.
+- updates server library to revision 10 of the OAuth 2.0 spec.
+- adds an option for more verbose error messages to be returned in the JSON
+  response.
+- adds method to be overridden for expiring used refresh tokens.
+- fixes bug checking token expiration.
+- makes some more methods protected instead of private so they can be
+  overridden.
+- fixes issue #1 http://code.google.com/p/oauth2-php/issues/detail?id=1
+
+oauth2-php revision 7, 2010-06-29
+----------------------
+- fixed mongo connection constants.
+- updated store_refresh_token to include expires time.
+- changed example server directory structure
+- corrected "false" return result on get_stored_auth_code.
+- implemented PDO example adapter.
+- corrected an error in assertion grant type.
+- updated for ietf draft v9:
+  http://tools.ietf.org/html/draft-ietf-oauth-v2-09.
+- updated updated to support v9 lib.
+- added mysql table creation script.
+
+oauth2-php revision 0, 2010-06-27
+----------------------
+- initial commit.
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2RefreshTokens.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2RefreshTokens.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2RefreshTokens.php	(revision 6351)
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * Storage engines that want to support refresh tokens should
+ * implement this interface.
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-6
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-1.5
+ */
+interface IOAuth2RefreshTokens extends IOAuth2Storage {
+
+	/**
+	 * Grant refresh access tokens.
+	 *
+	 * Retrieve the stored data for the given refresh token.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be check with.
+	 *
+	 * @return
+	 * An associative array as below, and NULL if the refresh_token is
+	 * invalid:
+	 * - client_id: Stored client identifier.
+	 * - expires: Stored expiration unix timestamp.
+	 * - scope: (optional) Stored scope values in space-separated string.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-6
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function getRefreshToken($refresh_token);
+
+	/**
+	 * Take the provided refresh token values and store them somewhere.
+	 *
+	 * This function should be the storage counterpart to getRefreshToken().
+	 *
+	 * If storage fails for some reason, we're not currently checking for
+	 * any sort of success/failure, so you should bail out of the script
+	 * and provide a descriptive fail message.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be stored.
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $expires
+	 * expires to be stored.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = NULL);
+
+	/**
+	 * Expire a used refresh token.
+	 *
+	 * This is not explicitly required in the spec, but is almost implied.
+	 * After granting a new refresh token, the old one is no longer useful and
+	 * so should be forcibly expired in the data store so it can't be used again.
+	 *
+	 * If storage fails for some reason, we're not currently checking for
+	 * any sort of success/failure, so you should bail out of the script
+	 * and provide a descriptive fail message.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be expirse.
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function unsetRefreshToken($refresh_token);
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2Storage.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2Storage.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2Storage.php	(revision 6351)
@@ -0,0 +1,103 @@
+<?php
+
+/**
+ * All storage engines need to implement this interface in order to use OAuth2 server
+ * 
+ * @author David Rochwerger <catch.dave@gmail.com>
+ */
+interface IOAuth2Storage {
+
+	/**
+	 * Make sure that the client credentials is valid.
+	 * 
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $client_secret
+	 * (optional) If a secret is required, check that they've given the right one.
+	 *
+	 * @return
+	 * TRUE if the client credentials are valid, and MUST return FALSE if it isn't.
+	 * @endcode
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1
+	 *
+	 * @ingroup oauth2_section_3
+	 */
+	public function checkClientCredentials($client_id, $client_secret = NULL);
+
+	/**
+	 * Get client details corresponding client_id.
+	 *
+	 * OAuth says we should store request URIs for each registered client.
+	 * Implement this function to grab the stored URI for a given client id.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 *
+	 * @return array
+	 * Client details. Only mandatory item is the "registered redirect URI", and MUST
+	 * return FALSE if the given client does not exist or is invalid.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function getClientDetails($client_id);
+
+	/**
+	 * Look up the supplied oauth_token from storage.
+	 *
+	 * We need to retrieve access token data as we create and verify tokens.
+	 *
+	 * @param $oauth_token
+	 * oauth_token to be check with.
+	 *
+	 * @return
+	 * An associative array as below, and return NULL if the supplied oauth_token
+	 * is invalid:
+	 * - client_id: Stored client identifier.
+	 * - expires: Stored expiration in unix timestamp.
+	 * - scope: (optional) Stored scope values in space-separated string.
+	 *
+	 * @ingroup oauth2_section_7
+	 */
+	public function getAccessToken($oauth_token);
+
+	/**
+	 * Store the supplied access token values to storage.
+	 *
+	 * We need to store access token data as we create and verify tokens.
+	 *
+	 * @param $oauth_token
+	 * oauth_token to be stored.
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $user_id
+	 * User identifier to be stored.
+	 * @param $expires
+	 * Expiration to be stored.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL, $refresh_token);
+
+	/**
+	 * Check restricted grant types of corresponding client identifier.
+	 *
+	 * If you want to restrict clients to certain grant types, override this
+	 * function.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $grant_type
+	 * Grant type to be check with, would be one of the values contained in
+	 * OAuth2::GRANT_TYPE_REGEXP.
+	 *
+	 * @return
+	 * TRUE if the grant type is supported by this client identifier, and
+	 * FALSE if it isn't.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function checkRestrictedGrantType($client_id, $grant_type);
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2AuthenticateException.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2AuthenticateException.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2AuthenticateException.php	(revision 6351)
@@ -0,0 +1,55 @@
+<?php
+
+/**
+ * Send an error header with the given realm and an error, if provided.
+ * Suitable for the bearer token type.
+ *
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-04#section-2.4
+ *
+ * @ingroup oauth2_error
+ */
+class OAuth2AuthenticateException extends OAuth2ServerException {
+	
+	protected $header;
+
+	/**
+	 * 
+	 * @param $http_status_code
+	 * HTTP status code message as predefined.
+	 * @param $error
+	 * The "error" attribute is used to provide the client with the reason
+	 * why the access request was declined.
+	 * @param $error_description
+	 * (optional) The "error_description" attribute provides a human-readable text
+	 * containing additional information, used to assist in the understanding
+	 * and resolution of the error occurred.
+	 * @param $scope
+	 * A space-delimited list of scope values indicating the required scope
+	 * of the access token for accessing the requested resource.
+	 */
+	public function __construct($httpCode, $tokenType, $realm, $error, $error_description = NULL, $scope = NULL) {
+		parent::__construct($httpCode, $error, $error_description);
+		
+		if ($scope) {
+			$this->errorData['scope'] = $scope;
+		}
+		
+		// Build header
+		$this->header = sprintf('WWW-Authenticate: %s realm="%s"', ucwords($tokenType), $realm);
+		foreach ( $this->errorData as $key => $value ) {
+			$this->header .= ", $key=\"$value\"";
+		}
+	}
+
+	/**
+	 * Send out HTTP headers for JSON.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 *
+	 * @ingroup oauth2_section_5
+	 */
+	protected function sendHeaders() {
+		header($this->header);
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Client.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Client.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Client.php	(revision 6351)
@@ -0,0 +1,692 @@
+<?php
+
+/**
+ * OAuth2.0 draft v10 client-side implementation.
+ *
+ * @author Originally written by Naitik Shah <naitik@facebook.com>.
+ * @author Update to draft v10 by Edison Wong <hswong3i@pantarei-design.com>.
+ *
+ * @sa <a href="https://github.com/facebook/php-sdk">Facebook PHP SDK</a>.
+ */
+abstract class OAuth2Client {
+	
+	/**
+	 * The default Cache Lifetime (in seconds).
+	 */
+	const DEFAULT_EXPIRES_IN = 3600;
+	
+	/**
+	 * The default Base domain for the Cookie.
+	 */
+	const DEFAULT_BASE_DOMAIN = '';
+	
+	/**
+	 * Array of persistent variables stored.
+	 */
+	protected $conf = array();
+
+	/**
+	 * Returns a persistent variable.
+	 *
+	 * To avoid problems, always use lower case for persistent variable names.
+	 *
+	 * @param $name
+	 * The name of the variable to return.
+	 * @param $default
+	 * The default value to use if this variable has never been set.
+	 *
+	 * @return
+	 * The value of the variable.
+	 */
+	public function getVariable($name, $default = NULL) {
+		return isset($this->conf[$name]) ? $this->conf[$name] : $default;
+	}
+
+	/**
+	 * Sets a persistent variable.
+	 *
+	 * To avoid problems, always use lower case for persistent variable names.
+	 *
+	 * @param $name
+	 * The name of the variable to set.
+	 * @param $value
+	 * The value to set.
+	 */
+	public function setVariable($name, $value) {
+		$this->conf[$name] = $value;
+		return $this;
+	}
+
+	// Stuff that should get overridden by subclasses.
+	//
+	// I don't want to make these abstract, because then subclasses would have
+	// to implement all of them, which is too much work.
+	//
+	// So they're just stubs. Override the ones you need.
+	
+
+	/**
+	 * Initialize a Drupal OAuth2.0 Application.
+	 *
+	 * @param $config
+	 * An associative array as below:
+	 * - base_uri: The base URI for the OAuth2.0 endpoints.
+	 * - code: (optional) The authorization code.
+	 * - username: (optional) The username.
+	 * - password: (optional) The password.
+	 * - client_id: (optional) The application ID.
+	 * - client_secret: (optional) The application secret.
+	 * - authorize_uri: (optional) The end-user authorization endpoint URI.
+	 * - access_token_uri: (optional) The token endpoint URI.
+	 * - services_uri: (optional) The services endpoint URI.
+	 * - cookie_support: (optional) TRUE to enable cookie support.
+	 * - base_domain: (optional) The domain for the cookie.
+	 * - file_upload_support: (optional) TRUE if file uploads are enabled.
+	 */
+	public function __construct($config = array()) {
+		// We must set base_uri first.
+		$this->setVariable('base_uri', $config['base_uri']);
+		unset($config['base_uri']);
+		
+		// Use predefined OAuth2.0 params, or get it from $_REQUEST.
+		foreach ( array('code', 'username', 'password') as $name ) {
+			if (isset($config[$name])) {
+				$this->setVariable($name, $config[$name]);
+			} else if (isset($_REQUEST[$name]) && !empty($_REQUEST[$name])) {
+				$this->setVariable($name, $_REQUEST[$name]);
+			}
+			unset($config[$name]);
+		}
+		
+		// Endpoint URIs.
+		foreach ( array('authorize_uri', 'access_token_uri', 'services_uri') as $name ) {
+			if (isset($config[$name]))
+				if (substr($config[$name], 0, 4) == "http") {
+					$this->setVariable($name, $config[$name]);
+				} else {
+					$this->setVariable($name, $this->getVariable('base_uri') . $config[$name]);
+				}
+			unset($config[$name]);
+		}
+		
+		// Other else configurations.
+		foreach ( $config as $name => $value ) {
+			$this->setVariable($name, $value);
+		}
+	}
+
+	/**
+	 * Try to get session object from custom method.
+	 *
+	 * By default we generate session object based on access_token response, or
+	 * if it is provided from server with $_REQUEST. For sure, if it is provided
+	 * by server it should follow our session object format.
+	 *
+	 * Session object provided by server can ensure the correct expires and
+	 * base_domain setup as predefined in server, also you may get more useful
+	 * information for custom functionality, too. BTW, this may require for
+	 * additional remote call overhead.
+	 *
+	 * You may wish to override this function with your custom version due to
+	 * your own server-side implementation.
+	 *
+	 * @param $access_token
+	 * (optional) A valid access token in associative array as below:
+	 * - access_token: A valid access_token generated by OAuth2.0
+	 * authorization endpoint.
+	 * - expires_in: (optional) A valid expires_in generated by OAuth2.0
+	 * authorization endpoint.
+	 * - refresh_token: (optional) A valid refresh_token generated by OAuth2.0
+	 * authorization endpoint.
+	 * - scope: (optional) A valid scope generated by OAuth2.0
+	 * authorization endpoint.
+	 *
+	 * @return
+	 * A valid session object in associative array for setup cookie, and
+	 * NULL if not able to generate it with custom method.
+	 */
+	protected function getSessionObject($access_token = NULL) {
+		$session = NULL;
+		
+		// Try generate local version of session cookie.
+		if (!empty($access_token) && isset($access_token['access_token'])) {
+			$session['access_token'] = $access_token['access_token'];
+			$session['base_domain'] = $this->getVariable('base_domain', self::DEFAULT_BASE_DOMAIN);
+			$session['expires'] = isset($access_token['expires_in']) ? time() + $access_token['expires_in'] : time() + $this->getVariable('expires_in', self::DEFAULT_EXPIRES_IN);
+			$session['refresh_token'] = isset($access_token['refresh_token']) ? $access_token['refresh_token'] : '';
+			$session['scope'] = isset($access_token['scope']) ? $access_token['scope'] : '';
+			$session['secret'] = md5(base64_encode(pack('N6', mt_rand(), mt_rand(), mt_rand(), mt_rand(), mt_rand(), uniqid())));
+			
+			// Provide our own signature.
+			$sig = self::generateSignature($session, $this->getVariable('client_secret'));
+			$session['sig'] = $sig;
+		}
+		
+		// Try loading session from $_REQUEST.
+		if (!$session && isset($_REQUEST['session'])) {
+			$session = json_decode(get_magic_quotes_gpc() ? stripslashes($_REQUEST['session']) : $_REQUEST['session'], TRUE);
+		}
+		
+		return $session;
+	}
+
+	/**
+	 * Make an API call.
+	 *
+	 * Support both OAuth2.0 or normal GET/POST API call, with relative
+	 * or absolute URI.
+	 *
+	 * If no valid OAuth2.0 access token found in session object, this function
+	 * will automatically switch as normal remote API call without "oauth_token"
+	 * parameter.
+	 *
+	 * Assume server reply in JSON object and always decode during return. If
+	 * you hope to issue a raw query, please use makeRequest().
+	 *
+	 * @param $path
+	 * The target path, relative to base_path/service_uri or an absolute URI.
+	 * @param $method
+	 * (optional) The HTTP method (default 'GET').
+	 * @param $params
+	 * (optional The GET/POST parameters.
+	 *
+	 * @return
+	 * The JSON decoded response object.
+	 *
+	 * @throws OAuth2Exception
+	 */
+	public function api($path, $method = 'GET', $params = array()) {
+		if (is_array($method) && empty($params)) {
+			$params = $method;
+			$method = 'GET';
+		}
+		
+		// json_encode all params values that are not strings.
+		foreach ( $params as $key => $value ) {
+			if (!is_string($value)) {
+				$params[$key] = json_encode($value);
+			}
+		}
+		
+		$result = json_decode($this->makeOAuth2Request($this->getUri($path), $method, $params), TRUE);
+		
+		// Results are returned, errors are thrown.
+		if (is_array($result) && isset($result['error'])) {
+			$e = new OAuth2Exception($result);
+			switch ($e->getType()) {
+				// OAuth 2.0 Draft 10 style.
+				case 'invalid_token':
+					$this->setSession(NULL);
+				default :
+					$this->setSession(NULL);
+			}
+			throw $e;
+		}
+		return $result;
+	}
+	
+	// End stuff that should get overridden.
+	
+
+	/**
+	 * Default options for cURL.
+	 */
+	public static $CURL_OPTS = array(
+		CURLOPT_CONNECTTIMEOUT => 10,
+		CURLOPT_RETURNTRANSFER => TRUE,
+		CURLOPT_HEADER => TRUE,
+		CURLOPT_TIMEOUT => 60,
+		CURLOPT_USERAGENT => 'oauth2-draft-v10',
+		CURLOPT_HTTPHEADER => array("Accept: application/json")
+	);
+
+	/**
+	 * Set the Session.
+	 *
+	 * @param $session
+	 * (optional) The session object to be set. NULL if hope to frush existing
+	 * session object.
+	 * @param $write_cookie
+	 * (optional) TRUE if a cookie should be written. This value is ignored
+	 * if cookie support has been disabled.
+	 *
+	 * @return
+	 * The current OAuth2.0 client-side instance.
+	 */
+	public function setSession($session = NULL, $write_cookie = TRUE) {
+		$this->setVariable('_session', $this->validateSessionObject($session));
+		$this->setVariable('_session_loaded', TRUE);
+		if ($write_cookie) {
+			$this->setCookieFromSession($this->getVariable('_session'));
+		}
+		return $this;
+	}
+
+	/**
+	 * Get the session object.
+	 *
+	 * This will automatically look for a signed session via custom method,
+	 * OAuth2.0 grant type with authorization_code, OAuth2.0 grant type with
+	 * password, or cookie that we had already setup.
+	 *
+	 * @return
+	 * The valid session object with OAuth2.0 infomration, and NULL if not
+	 * able to discover any cases.
+	 */
+	public function getSession() {
+		if (!$this->getVariable('_session_loaded')) {
+			$session = NULL;
+			$write_cookie = TRUE;
+			
+			// Try obtain login session by custom method.
+			$session = $this->getSessionObject(NULL);
+			$session = $this->validateSessionObject($session);
+			
+			// grant_type == authorization_code.
+			if (!$session && $this->getVariable('code')) {
+				$access_token = $this->getAccessTokenFromAuthorizationCode($this->getVariable('code'));
+				$session = $this->getSessionObject($access_token);
+				$session = $this->validateSessionObject($session);
+			}
+			
+			// grant_type == password.
+			if (!$session && $this->getVariable('username') && $this->getVariable('password')) {
+				$access_token = $this->getAccessTokenFromPassword($this->getVariable('username'), $this->getVariable('password'));
+				$session = $this->getSessionObject($access_token);
+				$session = $this->validateSessionObject($session);
+			}
+			
+			// Try loading session from cookie if necessary.
+			if (!$session && $this->getVariable('cookie_support')) {
+				$cookie_name = $this->getSessionCookieName();
+				if (isset($_COOKIE[$cookie_name])) {
+					$session = array();
+					parse_str(trim(get_magic_quotes_gpc() ? stripslashes($_COOKIE[$cookie_name]) : $_COOKIE[$cookie_name], '"'), $session);
+					$session = $this->validateSessionObject($session);
+					// Write only if we need to delete a invalid session cookie.
+					$write_cookie = empty($session);
+				}
+			}
+			
+			$this->setSession($session, $write_cookie);
+		}
+		
+		return $this->getVariable('_session');
+	}
+
+	/**
+	 * Gets an OAuth2.0 access token from session.
+	 *
+	 * This will trigger getSession() and so we MUST initialize with required
+	 * configuration.
+	 *
+	 * @return
+	 * The valid OAuth2.0 access token, and NULL if not exists in session.
+	 */
+	public function getAccessToken() {
+		$session = $this->getSession();
+		return isset($session['access_token']) ? $session['access_token'] : NULL;
+	}
+
+	/**
+	 * Get access token from OAuth2.0 token endpoint with authorization code.
+	 *
+	 * This function will only be activated if both access token URI, client
+	 * identifier and client secret are setup correctly.
+	 *
+	 * @param $code
+	 * Authorization code issued by authorization server's authorization
+	 * endpoint.
+	 *
+	 * @return
+	 * A valid OAuth2.0 JSON decoded access token in associative array, and
+	 * NULL if not enough parameters or JSON decode failed.
+	 */
+	private function getAccessTokenFromAuthorizationCode($code) {
+		if ($this->getVariable('access_token_uri') && $this->getVariable('client_id') && $this->getVariable('client_secret')) {
+			return json_decode($this->makeRequest(
+				$this->getVariable('access_token_uri'),
+				'POST',
+				array(
+					'grant_type' => 'authorization_code',
+					'client_id' => $this->getVariable('client_id'),
+					'client_secret' => $this->getVariable('client_secret'),
+					'code' => $code,
+					'redirect_uri' => $this->getCurrentUri()
+				)
+			), TRUE);
+		}
+		return NULL;
+	}
+
+	/**
+	 * Get access token from OAuth2.0 token endpoint with basic user
+	 * credentials.
+	 *
+	 * This function will only be activated if both username and password
+	 * are setup correctly.
+	 *
+	 * @param $username
+	 * Username to be check with.
+	 * @param $password
+	 * Password to be check with.
+	 *
+	 * @return
+	 * A valid OAuth2.0 JSON decoded access token in associative array, and
+	 * NULL if not enough parameters or JSON decode failed.
+	 */
+	private function getAccessTokenFromPassword($username, $password) {
+		if ($this->getVariable('access_token_uri') && $this->getVariable('client_id') && $this->getVariable('client_secret')) {
+			return json_decode($this->makeRequest(
+				$this->getVariable('access_token_uri'),
+				'POST',
+				array(
+					'grant_type' => 'password',
+					'client_id' => $this->getVariable('client_id'),
+					'client_secret' => $this->getVariable('client_secret'),
+					'username' => $username,
+					'password' => $password
+				)
+			), TRUE);
+		}
+		return NULL;
+	}
+
+	/**
+	 * Make an OAuth2.0 Request.
+	 *
+	 * Automatically append "oauth_token" in query parameters if not yet
+	 * exists and able to discover a valid access token from session. Otherwise
+	 * just ignore setup with "oauth_token" and handle the API call AS-IS, and
+	 * so may issue a plain API call without OAuth2.0 protection.
+	 *
+	 * @param $path
+	 * The target path, relative to base_path/service_uri or an absolute URI.
+	 * @param $method
+	 * (optional) The HTTP method (default 'GET').
+	 * @param $params
+	 * (optional The GET/POST parameters.
+	 *
+	 * @return
+	 * The JSON decoded response object.
+	 *
+	 * @throws OAuth2Exception
+	 */
+	protected function makeOAuth2Request($path, $method = 'GET', $params = array()) {
+		if ((!isset($params['oauth_token']) || empty($params['oauth_token'])) && $oauth_token = $this->getAccessToken()) {
+			$params['oauth_token'] = $oauth_token;
+		}
+		return $this->makeRequest($path, $method, $params);
+	}
+
+	/**
+	 * Makes an HTTP request.
+	 *
+	 * This method can be overriden by subclasses if developers want to do
+	 * fancier things or use something other than cURL to make the request.
+	 *
+	 * @param $path
+	 * The target path, relative to base_path/service_uri or an absolute URI.
+	 * @param $method
+	 * (optional) The HTTP method (default 'GET').
+	 * @param $params
+	 * (optional The GET/POST parameters.
+	 * @param $ch
+	 * (optional) An initialized curl handle
+	 *
+	 * @return
+	 * The JSON decoded response object.
+	 */
+	protected function makeRequest($path, $method = 'GET', $params = array(), $ch = NULL) {
+		if (!$ch)
+			$ch = curl_init();
+		
+		$opts = self::$CURL_OPTS;
+		if ($params) {
+			switch ($method) {
+				case 'GET':
+					$path .= '?' . http_build_query($params, NULL, '&');
+					break;
+				// Method override as we always do a POST.
+				default :
+					if ($this->getVariable('file_upload_support')) {
+						$opts[CURLOPT_POSTFIELDS] = $params;
+					} else {
+						$opts[CURLOPT_POSTFIELDS] = http_build_query($params, NULL, '&');
+					}
+			}
+		}
+		$opts[CURLOPT_URL] = $path;
+		
+		// Disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
+		// for 2 seconds if the server does not support this header.
+		if (isset($opts[CURLOPT_HTTPHEADER])) {
+			$existing_headers = $opts[CURLOPT_HTTPHEADER];
+			$existing_headers[] = 'Expect:';
+			$opts[CURLOPT_HTTPHEADER] = $existing_headers;
+		} else {
+			$opts[CURLOPT_HTTPHEADER] = array('Expect:');
+		}
+		
+		curl_setopt_array($ch, $opts);
+		$result = curl_exec($ch);
+		
+		if (curl_errno($ch) == 60) { // CURLE_SSL_CACERT
+			error_log('Invalid or no certificate authority found, using bundled information');
+			curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/fb_ca_chain_bundle.crt');
+			$result = curl_exec($ch);
+		}
+		
+		if ($result === FALSE) {
+			$e = new OAuth2Exception(array('code' => curl_errno($ch), 'message' => curl_error($ch)));
+			curl_close($ch);
+			throw $e;
+		}
+		curl_close($ch);
+		
+		// Split the HTTP response into header and body.
+		list($headers, $body) = explode("\r\n\r\n", $result);
+		$headers = explode("\r\n", $headers);
+		
+		// We catch HTTP/1.1 4xx or HTTP/1.1 5xx error response.
+		if (strpos($headers[0], 'HTTP/1.1 4') !== FALSE || strpos($headers[0], 'HTTP/1.1 5') !== FALSE) {
+			$result = array('code' => 0, 'message' => '');
+			
+			if (preg_match('/^HTTP\/1.1 ([0-9]{3,3}) (.*)$/', $headers[0], $matches)) {
+				$result['code'] = $matches[1];
+				$result['message'] = $matches[2];
+			}
+			
+			// In case retrun with WWW-Authenticate replace the description.
+			foreach ( $headers as $header ) {
+				if (preg_match("/^WWW-Authenticate:.*error='(.*)'/", $header, $matches)) {
+					$result['error'] = $matches[1];
+				}
+			}
+			
+			return json_encode($result);
+		}
+		
+		return $body;
+	}
+
+	/**
+	 * The name of the cookie that contains the session object.
+	 *
+	 * @return
+	 * The cookie name.
+	 */
+	private function getSessionCookieName() {
+		return 'oauth2_' . $this->getVariable('client_id');
+	}
+
+	/**
+	 * Set a JS Cookie based on the _passed in_ session.
+	 *
+	 * It does not use the currently stored session - you need to explicitly
+	 * pass it in.
+	 *
+	 * @param $session
+	 * The session to use for setting the cookie.
+	 */
+	protected function setCookieFromSession($session = NULL) {
+		if (!$this->getVariable('cookie_support'))
+			return;
+		
+		$cookie_name = $this->getSessionCookieName();
+		$value = 'deleted';
+		$expires = time() - 3600;
+		$base_domain = $this->getVariable('base_domain', self::DEFAULT_BASE_DOMAIN);
+		if ($session) {
+			$value = '"' . http_build_query($session, NULL, '&') . '"';
+			$base_domain = isset($session['base_domain']) ? $session['base_domain'] : $base_domain;
+			$expires = isset($session['expires']) ? $session['expires'] : time() + $this->getVariable('expires_in', self::DEFAULT_EXPIRES_IN);
+		}
+		
+		// Prepend dot if a domain is found.
+		if ($base_domain)
+			$base_domain = '.' . $base_domain;
+		
+		// If an existing cookie is not set, we dont need to delete it.
+		if ($value == 'deleted' && empty($_COOKIE[$cookie_name]))
+			return;
+		
+		if (headers_sent())
+			error_log('Could not set cookie. Headers already sent.');
+		else
+			setcookie($cookie_name, $value, $expires, '/', $base_domain);
+	}
+
+	/**
+	 * Validates a session_version = 3 style session object.
+	 *
+	 * @param $session
+	 * The session object.
+	 *
+	 * @return
+	 * The session object if it validates, NULL otherwise.
+	 */
+	protected function validateSessionObject($session) {
+		// Make sure some essential fields exist.
+		if (is_array($session) && isset($session['access_token']) && isset($session['sig'])) {
+			// Validate the signature.
+			$session_without_sig = $session;
+			unset($session_without_sig['sig']);
+			
+			$expected_sig = self::generateSignature($session_without_sig, $this->getVariable('client_secret'));
+			
+			if ($session['sig'] != $expected_sig) {
+				error_log('Got invalid session signature in cookie.');
+				$session = NULL;
+			}
+		} else {
+			$session = NULL;
+		}
+		return $session;
+	}
+
+	/**
+	 * Since $_SERVER['REQUEST_URI'] is only available on Apache, we
+	 * generate an equivalent using other environment variables.
+	 */
+	function getRequestUri() {
+		if (isset($_SERVER['REQUEST_URI'])) {
+			$uri = $_SERVER['REQUEST_URI'];
+		} else {
+			if (isset($_SERVER['argv'])) {
+				$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
+			} elseif (isset($_SERVER['QUERY_STRING'])) {
+				$uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
+			} else {
+				$uri = $_SERVER['SCRIPT_NAME'];
+			}
+		}
+		// Prevent multiple slashes to avoid cross site requests via the Form API.
+		$uri = '/' . ltrim($uri, '/');
+		
+		return $uri;
+	}
+
+	/**
+	 * Returns the Current URL.
+	 *
+	 * @return
+	 * The current URL.
+	 */
+	protected function getCurrentUri() {
+		$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://' : 'http://';
+		$current_uri = $protocol . $_SERVER['HTTP_HOST'] . $this->getRequestUri();
+		$parts = parse_url($current_uri);
+		
+		$query = '';
+		if (!empty($parts['query'])) {
+			$params = array();
+			parse_str($parts['query'], $params);
+			$params = array_filter($params);
+			if (!empty($params)) {
+				$query = '?' . http_build_query($params, NULL, '&');
+			}
+		}
+		
+		// Use port if non default.
+		$port = '';
+		if (isset($parts['port']) && (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443))) {
+			$port = ':' . $parts['port'];
+		}
+		
+		
+		// Rebuild.
+		return $protocol . $parts['host'] . $port . $parts['path'] . $query;
+	}
+
+	/**
+	 * Build the URL for given path and parameters.
+	 *
+	 * @param $path
+	 * (optional) The path.
+	 * @param $params
+	 * (optional) The query parameters in associative array.
+	 *
+	 * @return
+	 * The URL for the given parameters.
+	 */
+	protected function getUri($path = '', $params = array()) {
+		$url = $this->getVariable('services_uri') ? $this->getVariable('services_uri') : $this->getVariable('base_uri');
+		
+		if (!empty($path))
+			if (substr($path, 0, 4) == "http")
+				$url = $path;
+			else
+				$url = rtrim($url, '/') . '/' . ltrim($path, '/');
+		
+		if (!empty($params))
+			$url .= '?' . http_build_query($params, NULL, '&');
+		
+		return $url;
+	}
+
+	/**
+	 * Generate a signature for the given params and secret.
+	 *
+	 * @param $params
+	 * The parameters to sign.
+	 * @param $secret
+	 * The secret to sign with.
+	 *
+	 * @return
+	 * The generated signature
+	 */
+	protected function generateSignature($params, $secret) {
+		// Work with sorted data.
+		ksort($params);
+		
+		// Generate the base string.
+		$base_string = '';
+		foreach ( $params as $key => $value ) {
+			$base_string .= $key . '=' . $value;
+		}
+		$base_string .= $secret;
+		
+		return md5($base_string);
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Exception.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Exception.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2Exception.php	(revision 6351)
@@ -0,0 +1,83 @@
+<?php
+
+/**
+ * OAuth2.0 draft v10 exception handling.
+ *
+ * @author Originally written by Naitik Shah <naitik@facebook.com>.
+ * @author Update to draft v10 by Edison Wong <hswong3i@pantarei-design.com>.
+ *
+ * @sa <a href="https://github.com/facebook/php-sdk">Facebook PHP SDK</a>.
+ */
+class OAuth2Exception extends Exception {
+	
+	/**
+	 * The result from the API server that represents the exception information.
+	 */
+	protected $result;
+
+	/**
+	 * Make a new API Exception with the given result.
+	 *
+	 * @param $result
+	 * The result from the API server.
+	 */
+	public function __construct($result) {
+		$this->result = $result;
+		
+		$code = isset($result['code']) ? $result['code'] : 0;
+		
+		if (isset($result['error'])) {
+			// OAuth 2.0 Draft 10 style
+			$message = $result['error'];
+		} elseif (isset($result['message'])) {
+			// cURL style
+			$message = $result['message'];
+		} else {
+			$message = 'Unknown Error. Check getResult()';
+		}
+		
+		parent::__construct($message, $code);
+	}
+
+	/**
+	 * Return the associated result object returned by the API server.
+	 *
+	 * @returns
+	 * The result from the API server.
+	 */
+	public function getResult() {
+		return $this->result;
+	}
+
+	/**
+	 * Returns the associated type for the error. This will default to
+	 * 'Exception' when a type is not available.
+	 *
+	 * @return
+	 * The type for the error.
+	 */
+	public function getType() {
+		if (isset($this->result['error'])) {
+			$message = $this->result['error'];
+			if (is_string($message)) {
+				// OAuth 2.0 Draft 10 style
+				return $message;
+			}
+		}
+		return 'Exception';
+	}
+
+	/**
+	 * To make debugging easier.
+	 *
+	 * @returns
+	 * The string representation of the error.
+	 */
+	public function __toString() {
+		$str = $this->getType() . ': ';
+		if ($this->code != 0) {
+			$str .= $this->code . ': ';
+		}
+		return $str . $this->message;
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantCode.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantCode.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantCode.php	(revision 6351)
@@ -0,0 +1,72 @@
+<?php
+
+/**
+ * Storage engines that support the "Authorization Code"
+ * grant type should implement this interface
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1
+ */
+interface IOAuth2GrantCode extends IOAuth2Storage {
+	
+	/**
+	 * The Authorization Code grant type supports a response type of "code". 
+	 * 
+	 * @var string
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-1.4.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2
+	 */
+	const RESPONSE_TYPE_CODE = OAuth2::RESPONSE_TYPE_AUTH_CODE;
+
+	/**
+	 * Fetch authorization code data (probably the most common grant type).
+	 *
+	 * Retrieve the stored data for the given authorization code.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_AUTH_CODE.
+	 *
+	 * @param $code
+	 * Authorization code to be check with.
+	 *
+	 * @return
+	 * An associative array as below, and NULL if the code is invalid:
+	 * - client_id: Stored client identifier.
+	 * - redirect_uri: Stored redirect URI.
+	 * - expires: Stored expiration in unix timestamp.
+	 * - scope: (optional) Stored scope values in space-separated string.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function getAuthCode($code);
+
+	/**
+	 * Take the provided authorization code values and store them somewhere.
+	 *
+	 * This function should be the storage counterpart to getAuthCode().
+	 *
+	 * If storage fails for some reason, we're not currently checking for
+	 * any sort of success/failure, so you should bail out of the script
+	 * and provide a descriptive fail message.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_AUTH_CODE.
+	 *
+	 * @param $code
+	 * Authorization code to be stored.
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $user_id
+	 * User identifier to be stored.
+	 * @param $redirect_uri
+	 * Redirect URI to be stored.
+	 * @param $expires
+	 * Expiration to be stored.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function setAuthCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = NULL);
+
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantImplicit.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantImplicit.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantImplicit.php	(revision 6351)
@@ -0,0 +1,20 @@
+<?php
+
+/**
+ * Storage engines that support the "Implicit"
+ * grant type should implement this interface
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2
+ */
+interface IOAuth2GrantImplicit extends IOAuth2Storage {
+	
+	/**
+	 * The Implicit grant type supports a response type of "token". 
+	 * 
+	 * @var string
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-1.4.2
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2
+	 */
+	const RESPONSE_TYPE_TOKEN = OAuth2::RESPONSE_TYPE_ACCESS_TOKEN;
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2.php	(revision 6351)
@@ -0,0 +1,1367 @@
+<?php
+require_once ROOTPATH . '/library/oauth2/lib/OAuth2ServerException.php';
+require_once ROOTPATH . '/library/oauth2/lib/OAuth2AuthenticateException.php';
+require_once ROOTPATH . '/library/oauth2/lib/OAuth2RedirectException.php';
+
+/**
+ * @mainpage
+ * OAuth 2.0 server in PHP, originally written for
+ * <a href="http://www.opendining.net/"> Open Dining</a>. Supports
+ * <a href="http://tools.ietf.org/html/draft-ietf-oauth-v2-20">IETF draft v20</a>.
+ *
+ * Source repo has sample servers implementations for
+ * <a href="http://php.net/manual/en/book.pdo.php"> PHP Data Objects</a> and
+ * <a href="http://www.mongodb.org/">MongoDB</a>. Easily adaptable to other
+ * storage engines.
+ *
+ * PHP Data Objects supports a variety of databases, including MySQL,
+ * Microsoft SQL Server, SQLite, and Oracle, so you can try out the sample
+ * to see how it all works.
+ *
+ * We're expanding the wiki to include more helpful documentation, but for
+ * now, your best bet is to view the oauth.php source - it has lots of
+ * comments.
+ *
+ * @author Tim Ridgely <tim.ridgely@gmail.com>
+ * @author Aaron Parecki <aaron@parecki.com>
+ * @author Edison Wong <hswong3i@pantarei-design.com>
+ * @author David Rochwerger <catch.dave@gmail.com>
+ *
+ * @see http://code.google.com/p/oauth2-php/
+ * @see https://github.com/quizlet/oauth2-php
+ */
+
+/**
+ * OAuth2.0 draft v20 server-side implementation.
+ * 
+ * @todo Add support for Message Authentication Code (MAC) token type.
+ *
+ * @author Originally written by Tim Ridgely <tim.ridgely@gmail.com>.
+ * @author Updated to draft v10 by Aaron Parecki <aaron@parecki.com>.
+ * @author Debug, coding style clean up and documented by Edison Wong <hswong3i@pantarei-design.com>.
+ * @author Refactored (including separating from raw POST/GET) and updated to draft v20 by David Rochwerger <catch.dave@gmail.com>.
+ */
+class OAuth2 {
+	
+	/**
+	 * Array of persistent variables stored.
+	 */
+	protected $conf = array();
+	
+	/**
+	 * Storage engine for authentication server
+	 * 
+	 * @var IOAuth2Storage
+	 */
+	protected $storage;
+	
+	/**
+	 * Keep track of the old refresh token. So we can unset
+	 * the old refresh tokens when a new one is issued.
+	 * 
+	 * @var string
+	 */
+	protected $oldRefreshToken;
+	
+	/**
+	 * Default values for configuration options.
+	 * 
+	 * @var int
+	 * @see OAuth2::setDefaultOptions()
+	 */
+	const DEFAULT_ACCESS_TOKEN_LIFETIME = 3600;
+	const DEFAULT_REFRESH_TOKEN_LIFETIME = 1209600;
+	const DEFAULT_AUTH_CODE_LIFETIME = 3600;
+	const DEFAULT_WWW_REALM = 'Service';
+	
+	/**
+	 * Configurable options.
+	 * 
+	 * @var string
+	 */
+	const CONFIG_ACCESS_LIFETIME = 3600; // The lifetime of access token in seconds.
+	const CONFIG_REFRESH_LIFETIME = 3600; // The lifetime of refresh token in seconds.
+	const CONFIG_AUTH_LIFETIME = 3600; // The lifetime of auth code in seconds.
+	const CONFIG_SUPPORTED_SCOPES = 'supported_scopes'; // Array of scopes you want to support
+	const CONFIG_TOKEN_TYPE = 'token_type'; // Token type to respond with. Currently only "Bearer" supported.
+	const CONFIG_WWW_REALM = 'realm';
+	const CONFIG_ENFORCE_INPUT_REDIRECT = 'enforce_redirect'; // Set to true to enforce redirect_uri on input for both authorize and token steps.
+	const CONFIG_ENFORCE_STATE = 'enforce_state'; // Set to true to enforce state to be passed in authorization (see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12)
+	
+
+	/**
+	 * Regex to filter out the client identifier (described in Section 2 of IETF draft).
+	 *
+	 * IETF draft does not prescribe a format for these, however I've arbitrarily
+	 * chosen alphanumeric strings with hyphens and underscores, 3-32 characters
+	 * long.
+	 *
+	 * Feel free to change.
+	 */
+	const CLIENT_ID_REGEXP = '/^[a-z0-9-_]{3,32}$/i';
+	
+	/**
+	 * @defgroup oauth2_section_5 Accessing a Protected Resource
+	 * @{
+	 *
+	 * Clients access protected resources by presenting an access token to
+	 * the resource server. Access tokens act as bearer tokens, where the
+	 * token string acts as a shared symmetric secret. This requires
+	 * treating the access token with the same care as other secrets (e.g.
+	 * end-user passwords). Access tokens SHOULD NOT be sent in the clear
+	 * over an insecure channel.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
+	 */
+	
+	/**
+	 * Used to define the name of the OAuth access token parameter
+	 * (POST & GET). This is for the "bearer" token type.
+	 * Other token types may use different methods and names.
+	 *
+	 * IETF Draft section 2 specifies that it should be called "access_token"
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.2
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-06#section-2.3
+	 */
+	const TOKEN_PARAM_NAME = 'access_token';
+	
+	/**
+	 * When using the bearer token type, there is a specifc Authorization header
+	 * required: "Bearer"
+	 * 
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-04#section-2.1
+	 */
+	const TOKEN_BEARER_HEADER_NAME = 'Bearer';
+	
+	/**
+	 * @}
+	 */
+	
+	/**
+	 * @defgroup oauth2_section_4 Obtaining Authorization
+	 * @{
+	 *
+	 * When the client interacts with an end-user, the end-user MUST first
+	 * grant the client authorization to access its protected resources.
+	 * Once obtained, the end-user authorization grant is expressed as an
+	 * authorization code which the client uses to obtain an access token.
+	 * To obtain an end-user authorization, the client sends the end-user to
+	 * the end-user authorization endpoint.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
+	 */
+	
+	/**
+	 * List of possible authentication response types.
+	 * The "authorization_code" mechanism exclusively supports 'code'
+	 * and the "implicit" mechanism exclusively supports 'token'.
+	 * 
+	 * @var string
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.1
+	 */
+	const RESPONSE_TYPE_AUTH_CODE = 'code';
+	const RESPONSE_TYPE_ACCESS_TOKEN = 'token';
+	
+	/**
+	 * @}
+	 */
+	
+	/**
+	 * @defgroup oauth2_section_5 Obtaining an Access Token
+	 * @{
+	 *
+	 * The client obtains an access token by authenticating with the
+	 * authorization server and presenting its authorization grant (in the form of
+	 * an authorization code, resource owner credentials, an assertion, or a
+	 * refresh token).
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
+	 */
+	
+	/**
+	 * Grant types support by draft 20
+	 */
+	const GRANT_TYPE_AUTH_CODE = 'authorization_code';
+	const GRANT_TYPE_IMPLICIT = 'token';
+	const GRANT_TYPE_USER_CREDENTIALS = 'password';
+	const GRANT_TYPE_CLIENT_CREDENTIALS = 'client_credentials';
+	const GRANT_TYPE_REFRESH_TOKEN = 'refresh_token';
+	const GRANT_TYPE_EXTENSIONS = 'extensions';
+	
+	/**
+	 * Regex to filter out the grant type.
+	 * NB: For extensibility, the grant type can be a URI
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.5
+	 */
+	const GRANT_TYPE_REGEXP = '#^(authorization_code|token|password|client_credentials|refresh_token|http://.*)$#';
+	
+	/**
+	 * @}
+	 */
+	
+	/**
+	 * Possible token types as defined by draft 20.
+	 * 
+	 * TODO: Add support for mac (and maybe other types?)
+	 * 
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7.1 
+	 */
+	const TOKEN_TYPE_BEARER = 'bearer';
+	const TOKEN_TYPE_MAC = 'mac'; // Currently unsupported
+	
+
+	/**
+	 * @defgroup self::HTTP_status HTTP status code
+	 * @{
+	 */
+	
+	/**
+	 * HTTP status codes for successful and error states as specified by draft 20.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const HTTP_FOUND = '302 Found';
+	const HTTP_BAD_REQUEST = '400 Bad Request';
+	const HTTP_UNAUTHORIZED = '401 Unauthorized';
+	const HTTP_FORBIDDEN = '403 Forbidden';
+	const HTTP_UNAVAILABLE = '503 Service Unavailable';
+	
+	/**
+	 * @}
+	 */
+	
+	/**
+	 * @defgroup oauth2_error Error handling
+	 * @{
+	 *
+	 * @todo Extend for i18n.
+	 * @todo Consider moving all error related functionality into a separate class.
+	 */
+	
+	/**
+	 * The request is missing a required parameter, includes an unsupported
+	 * parameter or parameter value, or is otherwise malformed.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_INVALID_REQUEST = 'invalid_request';
+	
+	/**
+	 * The client identifier provided is invalid.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_INVALID_CLIENT = 'invalid_client';
+	
+	/**
+	 * The client is not authorized to use the requested response type.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_UNAUTHORIZED_CLIENT = 'unauthorized_client';
+	
+	/**
+	 * The redirection URI provided does not match a pre-registered value.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2.4
+	 */
+	const ERROR_REDIRECT_URI_MISMATCH = 'redirect_uri_mismatch';
+	
+	/**
+	 * The end-user or authorization server denied the request.
+	 * This could be returned, for example, if the resource owner decides to reject
+	 * access to the client at a later point.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 */
+	const ERROR_USER_DENIED = 'access_denied';
+	
+	/**
+	 * The requested response type is not supported by the authorization server.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 */
+	const ERROR_UNSUPPORTED_RESPONSE_TYPE = 'unsupported_response_type';
+	
+	/**
+	 * The requested scope is invalid, unknown, or malformed.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 */
+	const ERROR_INVALID_SCOPE = 'invalid_scope';
+	
+	/**
+	 * The provided authorization grant is invalid, expired,
+	 * revoked, does not match the redirection URI used in the
+	 * authorization request, or was issued to another client.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_INVALID_GRANT = 'invalid_grant';
+	
+	/**
+	 * The authorization grant is not supported by the authorization server.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_UNSUPPORTED_GRANT_TYPE = 'unsupported_grant_type';
+	
+	/**
+	 * The request requires higher privileges than provided by the access token.
+	 * The resource server SHOULD respond with the HTTP 403 (Forbidden) status
+	 * code and MAY include the "scope" attribute with the scope necessary to
+	 * access the protected resource.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 */
+	const ERROR_INSUFFICIENT_SCOPE = 'invalid_scope';
+
+	/**
+	 * @}
+	 */
+	
+	/**
+	 * Creates an OAuth2.0 server-side instance.
+	 *
+	 * @param $config - An associative array as below of config options. See CONFIG_* constants.
+	 */
+	public function __construct(IOAuth2Storage $storage, $config = array()) {
+		$this->storage = $storage;
+		
+		// Configuration options
+		$this->setDefaultOptions();
+		foreach ( $config as $name => $value ) {
+			$this->setVariable($name, $value);
+		}
+	}
+
+	/**
+	 * Default configuration options are specified here.
+	 */
+	protected function setDefaultOptions() {
+		$this->conf = array(
+			self::CONFIG_ACCESS_LIFETIME => self::DEFAULT_ACCESS_TOKEN_LIFETIME,
+			self::CONFIG_REFRESH_LIFETIME => self::DEFAULT_REFRESH_TOKEN_LIFETIME,
+			self::CONFIG_AUTH_LIFETIME => self::DEFAULT_AUTH_CODE_LIFETIME,
+			self::CONFIG_WWW_REALM => self::DEFAULT_WWW_REALM,
+			self::CONFIG_TOKEN_TYPE => self::TOKEN_TYPE_BEARER,
+			self::CONFIG_ENFORCE_INPUT_REDIRECT => FALSE,
+			self::CONFIG_ENFORCE_STATE => FALSE,
+			self::CONFIG_SUPPORTED_SCOPES => array() // This is expected to be passed in on construction. Scopes can be an aribitrary string.
+		);  
+	}
+
+	/**
+	 * Returns a persistent variable.
+	 *
+	 * @param $name
+	 * The name of the variable to return.
+	 * @param $default
+	 * The default value to use if this variable has never been set.
+	 *
+	 * @return
+	 * The value of the variable.
+	 */
+	public function getVariable($name, $default = NULL) {
+		$name = strtolower($name);
+		
+		return isset($this->conf[$name]) ? $this->conf[$name] : $default;
+	}
+
+	/**
+	 * Sets a persistent variable.
+	 *
+	 * @param $name
+	 * The name of the variable to set.
+	 * @param $value
+	 * The value to set.
+	 */
+	public function setVariable($name, $value) {
+		$name = strtolower($name);
+		
+		$this->conf[$name] = $value;
+		return $this;
+	}
+
+	// Resource protecting (Section 5).
+	
+
+	/**
+	 * Check that a valid access token has been provided.
+	 * The token is returned (as an associative array) if valid.
+	 *
+	 * The scope parameter defines any required scope that the token must have.
+	 * If a scope param is provided and the token does not have the required
+	 * scope, we bounce the request.
+	 *
+	 * Some implementations may choose to return a subset of the protected
+	 * resource (i.e. "public" data) if the user has not provided an access
+	 * token or if the access token is invalid or expired.
+	 *
+	 * The IETF spec says that we should send a 401 Unauthorized header and
+	 * bail immediately so that's what the defaults are set to. You can catch
+	 * the exception thrown and behave differently if you like (log errors, allow
+	 * public access for missing tokens, etc)
+	 *
+	 * @param $scope
+	 * A space-separated string of required scope(s), if you want to check
+	 * for scope.
+	 * @return array
+	 * Token
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
+	 *
+	 * @ingroup oauth2_section_7
+	 */
+	public function verifyAccessToken($token_param, $scope = NULL) {
+		$tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
+		$realm = $this->getVariable(self::CONFIG_WWW_REALM);
+		
+		if (!$token_param) { // Access token was not provided
+			throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The request is missing a required parameter, includes an unsupported parameter or parameter value, repeats the same parameter, uses more than one method for including an access token, or is otherwise malformed.', $scope);
+		}
+		
+		// Get the stored token data (from the implementing subclass)
+		$token = $this->storage->getAccessToken($token_param);
+		if ($token === NULL) {
+			throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided is invalid.', $scope);
+		}
+		
+		// Check we have a well formed token
+		if (!isset($token["expires"]) || !isset($token["client_id"])) {
+			throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'Malformed token (missing "expires" or "client_id")', $scope);
+		}
+		
+		// Check token expiration (expires is a mandatory paramter)
+		if (isset($token["expires"]) && time() > $token["expires"]) {
+			throw new OAuth2AuthenticateException(self::HTTP_UNAUTHORIZED, $tokenType, $realm, self::ERROR_INVALID_GRANT, 'The access token provided has expired.', $scope);
+		}
+		
+		// Check scope, if provided
+		// If token doesn't have a scope, it's NULL/empty, or it's insufficient, then throw an error
+		if ($scope && (!isset($token["scope"]) || !$token["scope"] || !$this->checkScope($scope, $token["scope"]))) {
+			throw new OAuth2AuthenticateException(self::HTTP_FORBIDDEN, $tokenType, $realm, self::ERROR_INSUFFICIENT_SCOPE, 'The request requires higher privileges than provided by the access token.', $scope);
+		}
+		
+		
+		
+		session_write_close(); //Fecha session anterior
+		session_id($token['refresh_token']); //Define o id da session o mesmo do resfresh token
+		@session_start();
+		
+		/* TODO - Verificar melhor solução para verificação de tratamento para sessions já startadas
+		if(!isset($_SESSION))
+		    session_start();
+		*/
+		return $token;
+	}
+
+	/**
+	 * This is a convenience function that can be used to get the token, which can then
+	 * be passed to verifyAccessToken(). The constraints specified by the draft are
+	 * attempted to be adheared to in this method.
+	 * 
+	 * As per the Bearer spec (draft 8, section 2) - there are three ways for a client
+	 * to specify the bearer token, in order of preference: Authorization Header,
+	 * POST and GET.
+	 * 
+	 * NB: Resource servers MUST accept tokens via the Authorization scheme
+	 * (http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2).
+	 * 
+	 * @todo Should we enforce TLS/SSL in this function?
+	 * 
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.2
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-08#section-2.3
+	 * 
+	 * Old Android version bug (at least with version 2.2)
+	 * @see http://code.google.com/p/android/issues/detail?id=6684
+	 * 
+	 * We don't want to test this functionality as it relies on superglobals and headers:
+	 * @codeCoverageIgnoreStart
+	 */
+	public function getBearerToken() {
+	    
+		if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
+			$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
+		} elseif (function_exists('apache_request_headers')) {
+			$requestHeaders = apache_request_headers();
+			
+			// Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
+			$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
+			
+			if (isset($requestHeaders['Authorization'])) {
+				$headers = trim($requestHeaders['Authorization']);
+			}
+		}
+		
+		$tokenType = $this->getVariable(self::CONFIG_TOKEN_TYPE);
+		$realm = $this->getVariable(self::CONFIG_WWW_REALM);
+		// Check that exactly one method was used
+		$methodsUsed = !empty($headers) + isset($_GET[self::TOKEN_PARAM_NAME]) + isset($_POST[self::TOKEN_PARAM_NAME]);
+		if ($methodsUsed > 1) { 
+			throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Only one method may be used to authenticate at a time (Auth header, GET or POST).');
+		} elseif ($methodsUsed == 0) {
+			throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The access token was not found.');
+		}
+		
+		// HEADER: Get the access token from the header
+		if (!empty($headers)) {
+			if (!preg_match('/' . self::TOKEN_BEARER_HEADER_NAME . '\s(\S+)/', $headers, $matches)) {
+				throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'Malformed auth header');
+			}
+			
+			return $matches[1];
+		}		
+		// POST: Get the token from POST data
+		if (isset($_POST[self::TOKEN_PARAM_NAME])) {
+			if ($_SERVER['REQUEST_METHOD'] != 'POST') {
+				throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'When putting the token in the body, the method must be POST.');
+			}
+			
+			// IETF specifies content-type. NB: Not all webservers populate this _SERVER variable
+			if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] != 'application/x-www-form-urlencoded') {
+				throw new OAuth2AuthenticateException(self::HTTP_BAD_REQUEST, $tokenType, $realm, self::ERROR_INVALID_REQUEST, 'The content type for POST requests must be "application/x-www-form-urlencoded"');
+			}
+			
+			return $_POST[self::TOKEN_PARAM_NAME];
+		}
+		
+		// GET method
+		return $_GET[self::TOKEN_PARAM_NAME];
+	}
+
+	/** @codeCoverageIgnoreEnd */
+	
+	/**
+	 * Check if everything in required scope is contained in available scope.
+	 *
+	 * @param $required_scope
+	 * Required scope to be check with.
+	 *
+	 * @return
+	 * TRUE if everything in required scope is contained in available scope,
+	 * and False if it isn't.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-7
+	 *
+	 * @ingroup oauth2_section_7
+	 */
+	private function checkScope($required_scope, $available_scope) {
+		// The required scope should match or be a subset of the available scope
+		if (!is_array($required_scope)) {
+			$required_scope = explode(' ', trim($required_scope));
+		}
+		
+		if (!is_array($available_scope)) {
+			$available_scope = explode(' ', trim($available_scope));
+		}
+		
+		return (count(array_diff($required_scope, $available_scope)) == 0);
+	}
+
+	// Access token granting (Section 4).
+	
+
+	/**
+	 * Grant or deny a requested access token.
+	 * This would be called from the "/token" endpoint as defined in the spec.
+	 * Obviously, you can call your endpoint whatever you want.
+	 * 
+	 * @param $inputData - The draft specifies that the parameters should be
+	 * retrieved from POST, but you can override to whatever method you like.
+	 * @throws OAuth2ServerException
+	 * 
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.6
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-4.1.3
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+//ORIGINAL URI	
+//	public function grantAccessToken(array $inputData = NULL, array $authHeaders = NULL) {
+//		$filters = array(
+//			"grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
+//			"scope" => array("flags" => FILTER_REQUIRE_SCALAR),
+//			"code" => array("flags" => FILTER_REQUIRE_SCALAR),
+//			"redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
+//			"username" => array("flags" => FILTER_REQUIRE_SCALAR),
+//			"password" => array("flags" => FILTER_REQUIRE_SCALAR),
+//			"refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
+//		);
+//		
+//		// Input data by default can be either POST or GET
+//		if (!isset($inputData)) {
+//			$inputData = ($_SERVER['REQUEST_METHOD'] == 'POST') ? $_POST : $_GET;
+//		}
+//		
+//		// Basic authorization header
+//		$authHeaders = isset($authHeaders) ? $authHeaders : $this->getAuthorizationHeader();
+//		
+//                
+//                
+//		// Filter input data
+//		$input = filter_var_array($inputData, $filters);
+//		
+//              
+//                
+//		// Grant Type must be specified.
+//		if (!$input["grant_type"]) {
+//			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
+//		}
+//		
+//		// Authorize the client
+//		$client = $this->getClientCredentials($inputData, $authHeaders);
+//          
+//		if ($this->storage->checkClientCredentials($client[0], $client[1]) === FALSE) {
+//			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client credentials are invalid');
+//		}
+//		
+//		if (!$this->storage->checkRestrictedGrantType($client[0], $input["grant_type"])) {
+//			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNAUTHORIZED_CLIENT, 'The grant type is unauthorized for this client_id');
+//		}
+//		
+//		// Do the granting
+//		//
+//		switch ($input["grant_type"]) {
+//			case self::GRANT_TYPE_AUTH_CODE:
+//				if (!($this->storage instanceof IOAuth2GrantCode)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				
+//				if (!$input["code"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameter. "code" is required');
+//				}
+//				
+//				if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, "The redirect URI parameter is required.");
+//				}
+//				
+//				$stored = $this->storage->getAuthCode($input["code"]);
+//				
+//				// Check the code exists
+//				if ($stored === NULL || $client[0] != $stored["client_id"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "Refresh token doesn't exist or is invalid for the client");
+//				}
+//				
+//				// Validate the redirect URI. If a redirect URI has been provided on input, it must be validated
+//				if ($input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, "The redirect URI is missing or do not match");
+//				}
+//				
+//				if ($stored["expires"] < time()) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "The authorization code has expired");
+//				}
+//				break;
+//			
+//			case self::GRANT_TYPE_USER_CREDENTIALS:
+//				if (!($this->storage instanceof IOAuth2GrantUser)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				
+//				if (!$input["username"] || !$input["password"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
+//				}
+//				
+//				$stored = $this->storage->checkUserCredentials($client[0], $input["username"], $input["password"]);
+//
+//				if ($stored === FALSE) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
+//				}
+//				break;
+//			
+//			case self::GRANT_TYPE_CLIENT_CREDENTIALS:
+//				if (!($this->storage instanceof IOAuth2GrantClient)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				
+//				if (empty($client[1])) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client_secret is mandatory for the "client_credentials" grant type');
+//				}
+//				// NB: We don't need to check for $stored==false, because it was checked above already
+//				$stored = $this->storage->checkClientCredentialsGrant($client[0], $client[1]);
+//				break;
+//			
+//			case self::GRANT_TYPE_REFRESH_TOKEN:
+//				if (!($this->storage instanceof IOAuth2RefreshTokens)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				
+//				if (!$input["refresh_token"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
+//				}
+//				
+//				$stored = $this->storage->getRefreshToken($input["refresh_token"]);
+//				
+//				if ($stored === NULL || $client[0] != $stored["client_id"]) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Invalid refresh token');
+//				}
+//				
+//				if ($stored["expires"] < time()) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Refresh token has expired');
+//				}
+//				
+//				// store the refresh token locally so we can delete it when a new refresh token is generated
+//				$this->oldRefreshToken = $stored["refresh_token"];
+//				break;
+//			
+//			case self::GRANT_TYPE_IMPLICIT:
+//				/* TODO: NOT YET IMPLEMENTED */
+//				throw new OAuth2ServerException('501 Not Implemented', 'This OAuth2 library is not yet complete. This functionality is not implemented yet.');
+//				if (!($this->storage instanceof IOAuth2GrantImplicit)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				
+//				break;
+//			
+//			// Extended grant types:
+//			case filter_var($input["grant_type"], FILTER_VALIDATE_URL):
+//				if (!($this->storage instanceof IOAuth2GrantExtension)) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+//				}
+//				$uri = filter_var($input["grant_type"], FILTER_VALIDATE_URL);
+//				$stored = $this->storage->checkGrantExtension($uri, $inputData, $authHeaders);
+//				
+//				if ($stored === FALSE) {
+//					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
+//				}
+//				break;
+//			
+//			default :
+//				throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
+//		}
+//		
+//		if (!isset($stored["scope"])) {
+//			$stored["scope"] = NULL;
+//		}
+//		
+//		// Check scope, if provided
+//		if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
+//			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
+//		}
+//		
+//		$user_id = isset($stored['user_id']) ? $stored['user_id'] : null;
+//		$token = $this->createAccessToken($client[0], $user_id, $stored['scope']);
+//		
+//	
+//		// Send response
+//		$this->sendJsonHeaders();
+//		echo json_encode($token);
+//	}
+	
+	public function grantAccessToken(array $inputData = NULL, array $authHeaders = NULL) {
+		$filters = array(
+			"grant_type" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::GRANT_TYPE_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
+			"scope" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"code" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
+			"username" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"password" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"refresh_token" => array("flags" => FILTER_REQUIRE_SCALAR),
+		);
+		
+		// Input data by default can be either POST or GET
+		if (!isset($inputData)) {
+			$inputData = ($_SERVER['REQUEST_METHOD'] == 'POST') ? $_POST : $_GET;
+		}
+		
+		// Basic authorization header
+		$authHeaders = isset($authHeaders) ? $authHeaders : $this->getAuthorizationHeader();
+		
+                
+                
+		// Filter input data
+		$input = filter_var_array($inputData, $filters);
+		
+              
+                
+		// Grant Type must be specified.
+		if (!$input["grant_type"]) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
+		}
+		
+		// Authorize the client
+		$client = $this->getClientCredentials($inputData, $authHeaders);
+          
+		if ($this->storage->checkClientCredentials($client[0], $client[1]) === FALSE) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client credentials are invalid');
+		}
+		
+		if (!$this->storage->checkRestrictedGrantType($client[0], $input["grant_type"])) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNAUTHORIZED_CLIENT, 'The grant type is unauthorized for this client_id');
+		}
+		
+		// Do the granting
+		//
+		switch ($input["grant_type"]) {
+			case self::GRANT_TYPE_AUTH_CODE:
+				if (!($this->storage instanceof IOAuth2GrantCode)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				
+				if (!$input["code"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameter. "code" is required');
+				}
+				
+				if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, "The redirect URI parameter is required.");
+				}
+				
+				$stored = $this->storage->getAuthCode($input["code"]);
+				
+				// Check the code exists
+				if ($stored === NULL || $client[0] != $stored["client_id"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "Refresh token doesn't exist or is invalid for the client");
+				}
+				
+				// Validate the redirect URI. If a redirect URI has been provided on input, it must be validated
+				if ($input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, "The redirect URI is missing or do not match");
+				}
+				
+				if ($stored["expires"] < time()) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, "The authorization code has expired");
+				}
+				break;
+			
+			case self::GRANT_TYPE_USER_CREDENTIALS:
+				if (!($this->storage instanceof IOAuth2GrantUser)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				
+				if (!$input["username"] || !$input["password"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Missing parameters. "username" and "password" required');
+				}
+				
+				$stored = $this->storage->checkUserCredentials($client[0], $input["username"], $input["password"]);
+
+				if ($stored === FALSE) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
+				}
+				break;
+			
+			case self::GRANT_TYPE_CLIENT_CREDENTIALS:
+				if (!($this->storage instanceof IOAuth2GrantClient)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				
+				if (empty($client[1])) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'The client_secret is mandatory for the "client_credentials" grant type');
+				}
+				// NB: We don't need to check for $stored==false, because it was checked above already
+				$stored = $this->storage->checkClientCredentialsGrant($client[0], $client[1]);
+				break;
+			
+			case self::GRANT_TYPE_REFRESH_TOKEN:
+				if (!($this->storage instanceof IOAuth2RefreshTokens)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				
+				if (!$input["refresh_token"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'No "refresh_token" parameter found');
+				}
+				
+				$stored = $this->storage->getRefreshToken($input["refresh_token"]);
+				
+				if ($stored === NULL || $client[0] != $stored["client_id"]) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Invalid refresh token');
+				}
+				
+				if ($stored["expires"] < time()) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT, 'Refresh token has expired');
+				}
+				
+				// store the refresh token locally so we can delete it when a new refresh token is generated
+				$this->oldRefreshToken = $stored["refresh_token"];
+				
+				session_write_close(); //Fecha session anterior
+				session_id($stored['refresh_token']); //Define o id da session o mesmo do resfresh token
+				session_start();
+				
+				break;
+			
+			case self::GRANT_TYPE_IMPLICIT:
+				/* TODO: NOT YET IMPLEMENTED */
+				throw new OAuth2ServerException('501 Not Implemented', 'This OAuth2 library is not yet complete. This functionality is not implemented yet.');
+				if (!($this->storage instanceof IOAuth2GrantImplicit)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				
+				break;
+			
+			// Extended grant types:
+			case filter_var($input["grant_type"], FILTER_VALIDATE_URL):
+				if (!($this->storage instanceof IOAuth2GrantExtension)) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_UNSUPPORTED_GRANT_TYPE);
+				}
+				$uri = filter_var($input["grant_type"], FILTER_VALIDATE_URL);
+				$stored = $this->storage->checkGrantExtension($uri, $inputData, $authHeaders);
+				
+				if ($stored === FALSE) {
+					throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_GRANT);
+				}
+				break;
+			
+			default :
+				throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_REQUEST, 'Invalid grant_type parameter or parameter missing');
+		}
+		
+		if (!isset($stored["scope"])) {
+			$stored["scope"] = NULL;
+		}
+		
+		// Check scope, if provided
+		if ($input["scope"] && (!is_array($stored) || !isset($stored["scope"]) || !$this->checkScope($input["scope"], $stored["scope"]))) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.');
+		}
+		
+		$user_id = isset($stored['user_id']) ? $stored['user_id'] : null;
+		$token = $this->createAccessToken($client[0], $user_id, $stored['scope']);
+		
+		//Gerando Session Para o refresh_token
+		session_write_close(); //Fecha session anterior
+		session_start();
+		session_id($token['refresh_token']); //Define o id da session o mesmo do resfresh token
+		session_cache_expire(self::CONFIG_REFRESH_LIFETIME); //Define o tempo da session o mesmo do Refresh token	
+		
+		if(isset($input["username"]) && isset($input["password"]))
+		{
+		    $_SESSION['wallet']['user']['uid'] =     $input["username"];
+		    $_SESSION['wallet']['user']['password']       =  $input["password"];
+		    $_SESSION['wallet']['user']['uidNumber']       =  $user_id;
+		}
+		
+		
+		
+		//session_write_close(); //Fecha nova session
+		
+		// Send response
+		$this->sendJsonHeaders();
+		echo json_encode($token);
+	}
+
+	/**
+	 * Internal function used to get the client credentials from HTTP basic
+	 * auth or POST data.
+	 * 
+	 * According to the spec (draft 20), the client_id can be provided in
+	 * the Basic Authorization header (recommended) or via GET/POST.
+	 *
+	 * @return
+	 * A list containing the client identifier and password, for example
+	 * @code
+	 * return array(
+	 * CLIENT_ID,
+	 * CLIENT_SECRET
+	 * );
+	 * @endcode
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
+	 *
+	 * @ingroup oauth2_section_2
+	 */
+	protected function getClientCredentials(array $inputData, array $authHeaders) {
+		
+		// Basic Authentication is used
+		if (!empty($authHeaders['PHP_AUTH_USER'])) {
+			return array($authHeaders['PHP_AUTH_USER'], $authHeaders['PHP_AUTH_PW']);
+		} elseif (empty($inputData['client_id'])) { // No credentials were specified
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, 'Client id was not found in the headers or body');
+		} else {
+			// This method is not recommended, but is supported by specification
+			return array($inputData['client_id'], $inputData['client_secret']);
+		}
+	}
+
+	// End-user/client Authorization (Section 2 of IETF Draft).
+	
+
+	/**
+	 * Pull the authorization request data out of the HTTP request.
+	 * - The redirect_uri is OPTIONAL as per draft 20. But your implementation can enforce it
+	 * by setting CONFIG_ENFORCE_INPUT_REDIRECT to true.
+	 * - The state is OPTIONAL but recommended to enforce CSRF. Draft 21 states, however, that
+	 * CSRF protection is MANDATORY. You can enforce this by setting the CONFIG_ENFORCE_STATE to true.
+	 *
+	 * @param $inputData - The draft specifies that the parameters should be
+	 * retrieved from GET, but you can override to whatever method you like.
+	 * @return
+	 * The authorization parameters so the authorization server can prompt
+	 * the user for approval if valid.
+	 *
+	 * @throws OAuth2ServerException
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-21#section-10.12
+	 * 
+	 * @ingroup oauth2_section_3
+	 */
+	public function getAuthorizeParams(array $inputData = NULL) {
+		$filters = array(
+			"client_id" => array("filter" => FILTER_VALIDATE_REGEXP, "options" => array("regexp" => self::CLIENT_ID_REGEXP), "flags" => FILTER_REQUIRE_SCALAR),
+			"response_type" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"redirect_uri" => array("filter" => FILTER_SANITIZE_URL),
+			"state" => array("flags" => FILTER_REQUIRE_SCALAR),
+			"scope" => array("flags" => FILTER_REQUIRE_SCALAR)
+		);
+		
+		if (!isset($inputData)) {
+			$inputData = $_GET;
+		}
+		$input = filter_var_array($inputData, $filters);
+		
+		// Make sure a valid client id was supplied (we can not redirect because we were unable to verify the URI)
+		if (!$input["client_id"]) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "No client id supplied"); // We don't have a good URI to use
+		}
+		
+		// Get client details
+		$stored = $this->storage->getClientDetails($input["client_id"]);
+		if ($stored === FALSE) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_INVALID_CLIENT, "Client id does not exist");
+		}
+		
+		// Make sure a valid redirect_uri was supplied. If specified, it must match the stored URI.
+		// @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1.2
+		// @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+		// @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2.2.1
+		if (!$input["redirect_uri"] && !$stored["redirect_uri"]) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'No redirect URL was supplied or stored.');
+		}
+		if ($this->getVariable(self::CONFIG_ENFORCE_INPUT_REDIRECT) && !$input["redirect_uri"]) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI is mandatory and was not supplied.');
+		}
+		// Only need to validate if redirect_uri provided on input and stored.
+		if ($stored["redirect_uri"] && $input["redirect_uri"] && !$this->validateRedirectUri($input["redirect_uri"], $stored["redirect_uri"])) {
+			throw new OAuth2ServerException(self::HTTP_BAD_REQUEST, self::ERROR_REDIRECT_URI_MISMATCH, 'The redirect URI provided is missing or does not match');
+		}
+		
+		// Select the redirect URI
+		$input["redirect_uri"] = isset($input["redirect_uri"]) ? $input["redirect_uri"] : $stored["redirect_uri"];
+		
+		// type and client_id are required
+		if (!$input["response_type"]) {
+			throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, 'Invalid or missing response type.', $input["state"]);
+		}
+		
+		// Check requested auth response type against interfaces of storage engine
+		$reflect = new ReflectionClass($this->storage);
+		if (!$reflect->hasConstant('RESPONSE_TYPE_' . strtoupper($input['response_type']))) {
+			throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_UNSUPPORTED_RESPONSE_TYPE, NULL, $input["state"]);
+		}
+		
+		// Validate that the requested scope is supported
+		if ($input["scope"] && !$this->checkScope($input["scope"], $this->getVariable(self::CONFIG_SUPPORTED_SCOPES))) {
+			throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_SCOPE, 'An unsupported scope was requested.', $input["state"]);
+		}
+		
+		// Validate state parameter exists (if configured to enforce this)
+		if ($this->getVariable(self::CONFIG_ENFORCE_STATE) && !$input["state"]) {
+			throw new OAuth2RedirectException($input["redirect_uri"], self::ERROR_INVALID_REQUEST, "The state parameter is required.");
+		}
+		
+		// Return retrieved client details together with input
+		return ($input + $stored);
+	}
+
+	/**
+	 * Redirect the user appropriately after approval.
+	 *
+	 * After the user has approved or denied the access request the
+	 * authorization server should call this function to redirect the user
+	 * appropriately.
+	 *
+	 * @param $is_authorized
+	 * TRUE or FALSE depending on whether the user authorized the access.
+	 * @param $user_id
+	 * Identifier of user who authorized the client
+	 * @param $params
+	 * An associative array as below:
+	 * - response_type: The requested response: an access token, an
+	 * authorization code, or both.
+	 * - client_id: The client identifier as described in Section 2.
+	 * - redirect_uri: An absolute URI to which the authorization server
+	 * will redirect the user-agent to when the end-user authorization
+	 * step is completed.
+	 * - scope: (optional) The scope of the access request expressed as a
+	 * list of space-delimited strings.
+	 * - state: (optional) An opaque value used by the client to maintain
+	 * state between the request and callback.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function finishClientAuthorization($is_authorized, $user_id = NULL, $params = array()) {
+		
+		// We repeat this, because we need to re-validate. In theory, this could be POSTed
+		// by a 3rd-party (because we are not internally enforcing NONCEs, etc)
+		$params = $this->getAuthorizeParams($params);
+		
+		$params += array('scope' => NULL, 'state' => NULL);
+		extract($params);
+		
+		if ($state !== NULL) {
+			$result["query"]["state"] = $state;
+		}
+		
+		if ($is_authorized === FALSE) {
+			throw new OAuth2RedirectException($redirect_uri, self::ERROR_USER_DENIED, "The user denied access to your application", $state);
+		} else {
+			if ($response_type == self::RESPONSE_TYPE_AUTH_CODE) {
+				$result["query"]["code"] = $this->createAuthCode($client_id, $user_id, $redirect_uri, $scope);
+			} elseif ($response_type == self::RESPONSE_TYPE_ACCESS_TOKEN) {
+				$result["fragment"] = $this->createAccessToken($client_id, $user_id, $scope);
+			}
+		}
+		
+		$this->doRedirectUriCallback($redirect_uri, $result);
+	}
+
+	// Other/utility functions.
+	
+
+	/**
+	 * Redirect the user agent.
+	 *
+	 * Handle both redirect for success or error response.
+	 *
+	 * @param $redirect_uri
+	 * An absolute URI to which the authorization server will redirect
+	 * the user-agent to when the end-user authorization step is completed.
+	 * @param $params
+	 * Parameters to be pass though buildUri().
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	private function doRedirectUriCallback($redirect_uri, $params) {
+		header("HTTP/1.1 " . self::HTTP_FOUND);
+		header("Location: " . $this->buildUri($redirect_uri, $params));
+		exit();
+	}
+
+	/**
+	 * Build the absolute URI based on supplied URI and parameters.
+	 *
+	 * @param $uri
+	 * An absolute URI.
+	 * @param $params
+	 * Parameters to be append as GET.
+	 *
+	 * @return
+	 * An absolute URI with supplied parameters.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	private function buildUri($uri, $params) {
+		$parse_url = parse_url($uri);
+		
+		// Add our params to the parsed uri
+		foreach ( $params as $k => $v ) {
+			if (isset($parse_url[$k])) {
+				$parse_url[$k] .= "&" . http_build_query($v);
+			} else {
+				$parse_url[$k] = http_build_query($v);
+			}
+		}
+		
+		// Put humpty dumpty back together
+		return
+			((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "")
+			. ((isset($parse_url["user"])) ? $parse_url["user"]
+			. ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "")
+			. ((isset($parse_url["host"])) ? $parse_url["host"] : "")
+			. ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "")
+			. ((isset($parse_url["path"])) ? $parse_url["path"] : "")
+			. ((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "")
+			. ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "")
+		;
+	}
+
+	/**
+	 * Handle the creation of access token, also issue refresh token if support.
+	 *
+	 * This belongs in a separate factory, but to keep it simple, I'm just
+	 * keeping it here.
+	 *
+	 * @param $client_id
+	 * Client identifier related to the access token.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5
+	 * @ingroup oauth2_section_5
+	 */
+// FunÃ§Ã£o ORIGINAL;	
+//	protected function createAccessToken($client_id, $user_id, $scope = NULL) {
+//		
+//		$token = array(
+//			"access_token" => $this->genAccessToken(),
+//			"expires_in" => $this->getVariable(self::CONFIG_ACCESS_LIFETIME),
+//			"token_type" => $this->getVariable(self::CONFIG_TOKEN_TYPE),
+//			"scope" => $scope
+//		);
+//		
+//		$this->storage->setAccessToken($token["access_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_ACCESS_LIFETIME), $scope);
+//		
+//		// Issue a refresh token also, if we support them
+//		if ($this->storage instanceof IOAuth2RefreshTokens) {
+//			$token["refresh_token"] = $this->genAccessToken();
+//			$this->storage->setRefreshToken($token["refresh_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_REFRESH_LIFETIME), $scope);
+//			
+//			// If we've granted a new refresh token, expire the old one
+//			if ($this->oldRefreshToken) {
+//				$this->storage->unsetRefreshToken($this->oldRefreshToken);
+//				unset($this->oldRefreshToken);
+//			}
+//		}
+//		
+//		return $token;
+//	}
+	protected function createAccessToken($client_id, $user_id, $scope = NULL) {
+		
+		$token = array(
+			"access_token" => $this->genAccessToken(),
+			"expires_in" => $this->getVariable(self::CONFIG_ACCESS_LIFETIME),
+			"token_type" => $this->getVariable(self::CONFIG_TOKEN_TYPE),
+			"scope" => $scope
+		);
+		$token["refresh_token"] = $this->genAccessToken();
+		
+		$this->storage->setAccessToken($token["access_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_ACCESS_LIFETIME), $scope , $token['refresh_token']);
+		
+		// Issue a refresh token also, if we support them
+		if ($this->storage instanceof IOAuth2RefreshTokens) {
+			$this->storage->setRefreshToken($token["refresh_token"], $client_id, $user_id, time() + $this->getVariable(self::CONFIG_REFRESH_LIFETIME), $scope);
+			
+			// If we've granted a new refresh token, expire the old one
+			if ($this->oldRefreshToken) {
+				$this->storage->unsetRefreshToken($this->oldRefreshToken);
+				unset($this->oldRefreshToken);
+			}
+		}
+		
+		return $token;
+	}
+
+	/**
+	 * Handle the creation of auth code.
+	 *
+	 * This belongs in a separate factory, but to keep it simple, I'm just
+	 * keeping it here.
+	 *
+	 * @param $client_id
+	 * Client identifier related to the access token.
+	 * @param $redirect_uri
+	 * An absolute URI to which the authorization server will redirect the
+	 * user-agent to when the end-user authorization step is completed.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	private function createAuthCode($client_id, $user_id, $redirect_uri, $scope = NULL) {
+		$code = $this->genAuthCode();
+		$this->storage->setAuthCode($code, $client_id, $user_id, $redirect_uri, time() + $this->getVariable(self::CONFIG_AUTH_LIFETIME), $scope);
+		return $code;
+	}
+
+	/**
+	 * Generates an unique access token.
+	 *
+	 * Implementing classes may want to override this function to implement
+	 * other access token generation schemes.
+	 *
+	 * @return
+	 * An unique access token.
+	 *
+	 * @ingroup oauth2_section_4
+	 * @see OAuth2::genAuthCode()
+	 */
+	protected function genAccessToken() {
+		$tokenLen = 40;
+		if (file_exists('/dev/urandom')) { // Get 100 bytes of random data
+			$randomData = file_get_contents('/dev/urandom', false, null, 0, 100) . uniqid(mt_rand(), true);
+		} else {
+			$randomData = mt_rand() . mt_rand() . mt_rand() . mt_rand() . microtime(true) . uniqid(mt_rand(), true);
+		}
+		return substr(hash('sha512', $randomData), 0, $tokenLen);
+	}
+
+	/**
+	 * Generates an unique auth code.
+	 *
+	 * Implementing classes may want to override this function to implement
+	 * other auth code generation schemes.
+	 *
+	 * @return
+	 * An unique auth code.
+	 *
+	 * @ingroup oauth2_section_4
+	 * @see OAuth2::genAccessToken()
+	 */
+	protected function genAuthCode() {
+		return $this->genAccessToken(); // let's reuse the same scheme for token generation
+	}
+
+	/**
+	 * Pull out the Authorization HTTP header and return it.
+	 * According to draft 20, standard basic authorization is the only
+	 * header variable required (this does not apply to extended grant types).
+	 *
+	 * Implementing classes may need to override this function if need be.
+	 * 
+	 * @todo We may need to re-implement pulling out apache headers to support extended grant types
+	 *
+	 * @return
+	 * An array of the basic username and password provided.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-2.4.1
+	 * @ingroup oauth2_section_2
+	 */
+	protected function getAuthorizationHeader() {
+		return array(
+			'PHP_AUTH_USER' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
+			'PHP_AUTH_PW' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''
+		);
+	}
+
+	/**
+	 * Send out HTTP headers for JSON.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 *
+	 * @ingroup oauth2_section_5
+	 */
+	private function sendJsonHeaders() {
+		if (php_sapi_name() === 'cli' || headers_sent()) {
+			return;
+		}
+		
+		header("Content-Type: application/json");
+		header("Cache-Control: no-store");
+	}
+
+	/**
+	 * Internal method for validating redirect URI supplied 
+	 * @param string $inputUri
+	 * @param string $storedUri
+	 */
+	protected function validateRedirectUri($inputUri, $storedUri) {
+		if (!$inputUri || !$storedUri) {
+			return false; // if either one is missing, assume INVALID
+		}
+		return strcasecmp(substr($inputUri, 0, strlen($storedUri)), $storedUri) === 0;
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2RedirectException.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2RedirectException.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2RedirectException.php	(revision 6351)
@@ -0,0 +1,80 @@
+<?php
+
+/**
+ * Redirect the end-user's user agent with error message.
+ *
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1
+ *
+ * @ingroup oauth2_error
+ */
+class OAuth2RedirectException extends OAuth2ServerException {
+	
+	protected $redirectUri;
+
+	/**
+	 * @param $redirect_uri
+	 * An absolute URI to which the authorization server will redirect the
+	 * user-agent to when the end-user authorization step is completed.
+	 * @param $error
+	 * A single error code as described in Section 4.1.2.1
+	 * @param $error_description
+	 * (optional) A human-readable text providing additional information,
+	 * used to assist in the understanding and resolution of the error
+	 * occurred.
+	 * @param $state
+	 * (optional) REQUIRED if the "state" parameter was present in the client
+	 * authorization request. Set to the exact value received from the client.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.1.2.1
+	 *
+	 * @ingroup oauth2_error
+	 */
+	public function __construct($redirect_uri, $error, $error_description = NULL, $state = NULL) {
+		parent::__construct(OAuth2::HTTP_FOUND, $error, $error_description);
+		
+		$this->redirectUri = $redirect_uri;
+		if ($state) {
+			$this->errorData['state'] = $state;
+		}
+	
+	}
+
+	/**
+	 * Redirect the user agent.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	protected function sendHeaders() {
+		$params = array('query' => $this->errorData);
+		header("Location: " . $this->buildUri($this->redirectUri, $params));
+		exit(); // No point in printing out data if we're redirecting
+	}
+
+	/**
+	 * Build the absolute URI based on supplied URI and parameters.
+	 *
+	 * @param $uri
+	 * An absolute URI.
+	 * @param $params
+	 * Parameters to be append as GET.
+	 *
+	 * @return
+	 * An absolute URI with supplied parameters.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	protected function buildUri($uri, $params) {
+		$parse_url = parse_url($uri);
+		
+		// Add our params to the parsed uri
+		foreach ( $params as $k => $v ) {
+			if (isset($parse_url[$k]))
+				$parse_url[$k] .= "&" . http_build_query($v);
+			else
+				$parse_url[$k] = http_build_query($v);
+		}
+		
+		// Put humpty dumpty back together
+		return ((isset($parse_url["scheme"])) ? $parse_url["scheme"] . "://" : "") . ((isset($parse_url["user"])) ? $parse_url["user"] . ((isset($parse_url["pass"])) ? ":" . $parse_url["pass"] : "") . "@" : "") . ((isset($parse_url["host"])) ? $parse_url["host"] : "") . ((isset($parse_url["port"])) ? ":" . $parse_url["port"] : "") . ((isset($parse_url["path"])) ? $parse_url["path"] : "") . ((isset($parse_url["query"])) ? "?" . $parse_url["query"] : "") . ((isset($parse_url["fragment"])) ? "#" . $parse_url["fragment"] : "");
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantExtension.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantExtension.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantExtension.php	(revision 6351)
@@ -0,0 +1,35 @@
+<?php
+
+/**
+ * Storage engines that support the "Extensible"
+ * grant types should implement this interface
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.5
+ */
+interface IOAuth2GrantExtension extends IOAuth2Storage {
+
+	/**
+	 * Check any extended grant types.
+	 * 
+	 * @param string $uri
+	 * URI of the grant type definition
+	 * @param array $inputData
+	 * Unfiltered input data. The source is *not* guaranteed to be POST (but
+	 * is likely to be).
+	 * @param array $authHeaders
+	 * Authorization headers
+	 * @return
+	 * FALSE if the authorization is rejected or not support.
+	 * TRUE or an associative array if you wantto verify the scope:
+	 * @code
+	 * return array(
+	 * 'scope' => <stored scope values (space-separated string)>,
+	 * );
+	 * @endcode
+	 * 
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-1.4.5
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.2
+	 */
+	public function checkGrantExtension($uri, array $inputData, array $authHeaders);
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantClient.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantClient.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantClient.php	(revision 6351)
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * Storage engines that support the "Client Credentials"
+ * grant type should implement this interface
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.4
+ */
+interface IOAuth2GrantClient extends IOAuth2Storage {
+
+	/**
+	 * Required for OAuth2::GRANT_TYPE_CLIENT_CREDENTIALS.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $client_secret
+	 * (optional) If a secret is required, check that they've given the right one.
+	 *
+	 * @return
+	 * TRUE if the client credentials are valid, and MUST return FALSE if it isn't.
+	 * When using "client credentials" grant mechanism and you want to
+	 * verify the scope of a user's access, return an associative array
+	 * with the scope values as below. We'll check the scope you provide
+	 * against the requested scope before providing an access token:
+	 * @code
+	 * return array(
+	 * 'scope' => <stored scope values (space-separated string)>,
+	 * );
+	 * @endcode
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.4.2
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function checkClientCredentialsGrant($client_id, $client_secret);
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantUser.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantUser.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/IOAuth2GrantUser.php	(revision 6351)
@@ -0,0 +1,46 @@
+<?php
+
+/**
+ * Storage engines that support the "Resource Owner Password Credentials"
+ * grant type should implement this interface
+ * 
+ * @author Dave Rochwerger <catch.dave@gmail.com>
+ * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.3
+ */
+interface IOAuth2GrantUser extends IOAuth2Storage {
+
+	/**
+	 * Grant access tokens for basic user credentials.
+	 *
+	 * Check the supplied username and password for validity.
+	 *
+	 * You can also use the $client_id param to do any checks required based
+	 * on a client, if you need that.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_USER_CREDENTIALS.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $username
+	 * Username to be check with.
+	 * @param $password
+	 * Password to be check with.
+	 *
+	 * @return
+	 * TRUE if the username and password are valid, and FALSE if it isn't.
+	 * Moreover, if the username and password are valid, and you want to
+	 * verify the scope of a user's access, return an associative array
+	 * with the scope values as below. We'll check the scope you provide
+	 * against the requested scope before providing an access token:
+	 * @code
+	 * return array(
+	 * 'scope' => <stored scope values (space-separated string)>,
+	 * );
+	 * @endcode
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-4.3
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function checkUserCredentials($client_id, $username, $password);
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2ServerException.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2ServerException.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/lib/OAuth2ServerException.php	(revision 6351)
@@ -0,0 +1,82 @@
+<?php
+
+/**
+ * OAuth2 errors that require termination of OAuth2 due to
+ * an error.
+ *
+ */
+class OAuth2ServerException extends Exception {
+	
+	protected $httpCode;
+	protected $errorData = array();
+
+	/**
+	 * @param $http_status_code
+	 * HTTP status code message as predefined.
+	 * @param $error
+	 * A single error code.
+	 * @param $error_description
+	 * (optional) A human-readable text providing additional information,
+	 * used to assist in the understanding and resolution of the error
+	 * occurred.
+	 */
+	public function __construct($http_status_code, $error, $error_description = NULL) {
+		parent::__construct($error);
+		
+		$this->httpCode = $http_status_code;
+		
+		$this->errorData['error'] = $error;
+		if ($error_description) {
+			$this->errorData['error_description'] = $error_description;
+		}
+	}
+
+	/**
+	 * @return string 
+	 */
+	public function getDescription() {
+		return isset($this->errorData['error_description']) ? $this->errorData['error_description'] : null;
+	}
+
+	/**
+	 * @return string 
+	 */
+	public function getHttpCode() {
+		return $this->httpCode;
+	}
+
+	/**
+	 * Send out error message in JSON.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 *
+	 * @ingroup oauth2_error
+	 */
+	public function sendHttpResponse() {
+		header("HTTP/1.1 " . $this->httpCode);
+		$this->sendHeaders();
+		echo (string) $this;
+		exit();
+	}
+
+	/**
+	 * Send out HTTP headers for JSON.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.1
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-5.2
+	 *
+	 * @ingroup oauth2_section_5
+	 */
+	protected function sendHeaders() {
+		header("Content-Type: application/json");
+		header("Cache-Control: no-store");
+	}
+
+	/**
+	 * @see Exception::__toString()
+	 */
+	public function __toString() {
+		return json_encode($this->errorData);
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/authorize.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/authorize.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/authorize.php	(revision 6351)
@@ -0,0 +1,42 @@
+<?php
+
+/**
+ * @file
+ * Sample authorize endpoint.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/MongoOAuth2.php";
+
+$oauth = new MongoOAuth2();
+
+if ($_POST) {
+	$oauth->finishClientAuthorization($_POST["accept"] == "Yep", $_POST);
+}
+
+try {
+	$auth_params = $oauth->getAuthorizeParams();
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+?>
+<html>
+<head>
+Authorize
+</head>
+<body>
+<form method="post" action="authorize.php">
+      <?php foreach ($auth_params as $k => $v) { ?>
+      <input type="hidden" name="<?php echo $k ?>"
+	value="<?php echo $v ?>" />
+      <?php } ?>
+      Do you authorize the app to do its thing?
+      <p><input type="submit" name="accept" value="Yep" /> <input
+	type="submit" name="accept" value="Nope" /></p>
+</form>
+</body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/lib/OAuth2StorageMongo.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/lib/OAuth2StorageMongo.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/lib/OAuth2StorageMongo.php	(revision 6351)
@@ -0,0 +1,175 @@
+<?php
+
+/**
+ * @file
+ * Sample OAuth2 Library Mongo DB Implementation.
+ * 
+ */
+
+require __DIR__ . '/../../../../lib/OAuth2.php';
+require __DIR__ . '/../../../../lib/IOAuth2Storage.php';
+require __DIR__ . '/../../../../lib/IOAuth2GrantCode.php';
+require __DIR__ . '/../../../../lib/IOAuth2RefreshTokens.php';
+
+/**
+ * WARNING: This example file has not been kept up to date like the PDO example has.
+ * FIXME: Update the Mongo examples
+ * 
+ * Mongo storage engine for the OAuth2 Library.
+ */
+class OAuth2StorageMongo implements IOAuth2GrantCode, IOAuth2RefreshTokens {
+	
+	/**
+	 * Change this to something unique for your system
+	 * @var string
+	 */
+	const SALT = 'CHANGE_ME!';
+	
+	const CONNECTION = 'mongodb://user:pass@mongoserver/mydb';
+	const DB = 'mydb';
+	
+	/**
+	 * @var Mongo
+	 */
+	private $db;
+
+	/**
+	 * Implements OAuth2::__construct().
+	 */
+	public function __construct(PDO $db) {
+		
+		$mongo = new Mongo(self::CONNECTION);
+		$this->db = $mongo->selectDB(self::DB);
+	}
+
+	/**
+	 * Release DB connection during destruct.
+	 */
+	function __destruct() {
+		$this->db = NULL; // Release db connection
+	}
+
+	/**
+	 * Handle PDO exceptional cases.
+	 */
+	private function handleException($e) {
+		echo 'Database error: ' . $e->getMessage();
+		exit();
+	}
+
+	/**
+	 * Little helper function to add a new client to the database.
+	 *
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $client_secret
+	 * Client secret to be stored.
+	 * @param $redirect_uri
+	 * Redirect URI to be stored.
+	 */
+	public function addClient($client_id, $client_secret, $redirect_uri) {
+		$this->db->clients->insert(array("_id" => $client_id, "pw" => $this->hash($client_secret, $client_id), "redirect_uri" => $redirect_uri));
+	}
+
+	/**
+	 * Implements IOAuth2Storage::checkClientCredentials().
+	 *
+	 */
+	public function checkClientCredentials($client_id, $client_secret = NULL) {
+		$client = $this->db->clients->findOne(array("_id" => $client_id, "pw" => $client_secret));
+		return $this->checkPassword($client_secret, $result['client_secret'], $client_id);
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getRedirectUri().
+	 */
+	public function getClientDetails($client_id) {
+		$result = $this->db->clients->findOne(array("_id" => $client_id), array("redirect_uri"));
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getAccessToken().
+	 */
+	public function getAccessToken($oauth_token) {
+		return $this->db->tokens->findOne(array("_id" => $oauth_token));
+	}
+
+	/**
+	 * Implements IOAuth2Storage::setAccessToken().
+	 */
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL) {
+		$this->db->tokens->insert(array("_id" => $oauth_token, "client_id" => $client_id, "expires" => $expires, "scope" => $scope));
+	}
+
+	/**
+	 * @see IOAuth2Storage::getRefreshToken()
+	 */
+	public function getRefreshToken($refresh_token) {
+		return $this->getToken($refresh_token, TRUE);
+	}
+
+	/**
+	 * @see IOAuth2Storage::setRefreshToken()
+	 */
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = NULL) {
+		return $this->setToken($refresh_token, $client_id, $user_id, $expires, $scope, TRUE);
+	}
+
+	/**
+	 * @see IOAuth2Storage::unsetRefreshToken()
+	 */
+	public function unsetRefreshToken($refresh_token) {
+		try {
+			$sql = 'DELETE FROM ' . self::TABLE_TOKENS . ' WHERE refresh_token = :refresh_token';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':refresh_token', $refresh_token, PDO::PARAM_STR);
+			$stmt->execute();
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getAuthCode().
+	 */
+	public function getAuthCode($code) {
+		$stored_code = $this->db->auth_codes->findOne(array("_id" => $code));
+		return $stored_code !== NULL ? $stored_code : FALSE;
+	}
+
+	/**
+	 * Implements IOAuth2Storage::setAuthCode().
+	 */
+	public function setAuthCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = NULL) {
+		$this->db->auth_codes->insert(array("_id" => $code, "client_id" => $client_id, "redirect_uri" => $redirect_uri, "expires" => $expires, "scope" => $scope));
+	}
+
+	/**
+	 * @see IOAuth2Storage::checkRestrictedGrantType()
+	 */
+	public function checkRestrictedGrantType($client_id, $grant_type) {
+		return TRUE; // Not implemented
+	}
+
+	/**
+	 * Change/override this to whatever your own password hashing method is.
+	 * 
+	 * @param string $secret
+	 * @return string
+	 */
+	protected function hash($client_secret, $client_id) {
+		return hash('blowfish', $client_id . $client_secret . self::SALT);
+	}
+
+	/**
+	 * Checks the password.
+	 * Override this if you need to
+	 * 
+	 * @param string $client_id
+	 * @param string $client_secret
+	 * @param string $actualPassword
+	 */
+	protected function checkPassword($try, $client_secret, $client_id) {
+		return $try == $this->hash($client_secret, $client_id);
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/protected_resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/protected_resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/protected_resource.php	(revision 6351)
@@ -0,0 +1,37 @@
+<?php
+
+/**
+ * @file
+ * Sample protected resource.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/OAuth2StorageMongo.php";
+
+$token = isset($_GET[OAuth2::TOKEN_PARAM_NAME]) ? $_GET[OAuth2::TOKEN_PARAM_NAME] : null;
+
+try {
+	$oauth = new OAuth2(new OAuth2StorageMongo());
+	$token = $oauth->getBearerToken();
+	$oauth->verifyAccessToken($token);
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+// With a particular scope, you'd do:
+// $oauth->verifyAccessToken("scope_name");
+
+
+?>
+
+<html>
+	<head>
+		<title>Hello!</title>
+	</head>
+	<body>
+		<p>This is a secret.</p>
+	</body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/token.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/token.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/token.php	(revision 6351)
@@ -0,0 +1,19 @@
+<?php
+
+/**
+ * @file
+ * Sample token endpoint.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/MongoOAuth2.php";
+
+$oauth = new MongoOAuth2();
+try {
+	$oauth->grantAccessToken();
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/addclient.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/addclient.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/mongo/addclient.php	(revision 6351)
@@ -0,0 +1,33 @@
+<?php
+
+/**
+ * @file
+ * Sample client add script.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ */
+
+require "lib/MongoOAuth2.php";
+
+if ($_POST && isset($_POST["client_id"]) && isset($_POST["client_secret"]) && isset($_POST["redirect_uri"])) {
+	$oauth = new MongoOAuth2();
+	$oauth->addClient($_POST["client_id"], $_POST["client_secret"], $_POST["redirect_uri"]);
+}
+
+?>
+
+<html>
+<head>
+Add Client
+</head>
+<body>
+<form method="post" action="addclient.php">
+<p><label for="client_id">Client ID:</label> <input type="text"
+	name="client_id" id="client_id" /></p>
+<p><label for="client_secret">Client Secret (password/key):</label> <input
+	type="text" name="client_secret" id="client_secret" /></p>
+<p><label for="redirect_uri">Redirect URI:</label> <input type="text"
+	name="redirect_uri" id="redirect_uri" /></p>
+<input type="submit" value="Submit" /></form>
+</body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/authorize.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/authorize.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/authorize.php	(revision 6351)
@@ -0,0 +1,67 @@
+<?php
+/**
+ * @file
+ * Sample authorize endpoint.
+ *
+ * This sample provides two click-jacking prevention methods, neither which are perfect. 
+ * The javascript solution is similar to what facebook used to have (but can be defeated with a 
+ * specially crafted frame-wrapper).
+ */
+
+// Clickjacking prevention (supported by IE8+, FF3.6.9+, Opera10.5+, Safari4+, Chrome 4.1.249.1042+)
+header('X-Frame-Options: DENY');
+
+require "lib/OAuth2StoragePdo.php";
+
+/*
+ * You would need to authenticate the user before authorization.
+ * 
+ * Below is some psudeo-code to show what you might do:
+ * 
+session_start();
+if (!isLoggedIn()) {
+	redirectToLoginPage();
+	exit();
+}
+ */
+
+$oauth = new OAuth2(new OAuth2StoragePDO());
+
+if ($_POST) {
+	$userId = '12345'; // Use whatever method you have for identifying users.
+	$oauth->finishClientAuthorization($_POST["accept"] == "Yep", $userId, $_POST);
+}
+
+try {
+	$auth_params = $oauth->getAuthorizeParams();
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+?>
+<html>
+<head>
+<title>Authorize</title>
+<script>
+	if (top != self) {
+		window.document.write("<div style='background:black; opacity:0.5; filter: alpha (opacity = 50); position: absolute; top:0px; left: 0px;"
+		+ "width: 9999px; height: 9999px; zindex: 1000001' onClick='top.location.href=window.location.href'></div>");
+	}
+  </script>
+</head>
+<body>
+<form method="post" action="authorize.php">
+ 
+    
+      <?php 
+      foreach ($auth_params as $key => $value) : ?>
+      	<input type="hidden"
+	name="<?php echo htmlspecialchars($key, ENT_QUOTES); ?>"
+	value="<?php echo htmlspecialchars($value, ENT_QUOTES); ?>" />
+      <?php endforeach; ?>
+      Do you authorize the app to do its thing?
+      <p><input type="submit" name="accept" value="Yep" /> <input
+	type="submit" name="accept" value="Nope" /></p>
+</form>
+</body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/mysql_create_tables.sql
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/mysql_create_tables.sql	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/mysql_create_tables.sql	(revision 6351)
@@ -0,0 +1,36 @@
+SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
+
+CREATE TABLE `auth_codes` (
+  `code` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `redirect_uri` varchar(200) NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`code`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `clients` (
+  `client_id` varchar(40) NOT NULL,
+  `client_secret` varchar(20) NOT NULL,
+  `redirect_uri` varchar(255) NOT NULL,
+  PRIMARY KEY (`client_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `access_tokens` (
+  `oauth_token` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`oauth_token`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `refresh_tokens` (
+  `refresh_token` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`refresh_token`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StoragePdo.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StoragePdo.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StoragePdo.php	(revision 6351)
@@ -0,0 +1,311 @@
+<?php
+
+/**
+ * @file
+ * Sample OAuth2 Library PDO DB Implementation.
+ * 
+ * Simply pass in a configured PDO class, eg:
+ * new OAuth2StoragePDO( new PDO('mysql:dbname=mydb;host=localhost', 'user', 'pass') );
+ */
+session_start();
+require __DIR__ . '/../../../../lib/OAuth2.php';
+require __DIR__ . '/../../../../lib/IOAuth2Storage.php';
+require __DIR__ . '/../../../../lib/IOAuth2GrantCode.php';
+require __DIR__ . '/../../../../lib/IOAuth2RefreshTokens.php';
+
+/**
+ * PDO storage engine for the OAuth2 Library.
+ * 
+ * IMPORTANT: This is provided as an example only. In production you may implement
+ * a client-specific salt in the OAuth2StoragePDO::hash() and possibly other goodies.
+ * 
+ *** The point is, use this as an EXAMPLE ONLY. ***
+ */
+class OAuth2StoragePDO implements IOAuth2GrantCode, IOAuth2RefreshTokens {
+	
+	/**
+	 * Change this to something unique for your system
+	 * @var string
+	 */
+	const SALT = 'CHANGE_ME!';
+	
+	/**@#+
+	 * Centralized table names
+	 * 
+	 * @var string
+	 */
+	const TABLE_CLIENTS = 'clients';
+	const TABLE_CODES = 'auth_codes';
+	const TABLE_TOKENS = 'access_tokens';
+	const TABLE_REFRESH = 'refresh_tokens';
+	/**@#-*/
+	
+	/**
+	 * @var PDO
+	 */
+	private $db;
+
+	/**
+	 * Implements OAuth2::__construct().
+	 */
+	public function __construct() {
+		
+		try {
+			$this->db = new PDO('pgsql:dbname=oauth;host=/tmp', 'expressodev', 'prognus');
+		} catch (PDOException $e) {
+			die('Connection failed: ' . $e->getMessage());
+		}
+	}
+
+	/**
+	 * Release DB connection during destruct.
+	 */
+	function __destruct() {
+		$this->db = NULL; // Release db connection
+	}
+
+	/**
+	 * Handle PDO exceptional cases.
+	 */
+	private function handleException($e) {
+		echo 'Database error: ' . $e->getMessage();
+		exit();
+	}
+
+	/**
+	 * Little helper function to add a new client to the database.
+	 *
+	 * Do NOT use this in production! This sample code stores the secret
+	 * in plaintext!
+	 *
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $client_secret
+	 * Client secret to be stored.
+	 * @param $redirect_uri
+	 * Redirect URI to be stored.
+	 */
+	public function addClient($client_id, $client_secret, $redirect_uri) {
+		try {
+			$client_secret = $this->hash($client_secret, $client_id);
+			
+			$sql = 'INSERT INTO ' . self::TABLE_CLIENTS . ' (client_id, client_secret, redirect_uri) VALUES (:client_id, :client_secret, :redirect_uri)';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':client_id', $client_id, PDO::PARAM_STR);
+			$stmt->bindParam(':client_secret', $client_secret, PDO::PARAM_STR);
+			$stmt->bindParam(':redirect_uri', $redirect_uri, PDO::PARAM_STR);
+			$stmt->execute();
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::checkClientCredentials().
+	 *
+	 */
+	public function checkClientCredentials($client_id, $client_secret = NULL) {
+		try {
+			$sql = 'SELECT client_secret FROM ' . self::TABLE_CLIENTS . ' WHERE client_id = :client_id';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':client_id', $client_id, PDO::PARAM_STR);
+			$stmt->execute();
+			
+			$result = $stmt->fetch(PDO::FETCH_ASSOC);
+			
+			if ($client_secret === NULL) {
+				return $result !== FALSE;
+			}
+			
+			return $this->checkPassword($client_secret, $result['client_secret'], $client_id);
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getRedirectUri().
+	 */
+	public function getClientDetails($client_id) {
+		try {
+			$sql = 'SELECT redirect_uri FROM ' . self::TABLE_CLIENTS . ' WHERE client_id = :client_id';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':client_id', $client_id, PDO::PARAM_STR);
+			$stmt->execute();
+			
+			$result = $stmt->fetch(PDO::FETCH_ASSOC);
+			
+			if ($result === FALSE) {
+				return FALSE;
+			}
+			
+			return isset($result['redirect_uri']) && $result['redirect_uri'] ? $result : NULL;
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getAccessToken().
+	 */
+	public function getAccessToken($oauth_token) {
+		return $this->getToken($oauth_token, FALSE);
+	}
+
+	/**
+	 * Implements IOAuth2Storage::setAccessToken().
+	 */
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL) {
+		$this->setToken($oauth_token, $client_id, $user_id, $expires, $scope, FALSE);
+	}
+
+	/**
+	 * @see IOAuth2Storage::getRefreshToken()
+	 */
+	public function getRefreshToken($refresh_token) {
+		return $this->getToken($refresh_token, TRUE);
+	}
+
+	/**
+	 * @see IOAuth2Storage::setRefreshToken()
+	 */
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = NULL) {
+		return $this->setToken($refresh_token, $client_id, $user_id, $expires, $scope, TRUE);
+	}
+
+	/**
+	 * @see IOAuth2Storage::unsetRefreshToken()
+	 */
+	public function unsetRefreshToken($refresh_token) {
+		try {
+			$sql = 'DELETE FROM ' . self::TABLE_TOKENS . ' WHERE refresh_token = :refresh_token';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':refresh_token', $refresh_token, PDO::PARAM_STR);
+			$stmt->execute();
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::getAuthCode().
+	 */
+	public function getAuthCode($code) {
+		try {
+			$sql = 'SELECT code, client_id, user_id, redirect_uri, expires, scope FROM ' . self::TABLE_CODES . ' auth_codes WHERE code = :code';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':code', $code, PDO::PARAM_STR);
+			$stmt->execute();
+			
+			$result = $stmt->fetch(PDO::FETCH_ASSOC);
+			
+			return $result !== FALSE ? $result : NULL;
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Implements IOAuth2Storage::setAuthCode().
+	 */
+	public function setAuthCode($code, $client_id, $user_id, $redirect_uri, $expires, $scope = NULL) {
+		try {
+			$sql = 'INSERT INTO ' . self::TABLE_CODES . ' (code, client_id, user_id, redirect_uri, expires, scope) VALUES (:code, :client_id, :user_id, :redirect_uri, :expires, :scope)';
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':code', $code, PDO::PARAM_STR);
+			$stmt->bindParam(':client_id', $client_id, PDO::PARAM_STR);
+			$stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
+			$stmt->bindParam(':redirect_uri', $redirect_uri, PDO::PARAM_STR);
+			$stmt->bindParam(':expires', $expires, PDO::PARAM_INT);
+			$stmt->bindParam(':scope', $scope, PDO::PARAM_STR);
+			
+			$stmt->execute();
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * @see IOAuth2Storage::checkRestrictedGrantType()
+	 */
+	public function checkRestrictedGrantType($client_id, $grant_type) {
+		return TRUE; // Not implemented
+	}
+
+	/**
+	 * Creates a refresh or access token
+	 * 
+	 * @param string $token - Access or refresh token id
+	 * @param string $client_id
+	 * @param mixed $user_id
+	 * @param int $expires
+	 * @param string $scope
+	 * @param bool $isRefresh
+	 */
+	protected function setToken($token, $client_id, $user_id, $expires, $scope, $isRefresh = TRUE) {
+		try {
+			$tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS;
+			$tokenName = $isRefresh ? 'refresh_token' : 'oauth_token';
+                        
+			$sql = "INSERT INTO $tableName ($tokenName, client_id, user_id, expires, scope) VALUES (:token, :client_id, :user_id, :expires, :scope)";
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':token', $token, PDO::PARAM_STR);
+			$stmt->bindParam(':client_id', $client_id, PDO::PARAM_STR);
+			$stmt->bindParam(':user_id', $user_id, PDO::PARAM_STR);
+			$stmt->bindParam(':expires', $expires, PDO::PARAM_INT);
+			$stmt->bindParam(':scope', $scope, PDO::PARAM_STR);
+			
+			$stmt->execute();
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Retrieves an access or refresh token.
+	 * 
+	 * @param string $token
+	 * @param bool $refresh
+	 */
+	protected function getToken($token, $isRefresh = true) {
+		try {
+			$tableName = $isRefresh ? self::TABLE_REFRESH : self::TABLE_TOKENS;
+			$tokenName = $isRefresh ? 'refresh_token' : 'oauth_token';
+			
+			$sql = "SELECT $tokenName, client_id, expires, scope, user_id FROM $tableName WHERE $tokenName = :token";
+			$stmt = $this->db->prepare($sql);
+			$stmt->bindParam(':token', $token, PDO::PARAM_STR);
+			$stmt->execute();
+			
+			$result = $stmt->fetch(PDO::FETCH_ASSOC);
+			
+			return $result !== FALSE ? $result : NULL;
+		} catch (PDOException $e) {
+			$this->handleException($e);
+		}
+	}
+
+	/**
+	 * Change/override this to whatever your own password hashing method is.
+	 * 
+	 * In production you might want to a client-specific salt to this function. 
+	 * 
+	 * @param string $secret
+	 * @return string
+	 */
+	protected function hash($client_secret, $client_id) {            
+            return hash('md5', $client_id . $client_secret);
+	}
+
+	/**
+	 * Checks the password.
+	 * Override this if you need to
+	 * 
+	 * @param string $client_id
+	 * @param string $client_secret
+	 * @param string $actualPassword
+	 */
+	protected function checkPassword($try, $client_secret, $client_id) {
+		return ($client_secret == $this->hash($try, $client_id) )? TRUE : FALSE;
+	}
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StorageUserCredential.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StorageUserCredential.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/lib/OAuth2StorageUserCredential.php	(revision 6351)
@@ -0,0 +1,77 @@
+<?php
+
+/**
+ * @file
+ * Sample OAuth2 Library PDO DB Implementation.
+ * 
+ * Simply pass in a configured PDO class, eg:
+ * new OAuth2StoragePDO( new PDO('mysql:dbname=mydb;host=localhost', 'user', 'pass') );
+ */
+//session_start();
+//require __DIR__ . '/../../../../lib/OAuth2.php';
+///require __DIR__ . '/../../../../lib/IOAuth2Storage.php';
+//require __DIR__ . '/../../../../lib/IOAuth2GrantCode.php';
+//require __DIR__ . '/../../../../lib/IOAuth2RefreshTokens.php';
+require __DIR__ . '/../../../../lib/IOAuth2GrantUser.php';
+
+/**
+ * PDO storage engine for the OAuth2 Library.
+ * 
+ * IMPORTANT: This is provided as an example only. In production you may implement
+ * a client-specific salt in the OAuth2StoragePDO::hash() and possibly other goodies.
+ * 
+ *** The point is, use this as an EXAMPLE ONLY. ***
+ */
+class OAuth2StorageUserCredential implements IOAuth2GrantUser, IOAuth2RefreshTokens {
+
+	private $valid_client_id = 666;
+
+	public function checkUserCredentials($client_id, $username, $password) {
+		if( $client_id == $this->valid_client_id && $username == 'adirkuhn' && $password == '666' ) {
+			//return true; 
+			return array('scope' => 'all'); 
+		}
+		else {
+			return false;
+		}
+	}
+
+	public function checkClientCredentials($client_id, $client_secret = NULL) {
+	}
+
+	public function getClientDetails($client_id) {
+	}
+
+	public function getAccessToken($oauth_token) {
+	}
+
+	
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL) {
+		var_dump(func_get_args());
+	}
+
+	
+	public function checkRestrictedGrantType($client_id, $grant_type) {
+		if($client_id == $this->valid_client_id	&& $grant_type == 'password') {
+			return true;
+		}
+		else {
+			return false;
+		}
+	}
+
+
+	public function getRefreshToken($refresh_token) {
+	}
+
+	
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = NULL) {
+	}
+
+
+	public function unsetRefreshToken($refresh_token) {
+	}
+
+}
+
+
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/protected_resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/protected_resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/protected_resource.php	(revision 6351)
@@ -0,0 +1,35 @@
+<?php
+
+/**
+ * @file
+ * Sample protected resource.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/OAuth2StoragePdo.php";
+
+try {
+	$oauth = new OAuth2(new OAuth2StoragePDO());
+	$token = $oauth->getBearerToken();
+	$oauth->verifyAccessToken($token);
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+// With a particular scope, you'd do:
+// $oauth->verifyAccessToken("scope_name");
+
+
+?>
+
+<html>
+	<head>
+		<title>Hello!</title>
+	</head>
+	<body>
+		<p>This is a secret.</p>
+	</body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/token.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/token.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/token.php	(revision 6351)
@@ -0,0 +1,26 @@
+<?php
+ini_set('display_errors', 'on');
+/**
+ * @file
+ * Sample token endpoint.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/OAuth2StoragePdo.php";
+require "lib/OAuth2StorageUserCredential.php";
+
+if(isset($_GET['grant_type']) && $_GET['grant_type'] === 'password') {
+	$oauth = new OAuth2(new Oauth2StorageUserCredential());
+}
+else {
+	$oauth = new OAuth2(new OAuth2StoragePDO());
+}
+
+try {
+	$oauth->grantAccessToken();
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/hello.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/hello.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/hello.php	(revision 6351)
@@ -0,0 +1,4 @@
+<?php
+
+
+?>
Index: sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/addclient.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/addclient.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/server/examples/pdo/addclient.php	(revision 6351)
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * @file
+ * Sample client add script.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ */
+
+require "lib/OAuth2StoragePdo.php";
+
+if ($_POST && isset($_POST["client_id"]) && isset($_POST["client_secret"]) && isset($_POST["redirect_uri"])) {
+	$oauth = new OAuth2StoragePDO();
+	$oauth->addClient($_POST["client_id"], $_POST["client_secret"], $_POST["redirect_uri"]);
+}
+
+?>
+
+<html>
+  <head>
+  	<title>Add Client</title>
+  </head>
+  <body>
+    <form method="post" action="addclient.php">
+      <p>
+        <label for="client_id">Client ID:</label>
+        <input type="text" name="client_id" id="client_id" />
+      </p>
+      <p>
+        <label for="client_secret">Client Secret (password/key):</label>
+        <input type="text" name="client_secret" id="client_secret" />
+      </p>
+      <p>
+        <label for="redirect_uri">Redirect URI:</label>
+        <input type="text" name="redirect_uri" id="redirect_uri" />
+      </p>
+      <input type="submit" value="Submit" />
+    </form>
+  </body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/oauth2/config.doxy
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/config.doxy	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/config.doxy	(revision 6351)
@@ -0,0 +1,1631 @@
+# Doxyfile 1.7.1
+
+# This file describes the settings to be used by the documentation system
+# doxygen (www.doxygen.org) for a project
+#
+# All text after a hash (#) is considered a comment and will be ignored
+# The format is:
+#       TAG = value [value, ...]
+# For lists items can also be appended using:
+#       TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (" ")
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+
+# This tag specifies the encoding used for all characters in the config file
+# that follow. The default is UTF-8 which is also the encoding used for all
+# text before the first occurrence of this tag. Doxygen uses libiconv (or the
+# iconv built into libc) for the transcoding. See
+# http://www.gnu.org/software/libiconv for the list of possible encodings.
+
+DOXYFILE_ENCODING      = UTF-8
+
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
+# by quotes) that should identify the project.
+
+PROJECT_NAME           = oauth2-php
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number.
+# This could be handy for archiving the generated documentation or
+# if some version control system is used.
+
+PROJECT_NUMBER         = draft-ietf-oauth-v2-10
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
+# base path where the generated documentation will be put.
+# If a relative path is entered, it will be relative to the location
+# where doxygen was started. If left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = docs
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
+# 4096 sub-directories (in 2 levels) under the output directory of each output
+# format and will distribute the generated files over these directories.
+# Enabling this option can be useful when feeding doxygen a huge amount of
+# source files, where putting all generated files in the same directory would
+# otherwise cause performance problems for the file system.
+
+CREATE_SUBDIRS         = NO
+
+# The OUTPUT_LANGUAGE tag is used to specify the language in which all
+# documentation generated by doxygen is written. Doxygen will use this
+# information to generate all constant output in the proper language.
+# The default language is English, other supported languages are:
+# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
+# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
+# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
+# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
+# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
+# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+
+OUTPUT_LANGUAGE        = English
+
+# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
+# include brief member descriptions after the members that are listed in
+# the file and class documentation (similar to JavaDoc).
+# Set to NO to disable this.
+
+BRIEF_MEMBER_DESC      = YES
+
+# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
+# the brief description of a member or function before the detailed description.
+# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# brief descriptions will be completely suppressed.
+
+REPEAT_BRIEF           = YES
+
+# This tag implements a quasi-intelligent brief description abbreviator
+# that is used to form the text in various listings. Each string
+# in this list, if found as the leading text of the brief description, will be
+# stripped from the text and the result after processing the whole list, is
+# used as the annotated text. Otherwise, the brief description is used as-is.
+# If left blank, the following values are used ("$name" is automatically
+# replaced with the name of the entity): "The $name class" "The $name widget"
+# "The $name file" "is" "provides" "specifies" "contains"
+# "represents" "a" "an" "the"
+
+ABBREVIATE_BRIEF       = "The $name class" \
+                         "The $name widget" \
+                         "The $name file" \
+                         is \
+                         provides \
+                         specifies \
+                         contains \
+                         represents \
+                         a \
+                         an \
+                         the
+
+# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
+# Doxygen will generate a detailed section even if there is only a brief
+# description.
+
+ALWAYS_DETAILED_SEC    = NO
+
+# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all
+# inherited members of a class in the documentation of that class as if those
+# members were ordinary class members. Constructors, destructors and assignment
+# operators of the base classes will not be shown.
+
+INLINE_INHERITED_MEMB  = NO
+
+# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
+# path before files name in the file list and in the header files. If set
+# to NO the shortest path that makes the file name unique will be used.
+
+FULL_PATH_NAMES        = YES
+
+# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
+# can be used to strip a user-defined part of the path. Stripping is
+# only done if one of the specified strings matches the left-hand part of
+# the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the
+# path to strip.
+
+STRIP_FROM_PATH        =
+
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
+# the path mentioned in the documentation of a class, which tells
+# the reader which header file to include in order to use a class.
+# If left blank only the name of the header file containing the class
+# definition is used. Otherwise one should specify the include paths that
+# are normally passed to the compiler using the -I flag.
+
+STRIP_FROM_INC_PATH    =
+
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
+# (but less readable) file names. This can be useful is your file systems
+# doesn't support long names like on DOS, Mac, or CD-ROM.
+
+SHORT_NAMES            = NO
+
+# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
+# will interpret the first line (until the first dot) of a JavaDoc-style
+# comment as the brief description. If set to NO, the JavaDoc
+# comments will behave just like regular Qt-style comments
+# (thus requiring an explicit @brief command for a brief description.)
+
+JAVADOC_AUTOBRIEF      = NO
+
+# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
+# interpret the first line (until the first dot) of a Qt-style
+# comment as the brief description. If set to NO, the comments
+# will behave just like regular Qt-style comments (thus requiring
+# an explicit \brief command for a brief description.)
+
+QT_AUTOBRIEF           = NO
+
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
+# treat a multi-line C++ special comment block (i.e. a block of //! or ///
+# comments) as a brief description. This used to be the default behaviour.
+# The new default is to treat a multi-line C++ comment block as a detailed
+# description. Set this tag to YES if you prefer the old behaviour instead.
+
+MULTILINE_CPP_IS_BRIEF = NO
+
+# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
+# member inherits the documentation from any documented member that it
+# re-implements.
+
+INHERIT_DOCS           = YES
+
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
+# a new page for each member. If set to NO, the documentation of a member will
+# be part of the file/class/namespace that contains it.
+
+SEPARATE_MEMBER_PAGES  = NO
+
+# The TAB_SIZE tag can be used to set the number of spaces in a tab.
+# Doxygen uses this value to replace tabs by spaces in code fragments.
+
+TAB_SIZE               = 2
+
+# This tag can be used to specify a number of aliases that acts
+# as commands in the documentation. An alias has the form "name=value".
+# For example adding "sideeffect=\par Side Effects:\n" will allow you to
+# put the command \sideeffect (or @sideeffect) in the documentation, which
+# will result in a user-defined paragraph with heading "Side Effects:".
+# You can put \n's in the value part of an alias to insert newlines.
+
+ALIASES                =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
+# sources only. Doxygen will then generate output that is more tailored for C.
+# For instance, some of the names that are used will be different. The list
+# of all members will be omitted, etc.
+
+OPTIMIZE_OUTPUT_FOR_C  = NO
+
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
+# sources only. Doxygen will then generate output that is more tailored for
+# Java. For instance, namespaces will be presented as packages, qualified
+# scopes will look different, etc.
+
+OPTIMIZE_OUTPUT_JAVA   = NO
+
+# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
+# sources only. Doxygen will then generate output that is more tailored for
+# Fortran.
+
+OPTIMIZE_FOR_FORTRAN   = NO
+
+# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
+# sources. Doxygen will then generate output that is tailored for
+# VHDL.
+
+OPTIMIZE_OUTPUT_VHDL   = NO
+
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given extension.
+# Doxygen has a built-in mapping, but you can override or extend it using this
+# tag. The format is ext=language, where ext is a file extension, and language
+# is one of the parsers supported by doxygen: IDL, Java, Javascript, CSharp, C,
+# C++, D, PHP, Objective-C, Python, Fortran, VHDL, C, C++. For instance to make
+# doxygen treat .inc files as Fortran files (default is PHP), and .f files as C
+# (default is Fortran), use: inc=Fortran f=C. Note that for custom extensions
+# you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
+
+EXTENSION_MAPPING      =
+
+# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
+# to include (a tag file for) the STL sources as input, then you should
+# set this tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
+# func(std::string) {}). This also make the inheritance and collaboration
+# diagrams that involve STL classes more complete and accurate.
+
+BUILTIN_STL_SUPPORT    = NO
+
+# If you use Microsoft's C++/CLI language, you should set this option to YES to
+# enable parsing support.
+
+CPP_CLI_SUPPORT        = NO
+
+# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
+# Doxygen will parse them like normal C++ but will assume all classes use public
+# instead of private inheritance when no explicit protection keyword is present.
+
+SIP_SUPPORT            = NO
+
+# For Microsoft's IDL there are propget and propput attributes to indicate getter
+# and setter methods for a property. Setting this option to YES (the default)
+# will make doxygen to replace the get and set methods by a property in the
+# documentation. This will only work if the methods are indeed getting or
+# setting a simple type. If this is not the case, or you want to show the
+# methods anyway, you should set this option to NO.
+
+IDL_PROPERTY_SUPPORT   = YES
+
+# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC
+# tag is set to YES, then doxygen will reuse the documentation of the first
+# member in the group (if any) for the other members of the group. By default
+# all members of a group must be documented explicitly.
+
+DISTRIBUTE_GROUP_DOC   = NO
+
+# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
+# the same type (for instance a group of public functions) to be put as a
+# subgroup of that type (e.g. under the Public Functions section). Set it to
+# NO to prevent subgrouping. Alternatively, this can be done per class using
+# the \nosubgrouping command.
+
+SUBGROUPING            = YES
+
+# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
+# is documented as struct, union, or enum with the name of the typedef. So
+# typedef struct TypeS {} TypeT, will appear in the documentation as a struct
+# with name TypeT. When disabled the typedef will appear as a member of a file,
+# namespace, or class. And the struct will be named TypeS. This can typically
+# be useful for C code in case the coding convention dictates that all compound
+# types are typedef'ed and only the typedef is referenced, never the tag name.
+
+TYPEDEF_HIDES_STRUCT   = NO
+
+# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
+# determine which symbols to keep in memory and which to flush to disk.
+# When the cache is full, less often used symbols will be written to disk.
+# For small to medium size projects (<1000 input files) the default value is
+# probably good enough. For larger projects a too small cache size can cause
+# doxygen to be busy swapping symbols to and from disk most of the time
+# causing a significant performance penality.
+# If the system has enough physical memory increasing the cache will improve the
+# performance by keeping more symbols in memory. Note that the value works on
+# a logarithmic scale so increasing the size by one will rougly double the
+# memory usage. The cache size is given by this formula:
+# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
+# corresponding to a cache size of 2^16 = 65536 symbols
+
+SYMBOL_CACHE_SIZE      = 0
+
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+
+# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
+# documentation are documented, even if no documentation was available.
+# Private class members and static file members will be hidden unless
+# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
+
+EXTRACT_ALL            = YES
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
+# will be included in the documentation.
+
+EXTRACT_PRIVATE        = YES
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file
+# will be included in the documentation.
+
+EXTRACT_STATIC         = YES
+
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
+# defined locally in source files will be included in the documentation.
+# If set to NO only classes defined in header files are included.
+
+EXTRACT_LOCAL_CLASSES  = YES
+
+# This flag is only useful for Objective-C code. When set to YES local
+# methods, which are defined in the implementation section but not in
+# the interface are included in the documentation.
+# If set to NO (the default) only methods in the interface are included.
+
+EXTRACT_LOCAL_METHODS  = NO
+
+# If this flag is set to YES, the members of anonymous namespaces will be
+# extracted and appear in the documentation as a namespace called
+# 'anonymous_namespace{file}', where file will be replaced with the base
+# name of the file that contains the anonymous namespace. By default
+# anonymous namespace are hidden.
+
+EXTRACT_ANON_NSPACES   = NO
+
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
+# undocumented members of documented classes, files or namespaces.
+# If set to NO (the default) these members will be included in the
+# various overviews, but no documentation section is generated.
+# This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_MEMBERS     = NO
+
+# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy.
+# If set to NO (the default) these classes will be included in the various
+# overviews. This option has no effect if EXTRACT_ALL is enabled.
+
+HIDE_UNDOC_CLASSES     = NO
+
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
+# friend (class|struct|union) declarations.
+# If set to NO (the default) these declarations will be included in the
+# documentation.
+
+HIDE_FRIEND_COMPOUNDS  = NO
+
+# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
+# documentation blocks found inside the body of a function.
+# If set to NO (the default) these blocks will be appended to the
+# function's detailed documentation block.
+
+HIDE_IN_BODY_DOCS      = NO
+
+# The INTERNAL_DOCS tag determines if documentation
+# that is typed after a \internal command is included. If the tag is set
+# to NO (the default) then the documentation will be excluded.
+# Set it to YES to include the internal documentation.
+
+INTERNAL_DOCS          = NO
+
+# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
+# file names in lower-case letters. If set to YES upper-case letters are also
+# allowed. This is useful if you have classes or files whose names only differ
+# in case and if your file system supports case sensitive file names. Windows
+# and Mac users are advised to set this option to NO.
+
+CASE_SENSE_NAMES       = NO
+
+# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
+# will show members with their full class and namespace scopes in the
+# documentation. If set to YES the scope will be hidden.
+
+HIDE_SCOPE_NAMES       = YES
+
+# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
+# will put a list of the files that are included by a file in the documentation
+# of that file.
+
+SHOW_INCLUDE_FILES     = YES
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then Doxygen
+# will list include files with double quotes in the documentation
+# rather than with sharp brackets.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
+# is inserted in the documentation for inline members.
+
+INLINE_INFO            = YES
+
+# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
+# will sort the (detailed) documentation of file and class members
+# alphabetically by member name. If set to NO the members will appear in
+# declaration order.
+
+SORT_MEMBER_DOCS       = YES
+
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
+# brief documentation of file, namespace and class members alphabetically
+# by member name. If set to NO (the default) the members will appear in
+# declaration order.
+
+SORT_BRIEF_DOCS        = NO
+
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen
+# will sort the (brief and detailed) documentation of class members so that
+# constructors and destructors are listed first. If set to NO (the default)
+# the constructors will appear in the respective orders defined by
+# SORT_MEMBER_DOCS and SORT_BRIEF_DOCS.
+# This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO
+# and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+
+SORT_MEMBERS_CTORS_1ST = NO
+
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
+# hierarchy of group names into alphabetical order. If set to NO (the default)
+# the group names will appear in their defined order.
+
+SORT_GROUP_NAMES       = NO
+
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
+# sorted by fully-qualified names, including namespaces. If set to
+# NO (the default), the class list will be sorted only by class name,
+# not including the namespace part.
+# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
+# Note: This option applies only to the class list, not to the
+# alphabetical list.
+
+SORT_BY_SCOPE_NAME     = NO
+
+# The GENERATE_TODOLIST tag can be used to enable (YES) or
+# disable (NO) the todo list. This list is created by putting \todo
+# commands in the documentation.
+
+GENERATE_TODOLIST      = YES
+
+# The GENERATE_TESTLIST tag can be used to enable (YES) or
+# disable (NO) the test list. This list is created by putting \test
+# commands in the documentation.
+
+GENERATE_TESTLIST      = YES
+
+# The GENERATE_BUGLIST tag can be used to enable (YES) or
+# disable (NO) the bug list. This list is created by putting \bug
+# commands in the documentation.
+
+GENERATE_BUGLIST       = YES
+
+# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
+# disable (NO) the deprecated list. This list is created by putting
+# \deprecated commands in the documentation.
+
+GENERATE_DEPRECATEDLIST= YES
+
+# The ENABLED_SECTIONS tag can be used to enable conditional
+# documentation sections, marked by \if sectionname ... \endif.
+
+ENABLED_SECTIONS       =
+
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
+# the initial value of a variable or define consists of for it to appear in
+# the documentation. If the initializer consists of more lines than specified
+# here it will be hidden. Use a value of 0 to hide initializers completely.
+# The appearance of the initializer of individual variables and defines in the
+# documentation can be controlled using \showinitializer or \hideinitializer
+# command in the documentation regardless of this setting.
+
+MAX_INITIALIZER_LINES  = 30
+
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
+# at the bottom of the documentation of classes and structs. If set to YES the
+# list will mention the files that were used to generate the documentation.
+
+SHOW_USED_FILES        = YES
+
+# If the sources in your project are distributed over multiple directories
+# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
+# in the documentation. The default is NO.
+
+SHOW_DIRECTORIES       = NO
+
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
+# This will remove the Files entry from the Quick Index and from the
+# Folder Tree View (if specified). The default is YES.
+
+SHOW_FILES             = YES
+
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
+# Namespaces page.  This will remove the Namespaces entry from the Quick Index
+# and from the Folder Tree View (if specified). The default is YES.
+
+SHOW_NAMESPACES        = YES
+
+# The FILE_VERSION_FILTER tag can be used to specify a program or script that
+# doxygen should invoke to get the current version for each file (typically from
+# the version control system). Doxygen will invoke the program by executing (via
+# popen()) the command <command> <input-file>, where <command> is the value of
+# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
+# provided by doxygen. Whatever the program writes to standard output
+# is used as the file version. See the manual for examples.
+
+FILE_VERSION_FILTER    =
+
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. The create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option.
+# You can optionally specify a file name after the option, if omitted
+# DoxygenLayout.xml will be used as the name of the layout file.
+
+LAYOUT_FILE            =
+
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated
+# by doxygen. Possible values are YES and NO. If left blank NO is used.
+
+QUIET                  = NO
+
+# The WARNINGS tag can be used to turn on/off the warning messages that are
+# generated by doxygen. Possible values are YES and NO. If left blank
+# NO is used.
+
+WARNINGS               = YES
+
+# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
+# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
+# automatically be disabled.
+
+WARN_IF_UNDOCUMENTED   = YES
+
+# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some
+# parameters in a documented function, or documenting parameters that
+# don't exist or using markup commands wrongly.
+
+WARN_IF_DOC_ERROR      = YES
+
+# This WARN_NO_PARAMDOC option can be abled to get warnings for
+# functions that are documented, but have no documentation for their parameters
+# or return value. If set to NO (the default) doxygen will only warn about
+# wrong or incomplete parameter documentation, but not about the absence of
+# documentation.
+
+WARN_NO_PARAMDOC       = NO
+
+# The WARN_FORMAT tag determines the format of the warning messages that
+# doxygen can produce. The string should contain the $file, $line, and $text
+# tags, which will be replaced by the file and line number from which the
+# warning originated and the warning text. Optionally the format may contain
+# $version, which will be replaced by the version of the file (if it could
+# be obtained via FILE_VERSION_FILTER)
+
+WARN_FORMAT            = "$file:$line: $text"
+
+# The WARN_LOGFILE tag can be used to specify a file to which warning
+# and error messages should be written. If left blank the output is written
+# to stderr.
+
+WARN_LOGFILE           =
+
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag can be used to specify the files and/or directories that contain
+# documented source files. You may enter file names like "myfile.cpp" or
+# directories like "/usr/src/myproject". Separate the files or directories
+# with spaces.
+
+INPUT                  = .
+
+# This tag can be used to specify the character encoding of the source files
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
+# also the default input encoding. Doxygen uses libiconv (or the iconv built
+# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
+# the list of possible encodings.
+
+INPUT_ENCODING         = UTF-8
+
+# If the value of the INPUT tag contains directories, you can use the
+# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank the following patterns are tested:
+# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
+# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
+
+FILE_PATTERNS          = *.php \ *.module \ *.inc \ *.install \ *.js \ *.theme \ *.test
+
+# The RECURSIVE tag can be used to turn specify whether or not subdirectories
+# should be searched for input files as well. Possible values are YES and NO.
+# If left blank NO is used.
+
+RECURSIVE              = YES
+
+# The EXCLUDE tag can be used to specify files and/or directories that should
+# excluded from the INPUT source files. This way you can easily exclude a
+# subdirectory from a directory tree whose root is specified with the INPUT tag.
+
+EXCLUDE                =
+
+# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
+# directories that are symbolic links (a Unix filesystem feature) are excluded
+# from the input.
+
+EXCLUDE_SYMLINKS       = NO
+
+# If the value of the INPUT tag contains directories, you can use the
+# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
+# certain files from those directories. Note that the wildcards are matched
+# against the file with absolute path, so to exclude all test directories
+# for example use the pattern */test/*
+
+EXCLUDE_PATTERNS       =
+
+# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names
+# (namespaces, classes, functions, etc.) that should be excluded from the
+# output. The symbol name can be a fully qualified name, a word, or if the
+# wildcard * is used, a substring. Examples: ANamespace, AClass,
+# AClass::ANamespace, ANamespace::*Test
+
+EXCLUDE_SYMBOLS        =
+
+# The EXAMPLE_PATH tag can be used to specify one or more files or
+# directories that contain example code fragments that are included (see
+# the \include command).
+
+EXAMPLE_PATH           =
+
+# If the value of the EXAMPLE_PATH tag contains directories, you can use the
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
+# and *.h) to filter out the source-files in the directories. If left
+# blank all files are included.
+
+EXAMPLE_PATTERNS       = *
+
+# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
+# searched for input files to be used with the \include or \dontinclude
+# commands irrespective of the value of the RECURSIVE tag.
+# Possible values are YES and NO. If left blank NO is used.
+
+EXAMPLE_RECURSIVE      = NO
+
+# The IMAGE_PATH tag can be used to specify one or more files or
+# directories that contain image that are included in the documentation (see
+# the \image command).
+
+IMAGE_PATH             =
+
+# The INPUT_FILTER tag can be used to specify a program that doxygen should
+# invoke to filter for each input file. Doxygen will invoke the filter program
+# by executing (via popen()) the command <filter> <input-file>, where <filter>
+# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
+# input file. Doxygen will then use the output that the filter program writes
+# to standard output.  If FILTER_PATTERNS is specified, this tag will be
+# ignored.
+
+INPUT_FILTER           =
+
+# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
+# basis.  Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match.  The filters are a list of the form:
+# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
+# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
+# is applied to all files.
+
+FILTER_PATTERNS        =
+
+# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
+# INPUT_FILTER) will be used to filter the input files when producing source
+# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+
+FILTER_SOURCE_FILES    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will
+# be generated. Documented entities will be cross-referenced with these sources.
+# Note: To get rid of all source code in the generated output, make sure also
+# VERBATIM_HEADERS is set to NO.
+
+SOURCE_BROWSER         = YES
+
+# Setting the INLINE_SOURCES tag to YES will include the body
+# of functions and classes directly in the documentation.
+
+INLINE_SOURCES         = NO
+
+# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
+# doxygen to hide any special comment blocks from generated source code
+# fragments. Normal C and C++ comments will always remain visible.
+
+STRIP_CODE_COMMENTS    = NO
+
+# If the REFERENCED_BY_RELATION tag is set to YES
+# then for each documented function all documented
+# functions referencing it will be listed.
+
+REFERENCED_BY_RELATION = YES
+
+# If the REFERENCES_RELATION tag is set to YES
+# then for each documented function all documented entities
+# called/used by that function will be listed.
+
+REFERENCES_RELATION    = YES
+
+# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
+# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
+# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
+# link to the source code.  Otherwise they will link to the documentation.
+
+REFERENCES_LINK_SOURCE = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code
+# will point to the HTML generated by the htags(1) tool instead of doxygen
+# built-in source browser. The htags tool is part of GNU's global source
+# tagging system (see http://www.gnu.org/software/global/global.html). You
+# will need version 4.8.6 or higher.
+
+USE_HTAGS              = NO
+
+# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
+# will generate a verbatim copy of the header file for each class for
+# which an include is specified. Set to NO to disable this.
+
+VERBATIM_HEADERS       = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
+# of all compounds will be generated. Enable this if the project
+# contains a lot of classes, structs, unions or interfaces.
+
+ALPHABETICAL_INDEX     = YES
+
+# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
+# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
+# in which this list will be split (can be a number in the range [1..20])
+
+COLS_IN_ALPHA_INDEX    = 5
+
+# In case all classes in a project start with a common prefix, all
+# classes will be put under the same header in the alphabetical index.
+# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
+# should be ignored while generating the index headers.
+
+IGNORE_PREFIX          =
+
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
+# generate HTML output.
+
+GENERATE_HTML          = YES
+
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `html' will be used as the default path.
+
+HTML_OUTPUT            = html
+
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
+# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
+# doxygen will generate files with .html extension.
+
+HTML_FILE_EXTENSION    = .html
+
+# The HTML_HEADER tag can be used to specify a personal HTML header for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard header.
+
+HTML_HEADER            =
+
+# The HTML_FOOTER tag can be used to specify a personal HTML footer for
+# each generated HTML page. If it is left blank doxygen will generate a
+# standard footer.
+
+HTML_FOOTER            =
+
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
+# style sheet that is used by each HTML page. It can be used to
+# fine-tune the look of the HTML output. If the tag is left blank doxygen
+# will generate a default style sheet. Note that doxygen will try to copy
+# the style sheet file to the HTML output directory, so don't put your own
+# stylesheet in the HTML output directory as well, or it will be erased!
+
+HTML_STYLESHEET        =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output.
+# Doxygen will adjust the colors in the stylesheet and background images
+# according to this color. Hue is specified as an angle on a colorwheel,
+# see http://en.wikipedia.org/wiki/Hue for more information.
+# For instance the value 0 represents red, 60 is yellow, 120 is green,
+# 180 is cyan, 240 is blue, 300 purple, and 360 is red again.
+# The allowed range is 0 to 359.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of
+# the colors in the HTML output. For a value of 0 the output will use
+# grayscales only. A value of 255 will produce the most vivid colors.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to
+# the luminance component of the colors in the HTML output. Values below
+# 100 gradually make the output lighter, whereas values above 100 make
+# the output darker. The value divided by 100 is the actual gamma applied,
+# so 80 represents a gamma of 0.8, The value 220 represents a gamma of 2.2,
+# and 100 does not change the gamma.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting
+# this to NO can help when comparing the output of multiple runs.
+
+HTML_TIMESTAMP         = YES
+
+# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
+# files or namespaces will be aligned in HTML using tables. If set to
+# NO a bullet list will be used.
+
+HTML_ALIGN_MEMBERS     = YES
+
+# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
+# documentation will contain sections that can be hidden and shown after the
+# page has loaded. For this to work a browser that supports
+# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
+# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+
+HTML_DYNAMIC_SECTIONS  = NO
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files
+# will be generated that can be used as input for Apple's Xcode 3
+# integrated development environment, introduced with OSX 10.5 (Leopard).
+# To create a documentation set, doxygen will generate a Makefile in the
+# HTML output directory. Running make will produce the docset in that
+# directory and running "make install" will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
+# it at startup.
+# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+
+GENERATE_DOCSET        = NO
+
+# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
+# feed. A documentation feed provides an umbrella under which multiple
+# documentation sets from a single provider (such as a company or product suite)
+# can be grouped.
+
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+
+# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
+# should uniquely identify the documentation set bundle. This should be a
+# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
+# will append .docset to the name.
+
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+
+# When GENERATE_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The GENERATE_PUBLISHER_NAME tag identifies the documentation publisher.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES, additional index files
+# will be generated that can be used as input for tools like the
+# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
+# of the generated HTML documentation.
+
+GENERATE_HTMLHELP      = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
+# be used to specify the file name of the resulting .chm file. You
+# can add a path in front of the file if the result should not be
+# written to the html output directory.
+
+CHM_FILE               =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
+# be used to specify the location (absolute path including file name) of
+# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
+# the HTML help compiler on the generated index.hhp.
+
+HHC_LOCATION           =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
+# controls if a separate .chi index file is generated (YES) or that
+# it should be included in the master .chm file (NO).
+
+GENERATE_CHI           = NO
+
+# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
+# is used to encode HtmlHelp index (hhk), content (hhc) and project file
+# content.
+
+CHM_INDEX_ENCODING     =
+
+# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
+# controls whether a binary table of contents is generated (YES) or a
+# normal table of contents (NO) in the .chm file.
+
+BINARY_TOC             = NO
+
+# The TOC_EXPAND flag can be set to YES to add extra items for group members
+# to the contents of the HTML help documentation and to the tree view.
+
+TOC_EXPAND             = NO
+
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated
+# that can be used as input for Qt's qhelpgenerator to generate a
+# Qt Compressed Help (.qch) of the generated HTML documentation.
+
+GENERATE_QHP           = NO
+
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
+# be used to specify the file name of the resulting .qch file.
+# The path specified is relative to the HTML output folder.
+
+QCH_FILE               =
+
+# The QHP_NAMESPACE tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#namespace
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
+# Qt Help Project output. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+
+QHP_VIRTUAL_FOLDER     = doc
+
+# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to
+# add. For more information please see
+# http://doc.trolltech.com/qthelpproject.html#custom-filters
+
+QHP_CUST_FILTER_NAME   =
+
+# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see
+# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">
+# Qt Help Project / Custom Filters</a>.
+
+QHP_CUST_FILTER_ATTRS  =
+
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's
+# filter section matches.
+# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">
+# Qt Help Project / Filter Attributes</a>.
+
+QHP_SECT_FILTER_ATTRS  =
+
+# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
+# be used to specify the location of Qt's qhelpgenerator.
+# If non-empty doxygen will try to run qhelpgenerator on the generated
+# .qhp file.
+
+QHG_LOCATION           =
+
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files
+# will be generated, which together with the HTML files, form an Eclipse help
+# plugin. To install this plugin and make it available under the help contents
+# menu in Eclipse, the contents of the directory containing the HTML and XML
+# files needs to be copied into the plugins directory of eclipse. The name of
+# the directory within the plugins directory should be the same as
+# the ECLIPSE_DOC_ID value. After copying Eclipse needs to be restarted before
+# the help appears.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have
+# this name.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
+# top of each HTML page. The value NO (the default) enables the index and
+# the value YES disables it.
+
+DISABLE_INDEX          = NO
+
+# This tag can be used to set the number of enum values (range [1..20])
+# that doxygen will group on one line in the generated HTML documentation.
+
+ENUM_VALUES_PER_LINE   = 4
+
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information.
+# If the tag value is set to YES, a side panel will be generated
+# containing a tree-like index structure (just like the one that
+# is generated for HTML Help). For this to work a browser that supports
+# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
+# Windows users are probably better off using the HTML help feature.
+
+GENERATE_TREEVIEW      = YES
+
+# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
+# and Class Hierarchy pages using a tree view instead of an ordered list.
+
+USE_INLINE_TREES       = NO
+
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
+# used to set the initial width (in pixels) of the frame in which the tree
+# is shown.
+
+TREEVIEW_WIDTH         = 250
+
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open
+# links to external symbols imported via tag files in a separate window.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of Latex formulas included
+# as images in the HTML documentation. The default is 10. Note that
+# when you change the font size after a successful doxygen run you need
+# to manually remove any form_*.png images from the HTML output directory
+# to force them to be regenerated.
+
+FORMULA_FONTSIZE       = 10
+
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are
+# not supported properly for IE 6.0, but are supported on all modern browsers.
+# Note that when changing this option you need to delete any form_*.png files
+# in the HTML output before the changes have effect.
+
+FORMULA_TRANSPARENT    = YES
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box
+# for the HTML output. The underlying search engine uses javascript
+# and DHTML and should work on any modern browser. Note that when using
+# HTML help (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets
+# (GENERATE_DOCSET) there is already a search function so this one should
+# typically be disabled. For large projects the javascript based search engine
+# can be slow, then enabling SERVER_BASED_SEARCH may provide a better solution.
+
+SEARCHENGINE           = YES
+
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a PHP enabled web server instead of at the web client
+# using Javascript. Doxygen will generate the search PHP script and index
+# file to put on the web server. The advantage of the server
+# based approach is that it scales better to large projects and allows
+# full text search. The disadvances is that it is more difficult to setup
+# and does not have live searching capabilities.
+
+SERVER_BASED_SEARCH    = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
+# generate Latex output.
+
+GENERATE_LATEX         = NO
+
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `latex' will be used as the default path.
+
+LATEX_OUTPUT           = latex
+
+# The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
+# invoked. If left blank `latex' will be used as the default command name.
+# Note that when enabling USE_PDFLATEX this option is only used for
+# generating bitmaps for formulas in the HTML output, but not in the
+# Makefile that is written to the output directory.
+
+LATEX_CMD_NAME         = latex
+
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
+# generate index for LaTeX. If left blank `makeindex' will be used as the
+# default command name.
+
+MAKEINDEX_CMD_NAME     = makeindex
+
+# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
+# LaTeX documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_LATEX          = NO
+
+# The PAPER_TYPE tag can be used to set the paper type that is used
+# by the printer. Possible values are: a4, a4wide, letter, legal and
+# executive. If left blank a4wide will be used.
+
+PAPER_TYPE             = a4wide
+
+# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
+# packages that should be included in the LaTeX output.
+
+EXTRA_PACKAGES         =
+
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
+# the generated latex document. The header should contain everything until
+# the first chapter. If it is left blank doxygen will generate a
+# standard header. Notice: only use this tag if you know what you are doing!
+
+LATEX_HEADER           =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
+# is prepared for conversion to pdf (using ps2pdf). The pdf file will
+# contain links (just like the HTML output) instead of page references
+# This makes the output suitable for online browsing using a pdf viewer.
+
+PDF_HYPERLINKS         = YES
+
+# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
+# plain latex in the generated Makefile. Set this option to YES to get a
+# higher quality PDF documentation.
+
+USE_PDFLATEX           = YES
+
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
+# command to the generated LaTeX files. This will instruct LaTeX to keep
+# running if errors occur, instead of asking the user for help.
+# This option is also used when generating formulas in HTML.
+
+LATEX_BATCHMODE        = NO
+
+# If LATEX_HIDE_INDICES is set to YES then doxygen will not
+# include the index chapters (such as File Index, Compound Index, etc.)
+# in the output.
+
+LATEX_HIDE_INDICES     = NO
+
+# If LATEX_SOURCE_CODE is set to YES then doxygen will include
+# source code with syntax highlighting in the LaTeX output.
+# Note that which sources are shown also depends on other settings
+# such as SOURCE_BROWSER.
+
+LATEX_SOURCE_CODE      = YES
+
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
+# The RTF output is optimized for Word 97 and may not look very pretty with
+# other RTF readers or editors.
+
+GENERATE_RTF           = NO
+
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `rtf' will be used as the default path.
+
+RTF_OUTPUT             = rtf
+
+# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
+# RTF documents. This may be useful for small projects and may help to
+# save some trees in general.
+
+COMPACT_RTF            = NO
+
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
+# will contain hyperlink fields. The RTF file will
+# contain links (just like the HTML output) instead of page references.
+# This makes the output suitable for online browsing using WORD or other
+# programs which support those fields.
+# Note: wordpad (write) and others do not support links.
+
+RTF_HYPERLINKS         = NO
+
+# Load stylesheet definitions from file. Syntax is similar to doxygen's
+# config file, i.e. a series of assignments. You only have to provide
+# replacements, missing definitions are set to their default value.
+
+RTF_STYLESHEET_FILE    =
+
+# Set optional variables used in the generation of an rtf document.
+# Syntax is similar to doxygen's config file.
+
+RTF_EXTENSIONS_FILE    =
+
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
+# generate man pages
+
+GENERATE_MAN           = NO
+
+# The MAN_OUTPUT tag is used to specify where the man pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `man' will be used as the default path.
+
+MAN_OUTPUT             = man
+
+# The MAN_EXTENSION tag determines the extension that is added to
+# the generated man pages (default is the subroutine's section .3)
+
+MAN_EXTENSION          = .3
+
+# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
+# then it will generate one additional man file for each entity
+# documented in the real man page(s). These additional files
+# only source the real man page, but without them the man command
+# would be unable to find the correct page. The default is NO.
+
+MAN_LINKS              = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES Doxygen will
+# generate an XML file that captures the structure of
+# the code including all documentation.
+
+GENERATE_XML           = NO
+
+# The XML_OUTPUT tag is used to specify where the XML pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be
+# put in front of it. If left blank `xml' will be used as the default path.
+
+XML_OUTPUT             = xml
+
+# The XML_SCHEMA tag can be used to specify an XML schema,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_SCHEMA             =
+
+# The XML_DTD tag can be used to specify an XML DTD,
+# which can be used by a validating XML parser to check the
+# syntax of the XML files.
+
+XML_DTD                =
+
+# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
+# dump the program listings (including syntax highlighting
+# and cross-referencing information) to the XML output. Note that
+# enabling this will significantly increase the size of the XML output.
+
+XML_PROGRAMLISTING     = YES
+
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
+# generate an AutoGen Definitions (see autogen.sf.net) file
+# that captures the structure of the code including all
+# documentation. Note that this feature is still experimental
+# and incomplete at the moment.
+
+GENERATE_AUTOGEN_DEF   = NO
+
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES Doxygen will
+# generate a Perl module file that captures the structure of
+# the code including all documentation. Note that this
+# feature is still experimental and incomplete at the
+# moment.
+
+GENERATE_PERLMOD       = NO
+
+# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
+# the necessary Makefile rules, Perl scripts and LaTeX code to be able
+# to generate PDF and DVI output from the Perl module output.
+
+PERLMOD_LATEX          = NO
+
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
+# nicely formatted so it can be parsed by a human reader.  This is useful
+# if you want to understand what is going on.  On the other hand, if this
+# tag is set to NO the size of the Perl module output will be much smaller
+# and Perl will parse it just the same.
+
+PERLMOD_PRETTY         = YES
+
+# The names of the make variables in the generated doxyrules.make file
+# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
+# This is useful so different doxyrules.make files included by the same
+# Makefile don't overwrite each other's variables.
+
+PERLMOD_MAKEVAR_PREFIX =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+
+# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
+# evaluate all C-preprocessor directives found in the sources and include
+# files.
+
+ENABLE_PREPROCESSING   = YES
+
+# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
+# names in the source code. If set to NO (the default) only conditional
+# compilation will be performed. Macro expansion can be done in a controlled
+# way by setting EXPAND_ONLY_PREDEF to YES.
+
+MACRO_EXPANSION        = NO
+
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
+# then the macro expansion is limited to the macros specified with the
+# PREDEFINED and EXPAND_AS_DEFINED tags.
+
+EXPAND_ONLY_PREDEF     = NO
+
+# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
+# in the INCLUDE_PATH (see below) will be search if a #include is found.
+
+SEARCH_INCLUDES        = YES
+
+# The INCLUDE_PATH tag can be used to specify one or more directories that
+# contain include files that are not input files but should be processed by
+# the preprocessor.
+
+INCLUDE_PATH           =
+
+# You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
+# patterns (like *.h and *.hpp) to filter out the header-files in the
+# directories. If left blank, the patterns specified with FILE_PATTERNS will
+# be used.
+
+INCLUDE_FILE_PATTERNS  =
+
+# The PREDEFINED tag can be used to specify one or more macro names that
+# are defined before the preprocessor is started (similar to the -D option of
+# gcc). The argument of the tag is a list of macros of the form: name
+# or name=definition (no spaces). If the definition and the = are
+# omitted =1 is assumed. To prevent a macro definition from being
+# undefined via #undef or recursively expanded use the := operator
+# instead of the = operator.
+
+PREDEFINED             =
+
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
+# this tag can be used to specify a list of macro names that should be expanded.
+# The macro definition that is found in the sources will be used.
+# Use the PREDEFINED tag if you want to use a different macro definition.
+
+EXPAND_AS_DEFINED      =
+
+# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
+# doxygen's preprocessor will remove all function-like macros that are alone
+# on a line, have an all uppercase name, and do not end with a semicolon. Such
+# function macros are typically used for boiler-plate code, and will confuse
+# the parser if not removed.
+
+SKIP_FUNCTION_MACROS   = YES
+
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES option can be used to specify one or more tagfiles.
+# Optionally an initial location of the external documentation
+# can be added for each tagfile. The format of a tag file without
+# this location is as follows:
+#   TAGFILES = file1 file2 ...
+# Adding location for the tag files is done as follows:
+#   TAGFILES = file1=loc1 "file2 = loc2" ...
+# where "loc1" and "loc2" can be relative or absolute paths or
+# URLs. If a location is present for each tag, the installdox tool
+# does not have to be run to correct the links.
+# Note that each tag file must have a unique name
+# (where the name does NOT include the path)
+# If a tag file is not located in the directory in which doxygen
+# is run, you must also specify the path to the tagfile here.
+
+TAGFILES               =
+
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create
+# a tag file that is based on the input files it reads.
+
+GENERATE_TAGFILE       =
+
+# If the ALLEXTERNALS tag is set to YES all external classes will be listed
+# in the class index. If set to NO only the inherited external classes
+# will be listed.
+
+ALLEXTERNALS           = NO
+
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
+# in the modules index. If set to NO, only the current project's groups will
+# be listed.
+
+EXTERNAL_GROUPS        = YES
+
+# The PERL_PATH should be the absolute path and name of the perl script
+# interpreter (i.e. the result of `which perl').
+
+PERL_PATH              = /usr/bin/perl
+
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+
+# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
+# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
+# or super classes. Setting the tag to NO turns the diagrams off. Note that
+# this option is superseded by the HAVE_DOT option below. This is only a
+# fallback. It is recommended to install and use dot, since it yields more
+# powerful graphs.
+
+CLASS_DIAGRAMS         = YES
+
+# You can define message sequence charts within doxygen comments using the \msc
+# command. Doxygen will then run the mscgen tool (see
+# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# documentation. The MSCGEN_PATH tag allows you to specify the directory where
+# the mscgen tool resides. If left empty the tool is assumed to be found in the
+# default search path.
+
+MSCGEN_PATH            =
+
+# If set to YES, the inheritance and collaboration graphs will hide
+# inheritance and usage relations if the target is undocumented
+# or is not a class.
+
+HIDE_UNDOC_RELATIONS   = YES
+
+# If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
+# available from the path. This tool is part of Graphviz, a graph visualization
+# toolkit from AT&T and Lucent Bell Labs. The other options in this section
+# have no effect if this option is set to NO (the default)
+
+HAVE_DOT               = NO
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is
+# allowed to run in parallel. When set to 0 (the default) doxygen will
+# base this on the number of processors available in the system. You can set it
+# explicitly to a value larger than 0 to get control over the balance
+# between CPU load and processing speed.
+
+DOT_NUM_THREADS        = 0
+
+# By default doxygen will write a font called FreeSans.ttf to the output
+# directory and reference it in all dot files that doxygen generates. This
+# font does not include all possible unicode characters however, so when you need
+# these (or just want a differently looking font) you can specify the font name
+# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
+# which can be done by putting it in a standard location or by setting the
+# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
+# containing the font.
+
+DOT_FONTNAME           = FreeSans.ttf
+
+# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
+# The default size is 10pt.
+
+DOT_FONTSIZE           = 10
+
+# By default doxygen will tell dot to use the output directory to look for the
+# FreeSans.ttf font (which doxygen will put there itself). If you specify a
+# different font using DOT_FONTNAME you can set the path where dot
+# can find it using this tag.
+
+DOT_FONTPATH           =
+
+# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect inheritance relations. Setting this tag to YES will force the
+# the CLASS_DIAGRAMS tag to NO.
+
+CLASS_GRAPH            = YES
+
+# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for each documented class showing the direct and
+# indirect implementation dependencies (inheritance, containment, and
+# class references variables) of the class with other documented classes.
+
+COLLABORATION_GRAPH    = YES
+
+# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
+# will generate a graph for groups, showing the direct groups dependencies
+
+GROUP_GRAPHS           = YES
+
+# If the UML_LOOK tag is set to YES doxygen will generate inheritance and
+# collaboration diagrams in a style similar to the OMG's Unified Modeling
+# Language.
+
+UML_LOOK               = NO
+
+# If set to YES, the inheritance and collaboration graphs will show the
+# relations between templates and their instances.
+
+TEMPLATE_RELATIONS     = NO
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
+# tags are set to YES then doxygen will generate a graph for each documented
+# file showing the direct and indirect include dependencies of the file with
+# other documented files.
+
+INCLUDE_GRAPH          = YES
+
+# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
+# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
+# documented header file showing the documented files that directly or
+# indirectly include this file.
+
+INCLUDED_BY_GRAPH      = YES
+
+# If the CALL_GRAPH and HAVE_DOT options are set to YES then
+# doxygen will generate a call dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable call graphs
+# for selected functions only using the \callgraph command.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
+# doxygen will generate a caller dependency graph for every global function
+# or class method. Note that enabling this option will significantly increase
+# the time of a run. So in most cases it will be better to enable caller
+# graphs for selected functions only using the \callergraph command.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
+# will graphical hierarchy of all classes instead of a textual one.
+
+GRAPHICAL_HIERARCHY    = YES
+
+# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
+# then doxygen will show the dependencies a directory has on other directories
+# in a graphical way. The dependency relations are determined by the #include
+# relations between the files in the directories.
+
+DIRECTORY_GRAPH        = YES
+
+# The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
+# generated by dot. Possible values are png, jpg, or gif
+# If left blank png will be used.
+
+DOT_IMAGE_FORMAT       = png
+
+# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# found. If left blank, it is assumed the dot tool can be found in the path.
+
+DOT_PATH               =
+
+# The DOTFILE_DIRS tag can be used to specify one or more directories that
+# contain dot files that are included in the documentation (see the
+# \dotfile command).
+
+DOTFILE_DIRS           =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
+# nodes that will be shown in the graph. If the number of nodes in a graph
+# becomes larger than this value, doxygen will truncate the graph, which is
+# visualized by representing a node as a red box. Note that doxygen if the
+# number of direct children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
+# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+
+DOT_GRAPH_MAX_NODES    = 50
+
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
+# graphs generated by dot. A depth value of 3 means that only nodes reachable
+# from the root by following a path via at most 3 edges will be shown. Nodes
+# that lay further from the root node will be omitted. Note that setting this
+# option to 1 or 2 may greatly reduce the computation time needed for large
+# code bases. Also note that the size of a graph can be further restricted by
+# DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+
+MAX_DOT_GRAPH_DEPTH    = 0
+
+# Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
+# background. This is disabled by default, because dot on Windows does not
+# seem to support this out of the box. Warning: Depending on the platform used,
+# enabling this option may lead to badly anti-aliased labels on the edges of
+# a graph (i.e. they become hard to read).
+
+DOT_TRANSPARENT        = NO
+
+# Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
+# files in one run (i.e. multiple -o and -T options on the command line). This
+# makes dot run faster, but since only newer versions of dot (>1.8.10)
+# support this, this feature is disabled by default.
+
+DOT_MULTI_TARGETS      = NO
+
+# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
+# generate a legend page explaining the meaning of the various boxes and
+# arrows in the dot generated graphs.
+
+GENERATE_LEGEND        = YES
+
+# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
+# remove the intermediate dot files that are used to generate
+# the various graphs.
+
+DOT_CLEANUP            = YES
Index: sandbox/2.4.1-3/prototype/library/oauth2/README.txt
===================================================================
--- sandbox/2.4.1-3/prototype/library/oauth2/README.txt	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/oauth2/README.txt	(revision 6351)
@@ -0,0 +1,3 @@
+OAuth2 Server now implements draft 20 of OAuth 2.0
+
+The client is still only draft-10.
Index: sandbox/2.4.1-3/prototype/library/tonic/phpdoctor.ini
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/phpdoctor.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/phpdoctor.ini	(revision 6351)
@@ -0,0 +1,14 @@
+; Tonic configuration file for PHPDoctor
+
+files = "*.php"
+ignore = ".git"
+doclet = standard
+default_package = "Tonic"
+overview = README.markdown
+
+d = "apidocs"
+windowtitle = "Tonic"
+doctitle = "Tonic: A RESTful Web App Development PHP Library"
+header = "Tonic"
+footer = "Tonic"
+
Index: sandbox/2.4.1-3/prototype/library/tonic/LICENSE
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/LICENSE	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/LICENSE	(revision 6351)
@@ -0,0 +1,18 @@
+Copyright (c) 2009 Paul James
+ 
+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.
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/response.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/response.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/response.php	(revision 6351)
@@ -0,0 +1,56 @@
+<?php
+
+require_once('def/response.php');
+
+/**
+ * @namespace Tonic\Tests
+ */
+class ResponseTester extends UnitTestCase {
+    
+    function testDefaultCacheHeader() {
+        
+        $config = array(
+            'uri' => '/responsetest'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        $response->addCacheHeader();
+        
+        $this->assertEqual($response->headers['Cache-Control'], 'max-age=86400, must-revalidate');
+        
+    }
+    
+    function testNoCacheHeader() {
+        
+        $config = array(
+            'uri' => '/responsetest'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        $response->addCacheHeader(0);
+        
+        $this->assertEqual($response->headers['Cache-Control'], 'no-cache');
+        
+    }
+    
+    function testAddEtag() {
+        
+        $config = array(
+            'uri' => '/responsetest'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        $response->addEtag("123123");
+        
+        $this->assertEqual($response->headers['Etag'], '"123123"');
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/test.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/test.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/test.php	(revision 6351)
@@ -0,0 +1,43 @@
+<?php
+
+error_reporting(error_reporting() & ~2048 & ~8192); // Make sure E_STRICT and E_DEPRECATED are disabled
+
+require_once('simpletest/unit_tester.php');
+require_once('simpletest/reporter.php');
+
+$core = new GroupTest('Core');
+
+require_once('../lib/tonic.php');
+
+$core->addTestFile('request.php');
+$core->addTestFile('resource.php');
+$core->addTestFile('response.php');
+$core->addTestFile('filesystem.php');
+$core->addTestFile('filesystemcollection.php');
+
+$test = new GroupTest('Tonic');
+$test->addTestCase($core);
+
+//*
+@include_once 'PHP/CodeCoverage.php';
+if (class_exists('PHP_CodeCoverage')) {
+    $coverage = new PHP_CodeCoverage;
+    $coverage->start('Tonic');
+}
+//*/
+
+if (TextReporter::inCli()) {
+	$test->run(new TextReporter());
+} else {
+    $test->run(new HtmlReporter());
+}
+
+if (isset($coverage)) {
+    $coverage->stop();
+    
+    require_once 'PHP/CodeCoverage/Report/HTML.php';
+    
+    $writer = new PHP_CodeCoverage_Report_HTML;
+    $writer->process($coverage, 'report');
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/filesystemcollection.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/filesystemcollection.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/filesystemcollection.php	(revision 6351)
@@ -0,0 +1,137 @@
+<?php
+
+require_once('../lib/tonic.php');
+require_once('../examples/filesystem/filesystem.php');
+require_once('../examples/filesystem/filesystemcollection.php');
+
+/**
+ * @namespace Tonic\Tests
+ */
+class FilesystemCollectionTester extends UnitTestCase {
+    
+    var $testPath;
+    
+    function __construct() {
+        $this->testPath = sys_get_temp_dir();
+    }
+    
+    function setUp() {
+        @mkdir($this->testPath.DIRECTORY_SEPARATOR.'collection');
+        file_put_contents($this->testPath.DIRECTORY_SEPARATOR.'collectionIndex', '<ul>{{resources}}</ul>');
+        file_put_contents($this->testPath.DIRECTORY_SEPARATOR.'collection'.DIRECTORY_SEPARATOR.'1', 'one');
+        file_put_contents($this->testPath.DIRECTORY_SEPARATOR.'collection'.DIRECTORY_SEPARATOR.'2', 'two');
+    }
+    
+    function tearDown() {
+        unlink($this->testPath.DIRECTORY_SEPARATOR.'collectionIndex');
+        unlink($this->testPath.DIRECTORY_SEPARATOR.'collection'.DIRECTORY_SEPARATOR.'1');
+        unlink($this->testPath.DIRECTORY_SEPARATOR.'collection'.DIRECTORY_SEPARATOR.'2');
+        @unlink($this->testPath.DIRECTORY_SEPARATOR.'collection'.DIRECTORY_SEPARATOR.'3');
+        rmdir($this->testPath.DIRECTORY_SEPARATOR.'collection');
+    }
+    
+    function testCollection() {
+        
+        $config = array(
+            'uri' => '/filesystemcollection/collectionIndex'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 200);
+        $this->assertEqual($response->body, '<ul><li><a href="/filesystemcollection/collection/1">1</a></li><li><a href="/filesystemcollection/collection/2">2</a></li></ul>');
+        
+    }
+    
+    function testReadCollectionItem() {
+        
+        $config = array(
+            'uri' => '/filesystemcollection/collection/1'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 200);
+        $this->assertEqual($response->body, 'one');
+        
+    }
+    
+    function testCreateCollectionItem() {
+        
+        $config = array(
+            'uri' => '/filesystemcollection/collectionIndex',
+            'method' => 'POST'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 411);
+        
+        $config = array(
+            'uri' => '/filesystemcollection/collectionIndex',
+            'method' => 'POST',
+            'data' => 'three'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 201);
+        $this->assertEqual($response->headers['Location'], '/filesystemcollection/collection/3');
+        
+        $config = array(
+            'uri' => '/filesystemcollection/collectionIndex'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 200);
+        $this->assertEqual($response->body, '<ul><li><a href="/filesystemcollection/collection/1">1</a></li><li><a href="/filesystemcollection/collection/2">2</a></li><li><a href="/filesystemcollection/collection/3">3</a></li></ul>');
+        
+    }
+    
+}
+
+
+/* Test resource definitions */
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /filesystemcollection/collection/.*
+ */
+class TestFileSystemCollectionItem extends FilesystemResource {
+    
+    function __construct() {
+        
+        $this->path = sys_get_temp_dir();
+        $this->uriStub = '/filesystemcollection';
+        
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /filesystemcollection/collectionIndex
+ */
+class TestFileSystemCollection extends FilesystemCollection {
+    
+    function __construct() {
+        
+        $this->path = sys_get_temp_dir();
+        $this->uriStub = '/filesystemcollection';
+        $this->collection = sys_get_temp_dir().'/collection';
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/filesystem.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/filesystem.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/filesystem.php	(revision 6351)
@@ -0,0 +1,149 @@
+<?php
+
+require_once('../lib/tonic.php');
+require_once('../examples/filesystem/filesystem.php');
+
+/**
+ * @namespace Tonic\Tests
+ */
+class FilesystemTester extends UnitTestCase {
+    
+    function testReadFile() {
+        
+        $testFilename = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tonicFilesystemTest';
+        file_put_contents($testFilename, 'test');
+        
+        $config = array(
+            'uri' => '/filesystem/one/tonicFilesystemTest'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 200);
+        $this->assertEqual($response->body, 'test');
+        
+        unlink($testFilename);
+    }
+    
+    function testReadDefaultDocument() {
+        
+        $testFilename = sys_get_temp_dir().DIRECTORY_SEPARATOR.'default.html';
+        file_put_contents($testFilename, 'test');
+        
+        $config = array(
+            'uri' => '/filesystem/one/'
+        );
+        
+        $request = new Request($config);
+        
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 200);
+        $this->assertEqual($response->body, 'test');
+        
+        unlink($testFilename);
+        
+    }
+    
+    function testReadNoResource() {
+        
+        $config = array(
+            'uri' => '/filesystem/one/tonicFilesystemTestDoesntExist'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 404);
+        
+    }
+    
+    function testCreateResource() {
+        
+        $testFilename = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tonicFilesystemTest';
+        
+        $config = array(
+            'uri' => '/filesystem/one/tonicFilesystemTest',
+            'method' => 'PUT'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 411);
+        
+        $config['data'] = 'test';
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 204);
+        $this->assertTrue(file_exists($testFilename));
+        $this->assertEqual(file_get_contents($testFilename), 'test');
+        
+        unlink($testFilename);
+        
+    }
+    
+    function testDeleteResource() {
+        
+        $testFilename = sys_get_temp_dir().DIRECTORY_SEPARATOR.'tonicFilesystemTest';
+        file_put_contents($testFilename, 'test');
+        
+        $config = array(
+            'uri' => '/filesystem/one/tonicFilesystemTest',
+            'method' => 'DELETE'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 204);
+        $this->assertFalse(file_exists($testFilename));
+        
+    }
+    
+    function testDeleteNoResource() {
+        
+        $config = array(
+            'uri' => '/filesystem/one/tonicFilesystemTestDoesntExist',
+            'method' => 'DELETE'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, 404);
+        
+    }
+    
+}
+
+
+/* Test resource definitions */
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /filesystem/one
+ * @uri /filesystem/one/.*
+ */
+class TestFileSystem extends FilesystemResource {
+    
+    function __construct($parameters) {
+        
+        parent::__construct($parameters);
+        $this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR;
+        $this->uriStub = '/filesystem/one/';
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/resource.php	(revision 6351)
@@ -0,0 +1,54 @@
+<?php
+
+require_once('def/resource.php');
+
+/**
+ * @namespace Tonic\Tests
+ */
+class ResourceTester extends UnitTestCase {
+    
+    function testFunctioningResourceExec() {
+        
+        $config = array(
+            'uri' => '/resourcetest/one'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+        $this->assertEqual($response->code, '200');
+        $this->assertEqual($response->body, 'test');
+        
+    }
+    
+    function testNoParametersArgumentToResourceConstructor() {
+        
+        $config = array(
+            'uri' => '/resourcetest/badconstructor'
+        );
+        
+        $this->expectError(new PatternExpectation('/Missing argument 1 for Resource::__construct/'));
+        $this->expectError(new PatternExpectation('/Undefined variable: parameters/'));
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+    }
+    
+    function testMethodDoesNotReturnResponseObject() {
+        
+        $config = array(
+            'uri' => '/resourcetest/badmethodresponse'
+        );
+        
+        $this->expectException(new PatternExpectation('/Method GET of (.+\\\\)?TestBadMethodResponse did not return a Response object/'));
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        $response = $resource->exec($request);
+        
+    }
+
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/def/response.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/def/response.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/def/response.php	(revision 6351)
@@ -0,0 +1,20 @@
+<?php
+
+/* Test resource definitions */
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /responsetest
+ */
+class TestResponse extends Resource {
+    
+    function get($request) {
+        
+        $response = new Response($request);
+        $response->body = 'test';
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/def/resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/def/resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/def/resource.php	(revision 6351)
@@ -0,0 +1,47 @@
+<?php
+
+/* Test resource definitions */
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /resourcetest/one
+ */
+class TestResource extends Resource {
+    
+    function get($request) {
+        
+        $response = new Response($request);
+        $response->body = 'test';
+        return $response;
+        
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /resourcetest/badconstructor
+ */
+class TestBadResourceConstructor extends Resource {
+    
+    function __construct() {
+        
+        parent::__construct();
+        
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /resourcetest/badmethodresponse
+ */
+class TestBadMethodResponse extends Resource {
+    
+    function get($request) {
+        
+        return TRUE;
+        
+    }
+    
+}
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/def/Autoload.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/def/Autoload.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/def/Autoload.php	(revision 6351)
@@ -0,0 +1,8 @@
+<?php
+
+/**
+ * @namespace Tonic\Tests
+ */
+class Autoload extends Resource {
+
+}
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/def/request.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/def/request.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/def/request.php	(revision 6351)
@@ -0,0 +1,135 @@
+<?php
+
+/* Test resource definitions */
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/one
+ * @uri /requesttest/three/(.+)/four 12
+ */
+class NewResource extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/one/two
+ */
+class ChildResource extends NewResource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/railsstyle/:param/:param2
+ * @uri /requesttest/uritemplatestyle/{param}/{param2}
+ */
+class TwoUriParams extends Resource {
+
+    var $receivedParams;
+    
+    function get($request, $param, $param2) {
+        $this->receivedParams = array(
+            'param' => $param,
+            'param2' => $param2
+        );
+        return new Response($request);
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/railsmixedstyle/{param}/(.+)/{param2}/(.+)
+ * @uri /requesttest/uritemplatemixedstyle/{param}/(.+)/{param2}/(.+)
+ * @uri /requesttest/mixedstyle/:param/(.+)/{param2}/(.+)
+ */
+class FourUriParams extends Resource {
+    
+    var $receivedParams;
+    
+    function get($request, $something, $otherthing, $param, $param2) {
+        $this->receivedParams = array(
+            'param' => $param,
+            'param2' => $param2,
+            'something' => $something,
+            'otherthing' => $otherthing
+        );
+        return new Response($request);
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/trailingslashurl/
+ */
+class TrailingSlashUrl extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/optional(?:/param1/([^/]*))?
+ * @uri /requesttest/optional(?:/([a-z]+))?
+ */
+class OptionalParams extends Resource {
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/squiggly/(\d+-[0-9a-f]{8}-[0-9a-f]{6})
+ * @uri /requesttest/noncapture/(?:something)?
+ */
+class SquigglyRegexResource extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/httpmethods
+ */
+class MethodTestResource extends Resource {
+    
+    function options($request) {
+        return new Response($request);
+    }
+    
+    function woot($request) {
+        return new Response($request);
+    }
+    
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/priority 1
+  */
+class PriorityTestLessImportantResource extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/priority 2
+  */
+class PriorityTestMoreImportantResource extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/differenturi(priority) 1
+  */
+class PriorityTestDifferntURILessImportantResource extends Resource {
+
+}
+
+/**
+ * @namespace Tonic\Tests
+ * @uri /requesttest/differenturipriority 2
+  */
+class PriorityTestDifferntURIMoreImportantResource extends Resource {
+
+}
Index: sandbox/2.4.1-3/prototype/library/tonic/tests/request.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/tests/request.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/tests/request.php	(revision 6351)
@@ -0,0 +1,826 @@
+<?php
+
+require_once('def/request.php');
+
+/**
+ * @namespace Tonic\Tests
+ */
+class RequestTester extends UnitTestCase {
+    
+    function testRequestURI() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->uri, $config['uri']);
+        
+        $_SERVER['REQUEST_URI'] = '/requesttest/one/two';
+        $request = new Request();
+        $this->assertEqual($request->uri, $config['uri']);
+        
+    }
+    
+    function testRequestBaseUri() {
+        
+        $config = array(
+            'baseUri' => '/some/sub/dir'
+        );
+        
+        $request = new Request($config);
+        
+        $this->assertEqual($request->baseUri, $config['baseUri']);
+        
+    }
+    
+    function testAssignMimetypes() {
+        
+        $config = array(
+            'mimetypes' => array(
+                'some' => 'text/something'
+            )
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->mimetypes['some'], 'text/something');
+        
+    }
+    
+    function testGetRequestMethod() {
+        
+        $config = array();
+        
+        $request = new Request($config);
+        
+        $this->assertEqual($request->method, 'GET');
+        
+    }
+    
+    function testPostRequestMethodWithData() {
+        
+        $config = array(
+            'method' => 'post',
+            'data' => 'some data'
+        );
+        
+        $request = new Request($config);
+        
+        $this->assertEqual($request->method, 'POST');
+        $this->assertEqual($request->data, 'some data');
+        
+    }
+    
+    function testPutRequestMethodWithData() {
+        
+        $config = array(
+            'method' => 'put',
+            'data' => 'some data'
+        );
+        
+        $request = new Request($config);
+        
+        $this->assertEqual($request->method, 'PUT');
+        $this->assertEqual($request->data, 'some data');
+        
+    }
+    
+    function testConnegOnBareURI() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two',
+            'accept' => '',
+            'acceptLang' => ''
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->uri, '/requesttest/one/two');
+    
+    }
+    
+    function testConnegOnExtensionURI() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two.html',
+            'accept' => '',
+            'acceptLang' => ''
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->uri, '/requesttest/one/two');
+        
+    }
+    
+    function testConnegOnBareURIWithAccept() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two',
+            'accept' => 'image/png;q=0.5,text/html',
+            'acceptLang' => ''
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testConnegOnExtensionURIWithAccept() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two.html',
+            'accept' => 'image/png;q=0.5,text/html',
+            'acceptLang' => ''
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testConnegOnBareURIWithAcceptLang() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two',
+            'accept' => '',
+            'acceptLang' => 'fr;q=0.5,en'
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testConnegOnExtensionURIWithAcceptLang() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two.html',
+            'accept' => '',
+            'acceptLang' => 'fr;q=0.5,en'
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html.en',
+            '/requesttest/one/two.html.fr',
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testConnegOnBareURIWithAcceptAndAcceptLang() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two',
+            'accept' => 'image/png;q=0.5,text/html',
+            'acceptLang' => 'fr;q=0.5,en'
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html.en',
+            '/requesttest/one/two.html.fr',
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png.en',
+            '/requesttest/one/two.png.fr',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testConnegOnExtensionURIWithAcceptAndAcceptLang() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two.html',
+            'accept' => 'image/png;q=0.5,text/html',
+            'acceptLang' => 'fr;q=0.5,en'
+        );
+        
+        $request = new Request($config);
+        $this->assertEqual($request->negotiatedUris, array(
+            '/requesttest/one/two.html.en',
+            '/requesttest/one/two.html.fr',
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png.html',
+            '/requesttest/one/two.png.en',
+            '/requesttest/one/two.png.fr',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->formatNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.png',
+            '/requesttest/one/two'
+        ));
+        $this->assertEqual($request->languageNegotiatedUris, array(
+            '/requesttest/one/two.html',
+            '/requesttest/one/two.en',
+            '/requesttest/one/two.fr',
+            '/requesttest/one/two'
+        ));
+        
+    }
+    
+    function testResourceLoaderWithNoResources() {
+        
+        $config = array(
+            'uri' => '/three'
+        );
+        
+        $request = new Request($config);
+        
+        try {
+            $resource = $request->loadResource();
+            $this->fail('Expected ResponseException to be thrown');
+        } catch (ResponseException $e) {
+            $this->assertEqual($e->getCode(), 404);
+        }
+        
+    }
+    
+    function testResourceLoaderWithAResources() {
+        
+        $config = array(
+            'uri' => '/requesttest/one'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/NewResource/', get_class($resource));
+        
+    }
+    
+    function testResourceLoaderWithAChildResources() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/ChildResource/', get_class($resource));
+        
+    }
+    
+    function testResourceLoaderWithRegexURIMatch() {
+        
+        $config = array(
+            'uri' => '/requesttest/three/something/four'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/NewResource/', get_class($resource));
+        $this->assertPattern('/0: something/', $resource);
+        
+    }
+    
+    function testIfMatch() {
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifMatch' => '123123'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('123123'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifMatch' => '"123123"'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('123123'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifMatch' => '"123123","456456"'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('123123', '456456'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifMatch' => '"123123", "456456"'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('123123', '456456'));
+        $this->assertTrue($request->ifMatch('123123'));
+        $this->assertFalse($request->ifMatch('123456'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifMatch' => '*'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('*'));
+        $this->assertTrue($request->ifMatch('123123'));
+        $this->assertTrue($request->ifMatch('123456'));
+        
+    }
+    
+    function testIfNoneMatch() {
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '123123'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifNoneMatch, array('123123'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '"123123"'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifNoneMatch, array('123123'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '"123123","456456"'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifNoneMatch, array('123123', '456456'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '123123, 456456'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifNoneMatch, array('123123', '456456'));
+        $this->assertTrue($request->ifNoneMatch('123123'));
+        $this->assertFalse($request->ifNoneMatch('123456'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '*'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifNoneMatch, array('*'));
+        $this->assertFalse($request->ifNoneMatch('123123'));
+        $this->assertFalse($request->ifNoneMatch('123456'));
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'ifNoneMatch' => '123123, 456456',
+            'ifMatch' => '*'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->ifMatch, array('*'));
+        $this->assertTrue($request->ifMatch('123123'));
+        $this->assertTrue($request->ifMatch('123456'));
+        $this->assertFalse($request->ifNoneMatch('123123'));
+        $this->assertFalse($request->ifNoneMatch('123456'));
+        
+    }
+    
+    function test404NotFound() {
+        
+        $config = array(
+            'uri' => '/requesttest/notfound'
+        );
+        $request = new Request($config);
+        
+        try {
+            $resource = $request->loadResource();
+            $this->fail('Expected ResponseException to be thrown');
+        } catch (ResponseException $e) {
+            $this->assertEqual($e->getCode(), 404);
+        }
+        
+    }
+    
+    function testResourceDataLoading() {
+        
+        $config = array(
+            'uri' => '/requesttest/one/two'
+        );
+        
+        $request = new Request($config);
+        
+        $this->assertEqual($request->resources['/requesttest/one/two']['namespace'], 'Tonic\Tests');
+        $this->assertPattern('/ChildResource/', $request->resources['/requesttest/one/two']['class']);
+        $this->assertPattern('|def/request\.php|', $request->resources['/requesttest/one/two']['filename']);
+        $this->assertEqual($request->resources['/requesttest/one/two']['priority'], 0);
+        
+    }
+    
+    function testNamespaceMounting() {
+        
+        $config = array(
+            'uri' => '/foo/bar/requesttest/one',
+            'mount' => array(
+                'Tonic\Tests' => '/foo/bar'
+            )
+        );
+        
+        $request = new Request($config);
+        
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/NewResource/', get_class($resource));
+        
+    }
+    
+    function testURITemplateStyleUriParameters() {
+        
+        $config = array(
+            'uri' => '/requesttest/uritemplatestyle/woo/yay'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/TwoUriParams/', get_class($resource));
+        $this->assertPattern('/param: woo/', $resource);
+        $this->assertPattern('/param2: yay/', $resource);
+        
+        $resource->exec($request);
+        $this->assertEqual($resource->receivedParams['param'], 'woo');
+        $this->assertEqual($resource->receivedParams['param2'], 'yay');
+        
+        
+        $config = array(
+            'uri' => '/requesttest/uritemplatemixedstyle/woo/yay/foo/bar'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/FourUriParams/', get_class($resource));
+        $this->assertPattern('/param: woo/', $resource);
+        $this->assertPattern('/1: yay/', $resource);
+        $this->assertPattern('/param2: foo/', $resource);
+        $this->assertPattern('/3: bar/', $resource);
+        
+        $resource->exec($request);
+        $this->assertEqual($resource->receivedParams['param'], 'woo');
+        $this->assertEqual($resource->receivedParams['something'], 'yay');
+        $this->assertEqual($resource->receivedParams['param2'], 'foo');
+        $this->assertEqual($resource->receivedParams['otherthing'], 'bar');
+    }
+    
+    function testRailsStyleUriParameters() {
+        
+        $config = array(
+            'uri' => '/requesttest/railsstyle/woo/yay'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/TwoUriParams/', get_class($resource));
+        $this->assertPattern('/param: woo/', $resource);
+        $this->assertPattern('/param2: yay/', $resource);
+        
+        $resource->exec($request);
+        $this->assertEqual($resource->receivedParams['param'], 'woo');
+        $this->assertEqual($resource->receivedParams['param2'], 'yay');
+        
+        
+        $config = array(
+            'uri' => '/requesttest/railsmixedstyle/woo/yay/foo/bar'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/FourUriParams/', get_class($resource));
+        $this->assertPattern('/param: woo/', $resource);
+        $this->assertPattern('/1: yay/', $resource);
+        $this->assertPattern('/param2: foo/', $resource);
+        $this->assertPattern('/3: bar/', $resource);
+        
+        $resource->exec($request);
+        $this->assertEqual($resource->receivedParams['param'], 'woo');
+        $this->assertEqual($resource->receivedParams['something'], 'yay');
+        $this->assertEqual($resource->receivedParams['param2'], 'foo');
+        $this->assertEqual($resource->receivedParams['otherthing'], 'bar');
+    }
+    
+    function testMixedStyleUriParameters() {
+        
+        $config = array(
+            'uri' => '/requesttest/mixedstyle/woo/yay/foo/bar'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/FourUriParams/', get_class($resource));
+        $this->assertPattern('/param: woo/', $resource);
+        $this->assertPattern('/1: yay/', $resource);
+        $this->assertPattern('/param2: foo/', $resource);
+        $this->assertPattern('/3: bar/', $resource);
+        
+        $resource->exec($request);
+        $this->assertEqual($resource->receivedParams['param'], 'woo');
+        $this->assertEqual($resource->receivedParams['something'], 'yay');
+        $this->assertEqual($resource->receivedParams['param2'], 'foo');
+        $this->assertEqual($resource->receivedParams['otherthing'], 'bar');
+    }
+    
+    function testAutoloadingOfResourcesWithoutAutoloadFunction() {
+        
+        $config = array(
+            'uri' => '/requesttest/autoload',
+            'autoload' => array(
+                '/requesttest/autoload' => 'Autoload'
+            )
+        );
+        
+        $request = new Request($config);
+        
+        $this->expectException(new PatternExpectation('/Unable to load resource/'));
+        $resource = $request->loadResource();
+        
+    }
+    
+    function testAutoloadingOfResources() {
+        
+        $config = array(
+            'uri' => '/requesttest/autoload',
+            'autoload' => array(
+                '/requesttest/autoload' => 'Autoload'
+            )
+        );
+        
+        function __autoload($className) {
+            if (file_exists('def/'.$className.'.php')) {
+                require_once 'def/'.$className.'.php';
+            }
+        }
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/Autoload/', get_class($resource));
+        $this->assertPattern('/Class: Autoload/', $request);
+        $this->assertPattern('|File: '.dirname(__FILE__).DIRECTORY_SEPARATOR.'def/Autoload.php|', $request);
+        
+    }
+    
+    function testTrailingSlashRemoval() {
+        
+        $config = array(
+            'uri' => '/requesttest/trailingslashurl/'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->uri, substr($config['uri'], 0, -1));
+        
+    }
+    
+    function testRequestRootURI() {
+        
+        $config = array(
+            'uri' => '/'
+        );
+        $request = new Request($config);
+        $this->assertEqual($request->uri, $config['uri']);
+        
+        $_SERVER['REQUEST_URI'] = '/';
+        $request = new Request();
+        $this->assertEqual($request->uri, $config['uri']);
+        
+    }
+    
+    function testMethodNotAllowed() {
+        
+        $config = array(
+            'uri' => '/requesttest/one',
+            'method' => 'PUT'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        try {
+            $response = $resource->exec($request);
+            $this->fail('Expected ResponseException to be thrown');
+        } catch (ResponseException $e) {
+            $this->assertEqual($e->getCode(), 405);
+        }
+        
+    }
+    
+    function testOptionalRegexURIParams() {
+        
+        $config = array(
+            'uri' => '/requesttest/optional'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/OptionalParams/', get_class($resource));
+        $this->assertNoPattern('/0: /', $resource);
+        
+        $config = array(
+            'uri' => '/requesttest/optional/param1/woo'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/OptionalParams/', get_class($resource));
+        $this->assertPattern('/0: woo/', $resource);
+        
+        $config = array(
+            'uri' => '/requesttest/optional/something'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/OptionalParams/', get_class($resource));
+        $this->assertPattern('/0: something/', $resource);
+        
+    }
+    
+    function testResourceLoaderWithSquigglyBraceRegexURIMatch() {
+        
+        $config = array(
+            'uri' => '/requesttest/squiggly/9999-aaaaaaaa-bbbbbb'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/SquigglyRegexResource/', get_class($resource));
+        
+        $config = array(
+            'uri' => '/requesttest/squiggly/9999-aaa-bbb'
+        );
+        
+        $request = new Request($config);
+        
+        try {
+            $resource = $request->loadResource();
+            $this->fail('Expected ResponseException to be thrown');
+        } catch (ResponseException $e) {
+            $this->assertTrue(TRUE);
+        }
+        
+    }
+    
+    function testResourceLoaderWithNonCapturingGroupRegexURIMatch() {
+        
+        $config = array(
+            'uri' => '/requesttest/noncapture/something'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertPattern('/SquigglyRegexResource/', get_class($resource));
+        
+    }
+    
+    function testAllowedHTTPMethods() {
+        
+        $config = array(
+            'uri' => '/requesttest/httpmethods',
+            'method' => 'OPTIONS'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        try {
+            $response = $resource->exec($request);
+            $this->assertTrue(TRUE);
+        } catch (ResponseException $e) {
+            $this->fail('Did not expect ResponseException to be thrown');
+        }
+        
+        $config = array(
+            'uri' => '/requesttest/httpmethods',
+            'method' => 'WOOT'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        try {
+            $response = $resource->exec($request);
+            $this->fail('Expected ResponseException to be thrown');
+        } catch (ResponseException $e) {
+            $this->assertTrue(TRUE);
+        }
+        
+    }
+    
+    function testURIPriority() {
+        
+        // with same @uri
+        
+        $config = array(
+            'uri' => '/requesttest/priority'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertEqual(get_class($resource), 'PriorityTestMoreImportantResource');
+        
+        // with different @uri
+        
+        $config = array(
+            'uri' => '/requesttest/differenturipriority'
+        );
+        
+        $request = new Request($config);
+        $resource = $request->loadResource();
+        
+        $this->assertEqual(get_class($resource), 'PriorityTestDifferntURIMoreImportantResource');
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/.travis.yml
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/.travis.yml	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/.travis.yml	(revision 6351)
@@ -0,0 +1,5 @@
+language: php
+php:
+  - 5.2
+  - 5.3
+  - 5.4
Index: sandbox/2.4.1-3/prototype/library/tonic/lib/tonic.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/lib/tonic.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/lib/tonic.php	(revision 6351)
@@ -0,0 +1,882 @@
+<?php
+/*
+ * This file is part of the Tonic.
+ * (c) Paul James <paul@peej.co.uk>
+ *
+ * For the full copyright and license information, please view the LICENSE
+ * file that was distributed with this source code.
+ */
+
+/* Turn on namespace in PHP5.3 if you have namespace collisions from the Tonic classnames
+namespace Tonic;
+use \ReflectionClass as ReflectionClass;
+use \ReflectionMethod as ReflectionMethod;
+use \Exception as Exception;
+//*/
+
+/**
+ * Model the data of the incoming HTTP request
+ * @namespace Tonic\Lib
+ */
+class Request {
+    
+    /**
+     * The requested URI
+     * @var str
+     */
+    public $uri;
+    
+    /**
+     * The URI where the front controller is positioned in the server URI-space
+     * @var str
+     */
+    public $baseUri = '';
+    
+    /**
+     * Array of possible URIs based upon accept and accept-language request headers in order of preference
+     * @var str[]
+     */
+    public $negotiatedUris = array();
+    
+    /**
+     * Array of possible URIs based upon accept request headers in order of preference
+     * @var str[]
+     */
+    public $formatNegotiatedUris = array();
+    
+    /**
+     * Array of possible URIs based upon accept-language request headers in order of preference
+     * @var str[]
+     */
+    public $languageNegotiatedUris = array();
+    
+    /**
+     * Array of accept headers in order of preference
+     * @var str[][]
+     */
+    public $accept = array();
+    
+    /**
+     * Array of accept-language headers in order of preference
+     * @var str[][]
+     */
+    public $acceptLang = array();
+    
+    /**
+     * Array of accept-encoding headers in order of preference
+     * @var str[]
+     */
+    public $acceptEncoding = array();
+    
+    /**
+     * Map of file/URI extensions to mimetypes
+     * @var str[]
+     */
+    public $mimetypes = array(
+        'html' => 'text/html',
+        'txt' => 'text/plain',
+        'php' => 'application/php',
+        'css' => 'text/css',
+        'js' => 'application/javascript',
+        'json' => 'application/json',
+        'xml' => 'application/xml',
+        'rss' => 'application/rss+xml',
+        'atom' => 'application/atom+xml',
+        'gz' => 'application/x-gzip',
+        'tar' => 'application/x-tar',
+        'zip' => 'application/zip',
+        'gif' => 'image/gif',
+        'png' => 'image/png',
+        'jpg' => 'image/jpeg',
+        'ico' => 'image/x-icon',
+        'swf' => 'application/x-shockwave-flash',
+        'flv' => 'video/x-flv',
+        'avi' => 'video/mpeg',
+        'mpeg' => 'video/mpeg',
+        'mpg' => 'video/mpeg',
+        'mov' => 'video/quicktime',
+        'mp3' => 'audio/mpeg'
+    );
+    
+    /**
+     * Supported HTTP methods
+     * @var str[]
+     */
+    public $HTTPMethods = array(
+        'GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'
+    );
+    
+    /**
+     * Allowed resource methods
+     * @var str[]
+     */
+    public $allowedMethods = array();
+    
+    /**
+     * HTTP request method of incoming request
+     * @var str
+     */
+    public $method = 'GET';
+    
+    /**
+     * Body data of incoming request
+     * @var str
+     */
+    public $data;
+    
+    /**
+     * Body data of incoming request
+     * @var array
+     */
+    public $dataDecoded;
+    
+    /**
+     * Array of if-match etags
+     * @var str[]
+     */
+    public $ifMatch = array();
+    
+    /**
+     * Array of if-none-match etags
+     * @var str[]
+     */
+    public $ifNoneMatch = array();
+    
+    /**
+     * The resource classes loaded and how they are wired to URIs
+     * @var str[]
+     */
+    public $resources = array();
+    
+    /**
+     * A list of URL to namespace/package mappings for routing requests to a
+     * group of resources that are wired into a different URL-space
+     * @var str[]
+     */
+    public $mounts = array();
+    
+    /**
+     * Set a default configuration option
+     */
+    protected function getConfig($config, $configVar, $serverVar = NULL, $default = NULL) {
+        if (isset($config[$configVar])) {
+            return $config[$configVar];
+        } elseif (isset($_SERVER[$serverVar]) && $_SERVER[$serverVar] != '') {
+            return $_SERVER[$serverVar];
+        } else {
+            return $default;
+        }
+    }
+    
+    /**
+     * Create a request object using the given configuration options.
+     *
+     * The configuration options array can contain the following:
+     *
+     * <dl>
+     * <dt>uri</dt> <dd>The URI of the request</dd>
+     * <dt>method</dt> <dd>The HTTP method of the request</dd>
+     * <dt>data</dt> <dd>The body data of the request</dd>
+     * <dt>accept</dt> <dd>An accept header</dd>
+     * <dt>acceptLang</dt> <dd>An accept-language header</dd>
+     * <dt>acceptEncoding</dt> <dd>An accept-encoding header</dd>
+     * <dt>ifMatch</dt> <dd>An if-match header</dd>
+     * <dt>ifNoneMatch</dt> <dd>An if-none-match header</dd>
+     * <dt>mimetypes</dt> <dd>A map of file/URI extenstions to mimetypes, these
+     * will be added to the default map of mimetypes</dd>
+     * <dt>baseUri</dt> <dd>The base relative URI to use when dispatcher isn't
+     * at the root of the domain. Do not put a trailing slash</dd>
+     * <dt>mounts</dt> <dd>an array of namespace to baseUri prefix mappings</dd>
+     * <dt>HTTPMethods</dt> <dd>an array of HTTP methods to support</dd>
+     * </dl>
+     *
+     * @param mixed[] config Configuration options
+     */
+    function __construct($config = array()) {
+        
+        // set defaults
+        $config['uri'] = parse_url($this->getConfig($config, 'uri', 'REQUEST_URI'), PHP_URL_PATH);
+        $config['baseUri'] = $this->getConfig($config, 'baseUri', '');
+        $config['accept'] = $this->getConfig($config, 'accept', 'HTTP_ACCEPT');
+        $config['acceptLang'] = $this->getConfig($config, 'acceptLang', 'HTTP_ACCEPT_LANGUAGE');
+        $config['acceptEncoding'] = $this->getConfig($config, 'acceptEncoding', 'HTTP_ACCEPT_ENCODING');
+        $config['ifMatch'] = $this->getConfig($config, 'ifMatch', 'HTTP_IF_MATCH');
+        $config['ifNoneMatch'] = $this->getConfig($config, 'ifNoneMatch', 'HTTP_IF_NONE_MATCH');
+        
+        if (isset($config['mimetypes']) && is_array($config['mimetypes'])) {
+            foreach ($config['mimetypes'] as $ext => $mimetype) {
+                $this->mimetypes[$ext] = $mimetype;
+            }
+        }
+        
+        // set baseUri
+        $this->baseUri = $config['baseUri'];
+        
+        // get request URI
+        $parts = explode('/', $config['uri']);
+        $lastPart = array_pop($parts);
+        $this->uri = join('/', $parts);
+        
+        $parts = explode('.', $lastPart);
+        $this->uri .= '/'.$parts[0];
+        
+        if ($this->uri != '/' && substr($this->uri, -1, 1) == '/') { // remove trailing slash problem
+            $this->uri = substr($this->uri, 0, -1);
+        }
+        
+        array_shift($parts);
+        foreach ($parts as $part) {
+            $this->accept[10][] = $part;
+            $this->acceptLang[10][] = $part;
+        }
+        
+        // sort accept headers
+        $accept = explode(',', strtolower($config['accept']));
+        foreach ($accept as $mimetype) {
+            $parts = explode(';q=', $mimetype);
+            if (isset($parts) && isset($parts[1]) && $parts[1]) {
+                $num = $parts[1] * 10;
+            } else {
+                $num = 10;
+            }
+            $key = array_search($parts[0], $this->mimetypes);
+            if ($key) {
+                $this->accept[$num][] = $key;
+            }
+        }
+        krsort($this->accept);
+        
+        // sort lang accept headers
+        $accept = explode(',', strtolower($config['acceptLang']));
+        foreach ($accept as $mimetype) {
+            $parts = explode(';q=', $mimetype);
+            if (isset($parts) && isset($parts[1]) && $parts[1]) {
+                $num = $parts[1] * 10;
+            } else {
+                $num = 10;
+            }
+            $this->acceptLang[$num][] = $parts[0];
+        }
+        krsort($this->acceptLang);
+        
+        // get encoding accept headers
+        if ($config['acceptEncoding']) {
+            foreach (explode(',', $config['acceptEncoding']) as $key => $accept) {
+                $this->acceptEncoding[$key] = trim($accept);
+            }
+        }
+        
+        // create negotiated URI lists from accept headers and request URI
+        foreach ($this->accept as $typeOrder) {
+            foreach ($typeOrder as $type) {
+                if ($type) {
+                    foreach ($this->acceptLang as $langOrder) {
+                        foreach ($langOrder as $lang) {
+                            if ($lang && $lang != $type) {
+                                $this->negotiatedUris[] = $this->uri.'.'.$type.'.'.$lang;
+                            }
+                        }
+                    }
+                    $this->negotiatedUris[] = $this->uri.'.'.$type;
+                    $this->formatNegotiatedUris[] = $this->uri.'.'.$type;
+                }
+            }
+        }
+        foreach ($this->acceptLang as $langOrder) {
+            foreach ($langOrder as $lang) {
+                if ($lang) {
+                    $this->negotiatedUris[] = $this->uri.'.'.$lang;
+                    $this->languageNegotiatedUris[] = $this->uri.'.'.$lang;
+                }
+            }
+        }
+        $this->negotiatedUris[] = $this->uri;
+        $this->formatNegotiatedUris[] = $this->uri;
+        $this->languageNegotiatedUris[] = $this->uri;
+        
+        $this->negotiatedUris = array_values(array_unique($this->negotiatedUris));
+        $this->formatNegotiatedUris = array_values(array_unique($this->formatNegotiatedUris));
+        $this->languageNegotiatedUris = array_values(array_unique($this->languageNegotiatedUris));
+        
+        $this->HTTPMethods = $this->getConfig($config, 'HTTPMethods', NULL, $this->HTTPMethods);
+        
+        // get HTTP method
+        $this->method = strtoupper($this->getConfig($config, 'method', 'REQUEST_METHOD', $this->method));
+        
+	// get HTTP request data
+	$this->data = $this->getConfig($config, 'data', NULL, file_get_contents("php://input"));
+
+        // get HTTP request dataDecode into array
+	$this->dataDecoded  = $this->__decodeData( $this->data );
+	
+        // conditional requests
+        if ($config['ifMatch']) {
+            $ifMatch = explode(',', $config['ifMatch']);
+            foreach ($ifMatch as $etag) {
+                $this->ifMatch[] = trim($etag, '" ');
+            }
+        }
+        if ($config['ifNoneMatch']) {
+            $ifNoneMatch = explode(',', $config['ifNoneMatch']);
+            foreach ($ifNoneMatch as $etag) {
+                $this->ifNoneMatch[] = trim($etag, '" ');
+            }
+        }
+        
+        // mounts
+        if (isset($config['mount']) && is_array($config['mount'])) {
+            $this->mounts = $config['mount'];
+        }
+        
+        // prime named resources for autoloading
+        if (isset($config['autoload']) && is_array($config['autoload'])) {
+            foreach ($config['autoload'] as $uri => $className) {
+                $this->resources[$uri] = array(
+                    'class' => $className,
+                    'loaded' => FALSE
+                );
+            }
+        }
+        
+        // load definitions of already loaded resource classes
+        $resourceClassName = class_exists('Tonic\\Resource', false) ? 'Tonic\\Resource' : 'Resource';
+        foreach (get_declared_classes() as $className) {
+            if (is_subclass_of($className, $resourceClassName)) {
+                
+                $resourceDetails = $this->getResourceClassDetails($className);
+                
+                preg_match_all('/@uri\s+([^\s]+)(?:\s([0-9]+))?/', $resourceDetails['comment'], $annotations);
+                if (isset($annotations[1]) && $annotations[1]) {
+                    $uris = $annotations[1];
+                } else {
+                    $uris = array();
+                }
+                
+                foreach ($uris as $index => $uri) {
+                    if ($uri != '/' && substr($uri, -1, 1) == '/') { // remove trailing slash problem
+                        $uri = substr($uri, 0, -1);
+                    }
+                    if (isset($annotations[2][$index]) && is_numeric($annotations[2][$index])) {
+                        $priority = intval($annotations[2][$index]);
+                    } else {
+                        $priority = 0;
+                    }
+                    if (
+                        !isset($this->resources[$resourceDetails['mountPoint'].$uri]) ||
+                        $this->resources[$resourceDetails['mountPoint'].$uri]['priority'] < $priority
+                    ) {
+                        $this->resources[$resourceDetails['mountPoint'].$uri] = array(
+                            'namespace' => $resourceDetails['namespaceName'],
+                            'class' => $resourceDetails['className'],
+                            'filename' => $resourceDetails['filename'],
+                            'line' => $resourceDetails['line'],
+                            'priority' => $priority,
+                            'loaded' => TRUE
+                        );
+                    }
+                }
+            }
+        }
+        
+    }
+    
+    /**
+     * Get the details of a Resource class by reflection
+     * @param str className
+     * @return str[]
+     */
+    protected function getResourceClassDetails($className) {
+        
+        $resourceReflector = new ReflectionClass($className);
+        $comment = $resourceReflector->getDocComment();
+        
+        $className = $resourceReflector->getName();
+        if (method_exists($resourceReflector, 'getNamespaceName')) {
+            $namespaceName = $resourceReflector->getNamespaceName();
+        } else {
+            // @codeCoverageIgnoreStart
+            $namespaceName = FALSE;
+            // @codeCoverageIgnoreEnd
+        }
+        
+        if (!$namespaceName) {
+            preg_match('/@(?:package|namespace)\s+([^\s]+)/', $comment, $package);
+            if (isset($package[1])) {
+                $namespaceName = $package[1];
+            }
+        }
+        
+        // adjust URI for mountpoint
+        if (isset($this->mounts[$namespaceName])) {
+            $mountPoint = $this->mounts[$namespaceName];
+        } else {
+            $mountPoint = '';
+        }
+        
+        return array(
+            'comment' => $comment,
+            'className' => $className,
+            'namespaceName' => $namespaceName,
+            'filename' => $resourceReflector->getFileName(),
+            'line' => $resourceReflector->getStartLine(),
+            'mountPoint' => $mountPoint
+        );
+    
+    }
+
+     /**
+     * Convert the string data into a array data
+     * @return array
+     * @codeCoverageIgnore
+     */
+    function __decodeData($data) {
+	$arrayData = array();
+	if($data){
+	    $arrayIndex = explode('&', $data);
+	    foreach($arrayIndex as $key => $value){
+		list($i,$val) = explode ('=', $value);
+		$arrayData[$i] = $val;
+	    }
+	}
+	return $arrayData;
+    }
+
+    /**
+     * Convert the object into a string suitable for printing
+     * @return str
+     * @codeCoverageIgnore
+     */
+    function __toString() {
+        $str = 'URI: '.$this->uri."\n";
+        $str .= 'Method: '.$this->method."\n";
+        if ($this->data) {
+            $str .= 'Data: '.$this->data."\n";
+        }
+        $str .= 'Acceptable Formats:';
+        foreach ($this->accept as $accept) {
+            foreach ($accept as $a) {
+                $str .= ' .'.$a;
+                if (isset($this->mimetypes[$a])) $str .= ' ('.$this->mimetypes[$a].')';
+            }
+        }
+        $str .= "\n";
+        $str .= 'Acceptable Languages:';
+        foreach ($this->acceptLang as $accept) {
+            foreach ($accept as $a) {
+                $str .= ' '.$a;
+            }
+        }
+        $str .= "\n";
+        $str .= 'Negotated URIs:'."\n";
+        foreach ($this->negotiatedUris as $uri) {
+            $str .= "\t".$uri."\n";
+        }
+        $str .= 'Format Negotated URIs:'."\n";
+        foreach ($this->formatNegotiatedUris as $uri) {
+            $str .= "\t".$uri."\n";
+        }
+        $str .= 'Language Negotated URIs:'."\n";
+        foreach ($this->languageNegotiatedUris as $uri) {
+            $str .= "\t".$uri."\n";
+        }
+        if ($this->ifMatch) {
+            $str .= 'If Match:';
+            foreach ($this->ifMatch as $etag) {
+                $str .= ' '.$etag;
+            }
+            $str .= "\n";
+        }
+        if ($this->ifNoneMatch) {
+            $str .= 'If None Match:';
+            foreach ($this->ifNoneMatch as $etag) {
+                $str .= ' '.$etag;
+            }
+            $str .= "\n";
+        }
+        $str .= 'Loaded Resources:'."\n";
+        foreach ($this->resources as $uri => $resource) {
+            $str .= "\t".$uri."\n";
+            if (isset($resource['namespace']) && $resource['namespace']) $str .= "\t\tNamespace: ".$resource['namespace']."\n";
+            $str .= "\t\tClass: ".$resource['class']."\n";
+            $str .= "\t\tFile: ".$resource['filename'];
+            if (isset($resource['line']) && $resource['line']) $str .= '#'.$resource['line'];
+            $str .= "\n";
+        }
+        return $str;
+    }
+    
+    /**
+     * Instantiate the resource class that matches the request URI the best
+     * @return Resource
+     * @throws ResponseException If the resource does not exist, a 404 exception is thrown
+     */
+    function loadResource() {
+        
+        $uriMatches = array();
+        foreach ($this->resources as $uri => $resource) {
+            
+            preg_match_all('#((?<!\?):[^/]+|{[^0-9][^}]*}|\(.+?\))#', $uri, $params, PREG_PATTERN_ORDER);
+            
+            $uri = $this->baseUri.$uri;
+            if ($uri != '/' && substr($uri, -1, 1) == '/') { // remove trailing slash problem
+                $uri = substr($uri, 0, -1);
+            }
+            $uriRegex = preg_replace('#((?<!\?):[^(/]+|{[^0-9][^}]*})#', '(.+)', $uri);
+            
+            if (preg_match('#^'.$uriRegex.'$#', $this->uri, $matches)) {
+                array_shift($matches);
+                
+                if (isset($params[1])) {
+                    foreach ($params[1] as $index => $param) {
+                        if (isset($matches[$index])) {
+                            if (substr($param, 0, 1) == ':') {
+                                $matches[substr($param, 1)] = $matches[$index];
+                                unset($matches[$index]);
+                            } elseif (substr($param, 0, 1) == '{' && substr($param, -1, 1) == '}') {
+                                $matches[substr($param, 1, -1)] = $matches[$index];
+                                unset($matches[$index]);
+                            }
+                        }
+                    }
+                }
+                
+                $uriMatches[isset($resource['priority']) ? $resource['priority'] : 0] = array(
+                    $uri,
+                    $resource,
+                    $matches
+                );
+                
+            }
+        }
+        krsort($uriMatches);
+        
+        if ($uriMatches) {
+            list($uri, $resource, $parameters) = array_shift($uriMatches);
+            if (!$resource['loaded']) { // autoload
+                if (!class_exists($resource['class'])) {
+                    throw new Exception('Unable to load resource' . $resource['class']);
+                }
+                $resourceDetails = $this->getResourceClassDetails($resource['class']);
+                $resource = $this->resources[$uri] = array(
+                    'namespace' => $resourceDetails['namespaceName'],
+                    'class' => $resourceDetails['className'],
+                    'filename' => $resourceDetails['filename'],
+                    'line' => $resourceDetails['line'],
+                    'priority' => 0,
+                    'loaded' => TRUE
+                );
+            }
+            
+            $this->allowedMethods = array_intersect(array_map('strtoupper', get_class_methods($resource['class'])), $this->HTTPMethods);
+            
+            return new $resource['class']($parameters);
+        }
+        
+        // no resource found, throw response exception
+        throw new ResponseException('A resource matching URI "'.$this->uri.'" was not found', Response::NOTFOUND);
+        
+    }
+    
+    /**
+     * Check if an etag matches the requests if-match header
+     * @param str etag Etag to match
+     * @return bool
+     */
+    function ifMatch($etag) {
+        if (isset($this->ifMatch[0]) && $this->ifMatch[0] == '*') {
+            return TRUE;
+        }
+        return in_array($etag, $this->ifMatch);
+    }
+    
+    /**
+     * Check if an etag matches the requests if-none-match header
+     * @param str etag Etag to match
+     * @return bool
+     */
+    function ifNoneMatch($etag) {
+        if (isset($this->ifMatch[0]) && $this->ifMatch[0] == '*') {
+            return FALSE;
+        }
+        return in_array($etag, $this->ifNoneMatch);
+    }
+    
+    /**
+     * Return the most acceptable of the given formats based on the accept array
+     * @param str[] formats
+     * @param str default The default format if the requested format does not match $formats
+     * @return str
+     */
+    function mostAcceptable($formats, $default = NULL) {
+        foreach (call_user_func_array('array_merge', $this->accept) as $format) {
+            if (in_array($format, $formats)) {
+                return $format;
+            }
+        }
+        return $default;
+    }
+    
+}
+
+/**
+ * Base resource class
+ * @namespace Tonic\Lib
+ */
+class Resource {
+    
+    private $parameters;
+    
+    /**
+     * Resource constructor
+     * @param str[] parameters Parameters passed in from the URL as matched from the URI regex
+     */
+    function  __construct($parameters) {
+        $this->parameters = $parameters;
+    }
+    
+    /**
+     * Convert the object into a string suitable for printing
+     * @return str
+     * @codeCoverageIgnore
+     */
+    function __toString() {
+        $str = get_class($this);
+        foreach ($this->parameters as $name => $value) {
+            $str .= "\n".$name.': '.$value;
+        }
+        return $str;
+    }
+    
+    function secured() 
+    {  
+	try 
+	{
+	    $oauth = new OAuth2(new OAuth2StorageUserCredential());
+	    $token = $oauth->getBearerToken();
+	    $oauth->verifyAccessToken($token);
+	} 
+	catch (OAuth2ServerException $oauthError) 
+	{
+		$oauthError->sendHttpResponse();
+	}
+    }
+    
+    /**
+     * Execute a request on this resource.
+     * @param Request request The request to execute the resource in the context of
+     * @return Response
+     * @throws ResponseException If the HTTP method is not allowed on the resource, a 405 exception is thrown
+     */
+    function exec($request) {
+        
+        if (
+            in_array(strtoupper($request->method), $request->HTTPMethods) &&
+            method_exists($this, $request->method)
+        ) {
+            
+            $method = new ReflectionMethod($this, $request->method);
+            $parameters = array();
+            foreach ($method->getParameters() as $param) {
+                if ($param->name == 'request') {
+                    $parameters[] = $request;
+                } elseif (isset($this->parameters[$param->name])) {
+                    $parameters[] = $this->parameters[$param->name];
+                    unset($this->parameters[$param->name]);
+                } else {
+                    $parameters[] = reset($this->parameters);
+                    array_shift($this->parameters);
+                }
+            }
+            
+            $response = call_user_func_array(
+                array($this, $request->method),
+                $parameters
+            );
+            
+            $responseClassName = class_exists('Tonic\\Response', false) ? 'Tonic\\Response' : 'Response';
+            if (!$response || !($response instanceof $responseClassName)) {
+                throw new Exception('Method '.$request->method.' of '.get_class($this).' did not return a Response object');
+            }
+            
+        } else {
+            
+            // send 405 method not allowed
+            throw new ResponseException(
+                'The HTTP method "'.$request->method.'" is not allowed for the resource "'.$request->uri.'".',
+                Response::METHODNOTALLOWED
+            );
+            
+        }
+        
+        # good for debugging, remove this at some point
+        $response->addHeader('X-Resource', get_class($this));
+        
+        return $response;
+        
+    }
+    
+}
+
+/**
+ * Model the data of the outgoing HTTP response
+ * @namespace Tonic\Lib
+ */
+class Response {
+    
+    /**
+     * HTTP response code constant
+     */
+    const OK = 200,
+          CREATED = 201,
+          NOCONTENT = 204,
+          MOVEDPERMANENTLY = 301,
+          FOUND = 302,
+          SEEOTHER = 303,
+          NOTMODIFIED = 304,
+          TEMPORARYREDIRECT = 307,
+          BADREQUEST = 400,
+          UNAUTHORIZED = 401,
+          FORBIDDEN = 403,
+          NOTFOUND = 404,
+          METHODNOTALLOWED = 405,
+          NOTACCEPTABLE = 406,
+          GONE = 410,
+          LENGTHREQUIRED = 411,
+          PRECONDITIONFAILED = 412,
+          UNSUPPORTEDMEDIATYPE = 415,
+          INTERNALSERVERERROR = 500;
+    
+    /**
+     * The request object generating this response
+     * @var Request
+     */
+    public $request;
+    
+    /**
+     * The HTTP response code to send
+     * @var int
+     */
+    public $code = Response::OK;
+    
+    /**
+     * The HTTP headers to send
+     * @var str[]
+     */
+    public $headers = array();
+    
+    /**
+     * The HTTP response body to send
+     * @var str
+     */
+    public $body;
+    
+    /**
+     * Create a response object.
+     * @param Request request The request object generating this response
+     * @param str uri The URL of the actual resource being used to build the response
+     */
+    function __construct($request, $uri = NULL) {
+        
+        $this->request = $request;
+        
+        if ($uri && $uri != $request->uri) { // add content location header
+            $this->addHeader('Content-Location', $uri);
+            $this->addVary('Accept');
+            $this->addVary('Accept-Language');
+        }
+        $this->addHeader('Allow', implode(', ', $request->allowedMethods));
+        
+    }
+    
+    /**
+     * Convert the object into a string suitable for printing
+     * @return str
+     * @codeCoverageIgnore
+     */
+    function __toString() {
+        $str = 'HTTP/1.1 '.$this->code;
+        foreach ($this->headers as $name => $value) {
+            $str .= "\n".$name.': '.$value;
+        }
+        return $str;
+    }
+    
+    /**
+     * Add a header to the response
+     * @param str header
+     * @param str value
+     */
+    function addHeader($header, $value) {
+        $this->headers[$header] = $value;
+    }
+    
+    /**
+     * Send a cache control header with the response
+     * @param int time Cache length in seconds
+     */
+    function addCacheHeader($time = 86400) {
+        if ($time) {
+            $this->addHeader('Cache-Control', 'max-age='.$time.', must-revalidate');
+        } else {
+            $this->addHeader('Cache-Control', 'no-cache');
+        }
+    }
+    
+    /**
+     * Send an etag with the response
+     * @param str etag Etag value
+     */
+    function addEtag($etag) {
+        $this->addHeader('Etag', '"'.$etag.'"');
+    }
+    
+    function addVary($header) {
+        if (isset($this->headers['Vary'])) {
+            $this->headers['Vary'] .= ', '.$header;
+        } else {
+            $this->addHeader('Vary', $header);
+        }
+    }
+    
+    /**
+     * Output the response
+     * @codeCoverageIgnore
+     */
+    function output() {
+        
+        if (php_sapi_name() != 'cli' && !headers_sent()) {
+            
+            header('HTTP/1.1 '.$this->code);
+            foreach ($this->headers as $header => $value) {
+                header($header.': '.$value);
+            }
+        }
+        
+        if (strtoupper($this->request->method) !== 'HEAD') {
+            echo $this->body;
+        }
+        
+    }
+    
+}
+
+/**
+ * Exception class for HTTP response errors
+ * @namespace Tonic\Lib
+ */
+class ResponseException extends Exception {
+    
+    /**
+     * Generate a default response for this exception
+     * @param Request request
+     * @return Response
+     */
+    function response($request) {
+        $response = new Response($request);
+        $response->code = $this->code;
+        $response->body = $this->message;
+        return $response;
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/docroot/dispatch.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/docroot/dispatch.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/docroot/dispatch.php	(revision 6351)
@@ -0,0 +1,26 @@
+<?php
+
+// load Tonic library
+require_once '../lib/tonic.php';
+
+// load examples
+require_once '../examples/examples.php';
+
+// handle request
+$request = new Request();
+try {
+    $resource = $request->loadResource();
+    $response = $resource->exec($request);
+
+} catch (ResponseException $e) {
+    switch ($e->getCode()) {
+    case Response::UNAUTHORIZED:
+        $response = $e->response($request);
+        $response->addHeader('WWW-Authenticate', 'Basic realm="Tonic"');
+        break;
+    default:
+        $response = $e->response($request);
+    }
+}
+$response->output();
+
Index: sandbox/2.4.1-3/prototype/library/tonic/README.markdown
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/README.markdown	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/README.markdown	(revision 6351)
@@ -0,0 +1,233 @@
+PHP library/framework for building Web apps while respecting the 5 principles
+of RESTful design.
+
+ * Give every "thing" an ID (aka URIs)
+ * Link things together (HATEOAS)
+ * Use standard methods (aka the standard interface)
+ * Resources with multiple representations (aka standard document formats)
+ * Communicate statelessly
+
+[See the Tonic site for more info](http://peej.github.com/tonic/).
+
+
+How it works
+============
+
+Everything is a resource, and a resource is defined as a PHP class. An annotation
+wires a URI (or a collection of URIs) to the resource, and methods that match
+the HTTP methods by name allow interaction with it.
+
+    /**
+     * This class defines an example resource that is wired into the URI /example
+     * @uri /example
+     */
+    class ExampleResource extends Resource { }
+
+The incoming HTTP request is turned into a list of negotiated URIs based on the
+accept request headers which can then be used to pick the best representation
+for the response.
+
+    /**
+     * This class defines an example resource that is wired into the URI /example
+     * @uri /example
+     */
+    class ExampleResource extends Resource {
+        
+        function get($request) {
+            
+            $response = new Response($request);
+            
+            $response->code = Response::OK;
+            $response->body = 'Example response';
+            
+            return $response;
+            
+        }
+      
+    }
+
+
+How to get started
+==================
+
+The best place to get started is to get the hello world example running on your
+system, to do this you will need a web server running PHP5.1+.
+
+Place all of the Tonic files into your PHP include path so that other scripts can
+find it. By default on Windows this will probably be in "c:\php\includes\tonic" or
+on Linux/Unix it will be "/usr/share/php/tonic"
+
+Copy "docroot/dispatch.php" into your servers document root and edit it so that the
+require_once statement paths point to the Tonic library and the examples.
+
+Finally you need to route all incoming requests to dispatch.php. How you do this
+depends on your web server. If you are using Apache, the simplest way is to copy
+the .htaccess file from "docroot/.htaccess" into your Apache document root.
+
+
+Features
+========
+
+
+Request URI
+-----------
+
+The URI that is processed for the request when you create the Tonic Request object
+is gather by default from the REQUEST_URI Apache variable. If you need to gather
+the URI from another $_SERVER variable or somewhere else then you can pass it into
+the Request objects constructor as a configuration option:
+
+    $request = new Request(array(
+        'uri' => $_SERVER['PATH_INFO']
+    ));
+
+
+Base URI
+--------
+
+If you want to put your Tonic dispatcher at a URL that isn't the root of a domain
+then you'll need to let the Request object know so that the @uri annotations ignore
+it:
+
+    $request = new Request(array(
+        'baseUri' => '/some/base/uri'
+    ));
+
+Don't put a trailing slash on the end.
+
+
+URI annotations
+---------------
+
+Resources are attached to their URL by their @uri annotation:
+
+    /**
+     * @uri /example
+     */
+    class ExampleResource extends Resource { }
+
+As well as a straight forward URI string, you can also use a regular expression
+so that a resource is tied to a range of URIs:
+
+    /**
+     * @uri /example/([a-z]+)
+     */
+    class ExampleResource extends Resource {
+        function get($request, $parameter) {
+            ...
+        }
+    }
+
+URL template and Rails route style @uri annotations are also supported:
+
+    /**
+     * @uri /users/{username}
+     */
+    class ExampleResource extends Resource {
+        function get($request, $username) {
+            ...
+        }
+    }
+    
+    /**
+     * @uri /users/:username
+     */
+    class ExampleResource extends Resource {
+        function get($request, $username) {
+            ...
+        }
+    }
+
+It is also possible for multiple resource to match the same URI, so you can
+prioritise which resource should be used by specifying a priority level as part
+of the annotation:
+
+    /**
+     * @uri /example/([a-z]+)
+     */
+    class ExampleResource extends Resource { }
+
+    /**
+     * @uri /example/apple 2
+     */
+    class ExampleResource extends Resource { }
+
+By postfixing the @uri annotation with a number, of all the matching resources,
+the one with the highest postfixed number will be used.
+
+
+Mimetypes
+---------
+
+To handle content negotiation via filename style extensions to URLs as well the
+HTTP Accept header, a mapping between extensions and mimetypes can be provided.
+By default this list contains a number of common mappings, if you need to add one
+or more of your own, pass them into the constructor as an array:
+
+    $request = new Request(array(
+        'mimetypes' => array(
+            'ogv' => 'video/ogg'
+        )
+    ));
+
+
+Mount points
+------------
+
+To make resources more portable, it is possible to "mount" them into your URL-space
+by providing a namespace name to URL-space mapping. Every resource within that
+namespace will in effect have the URL-space prefixed to their @uri annotation.
+
+    $request = new Request(array(
+        'mount' => array(
+            'namespaceName' => '/some/mounted/uri'
+        )
+    ));
+
+Again, don't put a trailing slash on the end, and if you aren't using PHP5.3 and
+namespaces, you can use the @namespace annotation.
+
+
+Response exceptions
+-------------------
+
+The Request object and Resource objects can throw ResponseExceptions when a problem
+occurs that the object does not want to handle and so relinquishes control back
+to the dispatcher.
+
+The ResponseException has its code value set to the HTTP response code of the problem
+and its message set to a human readable reason for throwing the exception. The
+ResponseException::response() method can be used to produce a default Response object
+expressing the exception if required.
+
+The Request object throws a 404 ResponseException when the resource to be loaded
+does not exist.
+
+The Resource object throws a 405 ResponseException when the HTTP method from the
+request is not able to be handled by the resource.
+
+If you don't want to handle a problem within your Resource class, you can throw your
+own ResponseException and handle it in the dispatcher. Look at the auth example for
+an example of how.
+
+
+Autoloading classes
+-------------------
+
+If you've got lots of resource classes and don't fancy including them all in your
+dispatcher, you can use the autoload function to load a resource class for a given
+URL-space.
+
+    $request = new Request(array(
+        'autoload' => array(
+            '/example/[a-z]+' => 'ClassName'
+        )
+    ));
+
+In this example, the class ClassName will be autoloaded via [the standard PHP
+__autoload method](http://php.net/manual/en/language.oop5.autoload.php).
+
+
+
+For more information, read the code. Start with the dispatcher "docroot/dispatch.php"
+and then the examples in the "examples" directory.
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/default.html
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/default.html	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/default.html	(revision 6351)
@@ -0,0 +1,2 @@
+<p>This is the default content for the Smarty resource.</p>
+<p>Today is {""|@time|date_format}</p>
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/shell.html
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/shell.html	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/representations/shell.html	(revision 6351)
@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>{$title|escape}</title>
+    </head>
+    <body>
+        <h1>{$title|escape}</h1>
+        {$body}
+    </body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/smarty.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/smarty.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/smarty/smarty.php	(revision 6351)
@@ -0,0 +1,60 @@
+<?php
+
+@include_once 'smarty/Smarty.class.php';
+
+/**
+ * Smarty template example
+ *
+ * Using Smarty for representation generation
+ *
+ * @namespace Tonic\Examples\Filesystem
+ * @uri /smarty
+ */
+class SmartyResource extends Resource {
+    
+    protected $smarty;
+    
+    function __construct() {
+        
+        $this->smarty = new Smarty();
+        $this->smarty->template_dir = '../examples/smarty/representations';
+        $this->smarty->compile_dir = sys_get_temp_dir();
+        
+    }
+    
+    function get($request) {
+        
+        $response = new Response($request);
+        
+        $this->smarty->assign('title', 'Smarty template');
+        $body = $this->render('default');
+        
+        $etag = md5($body);
+        if ($request->ifNoneMatch($etag)) {
+            
+            $response->code = Response::NOTMODIFIED;
+            
+        } else {
+        
+            $response->code = Response::OK;
+            $response->addHeader('Content-type', 'text/html');
+            $response->body = $body;
+            
+        }
+        
+        return $response;
+        
+    }
+    
+    protected function render($view, $format = 'html', $useShell = TRUE) {
+        
+        if ($format == 'html' && $useShell) {
+            $this->smarty->assign('body', $this->smarty->fetch($view.'.'.$format));
+            return $this->smarty->fetch('shell.'.$format);
+        } else {
+            return $this->smarty->fetch($view.'.'.$format);
+        }
+        
+    }
+    
+}
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/auth/auth.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/auth/auth.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/auth/auth.php	(revision 6351)
@@ -0,0 +1,51 @@
+<?php
+
+/**
+ * Authentication example
+ *
+ * An example authentication resource, the isSecured() method can be used to ensure
+ * that only authorised users can access the resource.
+ *
+ * username: user
+ * password: pass
+ *
+ * @namespace Tonic\Examples\Auth
+ * @uri /auth
+ */
+class AuthResource extends Resource {
+    
+    const USERNAME = 'user';
+    const PASSWORD = 'pass';
+    
+    function isSecured() {
+        
+        if (
+            isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == AuthResource::USERNAME &&
+            isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] == AuthResource::PASSWORD
+        ) {
+            return;
+        }
+        
+        throw new ResponseException('Incorrect username and password', Response::UNAUTHORIZED);
+        
+    }
+    
+    /**
+     * Handle a GET request for this resource
+     * @param Request request
+     * @return Response
+     */
+    function get($request) {
+        
+        $this->isSecured();
+        
+        $response = new Response($request);
+        
+        $response->body = 'You have access to the secret';
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/multirep/multirep.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/multirep/multirep.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/multirep/multirep.php	(revision 6351)
@@ -0,0 +1,99 @@
+<?php
+
+/**
+ * Multiple representation example
+ *
+ * A representation is an output format for a resource. A single resource can have
+ * many output representations that can differ depending on the request data.
+ *
+ * Representations are built up as strings within the Response object and it is
+ * down to the programmer to implement the desired logic for choosing and building
+ * a required representation.
+ *
+ * This example produces three different representations of the resource data
+ * depending on the request accept header information.
+ *
+ * @namespace Tonic\Examples\Multirep
+ * @uri /multirep
+ */
+class MultiRepresentationResource extends Resource {
+    
+    var $data = array(
+        'secret' => 'monkey',
+        'hidden' => 'squirrel'
+    );
+    
+    /**
+     * Handle a GET request for this resource
+     * @param Request request
+     * @return Response
+     */
+    function get($request) {
+        
+        $response = new Response($request);
+        $response->code = Response::OK;
+        
+        // select the most acceptable format of the given types from the request
+        $format = $request->mostAcceptable(array(
+            'json', 'html', 'txt'
+        ));
+        
+        switch ($format) {
+        
+        // obviously it might make more sense to put the HTML in another file
+        // and use some kind of templating system
+        case 'html':
+            $response->addHeader('Content-type', 'text/html');
+            $response->body = '<!DOCTYPE html>';
+            $response->body .= '<html>';
+            $response->body .= '<head>';
+            $response->body .= '<title>HTML Representation</title>';
+            $response->body .= '</head>';
+            $response->body .= '<body>';
+            $response->body .= '<h1>HTML Representation</h1>';
+            $response->body .= '<table border="1">';
+            foreach ($this->data as $field => $value) {
+                $response->body .= '<tr>';
+                $response->body .= '<th>'.htmlspecialchars($field).'</th>';
+                $response->body .= '<td>'.htmlspecialchars($value).'</td>';
+                $response->body .= '</tr>';
+            }
+            $response->body .= '</table>';
+            $response->body .= '<h2>Explicit links to available formats</h2>';
+            $response->body .= '<a href="/multirep.txt">Plain text</a> ';
+            $response->body .= '<a href="/multirep.json">JSON</a> ';
+            $response->body .= '<a href="/multirep.html">HTML</a>';
+            $response->body .= '</body>';
+            $response->body .= '</html>';
+            break;
+        
+        case 'json':
+            $response->addHeader('Content-type', 'application/json');
+            $response->body = json_encode($this->data);
+            break;
+        
+        case 'txt':
+            $response->addHeader('Content-type', 'text/plain');
+            $response->body = "Plain Text Representation\n";
+            $response->body .= "\n";
+            ob_start();
+            var_dump($this->data);
+            $response->body .= ob_get_contents();
+            ob_end_clean();
+            break;
+            
+        // we don't have a suitable format, so do a 406 response instead
+        default:
+            $response->code = Response::NOTACCEPTABLE;
+            $response->addHeader('Content-type', 'text/plain');
+            $response->body = "406 Not Acceptable\n";
+            break;
+            
+        }
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/examples.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/examples.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/examples.php	(revision 6351)
@@ -0,0 +1,60 @@
+<?php
+
+require_once 'helloworld/helloworld.php';
+require_once 'filesystem/filesystem.php';
+require_once 'filesystem/filesystemcollection.php';
+require_once 'smarty/smarty.php';
+require_once 'htmlform/htmlform.php';
+require_once 'auth/auth.php';
+require_once 'multirep/multirep.php';
+
+/**
+ * Examples listing
+ * @namespace Tonic\Examples
+ * @uri /
+ */
+class ExamplesListResource extends Resource {
+    
+    function get($request) {
+        
+        $response = new Response($request);
+        
+        $examples = '';
+        $dirs = glob(dirname(__FILE__).DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
+        if ($dirs) {
+            foreach ($dirs as $path) {
+                $location = basename($path);
+                $readme = $path.DIRECTORY_SEPARATOR.$location.'.php';
+                if (file_exists($readme)) {
+                    preg_match('|/\*\*\s*\*\s*(.+?)\*/|s', file_get_contents($readme), $match);
+                    $comment = preg_replace('|\s*\*\s*(@.+)?|', "\n", $match[1]);
+                    $parts = explode("\n\n", $comment);
+                    $name = array_shift($parts);
+                    $description = join(' ', $parts);
+                } else {
+                    $name = $location;
+                    $description = '';
+                }
+                $examples .= 
+                    '<li>'.
+                    '<h3><a href="'.$location.'">'.$name.'</a></h3>'.
+                    '<p>'.$description.'</p>'.
+                    '</li>';
+            }
+        } else {
+            $examples .= '<li>No examples</li>';
+        }
+        
+        $response->body = <<<END
+<h1>Welcome to Tonic</h1>
+<p>Below is a list of example uses of the Tonic library. View each example to see it in action.</p>
+<h2>Examples</h2>
+END;
+        $response->body .= '<ul>'.$examples.'</ul>';
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/default.html
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/default.html	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/default.html	(revision 6351)
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>Default Document</title>
+    </head>
+    <body>
+        <p>Welcome to the filesystem example.</p>
+        <p>The resource "FilesystemResource" in filesystem.php is wired to any URI starting /filesystem and then maps the remaining part of the URI to the filenames on the filesystem within "examples/filesystem/representations".</p>
+        <p>This page is being read from "examples/filesystem/default.html" on the filesystem as it is the default document
+        for the current URL. <a href="filesystem/default.html">You'll also be able to see it at this URL</a>.</p>
+        <p>The FilesystemResource also allows updating of the files by sending PUT and DELETE requests to their mapped URI.</p>
+        <p>The resource "FilesystemCollection" in filesystemcollection.php 
+        <p><a href="filesystem/collection">View a collection resource for the directory "examples/filesystem/representations/collection"</a>.</p>
+        <p>The FilesystemCollection also allows adding of a file to the collection by sending a POST request to the collection URI.</p>
+    </body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.txt
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.txt	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.txt	(revision 6351)
@@ -0,0 +1,1 @@
+One
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.html
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.html	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/one.html	(revision 6351)
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>One</title>
+    </head>
+    <body>
+        One
+    </body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/two.html
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/two.html	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/representations/collection/two.html	(revision 6351)
@@ -0,0 +1,9 @@
+<!DOCTYPE html>
+<html>
+    <head>
+        <title>Two</title>
+    </head>
+    <body>
+        Two
+    </body>
+</html>
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystemcollection.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystemcollection.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystemcollection.php	(revision 6351)
@@ -0,0 +1,79 @@
+<?php
+
+/**
+ * Collection resource
+ * @namespace Tonic\Examples\Filesystem
+ * @uri /filesystem/collection
+ */
+class FilesystemCollection extends FilesystemResource {
+    
+    /**
+     * Path to the collections files
+     * @var str
+     */
+    var $collection;
+    
+    function __construct($parameters) {
+        parent::__construct($parameters);
+        $this->collection = dirname(__FILE__).'/representations/collection';
+    }
+    
+    /**
+     * Handle a GET request
+     * @param Request request
+     * @return Response
+     */
+    function get($request) {
+        
+        $response = new Response($request);
+        $collection = str_replace('/', DIRECTORY_SEPARATOR, $this->collection);
+        
+        $resourceUris = '';
+        $files = glob($collection.DIRECTORY_SEPARATOR.'*');
+        if ($files) {
+            foreach ($files as $filepath) {
+            	$filepath = str_replace(DIRECTORY_SEPARATOR, '/', $filepath);
+                $resourceUris .= '<li><a href="'.$this->turnFilePathIntoUri($filepath, $request).'">'.basename($filepath).'</a></li>';
+            }
+        } else {
+            $resourceUris .= '<li>Empty collection</li>';
+        }
+        
+        $response->body = '<ul>'.$resourceUris.'</ul>';
+        
+        return $response;
+        
+    }
+    
+    protected function getNextAvailableItemUri() {
+    	$collection = str_replace('/', DIRECTORY_SEPARATOR, $this->collection);
+        $filename = 1;
+        while (file_exists($collection.DIRECTORY_SEPARATOR.$filename)) {
+            $filename++;
+        }
+        return $this->uriStub.substr($this->collection, strlen($this->path)).'/'.$filename;
+    }
+    
+    function post($request) {
+        
+        $response = new Response($request);
+        
+        if ($request->data) {
+            $uri = $this->getNextAvailableItemUri();
+            $filePath = $this->turnUriIntoFilePath($uri, $request);
+            if (file_put_contents($filePath, $request->data)) {
+                $response->code = Response::CREATED;
+                $response->addHeader('Location', $uri);
+            } else {
+                $response->code = Response::INTERNALSERVERERROR;
+            }
+        } else {
+            $response->code = Response::LENGTHREQUIRED;
+        }
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystem.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystem.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/filesystem/filesystem.php	(revision 6351)
@@ -0,0 +1,160 @@
+<?php
+
+/**
+ * Use the filesystem as resource representations
+ *
+ * This example loads files from the filesystem to be used as resource representations
+ * and provides a resource collection to contain them within. It also demonstrates
+ * the ability to add resources to the collection, and update and delete resources
+ * from within the collection.
+ *
+ * @namespace Tonic\Examples\Filesystem
+ * @uri /filesystem(/.*)?
+ */
+class FilesystemResource extends Resource {
+    
+    /**
+     * Path to the files to use
+     * @var str
+     */
+    var $path;
+    
+    /**
+     * URI stub
+     * @var str
+     */
+    var $uriStub = '/filesystem/';
+    
+    /**
+     * The default document to use if the request is for a URI that maps to a directory
+     * @var str
+     */
+    var $defaultDocument = 'default.html';
+    
+    function __construct($parameters) {
+        parent::__construct($parameters);
+        $this->path = dirname(__FILE__).'/representations/';
+    }
+    
+    protected function turnUriIntoFilePath($uri, $request) {
+        return $this->path.DIRECTORY_SEPARATOR.substr($uri, strlen($request->baseUri.$this->uriStub));
+    }
+    
+    protected function turnFilePathIntoUri($path, $request) {
+        return $request->baseUri.$this->uriStub.substr($path, strlen($this->path));
+    }
+    
+    /**
+     * Handle a GET request for this resource by returning the contents of a file matching the request URI
+     * @param Request request
+     * @return Response
+     */
+    function get($request) {
+        
+        // look at all candidate URIs in turn and stop when we find a file that matches one
+        foreach ($request->negotiatedUris as $uri) {
+            
+            // convert URI into filesystem path
+            $filePath = $this->turnUriIntoFilePath($uri, $request);
+            
+            if (substr($filePath, -1, 1) == DIRECTORY_SEPARATOR) { // add a default filename to the path
+                $filePath .= $this->defaultDocument;
+                $uri .= $this->defaultDocument;
+            }
+            
+            if (file_exists($filePath)) { // use this file
+                
+                $response = new Response($request, $uri);
+                
+                // generate etag for the resource based on the files modified date
+                $etag = md5(filemtime($filePath));
+                if ($request->ifNoneMatch($etag)) { // client has matching etag
+                    
+                    $response->code = Response::NOTMODIFIED;
+                    
+                } else {
+                    
+                    $explodedPath = explode('.', $filePath);
+                    $extension = array_pop($explodedPath);
+                    if (isset($request->mimetypes[$extension])) { // add content type header
+                        $response->addHeader('Content-Type', $request->mimetypes[$extension]);
+                    }
+                    
+                    $response->addEtag($etag); // add etag header
+                    
+                    $response->body = file_get_contents($filePath); // set contents
+                    
+                }
+                return $response;
+                
+            }
+            
+        }
+        
+        // nothing found, send 404 response
+        $response = new Response($request);
+        $response->code = Response::NOTFOUND;
+        $response->addHeader('Content-Type', $request->mimetypes['html']);
+        $response->body = '<p>404, nothing found</p>';
+        return $response;
+        
+    }
+    
+    /**
+     * Handle a PUT request for this resource by overwriting the resources contents
+     * @param Request request
+     * @return Response
+     */
+    function put($request) {
+        
+        $response = new Response($request);
+        
+        if ($request->data) {
+            
+            $filePath = $this->turnUriIntoFilePath($request->uri, $request);
+            
+            file_put_contents($filePath, $request->data);
+            
+            $response->code = Response::NOCONTENT;
+            
+        } else {
+            
+            $response->code = Response::LENGTHREQUIRED;
+            
+        }
+        
+        return $response;
+        
+    }
+    
+    /**
+     * Handle a DELETE request for this resource by removing the resources file
+     * @param Request request
+     * @return Response
+     */
+    function delete($request) {
+        
+        $response = new Response($request);
+        
+        $filePath = $this->turnUriIntoFilePath($request->uri, $request);
+        
+        if (file_exists($filePath)) {
+            
+            if (unlink($filePath)) {
+                $response->code = Response::NOCONTENT;
+            } else {
+                $response->code = Response::INTERNALSERVERERROR;
+            }
+            
+            return $response;
+            
+        } else { // nothing found, send 404 response
+            $response->code = Response::NOTFOUND;
+        }
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/htmlform/htmlform.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/htmlform/htmlform.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/htmlform/htmlform.php	(revision 6351)
@@ -0,0 +1,66 @@
+<?php
+
+/**
+ * Display and process a HTML form via a HTTP POST request
+ *
+ * This example outputs a simple HTML form and gathers the POSTed data
+ *
+ * @namespace Tonic\Examples\HTMLForm
+ * @uri /htmlform
+ */
+class HTMLForm extends Resource {
+    
+    /**
+     * Handle a GET request for this resource
+     * @param Request request
+     * @return Response
+     */
+    function get($request, $name) {
+        
+        $response = new Response($request);
+        
+        if ($name) {
+            $welcome = "<p>Hello $name.</p>".
+                "<p>Raw POST data:</p>".
+                "<blockquote>$request->data</blockquote>";
+        } else {
+            $welcome = "<p>Enter your name.</p>";
+        }
+        
+        $response->addHeader('Content-type', 'text/html');
+        $response->body = <<<EOF
+<!DOCTYPE html>
+<html>
+    <body>
+        <form action="htmlform" method="post">
+            <label>Name: <input type="text" name="name"></label>
+            <input type="submit">
+        </form>
+        $welcome
+    </body>
+</html>
+EOF;
+        
+        return $response;
+        
+    }
+    
+    /**
+     * Handle a POST request for this resource
+     * @param Request request
+     * @return Response
+     */
+    function post($request) {
+        
+        if (isset($_POST['name'])) {
+            $name = htmlspecialchars($_POST['name']);
+        } else {
+            $name = '';
+        }
+        
+        return $this->get($request, $name);
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/examples/helloworld/helloworld.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/examples/helloworld/helloworld.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/examples/helloworld/helloworld.php	(revision 6351)
@@ -0,0 +1,52 @@
+<?php
+
+/**
+ * The Hello World of Tonic
+ *
+ * This example outputs a simple hello world message and the details of the
+ * request and response as generated by Tonic. It also demonstrates etags and
+ * "if none match" functionality.
+ *
+ * @namespace Tonic\Examples\Helloworld
+ * @uri /helloworld
+ */
+class HelloWorldResource extends Resource {
+    
+    /**
+     * Handle a GET request for this resource
+     * @param Request request
+     * @return Response
+     */
+    function get($request) {
+        
+        $response = new Response($request);
+        
+        $etag = md5($request->uri);
+        if ($request->ifNoneMatch($etag)) {
+            
+            $response->code = Response::NOTMODIFIED;
+            
+        } else {
+            
+            $response->code = Response::OK;
+            $response->addHeader('Content-type', 'text/plain');
+            $response->addEtag($etag);
+            $response->body =
+                "Hello world!\n".
+                "\n".
+                "This request:\n".
+                "\n".
+                $request->__toString()."\n".
+                "\n".
+                "This response:\n".
+                "\n".
+                $response->__toString();
+            
+        }
+        
+        return $response;
+        
+    }
+    
+}
+
Index: sandbox/2.4.1-3/prototype/library/tonic/features/resource.feature
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/resource.feature	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/resource.feature	(revision 6351)
@@ -0,0 +1,21 @@
+Feature: Resource object
+  In order to execute code
+  As a PHP developer
+  I want a PHP object that represents a HTTP resource
+  
+  Scenario: Load a non existant resource
+    Given the request URI of "/resourcetest"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    Then the response code should be "404"
+    And the response body should be 'Nothing was found for the resource "/resourcetest".'
+  
+  Scenario: Load a resource that exists
+    Given the request URI of "/resourcetest/one"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    Then the response code should be "200"
+    And the response body should be 'test'
+
Index: sandbox/2.4.1-3/prototype/library/tonic/features/request.feature
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/request.feature	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/request.feature	(revision 6351)
@@ -0,0 +1,198 @@
+Feature: HTTP request object
+  In order to handle a request
+  As a PHP developer
+  I want a PHP object that represents the state of the incoming HTTP request
+  
+  Scenario: Have access to the request URI
+    Given the request URI of "/something/otherthing"
+    When I create a request object
+    Then I should see a request URI of "/something/otherthing"
+    
+  Scenario: Have access to the HTTP request method
+    Given the request method of "GET"
+    When I create a request object
+    Then I should see a request method of "GET"
+    
+  Scenario: Receive the request querystring
+    Given the request URI of "/something/otherthing"
+    And the request method of "GET"
+    And the querystring is "?foo=bar"
+    When I create a request object
+    Then I should see a querystring of "foo=bar"
+    
+  Scenario: Have access to the HTTP request method
+    Given the request method of "post"
+    And the request data of "some data"
+    When I create a request object
+    Then I should see a request method of "POST"
+    And I should see the request data "some data"
+    
+  Scenario: Have access to the HTTP request data
+    Given the request method of "PUT"
+    And the request data of "some data"
+    When I create a request object
+    Then I should see a request method of "PUT"
+    And I should see the request data "some data"
+    
+  Scenario: Have bare request URI content negotiated correctly
+    Given the request URI of "/requesttest/one/two"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two"
+    
+  Scenario: Have extension request URI content negotiated correctly
+    Given the request URI of "/requesttest/one/two.html"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.html,/requesttest/one/two"
+    
+  Scenario: Have bare request URI with accept header content negotiated correctly
+    Given the request URI of "/requesttest/one/two"
+    And the accept header of "image/png;q=0.5,text/html"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two"
+    
+  Scenario: Have extension request URI with accept header content negotiated correctly
+    Given the request URI of "/requesttest/one/two.html"
+    And the accept header of "image/png;q=0.5,text/html"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.html,/requesttest/one/two"
+    
+  Scenario: Have bare request URI with language accept header content negotiated correctly
+    Given the request URI of "/requesttest/one/two"
+    And the language accept header of "fr;q=0.5,en"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    
+  Scenario: Have extension request URI with language accept header content negotiated correctly
+    Given the request URI of "/requesttest/one/two.html"
+    And the language accept header of "fr;q=0.5,en"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html.en,/requesttest/one/two.html.fr,/requesttest/one/two.html,/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    
+  Scenario: Have bare request URI with accept and language header content negotiated correctly
+    Given the request URI of "/requesttest/one/two"
+    And the accept header of "image/png;q=0.5,text/html"
+    And the language accept header of "fr;q=0.5,en"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html.en,/requesttest/one/two.html.fr,/requesttest/one/two.html,/requesttest/one/two.png.en,/requesttest/one/two.png.fr,/requesttest/one/two.png,/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    
+  Scenario: Have extension request URI with accept and language header content negotiated correctly
+    Given the request URI of "/requesttest/one/two.html"
+    And the accept header of "image/png;q=0.5,text/html"
+    And the language accept header of "fr;q=0.5,en"
+    When I create a request object
+    Then I should see a request URI of "/requesttest/one/two"
+    And I should see a negotiated URI of "/requesttest/one/two.html.en,/requesttest/one/two.html.fr,/requesttest/one/two.html,/requesttest/one/two.png.html,/requesttest/one/two.png.en,/requesttest/one/two.png.fr,/requesttest/one/two.png,/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    And I should see a format negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.png,/requesttest/one/two"
+    And I should see a language negotiated URI of "/requesttest/one/two.html,/requesttest/one/two.en,/requesttest/one/two.fr,/requesttest/one/two"
+    
+  Scenario: Have if match header
+    Given an if match header of '123123'
+    When I create a request object
+    Then I should see an if match header of "123123"
+    And if match should match "123123"
+    
+  Scenario: Have if match header in quotes
+    Given an if match header of '"123123"'
+    When I create a request object
+    Then I should see an if match header of "123123"
+    And if match should match "123123"
+    
+  Scenario: Have multiple if match headers in quotes
+    Given an if match header of '"123123","456456"'
+    When I create a request object
+    Then I should see an if match header of "123123,456456"
+    And if match should match "123123"
+    And if match should match "456456"
+    
+  Scenario: Have star if match header
+    Given an if match header of '*'
+    When I create a request object
+    Then I should see an if match header of "*"
+    And if match should match "123123"
+    And if match should match "123456"
+    
+  Scenario: Have if none match header
+    Given an if none match header of '123123'
+    When I create a request object
+    Then I should see an if none match header of "123123"
+    And if none match should match "123123"
+    
+  Scenario: Have multiple if none match headers in quotes
+    Given an if none match header of '"123123","456456"'
+    When I create a request object
+    Then I should see an if none match header of "123123,456456"
+    And if none match should match "123123"
+    And if none match should match "456456"
+  
+  Scenario: Have star if none match header
+    Given an if none match header of '*'
+    When I create a request object
+    Then I should see an if none match header of "*"
+    And if none match should not match "123123"
+    And if none match should not match "123456"
+    
+  Scenario: Load a non-existent resource
+    Given the request URI of "/three"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "NoResource"
+    
+  Scenario: Load a resource
+    Given the request URI of "/requesttest/one"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "NewResource"
+    
+  Scenario: Load a child resource
+    Given the request URI of "/requesttest/one/two"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "ChildResource"
+    
+  Scenario: Load a resource with a regex match URI
+    Given the request URI of "/requesttest/three/something/four"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "NewResource"
+  
+  Scenario: Load a non-existent resource with a new 404 resource class
+    Given the request URI of "/three"
+    And a 404 resource classname of "NewNoResource"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "NewNoResource"
+  
+  Scenario: Resource data loading
+    Given the request URI of "/requesttest/one/two"
+    When I create a request object
+    Then I should see resource "namespace" metadata of "Tonic/Tests"
+    And I should see resource "class" metadata of "ChildResource"
+    And I should see resource "priority" metadata of "0"
+    
+  Scenario: Mounting in a namespace to a URI
+    Given the request URI of "/foo/bar/requesttest/one"
+    And a mounting of "Tonic/Tests" to "/foo/bar"
+    When I create a request object
+    And I load the resource
+    Then I should have a response of type "NewResource"
Index: sandbox/2.4.1-3/prototype/library/tonic/features/response.feature
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/response.feature	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/response.feature	(revision 6351)
@@ -0,0 +1,58 @@
+Feature: Response object
+  In order to output a response representation
+  As a PHP developer
+  I want a PHP object that represents a HTTP response
+  
+  Scenario: Output should be gzipped if the client supports it
+    Given the request URI of "/resourcetest/one"
+    And an accept encoding of "gzip"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I process content encoding
+    Then the response header "Content-Encoding" should contain 'gzip'
+    And the response body should be gzipped and be "test"
+
+  Scenario: Output should be deflated if the client supports it
+    Given the request URI of "/resourcetest/one"
+    And an accept encoding of "deflate"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I process content encoding
+    Then the response header "Content-Encoding" should contain 'deflate'
+    And the response body should be deflated and be "test"
+
+  Scenario: Output should be compress if the client supports it
+    Given the request URI of "/resourcetest/one"
+    And an accept encoding of "compress"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I process content encoding
+    Then the response header "Content-Encoding" should contain 'compress'
+    And the response body should be compressed and be "test"
+
+  Scenario: Responses should have a default cache header
+    Given the request URI of "/resourcetest/one"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I add a cache header of ""
+    Then the response header "Cache-Control" should contain 'max-age=86400, must-revalidate'
+
+  Scenario: Responses told not to cache should send a zero cache header
+    Given the request URI of "/resourcetest/one"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I add a cache header of "0"
+    Then the response header "Cache-Control" should contain 'no-cache'
+
+  Scenario: Responses given an etag should send an etag response header
+    Given the request URI of "/resourcetest/one"
+    When I create a request object
+    And I load the resource
+    And execute the request
+    And I add an etag header of "123123"
+    Then the response header "Etag" should contain '"123123"'
Index: sandbox/2.4.1-3/prototype/library/tonic/features/support/env.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/support/env.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/support/env.php	(revision 6351)
@@ -0,0 +1,63 @@
+<?php
+
+require_once __DIR__.'/../../lib/tonic.php';
+
+$world->config = array();
+
+/* Test resource definitions */
+
+if (!class_exists('NewResource')) {
+    
+    /**
+     * @namespace Tonic\Tests
+     * @uri /requesttest/one
+     * @uri /requesttest/three/.+/four 12
+     */
+    class NewResource extends Resource {
+    
+    }
+
+}
+
+if (!class_exists('ChildResource')) {
+
+    /**
+     * @namespace Tonic\Tests
+     * @uri /requesttest/one/two
+     */
+    class ChildResource extends NewResource {
+    
+    }
+
+}
+
+if (!class_exists('NewNoResource')) {
+
+    /**
+     * @namespace Tonic\Tests
+     */
+    class NewNoResource extends NoResource {
+    
+    }
+
+}
+
+if (!class_exists('TestResource')) {
+    
+    /**
+     * @namespace Tonic\Tests
+     * @uri /resourcetest/one
+     */
+    class TestResource extends Resource {
+        
+        function get($request) {
+            
+            $response = new Response($request);
+            $response->body = 'test';
+            return $response;
+            
+        }
+        
+    }
+
+}
Index: sandbox/2.4.1-3/prototype/library/tonic/features/steps/response.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/steps/response.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/steps/response.php	(revision 6351)
@@ -0,0 +1,41 @@
+<?php
+
+$steps->Given('/^an accept encoding of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['acceptEncoding'] = $arg1;
+});
+
+$steps->When('/^I process content encoding$/', function($world) {
+    $world->response->doContentEncoding();
+});
+
+$steps->Then('/^the response header "([^"]*)" should contain \'([^\']*)\'$/', function($world, $arg1, $arg2) {
+    if ($world->response->headers[$arg1] != $arg2) throw new Exception;
+});
+
+$steps->Then('/^the response body should be ([^ ]*) and be "([^"]*)"$/', function($world, $arg1, $arg2) {
+    switch ($arg1) {
+    case 'gzipped':
+        var_dump($world->response->body, $arg2, gzencode($arg2));
+        if ($world->response->body != gzencode($arg2)) throw new Exception;
+        break;
+    case 'deflated':
+        if ($world->response->body != gzdeflate($arg2)) throw new Exception;
+        break;
+    case 'compressed':
+        if ($world->response->body != gzcompress($arg2)) throw new Exception;
+        break;
+    }
+});
+
+$steps->Then('/^I add a cache header of "([^"]*)"$/', function($world, $arg1) {
+    if ($arg1 == '') {
+        $world->response->addCacheHeader();
+    } else {
+        $world->response->addCacheHeader($arg1);
+    }
+});
+
+$steps->Then('/^I add an etag header of "([^"]*)"$/', function($world, $arg1) {
+    $world->response->addEtag($arg1);
+});
+
Index: sandbox/2.4.1-3/prototype/library/tonic/features/steps/resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/steps/resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/steps/resource.php	(revision 6351)
@@ -0,0 +1,14 @@
+<?php
+
+$steps->When('/^execute the request$/', function($world) {
+    $world->response = $world->resource->exec($world->request);
+});
+
+$steps->Then('/^the response code should be "([^"]*)"$/', function($world, $arg1) {
+    if ($world->response->code != $arg1) throw new Exception;
+});
+
+$steps->Then('/^the response body should be \'([^\']*)\'$/', function($world, $arg1) {
+    if ($world->response->body != $arg1) throw new Exception;
+});
+
Index: sandbox/2.4.1-3/prototype/library/tonic/features/steps/request.php
===================================================================
--- sandbox/2.4.1-3/prototype/library/tonic/features/steps/request.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/library/tonic/features/steps/request.php	(revision 6351)
@@ -0,0 +1,106 @@
+<?php
+
+$steps->Given('/^the request URI of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['uri'] = $arg1;
+});
+
+$steps->Given('/^the request method of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['method'] = $arg1;
+});
+
+$steps->Given('/^the request data of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['data'] = $arg1;
+});
+
+$steps->Given('/^the accept header of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['accept'] = $arg1;
+});
+
+$steps->Given('/^the language accept header of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['acceptLang'] = $arg1;
+});
+
+$steps->Given('/^an if match header of \'([^\']*)\'$/', function($world, $arg1) {
+    $world->config['ifMatch'] = $arg1;
+});
+
+$steps->Given('/^an if none match header of \'([^\']*)\'$/', function($world, $arg1) {
+    $world->config['ifNoneMatch'] = $arg1;
+});
+
+$steps->Given('/^a 404 resource classname of "([^"]*)"$/', function($world, $arg1) {
+    $world->config['404'] = $arg1;
+});
+
+$steps->Given('/^a mounting of "([^"]*)" to "([^"]*)"$/', function($world, $arg1, $arg2) {
+    $world->config['mount'][$arg1] = $arg2;
+});
+
+$steps->Given('/^the querystring is "([^"]*)"$/', function($world, $arg1) {
+    $_SERVER['QUERY_STRING'] = $arg1;
+});
+
+$steps->When('/^I create a request object$/', function($world) {
+    $world->request = new Request($world->config);
+});
+
+$steps->When('/^I load the resource$/', function($world) {
+    $world->resource = $world->request->loadResource();
+});
+
+$steps->Then('/^I should see a request URI of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->uri != $arg1) throw new Exception;
+});
+
+$steps->Then('/^I should see a request method of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->method != $arg1) throw new Exception;
+});
+
+$steps->Then('/^I should see the request data "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->data != $arg1) throw new Exception;
+});
+
+$steps->Then('/^I should see a negotiated URI of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->negotiatedUris != explode(',', $arg1)) throw new Exception;
+});
+
+$steps->Then('/^I should see a format negotiated URI of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->formatNegotiatedUris != explode(',', $arg1)) throw new Exception;
+});
+
+$steps->Then('/^I should see a language negotiated URI of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->languageNegotiatedUris != explode(',', $arg1)) throw new Exception;
+});
+
+$steps->Then('/^I should have a response of type "([^"]*)"$/', function($world, $arg1) {
+    if (get_class($world->resource) != $arg1) throw new Exception;
+});
+
+$steps->Then('/^I should see an if match header of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->ifMatch != explode(',', $arg1)) throw new Exception;
+});
+
+$steps->Then('/^if match should match "([^"]*)"$/', function($world, $arg1) {
+    if (!$world->request->ifMatch($arg1)) throw new Exception;
+});
+
+$steps->Then('/^I should see an if none match header of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->ifNoneMatch != explode(',', $arg1)) throw new Exception;
+});
+
+$steps->Then('/^if none match should match "([^"]*)"$/', function($world, $arg1) {
+    if (!$world->request->ifNoneMatch($arg1)) throw new Exception;
+});
+
+$steps->Then('/^if none match should not match "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->ifNoneMatch($arg1)) throw new Exception;
+});
+
+$steps->Then('/^I should see resource "([^"]*)" metadata of "([^"]*)"$/', function($world, $arg1, $arg2) {
+    if ($world->request->resources[$world->request->uri][$arg1] != $arg2) throw new Exception;
+});
+
+$steps->Then('/^I should see a querystring of "([^"]*)"$/', function($world, $arg1) {
+    if ($world->request->data != '?'.$arg1) throw new Exception("$arg1 does not equal {$world->request->data}");
+});
+
Index: sandbox/2.4.1-3/prototype/config/Tonic.srv
===================================================================
--- sandbox/2.4.1-3/prototype/config/Tonic.srv	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/Tonic.srv	(revision 6351)
@@ -0,0 +1,27 @@
+
+[/maillast]
+MailLastResource = /mail/MailLastResource.php
+
+[/calendarlast]
+CalendarLastResource = /calendar/CalendarLastResource.php
+
+[/newslast]
+NewsLastResource = /news/NewsLastResource.php
+
+[/dynamiccontacts]
+DynamicContactsResource = /contact/DynamicContactsResource.php
+
+[/oi]
+DynamicContactDeleteResource = /contact/DynamicContactDeleteResource.php
+
+[/dynamiccontacts/:id]
+DynamicContactResource = /contact/DynamicContactResource.php
+
+[/token]
+TokenResource = /oauth/TokenResource.php
+
+[/usersldap]
+UsersResource = /user/UsersResource.php
+
+[/userldap/:id]
+UserResource = /user/UserResource.php
Index: sandbox/2.4.1-3/prototype/config/oauthCode.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/oauthCode.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/oauthCode.ini	(revision 6351)
@@ -0,0 +1,10 @@
+service = PostgreSQL
+PostgreSQL.concept = auth_codes
+
+[PostgreSQL.mapping]
+redirect_uri = redirect_uri
+scope = scope
+expires = expires
+code = code
+client_id = client_id
+user_id = user_id
Index: sandbox/2.4.1-3/prototype/config/oauthToken.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/oauthToken.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/oauthToken.ini	(revision 6351)
@@ -0,0 +1,10 @@
+service = PostgreSQL
+PostgreSQL.concept = access_tokens
+
+[PostgreSQL.mapping]
+oauth_token = oauth_token
+client_id = client_id
+user_id = user_id
+expires = expires
+scope = scope
+refresh_token = refresh_token
Index: sandbox/2.4.1-3/prototype/config/OpenLDAP.srv
===================================================================
--- sandbox/2.4.1-3/prototype/config/OpenLDAP.srv	(revision 6173)
+++ sandbox/2.4.1-3/prototype/config/OpenLDAP.srv	(revision 6351)
@@ -4,6 +4,7 @@
 idAtribute = "uidNumber"
 host = 127.0.0.1
-context = "LDAP_DN"
-; Caso o LDAP requisite autenticacao, configure os parametros a seguir
-;user = 
-;password = 
+
+context = "dc=prognus"
+user = "cn=admin,dc=prognus"
+password = "prognus"
+
Index: sandbox/2.4.1-3/prototype/config/PostgreSQL.srv
===================================================================
--- sandbox/2.4.1-3/prototype/config/PostgreSQL.srv	(revision 6081)
+++ sandbox/2.4.1-3/prototype/config/PostgreSQL.srv	(revision 6351)
@@ -7,6 +7,6 @@
 ;host = 127.0.0.1
 port = 5432
-dbname = expresso
-user = postgres
+dbname = expressoDFDTezza
+user = expressodev
 ; Caso o usuario tenha senha...
 ;password=
Index: sandbox/2.4.1-3/prototype/config/oauthRefreshToken.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/oauthRefreshToken.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/oauthRefreshToken.ini	(revision 6351)
@@ -0,0 +1,10 @@
+service = PostgreSQL
+PostgreSQL.concept = refresh_tokens
+
+[PostgreSQL.mapping]
+refresh_token = refresh_token
+client_id = client_id
+user_id = user_id
+expires = expires
+scope = scope
+refresh_token = refresh_token
Index: sandbox/2.4.1-3/prototype/config/dynamicContact.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/dynamicContact.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/dynamicContact.ini	(revision 6351)
@@ -0,0 +1,10 @@
+service = PostgreSQL
+PostgreSQL.concept = expressomail_dynamic_contact
+
+
+[PostgreSQL.mapping]
+id = id
+name = name
+mail = mail
+owner = owner
+timestamp = timestamp
Index: sandbox/2.4.1-3/prototype/config/Cyrus.srv
===================================================================
--- sandbox/2.4.1-3/prototype/config/Cyrus.srv	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/Cyrus.srv	(revision 6351)
@@ -0,0 +1,4 @@
+[config]
+host = 127.0.0.1
+port = 143
+tlsEncryption = true
Index: sandbox/2.4.1-3/prototype/config/user.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/user.ini	(revision 5804)
+++ sandbox/2.4.1-3/prototype/config/user.ini	(revision 6351)
Index: sandbox/2.4.1-3/prototype/config/oauthCliente.ini
===================================================================
--- sandbox/2.4.1-3/prototype/config/oauthCliente.ini	(revision 6351)
+++ sandbox/2.4.1-3/prototype/config/oauthCliente.ini	(revision 6351)
@@ -0,0 +1,7 @@
+service = PostgreSQL
+PostgreSQL.concept = clients
+
+[PostgreSQL.mapping]
+client_id = client_id
+client_secret = client_secret
+redirect_uri = redirect_uri
Index: sandbox/2.4.1-3/prototype/modules/home/css/home.css
===================================================================
--- sandbox/2.4.1-3/prototype/modules/home/css/home.css	(revision 6351)
+++ sandbox/2.4.1-3/prototype/modules/home/css/home.css	(revision 6351)
@@ -0,0 +1,123 @@
+.portlets dl{ float:left; margin: 10px 5px; }
+
+.portlets .event-list dt,
+.portlets .mail-list dt,
+.portlets .news-list dt { display:none; }
+
+.portlets .event-list dd,
+.portlets .mail-list dd,
+.portlets .news-list dd { 
+	min-height: 55px; 
+	height: 55px; 
+	width: 400px; 
+	margin:0 0 5px 0; 
+	padding:8px; 
+	overflow:hidden;
+	background-color:#DDD; 
+	border-radius:8px; 
+	-moz-border-radius:8px; 
+	-webkit-border-radius:4px; 
+}
+
+.portlets .event-list .duration { color:#FF7777; font-size:9px;}
+.portlets .event-list .duration:before{ color:#FF7777; content:"[ "}
+.portlets .event-list .duration:after { color:#FF7777; content:" ]"}
+.portlets .event-list .duration .start:after { color:#FF7777; content:" - "}
+
+.portlets .event-list .title,
+.portlets .news-list .title,
+.portlets .mail-list .title
+{ color:#555; font-weight:bold; font-size:13px;}
+
+.portlets .event-list .description,
+.portlets .news-list .description,
+.portlets .mail-list .description
+{ color:#888;}
+
+.portlets .event-list .month {
+    color: #DDDDDD;
+    display: block;
+    font-size: 11px;
+    line-height: 11px;
+    margin-left: -3px;
+    padding-top: 5px;
+    text-align: center;
+    text-transform: uppercase;
+}
+.portlets .event-list .day {
+    color: #999999;
+    display: block;
+    font-size: 18px;
+    line-height: 18px;
+    margin-left: -3px;
+    padding-top: 8px;
+    text-align: center;
+    text-transform: uppercase;
+}
+.portlets .event-list .date {
+    background-attachment: scroll;
+    background-color: transparent;
+    background-image: url("../img/date-bg-red.png");
+    background-position: 0 0;
+    background-repeat: no-repeat;
+    float: left;
+    height: 49px;
+    width: 45px;
+	margin-right: 10px;
+}
+
+/* ----------- */
+
+.portlets .news-list dd { 
+	min-height: 55px; 
+	height: 130px; 
+	width: 400px; 
+}
+
+.portlets .news-list .date { 
+    background-attachment: scroll;
+    background-color: transparent;
+    background-image: url("../img/boletim.png");
+    background-position: 0 0;
+    background-repeat: no-repeat;
+    float: left;
+    height: 125px;
+    width: 110px;
+	margin-right: 10px;
+}
+.portlets .news-list .date .full{ 
+	font-size:8px;
+	color:#1E5AC6;
+	display:block;
+	margin:10px 0 0 15px;	
+}
+.portlets .news-list .duration {color:#FF7777; font-size:9px;}
+
+/* ----------- */
+
+.portlets .mail-list .date { 
+    background-attachment: scroll;
+    background-color: transparent;
+    background-image: url("../img/mail_unread.png");
+    background-position: 0 0;
+    background-repeat: no-repeat;
+    float: left;
+    height: 72px;
+    width: 72px;
+	margin-right: 10px;
+}
+.portlets .mail-list .date .hasCountdown {
+    color: #1E5AC6;
+    display: block;
+    font-size: 8px;
+    margin-bottom: 0;
+    margin-left: 0;
+    margin-right: 0;
+    margin-top: 44px;
+    overflow: hidden;
+    text-align: center;
+    width: 72px;
+}
+.portlets .mail-list .duration {color:#FF7777; font-size:9px;}
+.portlets .mail-list .from:before {content: "De: "; color:#555; font-size:10px; font-weight:normal;}
+.portlets .mail-list .from { color:#555; font-weight:bold; font-size:11px;}
Index: sandbox/2.4.1-3/prototype/modules/home/js/home.js
===================================================================
--- sandbox/2.4.1-3/prototype/modules/home/js/home.js	(revision 6351)
+++ sandbox/2.4.1-3/prototype/modules/home/js/home.js	(revision 6351)
@@ -0,0 +1,30 @@
+$(document).ready(function() {
+	$("#divAppboxHeader").css({fontStyle:'normal'});
+
+//	var carlendarResource = DataLayer.read("/calendarlast");
+//	var tmplCalendar = DataLayer.render("prototype/modules/home/templates/calendarlast.ejs", {resource: carlendarResource});
+
+
+	var mailResource = DataLayer.read("/maillast");
+	var tmplMail = DataLayer.render("prototype/modules/home/templates/maillast.ejs", {resource: mailResource});
+
+//	var newsResource = DataLayer.read("/newslast");
+//	var tmplNews = DataLayer.render("prototype/modules/home/templates/newslast.ejs", {resource: newsResource});
+
+
+//	$(".portlets").append(tmplCalendar);
+	$(".portlets").append(tmplMail);
+//	$(".portlets").append(tmplNews);
+
+
+	jQuery('.date .timable').each(function (i) {
+	    jQuery(this).countdown({
+		    since: new Date(parseInt($(this).text()) * 1000), 
+		    significant: 1,
+		    layout: 'h&aacute; {d<}{dn} {dl} {d>}{h<}{hn} {hl} {h>}{m<}{mn} {ml} {m>}{s<}{sn} {sl}{s>}', 
+		    description: ' atr&aacute;s'
+	    });					
+	});
+
+
+});
Index: sandbox/2.4.1-3/prototype/modules/home/templates/newslast.ejs
===================================================================
--- sandbox/2.4.1-3/prototype/modules/home/templates/newslast.ejs	(revision 6351)
+++ sandbox/2.4.1-3/prototype/modules/home/templates/newslast.ejs	(revision 6351)
@@ -0,0 +1,20 @@
+<dl class="news-list" title="Últimas notícias"> 
+    <%if(data.resource && data.resource.length){
+	for(var i = 0; i < data.resource.length; i++){
+	var date = new Date(parseInt(data.resource[i].startTime+'000'));%>
+	    <dt><%=data.resource[i].subject %></dt>
+	    <dd>
+		<div class="date">
+		    <span class="full"><%= date.toString("ddd, d &#100;e MMMM") %></span>
+		</div>
+		<div class="duration">
+			<span class="start"><%= date.toString("ddd, d &#100;e MMMM &#100;e yyyy") %></span>
+		</div>
+		<div class="title"><%=data.resource[i].subject %></div>
+		<div class="description"><%=data.resource[i].content%></div>
+	    </dd>
+	<%}%>
+	<%}else{%>
+	    <dt>Sem resultados</dt>
+	<%}%>   
+</dl>
Index: sandbox/2.4.1-3/prototype/modules/home/templates/maillast.ejs
===================================================================
--- sandbox/2.4.1-3/prototype/modules/home/templates/maillast.ejs	(revision 6351)
+++ sandbox/2.4.1-3/prototype/modules/home/templates/maillast.ejs	(revision 6351)
@@ -0,0 +1,16 @@
+<dl class="mail-list" title="Últimas e-mails">
+    <%if(data.resource && data.resource.length){
+	for(var i = 0; i < data.resource.length; i++){%>
+	    <dt><%=data.resource[i].subject %></dt>
+	    <dd>
+		<div class="date">
+		    <span class="timestamp timable"><%=data.resource[i].date%></span>
+		</div>
+		<div class="from" title="<%=data.resource[i].mail%>"><%=data.resource[i].from.name%></div>
+		<div class="description"><%=data.resource[i].subject%></div>
+	    </dd>
+	<%}%>
+	<%}else{%>
+	    <dt>Sem resultados</dt>
+	<%}%>    
+</dl> 
Index: sandbox/2.4.1-3/prototype/modules/home/templates/calendarlast.ejs
===================================================================
--- sandbox/2.4.1-3/prototype/modules/home/templates/calendarlast.ejs	(revision 6351)
+++ sandbox/2.4.1-3/prototype/modules/home/templates/calendarlast.ejs	(revision 6351)
@@ -0,0 +1,26 @@
+<dl class="event-list" title="Últimas eventos">
+    <%if(data.resource && data.resource.length){
+	for(var i = 0; i < data.resource.length; i++){
+	var date = new Date(parseInt(data.resource[i].startTime));%>
+	    <dt><%=data.resource[i].summary %></dt>
+	    <dd>
+		<div class="date">
+		    <span class="month"><%= date.toString("MMM") %></span>
+		    <span class="day"><%= date.toString("d") %></span>
+		</div>
+		<div class="duration">
+		    <%if(parseInt(data.resource[i].allDay)){%>
+			<span class="allDay">Durante o dia todo</span>
+		    <%}else{%>
+			<span class="start"><%= date.toString("HH:mm") %></span>
+			<span class="end"><%= new Date(parseInt(data.resource[i].endTime)).toString("HH:mm") %></span>
+		    <%}%>
+		</div>
+		<div class="title"><%=data.resource[i].summary %></div>
+		<div class="description"><%=data.resource[i].description%></div>
+	    </dd>
+	<%}%>
+	<%}else{%>
+	    <dt>Sem resultados</dt>
+	<%}%>    
+</dl>
Index: sandbox/2.4.1-3/prototype/api/datalayer.js
===================================================================
--- sandbox/2.4.1-3/prototype/api/datalayer.js	(revision 6008)
+++ sandbox/2.4.1-3/prototype/api/datalayer.js	(revision 6351)
@@ -1,3 +1,3 @@
-internalUrl = /^([A-z0-9-_]+)(:[A-z0-9-_]+)?$/;
+   internalUrl = /^([A-z0-9-_]+)(:[A-z0-9-_]+)?$/;
 internalUri = /^([a-zA-Z0-9-_]+)\(([a-zA-Z0-9-_]+)\):\/\/(.*)|([a-zA-Z0-9-_]+):\/\/(.*)$/;
 isGeneratedId = /^\d+\(javascript\)$/;
@@ -213,4 +213,15 @@
 
 		},
+	      'error': function( dt, textStatus, jqXHR ){
+
+		    if( callback )
+		    {
+			fired = true;
+			result = callback( $.parseJSON(dt.responseText), textStatus, jqXHR );
+		    }
+		    else
+			result = $.parseJSON(dt.responseText);
+
+		},
 	      'complete': function( jqXHR, textStatus ){
 
@@ -234,4 +245,77 @@
       
 	  return( result );
+    },
+    
+    /**
+    * This method is used to read resources from the server.
+    * 
+    * @param uri Uri of the resource that gonna be readed.
+    * @param callback A function that is called when the resource is loaded successfully. When the parameter is ignored the request is made synchrounsly.
+    * @param accept The attribute accept that is used to ask the target format to the server
+    * @return The target resource when the callback is ommitted ( made it synchronous )
+    */
+
+    read: function( uri, data, callback, accept ){
+	//return this.send( this.dispatchPath + 'rest' + uri, [ 'get', accept || 'json' ], false, callback );
+	//http://expressodev.prognus.com.br/cristiano/expresso-api/rest/maillast
+	return this.send( ('rest' + uri), [ 'get', accept || 'json' ], data, callback, !!!callback, 
+	{'beforeSend' : function (xhr){ 
+	    xhr.setRequestHeader('Authorization', "OAUTH Bearer " + DataLayer.me.token)} 
+	});
+      
+    },
+
+    /**
+    * This method is used to create resources from the server.
+    * 
+    * @param uri Uri of the resource that gonna be readed.
+    * @param callback A function that is called when the resource is created on the server successfully. When the parameter is ignored the request is made synchrounsly.
+    * @param accept The attribute accept that is used to ask the target format to the server.
+    * @return The result response of the create from the server when the callback is ommitted ( made it synchronous )
+    */
+    
+    create: function( uri, data, callback, accept ){
+      
+	return this.send( 'rest' + uri, [ 'post', accept || 'json' ], data, callback, !!!callback, 
+	{'beforeSend' : function (xhr){ 
+	    xhr.setRequestHeader('Authorization', "OAUTH Bearer " + DataLayer.me.token)} 
+	});
+      
+    },
+
+    /**
+    * This method is used to update resources from the server.
+    * 
+    * @param uri Uri of the resource that gonna be readed.
+    * @param callback A function that is called when the resource is update on the server successfully. When the parameter is ignored the request is made synchrounsly.
+    * @param accept The attribute accept that is used to ask the target format to the server
+    * @return The result response of the update from the server when the callback is ommitted ( made it synchronous )
+    */
+
+    update: function( uri, data, callback, accept ){
+      
+	return this.send( 'rest' + uri, [ 'put', accept || 'json' ], data, callback, !!!callback, 
+	{'beforeSend' : function (xhr){ 
+	    xhr.setRequestHeader('Authorization', "OAUTH Bearer " + DataLayer.me.token)} 
+	});
+      
+    },
+
+    /**
+    * This method is used to delete resources from the server.
+    * 
+    * @param uri Uri of the resource that gonna be readed.
+    * @param callback A function that is called when the resource is deleted successfully in the server. When the parameter is ignored the request is made synchrounsly.
+    * @param accept The attribute accept that is used to ask the target format to the server
+    * @return The result response of the delete from the server when the callback is ommitted ( made it synchronous )
+    */
+
+    "delete": function( uri, callback, accept ){
+      
+	return this.send( 'rest' + uri, [ 'delete', accept || 'json' ], false, callback, !!!callback, 
+	{'beforeSend' : function (xhr){ 
+	    xhr.setRequestHeader('Authorization', "OAUTH Bearer " + DataLayer.me.token)} 
+	});
+      
     },
     
@@ -2039,5 +2123,5 @@
 
 	if( !this.dispatchPath )
-	    this.dispatchPath = "../../";
+	    this.dispatchPath = "prototype/";
 
 	if( !this.templatePath )
@@ -2054,4 +2138,5 @@
 
 	this.start();
+	this.me = this.dispatch( "me" );
     }
 }
Index: sandbox/2.4.1-3/prototype/rest/oauth/authorize.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/authorize.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/authorize.php	(revision 6351)
@@ -0,0 +1,67 @@
+<?php
+/**
+ * @file
+ * Sample authorize endpoint.
+ *
+ * This sample provides two click-jacking prevention methods, neither which are perfect. 
+ * The javascript solution is similar to what facebook used to have (but can be defeated with a 
+ * specially crafted frame-wrapper).
+ */
+
+// Clickjacking prevention (supported by IE8+, FF3.6.9+, Opera10.5+, Safari4+, Chrome 4.1.249.1042+)
+header('X-Frame-Options: DENY');
+
+require "lib/OAuth2StoragePdo.php";
+
+/*
+ * You would need to authenticate the user before authorization.
+ * 
+ * Below is some psudeo-code to show what you might do:
+ * 
+session_start();
+if (!isLoggedIn()) {
+	redirectToLoginPage();
+	exit();
+}
+ */
+
+$oauth = new OAuth2(new OAuth2StoragePDO());
+
+if ($_POST) {
+	$userId = '12345'; // Use whatever method you have for identifying users.
+	$oauth->finishClientAuthorization($_POST["accept"] == "Yep", $userId, $_POST);
+}
+
+try {
+	$auth_params = $oauth->getAuthorizeParams();
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+?>
+<html>
+<head>
+<title>Authorize</title>
+<script>
+	if (top != self) {
+		window.document.write("<div style='background:black; opacity:0.5; filter: alpha (opacity = 50); position: absolute; top:0px; left: 0px;"
+		+ "width: 9999px; height: 9999px; zindex: 1000001' onClick='top.location.href=window.location.href'></div>");
+	}
+  </script>
+</head>
+<body>
+<form method="post" action="authorize.php">
+ 
+    
+      <?php 
+      foreach ($auth_params as $key => $value) : ?>
+      	<input type="hidden"
+	name="<?php echo htmlspecialchars($key, ENT_QUOTES); ?>"
+	value="<?php echo htmlspecialchars($value, ENT_QUOTES); ?>" />
+      <?php endforeach; ?>
+      Do you authorize the app to do its thing?
+      <p><input type="submit" name="accept" value="Yep" /> <input
+	type="submit" name="accept" value="Nope" /></p>
+</form>
+</body>
+</html>
Index: sandbox/2.4.1-3/prototype/rest/oauth/mysql_create_tables.sql
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/mysql_create_tables.sql	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/mysql_create_tables.sql	(revision 6351)
@@ -0,0 +1,36 @@
+SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
+
+CREATE TABLE `auth_codes` (
+  `code` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `redirect_uri` varchar(200) NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`code`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `clients` (
+  `client_id` varchar(40) NOT NULL,
+  `client_secret` varchar(20) NOT NULL,
+  `redirect_uri` varchar(255) NOT NULL,
+  PRIMARY KEY (`client_id`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `access_tokens` (
+  `oauth_token` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`oauth_token`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
+
+CREATE TABLE `refresh_tokens` (
+  `refresh_token` varchar(40) NOT NULL,
+  `client_id` varchar(40) NOT NULL,
+  `user_id` int(11) UNSIGNED NOT NULL,
+  `expires` int(11) NOT NULL,
+  `scope` varchar(255) DEFAULT NULL,
+  PRIMARY KEY (`refresh_token`)
+) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Index: sandbox/2.4.1-3/prototype/rest/oauth/protected_resource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/protected_resource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/protected_resource.php	(revision 6351)
@@ -0,0 +1,35 @@
+<?php
+
+/**
+ * @file
+ * Sample protected resource.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ *
+ * In reality, you'd probably use a nifty framework to handle most of the crud for you.
+ */
+
+require "lib/OAuth2StoragePdo.php";
+
+try {
+	$oauth = new OAuth2(new OAuth2StoragePDO());
+	$token = $oauth->getBearerToken();
+	$oauth->verifyAccessToken($token);
+} catch (OAuth2ServerException $oauthError) {
+	$oauthError->sendHttpResponse();
+}
+
+// With a particular scope, you'd do:
+// $oauth->verifyAccessToken("scope_name");
+
+
+?>
+
+<html>
+	<head>
+		<title>Hello!</title>
+	</head>
+	<body>
+		<p>This is a secret.</p>
+	</body>
+</html>
Index: sandbox/2.4.1-3/prototype/rest/oauth/OAuth2StorageUserCredential.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/OAuth2StorageUserCredential.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/OAuth2StorageUserCredential.php	(revision 6351)
@@ -0,0 +1,279 @@
+<?php
+
+require ROOTPATH . '/library/oauth2/lib/OAuth2.php';
+require ROOTPATH . '/library/oauth2/lib/IOAuth2Storage.php';
+require ROOTPATH . '/library/oauth2/lib/IOAuth2GrantCode.php';
+require ROOTPATH . '/library/oauth2/lib/IOAuth2RefreshTokens.php';
+
+require ROOTPATH . '/library/oauth2/lib/IOAuth2GrantUser.php';
+
+
+class OAuth2StorageUserCredential implements IOAuth2GrantUser, IOAuth2RefreshTokens {
+
+	public function checkUserCredentials($client_id, $username, $password) {
+	    
+		//Authentica no LDAP
+		$usuario =  Controller::find(array('concept'=>'user' , 'service' => 'OpenLDAP'), false , array('filter' => array('AND', array('=' , 'uid' , $username ), array('=' , 'password', '{md5}' . base64_encode(pack("H*",md5($password))))  ) ));
+
+		if(isset($usuario[0]['id']))
+		{
+		    return array('scope' => 'all' , 'user_id' => $usuario[0]['id']);
+		}
+
+		return false;
+	}
+	
+	/**
+	 * Make sure that the client credentials is valid.
+	 * 
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $client_secret
+	 * (optional) If a secret is required, check that they've given the right one.
+	 *
+	 * @return
+	 * TRUE if the client credentials are valid, and MUST return FALSE if it isn't.
+	 * @endcode
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-3.1
+	 *
+	 * @ingroup oauth2_section_3
+	 */
+	public function checkClientCredentials($client_id, $client_secret = NULL) {
+		if($client_secret == NULL) {
+			return false;
+		}
+
+		$res =  Controller::find(array('concept' => 'oauthCliente'), array('client_secret') , array('filter' => array('=' , 'client_id' , $client_id)) );
+
+		if(isset($res[0]['client_secret']) && $res[0]['client_secret'] == $client_secret) {
+			return true;
+		}
+		else {
+			return false;
+		}
+	}
+
+	/**
+	 * Get client details corresponding client_id.
+	 *
+	 * OAuth says we should store request URIs for each registered client.
+	 * Implement this function to grab the stored URI for a given client id.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 *
+	 * @return array
+	 * Client details. Only mandatory item is the "registered redirect URI", and MUST
+	 * return FALSE if the given client does not exist or is invalid.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function getClientDetails($client_id) {
+		$res =  Controller::find(array('concept' => 'oauthCliente'), array('redirect_uri') , array('filter' => array('=' , 'client_id' , $client_id)));
+		if(isset($res[0]['redirect_uri'])) {
+			return $res[0]['redirect_uri'];
+		}
+		else {
+			return false;
+		}
+	}
+
+	/**
+	 * Look up the supplied oauth_token from storage.
+	 *
+	 * We need to retrieve access token data as we create and verify tokens.
+	 *
+	 * @param $oauth_token
+	 * oauth_token to be check with.
+	 *
+	 * @return
+	 * An associative array as below, and return NULL if the supplied oauth_token
+	 * is invalid:
+	 * - client_id: Stored client identifier.
+	 * - expires: Stored expiration in unix timestamp.
+	 * - scope: (optional) Stored scope values in space-separated string.
+	 *
+	 * @ingroup oauth2_section_7
+	 */
+	public function getAccessToken($oauth_token) {
+		return $this->getToken($oauth_token, false);
+	}
+
+	/**
+	 * Take the provided refresh token values and store them somewhere.
+	 *
+	 * This function should be the storage counterpart to getRefreshToken().
+	 *
+	 * If storage fails for some reason, we're not currently checking for
+	 * any sort of success/failure, so you should bail out of the script
+	 * and provide a descriptive fail message.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be stored.
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $expires
+	 * expires to be stored.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = NULL) {
+		
+		$data = array();
+		$data['refresh_token']  = $refresh_token;
+		$data['client_id'] = $client_id;
+		$data['user_id'] = $user_id;
+		$data['expires'] = $expires;
+		$data['scope'] = $scope;
+
+	        Controller::create(array('concept' => 'oauthRefreshToken'), $data);
+	}
+	
+	/**
+	 * Store the supplied access token values to storage.
+	 *
+	 * We need to store access token data as we create and verify tokens.
+	 *
+	 * @param $oauth_token
+	 * oauth_token to be stored.
+	 * @param $client_id
+	 * Client identifier to be stored.
+	 * @param $user_id
+	 * User identifier to be stored.
+	 * @param $expires
+	 * Expiration to be stored.
+	 * @param $scope
+	 * (optional) Scopes to be stored in space-separated string.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = NULL, $refresh_token) {
+	   
+		$data = array();
+		$data['oauth_token']  = $oauth_token;
+		$data['client_id'] = $client_id;
+		$data['user_id'] = $user_id;
+		$data['expires'] = $expires;
+		$data['scope'] = $scope;
+		$data['refresh_token'] = $refresh_token;
+		
+		Controller::create(array('concept' => 'oauthToken'), $data);
+
+	}
+
+	/**
+	 * Check restricted grant types of corresponding client identifier.
+	 *
+	 * If you want to restrict clients to certain grant types, override this
+	 * function.
+	 *
+	 * @param $client_id
+	 * Client identifier to be check with.
+	 * @param $grant_type
+	 * Grant type to be check with, would be one of the values contained in
+	 * OAuth2::GRANT_TYPE_REGEXP.
+	 *
+	 * @return
+	 * TRUE if the grant type is supported by this client identifier, and
+	 * FALSE if it isn't.
+	 *
+	 * @ingroup oauth2_section_4
+	 */
+	public function checkRestrictedGrantType($client_id, $grant_type) {
+		/*TODO: essa funÃ§Ã£o deve verificar se o cliente tem permissao para realizar o login via 'password'
+		 * deixe para implementar no prox. sprint, quando trataremos de seguranca. Deve-se criar um campo extra no banco para guardar quais tipos
+		 * de grant_type o cliente esta autorizado a fazer
+		*/
+
+		return true;		
+	}
+
+	/**
+	 * Grant refresh access tokens.
+	 *
+	 * Retrieve the stored data for the given refresh token.
+	 *
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be check with.
+	 *
+	 * @return
+	 * An associative array as below, and NULL if the refresh_token is
+	 * invalid:
+	 * - client_id: Stored client identifier.
+	 * - expires: Stored expiration unix timestamp.
+	 * - scope: (optional) Stored scope values in space-separated string.
+	 *
+	 * @see http://tools.ietf.org/html/draft-ietf-oauth-v2-20#section-6
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function getRefreshToken($refresh_token) {
+		return $this->getToken($refresh_token, true);
+	}
+
+	/**
+	 * Expire a used refresh token.
+	 *
+	 * This is not explicitly required in the spec, but is almost implied.
+	 * After granting a new refresh token, the old one is no longer useful and
+	 * so should be forcibly expired in the data store so it can't be used again.
+	 *
+	 * If storage fails for some reason, we're not currently checking for
+	 * any sort of success/failure, so you should bail out of the script
+	 * and provide a descriptive fail message.
+	 *
+	 * @param $refresh_token
+	 * Refresh token to be expirse.
+	 *
+	 * @ingroup oauth2_section_6
+	 */
+	public function unsetRefreshToken($refresh_token) {
+		Controller::delete(
+			array('concept' => 'oauthRefreshToken'),
+			false,
+			array('filter' => array('=', 'refresh_token', $refresh_token ))
+		);
+	}
+	public function unsetAccessToken($refresh_token) {
+		Controller::delete(
+			array('concept' => 'oauthToken'),
+			false,
+			array('filter' => array('=', 'oauth_token', $refresh_token ))
+		);
+	}
+
+	/**
+	 * Retrieves an access or refresh token.
+	 * 
+	 * @param string $token
+	 * @param bool $refresh
+	 */
+	protected function getToken($token, $isRefresh = true) {
+
+		$tokenConcept = $isRefresh ? 'oauthRefreshToken' : 'oauthToken';
+		$filter =  $isRefresh ? 'refresh_token' : 'oauth_token';
+		
+		$res = Controller::find(
+			array('concept' => $tokenConcept), 
+			false, 
+			array('filter' => array('=' , $filter , $token))
+		);
+
+		/*return (!empty($res[0]))? $res[0] : false;*/
+		if(!empty($res[0])) {
+			return $res[0];
+		}
+		else {
+			return false;
+		}
+	}
+}
+
+
Index: sandbox/2.4.1-3/prototype/rest/oauth/hello.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/hello.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/hello.php	(revision 6351)
@@ -0,0 +1,4 @@
+<?php
+
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/oauth/addclient.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/addclient.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/addclient.php	(revision 6351)
@@ -0,0 +1,40 @@
+<?php
+
+/**
+ * @file
+ * Sample client add script.
+ *
+ * Obviously not production-ready code, just simple and to the point.
+ */
+
+require "lib/OAuth2StoragePdo.php";
+
+if ($_POST && isset($_POST["client_id"]) && isset($_POST["client_secret"]) && isset($_POST["redirect_uri"])) {
+	$oauth = new OAuth2StoragePDO();
+	$oauth->addClient($_POST["client_id"], $_POST["client_secret"], $_POST["redirect_uri"]);
+}
+
+?>
+
+<html>
+  <head>
+  	<title>Add Client</title>
+  </head>
+  <body>
+    <form method="post" action="addclient.php">
+      <p>
+        <label for="client_id">Client ID:</label>
+        <input type="text" name="client_id" id="client_id" />
+      </p>
+      <p>
+        <label for="client_secret">Client Secret (password/key):</label>
+        <input type="text" name="client_secret" id="client_secret" />
+      </p>
+      <p>
+        <label for="redirect_uri">Redirect URI:</label>
+        <input type="text" name="redirect_uri" id="redirect_uri" />
+      </p>
+      <input type="submit" value="Submit" />
+    </form>
+  </body>
+</html>
Index: sandbox/2.4.1-3/prototype/rest/oauth/TokenResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/oauth/TokenResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/oauth/TokenResource.php	(revision 6351)
@@ -0,0 +1,29 @@
+<?php
+
+/*
+ * @uri /token
+ */
+
+require_once dirname(__FILE__).'/../../api/controller.php';
+
+require_once 'OAuth2StorageUserCredential.php';
+
+class TokenResource extends Resource {
+
+	public function post($request) {
+		$res = new Response($request);
+
+		try {
+			$oauth = new OAuth2(new Oauth2StorageUserCredential());
+			$oauth->grantAccessToken($_POST);
+		} 
+		catch (OAuth2ServerException $oauthError) {
+			$oauthError->sendHttpResponse();
+		}
+		
+		return $res;
+	}
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/mail/MailLastResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/mail/MailLastResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/mail/MailLastResource.php	(revision 6351)
@@ -0,0 +1,97 @@
+<?php
+ 
+class MailLastResource extends Resource {
+ 
+    /**
+    * Busca as Ãºltimas 20 menssagens nÃ£o lidas do usuÃ¡rio
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃŽmica Federal
+    * @author     Cristiano CorrÃªa Schmidt
+    * @return     Lista das ultimas 10 menssagens do usuÃ¡rio nÃ£o lidas
+    * @access     public
+    **/
+    function get($request) 
+    {
+	$this->secured();
+	
+        $response = new Response($request);
+        $response->code = Response::OK;
+        $response->addHeader('Content-type', 'aplication/json');
+		
+	$cyrus = Config::service('Cyrus', 'config');
+	$options = ($cyrus['tlsEncryption']) ? '/tls/novalidate-cert' : '/notls/novalidate-cert'; 
+	$mbox = imap_open( '{'.$cyrus['host'].":".$cyrus['port'].$options.'}INBOX' , Config::me('uid') , Config::me('password') );
+	
+	$msgIds = imap_sort( $mbox , SORTDATE , 1 , null , "UNSEEN" , 'UTF-8');
+	$msgIds = array_splice($msgIds , 0 , 20);
+	
+	$return = array();
+	
+	foreach ($msgIds as $key => &$value) 
+	{    
+	      $header = imap_headerinfo( $mbox, $value );
+	      $return[$key]['subject'] = ( isset($header->subject) && trim($header->subject) !== '' ) ?  self::decodeMimeString($header->subject) : 'No Subject';
+	      $return[$key]['date'] =  $header->udate;
+	      $return[$key]['from'] =  (isset( $header->from[0] )) ? self::formatMailObject( $header->from[0] ) : array( 'name' => '' , 'mail' => '');
+	}
+
+	$response->body = json_encode($return);
+	
+	imap_close($mbox);
+	return $response;
+    }
+
+    
+    
+    /**
+    *  Decodifica os tokens encontrados na funÃ§Ã£o decodeMimeString
+    * 
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃ³mica Federal
+    * @author     Cristiano CorrÃªa Schmidt
+    * @return     bool
+    * @access     public
+    */
+    static private function decodeMimeStringCallback( $mathes )
+    {
+       $str = (strtolower($mathes[2]) == 'q') ?  quoted_printable_decode(str_replace('_','=20',$mathes[3])) : base64_decode( $mathes[3]) ;
+       return ( strtoupper($mathes[1]) == 'ISO-8859-1' ) ? mb_convert_encoding(  $str , 'UTF-8' , 'ISO-8859-1') : $str;
+    }
+
+    /**
+    *  Decodifica uma string no formato mime RFC2047
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃ³mica Federal
+    * @author     Cristiano CorrÃªa Schmidt
+    * @return     bool
+    * @access     public
+    */
+    static private function decodeMimeString( $string )
+    {
+      $string =  preg_replace('/\?\=(\s)*\=\?/', '?==?', $string);
+      return preg_replace_callback( '/\=\?([^\?]*)\?([qb])\?([^\?]*)\?=/i' ,array( 'self' , 'decodeMimeStringCallback'), $string);
+    }
+    
+     /**
+    *  Formata um mailObject para um array com name e email
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃ³mica Federal
+    * @author     Cristiano CorrÃªa Schmidt
+    * @return     bool
+    * @access     public
+    */
+    static private function formatMailObject( $obj )
+    {
+	$return = array();
+	$return['mail'] = self::decodeMimeString($obj->mailbox) . (( isset( $obj->host) && $obj->host != ('unspecified-domain') &&  $obj->host !=  '.SYNTAX-ERROR.')? '@'. $obj->host : '');
+	$return['name'] = ( isset( $obj->personal ) && trim($obj->personal) !== '' ) ? self::decodeMimeString($obj->personal) :  $return['mail'];
+	return $return;
+    }
+}
Index: sandbox/2.4.1-3/prototype/rest/dispatch.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/dispatch.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/dispatch.php	(revision 6351)
@@ -0,0 +1,58 @@
+<?php
+// load Tonic library
+require_once __DIR__ . '/../library/tonic/lib/tonic.php';
+require_once __DIR__ . '/../api/controller.php';
+require_once ROOTPATH . '/rest/oauth/OAuth2StorageUserCredential.php';
+
+
+//Retrieveing the mapping of the URIs and his respectives classNames and classPath
+$config = parse_ini_file( __DIR__ . '/../config/Tonic.srv', true );
+
+//looping through the mapping to create 2 separated maps:
+// First indexed by the uri that carry the classNames, 
+// that its used by Tonic to autoload them when routed by him accordingly;
+// Second indexed by the className that carry the classPaths,
+// used by the autoload register to find the correct path of the class that's going to
+// be loaded;
+
+$autoload = array();
+$classpath = array();
+
+foreach( $config as $uri => $classFile ){
+    foreach( $classFile as $className => $filePath )
+    {
+	$autoload[ $uri ] = $className;
+	$classpath[ $className ] = $filePath;
+    }
+}
+
+//The autoload function that's called by the PHP when Tonic routes a class not declared previously
+function __autoload($class) {
+
+	global $classpath;
+
+	require_once(__DIR__ . $classpath[ $class ] );
+}
+
+// handle request, passing the current env baseUri and autoload mapping;
+$request = new Request(array(
+	'baseUri'=> '/tezza/expressoDFD/rest',
+	'autoload' => $autoload,
+));
+
+try {
+    $resource = $request->loadResource();
+    $response = $resource->exec($request);
+
+} catch (ResponseException $e) {
+    switch ($e->getCode()) {
+    case Response::UNAUTHORIZED:
+        $response = $e->response($request);
+        $response->addHeader('WWW-Authenticate', 'Basic realm="Tonic"');
+        break;
+    default:
+        $response = $e->response($request);
+    }
+}
+$response->output();
+
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/data.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/data.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/data.php	(revision 6351)
@@ -0,0 +1,71 @@
+<?php
+
+class Data {
+
+    public $name;
+    public $value;
+    public $prompt;
+    public $dataType;
+    public $maxLength;
+    public $minLength;
+    public $required;
+
+    function setName($name) {
+	$this->name = $name;
+    }
+
+    function getName() {
+	return $this->name;
+    }
+
+    function setValue($value) {
+	$this->value = $value;
+    }
+
+    function getVame() {
+	return $this->value;
+    }
+
+    function setPrompt($prompt) {
+	$this->prompt = $prompt;
+    }
+
+    function getPrompt() {
+	return $this->prompt;
+    }
+
+    function setDataType($dataType) {
+	$this->dataType = $dataType;
+    }
+
+    function getDataType() {
+	return $this->dataType;
+    }
+
+    function setMaxLength($maxLength) {
+	$this->maxLength = $maxLength;
+    }
+
+    function getMaxLength() {
+	return $this->maxLength;
+    }
+
+    function setMinLength($minLength) {
+	$this->minLength = $minLength;
+    }
+
+    function getMinLength() {
+	return $this->minLength;
+    }
+
+    function setRequired($required) {
+	$this->required = $required;
+    }
+
+    function getRequired() {
+	return $this->required;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/error.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/error.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/error.php	(revision 6351)
@@ -0,0 +1,35 @@
+<?php
+
+class Error {
+
+    public $code;
+    public $description;
+    public $title;
+
+    public function setCode($code) {
+	$this->code = $code;
+    }
+
+    public function setDescription($description) {
+	$this->description = $description;
+    }
+
+    public function setTitle($title) {
+	$this->title = $title;
+    }
+
+    public function getCode() {
+	return $this->code;
+    }
+
+    public function getDescription() {
+	return $this->description;
+    }
+
+    public function getTitle() {
+	return $this->title;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/collection.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/collection.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/collection.php	(revision 6351)
@@ -0,0 +1,85 @@
+<?php
+
+include_once('item.php');
+include_once('link.php');
+include_once('data.php');
+include_once('template.php');
+include_once('query.php');
+include_once('error.php');
+
+class Collection {
+
+    public $itens = array();
+    public $href;
+    public $error;
+    public $pagination;
+    public $queries;
+    public $template;
+    public $type;
+    public $data;
+
+    function __construct($config, $className) {
+	foreach ($config as $key => $value) {
+	    if ($value['class'] == $className) {
+		$uri = $key;
+		break;
+	    }
+	}
+	$this->href = $uri;
+    }
+
+    function addItem($item) {
+	$this->itens[] = $item;
+    }
+
+    function setData($data) {
+	$this->data = $data;
+    }
+
+    function getData() {
+	return $this->data;
+    }
+    
+    function setTemplate($template) {
+	$this->template = $template;
+    }
+
+    function getTemplate() {
+	return $this->template;
+    }
+
+    function setType($type) {
+	$this->type = $type;
+    }
+
+    function getType() {
+	return $this->type;
+    }
+
+    function setQueries($queries) {
+	$this->queries = $queries;
+    }
+
+    function getQueries() {
+	return $this->queries;
+    }
+
+    function setError($error) {
+	$this->error = $error;
+    }
+
+    function getError() {
+	return $this->error;
+    }
+
+    function setPagination($pagination) {
+	$this->pagination = $pagination;
+    }
+
+    function getPagination() {
+	return $this->pagination;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/template.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/template.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/template.php	(revision 6351)
@@ -0,0 +1,13 @@
+<?php
+
+class Template {
+
+    public $data = array();
+
+    public function addData($data) {
+	$this->data[] = $data;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/link.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/link.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/link.php	(revision 6351)
@@ -0,0 +1,53 @@
+<?php
+
+class Link {
+
+    public $href;
+    public $rel;
+    public $alt;
+    public $prompt;
+    public $render;
+
+    function setHref($href) {
+	$this->href = $href;
+    }
+
+    function getHref() {
+	return $this->href;
+    }
+
+    function setRel($rel) {
+	$this->rel = $rel;
+    }
+
+    function getRel() {
+	return $this->rel;
+    }
+
+    function setAlt($alt) {
+	$this->alt = $alt;
+    }
+
+    function getAlt() {
+	return $this->alt;
+    }
+
+    function setPrompt($prompt) {
+	$this->prompt = $prompt;
+    }
+
+    function getPrompt() {
+	return $this->prompt;
+    }
+
+    function setRender($render) {
+	$this->render = $render;
+    }
+
+    function getRender() {
+	return $this->render;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/item.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/item.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/item.php	(revision 6351)
@@ -0,0 +1,38 @@
+<?php
+
+class Item {
+
+    public $href;
+    public $data = array();
+    public $links = array();
+
+    function __construct($config, $className, $id) {
+	foreach ($config as $key => $value) {
+	    if ($value['class'] == $className) {
+		//TODO - Verificar expressão regular
+		$uri = preg_replace('/\/[:][a-zA-Z-0-9]+/', '', $key);
+		break;
+	    }
+	}
+	$this->href = $uri .'/'. $id;
+    }
+
+    function setHref($href) {
+	$this->href = $href;
+    }
+
+    function getHref() {
+	return $this->href;
+    }
+
+    function addData($data) {
+	$this->data[] = $data;
+    }
+
+    function addLink($link) {
+	$this->links[] = $link;
+    }
+
+}
+
+?>  
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/query.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/query.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/query.php	(revision 6351)
@@ -0,0 +1,25 @@
+<?php
+
+class Querie {
+	public $href;
+	public $data = array();
+
+	public function getHref(){
+		return $this->href;
+	}
+
+	public function setHref($href){
+		$this->href = $href;
+	}
+
+	public function setData($field, $value, $required=false){
+		$this->data[] = array(
+					'name' => $field,
+					'value' => $value,
+					'required' => $required
+		);
+	}
+    
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/hypermedia/hypermedia.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/hypermedia/hypermedia.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/hypermedia/hypermedia.php	(revision 6351)
@@ -0,0 +1,70 @@
+<?php
+
+include_once('collection.php');
+
+class Hypermedia {
+
+    public $collection;
+    public $version = '0.1';
+
+    function setCollection($collection) {
+	$this->collection = $collection;
+    }
+
+    function getCollection() {
+	return $this->collection;
+    }
+
+    function getHypermedia($accept = 'json') {
+
+	$data = get_object_vars($this);
+
+	switch ($accept) {
+	    case 'json':
+		return json_encode($data);
+		break;
+	    case 'xml':
+		return $this->generateValidXmlFromArray($data);
+	    default :
+		return json_encode($data);
+	}
+    }
+
+// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
+
+    function generateValidXmlFromObj(stdClass $obj, $node_block = 'nodes', $node_name = 'node') {
+	$arr = get_object_vars($obj);
+	return self::generateValidXmlFromArray($arr, $node_block, $node_name);
+    }
+
+    function generateValidXmlFromArray($array, $node_block = 'nodes', $node_name = 'node') {
+	$xml = '<?xml version="1.0" encoding="UTF-8" ?>';
+
+	$xml .= '<' . $node_block . '>';
+	$xml .= self::generateXmlFromArray($array, $node_name);
+	$xml .= '</' . $node_block . '>';
+
+	return $xml;
+    }
+
+    function generateXmlFromArray($array, $node_name) {
+	$xml = '';
+
+	if (is_array($array) || is_object($array)) {
+	    foreach ($array as $key => $value) {
+		if (is_numeric($key)) {
+		    $key = $node_name;
+		}
+
+		$xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
+	    }
+	} else {
+	    $xml = htmlspecialchars($array, ENT_QUOTES);
+	}
+
+	return $xml;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/arquivos
===================================================================
--- sandbox/2.4.1-3/prototype/rest/arquivos	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/arquivos	(revision 6351)
@@ -0,0 +1,3 @@
+Arquivos do expresso modificados
+
+header.inc.php
Index: sandbox/2.4.1-3/prototype/rest/calendar/CalendarLastResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/calendar/CalendarLastResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/calendar/CalendarLastResource.php	(revision 6351)
@@ -0,0 +1,51 @@
+<?php
+
+class CalendarLastResource extends Resource{
+
+    
+    /**
+    * Busca os eventos contidos nas agendas assinas do usuÃ¡rio
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃŽmica Federal
+    * @author     Adriano Coutinho da Silva
+    * @return     Lista dos ultimos 10 eventos do usuÃ¡rio
+    * @access     public
+    **/
+    function GET($request){
+	$this->secured();
+
+	$calendar = Controller::find( array( 'concept' => 'calendarSignature' ), array('calendar'), array( 'filter' => array( '=', 'user',  Config::me("uidNumber") ) ) );
+
+	
+	
+	
+	if($calendar){
+	    $calendars = array();
+	    $timezones = array();
+
+	    foreach($calendar as $key => $value)
+		array_push($calendars, $value['calendar']);
+
+	    $calendarTimezone = Controller::find( array( 'concept' => 'calendar' ), array('id', 'timezone'), array( 'filter' => array( 'IN', 'id',  $calendars ) ) );
+
+	    foreach($calendarTimezone as $key => $value)
+		$timezones[ $value['id'] ] = $value['timezone'];
+
+
+	    $schedulables = Controller::find( array( 'concept' => 'schedulable' ), false, 
+		    array( 'filter' => array('AND', array('>=','rangeStart', (time() - 86400).'000'), array('<=','rangeEnd', (time() + 2592000).'000') ,array( 'IN', 'calendar', $calendars )), 'deepness' => 2, 'timezones' => $timezones) );
+
+	}
+	
+	$response = new Response($request);
+	$response->code = Response::OK;
+	$response->addHeader('Content-type', 'aplication/json');
+
+	$response->body = json_encode(( isset($schedulables) && $schedulables) ?  $schedulables : array());
+	return $response;
+    }
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/.htaccess
===================================================================
--- sandbox/2.4.1-3/prototype/rest/.htaccess	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/.htaccess	(revision 6351)
@@ -0,0 +1,6 @@
+<IfModule mod_rewrite.c>
+    RewriteEngine On
+    RewriteCond %{REQUEST_URI} !dispatch\.php$
+    RewriteCond %{REQUEST_FILENAME} !-f
+    RewriteRule .* dispatch.php [L,QSA]
+</IfModule>
Index: sandbox/2.4.1-3/prototype/rest/contact/DynamicContactDeleteResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/contact/DynamicContactDeleteResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/contact/DynamicContactDeleteResource.php	(revision 6351)
@@ -0,0 +1,135 @@
+<?php
+
+require_once('/home/tezza/expressoDFD/prototype/rest/hypermedia/hypermedia.php');
+
+class DynamicContactDeleteResource extends Resource{
+
+    /**
+    * Busca os eventos contidos nas agendas assinas do usuário
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa Econômica Federal
+    * @author     Adriano Coutinho da Silva
+    * @author     Adir Kuhn
+    * @return     Remove um resource do contato
+    * @access     public
+    **/
+	function get($request) {
+		try {
+
+		    $response = new Response($request);
+		    $response->addHeader('Content-type', 'aplication/json');
+		    $this->secured();
+		    $response->code = Response::OK;
+
+		    $dynamicContact = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('=', 'owner', Config::me("uidNumber"))));
+		    
+		    $h = new Hypermedia();
+		    $c = new Collection($request->resources, 'DynamicContactsResource');
+
+		    foreach($dynamicContact as $value){
+			$d = new Data();
+			$i = new Item($request->resources, 'DynamicContactResource', $value['id']);
+			
+			$d->setName('name');
+			$d->setValue($value['name']);
+			$d->setPrompt('Nome do contato');
+			$d->setDataType('string');
+			$d->setMaxLength('100');
+			$d->setMinLength(null);
+			$d->setRequired(false);
+			
+			$i->addData($d);
+
+			$d->setName('email');
+			$d->setValue($value['mail']);
+			$d->setPrompt('Email do contato');
+			$d->setDataType('string');
+			$d->setMaxLength('100');
+			$d->setMinLength(null);
+			$d->setRequired(true);
+			
+			$i->addData($d);			
+			$l = new Link();
+
+			$l->setHref($i->getHref());
+			$l->setRel('delete');
+			$l->setAlt('Remover');
+			$l->setPrompt('Remover');
+			$l->setRender('link');
+			
+			$i->addLink($l);
+			
+			$l->setHref($i->getHref());
+			$l->setRel('put');
+			$l->setAlt('Atualizar');
+			$l->setPrompt('Atualizar');
+			$l->setRender('link');
+			
+			$i->addLink($l);
+			
+			$l->setHref($i->getHref());
+			$l->setRel('get');
+			$l->setAlt('Buscar');
+			$l->setPrompt('Buscar');
+			$l->setRender('link');
+
+			$i->addLink($l);
+			$c->addItem($i);
+		    }
+
+		    $t = new Template();
+		    $d = new Data();
+
+		    $d->setName('name');
+		    $d->setValue(null);
+		    $d->setPrompt('Nome do contato');
+		    $d->setDataType('string');
+		    $d->setMaxLength(100);
+		    $d->setMinLength(null);
+		    $d->setRequired(false);
+
+		    $t->addData($d);
+		    $d = new Data();
+
+		    $d->setName('email');
+		    $d->setValue(null);
+		    $d->setPrompt('Email do contato');
+		    $d->setDataType('string');
+		    $d->setMaxLength(100);
+		    $d->setMinLength(null);
+		    $d->setRequired(true);
+
+		    $t->addData($d);
+
+		    $c->setTemplate($t);
+		    $d = new Data();
+
+		    $d->setName('Dynamic Contacts');
+		    $d->setValue(null);
+		    $d->setPrompt('Contatos Dinâmicos');
+		    $d->setDataType(null);
+		    $d->setMaxLength(null);
+		    $d->setMinLength(null);
+		    $d->setRequired(null);
+		    
+		    $c->setData($d);
+		    
+		    $h->setCollection($c);
+		    
+		}  catch (Exception $ex){
+			$response->code = Response::INTERNALSERVERERROR;
+			$error = array(
+				'code' => '500',
+				'title' => 'Internal Server Error',
+				'description' => $ex);
+			return $response;
+		}
+
+		$response->body = $h->getHypermeida($request->accept[10][0]);		
+		return $response;
+	}
+
+}
+?>
Index: sandbox/2.4.1-3/prototype/rest/contact/DynamicContactsResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/contact/DynamicContactsResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/contact/DynamicContactsResource.php	(revision 6351)
@@ -0,0 +1,171 @@
+<?php
+
+class DynamicContactsResource extends Resource {
+
+    /**
+     * Busca os eventos contidos nas agendas assinas do usuário
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     Adriano Coutinho da Silva
+     * @author     Adir Kuhn
+     * @return     Retorna a colection de contatos dinâmicos de um usuário
+     * @access     public
+     * */
+    function get($request) {
+	try {
+	    $response = new Response($request);
+	    $response->addHeader('Content-type', 'aplication/json');
+
+	    $this->secured();
+	    $dynamicContact = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('=', 'owner', Config::me("uidNumber"))));
+
+	    $response->code = Response::OK;
+	    $resourceHref = str_replace($request->baseUri, '', $request->uri);
+
+	    if ($dynamicContact) {
+		$data = array();
+		foreach ($dynamicContact as $key => $value) {
+		    $data[$key] = array(
+			'href' => '/dynamic-contacts/' . $value['id'],
+			'data' => array(
+			    array(
+				'name' => "name",
+				'value' => $value['name'],
+				'prompt' => "Nome do Contato"
+			    ),
+			    array(
+				"name" => "email",
+				"value" => $value['mail'],
+				"prompt" => "Email do Contato"
+			    )
+			),
+			'links' => array(
+			    array(
+				'href' => $resourceHref . "/" . $value['id'],
+				'rel' => 'delete',
+				'prompt' => 'Remover contato dinamico',
+				'name' => 'delete-contact',
+				'render' => 'link'
+			    ),
+			    array(
+				'href' => $resourceHref . '/' . $value['id'],
+				'rel' => 'update',
+				'prompt' => 'Editar contato dinamico',
+				'name' => 'edit-contact',
+				'render' => 'link'
+			    )
+			)
+		    );
+		}
+	    }else
+		$data = null;
+
+	    $result = array(
+		"version" => "0.1",
+		"collection" => array(
+		    "href" => $resourceHref,
+		    "type" => "dynamic-contacts",
+		    "data" => array(
+			"name" => "dynamic-contacts",
+			"prompt" => "Contatos dinâmicos"
+		    ),
+		    "pagination" => null,
+		    "items" => $data,
+		    "queries" => null,
+		    "template" => array(
+			"data" => array(
+			    array(
+				"name" => "name",
+				"value" => "",
+				"prompt" => "Nome do contato",
+				"dataType" => "string",
+				"minLength" => 0,
+				"maxLength" => 100,
+				"required" => false
+			    ),
+			    array(
+				"name" => "email",
+				"value" => "",
+				"prompt" => "Email do contato",
+				"dataType" => "string",
+				"minLength" => 0,
+				"maxLength" => 100,
+				"required" => true
+			    )
+			)
+		    ),
+		    'error' => null
+		)
+	    );
+	} catch (Exception $ex) {
+	    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', $ex);
+	    return $response;
+	}
+
+	$response->body = json_encode($result);
+	return $response;
+    }
+
+    function post($request) {
+
+	try {
+	    $response = new Response($request);
+	    $response->addHeader('Content-type', 'aplication/json');
+	    $data = $_POST;
+
+	    if ($this->validData($data)) {
+		$this->secured();
+
+		$response->code = Response::OK;
+
+		$exists = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('AND',
+				array('=', 'owner', Config::me("uidNumber")),
+				array('=', 'mail', $data['email'])
+				)));
+
+		if ($exists) {
+		    //Controller::update(array('concept' => 'dynamicContact', 'id' => $exists[0]['id']), array('name' => $data['name'], 'email' => $data['email'], 'timestamp' => time()));
+
+		    $this->createException($response, Response::BADREQUEST, 'Bad request', Controller::service('PostgreSQL')->error);
+		    return $response;
+		}else
+		    $newDynamicContact = Controller::create(array('concept' => 'dynamicContact'), array('name' => $data['name'], 'mail' => $data['email'], 'owner' => Config::me("uidNumber"), 'timestamp' => time()));
+
+		if (!$newDynamicContact)
+		    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
+	    } else {
+		$this->createException($response, Response::BADREQUEST, 'Bad request', 'Invalid template data');
+		return $response;
+	    }
+	} catch (Exception $ex) {
+	    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', $ex);
+	    return $response;
+	}
+
+	return $response;
+    }
+
+    private function createException(&$response, $code, $title, $description) {
+	$result = array(
+	    'version' => '0.1',
+	    'collection' => array(
+		'error' => array(
+		    'code' => $code,
+		    'title' => $title,
+		    'description' => $description
+		)
+	    )
+	);
+	$response->code = $code;
+	$response->body = json_encode($result);
+    }
+
+    private function validData($data) {
+	return ((array_key_exists('name', $data) && !empty($data['name'])) && (array_key_exists('email', $data) && !empty($data['email']))) ? true : false;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/contact/DynamicContactResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/contact/DynamicContactResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/contact/DynamicContactResource.php	(revision 6351)
@@ -0,0 +1,255 @@
+<?php
+
+class DynamicContactResource extends Resource {
+
+    /**
+     * Busca um contato dinâmico da lista do usuário
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     Adriano Coutinho da Silva
+     * @author     Adir Kuhn
+     * @return     Retorna um item da colection de contatos dinâmicos de um usuário
+     * @access     public
+     * */
+    function get($request, $id) {
+	try {
+	    $response = new Response($request);
+	    $response->addHeader('Content-type', 'aplication/json');
+
+	    $isValidId = $this->isValidId($id);
+
+	    if (!$isValidId) {
+		$this->createException($response, Response::BADREQUEST, 'Malformed URL', 'Malformed URL');
+		return $response;
+	    }
+	    $response->code = Response::OK;
+
+	    $this->secured();
+	    //$dynamicContact = false;
+	    $dynamicContact = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('AND', array('=', 'owner', Config::me("uidNumber")), array('=', 'id', $id))));
+
+	    $resourceHref = str_replace($request->baseUri, '', $request->uri);
+
+	    if ($dynamicContact) {
+		$data = array();
+		foreach ($dynamicContact as $key => $value) {
+		    $data[$key] = array(
+			'href' => '/dynamiccontacts/' . $value['id'],
+			'data' => array(
+			    array(
+				'name' => "name",
+				'value' => $value['name'],
+				'prompt' => "Nome do Contato"
+			    ),
+			    array(
+				"name" => "email",
+				"value" => $value['mail'],
+				"prompt" => "Email do Contato"
+			    )
+			),
+			'links' => array(
+			    array(
+				'href' => $resourceHref,
+				'rel' => 'delete',
+				'prompt' => 'Remover contato dinamico',
+				'name' => 'delete-contact',
+				'render' => 'link'
+			    ),
+			    array(
+				'href' => $resourceHref,
+				'rel' => 'update',
+				'prompt' => 'Editar contato dinamico',
+				'name' => 'edit-contact',
+				'render' => 'link'
+			    )
+			)
+		    );
+		}
+	    } else {
+		$this->createException($response, Response::NOTFOUND, 'Contact not found', ( $isValidId ? "The contact " . $id . " wasn't found on this server" : 'url malformed'));
+		return $response;
+	    }
+
+	    $result = array(
+		"version" => "0.1",
+		"collection" => array(
+		    "href" => $resourceHref,
+		    "type" => "dynamic-contact",
+		    "data" => array(
+			"name" => "dynamic-contact-" . $id,
+			"prompt" => "Contato dinâmico"
+		    ),
+		    "pagination" => null,
+		    "items" => $data,
+		    "queries" => null,
+		    "template" => array(
+			"data" => array(
+			    array(
+				"name" => "name",
+				"value" => "",
+				"prompt" => "Nome do contato",
+				"dataType" => "string",
+				"minLength" => 0,
+				"maxLength" => 100,
+				"required" => false
+			    ),
+			    array(
+				"name" => "email",
+				"value" => "",
+				"prompt" => "Email do contato",
+				"dataType" => "string",
+				"minLength" => 0,
+				"maxLength" => 100,
+				"required" => true
+			    )
+			)
+		    ),
+		'error' => null
+		)
+	    );
+	} catch (Exception $ex) {
+	    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', $ex);
+	    return $response;
+	}
+
+	$response->body = json_encode($result);
+	return $response;
+    }
+
+    /**
+     * Deleta um item da coleção de contatos dinâmicos
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     Adriano Coutinho da Silva
+     * @author     Adir Kuhn
+     * @return     status http
+     * @access     public
+     * */
+    function delete($request, $id) {
+
+	try {
+	    $response = new Response($request);
+	    $response->addHeader('Content-type', 'aplication/json');
+
+	    $isValidId = $this->isValidId($id);
+	    if (!$isValidId) {
+		$this->createException($response, Response::BADREQUEST, 'Malformed URL', 'Malformed URL');
+		return $response;
+	    }
+
+	    $this->secured();
+
+	    $response->code = Response::OK;
+	    $error = null;
+
+	    $exists = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('AND',
+			    array('=', 'owner', Config::me("uidNumber")),
+			    array('=', 'id', $id)
+			    )));
+
+	    if (!$exists) {
+		$this->createException($response, Response::BADREQUEST, 'Contact not found', "The contact " . $id . " wasn't found on this server");
+		return $response;
+	    }
+
+	    $deletedDynamicContact = Controller::delete(array('concept' => 'dynamicContact'), false, array('filter' => array('=', 'id', $id)));
+
+	    if (!$deletedDynamicContact)
+		$error = array(
+		    'code' => '500',
+		    'title' => 'Internal Server Error',
+		    'description' => Controller::service('PostgreSQL')->error
+		);
+	} catch (Exception $ex) {
+	    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', $ex);
+	    return $response;
+	}
+	return $response;
+    }
+
+    /**
+     * Atualiza um item da coleção de contatos dinâmicos
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     Adriano Coutinho da Silva
+     * @author     Adir Kuhn
+     * @return     status http
+     * @access     public
+     * */
+    function put($request, $id) {
+	try {
+	    $response = new Response($request);
+	    $response->addHeader('Content-type', 'aplication/json');
+
+	    $isValidId = $this->isValidId($id);
+	    if (!$isValidId) {
+		$this->createException($response, Response::BADREQUEST, 'Malformed URL', 'Malformed URL');
+		return $response;
+	    }
+
+	    $data = $request->dataDecoded;
+
+	    if ($this->validData($data)) {
+
+		$this->secured();
+
+		$response->code = Response::OK;
+		$exists = Controller::find(array('concept' => 'dynamicContact'), false, array('filter' => array('AND',
+				array('=', 'owner', Config::me("uidNumber")),
+				array('=', 'mail', $data['email'])
+				)));
+
+		if (!empty($exists)) {
+		    $this->createException($response, Response::BADREQUEST, 'Bad request', Controller::service('PostgreSQL')->error);
+		    return $response;
+		}
+
+		$newDynamicContact = Controller::update(array('concept' => 'dynamicContact', 'id' => $id), array('name' => $data['name'], 'mail' => $data['email'], 'timestamp' => time()));
+
+		if (!$newDynamicContact)
+		    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
+	    } else
+		$this->createException($response, Response::BADREQUEST, 'Bad request', 'Invalid template data');
+	} catch (Exception $ex) {
+	    $this->createException($response, Response::INTERNALSERVERERROR, 'Internal Server Error', $ex);
+	    return $response;
+	}
+
+	return $response;
+    }
+
+    private function createException(&$response, $code, $title, $description) {
+	$result = array(
+	    'version' => '0.1',
+	    'collection' => array(
+		'error' => array(
+		    'code' => $code,
+		    'title' => $title,
+		    'description' => $description
+		)
+	    )
+	);
+	$response->code = $code;
+	$response->body = json_encode($result);
+    }
+
+    private function validData($data) {
+	return ((array_key_exists('name', $data) && !empty($data['name'])) && (array_key_exists('email', $data) && !empty($data['email']))) ? true : false;
+    }
+
+    private function isValidId($id) {
+	if (is_numeric($id)) {
+	    return strlen($id) > 10 ? false : true;
+	}else
+	    return false;
+    }
+
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/news/NewsLastResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/news/NewsLastResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/news/NewsLastResource.php	(revision 6351)
@@ -0,0 +1,39 @@
+<?php
+
+class NewsLastResource extends Resource{
+    
+    /**
+    * Busca os Ãºltimos 10 boletins em que o usuÃ¡rio tem acesso
+    *
+    * @license    http://www.gnu.org/copyleft/gpl.html GPL
+    * @author     ConsÃ³rcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+    * @sponsor    Caixa EconÃŽmica Federal
+    * @author     Adriano Coutinho da Silva
+    * @return     Lista dos ultimos 10 boletins do usuÃ¡rio
+    * @access     public
+    **/
+    function GET($request){
+	$this->secured();
+
+	$news = Controller::service('PostgreSQL')->execResultSql( 'SELECT news_subject  as "subject" , 
+	    news_content as "content" ,
+	    news_date as "startTime", 
+	    news_end as "endTime", 
+	    news_id as "id" 
+	    FROM phpgw_news WHERE news_cat IN (1) AND news_begin <= '.time().' AND 
+	    news_end >= '.time().' ORDER BY news_date DESC limit 10');
+
+	if(isset($news) && count($news) > 0)
+	    foreach($news as $key => &$value)
+		$value['subject'] = utf8_encode($value['subject']);
+
+	$response = new Response($request);
+	$response->code = Response::OK;
+	$response->addHeader('Content-type', 'aplication/json');
+
+	$response->body = json_encode(( is_array($news) && $news) ? $news : array());
+	return $response;
+    }
+}
+
+?>
Index: sandbox/2.4.1-3/prototype/rest/user/UsersResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/user/UsersResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/user/UsersResource.php	(revision 6351)
@@ -0,0 +1,203 @@
+<?php
+
+if( !defined( 'ROOTPATH' ) )
+    define( 'ROOTPATH', dirname(__FILE__).'/..' );
+
+require_once(ROOTPATH.'/rest/hypermedia/hypermedia.php');
+
+class UsersResource extends Resource {
+
+    /**
+     * Retorna uma lista de usuários
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     José Vicente Tezza Jr. 
+     * @return     Retorna uma lista de usuários do LDAP
+     * @access     public
+     * */
+    function get($request) {
+
+	$response = new Response($request);
+	$response->addHeader('Content-type', 'aplication/json');
+	$response->code = Response::OK;
+
+	$h = new Hypermedia();
+	$c = new Collection($request->resources, 'UsersResource');
+
+	try {
+
+	    $this->secured();
+
+	    //Executa uma consulta de usuários do LDAP a partir de um determinado atributo e valor
+	    if(isset($_GET['field']) && isset($_GET['value'])){
+
+		    //recupera os atributos definidos no conceito 'user'
+		    $map = Config::get('user', 'OpenLDAP.mapping');
+
+		    //verifica se o campo(atributo) passado pelo usuário está definido no conceito 'user'
+		    if(isset($map[ $_GET['field'] ])){
+			    $users = Controller::find(array('concept' => 'user','service'=>'OpenLDAP'), false, array('filter' => array('=', $_GET['field'],$_GET['value'] )));
+		    }
+		    else{
+			//lança warning no log do Expresso
+			trigger_error("Invalid field (".$_GET['field'].") in the query.", E_USER_WARNING);
+
+			//formata os atributos LDAP do conceito 'user'
+			$attributes = implode(', ', $map); 
+
+			//Configura o erro na hypermedia
+			$error = new Error();
+			$error->setCode(Response::NOTFOUND);
+			$error->setTitle('UserLDAP not found');
+			$error->setDescription("Invalid field (".$_GET['field'].") in the query. Use of these: ".$attributes);
+
+			$c->setError($error);
+			$h->setCollection($c);
+
+			//retorna a hypermedia
+			$response->code = Response::NOTFOUND;
+			$response->body = $h->getHypermedia($request->accept[10][0]);
+			return $response;
+		    }
+	    }
+	    else{
+		    //Executa a consulta dos primeiros 20 usuarios do LDAP
+		    $users = Controller::find(array('concept' => 'user','service'=>'OpenLDAP'), false, array('filter' => array('=', 'phpgwAccountType', 'u'),'limit'=>20));
+	    }
+
+	    //Se nao foi encontrado usuarios na consulta
+	    if($users===false){
+		$error = new Error();
+		$error->setCode(Response::NOTFOUND);
+		$error->setTitle('UserLDAP not found');
+		$error->setDescription('Users not found.');
+
+		$c->setError($error);
+		$h->setCollection($c);
+
+		$response->code = Response::NOTFOUND;
+		$response->body = $h->getHypermedia($request->accept[10][0]);
+		return $response;
+	    }
+
+            foreach($users as $value){
+		$d = new Data();
+                $i = new Item($request->resources, 'UsersResource', $value['uid']);
+
+		$d->setName('name');
+                $d->setValue($value['name']);
+                $d->setPrompt('Nome do Usuário');
+                $d->setDataType('string');
+                $d->setMaxLength('100');
+                $d->setMinLength(null);
+                $d->setRequired(true);
+
+                $i->addData($d);
+
+                $d->setName('email');
+                $d->setValue($value['mail']);
+                $d->setPrompt('Email do Usuário');
+                $d->setDataType('string');
+                $d->setMaxLength('100');
+                $d->setMinLength(null);
+                $d->setRequired(true);
+
+                $i->addData($d);
+                $l = new Link();
+
+                $l->setHref('');
+                $l->setRel('delete');
+                $l->setAlt('Remover');
+                $l->setPrompt('Remover');
+                $l->setRender('link');
+
+                $i->addLink($l);
+
+                $l = new Link();
+                $l->setHref('');
+                $l->setRel('put');
+                $l->setAlt('Atualizar');
+                $l->setPrompt('Atualizar');
+                $l->setRender('link');
+
+                $i->addLink($l);
+
+                $l = new Link();
+                $l->setHref('/userldap/'.$value['uid']);
+                $l->setRel('get');
+                $l->setAlt('Buscar');
+                $l->setPrompt('Buscar');
+                $l->setRender('link');
+
+                $i->addLink($l);
+                $c->addItem($i);
+	    }
+
+            $t = new Template();
+            $d = new Data();
+
+            $d->setName('name');
+            $d->setValue(null);
+            $d->setPrompt('Nome do Usuário');
+            $d->setDataType('string');
+            $d->setMaxLength(100);
+            $d->setMinLength(null);
+            $d->setRequired(true);
+
+            $t->addData($d);
+            $d = new Data();
+
+            $d->setName('email');
+            $d->setValue(null);
+            $d->setPrompt('Email do Usuário');
+            $d->setDataType('string');
+            $d->setMaxLength(100);
+            $d->setMinLength(null);
+            $d->setRequired(true);
+
+            $t->addData($d);
+
+            $c->setTemplate($t);
+            $d = new Data();
+
+            $d->setName('Usuário LDAP');
+            $d->setValue(null);
+            $d->setPrompt('Usuário do LDAP');
+            $d->setDataType(null);
+            $d->setMaxLength(null);
+            $d->setMinLength(null);
+            $d->setRequired(null);
+
+            $c->setData($d);
+
+	    $queries = array();
+	    $queries[0] = new Querie();
+            $queries[0]->setHref($c->href);
+	    $queries[0]->setData('field','',true);
+	    $queries[0]->setData('value','',true);
+	    $c->setQueries($queries);
+
+
+            $h->setCollection($c);
+
+	}catch (Exception $ex){
+		$error = new Error();
+		$error->setCode(Response::INTERNALSERVERERROR);
+		$error->setTitle('Internal Server Error');
+		$error->setDescription($ex);
+
+		$c->setError($error);
+		$h->setCollection($c);
+
+		$response->code = Response::INTERNALSERVERERROR;
+		$response->body = $h->getHypermedia($request->accept[10][0]);
+		return $response;
+	}
+
+	$response->body = $h->getHypermedia($request->accept[10][0]);
+	return $response;
+  }
+}
+?>
Index: sandbox/2.4.1-3/prototype/rest/user/UserResource.php
===================================================================
--- sandbox/2.4.1-3/prototype/rest/user/UserResource.php	(revision 6351)
+++ sandbox/2.4.1-3/prototype/rest/user/UserResource.php	(revision 6351)
@@ -0,0 +1,160 @@
+<?php
+
+if( !defined( 'ROOTPATH' ) )
+    define( 'ROOTPATH', dirname(__FILE__).'/..' );
+
+require_once(ROOTPATH.'/rest/hypermedia/hypermedia.php');
+
+class UserResource extends Resource {
+
+    /**
+     * Retorna uma lista de usuários
+     *
+     * @license    http://www.gnu.org/copyleft/gpl.html GPL
+     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
+     * @sponsor    Caixa Econômica Federal
+     * @author     José Vicente Tezza Jr. 
+     * @return     Retorna um usuário do LDAP filtrado pelo atributo 'uid'
+     * @access     public
+     * */
+    function get($request, $id) {
+
+	$response = new Response($request);
+	$response->addHeader('Content-type', 'aplication/json');
+	$response->code = Response::OK;
+
+	$h = new Hypermedia();
+	$c = new Collection($request->resources, 'UserResource');
+
+	try {
+
+	    $this->secured();
+
+	    $user = Controller::find(array('concept' => 'user','service'=>'OpenLDAP'), false, array('filter' => array('=', 'uid', $id )));
+
+	    //Se nao foi encontrado usuario na consulta
+	    if($user===false){
+		$error = new Error();
+		$error->setCode(Response::NOTFOUND);
+		$error->setTitle('UserLDAP not found');
+		$error->setDescription('User not found.');
+
+		$c->setError($error);
+		$h->setCollection($c);
+
+		$response->code = Response::NOTFOUND;
+		$response->body = $h->getHypermedia($request->accept[10][0]);
+		return $response;
+	    }
+
+            foreach($user as $value){
+		$d = new Data();
+                $i = new Item($request->resources, 'UserResource', $value['uid']);
+
+		$d->setName('name');
+                $d->setValue($value['name']);
+                $d->setPrompt('Nome do Usuário');
+                $d->setDataType('string');
+                $d->setMaxLength('100');
+                $d->setMinLength(null);
+                $d->setRequired(true);
+
+                $i->addData($d);
+
+                $d->setName('email');
+                $d->setValue($value['mail']);
+                $d->setPrompt('Email do Usuário');
+                $d->setDataType('string');
+                $d->setMaxLength('100');
+                $d->setMinLength(null);
+                $d->setRequired(true);
+
+                $i->addData($d);
+                $l = new Link();
+
+                $l->setHref('');
+                $l->setRel('delete');
+                $l->setAlt('Remover');
+                $l->setPrompt('Remover');
+                $l->setRender('link');
+
+                $i->addLink($l);
+
+                $l = new Link();
+                $l->setHref('');
+                $l->setRel('put');
+                $l->setAlt('Atualizar');
+                $l->setPrompt('Atualizar');
+                $l->setRender('link');
+
+                $i->addLink($l);
+
+                $l = new Link();
+                $l->setHref($i->getHref());
+                $l->setRel('get');
+                $l->setAlt('Buscar');
+                $l->setPrompt('Buscar');
+                $l->setRender('link');
+
+                $i->addLink($l);
+                $c->addItem($i);
+	    }
+
+            $t = new Template();
+            $d = new Data();
+
+            $d->setName('name');
+            $d->setValue(null);
+            $d->setPrompt('Nome do Usuário');
+            $d->setDataType('string');
+            $d->setMaxLength(100);
+            $d->setMinLength(null);
+            $d->setRequired(true);
+
+            $t->addData($d);
+            $d = new Data();
+
+            $d->setName('email');
+            $d->setValue(null);
+            $d->setPrompt('Email do Usuário');
+            $d->setDataType('string');
+            $d->setMaxLength(100);
+            $d->setMinLength(null);
+            $d->setRequired(true);
+
+            $t->addData($d);
+
+            $c->setTemplate($t);
+            $d = new Data();
+
+            $d->setName('Usuário LDAP');
+            $d->setValue(null);
+            $d->setPrompt('Usuário do LDAP');
+            $d->setDataType(null);
+            $d->setMaxLength(null);
+            $d->setMinLength(null);
+            $d->setRequired(null);
+
+            $c->setData($d);
+
+            $h->setCollection($c);
+
+	}catch (Exception $ex){
+		$error = new Error();
+		$error->setCode(Response::INTERNALSERVERERROR);
+		$error->setTitle('Internal Server Error');
+		$error->setDescription($ex);
+
+		$c->setError($error);
+		$h->setCollection($c);
+
+		$response->code = Response::INTERNALSERVERERROR;
+		$response->body = $h->getHypermedia($request->accept[10][0]);
+		return $response;
+	}
+
+	$response->body = $h->getHypermedia($request->accept[10][0]);
+	return $response;
+  }
+}
+?>
