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','api_key'=>'theusersecretkey','key'=>'thesitesecretkey'));
26 * No matter how initialised and if civicrm is local or remote, you use the class the same way.
29 * $api->{entity}->{action}($params);
32 * So, to get the individual contacts:
35 * if ($api->Contact->Get(array('contact_type'=>'Individual','return'=>'sort_name,current_employer')) {
36 * // each key of the result array is an attribute of the api
37 * echo "\n contacts found " . $api->count;
38 * foreach ($api->values as $c) {
39 * echo "\n".$c->sort_name. " working for ". $c->current_employer;
41 * // in theory, doesn't append
43 * echo $api->errorMsg();
47 * Or, to create an event:
50 * if ($api->Event->Create(array('title'=>'Test','event_type_id' => 1,'is_public' => 1,'start_date' => 19430429))) {
51 * echo "created event id:". $api->id;
53 * echo $api->errorMsg();
57 * To make it easier, the Actions can either take for input an
58 * associative array $params, or simply an id. The following two lines
62 * $api->Activity->Get (42);
63 * $api->Activity->Get (array('id'=>42));
67 * You can also get the result like civicrm_api does, but as an object
68 * instead of an array (eg $entity->attribute instead of
69 * $entity['attribute']).
72 * $result = $api->result;
73 * // is the json encoded result
80 * @param array API configuration.
82 function __construct($config = NULL) {
84 $this->input
= array();
85 $this->lastResult
= array();
86 if (isset($config) && isset($config['server'])) {
87 // we are calling a remote server via REST
89 $this->uri
= $config['server'];
90 if (isset($config['path'])) {
91 $this->uri
.= "/" . $config['path'];
94 $this->uri
.= '/sites/all/modules/civicrm/extern/rest.php';
96 $this->uri
.= '?json=1';
97 if (isset($config['key'])) {
98 $this->key
= $config['key'];
101 die("\nFATAL:param['key] missing\n");
103 if (isset($config['api_key'])) {
104 $this->api_key
= $config['api_key'];
107 die("\nFATAL:param['api_key] missing\n");
111 if (isset($config) && isset($config['conf_path'])) {
112 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
113 require_once CIVICRM_SETTINGS_PATH
;
114 require_once 'CRM/Core/ClassLoader.php';
115 require_once 'api/api.php';
116 require_once "api/v3/utils.php";
117 CRM_Core_ClassLoader
::singleton()->register();
118 $this->cfg
= CRM_Core_Config
::singleton();
122 $this->cfg
= CRM_Core_Config
::singleton();
129 public function __toString() {
130 return json_encode($this->lastResult
);
136 public function __call($action, $params) {
137 // @TODO Check if it's a valid action.
138 if (isset($params[0])) {
139 return $this->call($this->currentEntity
, $action, $params[0]);
142 return $this->call($this->currentEntity
, $action, $this->input
);
149 public static function __callStatic($name, $arguments) {
150 // Should we implement it ?
151 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
157 function remoteCall($entity, $action, $params = array()) {
158 $fields = "key={$this->key}&api_key={$this->api_key}";
159 $query = $this->uri
. "&entity=$entity&action=$action";
160 foreach ($params as $k => $v) {
161 $fields .= "&$k=" . urlencode($v);
163 if (function_exists('curl_init')) {
164 // To facilitate debugging without leaking info, entity & action
165 // are GET, other data is POST.
167 curl_setopt($ch, CURLOPT_URL
, $query);
168 curl_setopt($ch, CURLOPT_POST
, count($params) +
2);
169 curl_setopt($ch, CURLOPT_POSTFIELDS
, $fields);
170 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
171 $result = curl_exec($ch);
172 // CiviCRM expects to get back a CiviCRM error object.
173 if (curl_errno($ch)) {
176 $res->error_message
= curl_error($ch);
177 $res->level
= "cURL";
178 $res->error
= array('cURL error' => curl_error($ch));
184 // Should be discouraged, because the API credentials and data
185 // are submitted as GET data, increasing chance of exposure..
186 $result = file_get_contents($query . '&' . $fields);
188 if (!$res = json_decode($result)) {
191 $res->error_message
= 'Unable to parse returned JSON';
192 $res->level
= 'json_decode';
193 $res->error
= array('Unable to parse returned JSON' => $result);
194 $res->row_result
= $result;
199 function call($entity, $action = 'Get', $params = array()) {
200 if (is_int($params)) {
201 $params = array('id' => $params);
203 elseif (is_string($params)) {
204 $params = json_decode($params);
207 if (!isset($params['version'])) {
208 $params['version'] = 3;
210 if (!isset($params['sequential'])) {
211 $params['sequential'] = 1;
215 $this->lastResult
= $this->remoteCall($entity, $action, $params);
218 // Converts a multi-dimentional array into an object.
219 $this->lastResult
= json_decode(json_encode(civicrm_api($entity, $action, $params)));
221 // Reset the input to be ready for a new call.
222 $this->input
= array();
223 if (property_exists($this->lastResult
, 'is_error')) {
224 return !$this->lastResult
->is_error
;
226 // getsingle doesn't have is_error.
231 * Helper method for long running programs (eg bots).
234 global $_DB_DATAOBJECT;
235 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
236 if (!$c->connection
->ping()) {
237 $c->connect($this->cfg
->dsn
);
238 if (!$c->connection
->ping()) {
239 die("we couldn't connect");
246 * Return the last error message.
248 function errorMsg() {
249 return $this->lastResult
->error_message
;
256 CRM_Core_DAO
::init($this->cfg
->dsn
);
262 public function attr($name, $value = NULL) {
263 if ($value === NULL) {
264 if (property_exists($this->lastResult
, $name)) {
265 return $this->lastResult
->$name;
269 $this->input
[$name] = $value;
277 public function is_error() {
278 return (property_exists($this->lastResult
, 'is_error') && $this->lastResult
->is_error
);
284 public function is_set($name) {
285 return (isset($this->lastResult
->$name));
291 public function __get($name) {
292 // @TODO Test if valid entity.
293 if (strtolower($name) !== $name) {
294 // Cheap and dumb test to differentiate call to
295 // $api->Entity->Action & value retrieval.
296 $this->currentEntity
= $name;
299 if ($name === 'result') {
300 return $this->lastResult
;
302 if ($name === 'values') {
303 return $this->lastResult
->values
;
305 if (property_exists($this->lastResult
, $name)) {
306 return $this->lastResult
->$name;
308 $this->currentEntity
= $name;
313 * Or use $api->value.
315 public function values() {
316 if (is_array($this->lastResult
)) {
317 return $this->lastResult
['values'];
320 return $this->lastResult
->values
;
325 * Or use $api->result.
327 public function result() {
328 return $this->lastResult
;