Merge pull request #19678 from totten/master-guzzle-url
[civicrm-core.git] / api / class.api.php
1 <?php
2
3 /**
4 *
5 * This class allows to consume the API, either from within a module that knows civicrm already:
6 *
7 * ```
8 * require_once('api/class.api.php');
9 * $api = new civicrm_api3();
10 * ```
11 *
12 * or from any code on the same server as civicrm
13 *
14 * ```
15 * require_once('/your/civi/folder/api/class.api.php');
16 * // the path to civicrm.settings.php
17 * $api = new civicrm_api3 (['conf_path'=> '/your/path/to/your/civicrm/or/joomla/site']);
18 * ```
19 *
20 * or to query a remote server via the rest api
21 *
22 * ```
23 * $api = new civicrm_api3 (['server' => 'http://example.org',
24 * 'api_key'=>'theusersecretkey',
25 * 'key'=>'thesitesecretkey']);
26 * ```
27 *
28 * No matter how initialised and if civicrm is local or remote, you use the class the same way.
29 *
30 * ```
31 * $api->{entity}->{action}($params);
32 * ```
33 *
34 * So, to get the individual contacts:
35 *
36 * ```
37 * if ($api->Contact->Get(['contact_type'=>'Individual','return'=>'sort_name,current_employer']) {
38 * // each key of the result array is an attribute of the api
39 * echo "\n contacts found " . $api->count;
40 * foreach ($api->values as $c) {
41 * echo "\n".$c->sort_name. " working for ". $c->current_employer;
42 * }
43 * // in theory, doesn't append
44 * } else {
45 * echo $api->errorMsg();
46 * }
47 * ```
48 *
49 * Or, to create an event:
50 *
51 * ```
52 * if ($api->Event->Create(['title'=>'Test','event_type_id' => 1,'is_public' => 1,'start_date' => 19430429])) {
53 * echo "created event id:". $api->id;
54 * } else {
55 * echo $api->errorMsg();
56 * }
57 * ```
58 *
59 * To make it easier, the Actions can either take for input an
60 * associative array $params, or simply an id. The following two lines
61 * are equivalent.
62 *
63 * ```
64 * $api->Activity->Get (42);
65 * $api->Activity->Get (['id'=>42]);
66 * ```
67 *
68 *
69 * You can also get the result like civicrm_api does, but as an object
70 * instead of an array (eg $entity->attribute instead of
71 * $entity['attribute']).
72 *
73 * ```
74 * $result = $api->result;
75 * // is the json encoded result
76 * echo $api;
77 * ```
78 *
79 * For remote calls, you may need to set the UserAgent and Referer strings for some environments (eg WordFence)
80 * Add 'referer' and 'useragent' to the initialisation config:
81 *
82 * ```
83 * $api = new civicrm_api3 (['server' => 'http://example.org',
84 * 'api_key'=>'theusersecretkey',
85 * 'key'=>'thesitesecretkey',
86 * 'referer'=>'https://my_site',
87 * 'useragent'=>'curl']);
88 * ```
89 */
90 class civicrm_api3 {
91
92 /**
93 * Class constructor.
94 *
95 * @param array $config API configuration.
96 */
97 public function __construct($config = NULL) {
98 $this->local = TRUE;
99 $this->input = [];
100 $this->lastResult = [];
101 if (!empty($config) && !empty($config['server'])) {
102 // we are calling a remote server via REST
103 $this->local = FALSE;
104 $this->uri = $config['server'];
105 if (!empty($config['path'])) {
106 $this->uri .= "/" . $config['path'];
107 }
108 else {
109 $this->uri .= '/sites/all/modules/civicrm/extern/rest.php';
110 }
111 if (!empty($config['key'])) {
112 $this->key = $config['key'];
113 }
114 else {
115 die("\nFATAL:param['key] missing\n");
116 }
117 if (!empty($config['api_key'])) {
118 $this->api_key = $config['api_key'];
119 }
120 else {
121 die("\nFATAL:param['api_key] missing\n");
122 }
123 $this->referer = !empty($config['referer']) ? $config['referer'] : '';
124 $this->useragent = !empty($config['useragent']) ? $config['useragent'] : 'curl';
125 return;
126 }
127 if (!empty($config) && !empty($config['conf_path'])) {
128 if (!defined('CIVICRM_SETTINGS_PATH')) {
129 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
130 }
131 require_once CIVICRM_SETTINGS_PATH;
132 require_once 'CRM/Core/ClassLoader.php';
133 require_once 'api/api.php';
134 require_once "api/v3/utils.php";
135 CRM_Core_ClassLoader::singleton()->register();
136 $this->cfg = CRM_Core_Config::singleton();
137 $this->init();
138 }
139 else {
140 $this->cfg = CRM_Core_Config::singleton();
141 }
142 }
143
144 /**
145 * Convert to string.
146 *
147 * @return string
148 */
149 public function __toString() {
150 return json_encode($this->lastResult);
151 }
152
153 /**
154 * Perform action.
155 *
156 * @param $action
157 * @param $params
158 *
159 * @return bool
160 */
161 public function __call($action, $params) {
162 // @TODO Check if it's a valid action.
163 if (isset($params[0])) {
164 return $this->call($this->currentEntity, $action, $params[0]);
165 }
166 else {
167 return $this->call($this->currentEntity, $action, $this->input);
168 }
169 }
170
171 /**
172 * Call via rest.
173 *
174 * @param $entity
175 * @param $action
176 * @param array $params
177 *
178 * @return \stdClass
179 */
180 private function remoteCall($entity, $action, $params = []) {
181 $query = $this->uri . "?entity=$entity&action=$action";
182 $fields = http_build_query([
183 'key' => $this->key,
184 'api_key' => $this->api_key,
185 'json' => json_encode($params),
186 ]);
187
188 if (function_exists('curl_init')) {
189 // To facilitate debugging without leaking info, entity & action
190 // are GET, other data is POST.
191 $ch = curl_init();
192 curl_setopt($ch, CURLOPT_URL, $query);
193 curl_setopt($ch, CURLOPT_POST, TRUE);
194 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
195 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
196 curl_setopt($ch, CURLOPT_USERAGENT, $this->useragent);
197 if ($this->referer) {
198 curl_setopt($ch, CURLOPT_REFERER, $this->referer);
199 }
200 $result = curl_exec($ch);
201 // CiviCRM expects to get back a CiviCRM error object.
202 if (curl_errno($ch)) {
203 $res = new stdClass();
204 $res->is_error = 1;
205 $res->error_message = curl_error($ch);
206 $res->level = "cURL";
207 $res->error = ['cURL error' => curl_error($ch)];
208 return $res;
209 }
210 curl_close($ch);
211 }
212 else {
213 // Should be discouraged, because the API credentials and data
214 // are submitted as GET data, increasing chance of exposure..
215 $result = file_get_contents($query . '&' . $fields);
216 }
217 if (!$res = json_decode($result)) {
218 $res = new stdClass();
219 $res->is_error = 1;
220 $res->error_message = 'Unable to parse returned JSON';
221 $res->level = 'json_decode';
222 $res->error = ['Unable to parse returned JSON' => $result];
223 $res->row_result = $result;
224 }
225 return $res;
226 }
227
228 /**
229 * Call api function.
230 *
231 * @param $entity
232 * @param string $action
233 * @param array $params
234 *
235 * @return bool
236 */
237 private function call($entity, $action = 'Get', $params = []) {
238 if (is_int($params)) {
239 $params = ['id' => $params];
240 }
241 elseif (is_string($params)) {
242 $params = json_decode($params);
243 }
244
245 if (!isset($params['version'])) {
246 $params['version'] = 3;
247 }
248 if (!isset($params['sequential'])) {
249 $params['sequential'] = 1;
250 }
251
252 if (!$this->local) {
253 $this->lastResult = $this->remoteCall($entity, $action, $params);
254 }
255 else {
256 // Converts a multi-dimentional array into an object.
257 $this->lastResult = json_decode(json_encode(civicrm_api($entity, $action, $params)));
258 }
259 // Reset the input to be ready for a new call.
260 $this->input = [];
261 if (property_exists($this->lastResult, 'is_error')) {
262 return !$this->lastResult->is_error;
263 }
264 // getsingle doesn't have is_error.
265 return TRUE;
266 }
267
268 /**
269 * Helper method for long running programs (eg bots).
270 */
271 public function ping() {
272 global $_DB_DATAOBJECT;
273 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
274 if (!$c->connection->ping()) {
275 $c->connect($this->cfg->dsn);
276 if (!$c->connection->ping()) {
277 die("we couldn't connect");
278 }
279 }
280 }
281 }
282
283 /**
284 * Return the last error message.
285 * @return string
286 */
287 public function errorMsg() {
288 return $this->lastResult->error_message;
289 }
290
291 /**
292 * Initialize.
293 */
294 public function init() {
295 CRM_Core_DAO::init($this->cfg->dsn);
296 }
297
298 /**
299 * Get attribute.
300 *
301 * @param $name
302 * @param null $value
303 *
304 * @return $this
305 */
306 public function attr($name, $value = NULL) {
307 if ($value === NULL) {
308 if (property_exists($this->lastResult, $name)) {
309 return $this->lastResult->$name;
310 }
311 }
312 else {
313 $this->input[$name] = $value;
314 }
315 return $this;
316 }
317
318 /**
319 * Is this an error.
320 *
321 * @return bool
322 */
323 public function is_error() {
324 return (property_exists($this->lastResult, 'is_error') && $this->lastResult->is_error);
325 }
326
327 /**
328 * Check if var is set.
329 *
330 * @param string $name
331 *
332 * @return bool
333 */
334 public function is_set($name) {
335 return (isset($this->lastResult->$name));
336 }
337
338 /**
339 * Get object.
340 *
341 * @param string $name
342 *
343 * @return $this
344 */
345 public function __get($name) {
346 // @TODO Test if valid entity.
347 if (strtolower($name) !== $name) {
348 // Cheap and dumb test to differentiate call to
349 // $api->Entity->Action & value retrieval.
350 $this->currentEntity = $name;
351 return $this;
352 }
353 if ($name === 'result') {
354 return $this->lastResult;
355 }
356 if ($name === 'values') {
357 return $this->lastResult->values;
358 }
359 if (property_exists($this->lastResult, $name)) {
360 return $this->lastResult->$name;
361 }
362 $this->currentEntity = $name;
363 return $this;
364 }
365
366 /**
367 * Or use $api->value.
368 * @return array
369 */
370 public function values() {
371 if (is_array($this->lastResult)) {
372 return $this->lastResult['values'];
373 }
374 else {
375 return $this->lastResult->values;
376 }
377 }
378
379 /**
380 * Or use $api->result.
381 * @return array
382 */
383 public function result() {
384 return $this->lastResult;
385 }
386
387 }