Subversion Repositories Applications.annuaire

Rev

Rev 69 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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