-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequest.php
executable file
·340 lines (309 loc) · 10.2 KB
/
Request.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
<?php
require dirname( __FILE__ ) . '/RequestInfo.php';
//{{{ SdfApi_Request
/**
* Библиотека для формирования запроса к API Мегаплана
* Полное описание API Мегаплана: http://wiki.megaplan.ru/API
*
* @since 31.03.2010 19:44:58
* @author megaplan
*/
class SdfApi_Request {
/** Идентификатор пользователя @var string */
protected $accessId;
/** Секретный ключ @var string */
protected $secretKey;
/** Название хоста @var string */
protected $host;
/** Индикатор использования https @var bool */
protected $https = false;
/** Результат последнего запроса @var string */
protected $result;
/** Информация о последнем запросе @var array */
protected $info;
/** Таймаут соединения в секундах @var integer */
protected $timeout;
/** Последняя ошибка CURL-запроса @var string */
protected $error;
/** Путь к файлу, который будет записан всё содержимое ответа @var string */
protected $outputFile = NULL;
//-----------------------------------------------------------------------------
//{{{ __construct
/**
* Создает объект
* @since 01.04.2010 14:43
* @author megaplan
* @param string $AccessId Идентификатор пользователя
* @param string $SecretKey Секретный ключ
* @param string $Host Имя хоста мегаплана
* @param bool $Https Использовать SSL-соединение (false)
* @param integer $Timeout Таймаут подключения
*/
public function __construct( $AccessId, $SecretKey, $Host, $Https = false, $Timeout = 60 )
{
$this->accessId = $AccessId;
$this->secretKey = $SecretKey;
$this->host = $Host;
$this->https = $Https;
$this->timeout = $Timeout;
}
//===========================================================================}}}
//{{{ useHttps
/**
* Устанавливает нужно ли использовать https-соединение
* @since 20.12.2010 13:43
* @author megaplan
* @param bool $Https true
*/
public function useHttps( $Https = true )
{
$this->https = $Https;
}
//===========================================================================}}}
//{{{ setOutputFile
/**
* Устанавливает путь к файлу, в который будет записан всё содержимое ответа
* @since 20.12.2010 13:46
* @author megaplan
* @param string $FilePath Путь к файлу
*/
public function setOutputFile( $FilePath )
{
$this->outputFile = $FilePath;
}
//===========================================================================}}}
//{{{ get
/**
* Отправляет GET-запрос
* @since 31.03.2010 20:17
* @author megaplan
* @param string $Uri
* @param array $Params GET-параметры
* @return string Ответ на запрос
*/
public function get( $Uri, array $Params = NULL )
{
$date = new DateTime();
$Uri = $this->processUri( $Uri, $Params );
$request = SdfApi_RequestInfo::create( 'GET', $this->host, $Uri, array( 'Date' => $date->format( 'r' ) ) );
return $this->send( $request );
}
//===========================================================================}}}
//{{{ post
/**
* Отправляет POST-запрос
* @since 19.05.2010 16:27
* @author megaplan
* @param string $Uri
* @param array $Params GET-параметры
* @return string Ответ на запрос
*/
public function post( $Uri, array $Params = NULL )
{
$date = new DateTime();
$Uri = $this->processUri( $Uri );
$headers = array(
'Date' => $date->format( 'r' ),
'Post-Fields' => $Params,
'Content-Type' => 'application/x-www-form-urlencoded',
);
$request = SdfApi_RequestInfo::create( 'POST', $this->host, $Uri, $headers );
return $this->send( $request );
}
//===========================================================================}}}
//{{{ processUri
/**
* Собирает строку запроса из URI и параметров
* @since 05.04.2010 14:26
* @author megaplan
* @param string $Uri URI
* @param array $Params Параметры запроса
* @return string
*/
public function processUri( $Uri, array $Params = NULL )
{
$part = parse_url( $Uri );
if ( ! preg_match( "/\.[a-z]+$/u", $part['path'] ) ) {
$part['path'] .= '.easy';
}
$Uri = $part['path'];
if ( $Params )
{
if ( ! empty( $part['query'] ) ) {
parse_str( $part['query'], $Params );
}
$Uri .= '?'.http_build_query( $Params );
}
elseif ( ! empty( $part['query'] ) ) {
$Uri .= '?' . $part['query'];
}
return $Uri;
}
//===========================================================================}}}
//{{{ send
/**
* Осуществляет отправку запроса
* @since 01.04.2010 14:53
* @author megaplan
* @param SdfApi_RequestInfo $Request Параметры запроса
* @return string Ответ на запрос
*/
protected function send( SdfApi_RequestInfo $Request )
{
$signature = self::calcSignature( $Request, $this->secretKey );
$headers = array(
'Date: '.$Request->Date,
'X-Sdf-Date:'.$Request->Date,
'X-Authorization: '.$this->accessId . ':' . $signature,
'Accept: application/json'
);
if ( $Request->ContentType ) {
$headers[] = 'Content-Type: '.$Request->ContentType;
}
if ( $Request->ContentMD5 ) {
$headers[] = 'Content-MD5: '.$Request->ContentMD5;
die(var_dump($headers));
}
$url = 'http' . ( $this->https ? 's' : '' ) . '://' . $this->host . $Request->Uri;
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, __CLASS__ );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $Request->Method );
if ( $Request->Method == 'POST' )
{
curl_setopt( $ch, CURLOPT_POST, true );
if ( $Request->PostFields )
{
$postFields = is_array( $Request->PostFields ) ? http_build_query( $Request->PostFields ) : $Request->PostFields;
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postFields );
}
}
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers );
if ( $this->https )
{
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
}
if ( $this->outputFile )
{
$fh = fopen( $this->outputFile, 'wb' );
curl_setopt( $ch, CURLOPT_FILE, $fh );
}
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $this->timeout );
curl_setopt( $ch, CURLOPT_TIMEOUT, $this->timeout );
if ( $this->outputFile )
{
curl_exec( $ch );
$this->result = NULL;
fclose( $fh );
}
else {
$this->result = curl_exec( $ch );
}
$this->info = curl_getinfo( $ch );
$this->error = curl_error( $ch );
curl_close( $ch );
return $this->result;
}
//===========================================================================}}}
//{{{ calcSignature
/**
* Вычисляет подпись запроса
* @since 31.03.2010 20:21
* @author megaplan
* @param SdfApi_RequestInfo $Request Параметры запроса
* @param string $SecretKey Секретный ключ
* @return string Подпись запроса
*/
public static function calcSignature( SdfApi_RequestInfo $Request, $SecretKey )
{
$stringToSign = $Request->Method . "\n" .
$Request->ContentMD5 . "\n" .
$Request->ContentType . "\n" .
$Request->Date . "\n" .
$Request->Host . $Request->Uri;
$signature = base64_encode( self::hashHmac( 'sha1', $stringToSign, $SecretKey ) );
return $signature;
}
//===========================================================================}}}
//{{{ hashHmac
/**
* Клон функции hash_hmac
* @since 14.05.2010
* @author megaplan
* @param string $Algo алгоритм, по которому производится шифрование
* @param string $Data строка для шифрования
* @param string $Key ключ
* @param boolean $RawOutput
* @return string
*/
public static function hashHmac( $Algo, $Data, $Key, $RawOutput = false )
{
if ( function_exists( 'hash_hmac' ) ) {
return hash_hmac( $Algo, $Data, $Key, $RawOutput );
}
$Algo = strtolower( $Algo );
$pack = 'H' . strlen( $Algo( 'test' ) );
$size = 64;
$opad = str_repeat( chr( 0x5C ), $size );
$ipad = str_repeat( chr( 0x36 ), $size );
if ( strlen( $Key ) > $size ){
$Key = str_pad( pack( $pack, $Algo( $Key ) ), $size, chr( 0x00 ) );
} else {
$Key = str_pad( $Key, $size, chr( 0x00 ) );
}
for ( $i = 0; $i < strlen( $Key ) - 1; $i++ ) {
$opad[$i] = $opad[$i] ^ $Key[$i];
$ipad[$i] = $ipad[$i] ^ $Key[$i];
}
$output = $Algo( $opad.pack( $pack, $Algo( $ipad.$Data ) ) );
return ( $RawOutput ) ? pack( $pack, $output ) : $output;
}
//===========================================================================}}}
//{{{ getResult
/**
* Возвращает результат последнего запроса
* @since 07.10.2010 17:45
* @author megaplan
* @return mixed
*/
public function getResult()
{
return $this->result;
}
//===========================================================================}}}
//{{{ getInfo
/**
* Возвращает информацию о последнем запросе
* @since 07.10.2010 17:52
* @author megaplan
* @param string $Param Параметр запроса (если не указан, возвращается вся информация)
* @return mixed
*/
public function getInfo( $Param = NULL )
{
if ( $Param ) {
return isset( $this->info[$Param] ) ? $this->info[$Param] : NULL;
}
else {
return $this->info;
}
}
//===========================================================================}}}
//{{{ getError
/**
* Возвращает последнюю ошибку запроса
* @since 14.10.2010 12:58:23
* @author megaplan
* @return string
*/
public function getError()
{
return $this->error;
}
//===========================================================================}}}
}
/*============================================================================*
* END OF SdfApi_Request *
*=========================================================================}}}*/