298427286b3533e92badfa1e8ade2922ee6fdbf1
[civicrm-core.git] / api / class.api.php
1 <?php
2 // $Id$
3
4 /**
5
6 This class allows to consume the API, either from within a module that knows civicrm already:
7
8 require_once('api/class/api.php');
9 $api = new civicrm_api3();
10
11 or from any code on the same server as civicrm
12
13 require_once('/your/civi/folder/api/class.api.php');
14 // the path to civicrm.settings.php
15 $api = new civicrm_api3 (array('conf_path'=> '/your/path/to/your/civicrm/or/joomla/site));
16
17 or to query a remote server via the rest api
18
19 $api = new civicrm_api3 (array ('server' => 'http://example.org','api_key'=>'theusersecretkey','key'=>'thesitesecretkey'));
20
21 no matter how initialised and if civicrm is local or remote, you use the class the same way
22
23 $api->{entity}->{action}($params);
24
25 so to get the individual contacts
26
27 if ($api->Contact->Get(array(
28 'contact_type'=>'Individual','return'=>'sort_name,current_employer')) {
29 // each key of the result array is an attribute of the api
30 echo "\n contacts found " . $api->count;
31 foreach ($api->values as $c) {
32 echo "\n".$c->sort_name. " working for ". $c->current_employer;
33 }
34 // in theory, doesn't append
35 } else {
36 echo $api->errorMsg();
37 }
38
39 or to create an event
40
41 if ($api->Event->Create(array(
42 'title'=>'Test','event_type_id' => 1,'is_public' => 1,'start_date' => 19430429))) {
43 echo "created event id:". $api->id;
44 } else {
45 echo $api->errorMsg();
46 }
47
48 To make it easier, the Actions can either take for input an associative array $params, or simply an id
49
50 $api->Activity->Get (42);
51
52 being the same as:
53
54 $api->Activity->Get (array('id'=>42));
55
56 you can too get the result like what civicrm_api does, but as an object instead of an array (eg $entity->attribute instead of $entity['attribute']
57
58 $result = $api->result;
59 // is the json encoded result
60 echo $api;
61
62 */
63 class civicrm_api3 {
64 function __construct($config = NULL) {
65 $this->local = TRUE;
66 $this->input = array();
67 $this->lastResult = array();
68 if (isset($config) && isset($config['server'])) {
69 // we are calling a remote server via REST
70 $this->local = FALSE;
71 $this->uri = $config['server'];
72 if (isset($config['path'])) {
73 $this->uri .= "/" . $config['path'];
74 }
75 else $this->uri .= '/sites/all/modules/civicrm/extern/rest.php';
76 $this->uri .= '?json=1';
77 if (isset($config['key'])) {
78 $this->key = $config['key'];
79 }
80 else {
81 die("\nFATAL:param['key] missing\n");
82 }
83 if (isset($config['api_key'])) {
84 $this->api_key = $config['api_key'];
85 }
86 else {
87 die("\nFATAL:param['api_key] missing\n");
88 }
89
90 return;
91 }
92 if (isset($config) && isset($config['conf_path'])) {
93 define('CIVICRM_SETTINGS_PATH', $config['conf_path'] . '/civicrm.settings.php');
94 require_once CIVICRM_SETTINGS_PATH;
95 require_once 'CRM/Core/Classloader.php';
96 require_once 'api/api.php';
97 require_once "api/v3/utils.php";
98 CRM_Core_Classloader::singleton()->register();
99 $this->cfg = CRM_Core_Config::singleton();
100 $this->init();
101 }
102 else {
103 $this->cfg = CRM_Core_Config::singleton();
104 }
105 }
106
107 public function __toString() {
108 return json_encode($this->lastResult);
109 }
110
111 public function __call($action, $params) {
112 // TODO : check if it's a valid action
113 if (isset($params[0])) {
114 return $this->call($this->currentEntity, $action, $params[0]);
115 }
116 else {
117 return $this->call($this->currentEntity, $action, $this->input);
118 }
119 }
120
121 /** As of PHP 5.3.0 */
122 public static function __callStatic($name, $arguments) {
123 // Should we implement it ?
124 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
125 }
126
127 function remoteCall($entity, $action, $params = array(
128 )) {
129 $fields = "key={$this->key}&api_key={$this->api_key}";
130 $query = $this->uri . "&entity=$entity&action=$action";
131 foreach ($params as $k => $v) {
132 $fields .= "&$k=" . urlencode($v);
133 }
134 if (function_exists('curl_init')) {
135 //to make it easier to debug but avoid leaking info, entity&action are the url, the rest is in the POST
136 $ch = curl_init();
137 curl_setopt($ch, CURLOPT_URL, $query);
138 curl_setopt($ch, CURLOPT_POST, count($params) + 2);
139 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
140 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
141
142 //execute post
143 $result = curl_exec($ch);
144 curl_close($ch);
145 return json_decode($result);
146 // not good, all in get when should be in post.
147 }
148 else {
149 $result = file_get_contents($query . '&' . $fields);
150 return json_decode($result);
151 }
152 }
153
154 function call($entity, $action = 'Get', $params = array(
155 )) {
156 if (is_int($params)) {
157 $params = array('id' => $params);
158 }
159 elseif (is_string($params)) {
160 $params = json_decode($params);
161 }
162
163 if (!isset($params['version'])) {
164
165 $params['version'] = 3;
166 }
167 if (!isset($params['sequential'])) {
168 $params['sequential'] = 1;
169 }
170
171 if (!$this->local) {
172 $this->lastResult = $this->remoteCall($entity, $action, $params);
173 }
174 else {
175 // easiest to convert a multi-dimentional array into an object
176 $this->lastResult = json_decode(json_encode(civicrm_api($entity, $action, $params)));
177 }
178 // reset the input to be ready for a new call
179 $this->input = array();
180 if (property_exists($this->lastResult, 'is_error')) {
181 return !$this->lastResult->is_error;
182 }
183 // getsingle doesn't have is_error
184 return TRUE;
185 }
186
187 //* helper method for long running programs (eg bots)
188 function ping() {
189 global $_DB_DATAOBJECT;
190 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
191 if (!$c->connection->ping()) {
192 $c->connect($this->cfg->dsn);
193 if (!$c->connection->ping()) {
194 die("we couldn't connect");
195 }
196 }
197 }
198 }
199
200 function errorMsg() {
201 return $this->lastResult->error_message;
202 }
203
204 function init() {
205 CRM_Core_DAO::init($this->cfg->dsn);
206 }
207
208 /*
209 // return the id
210 * $api->attr ('id');
211 * or
212 * $api->attr ('id',42) //set the id
213 */
214
215
216
217 public function attr($name, $value = NULL) {
218 if ($value === NULL) {
219 if (property_exists($this->lastResult, $name)) {
220 return $this->lastResult->$name;
221 }
222 }
223 else {
224 $this->input[$name] = $value;
225 }
226 return $this;
227 }
228
229 public function is_error() {
230 return (property_exists($this->lastResult, 'is_error') && $this->lastResult->is_error);
231 }
232
233 public function is_set($name) {
234 return (isset($this->lastResult->$name));
235 }
236
237 /* public function __set($name, $value) {
238 echo "Setting '$name' to '$value'\n";
239 }
240 */
241
242
243
244 public function __get($name) {
245 //TODO, test if valid entity
246 if (strtolower($name) !== $name) {
247 //cheap and dumb test to differenciate call to $api->Entity->Action & value retrieval
248 $this->currentEntity = $name;
249 return $this;
250 }
251
252 if ($name === 'result') {
253
254 return $this->lastResult;
255 }
256 if ($name === 'values') {
257 return $this->lastResult->values;
258 }
259
260 if (property_exists($this->lastResult, $name)) {
261
262 return $this->lastResult->$name;
263 }
264
265 $this->currentEntity = $name;
266 return $this;
267 }
268
269
270 // or use $api->value
271 public function values() {
272 if (is_array($this->lastResult)) {
273 return $this->lastResult['values'];
274 }
275 else return $this->lastResult->values;
276 }
277
278 // or use $api->result
279 public function result() {
280 return $this->lastResult;
281 }
282 }
283