Subversion Repositories Applications.bazar

Rev

Rev 471 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
480 mathias 1
<?php
2
// In : utf8 url_encoded (get et post)
3
// Out : utf8
4
 
5
// TODO : gerer les retours : dans ce controleur : code retour et envoi ...
6
class JRest {
7
 
8
 	/** Parsed configuration file */
9
    private $config;
10
 
11
	/** The HTTP request method used. */
12
	private $method = 'GET';
13
 
14
	/** The HTTP request data sent (if any). */
15
	private $requestData = NULL;
16
 
17
	/** Array of strings to convert into the HTTP response. */
18
	private $output = array();
19
 
20
	/** Nom resource. */
21
	private $resource = NULL;
22
 
23
	/** Identifiant unique resource. */
24
	private $uid = NULL;
25
 
26
	/**
27
	 * Constructor. Parses the configuration file "JRest.ini", grabs any request data sent, records the HTTP
28
	 * request method used and parses the request URL to find out the requested resource
29
	 * @param str iniFile Configuration file to use
30
	 */
31
	public function JRest($iniFile = 'jrest.ini.php') {
32
		$this->config = parse_ini_file($iniFile, TRUE);
33
		if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER['REQUEST_METHOD']) && isset($_SERVER['QUERY_STRING'])) {
34
			if (isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > 0) {
35
				$this->requestData = '';
36
				$httpContent = fopen('php://input', 'r');
37
				while ($data = fread($httpContent, 1024)) {
38
					$this->requestData .= $data;
39
				}
40
				fclose($httpContent);
41
			}
42
			if (strlen($_SERVER['QUERY_STRING']) == 0) {
43
				$len = strlen($_SERVER['REQUEST_URI']);
44
			} else {
45
				$len = -(strlen($_SERVER['QUERY_STRING']) + 1);
46
			}
47
 
48
			$urlString = '';
49
			if  (substr_count($_SERVER['REQUEST_URI'], $this->config['settings']['baseURL']) > 0) {
50
				$urlString = substr($_SERVER['REQUEST_URI'], strlen($this->config['settings']['baseURL']), $len);
51
			} else if (substr_count($_SERVER['REQUEST_URI'], $this->config['settings']['baseAlternativeURL']) > 0) {
52
				$urlString = substr($_SERVER['REQUEST_URI'], strlen($this->config['settings']['baseAlternativeURL']), $len);
53
			}
54
 
55
			$urlParts = explode('/', $urlString);
56
 
57
			if (isset($urlParts[0])) $this->resource = $urlParts[0];
58
			if (count($urlParts) > 1 && $urlParts[1] != '') {
59
				array_shift($urlParts);
60
				foreach ($urlParts as $uid) {
61
					if ($uid != '') {
62
						$this->uid[] = urldecode($uid);
63
					}
64
				}
65
			}
66
 
67
			$this->method = $_SERVER['REQUEST_METHOD'];
68
		} else {
69
			trigger_error('I require the server variables REQUEST_URI, REQUEST_METHOD and QUERY_STRING to work.', E_USER_ERROR);
70
		}
71
	}
72
 
73
	/**
74
	 * Execute the request.
75
	 */
76
	function exec() {
77
		switch ($this->method) {
78
			case 'GET':
79
				$this->get();
80
				break;
81
			case 'POST':
82
				$this->post();
83
				break;
84
			case 'DELETE':
85
				$this->delete();
86
				break;
87
			case 'PUT':
88
				$this->add();
89
				break;
90
		}
91
	}
92
 
93
	/**
94
	 * Execute a GET request. A GET request fetches a list of resource when no resource name is given, a list of element
95
	 * when a resource name is given, or a resource element when a resource and resource unique identifier are given. It does not change the
96
	 * database contents.
97
	 */
98
	private function get() {
99
		if ($this->resource) {
100
			$resource_file = 'services/'.ucfirst($this->resource).'.php';
101
			$resource_class = ucfirst($this->resource);
102
			if (file_exists($resource_file))  {
103
				include_once $resource_file;
104
				if (class_exists($resource_class)) {
105
					$service = new $resource_class($this->config);
106
					if ($this->uid) { // get a resource element
107
						if (method_exists($service, 'getElement')) {
108
							$service->getElement($this->uid);
109
						}
110
					} elseif (method_exists($service, 'getRessource')) { // get all elements of a ressource
111
						$service->getRessource();
112
					}
113
				}
114
			}
115
		} else { // get resources
116
			// include set.jrest.php, instanticiation et appel
117
		}
118
	}
119
 
120
	private function post() {
121
	   	$pairs = array();
122
		// Récupération des paramètres passés dans le contenu de la requête HTTP (= POST)
123
	   	if ($this->requestData) {
124
			$pairs = $this->parseRequestData();
125
		}
126
 
127
		// Ajout des informations concernant l'upload de fichier passées dans la variable $_FILE
128
		if(isset($_FILES)) {
129
			foreach ($_FILES as $v) {
130
				$pairs[$v['name']] = $v;
131
			}
132
 
133
			// Ne pas effacer cette ligne ! Elle est indispensable pour les services du Carnet en ligne
134
			// qui n'utilisent que le tableau pairs dans les posts
135
			$pairs = array_merge($_POST, $pairs);
136
		}
137
 
138
		// gestion du contenu du post
139
		if(isset($_POST))
140
		{
141
			// Safari ne sait pas envoyer des DELETE avec gwt...
142
			// Nous utilisons le parametre "action" passé dans le POST qui doit contenir DELETE pour lancer la supression
143
			if (isset($pairs['action']) && $pairs['action'] == 'DELETE') {
144
				$this->delete();
145
				return;
146
			}
147
 
148
			if (count($pairs) != 0) {
149
				if ($this->uid) { // get a resource element
150
					$resource_file = 'services/'.ucfirst($this->resource).'.php';
151
					$resource_class = ucfirst($this->resource);
152
					if (file_exists($resource_file)) {
153
						include_once $resource_file;
154
						if (class_exists($resource_class)) {
155
							$service = new $resource_class($this->config);
156
							if (method_exists($service,'updateElement')) { // Update element
157
								$ret_value = false;
158
								try {
159
									// TODO : a voir le retour ...
160
									$ret_value = $service->updateElement($this->uid, $pairs);
161
									if($ret_value) $this->created();
162
									else $this->badRequest();
163
								} catch (Exception $e) {
164
									$this->badRequest($e);
165
								}
166
							}
167
						}
168
					}
169
				} else { // get all elements of a ressource
170
					$this->add($pairs);
171
				}
172
			} else {
173
				$this->lengthRequired();
174
			}
175
		}
176
	}
177
 
178
	private function delete() {
179
		$resource_file = 'services/'.ucfirst($this->resource).'.php';
180
		$resource_class = ucfirst($this->resource);
181
		if (file_exists($resource_file)) {
182
			include_once $resource_file;
183
			if (class_exists($resource_class)) {
184
				$service = new $resource_class($this->config);
185
				if ($this->uid) { // get a resource element
186
		 			if (method_exists($service, 'deleteElement')) { // Delete element
187
						if ($service->deleteElement($this->uid)) {
188
							$this->noContent();
189
						}
190
	 				}
191
				}
192
			}
193
		}
194
	}
195
 
196
	private function add($pairs = null) {
197
		if (is_null($pairs)) {
198
			$pairs = array();
199
			// Récupération des paramètres passés dans le contenu de la requête HTTP (= POST)
200
			// FIXME : vérifier que l'on récupère bien les données passées par PUT
201
		   	if ($this->requestData) {
202
				$pairs = $this->parseRequestData();
203
			}
204
		}
205
 
206
		if (count($pairs) != 0) {
207
			$resource_file = 'services/'.ucfirst($this->resource).'.php';
208
			$resource_class = ucfirst($this->resource);
209
			if (file_exists($resource_file)) {
210
				include_once $resource_file;
211
				if (class_exists($resource_class)) {
212
					$service = new $resource_class($this->config);
213
					if (method_exists($service,'createElement')) { // Create a new element
214
						$ret_value = false;
215
						try {
216
							$ret_value = $service->createElement($pairs);
217
							if($ret_value) $this->created();
218
							else $this->badRequest();
219
						} catch (Exception $e) {
220
							$this->badRequest($e);
221
						}
222
					}
223
				}
224
			}
225
		} else {
226
			$this->lengthRequired();
227
		}
228
	}
229
 
230
	/**
231
	 * Parse the HTTP request data.
232
	 * @return str[] Array of name value pairs
233
	 */
234
	private function parseRequestData() {
235
		$values = array();
236
		$pairs = explode('&', $this->requestData);
237
		foreach ($pairs as $pair) {
238
			$parts = explode('=', $pair);
239
			if (isset($parts[0]) && isset($parts[1])) {
240
				$parts[1] = rtrim(urldecode($parts[1]));
241
				$values[$parts[0]] = $parts[1];
242
			}
243
		}
244
		return $values;
245
	}
246
 
247
	/**
248
	 * Send a HTTP 201 response header.
249
	 */
250
	private function created($url = FALSE) {
251
		header('HTTP/1.0 201 Created');
252
		if ($url) {
253
			header('Location: '.$url);
254
		}
255
	}
256
 
257
	/**
258
	 * Send a HTTP 204 response header.
259
	 */
260
	private function noContent() {
261
		header('HTTP/1.0 204 No Content');
262
	}
263
 
264
	/**
265
	 * Send a HTTP 400 response header.
266
	 */
267
	private function badRequest(Exception $e = NULL) {
268
		header('HTTP/1.0 400 Bad Request');
269
		if($e) echo $e->getMessage();
270
	}
271
 
272
	/**
273
	 * Send a HTTP 401 response header.
274
	 */
275
	private function unauthorized($realm = 'JRest') {
276
		if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
277
			header('WWW-Authenticate: Basic realm="'.$realm.'"');
278
		}
279
		header('HTTP/1.0 401 Unauthorized');
280
	}
281
 
282
	/**
283
	 * Send a HTTP 404 response header.
284
	 */
285
	private function notFound() {
286
		header('HTTP/1.0 404 Not Found');
287
	}
288
 
289
	/**
290
	 * Send a HTTP 405 response header.
291
	 */
292
	private function methodNotAllowed($allowed = 'GET, HEAD') {
293
		header('HTTP/1.0 405 Method Not Allowed');
294
		header('Allow: '.$allowed);
295
	}
296
 
297
	/**
298
	 * Send a HTTP 406 response header.
299
	 */
300
	private function notAcceptable() {
301
		header('HTTP/1.0 406 Not Acceptable');
302
		echo join(', ', array_keys($this->config['renderers']));
303
	}
304
 
305
	/**
306
	 * Send a HTTP 411 response header.
307
	 */
308
	private function lengthRequired() {
309
		header('HTTP/1.0 411 Length Required');
310
	}
311
 
312
	/**
313
	 * Send a HTTP 500 response header.
314
	 */
315
	private function internalServerError() {
316
		header('HTTP/1.0 500 Internal Server Error');
317
	}
318
}
453 aurelien 319
?>