| 1 | <?php |
| 2 | /* |
| 3 | +--------------------------------------------------------------------+ |
| 4 | | CiviCRM version 4.7 | |
| 5 | +--------------------------------------------------------------------+ |
| 6 | | Copyright CiviCRM LLC (c) 2004-2015 | |
| 7 | +--------------------------------------------------------------------+ |
| 8 | | This file is a part of CiviCRM. | |
| 9 | | | |
| 10 | | CiviCRM is free software; you can copy, modify, and distribute it | |
| 11 | | under the terms of the GNU Affero General Public License | |
| 12 | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | |
| 13 | | | |
| 14 | | CiviCRM is distributed in the hope that it will be useful, but | |
| 15 | | WITHOUT ANY WARRANTY; without even the implied warranty of | |
| 16 | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | |
| 17 | | See the GNU Affero General Public License for more details. | |
| 18 | | | |
| 19 | | You should have received a copy of the GNU Affero General Public | |
| 20 | | License and the CiviCRM Licensing Exception along | |
| 21 | | with this program; if not, contact CiviCRM LLC | |
| 22 | | at info[AT]civicrm[DOT]org. If you have questions about the | |
| 23 | | GNU Affero General Public License or the licensing of CiviCRM, | |
| 24 | | see the CiviCRM license FAQ at http://civicrm.org/licensing | |
| 25 | +--------------------------------------------------------------------+ |
| 26 | */ |
| 27 | |
| 28 | /** |
| 29 | * This class handles all REST client requests. |
| 30 | * |
| 31 | * @package CRM |
| 32 | * @copyright CiviCRM LLC (c) 2004-2015 |
| 33 | */ |
| 34 | class CRM_Utils_REST { |
| 35 | |
| 36 | /** |
| 37 | * Number of seconds we should let a REST process idle |
| 38 | */ |
| 39 | static $rest_timeout = 0; |
| 40 | |
| 41 | /** |
| 42 | * Cache the actual UF Class |
| 43 | */ |
| 44 | public $ufClass; |
| 45 | |
| 46 | /** |
| 47 | * Class constructor. This caches the real user framework class locally, |
| 48 | * so we can use it for authentication and validation. |
| 49 | * |
| 50 | * @internal param string $uf The userframework class |
| 51 | */ |
| 52 | public function __construct() { |
| 53 | // any external program which call Rest Server is responsible for |
| 54 | // creating and attaching the session |
| 55 | $args = func_get_args(); |
| 56 | $this->ufClass = array_shift($args); |
| 57 | } |
| 58 | |
| 59 | /** |
| 60 | * Simple ping function to test for liveness. |
| 61 | * |
| 62 | * @param string $var |
| 63 | * The string to be echoed. |
| 64 | * |
| 65 | * @return string |
| 66 | */ |
| 67 | public static function ping($var = NULL) { |
| 68 | $session = CRM_Core_Session::singleton(); |
| 69 | $key = $session->get('key'); |
| 70 | // $session->set( 'key', $var ); |
| 71 | return self::simple(array('message' => "PONG: $key")); |
| 72 | } |
| 73 | |
| 74 | /** |
| 75 | * Generates values needed for error messages. |
| 76 | * @param string $message |
| 77 | * |
| 78 | * @return array |
| 79 | */ |
| 80 | public static function error($message = 'Unknown Error') { |
| 81 | $values = array( |
| 82 | 'error_message' => $message, |
| 83 | 'is_error' => 1, |
| 84 | ); |
| 85 | return $values; |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Generates values needed for non-error responses. |
| 90 | * @param array $params |
| 91 | * |
| 92 | * @return array |
| 93 | */ |
| 94 | public static function simple($params) { |
| 95 | $values = array('is_error' => 0); |
| 96 | $values += $params; |
| 97 | return $values; |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * @return string |
| 102 | */ |
| 103 | public function run() { |
| 104 | $result = self::handle(); |
| 105 | return self::output($result); |
| 106 | } |
| 107 | |
| 108 | /** |
| 109 | * @return string |
| 110 | */ |
| 111 | public function bootAndRun() { |
| 112 | $response = $this->loadCMSBootstrap(); |
| 113 | if (is_array($response)) { |
| 114 | return self::output($response); |
| 115 | } |
| 116 | return $this->run(); |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * @param $result |
| 121 | * |
| 122 | * @return string |
| 123 | */ |
| 124 | public static function output(&$result) { |
| 125 | $requestParams = CRM_Utils_Request::exportValues(); |
| 126 | |
| 127 | $hier = FALSE; |
| 128 | if (is_scalar($result)) { |
| 129 | if (!$result) { |
| 130 | $result = 0; |
| 131 | } |
| 132 | $result = self::simple(array('result' => $result)); |
| 133 | } |
| 134 | elseif (is_array($result)) { |
| 135 | if (CRM_Utils_Array::isHierarchical($result)) { |
| 136 | $hier = TRUE; |
| 137 | } |
| 138 | elseif (!array_key_exists('is_error', $result)) { |
| 139 | $result['is_error'] = 0; |
| 140 | } |
| 141 | } |
| 142 | else { |
| 143 | $result = self::error('Could not interpret return values from function.'); |
| 144 | } |
| 145 | |
| 146 | if (!empty($requestParams['json'])) { |
| 147 | if (!empty($requestParams['prettyprint'])) { |
| 148 | // Don't set content-type header for api explorer output |
| 149 | return self::jsonFormated(array_merge($result)); |
| 150 | } |
| 151 | CRM_Utils_System::setHttpHeader('Content-Type', 'application/json'); |
| 152 | return json_encode(array_merge($result)); |
| 153 | } |
| 154 | |
| 155 | if (isset($result['count'])) { |
| 156 | $count = ' count="' . $result['count'] . '" '; |
| 157 | } |
| 158 | else { |
| 159 | $count = ""; |
| 160 | } |
| 161 | $xml = "<?xml version=\"1.0\"?> |
| 162 | <ResultSet xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" $count> |
| 163 | "; |
| 164 | // check if this is a single element result (contact_get etc) |
| 165 | // or multi element |
| 166 | if ($hier) { |
| 167 | foreach ($result['values'] as $k => $v) { |
| 168 | if (is_array($v)) { |
| 169 | $xml .= "<Result>\n" . CRM_Utils_Array::xml($v) . "</Result>\n"; |
| 170 | } |
| 171 | elseif (!is_object($v)) { |
| 172 | $xml .= "<Result>\n<id>{$k}</id><value>{$v}</value></Result>\n"; |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | else { |
| 177 | $xml .= "<Result>\n" . CRM_Utils_Array::xml($result) . "</Result>\n"; |
| 178 | } |
| 179 | |
| 180 | $xml .= "</ResultSet>\n"; |
| 181 | return $xml; |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * @param $data |
| 186 | * |
| 187 | * @deprecated - switch to native JSON_PRETTY_PRINT when we drop support for php 5.3 |
| 188 | * |
| 189 | * @return string |
| 190 | */ |
| 191 | public static function jsonFormated($data) { |
| 192 | // If php is 5.4+ we can use the native method |
| 193 | if (defined('JSON_PRETTY_PRINT')) { |
| 194 | return json_encode($data, JSON_PRETTY_PRINT + JSON_UNESCAPED_SLASHES + JSON_UNESCAPED_UNICODE); |
| 195 | } |
| 196 | |
| 197 | // PHP 5.3 shim |
| 198 | $json = str_replace('\/', '/', json_encode($data)); |
| 199 | $tabcount = 0; |
| 200 | $result = ''; |
| 201 | $inquote = FALSE; |
| 202 | $inarray = FALSE; |
| 203 | $ignorenext = FALSE; |
| 204 | |
| 205 | $tab = "\t"; |
| 206 | $newline = "\n"; |
| 207 | |
| 208 | for ($i = 0; $i < strlen($json); $i++) { |
| 209 | $char = $json[$i]; |
| 210 | |
| 211 | if ($ignorenext) { |
| 212 | $result .= $char; |
| 213 | $ignorenext = FALSE; |
| 214 | } |
| 215 | else { |
| 216 | switch ($char) { |
| 217 | case '{': |
| 218 | if ($inquote) { |
| 219 | $result .= $char; |
| 220 | } |
| 221 | else { |
| 222 | $inarray = FALSE; |
| 223 | $tabcount++; |
| 224 | $result .= $char . $newline . str_repeat($tab, $tabcount); |
| 225 | } |
| 226 | break; |
| 227 | |
| 228 | case '}': |
| 229 | if ($inquote) { |
| 230 | $result .= $char; |
| 231 | } |
| 232 | else { |
| 233 | $tabcount--; |
| 234 | $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char; |
| 235 | } |
| 236 | break; |
| 237 | |
| 238 | case ',': |
| 239 | if ($inquote || $inarray) { |
| 240 | $result .= $char; |
| 241 | } |
| 242 | else { |
| 243 | $result .= $char . $newline . str_repeat($tab, $tabcount); |
| 244 | } |
| 245 | break; |
| 246 | |
| 247 | case '"': |
| 248 | $inquote = !$inquote; |
| 249 | $result .= $char; |
| 250 | break; |
| 251 | |
| 252 | case '\\': |
| 253 | if ($inquote) { |
| 254 | $ignorenext = TRUE; |
| 255 | } |
| 256 | $result .= $char; |
| 257 | break; |
| 258 | |
| 259 | case '[': |
| 260 | $inarray = TRUE; |
| 261 | $result .= $char; |
| 262 | break; |
| 263 | |
| 264 | case ']': |
| 265 | $inarray = FALSE; |
| 266 | $result .= $char; |
| 267 | break; |
| 268 | |
| 269 | default: |
| 270 | $result .= $char; |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | return $result; |
| 276 | } |
| 277 | |
| 278 | /** |
| 279 | * @return array|int |
| 280 | */ |
| 281 | public static function handle() { |
| 282 | $requestParams = CRM_Utils_Request::exportValues(); |
| 283 | |
| 284 | // Get the function name being called from the q parameter in the query string |
| 285 | $q = CRM_Utils_array::value('q', $requestParams); |
| 286 | // or for the rest interface, from fnName |
| 287 | $r = CRM_Utils_array::value('fnName', $requestParams); |
| 288 | if (!empty($r)) { |
| 289 | $q = $r; |
| 290 | } |
| 291 | $entity = CRM_Utils_array::value('entity', $requestParams); |
| 292 | if (empty($entity) && !empty($q)) { |
| 293 | $args = explode('/', $q); |
| 294 | // If the function isn't in the civicrm namespace, reject the request. |
| 295 | if ($args[0] != 'civicrm') { |
| 296 | return self::error('Unknown function invocation.'); |
| 297 | } |
| 298 | |
| 299 | // If the query string is malformed, reject the request. |
| 300 | // Does this mean it will reject it |
| 301 | if ((count($args) != 3) && ($args[1] != 'ping')) { |
| 302 | return self::error('Unknown function invocation.'); |
| 303 | } |
| 304 | $store = NULL; |
| 305 | |
| 306 | if ($args[1] == 'ping') { |
| 307 | return self::ping(); |
| 308 | } |
| 309 | } |
| 310 | else { |
| 311 | // or the api format (entity+action) |
| 312 | $args = array(); |
| 313 | $args[0] = 'civicrm'; |
| 314 | $args[1] = CRM_Utils_array::value('entity', $requestParams); |
| 315 | $args[2] = CRM_Utils_array::value('action', $requestParams); |
| 316 | } |
| 317 | |
| 318 | // Everyone should be required to provide the server key, so the whole |
| 319 | // interface can be disabled in more change to the configuration file. |
| 320 | // first check for civicrm site key |
| 321 | if (!CRM_Utils_System::authenticateKey(FALSE)) { |
| 322 | $docLink = CRM_Utils_System::docURL2("Managing Scheduled Jobs", TRUE, NULL, NULL, NULL, "wiki"); |
| 323 | $key = CRM_Utils_array::value('key', $requestParams); |
| 324 | if (empty($key)) { |
| 325 | return self::error("FATAL: mandatory param 'key' missing. More info at: " . $docLink); |
| 326 | } |
| 327 | return self::error("FATAL: 'key' is incorrect. More info at: " . $docLink); |
| 328 | } |
| 329 | |
| 330 | // At this point we know we are not calling ping which does not require authentication. |
| 331 | // Therefore we now need a valid server key and API key. |
| 332 | // Check and see if a valid secret API key is provided. |
| 333 | $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST'); |
| 334 | if (!$api_key || strtolower($api_key) == 'null') { |
| 335 | return self::error("FATAL: mandatory param 'api_key' (user key) missing"); |
| 336 | } |
| 337 | $valid_user = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key'); |
| 338 | |
| 339 | // If we didn't find a valid user, die |
| 340 | if (empty($valid_user)) { |
| 341 | return self::error("User API key invalid"); |
| 342 | } |
| 343 | |
| 344 | return self::process($args, self::buildParamList()); |
| 345 | } |
| 346 | |
| 347 | /** |
| 348 | * @param $args |
| 349 | * @param array $params |
| 350 | * |
| 351 | * @return array|int |
| 352 | */ |
| 353 | public static function process(&$args, $params) { |
| 354 | $params['check_permissions'] = TRUE; |
| 355 | $fnName = $apiFile = NULL; |
| 356 | // clean up all function / class names. they should be alphanumeric and _ only |
| 357 | for ($i = 1; $i <= 3; $i++) { |
| 358 | if (!empty($args[$i])) { |
| 359 | $args[$i] = CRM_Utils_String::munge($args[$i]); |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | // incase of ajax functions className is passed in url |
| 364 | if (isset($params['className'])) { |
| 365 | $params['className'] = CRM_Utils_String::munge($params['className']); |
| 366 | |
| 367 | // functions that are defined only in AJAX.php can be called via |
| 368 | // rest interface |
| 369 | if (!CRM_Core_Page_AJAX::checkAuthz('method', $params['className'], $params['fnName'])) { |
| 370 | return self::error('Unknown function invocation.'); |
| 371 | } |
| 372 | |
| 373 | return call_user_func(array($params['className'], $params['fnName']), $params); |
| 374 | } |
| 375 | |
| 376 | if (!array_key_exists('version', $params)) { |
| 377 | $params['version'] = 3; |
| 378 | } |
| 379 | |
| 380 | if ($params['version'] == 2) { |
| 381 | $result['is_error'] = 1; |
| 382 | $result['error_message'] = "FATAL: API v2 not accessible from ajax/REST"; |
| 383 | $result['deprecated'] = "Please upgrade to API v3"; |
| 384 | return $result; |
| 385 | } |
| 386 | |
| 387 | if ($_SERVER['REQUEST_METHOD'] == 'GET' && |
| 388 | strtolower(substr($args[2], 0, 3)) != 'get' && |
| 389 | strtolower($args[2] != 'check')) { |
| 390 | // get only valid for non destructive methods |
| 391 | require_once 'api/v3/utils.php'; |
| 392 | return civicrm_api3_create_error("SECURITY: All requests that modify the database must be http POST, not GET.", |
| 393 | array( |
| 394 | 'IP' => $_SERVER['REMOTE_ADDR'], |
| 395 | 'level' => 'security', |
| 396 | 'referer' => $_SERVER['HTTP_REFERER'], |
| 397 | 'reason' => 'Destructive HTTP GET', |
| 398 | ) |
| 399 | ); |
| 400 | } |
| 401 | |
| 402 | // trap all fatal errors |
| 403 | $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); |
| 404 | $result = civicrm_api($args[1], $args[2], $params); |
| 405 | unset($errorScope); |
| 406 | |
| 407 | if ($result === FALSE) { |
| 408 | return self::error('Unknown error.'); |
| 409 | } |
| 410 | return $result; |
| 411 | } |
| 412 | |
| 413 | /** |
| 414 | * @return array|mixed|null |
| 415 | */ |
| 416 | public static function &buildParamList() { |
| 417 | $requestParams = CRM_Utils_Request::exportValues(); |
| 418 | $params = array(); |
| 419 | |
| 420 | $skipVars = array( |
| 421 | 'q' => 1, |
| 422 | 'json' => 1, |
| 423 | 'key' => 1, |
| 424 | 'api_key' => 1, |
| 425 | 'entity' => 1, |
| 426 | 'action' => 1, |
| 427 | ); |
| 428 | |
| 429 | if (array_key_exists('json', $requestParams) && $requestParams['json'][0] == "{") { |
| 430 | $params = json_decode($requestParams['json'], TRUE); |
| 431 | if ($params === NULL) { |
| 432 | CRM_Utils_JSON::output(array('is_error' => 1, 'error_message', 'Unable to decode supplied JSON.')); |
| 433 | } |
| 434 | } |
| 435 | foreach ($requestParams as $n => $v) { |
| 436 | if (!array_key_exists($n, $skipVars)) { |
| 437 | $params[$n] = $v; |
| 438 | } |
| 439 | } |
| 440 | if (array_key_exists('return', $requestParams) && is_array($requestParams['return'])) { |
| 441 | foreach ($requestParams['return'] as $key => $v) { |
| 442 | $params['return.' . $key] = 1; |
| 443 | } |
| 444 | } |
| 445 | return $params; |
| 446 | } |
| 447 | |
| 448 | /** |
| 449 | * @param $pearError |
| 450 | */ |
| 451 | public static function fatal($pearError) { |
| 452 | CRM_Utils_System::setHttpHeader('Content-Type', 'text/xml'); |
| 453 | $error = array(); |
| 454 | $error['code'] = $pearError->getCode(); |
| 455 | $error['error_message'] = $pearError->getMessage(); |
| 456 | $error['mode'] = $pearError->getMode(); |
| 457 | $error['debug_info'] = $pearError->getDebugInfo(); |
| 458 | $error['type'] = $pearError->getType(); |
| 459 | $error['user_info'] = $pearError->getUserInfo(); |
| 460 | $error['to_string'] = $pearError->toString(); |
| 461 | $error['is_error'] = 1; |
| 462 | |
| 463 | echo self::output($error); |
| 464 | |
| 465 | CRM_Utils_System::civiExit(); |
| 466 | } |
| 467 | |
| 468 | /** |
| 469 | * used to load a template "inline", eg. for ajax, without having to build a menu for each template |
| 470 | */ |
| 471 | public static function loadTemplate() { |
| 472 | $request = CRM_Utils_Request::retrieve('q', 'String'); |
| 473 | if (FALSE !== strpos($request, '..')) { |
| 474 | die ("SECURITY FATAL: the url can't contain '..'. Please report the issue on the forum at civicrm.org"); |
| 475 | } |
| 476 | |
| 477 | $request = explode('/', $request); |
| 478 | $entity = _civicrm_api_get_camel_name($request[2]); |
| 479 | $tplfile = _civicrm_api_get_camel_name($request[3]); |
| 480 | |
| 481 | $tpl = 'CRM/' . $entity . '/Page/Inline/' . $tplfile . '.tpl'; |
| 482 | $smarty = CRM_Core_Smarty::singleton(); |
| 483 | CRM_Utils_System::setTitle("$entity::$tplfile inline $tpl"); |
| 484 | if (!$smarty->template_exists($tpl)) { |
| 485 | CRM_Utils_System::setHttpHeader("Status", "404 Not Found"); |
| 486 | die ("Can't find the requested template file templates/$tpl"); |
| 487 | } |
| 488 | if (array_key_exists('id', $_GET)) {// special treatmenent, because it's often used |
| 489 | $smarty->assign('id', (int) $_GET['id']);// an id is always positive |
| 490 | } |
| 491 | $pos = strpos(implode(array_keys($_GET)), '<'); |
| 492 | |
| 493 | if ($pos !== FALSE) { |
| 494 | die ("SECURITY FATAL: one of the param names contains <"); |
| 495 | } |
| 496 | $param = array_map('htmlentities', $_GET); |
| 497 | unset($param['q']); |
| 498 | $smarty->assign_by_ref("request", $param); |
| 499 | |
| 500 | if (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
| 501 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" |
| 502 | ) { |
| 503 | |
| 504 | $smarty->assign('tplFile', $tpl); |
| 505 | $config = CRM_Core_Config::singleton(); |
| 506 | $content = $smarty->fetch('CRM/common/' . strtolower($config->userFramework) . '.tpl'); |
| 507 | |
| 508 | if (!defined('CIVICRM_UF_HEAD') && $region = CRM_Core_Region::instance('html-header', FALSE)) { |
| 509 | CRM_Utils_System::addHTMLHead($region->render('')); |
| 510 | } |
| 511 | CRM_Utils_System::appendTPLFile($tpl, $content); |
| 512 | |
| 513 | return CRM_Utils_System::theme($content); |
| 514 | |
| 515 | } |
| 516 | else { |
| 517 | $content = "<!-- .tpl file embedded: $tpl -->\n"; |
| 518 | CRM_Utils_System::appendTPLFile($tpl, $content); |
| 519 | echo $content . $smarty->fetch($tpl); |
| 520 | CRM_Utils_System::civiExit(); |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | /** |
| 525 | * This is a wrapper so you can call an api via json (it returns json too) |
| 526 | * http://example.org/civicrm/api/json?entity=Contact&action=Get"&json={"contact_type":"Individual","email.get.email":{}} |
| 527 | * to take all the emails from individuals. |
| 528 | * Works for POST & GET (POST recommended). |
| 529 | */ |
| 530 | public static function ajaxJson() { |
| 531 | $requestParams = CRM_Utils_Request::exportValues(); |
| 532 | |
| 533 | require_once 'api/v3/utils.php'; |
| 534 | $config = CRM_Core_Config::singleton(); |
| 535 | if (!$config->debug && (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
| 536 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" |
| 537 | ) |
| 538 | ) { |
| 539 | $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", |
| 540 | array( |
| 541 | 'IP' => $_SERVER['REMOTE_ADDR'], |
| 542 | 'level' => 'security', |
| 543 | 'referer' => $_SERVER['HTTP_REFERER'], |
| 544 | 'reason' => 'CSRF suspected', |
| 545 | ) |
| 546 | ); |
| 547 | CRM_Utils_JSON::output($error); |
| 548 | } |
| 549 | if (empty($requestParams['entity'])) { |
| 550 | CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity param')); |
| 551 | } |
| 552 | if (empty($requestParams['entity'])) { |
| 553 | CRM_Utils_JSON::output(civicrm_api3_create_error('missing entity entity')); |
| 554 | } |
| 555 | if (!empty($requestParams['json'])) { |
| 556 | $params = json_decode($requestParams['json'], TRUE); |
| 557 | } |
| 558 | $entity = CRM_Utils_String::munge(CRM_Utils_Array::value('entity', $requestParams)); |
| 559 | $action = CRM_Utils_String::munge(CRM_Utils_Array::value('action', $requestParams)); |
| 560 | if (!is_array($params)) { |
| 561 | CRM_Utils_JSON::output(array( |
| 562 | 'is_error' => 1, |
| 563 | 'error_message' => 'invalid json format: ?{"param_with_double_quote":"value"}', |
| 564 | )); |
| 565 | } |
| 566 | |
| 567 | $params['check_permissions'] = TRUE; |
| 568 | $params['version'] = 3; |
| 569 | $_GET['json'] = $requestParams['json'] = 1; // $requestParams is local-only; this line seems pointless unless there's a side-effect influencing other functions |
| 570 | if (!$params['sequential']) { |
| 571 | $params['sequential'] = 1; |
| 572 | } |
| 573 | |
| 574 | // trap all fatal errors |
| 575 | $errorScope = CRM_Core_TemporaryErrorScope::create(array('CRM_Utils_REST', 'fatal')); |
| 576 | $result = civicrm_api($entity, $action, $params); |
| 577 | unset($errorScope); |
| 578 | |
| 579 | echo self::output($result); |
| 580 | |
| 581 | CRM_Utils_System::civiExit(); |
| 582 | } |
| 583 | |
| 584 | /** |
| 585 | * Run ajax request. |
| 586 | * |
| 587 | * @return array |
| 588 | */ |
| 589 | public static function ajax() { |
| 590 | $requestParams = CRM_Utils_Request::exportValues(); |
| 591 | |
| 592 | // this is driven by the menu system, so we can use permissioning to |
| 593 | // restrict calls to this etc |
| 594 | // the request has to be sent by an ajax call. First line of protection against csrf |
| 595 | $config = CRM_Core_Config::singleton(); |
| 596 | if (!$config->debug && |
| 597 | (!array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER) || |
| 598 | $_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest" |
| 599 | ) |
| 600 | ) { |
| 601 | require_once 'api/v3/utils.php'; |
| 602 | $error = civicrm_api3_create_error("SECURITY ALERT: Ajax requests can only be issued by javascript clients, eg. CRM.api3().", |
| 603 | array( |
| 604 | 'IP' => $_SERVER['REMOTE_ADDR'], |
| 605 | 'level' => 'security', |
| 606 | 'referer' => $_SERVER['HTTP_REFERER'], |
| 607 | 'reason' => 'CSRF suspected', |
| 608 | ) |
| 609 | ); |
| 610 | CRM_Utils_JSON::output($error); |
| 611 | } |
| 612 | |
| 613 | $q = CRM_Utils_Array::value('fnName', $requestParams); |
| 614 | if (!$q) { |
| 615 | $entity = CRM_Utils_Array::value('entity', $requestParams); |
| 616 | $action = CRM_Utils_Array::value('action', $requestParams); |
| 617 | if (!$entity || !$action) { |
| 618 | $err = array('error_message' => 'missing mandatory params "entity=" or "action="', 'is_error' => 1); |
| 619 | echo self::output($err); |
| 620 | CRM_Utils_System::civiExit(); |
| 621 | } |
| 622 | $args = array('civicrm', $entity, $action); |
| 623 | } |
| 624 | else { |
| 625 | $args = explode('/', $q); |
| 626 | } |
| 627 | |
| 628 | // get the class name, since all ajax functions pass className |
| 629 | $className = CRM_Utils_Array::value('className', $requestParams); |
| 630 | |
| 631 | // If the function isn't in the civicrm namespace, reject the request. |
| 632 | if (($args[0] != 'civicrm' && count($args) != 3) && !$className) { |
| 633 | return self::error('Unknown function invocation.'); |
| 634 | } |
| 635 | |
| 636 | // Support for multiple api calls |
| 637 | if (isset($entity) && $entity === 'api3') { |
| 638 | $result = self::processMultiple(); |
| 639 | } |
| 640 | else { |
| 641 | $result = self::process($args, self::buildParamList()); |
| 642 | } |
| 643 | |
| 644 | echo self::output($result); |
| 645 | |
| 646 | CRM_Utils_System::civiExit(); |
| 647 | } |
| 648 | |
| 649 | /** |
| 650 | * Callback for multiple ajax api calls from CRM.api3() |
| 651 | * @return array |
| 652 | */ |
| 653 | public static function processMultiple() { |
| 654 | $output = array(); |
| 655 | foreach (json_decode($_REQUEST['json'], TRUE) as $key => $call) { |
| 656 | $args = array( |
| 657 | 'civicrm', |
| 658 | $call[0], |
| 659 | $call[1], |
| 660 | ); |
| 661 | $output[$key] = self::process($args, CRM_Utils_Array::value(2, $call, array())); |
| 662 | } |
| 663 | return $output; |
| 664 | } |
| 665 | |
| 666 | /** |
| 667 | * @return array|NULL |
| 668 | * NULL if execution should proceed; array if the response is already known |
| 669 | */ |
| 670 | public function loadCMSBootstrap() { |
| 671 | $requestParams = CRM_Utils_Request::exportValues(); |
| 672 | $q = CRM_Utils_array::value('q', $requestParams); |
| 673 | $args = explode('/', $q); |
| 674 | |
| 675 | // Proceed with bootstrap for "?entity=X&action=Y" |
| 676 | // Proceed with bootstrap for "?q=civicrm/X/Y" but not "?q=civicrm/ping" |
| 677 | if (!empty($q)) { |
| 678 | if (count($args) == 2 && $args[1] == 'ping') { |
| 679 | return NULL; // this is pretty wonky but maybe there's some reason I can't see |
| 680 | } |
| 681 | if (count($args) != 3) { |
| 682 | return self::error('ERROR: Malformed REST path'); |
| 683 | } |
| 684 | if ($args[0] != 'civicrm') { |
| 685 | return self::error('ERROR: Malformed REST path'); |
| 686 | } |
| 687 | // Therefore we have reasonably well-formed "?q=civicrm/X/Y" |
| 688 | } |
| 689 | |
| 690 | if (!CRM_Utils_System::authenticateKey(FALSE)) { |
| 691 | // FIXME: At time of writing, this doesn't actually do anything because |
| 692 | // authenticateKey abends, but that's a bad behavior which sends a |
| 693 | // malformed response. |
| 694 | return self::error('Failed to authenticate key'); |
| 695 | } |
| 696 | |
| 697 | $uid = NULL; |
| 698 | if (!$uid) { |
| 699 | $store = NULL; |
| 700 | $api_key = CRM_Utils_Request::retrieve('api_key', 'String', $store, FALSE, NULL, 'REQUEST'); |
| 701 | if (empty($api_key)) { |
| 702 | return self::error("FATAL: mandatory param 'api_key' (user key) missing"); |
| 703 | } |
| 704 | $contact_id = CRM_Core_DAO::getFieldValue('CRM_Contact_DAO_Contact', $api_key, 'id', 'api_key'); |
| 705 | if ($contact_id) { |
| 706 | $uid = CRM_Core_BAO_UFMatch::getUFId($contact_id); |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | if ($uid && $contact_id) { |
| 711 | CRM_Utils_System::loadBootStrap(array('uid' => $uid), TRUE, FALSE); |
| 712 | $session = CRM_Core_Session::singleton(); |
| 713 | $session->set('ufID', $uid); |
| 714 | $session->set('userID', $contact_id); |
| 715 | return NULL; |
| 716 | } |
| 717 | else { |
| 718 | return self::error('ERROR: No CMS user associated with given api-key'); |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | } |