Subversion Repositories Applications.framework

Rev

Rev 439 | Rev 494 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
252 jpm 1
<?php
2
// declare(encoding='UTF-8');
3
/**
4
* Classe client permettant d'interroger des services web REST.
5
*
473 jpm 6
* @category		php 5.2
7
* @package		Framework
252 jpm 8
* @author		Jean-Pascal MILCENT <jpm@tela-botanica.org>
9
* @copyright	Copyright (c) 2010, Tela Botanica (accueil@tela-botanica.org)
473 jpm 10
* @license		CeCILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-fr.txt>
11
* @license		GNU-GPL <http://www.gnu.org/licenses/gpl.html>
12
* @since		0.2
252 jpm 13
*/
287 jpm 14
class RestClient {
252 jpm 15
	const HTTP_URL_REQUETE_SEPARATEUR = '&';
349 jpm 16
	const HTTP_URL_REQUETE_CLE_VALEUR_SEPARATEUR = '=';
256 jpm 17
	private $http_methodes = array('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'CONNECT', 'TRACE');
252 jpm 18
	protected $parametres = null;
256 jpm 19
	private $url = null;
20
	private $reponse_entetes = null;
473 jpm 21
 
22
	//+------------------------------------------------------------------------------------------------------+
252 jpm 23
	// ACCESSEURS
473 jpm 24
 
353 jpm 25
	public function getReponseEntetes() {
256 jpm 26
		return $this->reponse_entetes;
27
	}
473 jpm 28
 
252 jpm 29
	public function getParametre($cle) {
30
		$valeur = (isset($this->parametres[$cle])) ? $this->parametres[$cle] : null;
31
		return $valeur;
32
	}
473 jpm 33
 
252 jpm 34
	public function ajouterParametre($cle, $valeur) {
35
		$this->parametres[$cle] = $valeur;
36
	}
473 jpm 37
 
252 jpm 38
	public function supprimerParametre($cle) {
39
		unset($this->parametres[$cle]);
40
	}
473 jpm 41
 
252 jpm 42
	public function nettoyerParametres() {
43
		$this->parametres = null;
44
	}
473 jpm 45
 
46
	//+------------------------------------------------------------------------------------------------------+
252 jpm 47
	// MÉTHODES
473 jpm 48
 
252 jpm 49
	public function consulter($url) {
50
		$retour = $this->envoyerRequete($url, 'GET');
51
		return $retour;
52
	}
473 jpm 53
 
252 jpm 54
	public function ajouter($url, Array $donnees) {
55
		$retour = $this->envoyerRequete($url, 'PUT', $donnees);
56
		return $retour;
57
	}
473 jpm 58
 
252 jpm 59
	public function modifier($url, Array $donnees) {
60
		$retour = $this->envoyerRequete($url, 'POST', $donnees);
61
		return $retour;
62
	}
473 jpm 63
 
252 jpm 64
	public function supprimer($url) {
65
		$retour = $this->envoyerRequete($url, 'DELETE');
66
		return $retour;
67
	}
473 jpm 68
 
69
	public function envoyerRequete($url, $mode, Array $donnees = array()) {
70
		$contenu = false;
71
		if (FALSE && function_exists('curl_init') && $mode == 'GET') {
72
			// nous n'activons le wrapper que pour GET pour l'instant
73
			// car l'utilisation de curl pour les autres modes pourrait
74
			// vraisemblablement induire des comportements différents. (test-suite needed)
75
			$contenu = $this->envoyerCurlRequete($url, $mode, $donnees);
76
		} else {
77
			$contenu = $this->envoyerStreamRequete($url, $mode, $donnees);
78
		}
79
		return $contenu;
80
	}
81
 
82
	private function envoyerStreamRequete($url, $mode, Array $donnees = array()) {
428 raphael 83
		$this->url = $url;
84
		$contenu = false;
85
		if (! in_array($mode, $this->http_methodes)) {
86
			$e = "Le mode de requête '$mode' n'est pas accepté!";
87
			trigger_error($e, E_USER_WARNING);
88
		} else {
89
			if ($mode == 'GET') {
90
				$this->traiterUrlParametres();
91
			}
473 jpm 92
			$content = http_build_query($donnees, null, self::HTTP_URL_REQUETE_SEPARATEUR);
93
			$contexte = stream_context_create(array(
94
				'http' => array(
95
      				'method' => $mode,
96
					'header' => "Content-type: application/x-www-form-urlencoded\r\n",
97
      				'content' => $content)));
98
			$flux = @fopen($this->url, 'r', false, $contexte);
99
			if (!$flux) {
100
				$this->reponse_entetes = $http_response_header;
101
				$entetesFmt = print_r($this->analyserEntete(), true);
102
				$e = "Echec requête '$mode' : {$this->url}\n".
103
					"Paramètres requête : $content \n".
104
					"Entêtes réponse : $entetesFmt \n";
105
				trigger_error($e, E_USER_WARNING);
106
			} else {
107
				// Informations sur les en-têtes et métadonnées du flux
108
				$this->reponse_entetes = stream_get_meta_data($flux);
428 raphael 109
 
473 jpm 110
				// Contenu actuel de $url
111
				$contenu = stream_get_contents($flux);
112
 
113
				fclose($flux);
114
			}
115
			$this->traiterEntete();
116
		}
117
		$this->reinitialiser();
118
		return $contenu;
119
	}
120
 
121
	private function envoyerCurlRequete($url, $mode, Array $donnees = array()) {
122
		$this->url = $url;
123
		$contenu = false;
124
		if (! in_array($mode, $this->http_methodes)) {
125
			$e = "Le mode de requête '$mode' n'est pas accepté!";
126
			trigger_error($e, E_USER_WARNING);
127
		} else {
128
			if ($mode == 'GET') {
129
				$this->traiterUrlParametres();
130
			}
131
 
428 raphael 132
			$ch = curl_init($this->url);
133
			curl_setopt($ch, CURLOPT_HEADER, TRUE);
134
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
438 raphael 135
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
473 jpm 136
			if ($mode == 'POST') {
137
				curl_setopt($ch, CURLOPT_POST, TRUE);
138
			} elseif ($mode == 'PUT') {
139
				curl_setopt($ch, CURLOPT_PUT, TRUE);
140
			} elseif($mode == 'DELETE') {
141
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
142
			}
428 raphael 143
 
473 jpm 144
			$content = '';
145
			if ($donnees) {
146
				$content = http_build_query($donnees, null, self::HTTP_URL_REQUETE_SEPARATEUR);
147
				curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
148
			}
428 raphael 149
 
150
			$flux = curl_exec($ch);
151
			curl_close($ch);
152
 
153
			if (!$flux) {
154
				$this->reponse_entetes = $http_response_header;
473 jpm 155
				$entetesFmt = print_r($this->analyserEntete(), true);
156
				$msgTpl = "Echec requête (CURL) '%s' : %s\nParamètres requête : %s \nEntêtes réponse : %s \n";
157
				$msg = sprintf($msgTpl, strtoupper($mode), $this->url, $content, $entetesFmt);
158
				trigger_error($msg, E_USER_WARNING);
428 raphael 159
			} else {
438 raphael 160
				// attention, CURLOPT_FOLLOWLOCATION amène le stream à contenir plusieurs section d'header HTTP successives
161
				$t = explode("\r\n\r\n", $flux);
162
				$contenu = array_splice($t, -1);
163
				$dernier_entete = array_splice($t, -1);
164
				$contenu = $contenu[0];
165
				$dernier_entete = $dernier_entete[0];
166
 
428 raphael 167
				// XXX: mimic stream_get_meta_data() (ce qui n'est pas très propre, le code appelant ferait mieux de se mettre à jour)
438 raphael 168
				$this->reponse_entetes = array('wrapper_data' => explode("\r\n", $dernier_entete));
428 raphael 169
			}
170
			$this->traiterEntete();
171
		}
172
		$this->reinitialiser();
173
		return $contenu;
174
	}
175
 
257 jpm 176
	private function traiterUrlParametres() {
252 jpm 177
		$parametres = array();
178
		if (count($this->parametres) > 0) {
179
			foreach ($this->parametres as $cle => $valeur) {
350 jpm 180
				$cle = rawurlencode($cle);
181
				$valeur = rawurlencode($valeur);
349 jpm 182
				$parametres[] = $cle.self::HTTP_URL_REQUETE_CLE_VALEUR_SEPARATEUR.$valeur;
252 jpm 183
			}
184
			$url_parametres = implode(self::HTTP_URL_REQUETE_SEPARATEUR, $parametres);
257 jpm 185
			$this->url = $this->url.'?'.$url_parametres;
252 jpm 186
		}
187
	}
473 jpm 188
 
256 jpm 189
	private function traiterEntete() {
190
		$infos = $this->analyserEntete();
252 jpm 191
		$this->traiterEnteteDebogage($infos);
192
	}
473 jpm 193
 
256 jpm 194
	private function analyserEntete() {
473 jpm 195
		$entetes = $this->reponse_entetes;
256 jpm 196
		$infos = array('date' => null, 'uri' => $this->url, 'debogages' => null);
473 jpm 197
 
252 jpm 198
		if (isset($entetes['wrapper_data'])) {
199
			$entetes = $entetes['wrapper_data'];
200
		}
201
		foreach ($entetes as $entete) {
202
			if (preg_match('/^X_REST_DEBOGAGE_MESSAGES: (.+)$/', $entete, $match)) {
203
				$infos['debogages'] = json_decode($match[1]);
204
			}
205
			if (preg_match('/^Date: .+ ([012][0-9]:[012345][0-9]:[012345][0-9]) .*$/', $entete, $match)) {
206
				$infos['date'] = $match[1];
207
			}
208
		}
209
		return $infos;
210
	}
473 jpm 211
 
212
	private function traiterEnteteDebogage($entetes) {
252 jpm 213
		if (isset($entetes['debogages'])) {
214
			$date = $entetes['date'];
215
			$uri = $entetes['uri'];
216
			$debogages = $entetes['debogages'];
217
			foreach ($debogages as $debogage) {
218
				$e = "DEBOGAGE : $date - $uri :\n$debogage";
219
				trigger_error($e, E_USER_NOTICE);
220
			}
221
		}
222
	}
473 jpm 223
 
252 jpm 224
	private function reinitialiser() {
225
		$this->nettoyerParametres();
226
	}
227
}