Exemplo n.º 1
0
 /**
  * Tests OutputJsonConverter->outputResponse()
  */
 public function testOutputResponse()
 {
     $inputConverter = new InputJsonConverter();
     $outputConverter = new OutputJsonConverter();
     $servletRequest = array('url' => '/people/1/@self');
     $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
     $requestItem = RestRequestItem::createWithRequest($servletRequest, $token, $inputConverter, $outputConverter);
     $requestItem->applyUrlTemplate("/people/{userId}/{groupId}/{personId}");
     $response = array('entry' => array('isOwner' => false, 'isViewer' => false, 'displayName' => '1 1', 'id' => '1'));
     $responseItem = new ResponseItem(null, null, $response);
     ob_start();
     $outputConverter->outputResponse($responseItem, $requestItem);
     $output = ob_get_clean();
     $expected = '{
     "entry": {
       "isOwner": false,
       "isViewer": false,
       "displayName": "1 1",
       "id": "1"
     }
 }';
     $outputJson = json_decode($output);
     $expectedJson = json_decode($expected);
     $this->assertEquals($expectedJson, $outputJson);
 }
Exemplo n.º 2
0
    /**
     * Tests OutputXmlConverter->outputResponse()
     */
    public function testOutputResponse()
    {
        $inputConverter = new InputXmlConverter();
        $outputConverter = new OutputXmlConverter();
        $servletRequest = array('url' => '/people/1/@self');
        $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
        $requestItem = RestRequestItem::createWithRequest($servletRequest, $token, $inputConverter, $outputConverter);
        $requestItem->applyUrlTemplate("/people/{userId}/{groupId}/{personId}");
        $entry = array('isOwner' => false, 'isViewer' => false, 'displayName' => '1 1', 'id' => '1');
        $response = array('entry' => $entry);
        $responseItem = new ResponseItem(null, null, $response);
        ob_start();
        $outputConverter->outputResponse($responseItem, $requestItem);
        $output = ob_get_clean();
        $expected = '<?xml version="1.0" encoding="UTF-8"?>
<response>
  <entry>
    <isOwner></isOwner>
    <isViewer></isViewer>
    <displayName>1 1</displayName>
    <id>1</id>
  </entry>
</response>
';
        $outputXml = simplexml_load_string($output);
        $expectedXml = simplexml_load_string($expected);
        $this->assertEquals($expectedXml, $outputXml);
    }
 private function getToken()
 {
     if (is_null($this->token)) {
         $this->token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     }
     return $this->token;
 }
Exemplo n.º 4
0
 public function __construct()
 {
     $db = new JsonDbOpensocialService();
     $db->resetDb();
     $this->securityToken = BasicSecurityToken::createFromValues(1, 1, 1, 'partuza', 'test.com', 1, 0)->toSerialForm();
     $this->securityToken = urldecode($this->securityToken);
     $this->restUrl = 'http://localhost' . Config::get('web_prefix') . '/social/rest';
 }
 /**
  * gets security token string from get, post or auth header
  * @return string
  */
 public static function getTokenStringFromRequest()
 {
     if (self::$rawToken) {
         return self::$rawToken;
     }
     $headers = OAuthUtil::get_headers();
     self::$rawToken = isset($_GET['st']) ? $_GET['st'] : (isset($_POST['st']) ? $_POST['st'] : (isset($headers['Authorization']) ? self::parseAuthorization($headers['Authorization']) : ''));
     return self::$rawToken;
 }
 /**
  * Produces the proxied version of a URL if it falls within the content-rewrite params and
  * will append a refresh param to the proxied url based on the expires param, and the gadget
  * url so that the proxy server knows to rewrite it's content or not
  *
  * @param string $url
  * @return string
  */
 private function getProxyUrl($url)
 {
     if (strpos(strtolower($url), 'http://') === false && strpos(strtolower($url), 'https://') === false) {
         $url = $this->baseUrl . $url;
     }
     $url = Config::get('web_prefix') . '/gadgets/proxy?url=' . urlencode($url);
     $url .= '&refresh=' . (isset($this->rewrite['expires']) && is_numeric($this->rewrite['expires']) ? $this->rewrite['expires'] : '3600');
     $url .= '&gadget=' . urlencode($this->context->getUrl());
     $url .= '&st=' . urlencode(BasicSecurityToken::getTokenStringFromRequest());
     return $url;
 }
 /**
  * Fetches the content and returns it as-is using the headers as returned
  * by the remote host.
  *
  * @param string $url the url to retrieve
  */
 public function fetch($url)
 {
     // TODO: Check to see if we can just use MakeRequestOptions::fromCurrentRequest
     $st = BasicSecurityToken::getTokenStringFromRequest();
     $body = isset($_GET['postData']) ? $_GET['postData'] : (isset($_POST['postData']) ? $_POST['postData'] : false);
     $authz = isset($_GET['authz']) ? $_GET['authz'] : (isset($_POST['authz']) ? $_POST['authz'] : null);
     $headers = isset($_GET['headers']) ? $_GET['headers'] : (isset($_POST['headers']) ? $_POST['headers'] : null);
     $params = new MakeRequestOptions($url);
     $params->setSecurityTokenString($st)->setAuthz($authz)->setRequestBody($body)->setHttpMethod('GET')->setFormEncodedRequestHeaders($headers)->setNoCache($this->context->getIgnoreCache());
     $result = $this->makeRequest->fetch($this->context, $params);
     $httpCode = (int) $result->getHttpCode();
     $cleanedResponseHeaders = $this->makeRequest->cleanResponseHeaders($result->getResponseHeaders());
     $isShockwaveFlash = false;
     foreach ($cleanedResponseHeaders as $key => $val) {
         header("{$key}: {$val}", true);
         if (strtoupper($key) == 'CONTENT-TYPE' && strtolower($val) == 'application/x-shockwave-flash') {
             // We're skipping the content disposition header for flash due to an issue with Flash player 10
             // This does make some sites a higher value phishing target, but this can be mitigated by
             // additional referer checks.
             $isShockwaveFlash = true;
         }
     }
     if (!$isShockwaveFlash && !Config::get('debug')) {
         header('Content-Disposition: attachment;filename=p.txt');
     }
     $lastModified = $result->getResponseHeader('Last-Modified') != null ? $result->getResponseHeader('Last-Modified') : gmdate('D, d M Y H:i:s', $result->getCreated()) . ' GMT';
     $notModified = false;
     if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && $lastModified && !isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
         $if_modified_since = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
         // Use the request's Last-Modified, otherwise fall back on our internal time keeping (the time the request was created)
         $lastModified = strtotime($lastModified);
         if ($lastModified <= $if_modified_since) {
             $notModified = true;
         }
     }
     if ($httpCode == 200) {
         // only set caching headers if the result was 'OK'
         $this->setCachingHeaders($lastModified);
         // was the &gadget=<gadget url> specified in the request? if so parse it and check the rewrite settings
         if (isset($_GET['gadget'])) {
             $this->rewriteContent($_GET['gadget'], $result);
         }
     }
     // If the cached file time is within the refreshInterval params value, return not-modified
     if ($notModified) {
         header('HTTP/1.0 304 Not Modified', true);
         header('Content-Length: 0', true);
     } else {
         header("HTTP/1.1 {$httpCode} " . $result->getHttpCodeMsg());
         // then echo the content
         echo $result->getResponseContent();
     }
 }
 /**
  * Tests MessagesHandler->handlePut()
  */
 public function testHandlePut()
 {
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     //Create message
     $request = array();
     $request['url'] = '/messages/@viewer/outbox/1';
     $request['postData'] = 'message 1';
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $response = $this->MessagesHandler->handlePut($requestItem);
     $this->assertEquals(NOT_IMPLEMENTED, $response->getError());
     $this->assertEquals("Not implemented", $response->getErrorMessage());
 }
 /**
  * Tests UserId->getUserId()
  */
 public function testGetUserId()
 {
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     $userId = $this->UserId->getUserId($token);
     $this->assertEquals('john.doe', $userId);
     $this->UserId->__construct(UserId::$types[1], 1);
     //owner
     $userId = $this->UserId->getUserId($token);
     $this->assertEquals('john.doe', $userId);
     $this->UserId->__construct(UserId::$types[2], 1);
     //userId
     $userId = $this->UserId->getUserId($token);
     $this->assertEquals('1', $userId);
 }
 /**
  * Tests RestRequestItem->createWithRequest()
  */
 public function testCreateWithRequest()
 {
     $expectedParams = array('oauth_nonce' => '10075052d8a3cd0087d11346edba8f1f', 'oauth_timestamp' => '1242011332', 'oauth_consumer_key' => 'consumerKey', 'fields' => 'gender,name', 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_signature' => 'wDcyXTBqhxW70G+ddZtw7zPVGyE=');
     $urlencodedParams = array();
     foreach ($expectedParams as $key => $value) {
         $urlencodedParams[] = $key . '=' . urlencode($value);
     }
     $url = '/people/1/@self?' . join('&', $urlencodedParams);
     $outputConverter = new OutputJsonConverter();
     $servletRequest = array('url' => $url);
     $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
     $requestItem = RestRequestItem::createWithRequest($servletRequest, $token, 'convertJson', $outputConverter);
     $params = $requestItem->getParameters();
     $this->assertEquals($expectedParams, $params);
 }
 /**
  * Tests JsonDbOpensocialService->getActivities() with paging.
  */
 public function testGetActivities()
 {
     $token = BasicSecurityToken::createFromValues('jane.doe', 'jane.doe', 1, 1, 1, 1);
     $userId = new UserId('owner', null);
     $userIds = array($userId);
     $groupId = new GroupId('self', null);
     $startIndex = 1;
     $count = 1;
     $ret = $this->service->getActivities($userIds, $groupId, 1, null, null, null, null, $startIndex, $count, null, 1, $token);
     $this->assertEquals($startIndex, $ret->startIndex);
     $this->assertEquals($count, count($ret->entry));
     $this->assertEquals(2, $ret->totalResults);
     $this->assertEquals('2', $ret->entry[0]['id']);
     $this->assertEquals('Jane says George likes yoda!', $ret->entry[0]['title']);
     $this->assertEquals('or is it you?', $ret->entry[0]['body']);
 }
 /**
  * Tests PeopleHandler->handleGet()
  */
 public function testHandleGet()
 {
     $request = array();
     $request['url'] = '/people/@viewer/@self';
     $request['method'] = 'GET';
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $response = $this->PeopleHandler->handleGet($requestItem);
     $person = $response->getResponse();
     $this->assertEquals('john.doe', $person['id']);
     $this->assertEquals('MALE', $person['gender']['key']);
     $this->assertEquals('Male', $person['gender']['displayValue']);
     $this->assertEquals('Doe', $person['name']['familyName']);
     $this->assertEquals('John', $person['name']['givenName']);
     $this->assertEquals('John Doe', $person['name']['unstructured']);
 }
 /**
  * {@inheritDoc}
  *
  * Returns a token with some faked out values.
  */
 public function createToken($stringToken)
 {
     if (empty($stringToken) && !empty($_GET['authz'])) {
         throw new GadgetException('INVALID_GADGET_TOKEN');
     }
     try {
         //TODO remove this once we have a better way to generate a fake token
         // in the example files
         if (Config::get('allow_plaintext_token') && count(explode(':', $stringToken)) == 6) {
             $tokens = explode(":", $stringToken);
             return new BasicSecurityToken(null, null, urldecode($tokens[$this->OWNER_INDEX]), urldecode($tokens[$this->VIEWER_INDEX]), urldecode($tokens[$this->APP_ID_INDEX]), urldecode($tokens[$this->CONTAINER_INDEX]), urldecode($tokens[$this->APP_URL_INDEX]), urldecode($tokens[$this->MODULE_ID_INDEX]));
         } else {
             return BasicSecurityToken::createFromToken($stringToken, Config::get('token_max_age'));
         }
     } catch (Exception $e) {
         throw new GadgetException('INVALID_GADGET_TOKEN');
     }
 }
 /**
  *
  * @return SecurityToken
  */
 private function getSecurityToken()
 {
     $token = BasicSecurityToken::getTokenStringFromRequest();
     if (empty($token)) {
         if (Config::get('allow_anonymous_token')) {
             // no security token, continue anonymously, remeber to check
             // for private profiles etc in your code so their not publicly
             // accessable to anoymous users! Anonymous == owner = viewer = appId = modId = 0
             // create token with 0 values, no gadget url, no domain and 0 duration
             $gadgetSigner = Config::get('security_token');
             return new $gadgetSigner(null, 0, SecurityToken::$ANONYMOUS, SecurityToken::$ANONYMOUS, 0, '', '', 0, Config::get('container_id'));
         } else {
             return null;
         }
     }
     $gadgetSigner = Config::get('security_token_signer');
     $gadgetSigner = new $gadgetSigner();
     return $gadgetSigner->createToken($token);
 }
Exemplo n.º 15
0
    /**
     * Tests OutputAtomConverter->outputResponse()
     */
    public function testOutputResponse()
    {
        $inputConverter = new InputAtomConverter();
        $outputConverter = new OutputAtomConverter();
        $servletRequest = array('url' => '/people/1/@self');
        $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
        $requestItem = RestRequestItem::createWithRequest($servletRequest, $token, $inputConverter, $outputConverter);
        $requestItem->applyUrlTemplate("/people/{userId}/{groupId}/{personId}");
        $entry = array('isOwner' => false, 'isViewer' => false, 'displayName' => '1 1', 'id' => '1');
        $response = array('entry' => $entry);
        $responseItem = new ResponseItem(null, null, $response);
        ob_start();
        $outputConverter->outputResponse($responseItem, $requestItem);
        $output = ob_get_clean();
        $expected = '<entry xmlns="http://www.w3.org/2005/Atom">
  <title>person entry for shindig:1</title>
  <author>
    <uri>urn:guid:1</uri>
    <name>shindig:1</name>
  </author>
  <id>urn:guid:1</id>
  <updated>2008-12-11T19:58:31+01:00</updated>
  <content type="application/xml">
    <entry xmlns="http://ns.opensocial.org/2008/opensocial">
      <isOwner></isOwner>
      <isViewer></isViewer>
      <displayName>1 1</displayName>
      <id>1</id>
    </entry>
  </content>
</entry>
';
        $outputXml = simplexml_load_string($output);
        $expectedXml = simplexml_load_string($expected);
        $expectedXml->updated = $outputXml->updated;
        // Prefix may be 'shindig' or something else.
        $expectedXml->title = $outputXml->title;
        $expectedXml->author->name = $outputXml->author->name;
        $this->assertEquals($expectedXml, $outputXml);
    }
Exemplo n.º 16
0
 public function set($params)
 {
     if (empty($_GET['st']) || empty($_GET['name']) || !isset($_GET['value'])) {
         header("HTTP/1.0 400 Bad Request", true);
         echo "<html><body><h1>400 - Bad Request</h1></body></html>";
     } else {
         try {
             $st = urldecode(base64_decode($_GET['st']));
             $key = urldecode($_GET['name']);
             $value = urldecode($_GET['value']);
             $token = BasicSecurityToken::createFromToken($st, PartuzaConfig::get('st_max_age'));
             $app_id = $token->getAppId();
             $viewer = $token->getViewerId();
             $apps = $this->model('applications');
             $apps->set_application_pref($viewer, $app_id, $key, $value);
         } catch (Exception $e) {
             header("HTTP/1.0 400 Bad Request", true);
             echo "<html><body><h1>400 - Bad Request</h1>" . $e->getMessage() . "</body></html>";
         }
     }
     die;
 }
 /**
  *
  * @return SecurityToken
  */
 public function getSecurityToken()
 {
     // Support a configurable host name ('http_host' key) so that OAuth signatures don't fail in reverse-proxy type situations
     $scheme = !isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on" ? 'http' : 'https';
     $http_url = $scheme . '://' . (Config::get('http_host') ? Config::get('http_host') : $_SERVER['HTTP_HOST']) . $_SERVER['REQUEST_URI'];
     // see if we have an OAuth request
     $request = OAuthRequest::from_request(null, $http_url, null);
     $appUrl = $request->get_parameter('oauth_consumer_key');
     $userId = $request->get_parameter('xoauth_requestor_id');
     // from Consumer Request extension (2-legged OAuth)
     $signature = $request->get_parameter('oauth_signature');
     if ($appUrl && $signature) {
         //if ($appUrl && $signature && $userId) {
         // look up the user and perms for this oauth request
         $oauthLookupService = Config::get('oauth_lookup_service');
         $oauthLookupService = new $oauthLookupService();
         $token = $oauthLookupService->getSecurityToken($request, $appUrl, $userId, $this->getContentType());
         if ($token) {
             $token->setAuthenticationMode(AuthenticationMode::$OAUTH_CONSUMER_REQUEST);
             return $token;
         } else {
             return null;
             // invalid oauth request, or 3rd party doesn't have access to this user
         }
     }
     // else, not a valid oauth request, so don't bother
     // look for encrypted security token
     $token = BasicSecurityToken::getTokenStringFromRequest();
     if (empty($token)) {
         if (Config::get('allow_anonymous_token')) {
             // no security token, continue anonymously, remeber to check
             // for private profiles etc in your code so their not publicly
             // accessable to anoymous users! Anonymous == owner = viewer = appId = modId = 0
             // create token with 0 values, no gadget url, no domain and 0 duration
             $gadgetSigner = Config::get('security_token');
             return new $gadgetSigner(null, 0, SecurityToken::$ANONYMOUS, SecurityToken::$ANONYMOUS, 0, '', '', 0, Config::get('container_id'));
         } else {
             return null;
         }
     }
     $gadgetSigner = Config::get('security_token_signer');
     $gadgetSigner = new $gadgetSigner();
     return $gadgetSigner->createToken($token);
 }
Exemplo n.º 18
0
 /**
  * Tests BasicSecurityToken->isAnonymous()
  */
 public function testIsAnonymous()
 {
     $this->assertFalse($this->BasicSecurityToken->isAnonymous());
 }
Exemplo n.º 19
0
<link rel='stylesheet' type='text/css' href='../html/css/general.css'>
<script type="text/javascript" src="../html/js/validations.js"></script>
<?php 
require_once 'Config/config.php';
$ret = array();
$res = "select * from applications where id = {$app_id}";
$rs_Apps = mysql_query($res);
$row_rs_Apps = mysql_fetch_assoc($rs_Apps);
$gadget = $row_rs_Apps;
$container = 'default';
$prefs = '';
if ($gadget['user_prefs']) {
    foreach ($gadget['user_prefs'] as $name => $value) {
        if (!empty($value) && !isset($appParams[$name])) {
            $prefs .= '&up_' . urlencode($name) . '=' . urlencode($value);
        }
    }
}
$securityToken = BasicSecurityToken::createFromValues(isset($person_id) ? $person_id : '0', isset($viewer_id) ? $viewer_id : '0', $gadget['id'], $_SERVER['HTTP_HOST'], urlencode($gadget['url']), $gadget['mod_id']);
$gadget_url_params = array();
parse_str(parse_url($gadget['url'], PHP_URL_QUERY), $gadget_url_params);
$iframe_url = $gadget_server . '/gadgets/ifr?' . "synd=" . $container . "&container=" . $container . "&viewer=" . (isset($viewer_id) ? $viewer_id : '0') . "&owner=" . (isset($person_id) ? $person_id : $viewer_id) . "&aid=" . $gadget['id'] . "&mid=" . $gadget['mod_id'] . "&nocache=1" . "&country=US" . "&lang=EN" . "&view=" . $view . "&parent=" . urlencode("http://" . $_SERVER['HTTP_HOST']) . $prefs . (isset($_REQUEST['appParams']) ? '&view-params=' . urlencode($_REQUEST['appParams']) : '') . "&st=" . base64_encode($securityToken->toSerialForm()) . "&v=" . $gadget['version'] . "&url=" . urlencode($gadget['url']) . "#rpctoken=" . rand(0, getrandmax());
$height = !empty($gadget['height']) ? $gadget['height'] : '200';
$iframe_name = "remote_iframe_" . $mod_id;
$iframe_id = "remote_iframe_" . $mod_id;
$scrolling = $gadget['scrolling'] ? 'yes' : 'no';
$iframe_str = "<iframe width=" . $width . " height=" . $height . " name=" . $iframe_name . " id=" . $iframe_id . " scrolling =" . $scrolling . " frameborder='no' src= '" . $iframe_url . "' class='gadgets-gadget' style=\"display:none;\" onLoad=\"showIframe('" . $iframe_id . "','" . $mod_id . "');\"></iframe>";
echo "<div class='iframe_div'>" . $iframe_str . "</div>";
?>

  
Exemplo n.º 20
0
 /** 
  * Return iframe URL based on the given parameters
  * @param	int			owner id
  * @param	string		avaiable options are 'profile', 'canvas'
  *						http://code.google.com/apis/orkut/docs/orkutdevguide/orkutdevguide-0.8.html#ops_mode
  * @param	string		extra application parameters
  * @return	iframe url
  */
 function getIframeUrl($oid, $view = 'default', $appParams = '')
 {
     $app_settings = $this->getSettings();
     $user_settings = $this->getApplicationSettings($_SESSION['member_id']);
     //retrieve user preferences
     foreach ($app_settings as $key => $setting) {
         if (!empty($key)) {
             $value = isset($user_settings[$key]) ? $user_settings[$key] : (isset($setting->default) ? $setting->default : null);
             if (isset($user_settings[$key])) {
                 unset($user_settings[$key]);
             }
             //shindig doesn't like ';', it only takes '&' as of Apr 6th, 2009
             //$prefs .= SEP.'up_' . urlencode($key) . '=' . urlencode($value);
             $prefs .= '&up_' . urlencode($key) . '=' . urlencode($value);
         }
     }
     foreach ($user_settings as $name => $value) {
         // if some keys _are_ set in the db, but not in the gadget metadata, we still parse them on the url
         // (the above loop unsets the entries that matched
         if (!empty($value) && !isset($appParams[$name])) {
             //shindig doesn't like ';', it only takes '&' as of Apr 6th, 2009
             //$prefs .= SEP.'up_' . urlencode($name) . '=' . urlencode($value);
             $prefs .= '&up_' . urlencode($name) . '=' . urlencode($value);
         }
     }
     //generate security token
     $securityToken = BasicSecurityToken::createFromValues($oid > 0 ? $oid : $_SESSION['member_id'], $_SESSION['member_id'], $this->getId(), 'default', urlencode($this->getUrl()), $this->getModuleId());
     // mod id
     //TODO:
     //   all the & should be using the constant "SEP", however, shingdig isn't parsing ";",
     //   it only parses "&".  Once shindig fixed this, we gotta change it back to SEP
     //@harris July 23, 2009
     $url = AT_SHINDIG_URL . '/gadgets/ifr?' . "bpc=1&synd=ATutor" . "&container=default" . "&viewer=" . $_SESSION['member_id'] . "&owner=" . $oid . "&aid=" . $this->getId() . "&mid=" . $this->getModuleId() . "&country=US" . "&lang=en" . "&view=" . $view . "&parent=" . urlencode("http://" . $_SERVER['HTTP_HOST']) . $prefs . (isset($appParams) ? '&view-params=' . urlencode($appParams) : '') . "&st=" . urlencode(base64_encode($securityToken->toSerialForm())) . "&v=" . $this->getVersion() . "&url=" . urlencode($this->getUrl()) . "#rpctoken=" . rand(0, getrandmax());
     //random unique number
     return $url;
 }
Exemplo n.º 21
0
            if (isset($user_prefs[$key])) {
                unset($user_prefs[$key]);
            }
            $prefs .= '&up_' . urlencode($key) . '=' . urlencode($value);
        }
    }
    // Prepare the user preferences for inclusion in the iframe url
    foreach ($user_prefs as $name => $value) {
        // if some keys _are_ set in the db, but not in the gadget metadata, we still parse them on the url
        // (the above loop unsets the entries that matched
        if (!empty($value) && !isset($appParams[$name])) {
            $prefs .= '&up_' . urlencode($name) . '=' . urlencode($value);
        }
    }
    // Create an encrypted security token, this is used by shindig to get the various gadget instance info like the viewer and owner
    $securityToken = BasicSecurityToken::createFromValues(isset($vars['person']['id']) ? $vars['person']['id'] : SecurityToken::$ANONYMOUS, isset($_SESSION['id']) ? $_SESSION['id'] : SecurityToken::$ANONYMOUS, $gadget['id'], PartuzaConfig::get('container'), urlencode($gadget['url']), $gadget['mod_id']);
    $gadget_url_params = array();
    parse_str(parse_url($gadget['url'], PHP_URL_QUERY), $gadget_url_params);
    // Create the actual iframe URL, this containers a slew of query params that shindig requires to render the gadget, and for the gadget to be able to make social requests
    $rpctoken = rand(0, getrandmax());
    $iframe_url = PartuzaConfig::get('gadget_server') . '/gadgets/ifr?' . "synd=" . PartuzaConfig::get('container') . "&container=" . PartuzaConfig::get('container') . "&viewer=" . (isset($_SESSION['id']) ? $_SESSION['id'] : '0') . "&owner=" . (isset($vars['person']['id']) ? $vars['person']['id'] : '0') . "&aid=" . $gadget['id'] . "&mid=" . $gadget['mod_id'] . (isset($_GET['nocache']) && $_GET['nocache'] == '1' || isset($gadget_url_params['nocache']) && intval($gadget_url_params['nocache']) == 1 || isset($_GET['bpc']) && $_GET['bpc'] == '1' ? "&nocache=1" : '') . "&country=US" . "&lang=en" . "&view=" . $view . "&parent=" . urlencode("http://" . $_SERVER['HTTP_HOST']) . $prefs . (isset($_GET['appParams']) ? '&view-params=' . urlencode($_GET['appParams']) : '') . "&st=" . urlencode(base64_encode($securityToken->toSerialForm())) . "&v=" . $gadget['version'] . "&url=" . urlencode($gadget['url']) . "#rpctoken=" . $rpctoken;
    // Create some chrome, this includes a header with a title, various button for varios actions, and the actual iframe
    ?>
<div class="gadgets-gadget-chrome" style="width:<?php 
    echo $width;
    ?>
px">
<div id="gadgets-gadget-title-bar-<?php 
    echo $gadget['mod_id'];
    ?>
" class="gadgets-gadget-title-bar">
 /**
  * Tests ActivitiesHandler->handlePut()
  */
 public function testHandlePut()
 {
     return;
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     //Create activity
     $request = array();
     $request['url'] = '/activities/@viewer/@self/@app?networkDistance=';
     $request['method'] = 'POST';
     $request['postData'] = array();
     $request['postData']['id'] = '3';
     $request['postData']['appId'] = '1';
     $request['postData']['userId'] = 'john.doe';
     $request['postData']['title'] = 'TestPost 3';
     $request['postData']['body'] = 'TestBody 3';
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $this->ActivitiesHandler->handlePut($requestItem);
     //Validate generated activity
     $request = array();
     $request['url'] = '/activities/@viewer/@self/@app';
     $request['method'] = 'GET';
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $response = $this->ActivitiesHandler->handleGet($requestItem);
     $response = $response->getResponse();
     $entry = $response->getEntry();
     $this->assertEquals('2', $response->getTotalResults());
     //First Entry
     $this->assertEquals('1', $entry[0]['id']);
     $this->assertEquals('john.doe', $entry[0]['userId']);
     $this->assertEquals('yellow', $entry[0]['title']);
     $this->assertEquals('what a color!', $entry[0]['body']);
     //Second Entry
     $this->assertEquals('3', $entry[1]['id']);
     $this->assertEquals('john.doe', $entry[1]['userId']);
     $this->assertEquals('TestPost 3', $entry[1]['title']);
     $this->assertEquals('TestBody 3', $entry[1]['body']);
 }
Exemplo n.º 23
0
 public function testInvalidateUserResourcesWithEmptyAppId()
 {
     $token = BasicSecurityToken::createFromValues('owner', 'viewer', null, 'domain', 'appUrl', '1', 'default');
     $token->setAuthenticationMode(AuthenticationMode::$OAUTH_CONSUMER_REQUEST);
     $request = new RemoteContentRequest('http://url');
     $request->setToken($token);
     $request->setAuthType(RemoteContentRequest::$AUTH_SIGNED);
     $this->service->markResponse($request);
     $opensocialIds = array('owner');
     $this->service->invalidateUserResources($opensocialIds, $token);
     $this->assertFalse($this->service->isValid($request));
     $this->service->markResponse($request);
     $this->assertTrue($this->service->isValid($request));
 }
Exemplo n.º 24
0
 public function testGetMessageCollections()
 {
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 1, 1, 1, 1, 'default');
     $userId = new UserId('owner', null);
     $ret = $this->service->getMessageCollections($userId, MessageCollection::$DEFAULT_FIELDS, null, $token);
     $this->assertEquals('Notifications', $ret->entry[0]['title']);
     $this->assertEquals('notification', $ret->entry[0]['id']);
     $this->assertEquals(2, $ret->entry[0]['total']);
     $this->assertEquals('Inbox', $ret->entry[1]['title']);
     $this->assertEquals('privateMessage', $ret->entry[1]['id']);
     $this->assertEquals(0, $ret->entry[1]['total']);
     $this->assertEquals('Inbox', $ret->entry[2]['title']);
     $this->assertEquals('publicMessage', $ret->entry[2]['id']);
     $this->assertEquals(0, $ret->entry[2]['total']);
 }
 /**
  * Builds a MakeRequestOptions object from the current $_GET and $_POST
  * superglobals.
  *
  * @return MakeRequestOptions An object initialized from the current request.
  * @throws MakeRequestParameterException If any of the parameters were
  *     invalid.
  */
 public static function fromCurrentRequest()
 {
     $href = MakeRequestOptions::getRequestParam('href');
     if (!isset($href)) {
         $href = MakeRequestOptions::getRequestParam('url');
     }
     $options = new MakeRequestOptions($href);
     $options->setHttpMethod(MakeRequestOptions::getRequestParam('httpMethod'))->setRequestBody(MakeRequestOptions::getRequestParam('postData'))->setFormEncodedRequestHeaders(MakeRequestOptions::getRequestParam('headers'))->setResponseFormat(MakeRequestOptions::getRequestParam('contentType'))->setAuthz(MakeRequestOptions::getRequestParam('authz'))->setSignViewer(MakeRequestOptions::getRequestParam('signViewer', 'boolean'))->setSignOwner(MakeRequestOptions::getRequestParam('signOwner', 'boolean'))->setNumEntries(MakeRequestOptions::getRequestParam('numEntries', 'integer'))->setGetSummaries(MakeRequestOptions::getRequestParam('getSummaries', 'boolean'))->setRefreshInterval(MakeRequestOptions::getRequestParam('refreshInterval', 'integer'))->setNoCache(MakeRequestOptions::getRequestParam('bypassSpecCache', 'boolean'))->setOAuthServiceName(MakeRequestOptions::getRequestParam('OAUTH_SERVICE_NAME'))->setOAuthTokenName(MakeRequestOptions::getRequestParam('OAUTH_TOKEN_NAME'))->setOAuthRequestToken(MakeRequestOptions::getRequestParam('OAUTH_REQUEST_TOKEN'))->setOAuthRequestTokenSecret(MakeRequestOptions::getRequestParam('OAUTH_REQUEST_TOKEN_SECRET'))->setOAuthUseToken(MakeRequestOptions::getRequestParam('OAUTH_USE_TOKEN'))->setOAuthReceivedCallback(MakeRequestOptions::getRequestParam('OAUTH_RECEIVED_CALLBACK'))->setOAuthClientState(MakeRequestOptions::getRequestParam('oauthState'))->setSecurityTokenString(BasicSecurityToken::getTokenStringFromRequest());
     return $options;
 }
Exemplo n.º 26
0
 public function load_get_application($app_url)
 {
     global $db;
     $error = false;
     $info = array();
     // see if we have up-to-date info in our db. Cut-off time is 1 day (aka refresh module info once a day)
     $time = $_SERVER['REQUEST_TIME'] - 24 * 60 * 60;
     $url = $db->addslashes($app_url);
     $res = $db->query("select * from applications where url = '{$url}' and modified > {$time}");
     if ($db->num_rows($res)) {
         // we have an entry with up-to-date info
         $info = $db->fetch_array($res, MYSQLI_ASSOC);
     } else {
         // Either we dont have a record of this module or its out of date, so we retrieve the app meta data.
         // Create a fake security token so that gadgets with signed preloading don't fail to load
         $securityToken = BasicSecurityToken::createFromValues(1, 1, 0, PartuzaConfig::get('container'), urlencode($app_url), 0, 1);
         $response = $this->fetch_gadget_metadata($app_url, $securityToken);
         if (!is_object($response) && !is_array($response)) {
             // invalid json object, something bad happened on the shindig metadata side.
             $error = 'An error occured while retrieving the gadget information';
         } else {
             // valid response, process it
             $gadget = $response->gadgets[0];
             if (isset($gadget->errors) && !empty($gadget->errors[0])) {
                 // failed to retrieve gadget, or failed parsing it
                 $error = $gadget->errors[0];
             } else {
                 // retrieved and parsed gadget ok, store it in db
                 $info['url'] = $db->addslashes($gadget->url);
                 $info['title'] = isset($gadget->title) ? $gadget->title : '';
                 $info['directory_title'] = isset($gadget->directoryTitle) ? $gadget->directoryTitle : '';
                 $info['height'] = isset($gadget->height) ? $gadget->height : '';
                 $info['screenshot'] = isset($gadget->screenshot) ? $gadget->screenshot : '';
                 $info['thumbnail'] = isset($gadget->thumbnail) ? $gadget->thumbnail : '';
                 $info['author'] = isset($gadget->author) ? $gadget->author : '';
                 $info['author_email'] = isset($gadget->authorEmail) ? $gadget->authorEmail : '';
                 $info['description'] = isset($gadget->description) ? $gadget->description : '';
                 $info['settings'] = isset($gadget->userPrefs) ? serialize($gadget->userPrefs) : '';
                 $info['views'] = isset($gadget->views) ? serialize($gadget->views) : '';
                 if ($gadget->scrolling == 'true') {
                     $gadget->scrolling = 1;
                 }
                 $info['scrolling'] = !empty($gadget->scrolling) ? $gadget->scrolling : '0';
                 $info['height'] = !empty($gadget->height) ? $gadget->height : '0';
                 // extract the version from the iframe url
                 $iframe_url = $gadget->iframeUrl;
                 $iframe_params = array();
                 parse_str($iframe_url, $iframe_params);
                 $info['version'] = isset($iframe_params['v']) ? $iframe_params['v'] : '';
                 $info['modified'] = $_SERVER['REQUEST_TIME'];
                 // Insert new application into our db, or if it exists (but had expired info) update the meta data
                 $db->query("insert into applications\n\t\t\t\t\t\t\t\t(id, url, title, directory_title, screenshot, thumbnail, author, author_email, description, settings, views, version, height, scrolling, modified)\n\t\t\t\t\t\t\t\tvalues\n\t\t\t\t\t\t\t\t(\n\t\t\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['url']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['title']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['directory_title']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['screenshot']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['thumbnail']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['author']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['author_email']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['description']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['settings']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['views']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['version']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['height']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['scrolling']) . "',\n\t\t\t\t\t\t\t\t\t'" . $db->addslashes($info['modified']) . "'\n\t\t\t\t\t\t\t\t) on duplicate key update\n\t\t\t\t\t\t\t\t\turl = '" . $db->addslashes($info['url']) . "',\n\t\t\t\t\t\t\t\t\ttitle = '" . $db->addslashes($info['title']) . "',\n\t\t\t\t\t\t\t\t\tdirectory_title = '" . $db->addslashes($info['directory_title']) . "',\n\t\t\t\t\t\t\t\t\tscreenshot = '" . $db->addslashes($info['screenshot']) . "',\n\t\t\t\t\t\t\t\t\tthumbnail = '" . $db->addslashes($info['thumbnail']) . "',\n\t\t\t\t\t\t\t\t\tauthor = '" . $db->addslashes($info['author']) . "',\n\t\t\t\t\t\t\t\t\tauthor_email = '" . $db->addslashes($info['author_email']) . "',\n\t\t\t\t\t\t\t\t\tdescription = '" . $db->addslashes($info['description']) . "',\n\t\t\t\t\t\t\t\t\tsettings = '" . $db->addslashes($info['settings']) . "',\n\t\t\t\t\t\t\t\t\tviews = '" . $db->addslashes($info['views']) . "',\n\t\t\t\t\t\t\t\t\tversion = '" . $db->addslashes($info['version']) . "',\n\t\t\t\t\t\t\t\t\theight = '" . $db->addslashes($info['height']) . "',\n\t\t\t\t\t\t\t\t\tscrolling = '" . $db->addslashes($info['scrolling']) . "',\n\t\t\t\t\t\t\t\t\tmodified = '" . $db->addslashes($info['modified']) . "'\n\t\t\t\t\t\t\t\t");
                 $res = $db->query("select id from applications where url = '" . $db->addslashes($info['url']) . "'");
                 if (!$db->num_rows($res)) {
                     $error = "Could not store application in registry";
                 } else {
                     list($id) = $db->fetch_row($res);
                     $info['id'] = $id;
                     $this->invalidate_dependency('applications', $id);
                 }
             }
         }
     }
     if (!$error) {
         $this->add_dependency('applications', $info['id']);
     }
     $info['error'] = $error;
     return $info;
 }
 /**
  * Tests ActivitiesHandler->handlePut()
  */
 public function testHandlePut()
 {
     $token = BasicSecurityToken::createFromValues('john.doe', 'john.doe', 'app', 'domain', 'appUrl', '1');
     //Create data
     $request = array();
     $request['url'] = '/appdata/@viewer/@self/@app?fields=count';
     $request['method'] = 'POST';
     $request['postData'] = array();
     $request['postData']['count'] = 'TestHandlePut';
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $this->AppDataHandler->handlePut($requestItem);
     //Validate generated data
     $request = array();
     $request['url'] = '/appdata/@viewer/@self/@app?networkDistance=&fields=count';
     $request['method'] = 'GET';
     $requestItem = new RestRequestItem();
     $requestItem->createRequestItemWithRequest($request, $token);
     $response = $this->AppDataHandler->handleGet($requestItem);
     $response = $response->getResponse();
     $entry = $response->getEntry();
     $this->assertEquals('TestHandlePut', $entry['john.doe']['count']);
 }
 /**
  * Extracts the 'st' token from the GET or POST params and calls the
  * signer to validate the token
  *
  * @param SecurityTokenDecoder $signer the signer to use (configured in config.php)
  * @return SecurityToken An object representation of the token data.
  */
 public function extractAndValidateToken($signer)
 {
     if ($signer == null) {
         return null;
     }
     $token = BasicSecurityToken::getTokenStringFromRequest();
     return $this->validateToken($token, $signer);
 }
 /**
  * Tests through SigningFetcher
  */
 public function testSigningFetch()
 {
     $request1 = new RemoteContentRequest('http://test.chabotc.com/signing.html');
     $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
     $request1->setToken($token);
     $request1->setAuthType(RemoteContentRequest::$AUTH_SIGNED);
     $request2 = new RemoteContentRequest('http://test.chabotc.com/ok.html');
     $this->basicRemoteContent->invalidate($request1);
     $this->basicRemoteContent->invalidate($request2);
     $requests = array($request1, $request2);
     $this->basicRemoteContent->multiFetch($requests);
     $content = $request1->getResponseContent();
     $this->assertEquals("OK", trim($content));
     $content = $request2->getResponseContent();
     $this->assertEquals("OK", trim($content));
 }
Exemplo n.º 30
0
 /**
  * Tests that setting "sign_viewer" = false does not include viewer
  * information in the request.
  */
 public function testSignedNoViewerRequest()
 {
     $token = BasicSecurityToken::createFromValues('owner', 'viewer', 'app', 'domain', 'appUrl', '1', 'default');
     $params = new MakeRequestOptions('http://www.example.com');
     $params->setAuthz('SIGNED')->setNoCache(true)->setSignViewer(false)->setSecurityTokenString(urldecode($token->toSerialForm()));
     $request = $this->catchRequest($params, $this->response);
     $this->assertContains('oauth_signature', $request->getUrl());
     $this->assertNotContains('opensocial_viewer_id=viewer', $request->getUrl());
     $this->assertContains('opensocial_owner_id=owner', $request->getUrl());
 }