5 * This class allows to consume the API, either from within a module that knows civicrm already:
8 * require_once('api/class.api.php');
9 * $api = new civicrm_api3();
12 * or from any code on the same server as civicrm
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']);
20 * or to query a remote server via the rest api
23 * $api = new civicrm_api3 (['server' => 'http://example.org',
24 * 'api_key'=>'theusersecretkey',
25 * 'key'=>'thesitesecretkey']);
28 * No matter how initialised and if civicrm is local or remote, you use the class the same way.
31 * $api->{entity}->{action}($params);
34 * So, to get the individual contacts:
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;
43 * // in theory, doesn't append
45 * echo $api->errorMsg();
49 * Or, to create an event:
52 * if ($api->Event->Create(['title'=>'Test','event_type_id' => 1,'is_public' => 1,'start_date' => 19430429])) {
53 * echo "created event id:". $api->id;
55 * echo $api->errorMsg();
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
64 * $api->Activity->Get (42);
65 * $api->Activity->Get (['id'=>42]);
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']).
74 * $result = $api->result;
75 * // is the json encoded result
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:
83 * $api = new civicrm_api3 (['server' => 'http://example.org',
84 * 'api_key'=>'theusersecretkey',
85 * 'key'=>'thesitesecretkey',
86 * 'referer'=>'https://my_site',
87 * 'useragent'=>'curl']);
95 * @param array $config API configuration.
97 public function __construct($config = NULL) {
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'];
109 $this->uri
.= '/sites/all/modules/civicrm/extern/rest.php';
111 if (!empty($config['key'])) {
112 $this->key
= $config['key'];
115 die("\nFATAL:param['key] missing\n");
117 if (!empty($config['api_key'])) {
118 $this->api_key
= $config['api_key'];
121 die("\nFATAL:param['api_key] missing\n");
123 $this->referer
= !empty($config['referer']) ?
$config['referer'] : '';
124 $this->useragent
= !empty($config['useragent']) ?
$config['useragent'] : 'curl';
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');
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();
140 $this->cfg
= CRM_Core_Config
::singleton();
149 public function __toString() {
150 return json_encode($this->lastResult
);
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]);
167 return $this->call($this->currentEntity
, $action, $this->input
);
176 * @param array $params
180 private function remoteCall($entity, $action, $params = []) {
181 $query = $this->uri
. "?entity=$entity&action=$action";
182 $fields = http_build_query([
184 'api_key' => $this->api_key
,
185 'json' => json_encode($params),
188 if (function_exists('curl_init')) {
189 // To facilitate debugging without leaking info, entity & action
190 // are GET, other data is POST.
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
);
200 $result = curl_exec($ch);
201 // CiviCRM expects to get back a CiviCRM error object.
202 if (curl_errno($ch)) {
203 $res = new stdClass();
205 $res->error_message
= curl_error($ch);
206 $res->level
= "cURL";
207 $res->error
= ['cURL error' => curl_error($ch)];
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);
217 if (!$res = json_decode($result)) {
218 $res = new stdClass();
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;
232 * @param string $action
233 * @param array $params
237 private function call($entity, $action = 'Get', $params = []) {
238 if (is_int($params)) {
239 $params = ['id' => $params];
241 elseif (is_string($params)) {
242 $params = json_decode($params);
245 if (!isset($params['version'])) {
246 $params['version'] = 3;
248 if (!isset($params['sequential'])) {
249 $params['sequential'] = 1;
253 $this->lastResult
= $this->remoteCall($entity, $action, $params);
256 // Converts a multi-dimentional array into an object.
257 $this->lastResult
= json_decode(json_encode(civicrm_api($entity, $action, $params)));
259 // Reset the input to be ready for a new call.
261 if (property_exists($this->lastResult
, 'is_error')) {
262 return !$this->lastResult
->is_error
;
264 // getsingle doesn't have is_error.
269 * Helper method for long running programs (eg bots).
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");
284 * Return the last error message.
287 public function errorMsg() {
288 return $this->lastResult
->error_message
;
294 public function init() {
295 CRM_Core_DAO
::init($this->cfg
->dsn
);
306 public function attr($name, $value = NULL) {
307 if ($value === NULL) {
308 if (property_exists($this->lastResult
, $name)) {
309 return $this->lastResult
->$name;
313 $this->input
[$name] = $value;
323 public function is_error() {
324 return (property_exists($this->lastResult
, 'is_error') && $this->lastResult
->is_error
);
328 * Check if var is set.
330 * @param string $name
334 public function is_set($name) {
335 return (isset($this->lastResult
->$name));
341 * @param string $name
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;
353 if ($name === 'result') {
354 return $this->lastResult
;
356 if ($name === 'values') {
357 return $this->lastResult
->values
;
359 if (property_exists($this->lastResult
, $name)) {
360 return $this->lastResult
->$name;
362 $this->currentEntity
= $name;
367 * Or use $api->value.
370 public function values() {
371 if (is_array($this->lastResult
)) {
372 return $this->lastResult
['values'];
375 return $this->lastResult
->values
;
380 * Or use $api->result.
383 public function result() {
384 return $this->lastResult
;