Subversion Repositories Applications.referentiel

Rev

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

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