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