Update class.api to send params as json
[civicrm-core.git] / api / class.api.php
CommitLineData
6a488035 1<?php
6a488035
TO
2
3/**
ade83e4b
CB
4 *
5 * This class allows to consume the API, either from within a module that knows civicrm already:
6 *
7 * @code
0cd417ef 8 * require_once('api/class.api.php');
ade83e4b
CB
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
0cd417ef
KW
23 * $api = new civicrm_api3 (array ('server' => 'http://example.org',
24 * 'api_key'=>'theusersecretkey',
25 * 'key'=>'thesitesecretkey'));
ade83e4b
CB
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
6a488035
TO
78 */
79class civicrm_api3 {
ade83e4b
CB
80
81 /**
dc64d047
EM
82 * Class constructor.
83 *
decce855 84 * @param array $config API configuration.
ade83e4b 85 */
3bdca100 86 public function __construct($config = NULL) {
6a488035
TO
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 }
ade83e4b
CB
97 else {
98 $this->uri .= '/sites/all/modules/civicrm/extern/rest.php';
99 }
6a488035
TO
100 if (isset($config['key'])) {
101 $this->key = $config['key'];
102 }
103 else {
104 die("\nFATAL:param['key] missing\n");
105 }
106 if (isset($config['api_key'])) {
107 $this->api_key = $config['api_key'];
108 }
109 else {
110 die("\nFATAL:param['api_key] missing\n");
111 }
6a488035
TO
112 return;
113 }
114 if (isset($config) && isset($config['conf_path'])) {
115 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
116 require_once CIVICRM_SETTINGS_PATH;
f9c7ce43 117 require_once 'CRM/Core/ClassLoader.php';
6a488035
TO
118 require_once 'api/api.php';
119 require_once "api/v3/utils.php";
f9c7ce43 120 CRM_Core_ClassLoader::singleton()->register();
6a488035
TO
121 $this->cfg = CRM_Core_Config::singleton();
122 $this->init();
123 }
124 else {
125 $this->cfg = CRM_Core_Config::singleton();
126 }
127 }
128
ade83e4b 129 /**
dc64d047
EM
130 * Convert to string.
131 *
c490a46a 132 * @return string
ade83e4b 133 */
6a488035
TO
134 public function __toString() {
135 return json_encode($this->lastResult);
136 }
137
ade83e4b 138 /**
dc64d047
EM
139 * Perform action.
140 *
645ee340
EM
141 * @param $action
142 * @param $params
dc64d047 143 *
645ee340 144 * @return bool
ade83e4b 145 */
6a488035 146 public function __call($action, $params) {
ade83e4b 147 // @TODO Check if it's a valid action.
6a488035
TO
148 if (isset($params[0])) {
149 return $this->call($this->currentEntity, $action, $params[0]);
150 }
151 else {
152 return $this->call($this->currentEntity, $action, $this->input);
153 }
154 }
155
ade83e4b 156 /**
dc64d047
EM
157 * As of PHP 5.3.0.
158 *
645ee340
EM
159 * @param $name
160 * @param $arguments
ade83e4b 161 */
6a488035
TO
162 public static function __callStatic($name, $arguments) {
163 // Should we implement it ?
164 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
165 }
166
ade83e4b 167 /**
dc64d047
EM
168 * Call via rest.
169 *
645ee340
EM
170 * @param $entity
171 * @param $action
172 * @param array $params
dc64d047 173 *
645ee340 174 * @return \stdClass
ade83e4b 175 */
3bdca100 176 public function remoteCall($entity, $action, $params = array()) {
735682e9
CW
177 $fields = "key={$this->key}&api_key={$this->api_key}&json=" . urlencode(json_encode($params));
178 $query = $this->uri . "?entity=$entity&action=$action";
179
6a488035 180 if (function_exists('curl_init')) {
ade83e4b
CB
181 // To facilitate debugging without leaking info, entity & action
182 // are GET, other data is POST.
6a488035
TO
183 $ch = curl_init();
184 curl_setopt($ch, CURLOPT_URL, $query);
735682e9 185 curl_setopt($ch, CURLOPT_POST, TRUE);
6a488035
TO
186 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
187 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
6a488035 188 $result = curl_exec($ch);
7a514fb1
CB
189 // CiviCRM expects to get back a CiviCRM error object.
190 if (curl_errno($ch)) {
3bdca100 191 $res = new stdClass();
ade83e4b 192 $res->is_error = 1;
7922c1d3
XD
193 $res->error_message = curl_error($ch);
194 $res->level = "cURL";
ade83e4b
CB
195 $res->error = array('cURL error' => curl_error($ch));
196 return $res;
8ef12e64 197 }
6a488035 198 curl_close($ch);
6a488035
TO
199 }
200 else {
ade83e4b
CB
201 // Should be discouraged, because the API credentials and data
202 // are submitted as GET data, increasing chance of exposure..
6a488035 203 $result = file_get_contents($query . '&' . $fields);
6a488035 204 }
78a069a9 205 if (!$res = json_decode($result)) {
3bdca100 206 $res = new stdClass();
78a069a9
CB
207 $res->is_error = 1;
208 $res->error_message = 'Unable to parse returned JSON';
209 $res->level = 'json_decode';
210 $res->error = array('Unable to parse returned JSON' => $result);
211 $res->row_result = $result;
212 }
213 return $res;
6a488035
TO
214 }
215
aa1b1481 216 /**
dc64d047
EM
217 * Call api function.
218 *
aa1b1481
EM
219 * @param $entity
220 * @param string $action
221 * @param array $params
222 *
223 * @return bool
224 */
3bdca100 225 public function call($entity, $action = 'Get', $params = array()) {
6a488035
TO
226 if (is_int($params)) {
227 $params = array('id' => $params);
228 }
229 elseif (is_string($params)) {
230 $params = json_decode($params);
231 }
232
233 if (!isset($params['version'])) {
6a488035
TO
234 $params['version'] = 3;
235 }
236 if (!isset($params['sequential'])) {
237 $params['sequential'] = 1;
238 }
239
240 if (!$this->local) {
241 $this->lastResult = $this->remoteCall($entity, $action, $params);
242 }
243 else {
ade83e4b 244 // Converts a multi-dimentional array into an object.
6a488035
TO
245 $this->lastResult = json_decode(json_encode(civicrm_api($entity, $action, $params)));
246 }
ade83e4b 247 // Reset the input to be ready for a new call.
6a488035
TO
248 $this->input = array();
249 if (property_exists($this->lastResult, 'is_error')) {
250 return !$this->lastResult->is_error;
251 }
ade83e4b 252 // getsingle doesn't have is_error.
6a488035
TO
253 return TRUE;
254 }
255
ade83e4b
CB
256 /**
257 * Helper method for long running programs (eg bots).
258 */
3bdca100 259 public function ping() {
6a488035
TO
260 global $_DB_DATAOBJECT;
261 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
262 if (!$c->connection->ping()) {
263 $c->connect($this->cfg->dsn);
264 if (!$c->connection->ping()) {
265 die("we couldn't connect");
266 }
267 }
268 }
269 }
270
ade83e4b
CB
271 /**
272 * Return the last error message.
c490a46a 273 * @return string
ade83e4b 274 */
3bdca100 275 public function errorMsg() {
6a488035
TO
276 return $this->lastResult->error_message;
277 }
278
ade83e4b 279 /**
1747ab99 280 * Initialize.
ade83e4b 281 */
3bdca100 282 public function init() {
6a488035
TO
283 CRM_Core_DAO::init($this->cfg->dsn);
284 }
285
ade83e4b 286 /**
1747ab99
EM
287 * Get attribute.
288 *
645ee340
EM
289 * @param $name
290 * @param null $value
1747ab99 291 *
c490a46a 292 * @return $this
6a488035 293 */
6a488035
TO
294 public function attr($name, $value = NULL) {
295 if ($value === NULL) {
296 if (property_exists($this->lastResult, $name)) {
297 return $this->lastResult->$name;
298 }
299 }
300 else {
301 $this->input[$name] = $value;
302 }
303 return $this;
304 }
305
ade83e4b 306 /**
dc64d047
EM
307 * Is this an error.
308 *
c490a46a 309 * @return bool
ade83e4b 310 */
6a488035
TO
311 public function is_error() {
312 return (property_exists($this->lastResult, 'is_error') && $this->lastResult->is_error);
313 }
314
ade83e4b 315 /**
1747ab99
EM
316 * Check if var is set.
317 *
100fef9d 318 * @param string $name
dc64d047 319 *
c490a46a 320 * @return bool
ade83e4b 321 */
6a488035
TO
322 public function is_set($name) {
323 return (isset($this->lastResult->$name));
324 }
325
ade83e4b 326 /**
1747ab99
EM
327 * Get object.
328 *
329 * @param string $name
dc64d047 330 *
c490a46a 331 * @return $this
ade83e4b 332 */
6a488035 333 public function __get($name) {
ade83e4b 334 // @TODO Test if valid entity.
6a488035 335 if (strtolower($name) !== $name) {
ade83e4b
CB
336 // Cheap and dumb test to differentiate call to
337 // $api->Entity->Action & value retrieval.
6a488035
TO
338 $this->currentEntity = $name;
339 return $this;
340 }
6a488035 341 if ($name === 'result') {
6a488035
TO
342 return $this->lastResult;
343 }
344 if ($name === 'values') {
345 return $this->lastResult->values;
346 }
6a488035 347 if (property_exists($this->lastResult, $name)) {
6a488035
TO
348 return $this->lastResult->$name;
349 }
6a488035
TO
350 $this->currentEntity = $name;
351 return $this;
352 }
353
ade83e4b
CB
354 /**
355 * Or use $api->value.
c490a46a 356 * @return array
ade83e4b 357 */
6a488035
TO
358 public function values() {
359 if (is_array($this->lastResult)) {
360 return $this->lastResult['values'];
361 }
ade83e4b
CB
362 else {
363 return $this->lastResult->values;
364 }
6a488035
TO
365 }
366
ade83e4b
CB
367 /**
368 * Or use $api->result.
c490a46a 369 * @return array
ade83e4b 370 */
6a488035
TO
371 public function result() {
372 return $this->lastResult;
373 }
96025800 374
6a488035 375}