Ejemplo n.º 1
0
 function testResponse()
 {
     $r = new RestResponse();
     $this->assertFalse($r->headerSent());
     $r->setResponse("foo");
     $r->appendResponse("bar");
     $this->assertEquals($r->getResponse(), "foobar");
 }
Ejemplo n.º 2
0
 /**
  * Handles incoming REST requests for which the user must be authenticated.
  * Used for requests where tokens are provided for verification.
  * Forwards the request to plugin hook registered for the RewriteRule.
  *
  * @see act_rest()
  */
 public function act_verified_rest()
 {
     Plugins::act('auth_rest_verify', $this);
     $matched_rule = Controller::get_matched_rule();
     $hookfn = $matched_rule->parameters['hook'];
     $result = call_user_func_array($hookfn, array($matched_rule->named_arg_values));
     if (!$result instanceof RestResponse) {
         $result = new RestResponse($result);
     }
     $result->out();
 }
Ejemplo n.º 3
0
 public function testWhenNotFound()
 {
     $resourceId = 8282;
     $this->repository->expects($this->once())->method('LoadById')->with($this->equalTo($resourceId))->will($this->returnValue(BookableResource::Null()));
     $this->service->GetResource($resourceId);
     $this->assertEquals(RestResponse::NotFound(), $this->server->_LastResponse);
 }
 public function testWhenAttributeNotFound()
 {
     $attributeId = 123;
     $this->attributeService->expects($this->once())->method('GetById')->with($this->equalTo($attributeId))->will($this->returnValue(null));
     $this->service->GetAttribute($attributeId);
     $this->assertEquals(RestResponse::NotFound(), $this->server->_LastResponse);
 }
Ejemplo n.º 5
0
 /**
  * Returns HTML text to access GoogleMap.
  * @param address - address string to generate map for.
  * @param zoom.
  */
 public static function getGoogleMap($address, $zoom, $iframe)
 {
     $key = self::getApiKey();
     $encoded = urlencode($address);
     $coder = new GeoCoder($encoded, $key);
     $code = $coder->invoke();
     $mapRep = "";
     if ($iframe != null && $iframe == "true") {
         $mapRep .= "    <div id='map' style='width: 500px; height: 300px'></div>\n" . self::getMapScript($address, $zoom, $code->getLatitude(), $code->getLongitude(), $key) . "    <script type='text/javascript'>\n" . "       loadScript();\n" . "    </script>\n";
     } else {
         $mapRep .= "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Strict//EN'\n" . "  'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'>\n" . "<html xmlns='http://www.w3.org/1999/xhtml'>\n" . "  <head>\n" . "    <meta http-equiv='content-type' content='text/html; charset=utf-8'/>\n" . "    <title>Google Maps JavaScript API Example</title>\n" . self::getMapScript($address, $zoom, $code->getLatitude(), $code->getLongitude(), $key) . "  </head>\n" . "  <body onload='loadScript()' onunload='GUnload()'>\n" . "    <div id='map' style='width: 500px; height: 300px'></div>\n" . "  </body>\n" . "</html>";
     }
     $result = new RestResponse();
     $result->setResponseBody($mapRep);
     return $result;
 }
Ejemplo n.º 6
0
 public function testWhenScheduleNotFound()
 {
     $scheduleId = 89181;
     $this->scheduleRepository->expects($this->once())->method('LoadById')->with($this->equalTo($scheduleId))->will($this->returnValue(null));
     $this->service->GetSchedule($scheduleId);
     $this->assertEquals(RestResponse::NotFound(), $this->server->_LastResponse);
 }
 /**
  * Handle payload
  * 
  * @param   lang.Type target
  * @return  var
  */
 protected function handlePayloadOf($target)
 {
     if (204 === $this->response->statusCode()) {
         return NULL;
     }
     // "No Content"
     return parent::handlePayloadOf($target);
 }
 public function testWhenAccessoryNotFound()
 {
     $accessoryId = 1233;
     $this->accessoryRepository->expects($this->once())->method('LoadById')->with($this->equalTo($accessoryId))->will($this->returnValue(null));
     $this->service->GetAccessory($accessoryId);
     $this->assertEquals(RestResponse::NotFound(), $this->server->_LastResponse);
     $this->assertEquals(RestResponse::NOT_FOUND_CODE, $this->server->_LastResponseCode);
 }
Ejemplo n.º 9
0
 public function testWhenGroupIsNotFound()
 {
     $groupId = 999;
     $this->groupRepository->expects($this->once())->method('LoadById')->with($this->equalTo($groupId))->will($this->returnValue(null));
     $expectedResponse = RestResponse::NotFound();
     $this->service->GetGroup($groupId);
     $this->assertEquals($expectedResponse, $this->server->_LastResponse);
     $this->assertEquals(RestResponse::NOT_FOUND_CODE, $this->server->_LastResponseCode);
 }
Ejemplo n.º 10
0
 /**
  * @name GetAttribute
  * @description Gets all custom attribute definitions for the requested attribute
  * @response CustomAttributeDefinitionResponse
  * @return void
  * @param int $attributeId
  */
 public function GetAttribute($attributeId)
 {
     $attribute = $this->attributeService->GetById($attributeId);
     if ($attribute != null) {
         $this->server->WriteResponse(new CustomAttributeDefinitionResponse($this->server, $attribute));
     } else {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     }
 }
Ejemplo n.º 11
0
 /**
  * @name GetAccessory
  * @description Loads a specific accessory by id
  * @param int $accessoryId
  * @response AccessoryResponse
  * @return void
  */
 public function GetAccessory($accessoryId)
 {
     $accessory = $this->accessoryRepository->LoadById($accessoryId);
     if (empty($accessory)) {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     } else {
         $this->server->WriteResponse(new AccessoryResponse($this->server, $accessory));
     }
 }
Ejemplo n.º 12
0
 /**
  * @name GetGroup
  * @description Loads a specific group by id
  * @response GroupResponse
  * @param int $groupId
  * @return void
  */
 public function GetGroup($groupId)
 {
     $group = $this->groupRepository->LoadById($groupId);
     if ($group != null) {
         $this->server->WriteResponse(new GroupResponse($this->server, $group));
     } else {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     }
 }
Ejemplo n.º 13
0
 /**
  * @name GetSchedule
  * @description Loads a specific schedule by id
  * @response ScheduleResponse
  * @param $scheduleId
  * @return void
  */
 public function GetSchedule($scheduleId)
 {
     $schedule = $this->scheduleRepository->LoadById($scheduleId);
     if ($schedule != null) {
         $layout = $this->scheduleRepository->GetLayout($schedule->GetId(), new ScheduleLayoutFactory($this->server->GetSession()->Timezone));
         $this->server->WriteResponse(new ScheduleResponse($this->server, $schedule, $layout));
     } else {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     }
 }
Ejemplo n.º 14
0
 /**
  * Set response to be read from file
  */
 public function fileResponse($filename)
 {
     if (empty($this->response)) {
         return false;
     }
     $this->response->setType(RestResponse::FILE)->setFilename($filename);
     $this->response->setHeader("Pragma", "public");
     $this->response->setHeader("Cache-Control", "max-age=1, post-check=0, pre-check=0");
     $this->response->setHeader("X-Content-Type-Options", "nosniff");
 }
Ejemplo n.º 15
0
 /**
  * @name GetResource
  * @description Loads a specific resource by id
  * @param int $resourceId
  * @response ResourceResponse
  * @return void
  */
 public function GetResource($resourceId)
 {
     $resource = $this->resourceRepository->LoadById($resourceId);
     $resourceId = $resource->GetResourceId();
     if (empty($resourceId)) {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     } else {
         $attributes = $this->attributeService->GetAttributes(CustomAttributeCategory::RESOURCE, array($resourceId));
         $this->server->WriteResponse(new ResourceResponse($this->server, $resource, $attributes));
     }
 }
Ejemplo n.º 16
0
 public static function processRequest()
 {
     // get our verb
     $request_method = strtolower($_SERVER['REQUEST_METHOD']);
     $response = new RestResponse();
     // we'll store our data here
     $data = array();
     switch ($request_method) {
         // gets are easy...
         case 'get':
             $data = $_GET;
             break;
             // so are posts
         // so are posts
         case 'post':
             $data = $_POST;
             break;
             // here's the tricky bit...
         // here's the tricky bit...
         case 'put':
             // basically, we read a string from PHP's special input location,
             // and then parse it out into an array via parse_str... per the PHP docs:
             // Parses str  as if it were the query string passed via a URL and sets
             // variables in the current scope.
             parse_str(file_get_contents('php://input'), $put_vars);
             $data = $put_vars;
             break;
         default:
             // TODO. Hvis vi når hertil bør vi nok råbe av.
             break;
     }
     if (isset($_GET['q'])) {
         $data['q'] = $_GET['q'];
     }
     // store the method
     $response->setMethod($request_method);
     // set the raw data, so we can access it if needed (there may be
     // other pieces to your requests)
     $response->setRequestVars($data);
     if (isset($data['data'])) {
         // TODO
         // translate the JSON to an Object for use however you want
         $response->setData(json_decode($data['data']));
     }
     $path = $response->getRequestVars();
     if (!isset($path['q'])) {
         die(RestUtils::sendResponse(404));
     }
     $path_array = explode('/', $path['q']);
     if (!isset($path_array[0])) {
         die(RestUtils::sendResponse(404));
     }
     // Set the controller.
     $controller = RestUtils::getController($response, $path_array);
     $controller->process();
     // TODO. Right now we only return json.
     $body = json_encode($controller->getProcessedResponse());
     RestUtils::sendResponse(200, $body, 'application/json');
 }
Ejemplo n.º 17
0
 /**
  * @name GetSlots
  * @description Loads slots for a specific schedule
  * Optional query string parameters:  resourceId, startDateTime, endDateTime.
  * If no dates are provided the default schedule dates will be returned.
  * If dates do not include the timezone offset, the timezone of the authenticated user will be assumed.
  * @response ScheduleSlotsResponse
  * @param $scheduleId
  * @return void
  */
 public function GetSlots($scheduleId)
 {
     $startDate = $this->GetDate(WebServiceQueryStringKeys::START_DATE_TIME);
     $endDate = $this->GetDate(WebServiceQueryStringKeys::END_DATE_TIME);
     $resourceId = $this->server->GetQueryString(WebServiceQueryStringKeys::RESOURCE_ID);
     $scheduleWebServiceView = new ScheduleWebServiceView($scheduleId, $startDate);
     $permissionServiceFactory = new PermissionServiceFactory();
     $scheduleRepository = new ScheduleRepository();
     $userRepository = new UserRepository();
     $resourceService = new ResourceService(new ResourceRepository(), $permissionServiceFactory->GetPermissionService(), new AttributeService(new AttributeRepository()), $userRepository);
     $builder = new ScheduleWebServicePageBuilder($startDate, $endDate, $resourceId);
     $reservationService = new ReservationService(new ReservationViewRepository(), new ReservationListingFactory());
     $dailyLayoutFactory = new DailyLayoutFactory();
     $scheduleService = new ScheduleService($scheduleRepository, $resourceService);
     $presenter = new SchedulePresenter($scheduleWebServiceView, $scheduleService, $resourceService, $builder, $reservationService, $dailyLayoutFactory);
     $presenter->PageLoad($this->server->GetSession());
     $layout = $scheduleWebServiceView->GetDailyLayout();
     $isError = $scheduleWebServiceView->IsPermissionError();
     $dates = $scheduleWebServiceView->GetDates();
     $resources = $scheduleWebServiceView->GetResources();
     if ($isError) {
         $this->server->WriteResponse(RestResponse::Unauthorized(), RestResponse::UNAUTHORIZED_CODE);
     } else {
         $response = new ScheduleSlotsResponse($this->server, $scheduleId, $layout, $dates, $resources, $this->privacyFilter);
         $this->server->WriteResponse($response);
     }
 }
Ejemplo n.º 18
0
  private static function getController(RestResponse $response, $path_array) {
    // Check versions of the api.
    if ('v1' != $path_array[0]) {
      die(RestUtils::sendResponse(501));
    }
    try {
      if ('tag' == $path_array[1]) {
        include './tagger/Tagger.php';
        $tagger = Tagger::getTagger();
        if ($response->getRequestVars('url')) {
          $text = file_get_contents($response->getRequestVars('url'));
        } else if ($response->getRequestVars('text')) {
          $text = $response->getRequestVars('text');
        } else {
          RestUtils::sendResponse(500, 'Missing argument: text or url');
        }
        
        $configuration = $tagger->getConfiguration();

        if (empty($configuration['vocab_names'])) {
          RestUtils::sendResponse(500, 'No configured vocabs');
        }

        return $tagger->tagText(
            $text,
            $configuration['vocab_names'],
            $response->getRequestVars('disambiguate') ? true : false,
            $response->getRequestVars('uris') ? true : false,
            $response->getRequestVars('unmatched') ? true : false,
            $response->getRequestVars('markup') ? true : false,
            $response->getRequestVars('nl2br') ? true : false
          );
      }
    }
    catch (Exception $e) {
      die(RestUtils::sendResponse(400));
    }
    die(RestUtils::sendResponse(404));
  }
Ejemplo n.º 19
0
 /**
  * @name GetReservation
  * @param string $referenceNumber
  * @description Loads a specific reservation by reference number
  * @response ReservationResponse
  * @return void
  */
 public function GetReservation($referenceNumber)
 {
     Log::Debug('GetReservation called. $referenceNumber=%s', $referenceNumber);
     $reservation = $this->reservationViewRepository->GetReservationForEditing($referenceNumber);
     if (!empty($reservation->ReferenceNumber)) {
         $attributes = $this->attributeService->GetByCategory(CustomAttributeCategory::RESERVATION);
         $response = new ReservationResponse($this->server, $reservation, $this->privacyFilter, $attributes);
         $this->server->WriteResponse($response);
     } else {
         $this->server->WriteResponse($response = RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
     }
 }
 public function testWhenReservationIsNotFound()
 {
     $reservation = NullReservationView::Instance();
     $referenceNumber = '12323';
     $this->reservationViewRepository->expects($this->once())->method('GetReservationForEditing')->with($this->equalTo($referenceNumber))->will($this->returnValue($reservation));
     $this->service->GetReservation($referenceNumber);
     $expectedResponse = RestResponse::NotFound();
     $this->assertEquals($expectedResponse, $this->server->_LastResponse);
 }
Ejemplo n.º 21
0
 /**
  * Execute a request
  *
  * @param   var t either a string or a lang.Type - response type, defaults to webservices.rest.RestResponse
  * @param   webservices.rest.RestRequest request
  * @return  webservices.rest.RestResponse
  * @throws  lang.IllegalStateException if no connection is set
  */
 public function execute($t, $request = NULL)
 {
     if (1 === func_num_args()) {
         // Overloaded version with single argument
         $request = $t;
         $type = NULL;
     } else {
         if (is_string($t)) {
             // Overloaded version with string type
             $type = Type::forName($t);
         } else {
             if ($t instanceof Type) {
                 // Overloaded version with Type instance
                 $type = $t;
             } else {
                 throw new IllegalArgumentException('Given type is neither a Type nor a string, ' . xp::typeOf($request) . ' given');
             }
         }
     }
     if (!$request instanceof RestRequest) {
         throw new IllegalArgumentException('Given request is not a RestRequest, ' . xp::typeOf($request) . ' given');
     }
     if (NULL === $this->connection) {
         throw new IllegalStateException('No connection set');
     }
     $send = $this->connection->create(new HttpRequest());
     $send->addHeaders($request->headerList());
     $send->setMethod($request->getMethod());
     $send->setTarget($request->getTarget($this->connection->getUrl()->getPath('/')));
     if ($request->hasBody()) {
         $send->setParameters($request->getBody());
     } else {
         $send->setParameters($request->getParameters());
     }
     try {
         $this->cat && $this->cat->debug('>>>', $send->getRequestString());
         $response = $this->connection->send($send);
     } catch (IOException $e) {
         throw new RestException('Cannot send request', $e);
     }
     if ($type instanceof XPClass && $type->isSubclassOf('webservices.rest.RestResponse')) {
         $rr = $type->newInstance($response, $this->deserializerFor(this($response->header('Content-Type'), 0)));
     } else {
         $rr = new RestResponse($response, $this->deserializerFor(this($response->header('Content-Type'), 0)), $type);
     }
     $this->cat && $this->cat->debug('<<<', $response->toString(), $rr->contentCopy());
     return $rr;
 }
Ejemplo n.º 22
0
 public function testWhenNotAllowedToGetUser()
 {
     $sessionUserId = $this->server->GetSession()->UserId;
     $userId = 999;
     $this->HideUsers(true);
     $user = new FakeUser($userId);
     $me = new FakeUser($sessionUserId);
     $me->_SetIsAdminForUser(false);
     $attributes = $this->getMock('IEntityAttributeList');
     $this->userRepositoryFactory->expects($this->once())->method('Create')->with($this->equalTo($this->server->GetSession()))->will($this->returnValue($this->userRepository));
     $this->userRepository->expects($this->at(0))->method('LoadById')->with($this->equalTo($userId))->will($this->returnValue($user));
     $this->userRepository->expects($this->at(1))->method('LoadById')->with($this->equalTo($sessionUserId))->will($this->returnValue($me));
     $this->attributeService->expects($this->once())->method('GetAttributes')->with($this->equalTo(CustomAttributeCategory::USER), $this->equalTo(array($userId)))->will($this->returnValue($attributes));
     $this->service->GetUser($userId);
     $this->assertEquals(RestResponse::Unauthorized(), $this->server->_LastResponse);
     $this->assertEquals(RestResponse::UNAUTHORIZED_CODE, $this->server->_LastResponseCode);
 }
Ejemplo n.º 23
0
 /**
  * Execute a request
  *
  * <code>
  *   $client->execute(new RestRequest('/', HttpConstants::GET));
  * </code>
  *
  * @param   var t either a string or a lang.Type - response type, defaults to webservices.rest.RestResponse
  * @param   webservices.rest.RestRequest request
  * @return  webservices.rest.RestResponse
  * @throws  lang.IllegalStateException if no connection is set
  */
 public function execute($t, $request = NULL)
 {
     if (1 === func_num_args()) {
         // Overloaded version with single argument
         $request = $t;
         $type = NULL;
     } else {
         if (is_string($t)) {
             // Overloaded version with string type
             $type = Type::forName($t);
         } else {
             if ($t instanceof Type) {
                 // Overloaded version with Type instance
                 $type = $t;
             } else {
                 throw new IllegalArgumentException('Given type is neither a Type nor a string, ' . xp::typeOf($request) . ' given');
             }
         }
     }
     if (!$request instanceof RestRequest) {
         throw new IllegalArgumentException('Given request is not a RestRequest, ' . xp::typeOf($request) . ' given');
     }
     if (NULL === $this->connection) {
         throw new IllegalStateException('No connection set');
     }
     $send = $this->connection->create(new HttpRequest());
     $send->addHeaders($request->headerList());
     $send->setMethod($request->getMethod());
     $send->setTarget($request->getTarget($this->connection->getUrl()->getPath('/')));
     // Compose body
     // * Serialize payloads using the serializer for the given mimetype
     // * Use bodies as-is, e.g. file uploads
     // * If no body and no payload is set, use parameters
     if ($request->hasPayload()) {
         $send->setParameters(new RequestData($this->serializerFor($request->getContentType())->serialize($this->marshalling->marshal($request->getPayload()))));
     } else {
         if ($request->hasBody()) {
             $send->setParameters($request->getBody());
         } else {
             $send->setParameters($request->getParameters());
         }
     }
     try {
         $this->cat && $this->cat->debug('>>>', $send->getRequestString());
         $response = $this->connection->send($send);
     } catch (IOException $e) {
         throw new RestException('Cannot send request', $e);
     }
     $reader = new ResponseReader($this->deserializerFor(this($response->header('Content-Type'), 0), FALSE), $this->marshalling);
     if (NULL === $type) {
         $rr = new RestResponse($response, $reader);
     } else {
         if ($type instanceof XPClass && $type->isSubclassOf('webservices.rest.RestResponse')) {
             $rr = $type->newInstance($response, $reader);
         } else {
             $rr = new RestResponse($response, $reader, $type);
             // Deprecated!
         }
     }
     $this->cat && $this->cat->debug('<<<', $response->toString(), $rr->contentCopy());
     return $rr;
 }
Ejemplo n.º 24
0
 /**
  *
  * Make a cURL call
  * @param string $endpoint		URL to call
  * @param string $method			HTTP Method used for the call
  * @param string/Array $payload	Body message to send with the call
  * @throws Exception
  * @return RestResponse
  */
 public function makeCall($path, $method = "GET", $payload = "")
 {
     try {
         if (strpos($path, "/") !== 0) {
             $path = "/" . $path;
         }
         $endpoint = $this->protocol . "://" . $this->host . ":" . $this->port . $path;
         // Initialize the curl_session with targeted URL
         $ch = curl_init($endpoint);
         // Throw exception if curl is not initialize
         if ($ch == FALSE) {
             throw new CURLException("CURL Not available");
         }
         // Set the content type depending the payload type
         if (is_array($payload)) {
             $contentType = "multipart/form-data";
         } else {
             $contentType = "application/xml; charset=UTF-8";
         }
         // Set global headers for the call
         $headers = array('Cache-Control: nocache', 'Accept: application/xml', 'Content-Type: ' . $contentType, 'Connection: Keep-Alive');
         if (!empty($this->basicauth)) {
             $arr = explode(":", $this->basicauth, 2);
             $username = $arr[0];
             $password = $arr[1];
             $headers[] = $this->genAuthHeaderBasic($username, $password);
         }
         if (!empty($this->peerCertificatePath)) {
             // This will probably work, but I won't know until it's tested.
             // Until it's reliably tested, skip execution with an exception.
             throw new Exception("Not tested!");
             curl_setopt($ch, CURLOPT_CAINFO, $this->{$peerCertificatePath});
             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
             curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
         }
         // Set cURL options for the call
         curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
         curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
         curl_setopt($ch, CURLOPT_HEADER, TRUE);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
         curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIMEOUT);
         // Execute the call
         $return = curl_exec($ch);
         // Close cURL session
         curl_close($ch);
         // Check if endpoint is unavailable
         if ($return == FALSE) {
             $err = "No Server Responding";
             LoggerInterface::log($err, LoggerInterface::ERROR);
             throw new CURLException($err);
         }
         // Implements a new RestResponse to store useful informations
         $response = new RestResponse();
         // Retrieve useful informations from REST call response
         // Extract the HTTP Code
         $response->setHTTPCode($this->getHTTPCode($return));
         // Extract the specific X-E3-Application-Error-Code used for functionnal errors
         $response->setXApplicationCode($this->getSpecificApplicationCode($return));
         // Extract the payload
         $response->setPayload($this->getBody($return));
         // Throw Exception if BackEnd retrieve functionnal error
         if ($response->getXApplicationCode() !== NULL && $response->getXApplicationCode() != 200) {
             $errorMessage = "E3_API_Err_" . $response->getXApplicationCode();
             throw new RESTAppException($errorMessage, $response->getXApplicationCode());
         }
         // Throw Exception if BackEnd retrieve HTTP error
         if (false && !in_array($response->getHTTPCode(), array(200, 201, 202, 203, 204))) {
             if ($response->getHTTPCode() == 404) {
                 $errorMessage = '404 - Server Unreachable';
             } else {
                 $errorXML = simplexml_load_string($response->getPayload());
                 if ($errorXML->status == "SUCCESS") {
                     LoggerInterface::log("Response successful with improper return code ({$response->getHTTPCode()}): " . print_r($response->getPayload(), true), LoggerInterface::WARN);
                     return $response;
                 }
                 LoggerInterface::log("Errored response: ({$response->getHTTPCode()}) " . print_r($response->getPayload(), true), LoggerInterface::DEBUG);
                 $errorMessage = $errorXML->error->errorText;
                 //$errorMessage = htmlspecialchars($response->getPayload());
             }
             throw new Exception($errorMessage, $response->getHTTPCode());
         }
         // Return the formatted response object
         return $response;
     } catch (Exception $e) {
         LoggerInterface::log('Rest Curl Call', $e->getMessage(), array(), LoggerInterface::ERROR);
         //drupal_set_message('An error as occured during the operation, please retry or contact an administrator.', 'error');
         throw new Exception($e->getMessage());
     }
 }
Ejemplo n.º 25
0
 public function connect()
 {
     $this->response = $this->req->sendRequest();
     if (PEAR::isError($this->response)) {
         echo $this->response->getMessage();
         die;
     } else {
         $this->responseBody = $this->req->getResponseBody();
     }
     $response = new RestResponse();
     $response->setResponseCode($this->req->getResponseCode());
     $response->setResponseBody($this->req->getResponseBody());
     return $response;
 }
Ejemplo n.º 26
0
 public function __construct($data, $parent = null)
 {
     if ($data instanceof XMLRestResponseBase) {
         $datatype = $data->getParent()->datatype;
         if ($data->isFragment()) {
             $data = $data->finalize();
         }
         $result = $data->getData();
         if (is_array($result)) {
             $result = implode('', $result);
         }
         exec("bash " . RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . "group.xsl.template {$datatype}", $xf);
         $xf = implode("\n", $xf);
         $xsl = new DOMDocument();
         $xsl->loadXML($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $xf = RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . 'strip_prefix.xsl';
         $xsl = new DOMDocument();
         $xsl->load($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $xf = RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . 'text2att.xsl';
         $xsl = new DOMDocument();
         $xsl->load($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $xf = RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . 'att2elem.xsl';
         $xsl = new DOMDocument();
         $xsl->load($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $xf = RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . 'remove_empty_nodes.xsl';
         $xsl = new DOMDocument();
         $xsl->load($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $xf = RestAPIHelper::getFolder(RestFolderEnum::FE_XSL_FOLDER) . 'xml2json.xsl';
         $xsl = new DOMDocument();
         $xsl->load($xf);
         $proc = new XSLTProcessor();
         $proc->registerPHPFunctions();
         $proc->importStylesheet($xsl);
         $xml = new DOMDocument();
         $xml->loadXML($result, LIBXML_NSCLEAN | LIBXML_COMPACT);
         $result = $proc->transformToXml($xml);
         $data = $result;
     }
     parent::__construct($data, $parent);
 }
Ejemplo n.º 27
0
 /**
  * @name GetUser
  * @description Loads the requested user by Id
  * @response UserResponse
  * @param int $userId
  * @return void
  */
 public function GetUser($userId)
 {
     $responseCode = RestResponse::OK_CODE;
     $hideUsers = Configuration::Instance()->GetSectionKey(ConfigSection::PRIVACY, ConfigKeys::PRIVACY_HIDE_USER_DETAILS, new BooleanConverter());
     $userSession = $this->server->GetSession();
     $repository = $this->repositoryFactory->Create($userSession);
     $user = $repository->LoadById($userId);
     $loadedUserId = $user->Id();
     if (empty($loadedUserId)) {
         $this->server->WriteResponse(RestResponse::NotFound(), RestResponse::NOT_FOUND_CODE);
         return;
     }
     $attributes = $this->attributeService->GetAttributes(CustomAttributeCategory::USER, array($userId));
     if ($userId == $userSession->UserId || !$hideUsers || $userSession->IsAdmin) {
         $response = new UserResponse($this->server, $user, $attributes);
     } else {
         $me = $repository->LoadById($userSession->UserId);
         if ($me->IsAdminFor($user)) {
             $response = new UserResponse($this->server, $user, $attributes);
         } else {
             $response = RestResponse::Unauthorized();
             $responseCode = RestResponse::UNAUTHORIZED_CODE;
         }
     }
     $this->server->WriteResponse($response, $responseCode);
 }
Ejemplo n.º 28
0
 public function __construct(RestResponse $response)
 {
     global $conf;
     if (!isset($conf['vocab_names']) || empty($conf['vocab_names'])) {
         throw new ErrorException('Missing vocab definition in configuration.');
     }
     $this->response = $response;
     $this->text = $response->getRequestVars('text');
     if (empty($this->text)) {
         $url = $response->getRequestVars('url');
         if (!empty($url)) {
             // Suppress errors.
             $this->text = @file_get_contents($response->getRequestVars('url'));
         }
     }
     if (empty($this->text)) {
         throw new InvalidArgumentException('No text to find tags in has been supplied.');
     }
     if (mb_detect_encoding($this->text) != 'UTF-8') {
         $this->text = utf8_encode($this->text);
     }
     $ner = $response->getRequestVars('ner');
     if (!empty($ner) && preg_match_all('/(' . implode('|', $conf['vocab_names']) . ')+[\\ ]?/', $ner, $matches)) {
         $this->ner_vocabs = array_intersect_key(array_flip($conf['vocab_names']), array_flip($matches[1]));
     } else {
         $this->ner_vocabs = array_flip($conf['vocab_names']);
     }
     if ($response->getRequestVars('disambiguate')) {
         $this->disambiguate = $response->getRequestVars('disambiguate');
     }
     if ($response->getRequestVars('uris')) {
         $this->return_uris = $response->getRequestVars('uris');
     }
     if ($response->getRequestVars('unmatched')) {
         $this->return_unmatched = $response->getRequestVars('unmatched');
     }
     $this->use_markup = $response->getRequestVars('markup');
     $this->nl2br = $response->getRequestVars('nl2br');
 }