a few random comment fixes
[civicrm-core.git] / api / class.api.php
1 <?php
2
3 /**
4 *
5 * This class allows to consume the API, either from within a module that knows civicrm already:
6 *
7 * @code
8 * require_once('api/class.api.php');
9 * $api = new civicrm_api3();
10 * @endcode
11 *
12 * or from any code on the same server as civicrm
13 *
14 * @code
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));
18 * @endcode
19 *
20 * or to query a remote server via the rest api
21 *
22 * @code
23 * $api = new civicrm_api3 (array ('server' => 'http://example.org',
24 * 'api_key'=>'theusersecretkey',
25 * 'key'=>'thesitesecretkey'));
26 * @endcode
27 *
28 * No matter how initialised and if civicrm is local or remote, you use the class the same way.
29 *
30 * @code
31 * $api->{entity}->{action}($params);
32 * @endcode
33 *
34 * So, to get the individual contacts:
35 *
36 * @code
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;
42 * }
43 * // in theory, doesn't append
44 * } else {
45 * echo $api->errorMsg();
46 * }
47 * @endcode
48 *
49 * Or, to create an event:
50 *
51 * @code
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;
54 * } else {
55 * echo $api->errorMsg();
56 * }
57 * @endcode
58 *
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
61 * are equivalent.
62 *
63 * @code
64 * $api->Activity->Get (42);
65 * $api->Activity->Get (array('id'=>42));
66 * @endcode
67 *
68 *
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']).
72 *
73 * @code
74 * $result = $api->result;
75 * // is the json encoded result
76 * echo $api;
77 * @endcode
78 */
79 class civicrm_api3 {
80
81 /**
82 * @param array API configuration.
83 */
84 function __construct($config = NULL) {
85 $this->local = TRUE;
86 $this->input = array();
87 $this->lastResult = array();
88 if (isset($config) && isset($config['server'])) {
89 // we are calling a remote server via REST
90 $this->local = FALSE;
91 $this->uri = $config['server'];
92 if (isset($config['path'])) {
93 $this->uri .= "/" . $config['path'];
94 }
95 else {
96 $this->uri .= '/sites/all/modules/civicrm/extern/rest.php';
97 }
98 $this->uri .= '?json=1';
99 if (isset($config['key'])) {
100 $this->key = $config['key'];
101 }
102 else {
103 die("\nFATAL:param['key] missing\n");
104 }
105 if (isset($config['api_key'])) {
106 $this->api_key = $config['api_key'];
107 }
108 else {
109 die("\nFATAL:param['api_key] missing\n");
110 }
111 return;
112 }
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();
121 $this->init();
122 }
123 else {
124 $this->cfg = CRM_Core_Config::singleton();
125 }
126 }
127
128 /**
129 * @return string
130 */
131 public function __toString() {
132 return json_encode($this->lastResult);
133 }
134
135 /**
136 * Perform action
137 * @param $action
138 * @param $params
139 * @return bool
140 */
141 public function __call($action, $params) {
142 // @TODO Check if it's a valid action.
143 if (isset($params[0])) {
144 return $this->call($this->currentEntity, $action, $params[0]);
145 }
146 else {
147 return $this->call($this->currentEntity, $action, $this->input);
148 }
149 }
150
151 /**
152 * As of PHP 5.3.0
153 * @param $name
154 * @param $arguments
155 */
156 public static function __callStatic($name, $arguments) {
157 // Should we implement it ?
158 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
159 }
160
161 /**
162 * Call via rest
163 * @param $entity
164 * @param $action
165 * @param array $params
166 * @return \stdClass
167 */
168 function remoteCall($entity, $action, $params = array()) {
169 $fields = "key={$this->key}&api_key={$this->api_key}";
170 $query = $this->uri . "&entity=$entity&action=$action";
171 foreach ($params as $k => $v) {
172 $fields .= "&$k=" . urlencode($v);
173 }
174 if (function_exists('curl_init')) {
175 // To facilitate debugging without leaking info, entity & action
176 // are GET, other data is POST.
177 $ch = curl_init();
178 curl_setopt($ch, CURLOPT_URL, $query);
179 curl_setopt($ch, CURLOPT_POST, count($params) + 2);
180 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
181 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
182 $result = curl_exec($ch);
183 // CiviCRM expects to get back a CiviCRM error object.
184 if (curl_errno($ch)) {
185 $res = new stdClass;
186 $res->is_error = 1;
187 $res->error_message = curl_error($ch);
188 $res->level = "cURL";
189 $res->error = array('cURL error' => curl_error($ch));
190 return $res;
191 }
192 curl_close($ch);
193 }
194 else {
195 // Should be discouraged, because the API credentials and data
196 // are submitted as GET data, increasing chance of exposure..
197 $result = file_get_contents($query . '&' . $fields);
198 }
199 if (!$res = json_decode($result)) {
200 $res = new stdClass;
201 $res->is_error = 1;
202 $res->error_message = 'Unable to parse returned JSON';
203 $res->level = 'json_decode';
204 $res->error = array('Unable to parse returned JSON' => $result);
205 $res->row_result = $result;
206 }
207 return $res;
208 }
209
210 /**
211 * @param $entity
212 * @param string $action
213 * @param array $params
214 *
215 * @return bool
216 */
217 function call($entity, $action = 'Get', $params = array()) {
218 if (is_int($params)) {
219 $params = array('id' => $params);
220 }
221 elseif (is_string($params)) {
222 $params = json_decode($params);
223 }
224
225 if (!isset($params['version'])) {
226 $params['version'] = 3;
227 }
228 if (!isset($params['sequential'])) {
229 $params['sequential'] = 1;
230 }
231
232 if (!$this->local) {
233 $this->lastResult = $this->remoteCall($entity, $action, $params);
234 }
235 else {
236 // Converts a multi-dimentional array into an object.
237 $this->lastResult = json_decode(json_encode(civicrm_api($entity, $action, $params)));
238 }
239 // Reset the input to be ready for a new call.
240 $this->input = array();
241 if (property_exists($this->lastResult, 'is_error')) {
242 return !$this->lastResult->is_error;
243 }
244 // getsingle doesn't have is_error.
245 return TRUE;
246 }
247
248 /**
249 * Helper method for long running programs (eg bots).
250 */
251 function ping() {
252 global $_DB_DATAOBJECT;
253 foreach ($_DB_DATAOBJECT['CONNECTIONS'] as & $c) {
254 if (!$c->connection->ping()) {
255 $c->connect($this->cfg->dsn);
256 if (!$c->connection->ping()) {
257 die("we couldn't connect");
258 }
259 }
260 }
261 }
262
263 /**
264 * Return the last error message.
265 * @return string
266 */
267 function errorMsg() {
268 return $this->lastResult->error_message;
269 }
270
271 /**
272 * Initialize
273 */
274 function init() {
275 CRM_Core_DAO::init($this->cfg->dsn);
276 }
277
278 /**
279 * @param $name
280 * @param null $value
281 * @return $this
282 */
283 public function attr($name, $value = NULL) {
284 if ($value === NULL) {
285 if (property_exists($this->lastResult, $name)) {
286 return $this->lastResult->$name;
287 }
288 }
289 else {
290 $this->input[$name] = $value;
291 }
292 return $this;
293 }
294
295 /**
296 * @return bool
297 */
298 public function is_error() {
299 return (property_exists($this->lastResult, 'is_error') && $this->lastResult->is_error);
300 }
301
302 /**
303 * @param string $name
304 * @return bool
305 */
306 public function is_set($name) {
307 return (isset($this->lastResult->$name));
308 }
309
310 /**
311 * @param $name
312 * @return $this
313 */
314 public function __get($name) {
315 // @TODO Test if valid entity.
316 if (strtolower($name) !== $name) {
317 // Cheap and dumb test to differentiate call to
318 // $api->Entity->Action & value retrieval.
319 $this->currentEntity = $name;
320 return $this;
321 }
322 if ($name === 'result') {
323 return $this->lastResult;
324 }
325 if ($name === 'values') {
326 return $this->lastResult->values;
327 }
328 if (property_exists($this->lastResult, $name)) {
329 return $this->lastResult->$name;
330 }
331 $this->currentEntity = $name;
332 return $this;
333 }
334
335 /**
336 * Or use $api->value.
337 * @return array
338 */
339 public function values() {
340 if (is_array($this->lastResult)) {
341 return $this->lastResult['values'];
342 }
343 else {
344 return $this->lastResult->values;
345 }
346 }
347
348 /**
349 * Or use $api->result.
350 * @return array
351 */
352 public function result() {
353 return $this->lastResult;
354 }
355 }