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