github github
  • Home
  • Pricing and Signup
  • Training
  • Gist
  • Blog
  • Login

diogok / restserver

  • Admin
  • Watch Unwatch
  • Fork
  • Your Fork
  • Pull Request
  • Download Source
    • 6
    • 1
  • Source
  • Commits
  • Network (1)
  • Issues (0)
  • Downloads (0)
  • Wiki (1)
  • Graphs
  • Tree: f3acd66

click here to add a description

click here to add a homepage

  • Switch Branches (1)
    • master
  • Switch Tags (0)
  • Comments
  • Contributors
Sending Request…

RESTful resource/url mapping and MVC, featuring Request an Response objects. — Read more

  Cancel

http://www.phpclasses.org/browse/package/5080.html

  Cancel
  • HTTP
  • Git Read-Only

This URL has Read+Write access

Bugs fixes and Authenticator done for Basic and Digest, and phpdocs
diogok (author)
Tue Dec 01 18:03:27 -0800 2009
commit  f3acd66706cbd286da53
tree    9fc721471352df2d956a
parent  6345b06a584f9f23de95
M GenericView.class.php 4 ••••
M RestAction.class.php 2 ••
A RestAuthenticator.class.php 242 •••••
M RestClient.class.php 72 ••••
M RestController.class.php 1 •
M RestRequest.class.php 389 ••••
M RestResponse.class.php 120 ••••
M RestServer.class.php 356 ••••
M RestView.class.php 15 ••••
D tests/RestClient.test.php 42 •••••
D tests/RestServer.test.php 147 •••••
D tests/localhost/TestController.class.php 16 •••••
D tests/localhost/index.php 60 •••••
D tests/localhost/rest.php 16 •••••
Txt GenericView.class.php
  • View file @ f3acd66
... ...
@@ -11,8 +11,8 @@ class GenericView implements RestView {
11 11
 
12 12
     /**
13 13
       * Constructor of GenericView
14  
-      * @param $file=null , The script to be rendered
15  
-      * @param $props=null , Vars to be passed to the script
  14
+      * @param string $file  The script to be rendered
  15
+      * @param mixed $props  Vars to be passed to the script
16 16
       */
17 17
     function __construct($file=null,$props=null) {
18 18
         if($file != null) $this->file = $file ;
Txt RestAction.class.php
  • View file @ f3acd66
... ...
@@ -1,7 +1,7 @@
1 1
 <?php
2 2
 /**
3 3
   * Class RestAction
4  
-  * Inteface for a possible action for to be taken
  4
+  * Inteface for a possible action for to be taken by RestServer
5 5
   */
6 6
 interface RestAction {
7 7
 
Txt RestAuthenticator.class.php
  • View file @ f3acd66
... ...
@@ -0,0 +1,242 @@
  1
+<?php
  2
+
  3
+include_once 'RestServer.class.php';
  4
+
  5
+/**
  6
+ * Class RestAuthenticator
  7
+ * Responsible for dealing with both Basic and Digest authentication
  8
+ */
  9
+class RestAuthenticator {
  10
+
  11
+    private $rest ;
  12
+    
  13
+    private $user ;
  14
+    private $pwd ;
  15
+    private $authData ;
  16
+    private $isDigest =false;
  17
+    private $requireAuth =false;
  18
+
  19
+    /**
  20
+     * RestAuthenticator constructor
  21
+     * @param RestServer $rest
  22
+     */
  23
+    public function __construct(RestServer $rest=null) {
  24
+        $this->rest = $rest ;
  25
+
  26
+        if(isset($_SERVER['PHP_AUTH_DIGEST']))
  27
+            $this->authData = $_SERVER['PHP_AUTH_DIGEST'] ;                
  28
+
  29
+        if(isset($_SERVER['PHP_AUTH_USER'])) 
  30
+            $this->user = $_SERVER["PHP_AUTH_USER"];
  31
+
  32
+        if(isset($_SERVER['PHP_AUTH_PW'])) 
  33
+            $this->pwd = $_SERVER["PHP_AUTH_PW"];
  34
+
  35
+        if(isset($_SERVER["HTTP_AUTHORIZATION"])) {
  36
+            $base = base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"],6));
  37
+            $arr = explode(":",$base);
  38
+            $this->user = $arr[0];
  39
+            $this->pwd = $arr[1];
  40
+        }
  41
+        
  42
+        if (!empty($this->authData) && ($data = $this->digestParse($this->authData)) && $data['username']) {
  43
+            $this->user = $data['username'] ;
  44
+            $this->pwd = $data['response'] ;
  45
+        }
  46
+    }
  47
+    
  48
+    /**
  49
+     * Return internal RestServer
  50
+    * Return  RestServer used;
  51
+    * @return RestServer
  52
+    */
  53
+    public function getRest() {
  54
+        return $this->rest;
  55
+    }
  56
+    
  57
+    /**
  58
+    * Return user sent on BASIC Authentication
  59
+    * @return string
  60
+    */
  61
+    public function getUser() {
  62
+        return $this->user;
  63
+    }
  64
+
  65
+    /**
  66
+    * Return password sent for Authentication
  67
+    * @return string
  68
+    */
  69
+    public function getPassword() {
  70
+        return $this->pwd ;
  71
+    }
  72
+    
  73
+    /**
  74
+    * Return if is using digest authentication
  75
+    * @return bool
  76
+    */
  77
+    public function isDigest() {
  78
+        return $this->isDigest ;
  79
+    }
  80
+
  81
+    /**
  82
+    * Set if authentication should be Digest(true) 
  83
+    * @param bool $bool
  84
+    * @param string $realm
  85
+    * @return RestAuthenticator
  86
+    */
  87
+    public function forceDigest($bool=true,$realm=null) {
  88
+        if($realm != null) $this->setRealm($realm);
  89
+        $this->isDigest = $bool;
  90
+        if($bool) {$this->requireAuthentication(true);}
  91
+        return $this;
  92
+    }
  93
+
  94
+    /**
  95
+    * Get the http Realm name
  96
+    * @return string $realm
  97
+    */
  98
+    public function getRealm() {
  99
+        return $this->realm;
  100
+    }
  101
+
  102
+    /**
  103
+    * Set the http Realm name
  104
+    * @param string $realm
  105
+    * @return RestAuthenticator
  106
+    */
  107
+    public function setRealm($realm) {
  108
+        $this->realm = $realm ;
  109
+        return $this;
  110
+    }
  111
+
  112
+    /**
  113
+    * Sets if authentication is required
  114
+    * @param bool $isRequered 
  115
+    * @return RestAuthenticator
  116
+    */
  117
+    public function requireAuthentication($isRequired=true) {
  118
+        if($bol !== null) $this->requireAuth = $isRequired ;
  119
+        return $this ;
  120
+    }
  121
+    
  122
+    /**
  123
+    * Checks if authenticated is required
  124
+    * @return bool $auth;
  125
+    */
  126
+    public function isAuthenticationRequired() {
  127
+        return $this->requireAuth ;
  128
+    }
  129
+
  130
+    /**
  131
+    * Checks if is authenticated
  132
+    * @return bool $auth;
  133
+    */
  134
+    public function isAuthenticated() {
  135
+        return $this->auth ;
  136
+    }
  137
+
  138
+    /**
  139
+    * Sets authentication status
  140
+    * @param bool $auth Status
  141
+    * @return RestServer
  142
+    */
  143
+    public function setAuthenticated($bool) {
  144
+        $this->auth = $bool;
  145
+        return $this ;
  146
+    }
  147
+    
  148
+    /**
  149
+    * Test if user is authenticated, and set proper headers if not
  150
+    * @return bool
  151
+    */
  152
+    public function tryAuthenticate() {
  153
+        if($this->isAuthenticationRequired() === false) return true;
  154
+        if($this->isAuthenticated() == false) { 
  155
+            $this->getRest()->getResponse()->cleanHeader();
  156
+            $this->getRest()->getResponse()->addHeader("HTTP/1.1 401 Unauthorized");
  157
+            if($this->isDigest()) {
  158
+                $this->getRest()->getResponse()->addHeader('WWW-Authenticate: Digest ' . $this->digestHeader());
  159
+            } else {
  160
+                $this->getRest()->getResponse()->addHeader('WWW-Authenticate: Basic realm="'.$this->getRealm().'"');
  161
+            }
  162
+            $this->getRest()->getResponse()->setResponse("Unauthorized");
  163
+            return false ;
  164
+        }
  165
+        return true ;
  166
+    }
  167
+    
  168
+    /**
  169
+    * Test authentication against password for given username in Digest 
  170
+    * @param string $user
  171
+    * @param string $password
  172
+    * @return RestAuthenticator
  173
+    */
  174
+    public function validate($user,$password) {
  175
+        if($this->isDigest()) {
  176
+            $data = $this->digestParse($this->authData);
  177
+            $A1 = md5($this->getUser() . ':' . $this->getRealm() . ':' . $password);
  178
+            $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$_SERVER['REQUEST_URI']);
  179
+            $response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
  180
+            if($this->getUser() === $user && $this->getPassword() === $response) {
  181
+                $this->pwd = $password ;
  182
+                $this->setAuthenticated(true);
  183
+            } else {
  184
+                $this->setAuthenticated(false);
  185
+            }
  186
+        } else {
  187
+            if($this->getUser() === $user && $this->getPassword() === $password) {
  188
+                $this->setAuthenticated(true);
  189
+            } else {
  190
+                $this->setAuthenticated(false);
  191
+            }
  192
+        }
  193
+        return $this;
  194
+    }
  195
+    
  196
+    /**
  197
+     * Parse the digest auth message
  198
+     * @param string $message
  199
+     * @return mixed
  200
+     */
  201
+    private function digestParse($txt) {
  202
+        $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
  203
+        $data = array();
  204
+        $parts = explode(",",$txt);
  205
+        foreach($parts as $part) {
  206
+            $div = strpos($part,"=");
  207
+            $name = trim(substr($part,0,$div));
  208
+            $value = trim(substr($part,$div + 1));
  209
+            if($value[0] == "\"") {
  210
+                $value = substr($value,1, strlen($value) - 2);
  211
+            }
  212
+            unset($needed_parts[$name]);
  213
+            $data[$name] = $value;
  214
+        }
  215
+
  216
+        return $needed_parts ? false : $data;
  217
+    }    
  218
+    
  219
+    /**
  220
+     * Digest header
  221
+     * @return string
  222
+     */
  223
+    private function digestHeader() {
  224
+        $op = array(
  225
+            'realm' => $this->getRealm(),
  226
+            'domain' => '/',
  227
+            'qop' => 'auth',
  228
+            'algorithm' => 'MD5',
  229
+            'nonce' => uniqid(),
  230
+            'opaque' => md5($this->getRealm()),
  231
+            );
  232
+        $str = 'realm="'.$op['realm'].'",';
  233
+        $str .= 'qop="'.$op['qop'].'",';
  234
+        $str .= 'nonce="'.$op['nonce'].'",';
  235
+        $str .= 'opaque="'.$op['opaque'].'"';
  236
+        return $str;
  237
+    }
  238
+
  239
+    
  240
+}
  241
+
  242
+?>
Txt RestClient.class.php
  • View file @ f3acd66
... ...
@@ -25,7 +25,7 @@ class RestClient {
25 25
          curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,true);
26 26
          curl_setopt($this->curl,CURLOPT_AUTOREFERER,true); // This make sure will follow redirects
27 27
          curl_setopt($this->curl,CURLOPT_FOLLOWLOCATION,true); // This too
28  
-         curl_setopt($this->curl,CURLOPT_HEADER,true); // THis verbose option for extracting the headers
  28
+         curl_setopt($this->curl,CURLOPT_HEADER,true); // This verbose option for extracting the headers
29 29
      }
30 30
 
31 31
      /**
... ...
@@ -33,9 +33,19 @@ class RestClient {
33 33
       * @return RestClient
34 34
       */ 
35 35
      public function execute() {
  36
+         if($this->contentType != null) {
  37
+             curl_setopt($this->curl,CURLOPT_HTTPHEADER,array("Content-Type: ".$this->contentType));
  38
+         }
36 39
          if($this->method === "POST") {
37 40
              curl_setopt($this->curl,CURLOPT_POST,true);
38  
-             curl_setopt($this->curl,CURLOPT_POSTFIELDS,$this->params);
  41
+             if(is_array($this->params)) {
  42
+                 foreach($this->params as $k=>$v) {
  43
+                     $params .= "$k=$v&";
  44
+                 }
  45
+             } else {
  46
+                 $params = $this->params ;
  47
+             }
  48
+             curl_setopt($this->curl,CURLOPT_POSTFIELDS,$params);
39 49
          } else if($this->method == "GET"){
40 50
              curl_setopt($this->curl,CURLOPT_HTTPGET,true);
41 51
              $this->treatURL();
... ...
@@ -50,9 +60,6 @@ class RestClient {
50 60
          } else {
51 61
              curl_setopt($this->curl,CURLOPT_CUSTOMREQUEST,$this->method);
52 62
          }
53  
-         if($this->contentType != null) {
54  
-             curl_setopt($this->curl,CURLOPT_HTTPHEADER,array("Content-Type: ".$this->contentType));
55  
-         }
56 63
          curl_setopt($this->curl,CURLOPT_URL,$this->url);
57 64
          $r = curl_exec($this->curl);
58 65
          $this->treatResponse($r); // Extract the headers and response
... ...
@@ -95,6 +102,9 @@ class RestClient {
95 102
         $this->headers['message'] = $reg[2];
96 103
         $this->response = "";
97 104
         for($i=1;$i<count($parts);$i++) {//This make sure that exploded response get back togheter
  105
+            if(($start = strpos($parts[$i],"\n")) !== false) {
  106
+                $parts[$i] = substr($parts[$i],1);
  107
+            }
98 108
             if($i > 1) {
99 109
                 $this->response .= "\n\r";
100 110
             }
... ...
@@ -103,6 +113,7 @@ class RestClient {
103 113
      }
104 114
 
105 115
      /*
  116
+      * Array of headers
106 117
       * @return array
107 118
       */
108 119
      public function getHeaders() {
... ...
@@ -110,6 +121,7 @@ class RestClient {
110 121
      }
111 122
 
112 123
      /*
  124
+      * Response body
113 125
       * @return string
114 126
       */ 
115 127
      public function getResponse() {
... ...
@@ -223,7 +235,7 @@ class RestClient {
223 235
 
224 236
      /**
225 237
       * Creates the RESTClient
226  
-      * @param string $url=null [optional]
  238
+      * @param string $url
227 239
       * @return RestClient
228 240
       */
229 241
      public static function createClient($url=null) {
... ...
@@ -237,51 +249,51 @@ class RestClient {
237 249
      /**
238 250
       * Convenience method wrapping a commom POST call
239 251
       * @param string $url
240  
-      * @param mixed params
241  
-      * @param string $user=null [optional]
242  
-      * @param string $password=null [optional]
243  
-      * @param string $contentType="multpary/form-data" [optional] commom post (multipart/form-data) as default
  252
+      * @param mixed $params
  253
+      * @param string $user
  254
+      * @param string $password
  255
+      * @param string $contentType 
244 256
       * @return RestClient
245 257
       */
246  
-     public static function post($url,$params=null,$user=null,$pwd=null,$contentType="multipart/form-data") {
247  
-         return self::call("POST",$url,$params,$user,$pwd,$contentType);
  258
+     public static function post($url,$params=null,$user=null,$password=null,$contentType="application/x-www-form-urlencoded") {
  259
+         return self::call("POST",$url,$params,$user,$password,$contentType);
248 260
      }
249 261
 
250 262
      /**
251 263
       * Convenience method wrapping a commom PUT call
252 264
       * @param string $url
253 265
       * @param string $body 
254  
-      * @param string $user=null [optional]
255  
-      * @param string $password=null [optional]
256  
-      * @param string $contentType=null [optional] 
  266
+      * @param string $user
  267
+      * @param string $password
  268
+      * @param string $contentType 
257 269
       * @return RestClient
258 270
       */
259  
-     public static function put($url,$body,$user=null,$pwd=null,$contentType=null) {
260  
-         return self::call("PUT",$url,$body,$user,$pwd,$contentType);
  271
+     public static function put($url,$body,$user=null,$password=null,$contentType=null) {
  272
+         return self::call("PUT",$url,$body,$user,$password,$contentType);
261 273
      }
262 274
 
263 275
      /**
264 276
       * Convenience method wrapping a commom GET call
265 277
       * @param string $url
266 278
       * @param array params
267  
-      * @param string $user=null [optional]
268  
-      * @param string $password=null [optional]
  279
+      * @param string $user
  280
+      * @param string $password
269 281
       * @return RestClient
270 282
       */
271  
-     public static function get($url,array $params=null,$user=null,$pwd=null) {
272  
-         return self::call("GET",$url,$params,$user,$pwd);
  283
+     public static function get($url,array $params=null,$user=null,$password=null) {
  284
+         return self::call("GET",$url,$params,$user,$password);
273 285
      }
274 286
 
275 287
      /**
276 288
       * Convenience method wrapping a commom delete call
277 289
       * @param string $url
278 290
       * @param array params
279  
-      * @param string $user=null [optional]
280  
-      * @param string $password=null [optional]
  291
+      * @param string $user
  292
+      * @param string $password
281 293
       * @return RestClient
282 294
       */
283  
-     public static function delete($url,array $params=null,$user=null,$pwd=null) {
284  
-         return self::call("DELETE",$url,$params,$user,$pwd);
  295
+     public static function delete($url,array $params=null,$user=null,$password=null) {
  296
+         return self::call("DELETE",$url,$params,$user,$password);
285 297
      }
286 298
 
287 299
      /**
... ...
@@ -289,16 +301,16 @@ class RestClient {
289 301
       * @param string $method
290 302
       * @param string $url
291 303
       * @param string $body 
292  
-      * @param string $user=null [optional]
293  
-      * @param string $password=null [optional]
294  
-      * @param string $contentType=null [optional] 
  304
+      * @param string $user
  305
+      * @param string $password
  306
+      * @param string $contentType 
295 307
       * @return RestClient
296 308
       */
297  
-     public static function call($method,$url,$body,$user=null,$pwd=null,$contentType=null) {
  309
+     public static function call($method,$url,$body,$user=null,$password=null,$contentType=null) {
298 310
          return self::createClient($url)
299 311
              ->setParameters($body)
300 312
              ->setMethod($method)
301  
-             ->setCredentials($user,$pwd)
  313
+             ->setCredentials($user,$password)
302 314
              ->setContentType($contentType)
303 315
              ->execute()
304 316
              ->close();
Txt RestController.class.php
  • View file @ f3acd66
... ...
@@ -9,7 +9,6 @@ interface RestController extends RestAction {
9 9
        * Execute the Default action of this controller
10 10
        * @param RestServer $restServer
11 11
        * @return RestAction $restVieworController
12  
-       *
13 12
      * */
14 13
     function execute(RestServer $restServer) ;
15 14
 }
Txt RestRequest.class.php
  • View file @ f3acd66
... ...
@@ -9,110 +9,45 @@ class RestRequest {
9 9
 
10 10
     private $requestURI ;
11 11
     private $URIParts ; 
12  
-        
13  
-    private $user ;
14  
-    private $pwd ;
15  
-    private $authData ;
16  
-  
17  
-  private $requestMethod ;
18  
-  private $get ;
19  
-  private $post ;
  12
+
  13
+    private $requestMethod ;
  14
+    private $get ;
  15
+    private $post ;
20 16
     private $files ;
21  
-  
  17
+
22 18
     /**
23  
-      * Constructor of RestRequest
24  
-      * @param RestServer $rest = null, Parent RestServer
25  
-      */
  19
+    * Constructor of RestRequest
  20
+    * @param RestServer $rest = null, Parent RestServer
  21
+    */
26 22
     public function __construct(RestServer $rest=null) {
27 23
 
28 24
         // Sets most of the parameters
29 25
         $this->rest = $rest ;
30  
-            
  26
+
31 27
         if(isset($_SERVER["REQUEST_METHOD"]))
32 28
             $this->requestMethod = $_SERVER["REQUEST_METHOD"];
33 29
         if(isset($_SERVER["REQUEST_URI"]))
34 30
             $this->requestURI = $_SERVER["REQUEST_URI"];
35 31
         $this->URIParts = explode("/",$this->requestURI);
36  
-                
37  
-        if(isset($_SERVER['PHP_AUTH_DIGEST']))
38  
-            $this->authData = $_SERVER['PHP_AUTH_DIGEST'] ;                
39  
-
40  
-        if(isset($_SERVER['PHP_AUTH_USER'])) 
41  
-            $this->user = $_SERVER["PHP_AUTH_USER"];
42 32
 
43  
-        if(isset($_SERVER['PHP_AUTH_PW'])) 
44  
-            $this->pwd = $_SERVER["PHP_AUTH_PW"];
45  
-
46  
-        if(isset($_SERVER["HTTP_AUTHORIZATION"])) {
47  
-            $base = base64_decode(substr($_SERVER["HTTP_AUTHORIZATION"],6));
48  
-            $arr = explode(":",$base);
49  
-            $this->user = $arr[0];
50  
-            $this->pwd = $arr[1];
51  
-        }
52  
-
53  
-      $authData = $this->authData ;
54  
-      if (!empty($authData) && ($data = $this->digestParse($authData)) && $data['username']) {
55  
-            $this->user = $data['username'] ;
56  
-            $this->password = $data['response'] ;
57  
-        }
  33
+        $this->get = $_GET?$_GET:array() ;
  34
+        $this->post = $_POST?$_POST:array() ;
  35
+        $this->files = $_FILES?$_FILES:array() ;
58 36
 
59  
-    $this->get = $_GET ;
60  
-    $this->post = $_POST ;
61  
-        $this->files = $_FILES ;
62  
-    
63  
-    }
64  
- 
65  
-    /**
66  
-      * Test authentication against password for given username in Digest authencitation
67  
-      * @param string $user
68  
-      * @param string $password
69  
-      * @return RestRequest 
70  
-      */
71  
-    public function validAuth($user,$password) {
72  
-        $bkp = $password;
73  
-        if($this->rest->isDigest()) {
74  
-            $authData = $this->authData ;
75  
-            if (!empty($authData) && ($data = $this->digestParse($authData)) && $data['username']) {
76  
-                $A1 = md5($this->getUser() . ':' . $this->getRest()->getRealm() . ':' . $password);
77  
-                $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$_SERVER['REQUEST_URI']);
78  
-                $password = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);
79  
-            }
80  
-        }
81  
-        if($this->getUser() === $user && $this->getPassword() === $password) {
82  
-            $this->getRest()->setAuth(true);
83  
-            $this->password = $password ;
84  
-            $this->password = $pwd ;
85  
-        }
86  
-        return $this->getRest();
87 37
     }
88 38
 
89 39
     /**
90  
-      * Return  RestServer used;
91  
-      * @return RestServer
92  
-      */
  40
+    * Return  RestServer used;
  41
+    * @return RestServer
  42
+    */
93 43
     public function getRest() {
94 44
         return $this->rest;
95 45
     }
96  
-    private function digestParse($txt) {
97  
-        // protect against missing data
98  
-        $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
99  
-        $data = array();
100  
-        // fix elements with missing "
101  
-        $txt = preg_replace('@=([^\'"])([^\s,]+)@', '="\1\2"', $txt);
102  
-        preg_match_all('@(\w+)=(?:([\'"])([^\2]+)\2|([^\s,]+))@U', $txt, $matches, PREG_SET_ORDER);
103  
-
104  
-        foreach ($matches as $m) {
105  
-            $data[$m[1]] = trim($m[3] ? $m[3] : $m[4]);
106  
-            unset($needed_parts[$m[1]]);
107  
-        }
108  
-
109  
-        return $needed_parts ? false : $data;
110  
-    }
111 46
 
112 47
     /**
113  
-      * Returns if Request is GET
114  
-      * @return boolean
115  
-      */
  48
+    * Returns if Request is GET
  49
+    * @return boolean
  50
+    */
116 51
     public function isGet() {
117 52
         if($this->requestMethod == "GET") {
118 53
             return true ;
... ...
@@ -121,200 +56,200 @@ class RestRequest {
121 56
     }
122 57
 
123 58
     /** 
124  
-      * Returns if Request is POST
125  
-      * @return boolean
126  
-      */
  59
+    * Returns if Request is POST
  60
+    * @return boolean
  61
+    */
127 62
     public function isPost() {
128  
-       if($this->requestMethod == "POST") {
129  
-           return true ;
130  
-       }
131  
-       return false;
  63
+        if($this->requestMethod == "POST") {
  64
+            return true ;
  65
+        }
  66
+        return false;
132 67
     }
133 68
 
134 69
     /**
135  
-      * Return if Request is PUT
136  
-      * @return boolean
137  
-      */
  70
+    * Return if Request is PUT
  71
+    * @return boolean
  72
+    */
138 73
     public function isPut() {
139  
-       if($this->requestMethod == "PUT") {
140  
-           return true ;
141  
-       }
142  
-       return false;
  74
+        if($this->requestMethod == "PUT") {
  75
+            return true ;
  76
+        }
  77
+        return false;
143 78
     }
144 79
 
145 80
     /**
146  
-      * Return true if Request is DELETE
147  
-      * @return boolean
148  
-      */
  81
+    * Return true if Request is DELETE
  82
+    * @return boolean
  83
+    */
149 84
     public function isDelete() {
150  
-       if($this->requestMethod == "DELETE") {
151  
-           return true ;
152  
-       }
153  
-       return false;
  85
+        if($this->requestMethod == "DELETE") {
  86
+            return true ;
  87
+        }
  88
+        return false;
154 89
     }
155  
-  
  90
+
156 91
 
157 92
     /** 
158  
-      * Get parameters sent with GET (url parameters)
159  
-      * @return array
160  
-      */
  93
+    * Get parameters sent with GET (url parameters)
  94
+    * @param mixed $k get[$key]
  95
+    * @return mixed
  96
+    */
161 97
     public function getGet($k=null) {
162 98
         if($k==null) return $this->get ;
163 99
         else return $this->get[$k] ;
164 100
     }
165 101
 
166 102
     /**
167  
-      * Return parameters sent on a POST
168  
-      * @return array
169  
-      */
  103
+    * Return parameters sent on a POST
  104
+    * @param mixed $k post[$key]
  105
+    * @return mixed
  106
+    */
170 107
     public function getPost($k=null) {
171 108
         if($k==null) return $this->post ;
172 109
         else return $this->post[$k] ;
173 110
     }
174 111
 
  112
+    /**
  113
+    * Return FILES sent on a POSt
  114
+    * @param mixed $k file[$key]
  115
+    * @return mixed
  116
+    */
175 117
     public function getFiles($k=null) {
176 118
         if($k==null) return $this->files ;
177 119
         else return $this->files[$k];
178 120
     }
179 121
 
180 122
     /**
181  
-      * Return content sent with PUT
182  
-      * @param $key=null
183  
-      * @return mixed 
184  
-      */
  123
+    * Return content sent with PUT
  124
+    * @param mixed $k
  125
+    * @return mixed 
  126
+    */
185 127
     public function getPut($k=null) {
186  
-       $_PUT  = array();
187  
-       if($_SERVER['REQUEST_METHOD'] == 'PUT') {
188  
-           $putdata = file_get_contents('php://input');
189  
-           $exploded = explode('&', $putdata); 
190  
-           foreach($exploded as $pair) {
191  
-               $item = explode('=', $pair);
192  
-               if(count($item) == 2) {
  128
+        $_PUT  = array();
  129
+        if($_SERVER['REQUEST_METHOD'] == 'PUT') {
  130
+            $putdata = file_get_contents('php://input');
  131
+            $exploded = explode('&', $putdata); 
  132
+            foreach($exploded as $pair) {
  133
+                $item = explode('=', $pair);
  134
+                if(count($item) == 2) {
193 135
                    $_PUT[urldecode($item[0])] = urldecode($item[1]);
194  
-               }
195  
-           }
196  
-      }
197  
-      if($k==null)return $_PUT ;
198  
-      else return $_PUT[$k];
  136
+                }
  137
+            }
  138
+        }
  139
+        if($k==null)return $_PUT ;
  140
+        else return $_PUT[$k];
199 141
     }
200 142
 
201 143
 
202 144
     /**
203  
-      * Return request BODY
204  
-      * @return string 
205  
-      */
  145
+    * Return request BODY
  146
+    * @return string 
  147
+    */
206 148
     public function getBody() {
207  
-      $data = file_get_contents('php://input');
208  
-      return $data;
  149
+        $data = file_get_contents('php://input');
  150
+        return $data;
209 151
     }
210 152
 
211 153
     /**
212  
-      * Get authentication data on DIGEST
213  
-      * @return mixed
214  
-      */
215  
-   public function getAuthData() {
216  
-      return $this->authData;
217  
-   }
218  
-   
219  
-   /**
220  
-     * Return user sent on BASIC Authentication
221  
-     * @return string
222  
-     */
223  
-   public function getUser() {
224  
-       return $this->user;
225  
-   }
226  
-        
227  
-   /**
228  
-     * Return password sent on Basic Authentication
229  
-     * @return string
230  
-     */
231  
-   public function getPassword() {
232  
-       return $this->pwd ;
233  
-   }
234  
-    
235  
-   /**
236  
-     * Return Request Method(PUT, DELETE, OPTION, GET...)
237  
-     * return string
238  
-     */
239  
-   public function getMethod() {
240  
-      return $this->requestMethod ;
241  
-   }
242  
-        
243  
-   /**
244  
-     * Set request method
245  
-     * @param string $method
246  
-     * @return  RestRequest
247  
-     */
248  
-   public function setMethod($m) {
249  
-       $this->requestMethod = $m ;
250  
-       return $this;
251  
-   }
252  
-  
253  
-   /**
254  
-     * Return the URI requested
255  
-     * @return string
256  
-     */
257  
-   public function getRequestURI() {
258  
-       return $this->requestURI ;
259  
-   }
260  
-
261  
-   /**
262  
-     * Return part of the URL
263  
-     * return string
264  
-     */
265  
-   public function getURIpart($i) {
266  
-       if(isset($this->URIParts[$i]))
  154
+    * Return user sent on BASIC Authentication
  155
+    * @return string
  156
+    */
  157
+    public function getUser() {
  158
+        return $this->rest->getAuthenticator()->getUser();
  159
+    }
  160
+
  161
+    /**
  162
+    * Return password sent on Basic Authentication
  163
+    * @return string
  164
+    */
  165
+    public function getPassword() {
  166
+        return $this->rest->getAuthenticator()->getPassword();
  167
+    }
  168
+
  169
+    /**
  170
+    * Return Request Method(PUT, DELETE, OPTION, GET...)
  171
+    * @return string
  172
+    */
  173
+    public function getMethod() {
  174
+        return $this->requestMethod ;
  175
+    }
  176
+
  177
+    /**
  178
+    * Set request method
  179
+    * @param string $method
  180
+    * @return RestRequest
  181
+    */
  182
+    public function setMethod($method) {
  183
+        $this->requestMethod = $method ;
  184
+        return $this;
  185
+    }
  186
+
  187
+    /**
  188
+    * Return the URI requested
  189
+    * @return string
  190
+    */
  191
+    public function getRequestURI() {
  192
+        return $this->requestURI ;
  193
+    }
  194
+
  195
+    /**
  196
+    * Return part of the URL
  197
+    * @param int $i part of the uri
  198
+    * @return string
  199
+    */
  200
+    public function getURIpart($i) {
  201
+        if(isset($this->URIParts[$i]))
267 202
             return $this->URIParts[$i];
268 203
         else
269 204
             return null;
270  
-   }
271  
-
272  
-   /**
273  
-     * Return the URI or part of it
274  
-     * @param $part=null, count of the part
275  
-     * @return string
276  
-     */
277  
-   public function getURI($i=null) {
  205
+    }
  206
+
  207
+    /**
  208
+    * Return the URI or part of it
  209
+    * @param int $i part of the uri
  210
+    * @return string
  211
+    */
  212
+    public function getURI($i=null) {
278 213
         if($i !== null) return $this->getURIpart($i);
279 214
         return $this->getRequestURI() ;
280  
-   }
281  
-
282  
-   /**
283  
-     * Sets the URI to deal
284  
-     * @param string $uri
285  
-     * @return RestRequest $url
286  
-     */
287  
-   public function setURI($url) {
288  
-    $this->requestURI = $url;
  215
+    }
  216
+
  217
+    /**
  218
+    * Sets the URI to deal
  219
+    * @param string $uri
  220
+    * @return RestRequest 
  221
+    */
  222
+    public function setURI($uri) {
  223
+        $this->requestURI = $uri;
289 224
         $this->URIParts = explode("/",$this->requestURI);
290 225
         return $this ;
291  
-   }
292  
-
293  
-   /**
294  
-     * Return the extension of the URI (if any)
295  
-     * @return string
296  
-     */
297  
-   public function getExtension() {
298  
-       $reg = array();
299  
-       preg_match('@\.([a-zA-Z0-9]{1,5})$@',$this->rest->getQuery(),$reg);
300  
-       if(isset($reg[1]))
301  
-           return $reg[1];
302  
-       else
303  
-           return false;
304  
-   }
305  
-  
306  
-   /**
307  
-     * Return true if given mime is accepted
308  
-     * @param string $mime to check
309  
-     * @return boolean
310  
-     */
311  
-   public function acceptMime($mime) {
312  
-        if(strpos($_SERVER["HTTP_ACCEPT"],$mime) > 0) {
  226
+    }
  227
+
  228
+    /**
  229
+    * Return the extension of the URI (if any)
  230
+    * @return string
  231
+    */
  232
+    public function getExtension() {
  233
+        $reg = array();
  234
+        preg_match('@\.([a-zA-Z0-9]{1,5})$@',$this->getURI(),$reg);
  235
+        if(isset($reg[1]))
  236
+            return $reg[1];
  237
+        else
  238
+            return false;
  239
+    }
  240
+
  241
+    /**
  242
+    * Return true if given mime is accepted
  243
+    * @param string $mime to check
  244
+    * @return boolean
  245
+    */
  246
+    public function acceptMime($mime) {
  247
+        if(($pos = strpos($_SERVER["HTTP_ACCEPT"],$mime)) !== false) {
313 248
             return true ;
314 249
         } else {
315 250
             return false ;
316 251
         }
317  
-   }
  252
+    }
318 253
 
319 254
 }
320 255
 ?>
Txt RestResponse.class.php
  • View file @ f3acd66
... ...
@@ -8,87 +8,101 @@ class RestResponse {
8 8
 
9 9
     private $headers ;
10 10
     private $response ;
  11
+    private $relm = "RESTful";
  12
+    private $useDigest = false;
11 13
 
12 14
     /** 
13  
-      * Constructor of RestServer
14  
-      * @param RestServer $rest
15  
-      */
16  
-    function __contruct($rest=null) {
  15
+    * Constructor of RestServer
  16
+    * @param RestServer $rest
  17
+    */
  18
+    public function __contruct(RestServer $rest=null) {
17 19
         $this->rest = $rest ;
18 20
     }
19 21
 
  22
+
20 23
     /**
21  
-      * Set the response to null
22  
-      * @return RestResponse
23  
-      */
24  
-    public function cleanResponse() {
25  
-        $this->response = null ;
26  
-        return $this ;
27  
-    }
28  
-  
29  
-    /**
30  
-      * Adds a header to the response
31  
-      * @param string $header
32  
-      * @return RestResponse
33  
-      */
34  
-  public function addHeader($header) {
  24
+    * Adds a header to the response
  25
+    * @param string $header
  26
+    * @return RestResponse
  27
+    */
  28
+    public function addHeader($header) {
35 29
         $this->headers[] = $header;
36 30
         return $this  ;
37  
-  }
38  
-  
  31
+    }
  32
+
39 33
     /**
40  
-      * Clean the headers set on the response
41  
-      * @return RestResponse
42  
-      */
43  
-  public function cleanHeader() {
  34
+    * Clean the headers set on the response
  35
+    * @return RestResponse
  36
+    */
  37
+    public function cleanHeader() {
44 38
         $this->headers = Array();
45 39
         return $this ;
46  
-  }
47  
-  
  40
+    }
  41
+
48 42
     /**
49  
-      * Show the headers
50  
-      */
51  
-  public function showHeader() {
  43
+    * Show the headers
  44
+    * @return RestResponse
  45
+    */
  46
+    public function showHeader() {
52 47
         if(count($this->headers) >=1) {
53 48
             foreach($this->headers as $value) {
54 49
                 header($value);
55 50
             }
56 51
         }
57 52
         return $this ;
58  
-  }
59  
-  
  53
+    }
  54
+
60 55
     /**
61  
-      * Check if headers were sent
62  
-      * @return bool
63  
-      */
64  
-  public function headerSent() {
  56
+    * Check if headers were sent
  57
+    * @return bool
  58
+    */
  59
+    public function headerSent() {
65 60
         return headers_sent();
66  
-  }
67  
-  
  61
+    }
  62
+
68 63
     /**
69  
-      * Set the response
70  
-      * @param mixed $response
71  
-      * @return RestResponse
72  
-      */
73  
-  public function setResponse($response) {
  64
+    * Set the response
  65
+    * @param mixed $response
  66
+    * @return RestResponse
  67
+    */
  68
+    public function setResponse($response) {
74 69
         $this->response = $response ;
75 70
         return $this ;
76  
-  }
77  
-  
  71
+    }
  72
+
  73
+    /**
  74
+    * Set the response to null
  75
+    * @return RestResponse
  76
+    */
  77
+    public function cleanResponse() {
  78
+        $this->response = null ;
  79
+        return $this ;
  80
+    }
  81
+
78 82
     /**
79  
-      * Add a string to the response, only work if response is a string
80  
-      * @param string $response
81  
-      * @return RestResponse
82  
-      */
83  
-  public function addResponse($response) {
  83
+    * Add a string to the response, only work if response is a string
  84
+    * @param string $response
  85
+    * @return RestResponse
  86
+    */
  87
+    public function appendResponse($response) {
84 88
         $this->response .= $response ;
85 89
         return $this ;
86  
-  }
  90
+    }
  91
+
  92
+    /**
  93
+    * Add a string to the response, only work if response is a string
  94
+    * @param string $response
  95
+    * @return RestResponse
  96
+    */
  97
+    public function addResponse($response) {
  98
+        $this->response .= $response ;
  99
+        return $this ;
  100
+    }
87 101
 
88 102
     /**
89  
-      * Return the reponse set
90  
-      * @return mixed $response;
91  
-      */
  103
+    * Return the reponse set
  104
+    * @return mixed $response;
  105
+    */
92 106
     public function getResponse() {
93 107
         return $this->response ;
94 108
     }
Txt RestServer.class.php
  • View file @ f3acd66
... ...
@@ -1,327 +1,227 @@
1 1
 <?php
2  
-            
  2
+
3 3
 include_once 'RestAction.class.php';
4 4
 include_once 'RestController.class.php';
5 5
 include_once 'RestView.class.php';
6 6
 include_once 'RestRequest.class.php';
7 7
 include_once 'RestResponse.class.php';
  8
+include_once 'RestAuthenticator.class.php';
8 9
 
9 10
 /**
10  
-  * Class RestServer 
11  
-  * Is the front controller for mapping URL to controllers and dealing with Request/Response and Headers
12  
-  * Made with Restful webservices in mind.
13  
-  * By Diogo Souza da Silva <manifesto@manifesto.blog.br>
14  
-  */
  11
+* Class RestServer 
  12
+* Is the front controller for mapping URL to controllers and dealing with Request/Response and Headers
  13
+* Made with Restful webservices in mind.
  14
+* By Diogo Souza da Silva <manifesto@manifesto.blog.br>
  15
+*/
15 16
 class RestServer {
16  
-  
17  
-    private $auth = true;
18  
-    private $requireAuth = false ;
19  
-    private $relm = "RESTful";
20  
-    private $useDigest = false;
21  
-  
22  
-  private $response ;
  17
+
  18
+    private $response ;
23 19
     private $request ;
24  
-  private $headerOn = false ;
25  
-  
26  
-  private $baseUrl ; 
27  
-  private $query ;
28  
-  private $qPart;
29  
-  
30  
-  private $map ;
  20
+    private $authenticator ;
  21
+
  22
+    private $baseUrl ; 
  23
+    private $query ;
  24
+    private $qPart;
  25
+
  26
+    private $map ;
31 27
     private $params ;
32 28
     private $stack ;
33  
-  
  29
+
34 30
     /** Contructor of RestServer
35  
-      * @param string $query Optional query to be treat as the URL
36  
-      * @return RestServer $rest;
37  
-     */
  31
+    * @param string $query Optional query to be treat as the URL
  32
+    * @return RestServer $rest;
  33
+    */
38 34
     public function __construct($query=null) {
39 35
         $this->request = new RestRequest($this); // Request handler
40 36
         $this->response = new RestResponse($this); // Response holder
41  
-            
  37
+        $this->authenticator = new RestAuthenticator($this); // Authenticator holder
  38
+
42 39
         if(isset($_SERVER["HTTP_HOST"]))
43 40
             $this->baseUrl = "http://".$_SERVER["HTTP_HOST"].dirname($_SERVER["SCRIPT_NAME"]);
44  
-        
  41
+
45 42
         // If will use custom URI or HTTP requested URI
46 43
         if($query===null) $this->query = $this->getRequest()->getRequestURI() ;
47 44
         else $this->query = $query ;
48 45
 
49 46
         $this->getRequest()->setURI($this->query);
50 47
 
51  
-    $this->qPart = explode("/",$this->query);
  48
+        $this->qPart = explode("/",$this->query);
52 49
     }
53  
-    
  50
+
54 51
     /**
55  
-       * Sets a parameter in a global scope that can be recovered at any request.
56  
-       * @param mixed $key The identifier of the parameter
57  
-       * @param mixed $value The content of the parameter
58  
-       * @return RestServer $this
59  
-       */
  52
+    * Sets a parameter in a global scope that can be recovered at any request.
  53
+    * @param mixed $key The identifier of the parameter
  54
+    * @param mixed $value The content of the parameter
  55
+    * @return RestServer $this
  56
+    */
60 57
     public function setParameter($key,$value) {
61 58
         $this->params[$key] = $value ;
62 59
         return $this ;
63 60
     }
64 61
 
65 62
     /**
66  
-      * Return the specified parameter
67  
-      * @param mixed $key The parameter identifier
68  
-       */
  63
+    * Return the specified parameter
  64
+    * @param mixed $key The parameter identifier
  65
+    * @return mixed
  66
+    */
69 67
     public function getParameter($key) {
70 68
         return $this->params[$key];
71 69
     }
72  
-    
73  
-    /**
74  
-      * Set the URL to be handle or part of it
75  
-      * @param mixed $value The url
76  
-      * @param int $key Optional, the part of the url to change
77  
-      * @return RestServer $this
78  
-      */
79  
-  public function setQuery($value,$k=null) {
80  
-       if($k !== null){
81  
-           $this->qPart[$k]  = $value ;               
82  
-       } else {
83  
-         $this->query = $value ;
84  
-         $this->qPart = explode("/",$value );
85  
-       }
86  
-       return $this ;
87  
-  }
88  
-  
  70
+
89 71
     /** 
90  
-      * Maps a Method and URL for a Class
91  
-      * @param string $method The method to be associated
92  
-      * @param string $uri The URL to be accossiated
93  
-      * @param string $class The name of the class to be called, it must implement RestAction
94  
-      * @return RestServer $this
95  
-      */
96  
-  public function addMap($method,$uri,$class) {
97  
-       $this->map[$method][$uri] = $class ;
98  
-       return $this ;
99  
-  }
100  
-       /**
101  
-         * Checks if is authenticated
102  
-         * @return boolean $auth;
103  
-         */
104  
-    public function isAuth() {
105  
-       return $this->auth ;
  72
+    * Maps a Method and URL for a Class
  73
+    * @param string $method The method to be associated
  74
+    * @param string $uri The URL to be accossiated
  75
+    * @param string $class The name of the class to be called, it must implement RestAction
  76
+    * @return RestServer $this
  77
+    */
  78
+    public function addMap($method,$uri,$class) {
  79
+        $this->map[$method][$uri] = $class ;
  80
+        return $this ;
106 81
     }
107  
-        /**
108  
-          * Sets authentication status
109  
-          * @param boolean $auth Status
110  
-          * @return RestServer
111  
-          */
112  
-    public function setAuth($bool) {
113  
-      $this->auth = $bool;
114  
-       return $this ;
  82
+
  83
+    /**
  84
+    * Set the URL to be handle or part of it
  85
+    * @param mixed $value The url
  86
+    * @param int $k the part of the url to change
  87
+    * @return RestServer $this
  88
+    */
  89
+    public function setQuery($value,$k=null) {
  90
+        if($k !== null){
  91
+            $this->qPart[$k]  = $value ;               
  92
+        } else {
  93
+            $this->query = $value ;
  94
+            $this->qPart = explode("/",$value );
  95
+            $this->getRequest()->setURI($value);
  96
+        }
  97
+        return $this ;
115 98
     }
116  
-   
  99
+
117 100
     /**
118  
-      * Get the URL or part of it, depreciated by RestRequest::getURI();
119  
-      **/
  101
+    * Get the URL or part of it, depreciated by RestRequest::getURI();
  102
+    * @param $k uri part
  103
+    * @return string
  104
+    **/
120 105
     public function getQuery($k=null) { 
121  
-       if($k !== null){
122  
-          return $this->qPart[$k];
  106
+        if($k !== null){
  107
+            return $this->qPart[$k];
123 108
         }
124 109
         return $this->query ;
125 110
     }  
126  
-  
  111
+
127 112
     /**
128  
-      * Get the baseurl, based on website location (eg. localhost/website or website.com/);
129  
-      * @return string;
130  
-      **/
131  
-  public function getBaseUrl() {
  113
+    * Get the baseurl, based on website location (eg. localhost/website or website.com/);
  114
+    * @return string
  115
+    **/
  116
+    public function getBaseUrl() {
132 117
         return $this->baseUrl ;
133  
-  }
  118
+    }
134 119
 
135 120
     /**
136  
-      * Get the Response handler object
137  
-      * @return RestResponse
138  
-      */
139  
-  public function getResponse() {
  121
+    * Get the Response handler object
  122
+    * @return RestResponse
  123
+    */
  124
+    public function getResponse() {
140 125
         return $this->response ;
141  
-  }
142  
-  
143  
-    /** Get the Request handler object
144  
-      * @return RestRequest
145  
-      */
  126
+    }
  127
+
  128
+    /**
  129
+     * Get the Request handler object
  130
+    * @return RestRequest
  131
+    */
146 132
     public function getRequest() {
147 133
         return $this->request ;
148 134
     }
149 135
 
150 136
     /**
151  
-      * Get the class for specified method and uri
152  
-      * @param string $method
153  
-      * @param string $uri
154  
-      * @return string
155  
-      */
156  
-  public function getMap($method,$uri) {
  137
+     * Get the Authentication handler object
  138
+    * @return RestAuthenticator
  139
+    */
  140
+    public function getAuthenticator() {
  141
+        return $this->authenticator ;
  142
+    }
  143
+
  144
+    /**
  145
+    * Get the class for specified method and uri
  146
+    * @param string $method
  147
+    * @param string $uri
  148
+    * @return string
  149
+    */
  150
+    public function getMap($method,$uri) {
157 151
         $maps = $this->map[$method];
158 152
         if(count($maps) < 1) return false;
159 153
         foreach($maps as $map=>$class) {
160 154
             if(preg_match("%^".$map."$%",$uri) ) {
161  
-                 return $class ;
  155
+                return $class ;
162 156
             }
163 157
         }
164 158
         return false ;
165  
-  }
166  
-
167  
-    /**
168  
-      * Set if authentication should be Digest(true) or Basic(false)
169  
-      * @param booblean $useDigest
170  
-      * @return RestServer
171  
-      */
172  
-    public function useDigest($boolean=true) {
173  
-        $this->useDigest = $boolean;
174  
-        return $this;
175  
-    }
176  
-
177  
-    /**
178  
-      * return true if should use Digest authentication
179  
-      * @return boolean
180  
-      */
181  
-    public function isDigest() {
182  
-        return $this->useDigest;
183 159
     }
184 160
 
185 161
     /**
186  
-      * Get the http Realm name
187  
-      * @return string $realm
188  
-      */
189  
-    public function getRealm() {
190  
-        return $this->realm;
191  
-    }
192  
-
193  
-    /**
194  
-      * Set the http Realm name
195  
-      * @param string $realm
196  
-      * @return RestServer
197  
-      */
198  
-    public function setRealm($realm) {
199  
-        $this->realm = $realm ;
200  
-        return $this;
201  
-    }
202  
-  
203  
-    private function digestString() {
204  
-        $opt = array(
205  
-            'realm' => $this->getRealm(),
206  
-            'domain' => '/',
207  
-            'qop' => 'auth',
208  
-            'algorithm' => 'MD5',
209  
-            'nonce' => uniqid(),
210  
-            'opaque' => md5($this->getRealm()),
211  
-        );
212  
-        $str = 'realm="'.$op['realm'].'",';
213  
-        $str .= 'qop="'.$op['qop'].'",';
214  
-        $str .= 'nonce="'.$op['nonce'].'",';
215  
-        $str .= 'opaque="'.$op['opaque'].'"';
216  
-        return $str;
217  
-    }
218  
-
219  
-    /** 
220  
-      * Unauthorize the request
221  
-      * $return RestServer
222  
-      */
223  
-    public function unAuth() {
224  
-        $this->getResponse()->cleanHeader();
225  
-        $this->getResponse()->addHeader("HTTP/1.1 401 Unauthorized");
226  
-        if($this->useDigest) {
227  
-            $rest->getResponse()->addHeader('WWW-Authenticate: Digest ' . $this->digestString());
228  
-        } else {
229  
-            $this->getResponse()->addHeader('WWW-Authenticate: Basic realm="'.$this->getRealm().'"');
230  
-        }
231  
-        $this->getResponse()->setResponse("Unauthorized");                  
232  
-        return $this ;
233  
-    }
234  
-
235  
-    private function testAuth() {
236  
-        if($this->requireAuth === false) return true;
237  
-        if(!$this->auth) { 
238  
-            $this->unAuth();
239  
-            return false ;
240  
-        }
241  
-        return true ;
242  
-    }
243  
-
244  
-    /**
245  
-      * Sets if authentication is required
246  
-      * @param boolean $isRequered Status to request, if null is given nothing changes
247  
-      * @return boolean if is required;
248  
-      */
249  
-    public function requireAuth($bol=null) {
250  
-        if($bol !== null) $this->requireAuth = $bol ;
251  
-        return $this->requireAuth ;
252  
-    }
253  
-
254  
-    /**
255  
-      * Return last class name from RestServer stack trace
256  
-      * return string 
257  
-      */
  162
+    * Return last class name from RestServer stack trace
  163
+    * @return string 
  164
+    */
258 165
     public function lastClass() {
259 166
         $i = count($this->stack);
260 167
         return $this->stack[$i - 1];
261 168
     }
262 169
 
263 170
     /**
264  
-      * Run the Server to handle the request and prepare the response
265  
-      * @return string $responseContent
266  
-      */
267  
-  public function execute() {
268  
-            
269  
-        if(!$this->testAuth()) return $this->show(); // If auth is required and its not ok, response is 401
270  
-           
  171
+    * Run the Server to handle the request and prepare the response
  172
+    * @return string $responseContent
  173
+    */
  174
+    public function execute() {
  175
+        if(!$this->getAuthenticator()->tryAuthenticate()) {
  176
+            return $this->show(); // If auth is required and its not ok, response is 401
  177
+        }
  178
+
271 179
         // This is the class name to call
272 180
         $responseClass = $this->getMap($this->getRequest()->getMethod(),$this->getQuery()) ;
  181
+        $responseMethod = null;
273 182
 
274 183
         if(!$responseClass) { // If no class was found, response is 404
275 184
             $this->getResponse()->cleanHeader();
276  
-            $this->getResponse()->addHeader("HTTP/1.1 404 NOT FOUND");
  185
+            $this->getResponse()->addHeader("HTTP/1.1 404 Not found");
277 186
             $this->getResponse()->setResponse("HTTP/1.1 404 NOT FOUND");
278 187
             return $this->show();
279 188
         }
280  
-    
  189
+
281 190
         // In case a specific method should be called
282  
-        $parts = explode("::",$responseClass);
283  
-        if(isset($parts[0]))
  191
+        if(count($parts = explode("::",$responseClass)) > 1) {
284 192
             $responseClass = $parts[0];
285  
-        else
286  
-            $responseClass = null ;
287  
-
288  
-        if(isset($parts[1]))
289 193
             $responseMethod = $parts[1];
290  
-        else
291  
-            $responseMethod =null;
  194
+        }
292 195
 
293  
-        $this->call(new $responseClass,$responseMethod); // Call the class
  196
+        return $this->call(new $responseClass,$responseMethod)->show(); // Call the class and return the response
  197
+    }
294 198
 
295  
-        return $this->show(); // Return response content  
296  
-  }
297  
-        
298  
-    private function call($class,$method=null) {                  
  199
+    private function call($class,$method=null) {             
299 200
         $this->stack[] = get_class($class) ;
300  
-        if($class instanceof RestView) { // If is a view, call Show($restServer)
301  
-            if($method==null) $method="show";
302  
-            $class = $class->$method($this) ; 
  201
+        if($method != null) {
  202
+        } else if($class instanceof RestView) { // If is a view, call Show($restServer)
  203
+            $method="show";
303 204
         } else if($class instanceof RestController)  {  //If is a controller, call execute($restServer)
304  
-            if($method==null) $method="execute";
305  
-            $class = $class->$method($this);
  205
+            $method="execute";
  206
+        } else {
  207
+            Throw new Exception(get_class($class)." is not a RestAction");
306 208
         }
  209
+        $class = $class->$method($this);
307 210
 
308 211
         if($class instanceof RestAction 
309  
-                    && get_class($class) != $this->lastClass() ) {
  212
+            && get_class($class) != $this->lastClass() ) {
310 213
             return $this->call($class); // May have another class to follow the request
311 214
         }
312  
-            
  215
+
313 216
         return $this ;
314 217
     }
315 218
 
316  
-                
317  
-  private function show() {
318  
-        $this->testAuth() ; // Test authentication
  219
+    private function show() {
319 220
         if(!$this->getResponse()->headerSent()) {
320 221
             $this->getResponse()->showHeader(); // Call headers, if no yet
321 222
         }
322 223
         return $this->getResponse()->getResponse() ; // Return response content;
323  
-  }
324  
-
  224
+    }
325 225
 }
326 226
 
327 227
 ?>
Txt RestView.class.php
  • View file @ f3acd66
... ...
@@ -6,13 +6,12 @@ include_once 'RestAction.class.php';
6 6
   * Interface describe a View for rendering an Response
7 7
   */
8 8
 interface RestView extends RestAction {
9  
-    /**
10  
-       * Render this view
11  
-       * Show($restServer)
12  
-       * @param RestServer $restServer
13  
-       * @return string HTML
14  
-       *
15  
-     * */
16  
-    function show(RestServer $restServer) ;
  9
+  /**
  10
+  * Render this view
  11
+  * Show($restServer)
  12
+  * @param RestServer $restServer
  13
+  * @return RestServer 
  14
+  * */
  15
+  function show(RestServer $restServer) ;
17 16
 }
18 17
 ?>
Txt tests/RestClient.test.php
  • View file @ f3acd66
... ...
@@ -1,42 +0,0 @@
1  
-<?php
2  
-// dummy example of RestTest
3  
-include '../RestClient.class.php';
4  
-$twitter = RestClient::post( // Same for RestClient::get()
5  
-            "http://twitter.com/statuses/update.json"
6  
-            ,array("status"=>"Working with RestClient from RestServer!") 
7  
-            ,"username"
8  
-            ,"password");
9  
-
10  
-var_dump($twitter->getResponse());
11  
-var_dump($twitter->getResponseCode());
12  
-var_dump($twitter->getResponseMessage());
13  
-var_dump($twitter->getResponseContentType());
14  
-
15  
-// Other examples
16  
-$url = "http://example";
17  
-$user = "user";
18  
-$password = "password";
19  
-
20  
-$ex = RestClient::get($url);
21  
-$ex = RestClient::get($url,null,$user,$password);
22  
-$ex = RestClient::get($url,array('key'=>'value'));
23  
-$ex = RestClient::get($url,array('key'=>'value'),$user,$password);
24  
-
25  
-//content post
26  
-$ex = RestClient::post($url);
27  
-$ex = RestClient::post($url,null,$user,$password);
28  
-$ex = RestClient::post($url,array('key'=>'value'));
29  
-$ex = RestClient::post($url,array('key'=>'value'),$user,$password); 
30  
-$ex = RestClient::post($url,"some text",$user,$password,"text/plain");
31  
-$ex = RestClient::post($url,"{ name: 'json'}",$user,$password,"application/json");
32  
-$ex = RestClient::post($url,"<xml>Or any thing</xml>",$user,$password,"application/xml");
33  
-
34  
-// General cases
35  
-$get = RestClient::get($url,array("q"=>"diogok.json","key"=>"value"),$user,$password);
36  
-$post = RestClient::post($url,array("q"=>"diogok.json","key"=>"value"),$user,$password);
37  
-$post = RestClient::post($url,"This is my json",$user,$password,"text/plain");
38  
-$post = RestClient::post($url."?key=diogok","This is my json",$user,$password,"text/plain");
39  
-$put = RestClient::put($url,"This is my json",$user,$password,"text/plain");
40  
-$delete = RestClient::delete($url."?key=diogok",array("key"=>"value"),$user,$password);
41  
-$http = RestClient::call("OPTIONS",$url."?key=diogok",array("key"=>"values"),$user,$password,"text/plain");
42  
-?>
Txt tests/RestServer.test.php
  • View file @ f3acd66
... ...
@@ -1,147 +0,0 @@
1  
-<?php
2  
-
3  
-    include ("../RestServer.class.php");
4  
-        
5  
-    class RC implements RestController {
6  
-        function execute(RestServer $rest) {
7  
-            $rest->getResponse()->setResponse("Yahoo");
8  
-            return $rest ;
9  
-        }
10  
-
11  
-        function rock(RestServer $rest) {
12  
-            $rest->getResponse()->setResponse("We rock!");
13  
-            return $rest ;
14  
-        }
15  
-    }
16  
-    
17  
-    class RC2 implements RestController {
18  
-        function execute(RestServer $rest) {
19  
-            return new view2();
20  
-        }
21  
-    }
22  
-    
23  
-    class view implements RestView {
24  
-      function show(RestServer $rest) {
25  
-          $rest->getResponse()->addResponse("Google");
26  
-          return $rest ;
27  
-      }
28  
-    }
29  
-    
30  
-    class view2 implements RestView {
31  
-        function show(RestServer $rest) {
32  
-            if($rest->getRequest()->getExtension() == "html") {
33  
-                $rest->getResponse()->setResponse("Its in HTML");
34  
-            } else {
35  
-              $rest->getResponse()->setResponse("Plain Text");
36  
-            }
37  
-            return $rest ;
38  
-        }
39  
-    }
40  
-
41  
-    class RC3 implements RestController {
42  
-        function execute(RestServer $rest) {
43  
-            $rest->getResponse()->setResponse("Finish!");
44  
-            return new RC3();
45  
-        }
46  
-    }
47  
-    
48  
-    $rest = new RestServer();
49  
-   
50  
-    $rest->getRequest()->setMethod("GET");
51  
-    $rest->addMap("POST","/user","RC");
52  
-    $rest->addMap("POST","/rock","RC::rock");
53  
-    $rest->addMap("POST","/user/([a-zA-Z0-9]*).?[a-zA-Z]{0,5}","RC2");
54  
-    $rest->addMap("GET","/user","view");
55  
-    $rest->addMap("GET","/rock","RC::rock");
56  
-    $rest->addMap("GET","/user/([a-zA-Z0-9]*).?[a-zA-Z]{0,5}","view2");
57  
-    $rest->addMap("GET","/error","RC3");
58  
-    
59  
-    $q = "/user.html";    
60  
-    $rest->setQuery($q);    
61  
-    if($rest->getQuery() != "/user.html") {
62  
-        echo "Failed at 1";
63  
-        return ;
64  
-    }
65  
-    if($rest->getRequest()->getExtension() != "html") {
66  
-        echo "Failed at 2";
67  
-        return ;
68  
-    }
69  
-    
70  
-    $q = "/user";
71  
-    $rest->setQuery($q);        
72  
-    $response = $rest->execute() ;
73  
-    if($response != "Google") {
74  
-        echo "Failed at 75";
75  
-        return ;
76  
-    }
77  
-    
78  
-    $q = "/rock";
79  
-    $rest->setQuery($q);        
80  
-    $response = $rest->execute() ;
81  
-    if($response != "We rock!") {
82  
-        echo "Failed at 83";
83  
-        return ;
84  
-    };
85  
-    
86  
-    $q = "/user/diogo";
87  
-    $rest->setQuery($q);        
88  
-    $response = $rest->execute() ;
89  
-    if($response != "Plain Text") {
90  
-        echo "Failed at 91";
91  
-        return ;
92  
-    }
93  
-    
94  
-    
95  
-    $q = "/user/diogo.html";
96  
-    $rest->setQuery($q);        
97  
-    $response = $rest->execute() ;
98  
-    if($response != "Its in HTML") {
99  
-        echo "Failed at 100";
100  
-        return ;
101  
-    }
102  
-    
103  
-    
104  
-    $q = "/user";
105  
-    $rest->setQuery($q);  
106  
-    $rest->getRequest()->setMethod("POST");
107  
-    $response = $rest->execute() ;
108  
-    if($response != "Yahoo"){
109  
-       echo "Failed at 110";
110  
-        return ;
111  
-    }
112  
-    
113  
-    $q = "/user/diogo.html";
114  
-    $rest->setQuery($q);  
115  
-    $rest->getRequest()->setMethod("POST");
116  
-    $response = $rest->execute() ;
117  
-    if($response != "Its in HTML") {
118  
-        echo "Failed at 119";
119  
-        return ;
120  
-    }
121  
-    
122  
-    $q = "/user/diogo";
123  
-    $rest->setQuery($q);  
124  
-    $rest->getRequest()->setMethod("POST");
125  
-    $response = $rest->execute() ;
126  
-    if($response != "Plain Text") {
127  
-        echo "Failed at 128";
128  
-        return ;
129  
-    }
130  
-    
131  
-    $q = "/error";
132  
-    $rest->setQuery($q);  
133  
-    $rest->getRequest()->setMethod("GET");
134  
-    $response = $rest->execute() ;
135  
-    if($response != "Finish!") {
136  
-        echo "Failed at 135";
137  
-        return ;
138  
-    }
139  
-
140  
-echo "PASSED\n";
141  
-if(!function_exists("xdebug_time_index")) return ;
142  
-
143  
-echo "It took ".round(xdebug_time_index(),5)." seconds \n";
144  
-echo "Used ".round(xdebug_memory_usage()/1024,5)."Kb of Memory\n";
145  
-echo "Used at peak ".round(xdebug_peak_memory_usage()/1024,5)."Kb of Memory\n";
146  
-   
147  
-?>
Txt tests/localhost/TestController.class.php
  • View file @ f3acd66
... ...
@@ -1,16 +0,0 @@
1  
-<?php
2  
-class TestController implements RestController {
3  
-
4  
-    public function execute(RestServer $rest) {
5  
-        $r .= '<p>URI: '.$rest->getRequest()->getRequestURI().'</p>';
6  
-        $r .= '<p>Method: '.$rest->getRequest()->getMethod().'</p>';
7  
-        $r .= '<p>User: '.$rest->getRequest()->getUser().'</p>';
8  
-        $r .= '<p>Password: '.$rest->getRequest()->getPassword().'</p>';
9  
-        $r .= '<p>$_GET["key"]: '.$rest->getRequest()->getGET('key').'</p>';
10  
-        $r .= '<p>$_POST["key"]: '.$rest->getRequest()->getPOST('key').'</p>';
11  
-        $r .= '<p>Body: '.$rest->getRequest()->getBody().'</p>';
12  
-        $rest->getResponse()->setResponse($r);
13  
-        return $rest;
14  
-    }
15  
-}
16  
-?>
Txt tests/localhost/index.php
  • View file @ f3acd66
... ...
@@ -1,60 +0,0 @@
1  
-<?php
2  
-include '../../RestClient.class.php';
3  
-
4  
-$base = "http://".$_SERVER["HTTP_HOST"].dirname($_SERVER["SCRIPT_NAME"]);
5  
-var_dump($base);
6  
-
7  
-echo "\n<hr>\n";
8  
-// The GET signature is get(URL,PARAMETERS,USER,PASSWORD), only the URI is mandatory;
9  
-$get = RestClient::get($base."/rest.php",array("q"=>"diogok.json","key"=>"value"),"diogok","123");
10  
-var_dump('$get = RestClient::get($base."/rest.php",array("q"=>"diogok.json","key"=>"value"),"diogok","123");');
11  
-echo '<br>';
12  
-var_dump($get->getResponseCode());
13  
-echo $get->getResponse();
14  
-
15  
-echo "\n<hr>\n";
16  
-// The POST signature is post(URL,PARAMETERS,USER,PASSWORD,CONTENT-TYPE) , only the URI is mandatory
17  
-$get = RestClient::post($base."/rest.php",array("q"=>"diogok.json","key"=>"value"),"diogok","123");
18  
-var_dump('$get = RestClient::post($base."/rest.php",array("q"=>"diogok.json","key"=>"value"),"diogok","123");');
19  
-echo '<br>';
20  
-var_dump($get->getResponseCOde());
21  
-echo $get->getResponse();
22  
-
23  
-echo "\n<hr>\n";
24  
-$get = RestClient::post($base."/rest.php","This is my json","diogok","123","text/plain");
25  
-var_dump('$get = RestClient::post($base."/rest.php","This is my json","diogok","123","text/plain");');
26  
-echo '<br>';
27  
-var_dump($get->getResponseCOde());
28  
-echo $get->getResponse();
29  
-
30  
-echo "\n<hr>\n";
31  
-$get = RestClient::post($base."/rest.php?key=diogok","This is my json","diogok","123","text/plain");
32  
-var_dump('$get = RestClient::post($base."/rest.php?key=diogok","This is my json","diogok","123","text/plain");');
33  
-echo '<br>';
34  
-var_dump($get->getResponseCOde());
35  
-echo $get->getResponse();
36  
-
37  
-echo "\n<hr>\n";
38  
-// The PUT signature is put(URL,CONTENT,USER,PASSWORD,CONTENT-TYPE), the URL and CONTENT is mandatory
39  
-$get = RestClient::put($base."/rest.php","This is my json","diogok","123","text/plain");
40  
-var_dump('$get = RestClient::put($base."/rest.php","This is my json","diogok","123","text/plain");');
41  
-echo '<br>';
42  
-var_dump($get->getResponseCOde());
43  
-echo $get->getResponse();
44  
-
45  
-echo "\n<hr>\n";
46  
-// The DELETE signature is delete(URL,PARAMETERS,USER,PASSWORD), the URL is mandatory
47  
-$get = RestClient::delete($base."/rest.php?key=diogok",array("key"=>"value"),"diogok","123");
48  
-var_dump('$get = RestClient::delete($base."/rest.php?key=diogok",array("key"=>"value"),"diogok","123");');
49  
-echo '<br>';
50  
-var_dump($get->getResponseCOde());
51  
-echo $get->getResponse();
52  
-
53  
-echo "\n<hr>\n";
54  
-// The custom call signature is call(URL,PARAMETERS,USER,PASSWORD,CONTENT-TYPE), only the URL is mandatory
55  
-$get = RestClient::call("OPTIONS",$base."/rest.php?key=diogok",array("key"=>"values"),"diogok","123","text/plain");
56  
-var_dump('$get = RestClient::call("OPTIONS",$base."/rest.php?key=diogok",array("key"=>"values"),"diogok","123","text/plain");');
57  
-echo '<br>';
58  
-var_dump($get->getResponseCOde());
59  
-echo $get->getResponse();
60  
-?>
Txt tests/localhost/rest.php
  • View file @ f3acd66
... ...
@@ -1,16 +0,0 @@
1  
-<?php
2  
-
3  
-include '../../RestServer.class.php';
4  
-include 'TestController.class.php';
5  
-
6  
-$rest = new RestServer($_GET['q']) ;
7  
-
8  
-$rest->addMap("GET",".*","TestController");
9  
-$rest->addMap("POST",".*","TestController");
10  
-$rest->addMap("PUT",".*","TestController");
11  
-$rest->addMap("DELETE",".*","TestController");
12  
-$rest->addMap("OPTIONS",".*","TestController");
13  
-
14  
-echo $rest->execute();
15  
-
16  
-?>

0 notes on commit f3acd66

Please log in to comment.
Dedicated Server Powered by the Dedicated Servers and
Cloud Computing of Rackspace Hosting®
  • Blog
  • Support
  • Training
  • Job Board
  • Shop
  • Contact
  • API
  • Status
  • © 2010 GitHub Inc. All rights reserved.
  • Terms of Service
  • Privacy
  • Security
  • English
  • Deutsch
  • Français
  • 日本語
  • Português (BR)
  • 中文
  • See all available languages

Your current locale selection: English. Choose another?

  • English
  • Afrikaans
  • Català
  • Čeština
  • Deutsch
  • Español
  • Français
  • Hrvatski
  • Indonesia
  • Italiano
  • 日本語
  • Nederlands
  • Norsk
  • Polski
  • Português (BR)
  • Српски
  • Svenska
  • 中文