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