Subversion Repositories Applications.annuaire

Rev

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