public function invalidateApplicationResources(array $uris, SecurityToken $token)
 {
     foreach ($uris as $uri) {
         $request = new RemoteContentRequest($uri);
         $this->cache->invalidate($request->toHash());
         // GET
         $request = new RemoteContentRequest($uri);
         $request->createRemoteContentRequestWithUri($uri);
         $this->cache->invalidate($request->toHash());
         // GET & SIGNED
         $request = new RemoteContentRequest($uri);
         $request->setAuthType(RemoteContentRequest::$AUTH_SIGNED);
         $request->setNotSignedUri($uri);
         $this->cache->invalidate($request->toHash());
     }
     if (Doctrine::getTable('SnsConfig')->get('is_use_outer_shindig', false) && Doctrine::getTable('SnsConfig')->get('is_relay_invalidation_notice', true)) {
         require_once 'OAuth.php';
         $shindigUrl = Doctrine::getTable('SnsConfig')->get('shindig_url');
         if (substr($shindigUrl, -1) !== '/') {
             $shindigUrl .= '/';
         }
         $invalidateUrl = $shindigUrl . 'gadgets/api/rest/cache';
         $key = Doctrine::getTable('SnsConfig')->get('shindig_backend_key');
         $secret = Doctrine::getTable('SnsConfig')->get('shindig_backend_secret');
         $consumer = new OAuthConsumer($key, $secret);
         $oauthRequest = OAuthRequest::from_consumer_and_token($consumer, null, 'POST', $invalidateUrl);
         $oauthRequest->set_parameter('xoauth_requestor_id', 1);
         $oauthRequest->sign_request(new OAuthSignatureMethod_HMAC_SHA1(), $consumer, null);
         $request = new RemoteContentRequest($invalidateUrl . '?xoauth_requestor_id=1');
         $request->setMethod('POST');
         $request->setContentType('application/json');
         $request->setPostBody(json_encode(array('invalidationKeys' => $uris)));
         $request->setHeaders($oauthRequest->to_header());
         $request->getOptions()->ignoreCache = true;
         $remoteContent = Shindig_Config::get('remote_content');
         $fetcher = new $remoteContent();
         $fetcher->fetch($request);
     }
 }
 /**
  * Builds a request to retrieve the actual content.
  *
  * @param GadgetContext $context The rendering context.
  * @param MakeRequestOptions $params Options for crafting the request.
  * @param SecurityTokenDecoder $signer A signer needed for signed requests.
  * @return RemoteContentRequest An initialized request object.
  */
 public function buildRequest(GadgetContext $context, MakeRequestOptions $params, SecurityTokenDecoder $signer = null)
 {
     // Check the protocol requested - curl doesn't really support file://
     // requests but the 'error' should be handled properly
     $protocolSplit = explode('://', $params->getHref(), 2);
     if (count($protocolSplit) < 2) {
         throw new Exception("Invalid protocol specified");
     }
     $protocol = strtoupper($protocolSplit[0]);
     if ($protocol != "HTTP" && $protocol != "HTTPS") {
         throw new Exception("Invalid protocol specified in url: " . htmlentities($protocol));
     }
     $method = $params->getHttpMethod();
     if ($method == 'POST' || $method == 'PUT') {
         // even if postData is an empty string, it will still post
         // (since RemoteContentRquest checks if its false)
         // so the request to POST is still honored
         $request = new RemoteContentRequest($params->getHref(), null, $params->getRequestBody());
     } else {
         if ($method == 'DELETE' || $method == 'GET' || $method == 'HEAD') {
             $request = new RemoteContentRequest($params->getHref());
         } else {
             throw new Exception("Invalid HTTP method.");
         }
     }
     $request->setMethod($method);
     if ($signer) {
         switch ($params->getAuthz()) {
             case 'SIGNED':
                 $request->setAuthType(RemoteContentRequest::$AUTH_SIGNED);
                 break;
             case 'OAUTH':
                 $request->setAuthType(RemoteContentRequest::$AUTH_OAUTH);
                 $request->setOAuthRequestParams($params->getOAuthRequestParameters());
                 break;
         }
         $st = $params->getSecurityTokenString();
         if ($st === false) {
             throw new Exception("A security token is required for signed requests");
         }
         $token = $context->validateToken($st, $signer);
         $request->setToken($token);
     }
     // Strip invalid request headers.  This limits the utility of the
     // MakeRequest class a little bit, but ensures that none of the invalid
     // headers are present in any request going through this class.
     $headers = $params->getRequestHeadersArray();
     if ($headers !== false) {
         $headers = $this->stripInvalidArrayKeys($headers, MakeRequest::$BAD_REQUEST_HEADERS);
         $params->setRequestHeaders($headers);
     }
     // The request expects headers to be stored as a normal header text blob.
     // ex: Content-Type: application/atom+xml
     //     Accept-Language: en-us
     $formattedHeaders = $params->getFormattedRequestHeaders();
     if ($formattedHeaders !== false) {
         $request->setHeaders($formattedHeaders);
     }
     return $request;
 }
Exemplo n.º 3
0
 /**
  * Peforms the actual http fetching of the data-pipelining requests, all social requests
  * are made to $_SERVER['HTTP_HOST'] (the virtual host name of this server) / (optional) web_prefix / social / rpc, and
  * the httpRequest's are made to $_SERVER['HTTP_HOST'] (the virtual host name of this server) / (optional) web_prefix / gadgets / makeRequest
  * both request types use the current security token ($_GET['st']) when performing the requests so they happen in the correct context
  *
  * @param array $requests
  * @return array response
  */
 private static function performRequests($requests, $context)
 {
     $jsonRequests = array();
     $httpRequests = array();
     $decodedResponse = array();
     // Using the same gadget security token for all social & http requests so everything happens in the right context
     if (!isset($_GET['st'])) {
         throw new ExpressionException("No security token set, required for data-pipeling");
     }
     $securityToken = $_GET['st'];
     foreach ($requests as $request) {
         switch ($request['type']) {
             case 'os:DataRequest':
                 // Add to the social request batch
                 $id = $request['key'];
                 $method = $request['method'];
                 // remove our internal fields so we can use the remainder as params
                 unset($request['key']);
                 unset($request['method']);
                 unset($request['type']);
                 if (isset($request['fields'])) {
                     $request['fields'] = explode(',', $request['fields']);
                 }
                 $jsonRequests[] = array('method' => $method, 'id' => $id, 'params' => $request);
                 break;
             case 'os:HttpRequest':
                 $id = $request['key'];
                 $url = $request['href'];
                 $format = isset($request['format']) ? $request['format'] : 'json';
                 unset($request['key']);
                 unset($request['type']);
                 unset($request['href']);
                 $httpRequests[$url] = array('id' => $id, 'url' => $url, 'format' => $format, 'queryStr' => implode('&', $request));
                 break;
         }
     }
     if (count($jsonRequests)) {
         // perform social api requests
         $request = new RemoteContentRequest('http://' . $_SERVER['HTTP_HOST'] . Config::get('web_prefix') . '/rpc?st=' . urlencode($securityToken) . '&format=json', "Content-Type: application/json\n", json_encode($jsonRequests));
         $request->setMethod('POST');
         $remoteFetcherClass = Config::get('remote_content_fetcher');
         $remoteFetcher = new $remoteFetcherClass();
         $basicRemoteContent = new BasicRemoteContent($remoteFetcher);
         $response = $basicRemoteContent->fetch($request);
         $decodedResponse = json_decode($response->getResponseContent(), true);
     }
     if (count($httpRequests)) {
         $requestQueue = array();
         foreach ($httpRequests as $request) {
             $req = new RemoteContentRequest($_SERVER['HTTP_HOST'] . Config::get('web_prefix') . '/gadgets/makeRequest?url=' . urlencode($request['url']) . '&st=' . urlencode($securityToken) . (!empty($request['queryStr']) ? '&' . $request['queryStr'] : ''));
             $req->getOptions()->ignoreCache = $context->getIgnoreCache();
             $req->setNotSignedUri($request['url']);
             $requestQueue[] = $req;
         }
         $basicRemoteContent = new BasicRemoteContent();
         $resps = $basicRemoteContent->multiFetch($requestQueue);
         foreach ($resps as $response) {
             //FIXME: this isn't completely correct yet since this picks up the status code and headers
             // as they are returned by the makeRequest handler and not the ones from the original request
             $url = $response->getNotSignedUrl();
             $id = $httpRequests[$url]['id'];
             // strip out the UNPARSEABLE_CRUFT (see makeRequestHandler.php) on assigning the body
             $resp = json_decode(str_replace("throw 1; < don't be evil' >", '', $response->getResponseContent()), true);
             if (is_array($resp)) {
                 $statusCode = $response->getHttpCode();
                 $statusCodeMessage = $response->getHttpCodeMsg();
                 $headers = $response->getHeaders();
                 if (intval($statusCode) == 200) {
                     $content = $httpRequests[$url]['format'] == 'json' ? json_decode($resp[$url]['body'], true) : $resp[$url]['body'];
                     $toAdd = array('result' => array('content' => $content, 'status' => $statusCode, 'headers' => $headers));
                 } else {
                     $content = $resp[$url]['body'];
                     $toAdd = array('error' => array('code' => $statusCode, 'message' => $statusCodeMessage, 'result' => array('content' => $content, 'headers' => $headers)));
                 }
                 //$toAdd[$id] = array('id' => $id, 'result' => $httpRequests[$url]['format'] == 'json' ? json_decode($resp[$url]['body'], true) : $resp[$url]['body']);
                 $decodedResponse[] = array('id' => $id, 'result' => $toAdd);
             }
         }
     }
     return $decodedResponse;
 }
 /**
  * Renders a 'proxied content' view, for reference see:
  * http://opensocial-resources.googlecode.com/svn/spec/draft/OpenSocial-Data-Pipelining.xml
  *
  * @param Gadget $gadget
  * @param array $view
  */
 public function renderGadget(Shindig_Gadget $gadget, $view)
 {
     $this->setGadget($gadget);
     if (Shindig_Config::get('P3P') != '') {
         header("P3P: " . Shindig_Config::get('P3P'));
     }
     /* TODO
      * We should really re-add OAuth fetching support some day, uses these view atributes:
      * $view['oauthServiceName'], $view['oauthTokenName'], $view['oauthRequestToken'], $view['oauthRequestTokenSecret'];
      */
     $authz = $this->getAuthz($view);
     $refreshInterval = $this->getRefreshInterval($view);
     $href = $this->buildHref($view, $authz);
     if (count($view['dataPipelining'])) {
         $request = new RemoteContentRequest($href, "Content-type: application/json\n");
         $request->setMethod('POST');
         $request->getOptions()->ignoreCache = $gadget->gadgetContext->getIgnoreCache();
     } else {
         // no data-pipelining set, use GET and set cache/refresh interval options
         $request = new RemoteContentRequest($href);
         $request->setMethod('GET');
         $request->setRefreshInterval($refreshInterval);
         $request->getOptions()->ignoreCache = $gadget->gadgetContext->getIgnoreCache();
     }
     $signingFetcherFactory = $gadgetSigner = false;
     if ($authz != 'none') {
         $gadgetSigner = Shindig_Config::get('security_token_signer');
         $gadgetSigner = new $gadgetSigner();
         $token = $gadget->gadgetContext->extractAndValidateToken($gadgetSigner);
         $request->setToken($token);
         $request->setAuthType($authz);
         $request->getOptions()->ownerSigned = $this->getSignOwner($view);
         $request->getOptions()->viewerSigned = $this->getSignViewer($view);
         $signingFetcherFactory = new SigningFetcherFactory(Shindig_Config::get("private_key_file"));
     }
     $remoteFetcherClass = Shindig_Config::get('remote_content_fetcher');
     $remoteFetcher = new $remoteFetcherClass();
     $basicRemoteContent = new BasicRemoteContent($remoteFetcher, $signingFetcherFactory, $gadgetSigner);
     // Cache POST's as if they were GET's, since we don't want to re-fetch and repost the social data for each view
     $basicRemoteContent->setCachePostRequest(true);
     if (($response = $basicRemoteContent->getCachedRequest($request)) == false) {
         // Don't fetch the data-pipelining social data unless we don't have a cached version of the gadget's content
         $dataPipeliningResults = DataPipelining::fetch($view['dataPipelining'], $this->context);
         // spec stats that the proxied content data-pipelinging data is *not* available to templates (to avoid duplicate posting
         // of the data to the gadget dev's server and once to js space), so we don't assign it to the data context, and just
         // post the json encoded results to the remote url.
         $request->setPostBody(json_encode($dataPipeliningResults));
         $response = $basicRemoteContent->fetch($request);
     }
     if ($response->getHttpCode() != '200') {
         // an error occured fetching the proxied content's gadget content
         $content = '<html><body><h1>An error occured fetching the gadget content</h1><p>http error code: ' . $response->getHttpCode() . '</p><p>' . $response->getResponseContent() . '</body></html>';
     } else {
         // fetched ok, build the response document and output it
         $content = $response->getResponseContent();
         $content = $this->parseTemplates($content);
         $content = $this->rewriteContent($content);
         $content = $this->addTemplates($content);
     }
     echo $content;
 }