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
82 * @param array API configuration.
84 function __construct($config = NULL) {
86 $this->input
= array();
87 $this->lastResult
= array();
88 if (isset($config) && isset($config['server'])) {
89 // we are calling a remote server via REST
91 $this->uri
= $config['server'];
92 if (isset($config['path'])) {
93 $this->uri
.= "/" . $config['path'];
96 $this->uri
.= '/sites/all/modules/civicrm/extern/rest.php';
98 $this->uri
.= '?json=1';
99 if (isset($config['key'])) {
100 $this->key
= $config['key'];
103 die("\nFATAL:param['key] missing\n");
105 if (isset($config['api_key'])) {
106 $this->api_key
= $config['api_key'];
109 die("\nFATAL:param['api_key] missing\n");
113 if (isset($config) && isset($config['conf_path'])) {
114 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
115 require_once CIVICRM_SETTINGS_PATH
;
116 require_once 'CRM/Core/ClassLoader.php';
117 require_once 'api/api.php';
118 require_once "api/v3/utils.php";
119 CRM_Core_ClassLoader
::singleton()->register();
120 $this->cfg
= CRM_Core_Config
::singleton();
124 $this->cfg
= CRM_Core_Config
::singleton();
131 public function __toString() {
132 return json_encode($this->lastResult
);
138 public function __call($action, $params) {
139 // @TODO Check if it's a valid action.
140 if (isset($params[0])) {
141 return $this->call($this->currentEntity
, $action, $params[0]);
144 return $this->call($this->currentEntity
, $action, $this->input
);
151 public static function __callStatic($name, $arguments) {
152 // Should we implement it ?
153 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
160 function remoteCall($entity, $action, $params = array()) {
161 $fields = "key={$this->key}&api_key={$this->api_key}";
162 $query = $this->uri
. "&entity=$entity&action=$action";
163 foreach ($params as $k => $v) {
164 $fields .= "&$k=" . urlencode($v);
166 if (function_exists('curl_init')) {
167 // To facilitate debugging without leaking info, entity & action
168 // are GET, other data is POST.
170 curl_setopt($ch, CURLOPT_URL
, $query);
171 curl_setopt($ch, CURLOPT_POST
, count($params) +
2);
172 curl_setopt($ch, CURLOPT_POSTFIELDS
, $fields);
173 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, TRUE);
174 $result = curl_exec($ch);
175 // CiviCRM expects to get back a CiviCRM error object.
176 if (curl_errno($ch)) {
179 $res->error_message
= curl_error($ch);
180 $res->level
= "cURL";
181 $res->error
= array('cURL error' => curl_error($ch));
187 // Should be discouraged, because the API credentials and data
188 // are submitted as GET data, increasing chance of exposure..
189 $result = file_get_contents($query . '&' . $fields);
191 if (!$res = json_decode($result)) {
194 $res->error_message
= 'Unable to parse returned JSON';
195 $res->level
= 'json_decode';
196 $res->error
= array('Unable to parse returned JSON' => $result);
197 $res->row_result
= $result;
204 * @param string $action
205 * @param array $params
209 function call($entity, $action = 'Get', $params = array()) {
210 if (is_int($params)) {
211 $params = array('id' => $params);
213 elseif (is_string($params)) {
214 $params = json_decode($params);
217 if (!isset($params['version'])) {
218 $params['version'] = 3;
220 if (!isset($params['sequential'])) {
221 $params['sequential'] = 1;
225 $this->lastResult
= $this->remoteCall($entity, $action, $params);
228 // Converts a multi-dimentional array into an object.
229 $this->lastResult
= json_decode(json_encode(civicrm_api($entity, $action, $params)));
231 // Reset the input to be ready for a new call.
232 $this->input
= array();
233 if (property_exists($this->lastResult
, 'is_error')) {
234 return !$this->lastResult
->is_error
;
236 // getsingle doesn't have is_error.
241 * Helper method for long running programs (eg bots).
244 global $_DB_DATAOBJECT;
245 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
246 if (!$c->connection
->ping()) {
247 $c->connect($this->cfg
->dsn
);
248 if (!$c->connection
->ping()) {
249 die("we couldn't connect");
256 * Return the last error message.
259 function errorMsg() {
260 return $this->lastResult
->error_message
;
267 CRM_Core_DAO
::init($this->cfg
->dsn
);
273 public function attr($name, $value = NULL) {
274 if ($value === NULL) {
275 if (property_exists($this->lastResult
, $name)) {
276 return $this->lastResult
->$name;
280 $this->input
[$name] = $value;
288 public function is_error() {
289 return (property_exists($this->lastResult
, 'is_error') && $this->lastResult
->is_error
);
293 * @param string $name
296 public function is_set($name) {
297 return (isset($this->lastResult
->$name));
303 public function __get($name) {
304 // @TODO Test if valid entity.
305 if (strtolower($name) !== $name) {
306 // Cheap and dumb test to differentiate call to
307 // $api->Entity->Action & value retrieval.
308 $this->currentEntity
= $name;
311 if ($name === 'result') {
312 return $this->lastResult
;
314 if ($name === 'values') {
315 return $this->lastResult
->values
;
317 if (property_exists($this->lastResult
, $name)) {
318 return $this->lastResult
->$name;
320 $this->currentEntity
= $name;
325 * Or use $api->value.
328 public function values() {
329 if (is_array($this->lastResult
)) {
330 return $this->lastResult
['values'];
333 return $this->lastResult
->values
;
338 * Or use $api->result.
341 public function result() {
342 return $this->lastResult
;