Subversion Repositories eFlore/Applications.cel

Rev

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

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