Example #1
0
 /**
  * Sets the caching (Cache-Control & Expires) with a cache age of $lastModified
  * or if $lastModified === false, sets Pragma: no-cache & Cache-Control: no-cache
  */
 protected function setCachingHeaders($lastModified = false)
 {
     $maxAge = $this->context->getIgnoreCache() ? false : $this->context->getRefreshInterval();
     if ($maxAge) {
         if ($lastModified) {
             header("Last-Modified: {$lastModified}");
         }
         // time() is a kernel call, so lets avoid it and use the request time instead
         $time = $_SERVER['REQUEST_TIME'];
         $expires = $maxAge !== false ? $time + $maxAge : $time - 3000;
         $public = $maxAge ? 'public' : 'private';
         $maxAge = $maxAge === false ? '0' : $maxAge;
         header("Cache-Control: {$public}; max-age={$maxAge}", true);
         header("Expires: " . gmdate("D, d M Y H:i:s", $expires) . " GMT", true);
     } else {
         header("Cache-Control: no-cache", true);
         header("Pragma: no-cache", true);
     }
 }
 /**
  * Fetches the gadget xml for the requested URL using the http fetcher
  *
  * @param unknown_type $gadgetUrl
  * @return string gadget's xml content
  */
 protected function fetchGadget($gadgetUrl)
 {
     $request = new RemoteContentRequest($gadgetUrl);
     $request->setToken($this->token);
     $request->getOptions()->ignoreCache = $this->context->getIgnoreCache();
     $xml = $this->context->getHttpFetcher()->fetch($request);
     if ($xml->getHttpCode() != '200') {
         throw new GadgetException("Failed to retrieve gadget content (recieved http code " . $xml->getHttpCode() . ")");
     }
     return $xml->getResponseContent();
 }
 private function getIframeURL(Gadget $gadget, GadgetContext $context)
 {
     $v = $gadget->getChecksum();
     $view = $gadget->getView($context->getView());
     $up = '';
     foreach ($gadget->gadgetSpec->userPrefs as $pref) {
         $up .= '&up_' . urlencode($pref['name']) . '=' . urlencode($pref['value']);
     }
     $locale = $context->getLocale();
     //Note: putting the URL last, else some browsers seem to get confused (reported by hi5)
     return Config::get('default_iframe_prefix') . 'container=' . $context->getContainer() . ($context->getIgnoreCache() ? '&nocache=1' : '&v=' . $v) . ($context->getModuleId() != 0 ? '&mid=' . $context->getModuleId() : '') . '&lang=' . $locale['lang'] . '&country=' . $locale['country'] . '&view=' . $view['view'] . $up . '&url=' . urlencode($context->getUrl());
 }
 /**
  * 
  */
 protected function setCachingHeaders()
 {
     $this->setContentType("text/html; charset=UTF-8");
     if ($this->context->getIgnoreCache()) {
         // no cache was requested, set non-caching-headers
         $this->setNoCache(true);
     } elseif (isset($_GET['v'])) {
         // version was given, cache for a long long time (a year)
         $this->setCacheTime(365 * 24 * 60 * 60);
     } else {
         // no version was given, cache for 5 minutes
         $this->setCacheTime(5 * 60);
     }
 }
 public function getFeatureContent($feature, GadgetContext $context, $isGadgetContext)
 {
     if (empty($feature)) {
         return '';
     }
     if (!isset($this->features[$feature])) {
         throw new GadgetException("Invalid feature: " . htmlentities($feature));
     }
     $featureName = $feature;
     $feature = $this->features[$feature];
     $filesContext = $isGadgetContext ? 'gadgetJs' : 'containerJs';
     if (!isset($feature[$filesContext])) {
         // no javascript specified for this context
         return '';
     }
     $ret = '';
     if (Config::get('compress_javascript')) {
         $featureCache = Cache::createCache(Config::get('feature_cache'), 'FeatureCache');
         if ($featureContent = $featureCache->get(md5('features:' . $featureName . $isGadgetContext))) {
             return $featureContent;
         }
     }
     foreach ($feature[$filesContext] as $entry) {
         switch ($entry['type']) {
             case 'URL':
                 $request = new RemoteContentRequest($entry['content']);
                 $request->getOptions()->ignoreCache = $context->getIgnoreCache();
                 $response = $context->getHttpFetcher()->fetch($request);
                 if ($response->getHttpCode() == '200') {
                     $ret .= $response->getResponseContent() . "\n";
                 }
                 break;
             case 'FILE':
                 $file = $feature['basePath'] . '/' . $entry['content'];
                 $ret .= file_get_contents($file) . "\n";
                 break;
             case 'INLINE':
                 $ret .= $entry['content'] . "\n";
                 break;
         }
     }
     if (Config::get('compress_javascript')) {
         $ret = JsMin::minify($ret);
         $featureCache->set(md5('features:' . $featureName . $isGadgetContext), $ret);
     }
     return $ret;
 }
 /**
  * Outputs a html content type gadget.
  * It creates a html page, with the javascripts from the features inline into the page, plus
  * calls to 'gadgets.config.init' with the container configuration (config/container.js) and
  * 'gadgets.Prefs.setMessages_' with all the substitutions. For external javascripts it adds
  * a <script> tag.
  *
  * @param Gadget $gadget
  * @param GadgetContext $context
  */
 private function outputHtmlGadget($gadget, $context, $view)
 {
     $content = '';
     $externJs = '';
     $externFmt = "<script src=\"%s\"></script>";
     $forcedLibs = $context->getForcedJsLibs();
     // allow the &libs=.. param to override our forced js libs configuration value
     if (empty($forcedLibs)) {
         $forcedLibs = Config::get('focedJsLibs');
     }
     $this->setContentType("text/html; charset=UTF-8");
     if ($context->getIgnoreCache()) {
         // no cache was requested, set non-caching-headers
         $this->setNoCache(true);
     } elseif (isset($_GET['v'])) {
         // version was given, cache for a long long time (a year)
         $this->setCacheTime(365 * 24 * 60 * 60);
     } else {
         // no version was given, cache for 5 minutes
         $this->setCacheTime(5 * 60);
     }
     // Was a privacy policy header configured? if so set it
     if (Config::get('P3P') != '') {
         header("P3P: " . Config::get('P3P'));
     }
     if (!$view->getQuirks()) {
         $content .= "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n";
     }
     $content .= "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/><style type=\"text/css\">" . Config::get('gadget_css') . "</style></head><body>\n";
     // Forced libs first.
     if (!empty($forcedLibs)) {
         $libs = explode(':', $forcedLibs);
         $content .= sprintf($externFmt, Config::get('default_js_prefix') . $this->getJsUrl($libs, $gadget) . "&container=" . $context->getContainer()) . "\n";
     }
     $content .= "<script>\n";
     if (!empty($forcedLibs)) {
         // if some of the feature libraries are externalized (through a browser cachable <script src="/gadgets/js/opensocial-0.7:settitle.js">
         // type url), then we don't want to include dependencies twice, so find the complete features chain, so we can skip over those
         $forcedLibsArray = explode(':', $forcedLibs);
         $registry = $this->context->getRegistry();
         $missing = array();
         $registry->getIncludedFeatures($forcedLibsArray, $forcedLibsArray, $missing);
     }
     foreach ($gadget->getJsLibraries() as $library) {
         $type = $library->getType();
         if ($type == 'URL') {
             // TODO: This case needs to be handled more gracefully by the js
             // servlet. We should probably inline external JS as well.
             $externJs .= sprintf($externFmt, $library->getContent()) . "\n";
             // else check if there are no forcedLibs, or if it wasn't included in their dep chain
         } elseif (empty($forcedLibs) || !in_array($library->getFeatureName(), $forcedLibsArray)) {
             $content .= $library->getContent();
         }
         // otherwise it was already included by config.forceJsLibs.
     }
     $content .= $this->appendJsConfig($context, $gadget, !empty($forcedLibs)) . $this->appendMessages($gadget) . $this->appendPreloads($gadget, $context) . "</script>";
     if (strlen($externJs) > 0) {
         $content .= $externJs;
     }
     $gadgetExceptions = array();
     $rewriter = new ContentRewriter();
     if ($rewriter->rewriteGadgetView($gadget, $view)) {
         $content .= $gadget->getSubstitutions()->substitute($view->getRewrittenContent());
     } else {
         $content .= $gadget->getSubstitutions()->substitute($view->getContent());
     }
     if (empty($content)) {
         // Unknown view
         $gadgetExceptions[] = "View: '" . $context->getView() . "' invalid for gadget: " . $gadget->getId()->getKey();
     }
     if (count($gadgetExceptions)) {
         throw new GadgetException(print_r($gadgetExceptions, true));
     }
     $content .= "\n<script>gadgets.util.runOnLoadHandlers();</script></body>\n</html>";
     echo $content;
 }
 public function getGadgetSpec(GadgetContext $context)
 {
     return $this->getGadgetSpecUri($context->getUrl(), $context->getIgnoreCache());
 }
 /**
  * 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
  * @param GadgetContext $context
  * @return array response
  */
 private static function performRequests($requests, GadgetContext $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 (!BasicSecurityToken::getTokenStringFromRequest()) {
         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;
 }