|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace IMSGlobal\LTI\HTTP; |
| 4 | + |
| 5 | +use IMSGlobal\LTI\HTTPMessage; |
| 6 | + |
| 7 | +/** |
| 8 | + * Sends HTTP messages with cURL. |
| 9 | + * |
| 10 | + * @author Stephen P Vickers <[email protected]> |
| 11 | + * @copyright IMS Global Learning Consortium Inc |
| 12 | + * @date 2016 |
| 13 | + * @version 3.0.0 |
| 14 | + * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0 |
| 15 | + */ |
| 16 | +class CurlClient implements Client |
| 17 | +{ |
| 18 | + |
| 19 | + /** |
| 20 | + * @inheritdoc |
| 21 | + */ |
| 22 | + public function send(HTTPMessage $message) |
| 23 | + { |
| 24 | + $message->ok = false; |
| 25 | + |
| 26 | + $resp = ''; |
| 27 | + $ch = curl_init(); |
| 28 | + curl_setopt($ch, CURLOPT_URL, $message->url); |
| 29 | + if (!empty($message->requestHeaders)) { |
| 30 | + curl_setopt($ch, CURLOPT_HTTPHEADER, $message->requestHeaders); |
| 31 | + } else { |
| 32 | + curl_setopt($ch, CURLOPT_HEADER, 0); |
| 33 | + } |
| 34 | + if ($message->method === 'POST') { |
| 35 | + curl_setopt($ch, CURLOPT_POST, true); |
| 36 | + curl_setopt($ch, CURLOPT_POSTFIELDS, $message->request); |
| 37 | + } else if ($message->method !== 'GET') { |
| 38 | + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $message->method); |
| 39 | + if (!is_null($message->request)) { |
| 40 | + curl_setopt($ch, CURLOPT_POSTFIELDS, $message->request); |
| 41 | + } |
| 42 | + } |
| 43 | + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
| 44 | + curl_setopt($ch, CURLINFO_HEADER_OUT, true); |
| 45 | + curl_setopt($ch, CURLOPT_HEADER, true); |
| 46 | + curl_setopt($ch, CURLOPT_SSLVERSION, 3); |
| 47 | + $chResp = curl_exec($ch); |
| 48 | + $message->ok = $chResp !== false; |
| 49 | + if ($message->ok) { |
| 50 | + $chResp = str_replace("\r\n", "\n", $chResp); |
| 51 | + $chRespSplit = explode("\n\n", $chResp, 2); |
| 52 | + if ((count($chRespSplit) > 1) && (substr($chRespSplit[1], 0, 5) === 'HTTP/')) { |
| 53 | + $chRespSplit = explode("\n\n", $chRespSplit[1], 2); |
| 54 | + } |
| 55 | + $message->responseHeaders = $chRespSplit[0]; |
| 56 | + $resp = $chRespSplit[1]; |
| 57 | + $message->status = curl_getinfo($ch, CURLINFO_HTTP_CODE); |
| 58 | + $message->ok = $message->status < 400; |
| 59 | + if (!$message->ok) { |
| 60 | + $message->error = curl_error($ch); |
| 61 | + } |
| 62 | + } |
| 63 | + $message->requestHeaders = str_replace("\r\n", "\n", curl_getinfo($ch, CURLINFO_HEADER_OUT)); |
| 64 | + curl_close($ch); |
| 65 | + $message->response = $resp; |
| 66 | + |
| 67 | + return $message->ok; |
| 68 | + } |
| 69 | + |
| 70 | +} |
0 commit comments