1: <?php
2:
3: /**
4: * Easily talk to APIs using Curl
5: * @package framework
6: * @subpackage api
7: */
8:
9: /**
10: * Class for sending commands to APIs
11: */
12: class Hm_API_Curl {
13:
14: public $last_status;
15: public $format = '';
16:
17: /**
18: * Init
19: * @param string $format format of the result
20: */
21: public function __construct($format = 'json') {
22: $this->format = $format;
23: }
24:
25: /**
26: * Execute command
27: * @param string $url url to fetch content from
28: * @param array $headers HTTP header array
29: * @param array $post post fields
30: * @return array
31: */
32: public function command($url, $headers = [], $post = [], $body = '', $method = false) {
33: $ch = Hm_Functions::c_init();
34: if (!$ch) {
35: return [];
36: }
37: $this->curl_setopt($ch, $url, $headers);
38: $this->curl_setopt_post($ch, $post);
39: if ($method) {
40: Hm_Functions::c_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
41: }
42: if ($body) {
43: Hm_Functions::c_setopt($ch, CURLOPT_POSTFIELDS, $body);
44: }
45: if (env('WIN_CACERT_DIR')) {
46: Hm_Functions::c_setopt($ch, CURLOPT_CAINFO, env('WIN_CACERT_DIR'));
47: }
48: return $this->curl_result($ch);
49: }
50:
51: /**
52: * Setup curl options
53: * @param resource|false $ch curl connection
54: * @param string $url url to fetch content from
55: * @param array $headers HTTP headers
56: * @return void
57: */
58: private function curl_setopt($ch, $url, $headers) {
59: Hm_Functions::c_setopt($ch, CURLOPT_URL, $url);
60: Hm_Functions::c_setopt($ch, CURLOPT_USERAGENT, 'hm3');
61: Hm_Functions::c_setopt($ch, CURLOPT_HTTPHEADER, $headers);
62: Hm_Functions::c_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
63: Hm_Functions::c_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
64: }
65:
66: /**
67: * Setup optional post properties
68: * @param resource|false $ch curl connection
69: * @param array $post post fields
70: * @return void
71: */
72: private function curl_setopt_post($ch, $post) {
73: if (!empty($post)) {
74: Hm_Functions::c_setopt($ch, CURLOPT_POST, true);
75: Hm_Functions::c_setopt($ch, CURLOPT_POSTFIELDS, $this->format_post_data($post));
76: }
77: }
78:
79: /**
80: * Process a curl request result
81: * @param resource $ch curl connection
82: * @return array
83: */
84: private function curl_result($ch) {
85: $curl_result = Hm_Functions::c_exec($ch);
86: $this->last_status = Hm_Functions::c_status($ch);
87: if ($this->format != 'json') {
88: return $curl_result;
89: }
90: $result = @json_decode($curl_result, true);
91: if ($result === NULL) {
92: return [];
93: }
94: return $result;
95: }
96:
97: /**
98: * Format key value pairs into post field format
99: * @param array $data fields to format
100: * @return string
101: */
102: private function format_post_data($data) {
103: $post = [];
104: if (!is_array($data)) {
105: return $data;
106: }
107: foreach ($data as $name => $value) {
108: $post[] = urlencode($name).'='.urlencode($value);
109: }
110: return implode('&', $post);
111: }
112: }
113: