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 (array('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 (array ('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(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;
43 * // in theory, doesn't append
45 * echo $api->errorMsg();
49 * Or, to create an event:
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;
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 (array('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
84 * @param array $config API configuration.
86 public function __construct($config = NULL) {
89 $this->lastResult
= [];
90 if (isset($config) && isset($config['server'])) {
91 // we are calling a remote server via REST
93 $this->uri
= $config['server'];
94 if (isset($config['path'])) {
95 $this->uri
.= "/" . $config['path'];
98 $this->uri
.= '/sites/all/modules/civicrm/extern/rest.php';
100 if (isset($config['key'])) {
101 $this->key
= $config['key'];
104 die("\nFATAL:param['key] missing\n");
106 if (isset($config['api_key'])) {
107 $this->api_key
= $config['api_key'];
110 die("\nFATAL:param['api_key] missing\n");
114 if (isset($config) && isset($config['conf_path'])) {
115 if (!defined('CIVICRM_SETTINGS_PATH')) {
116 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
118 require_once CIVICRM_SETTINGS_PATH
;
119 require_once 'CRM/Core/ClassLoader.php';
120 require_once 'api/api.php';
121 require_once "api/v3/utils.php";
122 CRM_Core_ClassLoader
::singleton()->register();
123 $this->cfg
= CRM_Core_Config
::singleton();
127 $this->cfg
= CRM_Core_Config
::singleton();
136 public function __toString() {
137 return json_encode($this->lastResult
);
148 public function __call($action, $params) {
149 // @TODO Check if it's a valid action.
150 if (isset($params[0])) {
151 return $this->call($this->currentEntity
, $action, $params[0]);
154 return $this->call($this->currentEntity
, $action, $this->input
);
163 * @param array $params
167 private function remoteCall($entity, $action, $params = []) {
168 $query = $this->uri
. "?entity=$entity&action=$action";
169 $fields = http_build_query([
171 'api_key' => $this->api_key
,
172 'json' => json_encode($params),
175 if (function_exists('curl_init')) {
176 // To facilitate debugging without leaking info, entity & action
177 // are GET, other data is POST.
179 curl_setopt($ch, CURLOPT_URL
, $query);
180 curl_setopt($ch, CURLOPT_POST
, TRUE);
181 curl_setopt($ch, CURLOPT_POSTFIELDS
, $fields);
182 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
183 $result = curl_exec($ch);
184 // CiviCRM expects to get back a CiviCRM error object.
185 if (curl_errno($ch)) {
186 $res = new stdClass();
188 $res->error_message
= curl_error($ch);
189 $res->level
= "cURL";
190 $res->error
= ['cURL error' => curl_error($ch)];
196 // Should be discouraged, because the API credentials and data
197 // are submitted as GET data, increasing chance of exposure..
198 $result = file_get_contents($query . '&' . $fields);
200 if (!$res = json_decode($result)) {
201 $res = new stdClass();
203 $res->error_message
= 'Unable to parse returned JSON';
204 $res->level
= 'json_decode';
205 $res->error
= ['Unable to parse returned JSON' => $result];
206 $res->row_result
= $result;
215 * @param string $action
216 * @param array $params
220 private function call($entity, $action = 'Get', $params = []) {
221 if (is_int($params)) {
222 $params = ['id' => $params];
224 elseif (is_string($params)) {
225 $params = json_decode($params);
228 if (!isset($params['version'])) {
229 $params['version'] = 3;
231 if (!isset($params['sequential'])) {
232 $params['sequential'] = 1;
236 $this->lastResult
= $this->remoteCall($entity, $action, $params);
239 // Converts a multi-dimentional array into an object.
240 $this->lastResult
= json_decode(json_encode(civicrm_api($entity, $action, $params)));
242 // Reset the input to be ready for a new call.
244 if (property_exists($this->lastResult
, 'is_error')) {
245 return !$this->lastResult
->is_error
;
247 // getsingle doesn't have is_error.
252 * Helper method for long running programs (eg bots).
254 public function ping() {
255 global $_DB_DATAOBJECT;
256 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
257 if (!$c->connection
->ping()) {
258 $c->connect($this->cfg
->dsn
);
259 if (!$c->connection
->ping()) {
260 die("we couldn't connect");
267 * Return the last error message.
270 public function errorMsg() {
271 return $this->lastResult
->error_message
;
277 public function init() {
278 CRM_Core_DAO
::init($this->cfg
->dsn
);
289 public function attr($name, $value = NULL) {
290 if ($value === NULL) {
291 if (property_exists($this->lastResult
, $name)) {
292 return $this->lastResult
->$name;
296 $this->input
[$name] = $value;
306 public function is_error() {
307 return (property_exists($this->lastResult
, 'is_error') && $this->lastResult
->is_error
);
311 * Check if var is set.
313 * @param string $name
317 public function is_set($name) {
318 return (isset($this->lastResult
->$name));
324 * @param string $name
328 public function __get($name) {
329 // @TODO Test if valid entity.
330 if (strtolower($name) !== $name) {
331 // Cheap and dumb test to differentiate call to
332 // $api->Entity->Action & value retrieval.
333 $this->currentEntity
= $name;
336 if ($name === 'result') {
337 return $this->lastResult
;
339 if ($name === 'values') {
340 return $this->lastResult
->values
;
342 if (property_exists($this->lastResult
, $name)) {
343 return $this->lastResult
->$name;
345 $this->currentEntity
= $name;
350 * Or use $api->value.
353 public function values() {
354 if (is_array($this->lastResult
)) {
355 return $this->lastResult
['values'];
358 return $this->lastResult
->values
;
363 * Or use $api->result.
366 public function result() {
367 return $this->lastResult
;