blob: ecf307556eb8499a44c5e497877b317eef3cbf7f (
plain)
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
|
<?php
/**
*
* This class is used to communicate with LonCapa
*
* @depends curl
* @modulegroup elearning_interface_modules
* @module LonCapaContentModule
* @package ELearning-Interface
*/
class LonCapaRequest
{
/**
* options for curl
* @var array
*/
protected $options;
/**
* curl resource
* @var resource
*/
protected $ch;
/**
* LonCapaRequest constructor.
*/
public function __construct()
{
$this->ch = curl_init();
$this->initOptions();
}
/**
* initializes curl options
*/
public function initOptions()
{
$this->options = [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
//CURLOPT_CAINFO => '',
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false
];
}
/**
* close connection
*/
public function __destruct()
{
curl_close($this->ch);
}
/**
* set curl options
* @param $key
* @param $value
*/
public function setOption($key, $value)
{
$this->options[$key] = $value;
}
/**
* do a curl request on the given url and return the result if successfull
*
* @param $url string
* @param array $postfields
* @return string
*/
public function request($url, $postfields = null)
{
$result = $this->sendRequest($url, $postfields);
if ($result['statusCode'] == 200) {
return $result['response'];
} else {
// TODO: fehlermeldung wäre schöner
return null;
}
}
/**
* do a curl request on the given url and return the result if successfull
* @param $url string
* @param array $postfields
* @return array
*/
protected function sendRequest($url, $postfields = null)
{
$options = $this->options;
$options[CURLOPT_URL] = $url;
if ($postfields) {
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $postfields;
}
curl_setopt_array($this->ch, $options);
$response = curl_exec($this->ch);
$statusCode = curl_getinfo($this->ch, CURLINFO_HTTP_CODE);
if ($response === false) {
$last_error = curl_error($this->ch);
Log::error(__CLASS__ . ' curl_exec failed: ' . $last_error);
}
return compact('statusCode', 'response');
}
}
|