Example #1
0
 public function addUrl(Url $loc, DateTime $lastmod = null, $changefreq = null, $priority = null)
 {
     // check length
     $url = $loc->getUrl();
     if (strlen($url) >= 2048) {
         throw new Exception('Location value must be less than 2048 characters');
     }
     $this->writer->startElement('url');
     $this->writer->writeElement('loc', $url);
     if ($lastmod !== null) {
         $this->writer->writeElement('lastmod', $lastmod->format(DateTime::W3C));
     }
     if ($changefreq !== null) {
         if (in_array($changefreq, self::$freq)) {
             $this->writer->writeElement('changefreq', $changefreq);
         } else {
             throw new Exception('Invalid change frequence must be one of ' . implode(', ', self::$freq));
         }
     }
     if ($priority !== null) {
         $priority = (double) $priority;
         if ($priority >= 0.0 && $priority <= 1.0) {
             $this->writer->writeElement('priority', $priority);
         } else {
             throw new Exception('Invalid priority must be between 0.0 and 0.1');
         }
     }
     $this->writer->endElement();
 }
Example #2
0
 /**
  * Requests the $url and tries to parse the response as oembed type. The url
  * must be pointing to an oembed provider i.e.:
  * http://flickr.com/services/oembed?url=http://www.flickr.com/photos/neilio/20403964/
  *
  * @param PSX\Url $url
  * @return PSX\Oembed\TypeAbstract
  */
 public function request(Url $url)
 {
     if (!$url->issetParam('url')) {
         throw new Exception('Required parameter url missing');
     }
     $format = $url->addParam('format', 'json');
     $request = new GetRequest($url, array('User-Agent' => __CLASS__ . ' ' . Base::VERSION, 'Accept' => 'application/json'));
     $response = $this->http->request($request);
     if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
         $source = function (array $data) {
             $type = isset($data['type']) ? strtolower($data['type']) : null;
             if (in_array($type, array('link', 'photo', 'rich', 'video'))) {
                 $class = 'PSX\\Oembed\\Type\\' . ucfirst($type);
                 if (class_exists($class)) {
                     return new $class();
                 } else {
                     throw new Exception('Class "' . $class . '" does not exist');
                 }
             } else {
                 throw new InvalidDataException('Invalid type');
             }
         };
         return $this->importer->import($source, $response, null, ReaderInterface::JSON);
     } else {
         throw new Exception('Invalid response code ' . $response->getStatusCode());
     }
 }
Example #3
0
File: Mock.php Project: seytar/psx
 public function request(RequestInterface $request, Options $options)
 {
     $url = $request->getUri();
     foreach ($this->resources as $resource) {
         $resourceUrl = new Url($resource['url']);
         if ($resource['method'] == $request->getMethod() && $resourceUrl->getHost() == $url->getHost() && $resourceUrl->getPath() == $url->getPath() && $resourceUrl->getQuery() == $url->getQuery()) {
             $response = $resource['handler']($request);
             return ResponseParser::convert($response);
         }
     }
     throw new Exception('Resource not available ' . $request->getMethod() . ' ' . $url);
 }
Example #4
0
 public function hasProject($url)
 {
     $url = new Url($url);
     if ($url->getHost() != 'github.com') {
         return false;
     }
     $parts = explode('/', trim($url->getPath(), '/'));
     if (count($parts) != 2) {
         return false;
     }
     $request = new GetRequest($url);
     $response = $this->http->request($request);
     return $response->getCode() == 200;
 }
Example #5
0
 /**
  * Helper method to start the flow by redirecting the user to the
  * authentication server. The getAccessToken method must be used when the
  * server redirects the user back to the redirect uri
  *
  * @param \PSX\Url $url
  * @param string $clientId
  * @param string $redirectUri
  * @param string $scope
  * @param string $state
  */
 public static function redirect(Url $url, $clientId, $redirectUri = null, $scope = null, $state = null)
 {
     $parameters = $url->getParameters();
     $parameters['response_type'] = 'code';
     $parameters['client_id'] = $clientId;
     if (isset($redirectUri)) {
         $parameters['redirect_uri'] = $redirectUri;
     }
     if (isset($scope)) {
         $parameters['scope'] = $scope;
     }
     if (isset($state)) {
         $parameters['state'] = $state;
     }
     throw new StatusCode\TemporaryRedirectException($url->withScheme('https')->withParameters($parameters)->toString());
 }
Example #6
0
 /**
  * @httpMethod GET
  * @path /
  */
 public function doIndex()
 {
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $search = $this->get->search('string');
     if (!empty($search)) {
         $search = strlen($search) > 64 ? substr($search, 0, 64) : $search;
         $queryString = new QueryString();
         //$queryString->setDefaultOperator('AND');
         $queryString->setQuery($search);
         $query = new Query();
         $query->setQuery($queryString);
         $query->setFrom($url->getParam('startIndex'));
         $query->setLimit($count);
         $query->setHighlight(array('pre_tags' => array('<mark>'), 'post_tags' => array('</mark>'), 'fields' => array('title' => new \stdClass(), 'content' => new \stdClass())));
         // get elasticsearch client
         $client = new Client(array('host' => $this->registry['search.host'], 'port' => $this->registry['search.port']));
         $index = $client->getIndex('amun');
         $searchResult = $index->search($query);
         $result = new ResultSet($searchResult->getTotalHits(), $url->getParam('startIndex'), $count);
         foreach ($searchResult as $row) {
             $data = $row->getData();
             $data['url'] = $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . $data['path'];
             $data['date'] = new DateTime('@' . $data['date']);
             // if we have an highlite overwrite the title or content
             $highlights = $row->getHighlights();
             if (isset($highlights['title'])) {
                 $data['title'] = implode(' ... ', $highlights['title']);
             }
             if (isset($highlights['content'])) {
                 $data['content'] = implode(' ... ', $highlights['content']);
             }
             $result->addData($data);
         }
         $this->template->assign('resultSearch', $result);
         $paging = new Paging($url, $result);
         $this->template->assign('pagingSearch', $paging, 0);
         return $result;
     }
 }
Example #7
0
 public function testGet()
 {
     $url = new Url($this->getEndpoint());
     $url->addParam('format', 'jas');
     $response = $this->signedRequest('GET', $url);
     $this->assertEquals(200, $response->getCode());
     // check result
     $result = Json::decode($response->getBody());
     $this->assertArrayHasKey('itemsPerPage', $result, $response->getBody());
     $this->assertArrayHasKey('startIndex', $result, $response->getBody());
     $this->assertArrayHasKey('items', $result, $response->getBody());
     $this->assertEquals(true, count($result['items']) > 0);
     foreach ($result['items'] as $activity) {
         $this->assertArrayHasKey('actor', $activity);
         $this->assertArrayHasKey('object', $activity);
         $this->assertArrayHasKey('verb', $activity);
     }
     // try to create activitystream object
     $reader = new Reader\Json();
     $result = $reader->read($response);
     $collection = new Collection();
     $collection->import($result);
     $this->assertInstanceOf('PSX\\ActivityStream\\Collection', $collection);
 }
Example #8
0
 public function getRequests()
 {
     $con = $this->getRequestCondition();
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\User\\Friend')->getRequestResultSet($this->user->getId(), array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, SQL::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingRequests', $paging, 0);
     return $result;
 }
Example #9
0
 private function getForum()
 {
     $con = $this->getRequestCondition();
     $con->add('pageId', '=', $this->page->getId());
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler()->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, SQL::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingForum', $paging, 0);
     return $result;
 }
Example #10
0
 public function getApplications()
 {
     $con = $this->getRequestCondition();
     $con->add('authorId', '=', $this->user->getId());
     $con->add('allowed', '=', 1);
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\Oauth\\Access')->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, SQL::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingApplications', $paging, 0);
     return $result;
 }
Example #11
0
 private function getFriends()
 {
     $con = $this->getRequestCondition();
     $con->add('authorId', '=', $this->user->getId());
     $con->add('status', '=', Friend\Record::NORMAL);
     // search
     $search = $this->post->search('string');
     if (strlen($search) >= 3 && strlen($search) <= 16) {
         $con->add('friendName', 'LIKE', '%' . $search . '%');
     }
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\User\\Friend')->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, Sql::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingFriends', $paging, 0);
     return $result;
 }
Example #12
0
File: Oauth.php Project: seytar/psx
 /**
  * Normalize the url like defined in
  *
  * @see http://tools.ietf.org/html/rfc5849#section-3.4.1.2
  * @param \PSX\Url $url
  * @return false|string
  */
 public static function getNormalizedUrl(Url $url)
 {
     $scheme = $url->getScheme();
     $host = $url->getHost();
     $port = $url->getPort();
     $path = $url->getPath();
     // no port for 80 (http) and 443 (https)
     if (($port == 80 || empty($port)) && strcasecmp($scheme, 'http') == 0 || ($port == 443 || empty($port)) && strcasecmp($scheme, 'https') == 0) {
         $normalizedUrl = $scheme . '://' . $host . $path;
     } else {
         if (!empty($port)) {
             $normalizedUrl = $scheme . '://' . $host . ':' . $port . $path;
         } else {
             throw new Exception('No port specified');
         }
     }
     return strtolower($normalizedUrl);
 }
Example #13
0
 private function getNews()
 {
     $con = $this->getRequestCondition();
     $con->add('pageId', '=', $this->page->getId());
     // archive
     $year = (int) $this->getUriFragments('year');
     $month = (int) $this->getUriFragments('month');
     // i think this software will not be used after the year 3000 if so
     // please travel back in time and slap me in the face ... nothing
     // happens ;D
     if ($year > 2010 && $year < 3000 && ($month > 0 && $month < 13)) {
         $date = new DateTime($year . '-' . ($month < 10 ? '0' : '') . $month . '-01', $this->registry['core.default_timezone']);
         $con->add('date', '>=', $date->format(DateTime::SQL));
         $con->add('date', '<', $date->add(new DateInterval('P1M'))->format(DateTime::SQL));
     }
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler()->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, SQL::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingNews', $paging, 0);
     return $result;
 }
Example #14
0
 /**
  * Resolves the $uri either to an PSX\OpenId\Identity if its an XRI or
  * to an PSX\Url
  *
  * @return PSX\OpenId\Identity|PSX\Url
  */
 public function normalizeUri($uri)
 {
     if (!empty($uri)) {
         $uri = strtolower($uri);
         $isXri = false;
         if (substr($uri, 0, 6) == 'xri://') {
             $uri = substr($uri, 6);
             $isXri = true;
         }
         if (in_array($uri[0], self::$xriGlobalContextSymbol)) {
             $isXri = true;
         }
         if ($isXri !== true) {
             if (substr($uri, 0, 7) != 'http://' && substr($uri, 0, 8) != 'https://') {
                 $uri = 'http://' . $uri;
             }
             $url = new Url($uri);
             if ($url->getScheme() == 'http' || $url->getScheme() == 'https') {
                 return $url;
             } else {
                 throw new Exception('Unknown protocol in identity');
             }
         } else {
             return $this->discoverXriIdentity($uri);
         }
     }
     return false;
 }
Example #15
0
 public function testResourceNotFound()
 {
     $url = new Url($this->getEndpoint());
     $url->addParam('resource', 'foobar');
     $request = new GetRequest($url);
     $response = $this->http->request($request);
     $this->assertEquals(404, $response->getCode());
 }
Example #16
0
File: View.php Project: visapi/amun
 private function getComments()
 {
     $con = new Condition();
     $con->add('pageId', '=', $this->page->getId());
     $con->add('refId', '=', $this->id);
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\Comment')->getResultSet(array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, Sql::FETCH_OBJECT);
     $paging = new Paging($url, $result);
     $this->template->assign('pagingComments', $paging, 0);
     return $result;
 }
Example #17
0
File: Auth.php Project: visapi/amun
 private function denyAccess($token, $callback)
 {
     // insert access
     $now = new DateTime('NOW', $this->registry['core.default_timezone']);
     $this->getSql()->replace($this->registry['table.oauth_access'], array('apiId' => $this->apiId, 'userId' => $this->user->getId(), 'allowed' => 0, 'date' => $now->format(DateTime::SQL)));
     // delete token
     $con = new Condition(array('token', '=', $token));
     $this->getSql()->delete($this->registry['table.oauth_request'], $con);
     // redirect if callback available
     if ($callback != 'oob') {
         $url = new Url($callback);
         // here we can inform the consumer that the request has been denied
         $url->addParam('oauth_token', $token);
         $url->addParam('x_oauth_error', 'request+denied');
         header('Location: ' . strval($url));
         exit;
     } else {
         header('Location: ' . $this->config['psx_url']);
         exit;
     }
 }
Example #18
0
 private function getActivities(Account\Record $account)
 {
     $con = $this->getRequestCondition();
     $url = new Url($this->base->getSelf());
     $count = $url->getParam('count') > 0 ? $url->getParam('count') : 8;
     $count = $count > 16 ? 16 : $count;
     $result = $this->getHandler('AmunService\\User\\Activity')->getPublicResultSet($account->id, array(), $url->getParam('startIndex'), $count, $url->getParam('sortBy'), $url->getParam('sortOrder'), $con, Sql::FETCH_OBJECT);
     $paging = new Paging($url, $result, 0);
     $this->template->assign('pagingActivities', $paging);
     return $result;
 }
Example #19
0
 protected function discoverWebfingerRfc7033(Url $url, $resource, $rel = null)
 {
     try {
         $url = $url->getScheme() . '://' . $url->getHost() . '/.well-known/webfinger';
         $url = new Url($url);
         $url->addParam('resource', $resource);
         if ($rel !== null) {
             $url->addParam('rel', $rel);
         }
         return Hostmeta::requestJrd($this->http, $url);
     } catch (\Exception $e) {
         $this->lastError = $e->getMessage();
     }
     return null;
 }
Example #20
0
File: Html.php Project: visapi/amun
 private function replaceUrl(Token\Text $text)
 {
     if (strpos($text->data, 'http://') === false && strpos($text->data, 'https://') === false) {
         return false;
     }
     // if parent element of the text is an link dont replace links
     $isHref = false;
     if ($text->parentNode instanceof Token\Element && strtolower($text->parentNode->name) == 'a') {
         $isHref = true;
     }
     $parts = preg_split('/(https?:\\/\\/\\S*)/S', $text->data, -1, PREG_SPLIT_DELIM_CAPTURE);
     $data = '';
     foreach ($parts as $i => $part) {
         if ($i % 2 == 0) {
             $data .= $part;
         } else {
             try {
                 $url = new Url($part);
                 if ($this->discover) {
                     foreach ($this->oembedHosts as $host => $endpoint) {
                         if (strpos($url->getHost(), $host) !== false) {
                             try {
                                 $api = new Url($endpoint);
                                 $api->addParam('url', $part);
                                 $api->addParam('maxwidth', 240);
                                 $api->addParam('maxheight', 180);
                                 $type = $this->oembed->request($api);
                                 $this->oembedMedia[] = $type;
                                 break;
                             } catch (\Exception $e) {
                                 // oembed discovery failed
                             }
                         }
                     }
                 }
                 if (!$isHref) {
                     $data .= '<a href="' . $part . '">' . $part . '</a>';
                 } else {
                     $data .= $part;
                 }
             } catch (Exception $e) {
                 $data .= $part;
             }
         }
     }
     $text->data = $data;
 }
Example #21
0
 public function create(RecordInterface $record)
 {
     if ($record->hasFields('groupId', 'status', 'identity', 'name', 'pw')) {
         // check whether identity exists
         $con = new Condition();
         $con->add('identity', '=', $record->identity);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // check whether name and hostid exists
         $con = new Condition();
         $con->add('hostId', '=', !empty($record->hostId) ? $record->hostId : 0);
         $con->add('name', '=', $record->name);
         if ($this->table->count($con) > 0) {
             throw new Exception('Identity already exists');
         }
         // default values
         if (!isset($record->countryId)) {
             $record->setCountryId(1);
         }
         if (!isset($record->timezone)) {
             $record->setTimezone('UTC');
         }
         $date = new DateTime('NOW', $this->registry['core.default_timezone']);
         $record->token = Security::generateToken();
         $record->ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
         $record->lastSeen = $date->format(DateTime::SQL);
         $record->updated = $date->format(DateTime::SQL);
         $record->date = $date->format(DateTime::SQL);
         // set host id if we have an remote host discover the profile url
         if (empty($record->hostId)) {
             $record->hostId = 0;
             $record->profileUrl = $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'profile/' . $record->name;
         } else {
             $record->status = Record::REMOTE;
             $record->profileUrl = $this->discoverProfileUrl($record->hostId, $record->name);
         }
         // set global id
         if (!isset($record->globalId)) {
             $profileUrl = new Url($record->profileUrl);
             $record->globalId = $this->base->getUUID('user:account:' . $profileUrl->getHost() . ':' . $record->name . ':' . uniqid());
         }
         // set thumbnail if email available and thumbnail not set
         if (!isset($record->thumbnailUrl)) {
             $default = $this->config['psx_url'] . '/img/avatar/no_image.png';
             if (!empty($record->email)) {
                 $record->thumbnailUrl = 'http://www.gravatar.com/avatar/' . md5(strtolower(trim($record->email))) . '?d=' . urlencode($default) . '&s=48';
             } else {
                 $record->thumbnailUrl = $default;
             }
         }
         $this->table->insert($record->getData());
         $record->id = $this->sql->getLastInsertId();
         // insert relation to self
         $this->sql->insert($this->registry['table.user_friend'], array('status' => Friend\Record::NORMAL, 'userId' => $record->id, 'friendId' => $record->id, 'date' => $date->format(DateTime::SQL)));
         $this->notify(RecordAbstract::INSERT, $record);
         return $record;
     } else {
         throw new Exception('Missing field in record');
     }
 }
Example #22
0
 protected function doCheckAuthentication(Url $url)
 {
     $params = $url->getParams();
     $params['openid_mode'] = 'check_authentication';
     $data = http_build_query($params, '', '&');
     $body = new TempStream(fopen('php://memory', 'r+'));
     $request = new Request(new Url('http://127.0.0.1/openid'), 'POST', array('Content-Type' => 'application/x-www-urlencoded'), $data);
     $response = new Response();
     $response->setBody($body);
     $controller = $this->loadController($request, $response);
     $body = (string) $response->getBody();
     $data = OpenId::keyValueDecode($body);
     $this->assertEquals('http://specs.openid.net/auth/2.0', $data['ns']);
     $this->assertEquals('true', $data['is_valid']);
 }
Example #23
0
    public function onCheckidSetup(SetupRequest $request)
    {
        // check whether authenticated
        if (!$this->isAuthenticated()) {
            $loginUrl = $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'login';
            $selfUrl = new Url($this->base->getSelf());
            $values = array_merge($_GET, $_POST);
            foreach ($values as $key => $value) {
                $selfUrl->addParam($key, $value);
            }
            //$selfUrl->addParam('openid.mode', 'checkid_setup');
            //$selfUrl->addParam('openid.ns', self::NS);
            header('Location: ' . $loginUrl . '?redirect=' . urlencode(strval($selfUrl)));
            exit;
        }
        // check association
        $sql = <<<SQL
SELECT
\t`assoc`.`id`,
\t`assoc`.`expires`,
\t`assoc`.`date`
FROM 
\t{$this->registry['table.openid_assoc']} `assoc`
WHERE 
\t`assoc`.`assocHandle` = ?
SQL;
        $row = $this->sql->getRow($sql, array($request->getAssocHandle()));
        if (!empty($row)) {
            // check expire
            $now = new DateTime('NOW', $this->registry['core.default_timezone']);
            $expire = (int) $row['expires'];
            if (time() > $now->getTimestamp() + $expire) {
                throw new Exception('Association is expired');
            }
        } else {
            if (!$request->isImmediate()) {
                // create association
                $date = new DateTime('NOW', $this->registry['core.default_timezone']);
                $assocHandle = ProviderAbstract::generateHandle();
                $secret = base64_encode(ProviderAbstract::randomBytes(20));
                $this->sql->insert($this->registry['table.openid_assoc'], array('assocHandle' => $assocHandle, 'assocType' => 'HMAC-SHA1', 'sessionType' => 'DH-SHA1', 'secret' => $secret, 'expires' => self::EXPIRE, 'date' => $date->format(DateTime::SQL)));
                // set assoc handle
                $request->setAssocHandle($assocHandle);
            } else {
                throw new Exception('Invalid association');
            }
        }
        // count connect requests
        /*
        $maxCount = 5;
        $con      = new PSX_Sql_Condition(array('userId', '=', $this->user->getId()), array('status', '=', AmunService_Oauth_Record::TEMPORARY));
        $count    = $this->sql->count($this->registry['table.oauth_request'], $con);
        
        if($count > $maxCount)
        {
        	$conDelete = new PSX_Sql_Condition();
        	$result    = $this->sql->select($this->registry['table.oauth_request'], array('id', 'expire', 'date'), $con, PSX_Sql::SELECT_ALL);
        
        	foreach($result as $row)
        	{
        		$now  = new DateTime('NOW', $this->registry['core.default_timezone']);
        		$date = new DateTime($row['date'], $this->registry['core.default_timezone']);
        		$date->add(new DateInterval($row['expire']));
        
        		if($now > $date)
        		{
        			$conDelete->add('id', '=', $row['id'], 'OR');
        		}
        	}
        
        	if($conDelete->hasCondition())
        	{
        		$this->sql->delete($this->registry['table.oauth_request'], $conDelete);
        	}
        
        	throw new Exception('You can have max ' . $maxCount . ' temporary account connect requests. Each request expires after 30 hour');
        }
        */
        // save request params
        $_SESSION['amun_openid_request'] = $request;
        // redirect
        header('Location: ' . $this->config['psx_url'] . '/' . $this->config['psx_dispatch'] . 'login/connect');
        exit;
    }