CRM-14423 - Extract class CRM_Utils_Check from CRM_Utils_Check_Security
[civicrm-core.git] / api / class.api.php
CommitLineData
6a488035 1<?php
6a488035
TO
2
3/**
ade83e4b
CB
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','api_key'=>'theusersecretkey','key'=>'thesitesecretkey'));
24 * @endcode
25 *
26 * No matter how initialised and if civicrm is local or remote, you use the class the same way.
27 *
28 * @code
29 * $api->{entity}->{action}($params);
30 * @endcode
31 *
32 * So, to get the individual contacts:
33 *
34 * @code
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;
40 * }
41 * // in theory, doesn't append
42 * } else {
43 * echo $api->errorMsg();
44 * }
45 * @endcode
46 *
47 * Or, to create an event:
48 *
49 * @code
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;
52 * } else {
53 * echo $api->errorMsg();
54 * }
55 * @endcode
56 *
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
59 * are equivalent.
60 *
61 * @code
62 * $api->Activity->Get (42);
63 * $api->Activity->Get (array('id'=>42));
64 * @endcode
65 *
66 *
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']).
70 *
71 * @code
72 * $result = $api->result;
73 * // is the json encoded result
74 * echo $api;
75 * @endcode
6a488035
TO
76 */
77class civicrm_api3 {
ade83e4b
CB
78
79 /**
80 * @param array API configuration.
81 */
6a488035
TO
82 function __construct($config = NULL) {
83 $this->local = TRUE;
84 $this->input = array();
85 $this->lastResult = array();
86 if (isset($config) && isset($config['server'])) {
87 // we are calling a remote server via REST
88 $this->local = FALSE;
89 $this->uri = $config['server'];
90 if (isset($config['path'])) {
91 $this->uri .= "/" . $config['path'];
92 }
ade83e4b
CB
93 else {
94 $this->uri .= '/sites/all/modules/civicrm/extern/rest.php';
95 }
6a488035
TO
96 $this->uri .= '?json=1';
97 if (isset($config['key'])) {
98 $this->key = $config['key'];
99 }
100 else {
101 die("\nFATAL:param['key] missing\n");
102 }
103 if (isset($config['api_key'])) {
104 $this->api_key = $config['api_key'];
105 }
106 else {
107 die("\nFATAL:param['api_key] missing\n");
108 }
6a488035
TO
109 return;
110 }
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;
f9c7ce43 114 require_once 'CRM/Core/ClassLoader.php';
6a488035
TO
115 require_once 'api/api.php';
116 require_once "api/v3/utils.php";
f9c7ce43 117 CRM_Core_ClassLoader::singleton()->register();
6a488035
TO
118 $this->cfg = CRM_Core_Config::singleton();
119 $this->init();
120 }
121 else {
122 $this->cfg = CRM_Core_Config::singleton();
123 }
124 }
125
ade83e4b
CB
126 /**
127 *
128 */
6a488035
TO
129 public function __toString() {
130 return json_encode($this->lastResult);
131 }
132
ade83e4b
CB
133 /**
134 *
135 */
6a488035 136 public function __call($action, $params) {
ade83e4b 137 // @TODO Check if it's a valid action.
6a488035
TO
138 if (isset($params[0])) {
139 return $this->call($this->currentEntity, $action, $params[0]);
140 }
141 else {
142 return $this->call($this->currentEntity, $action, $this->input);
143 }
144 }
145
ade83e4b
CB
146 /**
147 * As of PHP 5.3.0
148 */
6a488035
TO
149 public static function __callStatic($name, $arguments) {
150 // Should we implement it ?
151 echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
152 }
153
ade83e4b
CB
154 /**
155 *
156 */
157 function remoteCall($entity, $action, $params = array()) {
6a488035
TO
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);
162 }
163 if (function_exists('curl_init')) {
ade83e4b
CB
164 // To facilitate debugging without leaking info, entity & action
165 // are GET, other data is POST.
6a488035
TO
166 $ch = curl_init();
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);
6a488035 171 $result = curl_exec($ch);
7a514fb1
CB
172 // CiviCRM expects to get back a CiviCRM error object.
173 if (curl_errno($ch)) {
ade83e4b
CB
174 $res = new stdClass;
175 $res->is_error = 1;
7922c1d3
XD
176 $res->error_message = curl_error($ch);
177 $res->level = "cURL";
ade83e4b
CB
178 $res->error = array('cURL error' => curl_error($ch));
179 return $res;
8ef12e64 180 }
6a488035 181 curl_close($ch);
6a488035
TO
182 }
183 else {
ade83e4b
CB
184 // Should be discouraged, because the API credentials and data
185 // are submitted as GET data, increasing chance of exposure..
6a488035 186 $result = file_get_contents($query . '&' . $fields);
6a488035 187 }
78a069a9
CB
188 if (!$res = json_decode($result)) {
189 $res = new stdClass;
190 $res->is_error = 1;
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;
195 }
196 return $res;
6a488035
TO
197 }
198
ade83e4b 199 function call($entity, $action = 'Get', $params = array()) {
6a488035
TO
200 if (is_int($params)) {
201 $params = array('id' => $params);
202 }
203 elseif (is_string($params)) {
204 $params = json_decode($params);
205 }
206
207 if (!isset($params['version'])) {
6a488035
TO
208 $params['version'] = 3;
209 }
210 if (!isset($params['sequential'])) {
211 $params['sequential'] = 1;
212 }
213
214 if (!$this->local) {
215 $this->lastResult = $this->remoteCall($entity, $action, $params);
216 }
217 else {
ade83e4b 218 // Converts a multi-dimentional array into an object.
6a488035
TO
219 $this->lastResult = json_decode(json_encode(civicrm_api($entity, $action, $params)));
220 }
ade83e4b 221 // Reset the input to be ready for a new call.
6a488035
TO
222 $this->input = array();
223 if (property_exists($this->lastResult, 'is_error')) {
224 return !$this->lastResult->is_error;
225 }
ade83e4b 226 // getsingle doesn't have is_error.
6a488035
TO
227 return TRUE;
228 }
229
ade83e4b
CB
230 /**
231 * Helper method for long running programs (eg bots).
232 */
6a488035
TO
233 function ping() {
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");
240 }
241 }
242 }
243 }
244
ade83e4b
CB
245 /**
246 * Return the last error message.
247 */
6a488035
TO
248 function errorMsg() {
249 return $this->lastResult->error_message;
250 }
251
ade83e4b
CB
252 /**
253 *
254 */
6a488035
TO
255 function init() {
256 CRM_Core_DAO::init($this->cfg->dsn);
257 }
258
ade83e4b
CB
259 /**
260 *
6a488035 261 */
6a488035
TO
262 public function attr($name, $value = NULL) {
263 if ($value === NULL) {
264 if (property_exists($this->lastResult, $name)) {
265 return $this->lastResult->$name;
266 }
267 }
268 else {
269 $this->input[$name] = $value;
270 }
271 return $this;
272 }
273
ade83e4b
CB
274 /**
275 *
276 */
6a488035
TO
277 public function is_error() {
278 return (property_exists($this->lastResult, 'is_error') && $this->lastResult->is_error);
279 }
280
ade83e4b
CB
281 /**
282 *
283 */
6a488035
TO
284 public function is_set($name) {
285 return (isset($this->lastResult->$name));
286 }
287
ade83e4b
CB
288 /**
289 *
290 */
6a488035 291 public function __get($name) {
ade83e4b 292 // @TODO Test if valid entity.
6a488035 293 if (strtolower($name) !== $name) {
ade83e4b
CB
294 // Cheap and dumb test to differentiate call to
295 // $api->Entity->Action & value retrieval.
6a488035
TO
296 $this->currentEntity = $name;
297 return $this;
298 }
6a488035 299 if ($name === 'result') {
6a488035
TO
300 return $this->lastResult;
301 }
302 if ($name === 'values') {
303 return $this->lastResult->values;
304 }
6a488035 305 if (property_exists($this->lastResult, $name)) {
6a488035
TO
306 return $this->lastResult->$name;
307 }
6a488035
TO
308 $this->currentEntity = $name;
309 return $this;
310 }
311
ade83e4b
CB
312 /**
313 * Or use $api->value.
314 */
6a488035
TO
315 public function values() {
316 if (is_array($this->lastResult)) {
317 return $this->lastResult['values'];
318 }
ade83e4b
CB
319 else {
320 return $this->lastResult->values;
321 }
6a488035
TO
322 }
323
ade83e4b
CB
324 /**
325 * Or use $api->result.
326 */
6a488035
TO
327 public function result() {
328 return $this->lastResult;
329 }
330}