Subversion Repositories Applications.annuaire

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
69 aurelien 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
 
412 jpm 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
			}
69 aurelien 54
			$urlParts = explode('/', $urlString);
55
 
56
			if (isset($urlParts[0])) $this->resource = $urlParts[0];
57
			if (count($urlParts) > 1 && $urlParts[1] != '') {
58
				array_shift($urlParts);
59
				foreach ($urlParts as $uid) {
60
					if ($uid != '') {
61
						$this->uid[] = urldecode($uid);
62
					}
63
				}
64
			}
65
 
66
			$this->method = $_SERVER['REQUEST_METHOD'];
67
		} else {
68
			trigger_error('I require the server variables REQUEST_URI, REQUEST_METHOD and QUERY_STRING to work.', E_USER_ERROR);
69
		}
70
	}
71
 
72
	/**
73
	 * Execute the request.
74
	 */
75
	function exec() {
76
		switch ($this->method) {
77
			case 'GET':
78
				$this->get();
79
				break;
80
			case 'POST':
81
				$this->post();
82
				break;
83
			case 'DELETE':
84
				$this->delete();
85
				break;
86
			case 'PUT':
87
				$this->add();
88
				break;
89
		}
90
	}
91
 
92
	/**
93
	 * Execute a GET request. A GET request fetches a list of resource when no resource name is given, a list of element
94
	 * when a resource name is given, or a resource element when a resource and resource unique identifier are given. It does not change the
95
	 * database contents.
96
	 */
97
	private function get() {
98
		if ($this->resource) {
99
			$resource_file = 'services/'.ucfirst($this->resource).'.php';
100
			$resource_class = ucfirst($this->resource);
101
			if (file_exists($resource_file))  {
102
				include_once $resource_file;
103
				if (class_exists($resource_class)) {
104
					$service = new $resource_class($this->config);
105
					if ($this->uid) { // get a resource element
106
						if (method_exists($service, 'getElement')) {
107
							$service->getElement($this->uid);
108
						}
109
					} elseif (method_exists($service, 'getRessource')) { // get all elements of a ressource
110
						$service->getRessource();
111
					}
112
				}
113
			}
114
		} else { // get resources
115
			// include set.jrest.php, instanticiation et appel
116
		}
117
	}
118
 
119
	private function post() {
120
	   	$pairs = array();
121
		// Récupération des paramètres passés dans le contenu de la requête HTTP (= POST)
122
	   	if ($this->requestData) {
123
			$pairs = $this->parseRequestData();
124
		}
125
 
126
		// Ajout des informations concernant l'upload de fichier passées dans la variable $_FILE
127
		if(isset($_FILES)) {
128
			foreach ($_FILES as $v) {
129
				$pairs[$v['name']] = $v;
130
			}
131
 
132
			// Ne pas effacer cette ligne ! Elle est indispensable pour les services du Carnet en ligne
133
			// qui n'utilisent que le tableau pairs dans les posts
134
			$pairs = array_merge($pairs, $_POST);
135
		}
136
 
137
		// gestion du contenu du post
138
		if(isset($_POST))
139
		{
140
			// Safari ne sait pas envoyer des DELETE avec gwt...
141
			// Nous utilisons le parametre "action" passé dans le POST qui doit contenir DELETE pour lancer la supression
142
			if ($pairs['action'] == 'DELETE') {
143
				$this->delete();
144
				return;
145
			}
146
 
147
			if (count($pairs) != 0) {
148
				if ($this->uid) { // get a resource element
149
					$resource_file = 'services/'.ucfirst($this->resource).'.php';
150
					$resource_class = ucfirst($this->resource);
151
					if (file_exists($resource_file)) {
152
						include_once $resource_file;
153
						if (class_exists($resource_class)) {
154
							$service = new $resource_class($this->config);
155
							if (method_exists($service,'updateElement')) { // Update element
156
								// TODO : a voir le retour ...
157
								if ($service->updateElement($this->uid, $pairs)) {
158
									$this->created();
159
								}
160
							}
161
						}
162
					}
163
				} else { // get all elements of a ressource
164
					$this->add($pairs);
165
				}
166
			} else {
167
				$this->lengthRequired();
168
			}
169
		}
170
	}
171
 
172
	private function delete() {
173
		$resource_file = 'services/'.ucfirst($this->resource).'.php';
174
		$resource_class = ucfirst($this->resource);
175
		if (file_exists($resource_file)) {
176
			include_once $resource_file;
177
			if (class_exists($resource_class)) {
178
				$service = new $resource_class($this->config);
179
				if ($this->uid) { // get a resource element
180
		 			if (method_exists($service, 'deleteElement')) { // Delete element
181
						if ($service->deleteElement($this->uid)) {
182
							$this->noContent();
183
						}
184
	 				}
185
				}
186
			}
187
		}
188
	}
189
 
190
	private function add($pairs = null) {
191
		if (is_null($pairs)) {
192
			$pairs = array();
193
			// Récupération des paramètres passés dans le contenu de la requête HTTP (= POST)
194
			// FIXME : vérifier que l'on récupère bien les données passées par PUT
195
		   	if ($this->requestData) {
196
				$pairs = $this->parseRequestData();
197
			}
198
		}
199
 
200
		if (count($pairs) != 0) {
201
			$resource_file = 'services/'.ucfirst($this->resource).'.php';
202
			$resource_class = ucfirst($this->resource);
203
			if (file_exists($resource_file)) {
204
				include_once $resource_file;
205
				if (class_exists($resource_class)) {
206
					$service = new $resource_class($this->config);
207
					if (method_exists($service,'createElement')) { // Create a new element
208
						if ($service->createElement($pairs)) {
209
							$this->created();
210
						}
211
					}
212
				}
213
			}
214
		} else {
215
			$this->lengthRequired();
216
		}
217
	}
218
 
219
	/**
220
	 * Parse the HTTP request data.
221
	 * @return str[] Array of name value pairs
222
	 */
223
	private function parseRequestData() {
224
		$values = array();
225
		$pairs = explode('&', $this->requestData);
226
		foreach ($pairs as $pair) {
227
			$parts = explode('=', $pair);
228
			if (isset($parts[0]) && isset($parts[1])) {
229
				$parts[1] = rtrim(urldecode($parts[1]));
230
				$values[$parts[0]] = $parts[1];
231
			}
232
		}
233
		return $values;
234
	}
235
 
236
	/**
237
	 * Send a HTTP 201 response header.
238
	 */
239
	private function created($url = FALSE) {
240
		header('HTTP/1.0 201 Created');
241
		if ($url) {
242
			header('Location: '.$url);
243
		}
244
	}
245
 
246
	/**
247
	 * Send a HTTP 204 response header.
248
	 */
249
	private function noContent() {
250
		header('HTTP/1.0 204 No Content');
251
	}
252
 
253
	/**
254
	 * Send a HTTP 400 response header.
255
	 */
256
	private function badRequest() {
257
		header('HTTP/1.0 400 Bad Request');
258
	}
259
 
260
	/**
261
	 * Send a HTTP 401 response header.
262
	 */
263
	private function unauthorized($realm = 'JRest') {
264
		if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) {
265
			header('WWW-Authenticate: Basic realm="'.$realm.'"');
266
		}
267
		header('HTTP/1.0 401 Unauthorized');
268
	}
269
 
270
	/**
271
	 * Send a HTTP 404 response header.
272
	 */
273
	private function notFound() {
274
		header('HTTP/1.0 404 Not Found');
275
	}
276
 
277
	/**
278
	 * Send a HTTP 405 response header.
279
	 */
280
	private function methodNotAllowed($allowed = 'GET, HEAD') {
281
		header('HTTP/1.0 405 Method Not Allowed');
282
		header('Allow: '.$allowed);
283
	}
284
 
285
	/**
286
	 * Send a HTTP 406 response header.
287
	 */
288
	private function notAcceptable() {
289
		header('HTTP/1.0 406 Not Acceptable');
290
		echo join(', ', array_keys($this->config['renderers']));
291
	}
292
 
293
	/**
294
	 * Send a HTTP 411 response header.
295
	 */
296
	private function lengthRequired() {
297
		header('HTTP/1.0 411 Length Required');
298
	}
299
 
300
	/**
301
	 * Send a HTTP 500 response header.
302
	 */
303
	private function internalServerError() {
304
		header('HTTP/1.0 500 Internal Server Error');
305
	}
306
}
307
?>