Esempio n. 1
0
 /**
  * Convert the url or part of it to a string
  *
  * Using scheme://user:pass@host/path?query#fragment';
  *
  * @param integer $parts A bitmask of binary or'ed HTTP_URL constants; FULL is the default
  * @return  string
  */
 public function toString($parts = self::FULL)
 {
     if (isset($this->query['option'])) {
         $this->getObject('application')->getRouter()->build($this);
     }
     return parent::toString($parts);
 }
 public function testFormCollection()
 {
     $collection = FormCollection::create(TestCity::proto()->makeForm()->drop('id'));
     $url = HttpUrl::create()->parse('http://i.would.like.to.create.cities/?name[77]=Moscow&capital[77]=1&large[77]=1&name[50]=Krasnogorsk&name[78]=Piter&large[78]=1');
     parse_str($url->getQuery(), $getArray);
     $collection->import($getArray);
     foreach ($collection as $number => $form) {
         switch ($number) {
             case 77:
                 $this->assertEquals('Moscow', $form->getValue('name'));
                 $this->assertTrue($form->getValue('capital'));
                 $this->assertTrue($form->getValue('large'));
                 break;
             case 78:
                 $this->assertEquals('Piter', $form->getValue('name'));
                 $this->assertFalse($form->getValue('capital'));
                 $this->assertTrue($form->getValue('large'));
                 break;
             case 50:
                 $this->assertEquals('Krasnogorsk', $form->getValue('name'));
                 $this->assertFalse($form->getValue('capital'));
                 $this->assertFalse($form->getValue('large'));
                 break;
             default:
                 $this->assertTrue(false);
                 break;
         }
     }
 }
 public static function newFromUrlString($urlString)
 {
     if (strlen($urlString) <= 7) {
         return;
     }
     if (self::containsSpecialChar($urlString)) {
         return;
     }
     if ($urlString == WEBDIR) {
         return;
     }
     $url = new HttpUrl($urlString);
     if ($url->getDomainName() == 'localhost') {
         return;
     }
     return new self('', $urlString);
 }
Esempio n. 4
0
 function setHost($host)
 {
     parent::setHost($host);
     if (!$this->baseHost) {
         $this->baseHost = $this->getHost();
     }
     return $this;
 }
 /**
  * @return HttpUrl
  **/
 protected function processPath(HttpRequest $request)
 {
     if ($request->hasServerVar('REQUEST_URI')) {
         $path = $this->getPath(HttpUrl::create()->parse($request->getServerVar('REQUEST_URI')));
     } else {
         throw new RouterException('Cannot resolve path');
     }
     return $path;
 }
 public function testGetPath()
 {
     foreach (self::$fixtures as $base => $cases) {
         $rewriter = RouterRewrite::me()->setBaseUrl(HttpUrl::create()->parse($base));
         foreach ($cases as $requestUri => $pathResult) {
             $actualResult = RouterBaseRuleStub::create()->getPath(HttpUrl::create()->parse($requestUri))->toString();
             $this->assertEquals($pathResult, $actualResult, "base url: {$base}\nrequest uri: {$requestUri}");
         }
     }
 }
 public function testCurlException()
 {
     $request = HttpRequest::create()->setUrl(HttpUrl::create()->parse('http://nonexistentdomain.xyz'))->setMethod(HttpMethod::get());
     try {
         $response = CurlHttpClient::create()->setTimeout(3)->send($request);
         $this->fail();
     } catch (NetworkException $e) {
         $this->assertContains('curl error', $e->getMessage());
     }
 }
Esempio n. 8
0
 /**
  * Returns the HTTP referrer.
  *
  * 'referer' a commonly used misspelling word for 'referrer'
  * @link http://en.wikipedia.org/wiki/HTTP_referrer
  *
  * @param   boolean  $isInternal Only allow internal url's
  * @return  HttpUrl  A HttpUrl object
  */
 public function getReferrer($isInternal = true)
 {
     if (!isset($this->_referrer)) {
         $referrer = $this->getObject('lib:filter.url')->sanitize($this->_headers->get('Referer'));
         $this->_referrer = $this->getObject('lib:http.url', array('url' => $referrer));
     }
     if ($isInternal) {
         if (!$this->getObject('lib:filter.internalurl')->validate($this->_referrer->toString(HttpUrl::SCHEME | HttpUrl::HOST))) {
             return null;
         }
     }
     return $this->_referrer;
 }
Esempio n. 9
0
 public function import($scope)
 {
     if (!($result = parent::import($scope))) {
         return $result;
     }
     try {
         $this->value = HttpUrl::create()->parse($this->value)->setCheckPrivilegedPorts($this->checkPrivilegedPorts);
     } catch (WrongArgumentException $e) {
         $this->value = null;
         return false;
     }
     if (!$this->value->isValid()) {
         $this->value = null;
         return false;
     }
     $this->value->normalize();
     return true;
 }
Esempio n. 10
0
 /**
  * Returns the HTTP referrer.
  *
  * If a base64 encoded _referrer property exists in the request payload, it is used instead of the referrer.
  * 'referer' a commonly used misspelling word for 'referrer'
  * @link http://en.wikipedia.org/wiki/HTTP_referrer
  *
  * @param   boolean  $isInternal Only allow internal url's
  * @return  HttpUrl|null  A HttpUrl object or NULL if no referrer could be found
  */
 public function getReferrer($isInternal = true)
 {
     if (!isset($this->_referrer) && ($this->_headers->has('Referer') || $this->data->has('_referrer'))) {
         if ($this->data->has('_referrer')) {
             $referrer = base64_decode($this->data->get('_referrer', 'base64'));
         } else {
             $referrer = $this->_headers->get('Referer');
         }
         $this->setReferrer($this->getObject('lib:filter.url')->sanitize($referrer));
     }
     if (isset($this->_referrer) && $isInternal) {
         $url = $this->_referrer->toString(HttpUrl::SCHEME | HttpUrl::HOST);
         if (!$this->getObject('lib:filter.internalurl')->validate($url)) {
             return null;
         }
     }
     return $this->_referrer;
 }
Esempio n. 11
0
 /**
  * Render a sorting header
  *
  * @param   array   $config An optional array with configuration options
  * @return  string  Html
  */
 public function sort($config = array())
 {
     $config = new ObjectConfigJson($config);
     $config->append(array('title' => '', 'column' => '', 'direction' => 'asc', 'sort' => '', 'url' => null));
     $translator = $this->getObject('translator');
     //Set the title
     if (empty($config->title)) {
         $config->title = ucfirst($config->column);
     }
     //Set the direction
     $direction = strtolower($config->direction);
     $direction = in_array($direction, array('asc', 'desc')) ? $direction : 'asc';
     //Set the class
     $class = '';
     if ($config->column == $config->sort) {
         $direction = $direction == 'desc' ? 'asc' : 'desc';
         // toggle
         $class = 'class="-koowa-' . $direction . '"';
     }
     //Set the query in the route
     if (!$config->url instanceof HttpUrlInterface) {
         $config->url = HttpUrl::fromString($config->url);
     }
     $config->url->query['sort'] = $config->column;
     $config->url->query['direction'] = $direction;
     $html = '<a href="' . $config->url . '" title="' . $translator->translate('Click to sort by this column') . '"  ' . $class . '>';
     $html .= $translator->translate($config->title);
     // Mark the current column
     if ($config->column == $config->sort) {
         if (strtolower($config->direction) === 'asc') {
             $html .= ' <span class="koowa_icon--sort_up koowa_icon--12"></span>';
         } else {
             $html .= ' <span class="koowa_icon--sort_down koowa_icon--12"></span>';
         }
     } else {
         $html .= ' <span class="koowa_icon--sort koowa_icon--12"></span>';
     }
     $html .= '</a>';
     return $html;
 }
 /**
  * @param HttpMethod $method
  * @return HttpRequest
  */
 private function spawnRequest(HttpMethod $method, $urlPostfix = '')
 {
     $url = HttpUrl::create()->parse(ONPHP_CURL_TEST_URL);
     $glue = $url->getQuery() ? '&' : '?';
     return HttpRequest::create()->setUrl($url->parse(ONPHP_CURL_TEST_URL . $glue . $urlPostfix))->setMethod($method);
 }
 /**
  * @return TestUser
  */
 private function spawnUser($options = array())
 {
     $options += array('id' => '77', 'credentials' => Credentials::create(), 'lastLogin' => Timestamp::create('2011-12-31'), 'registered' => Timestamp::create('2011-12-30'), 'strangeTime' => Time::create('01:23:45'), 'city' => null, 'firstOptional' => null, 'secondOptional' => null, 'url' => HttpUrl::create()->parse('https://www.github.com'), 'properties' => Hstore::make(array('a' => 'apple', 'b' => 'bananas')), 'ip' => IpAddress::create('127.0.0.1'));
     return $this->spawnObject(TestUser::create(), $options);
 }
Esempio n. 14
0
 function testHttpUrlFail()
 {
     $url = new HttpUrl(true);
     $this->assertEquals('', $url->getDomainName());
     $this->assertEquals('', $url->getDirectory());
 }
 public function toValue(ProtoDAO $dao = null, $array, $prefix = null)
 {
     $raw = $array[$prefix . $this->columnName];
     if ($this->type == 'binary') {
         return DBPool::getByDao($dao)->getDialect()->unquoteBinary($raw);
     }
     if ($this->className == 'HttpUrl') {
         return HttpUrl::create()->parse($raw);
     }
     if (!$this->identifier && $this->generic && $this->className) {
         return call_user_func(array($this->className, 'create'), $raw);
     } elseif (!$this->identifier && $this->className) {
         // BOVM: prevents segfault on >=php-5.2.5
         Assert::classExists($this->className);
         if (!is_subclass_of($this->className, 'Enumeration')) {
             $remoteDao = call_user_func(array($this->className, 'dao'));
             $joinPrefix = $remoteDao->getJoinPrefix($this->columnName, $prefix);
             $joined = $this->strategyId == FetchStrategy::JOIN || isset($array[$joinPrefix . $remoteDao->getIdName()]);
             if ($joined) {
                 return $remoteDao->makeObject($array, $joinPrefix);
             } else {
                 // will be fetched later
                 // by AbstractProtoClass::fetchEncapsulants
                 $object = new $this->className();
                 $object->setId($raw);
                 return $object;
             }
         } else {
             return new $this->className($raw);
         }
     }
     // veeeeery "special" handling, by tradition.
     // MySQL returns 0/1, others - t/f
     if ($this->type == 'boolean') {
         return (bool) strtr($raw, array('f' => null));
     }
     return $raw;
 }
Esempio n. 16
0
 public function fill($assertions = true)
 {
     $moscow = TestCity::create()->setName('Moscow');
     $piter = TestCity::create()->setName('Saint-Peterburg');
     $mysqler = TestUser::create()->setCity($moscow)->setCredentials(Credentials::create()->setNickname('mysqler')->setPassword(sha1('mysqler')))->setLastLogin(Timestamp::create(time()))->setRegistered(Timestamp::create(time())->modify('-1 day'));
     $postgreser = clone $mysqler;
     $postgreser->setCredentials(Credentials::create()->setNickName('postgreser')->setPassword(sha1('postgreser')))->setCity($piter)->setUrl(HttpUrl::create()->parse('http://postgresql.org/'));
     $piter = TestCity::dao()->add($piter);
     $moscow = TestCity::dao()->add($moscow);
     if ($assertions) {
         $this->assertEquals($piter->getId(), 1);
         $this->assertEquals($moscow->getId(), 2);
     }
     $postgreser = TestUser::dao()->add($postgreser);
     for ($i = 0; $i < 10; $i++) {
         $encapsulant = TestEncapsulant::dao()->add(TestEncapsulant::create()->setName($i));
         $encapsulant->getCities()->fetch()->setList(array($piter, $moscow))->save();
     }
     $mysqler = TestUser::dao()->add($mysqler);
     if ($assertions) {
         $this->assertEquals($postgreser->getId(), 1);
         $this->assertEquals($mysqler->getId(), 2);
     }
     if ($assertions) {
         // put them in cache now
         TestUser::dao()->dropIdentityMap();
         TestUser::dao()->getById(1);
         TestUser::dao()->getById(2);
         $this->getListByIdsTest();
         Cache::me()->clean();
         $this->assertTrue($postgreser == TestUser::dao()->getById(1));
         $this->assertTrue($mysqler == TestUser::dao()->getById(2));
     }
     $firstClone = clone $postgreser;
     $secondClone = clone $mysqler;
     $firstCount = TestUser::dao()->dropById($postgreser->getId());
     $secondCount = TestUser::dao()->dropByIds(array($mysqler->getId()));
     if ($assertions) {
         $this->assertEquals($firstCount, 1);
         $this->assertEquals($secondCount, 1);
         try {
             TestUser::dao()->getById(1);
             $this->fail();
         } catch (ObjectNotFoundException $e) {
             /* pass */
         }
         $result = Criteria::create(TestUser::dao())->add(Expression::eq(1, 2))->getResult();
         $this->assertEquals($result->getCount(), 0);
         $this->assertEquals($result->getList(), array());
     }
     TestUser::dao()->import($firstClone);
     TestUser::dao()->import($secondClone);
     if ($assertions) {
         // cache multi-get
         $this->getListByIdsTest();
         $this->getListByIdsTest();
     }
 }
 public function testAssemblingWithHostnameAndTransparentWithBaseUrl()
 {
     $base = 'http://www.example.com/~users/public/www/';
     $hostname = RouterHostnameRule::create(':subdomain.example.com')->setDefaults(array('subdomain' => 'www'));
     $transparent = RouterTransparentRule::create('/company/:id')->setRequirements(array('id' => '\\d+'));
     $chain = RouterChainRule::create()->chain($hostname)->chain($transparent);
     $this->router->setBaseUrl(HttpUrl::create()->parse($base));
     $this->router->addRoute('chain', $chain);
     $this->assertEquals('http://test.example.com/~users/public/www/company/123', $this->router->assembly(array('subdomain' => 'test', 'id' => 123), 'chain'));
 }
Esempio n. 18
0
 public function __construct($id)
 {
     parent::__construct($id);
 }
 protected function loadXRDS($url)
 {
     $response = $this->httpClient->send(HttpRequest::create()->setHeaderVar('Accept', self::HEADER_ACCEPT)->setMethod(HttpMethod::get())->setUrl(HttpUrl::create()->parse($url)));
     if ($response->getStatus()->getId() != 200) {
         throw new OpenIdException('can\'t fetch document');
     }
     $this->parseXRDS($response->getBody());
     return $this;
 }
Esempio n. 20
0
 /**
  * Set the view url
  *
  * Ensure the url is properly escaped
  *
  * @param HttpUrl $url   A HttpUrl object or a string
  * @return  ViewAbstract
  */
 public function setUrl(HttpUrl $url)
 {
     $url->setEscaped(true);
     return parent::setUrl($url);
 }
 /**
  * @test
  */
 public function privilegdPortsValidationDisabled()
 {
     $url = HttpUrl::create()->parse($this->urlWithPrivilegedPort);
     $this->assertTrue($url->isValid());
     $this->assertTrue($url->isPrivilegedPortUsed());
 }
 /**
  * check_authentication mode request
  **/
 private function checkAuthentication(array $parameters, $manager = null)
 {
     $credentials = new OpenIdCredentials(HttpUrl::create()->parse($parameters['openid.identity']), $this->httpClient);
     $request = HttpRequest::create()->setMethod(HttpMethod::post())->setUrl($credentials->getServer());
     if (isset($parameters['openid.invalidate_handle']) && $manager) {
         $request->setPostVar('openid.invalidate_handle', $parameters['openid.invalidate_handle']);
     }
     foreach (explode(',', $parameters['openid.signed']) as $key) {
         $key = 'openid.' . $key;
         $request->setPostVar($key, $parameters[$key]);
     }
     $request->setPostVar('openid.mode', 'check_authentication')->setPostVar('openid.assoc_handle', $parameters['openid.assoc_handle'])->setPostVar('openid.sig', $parameters['openid.sig'])->setPostVar('openid.signed', $parameters['openid.signed']);
     $response = $this->httpClient->send($request);
     if ($response->getStatus()->getId() != HttpStatus::CODE_200) {
         throw new OpenIdException('bad response code from server');
     }
     $result = $this->parseKeyValueFormat($response->getBody());
     if (!isset($result['is_valid']) || $result['is_valid'] !== 'true' && $result['is_valid'] !== 'false') {
         throw new OpenIdException('strange response given');
     }
     if ($result['is_valid'] === 'true') {
         if (isset($result['invalidate_handle']) && $manager) {
             $manager->purgeByHandle($result['invalidate_handle']);
         }
         return true;
     } elseif ($result['is_valid'] === 'false') {
         return false;
     }
     Assert::isUnreachable();
 }
 public function poorReference($url)
 {
     Assert::isNotNull($this->base, 'set base url first');
     $parsedUrl = HttpUrl::create()->parse($url);
     return $this->base->transform($parsedUrl);
 }
Esempio n. 24
0
<?php

/**
 * $Id$
 **/
require '../../../config.inc.php';
define('DEFAULT_CONTROLLER', 'main');
try {
    $request = HttpRequest::create()->setGet($_GET)->setPost($_POST)->setCookie($_COOKIE)->setServer($_SERVER)->setFiles($_FILES);
    $controllerName = DEFAULT_CONTROLLER;
    RouterRewrite::me()->setBaseUrl(HttpUrl::create()->parse(PATH_WEB))->addRoute('default', RouterTransparentRule::create(':area/*')->setDefaults(array('area' => DEFAULT_CONTROLLER)))->route($request);
    if ($request->hasGetVar('area') && ClassUtils::isClassName($_GET['area']) && defined('PATH_CONTROLLERS') && is_readable(PATH_CONTROLLERS . $request->getGetVar('area') . EXT_CLASS)) {
        $controllerName = $request->getGetVar('area');
    } elseif ($request->hasAttachedVar('area') && ClassUtils::isClassName($request->getAttachedVar('area')) && defined('PATH_CONTROLLERS') && is_readable(PATH_CONTROLLERS . $request->getAttachedVar('area') . EXT_CLASS)) {
        $controllerName = $request->getAttachedVar('area');
    }
    $controller = new $controllerName();
    $modelAndView = $controller->handleRequest($request);
    $view = $modelAndView->getView();
    $model = $modelAndView->getModel();
    $prefix = PATH_WEB . '?area=';
    if (!$view) {
        $view = $controllerName;
    } elseif (is_string($view) && $view == 'error') {
        $view = new RedirectView($prefix);
    } elseif ($view instanceof RedirectToView) {
        $view->setPrefix($prefix);
    }
    if (!$view instanceof View) {
        $viewName = $view;
        $view = PhpViewResolver::create(PATH_TEMPLATES, EXT_TPL)->resolveViewName($viewName);
 public function apply($value)
 {
     $url = HttpUrl::create()->parse($value)->ensureAbsolute()->normalize();
     return $url->toString();
 }
Esempio n. 26
0
    public function testCredentials()
    {
        $credential = OpenIdCredentials::create(HttpUrl::create()->parse('http://www.example.com/'), HttpClientStub::create(HttpResponseStub::create()->setStatus(new HttpStatus(HttpStatus::CODE_200))->setBody(<<<EOT
<html><head><link rel="openid.server"
                  href="http://www.myopenid.com/server" />
            <link rel="openid.delegate" href="http://example.myopenid.com/" />
</head></html>
EOT
)));
        $this->assertEquals($credential->getServer()->toString(), 'http://www.myopenid.com/server');
        $this->assertEquals($credential->getRealId()->toString(), 'http://example.myopenid.com/');
        // from openId creator blog
        $credential = OpenIdCredentials::create(HttpUrl::create()->parse('http://brad.livejournal.com/'), HttpClientStub::create(HttpResponseStub::create()->setStatus(new HttpStatus(HttpStatus::CODE_200))->setBody(<<<EOT
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="alternate" type="application/rss+xml" title="RSS" href="http://brad.livejournal.com/data/rss" />
<link rel="alternate" type="application/atom+xml" title="Atom" href="http://brad.livejournal.com/data/atom" />
<link rel="service.feed" type="application/atom+xml" title="AtomAPI-enabled feed" href="http://www.livejournal.com/interface/atomapi/brad/feed" />
<link rel="service.post" type="application/atom+xml" title="Create a new post" href="http://www.livejournal.com/interface/atomapi/brad/post" />
<link rel="openid.server" href="http://www.livejournal.com/openid/server.bml" />
<meta http-equiv="X-XRDS-Location" content="http://brad.livejournal.com/data/yadis" />
<script src='http://www.livejournal.com/js/core.js' type='text/javascript'></script>
<script src='http://www.livejournal.com/js/dom.js' type='text/javascript'></script>
<script src='http://www.livejournal.com/js/httpreq.js' type='text/javascript'></script>

<script type='text/javascript'>
    function controlstrip_init() {
        if (! \$('lj_controlstrip') ){
            HTTPReq.getJSON({
              url: "/brad/__rpc_controlstrip?user=brad",
              onData: function (data) {
                  var body = document.getElementsByTagName("body")[0];
                  var div = document.createElement("div");
                  div.innerHTML = data;
                      body.appendChild(div);
              },
              onError: function (msg) { }
            });
        }
    }
    DOM.addEventListener(window, "load", controlstrip_init);
</script>
    <link rel="meta" type="application/rdf+xml" title="FOAF" href="http://brad.livejournal.com/data/foaf" />
<meta name="foaf:maker" content="foaf:mbox_sha1sum '4caa1d6f6203d21705a00a7aca86203e82a9cf7a'" />
<link rel="group friends made" title="LiveJournal friends" href="http://brad.livejournal.com/friends" />
<meta name="ICBM" content="37.7788,-122.3974" />

        <script language="JavaScript" type="text/javascript">
            var Site;
            if (!Site)
                Site = {};

            var site_p = {"media_embed_enabled": 1,
"inbox_update_poll": 0,
"has_remote": 1,
"statprefix": "http://stat.livejournal.com",
"ctx_popup": 1,
"imgprefix": "http://stat.livejournal.com/img",
"esn_async": 1,
"currentJournal": "brad",
"siteroot": "http://www.livejournal.com",
"currentJournalBase": "http://brad.livejournal.com"};
            var site_k = ["media_embed_enabled", "inbox_update_poll", "has_remote", "statprefix", "ctx_popup", "imgprefix", "esn_async", "currentJournal", "siteroot", "currentJournalBase"];
            for (var i = 0; i < site_k.length; i++) {
                Site[site_k[i]] = site_p[site_k[i]];
            }
       </script>
    <script type="text/javascript" src="http://www.livejournal.com/js/??core.js,dom.js,httpreq.js,livejournal.js,common/AdEngine.js,esn.js,ippu.js,lj_ippu.js,hourglass.js,contextualhover.js,md5.js,login.js,livejournal-local.js?v=1186096206"></script>
<link rel="stylesheet" type="text/css" href="http://stat.livejournal.com/??lj_base.css,esn.css,contextualhover.css,controlstrip.css,controlstrip-dark.css,controlstrip-dark-local.css,controlstrip-local.css?v=1186000719" />
<style type="text/css">
/* Cleaned CSS: */
body, td {
font-family: "Verdana", sans-serif;
font-size: 10pt;
}
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.shadowed {
font-size: 8pt;
background: #aaaaaa;
}
.meta {
font-size: 8pt;
}
.index {
font-size: 8pt;
}
.caption, .index {
color: #ffffff;
}
.comments {
font-size: 8pt;
}
.quickreply {
margin-top: 1em;
width:100%;
}
.box, .entrybox {
border:  hidden #000000;
}

</style>
<title>brad&#39;s life</title>
</head>
<body bgcolor="#2d4f89" text="#000000" link="#0000ff" vlink="#0000ff" alink="#00ffff">
<!-- body omitted -->
</body>
</html>
EOT
)));
        $this->assertEquals($credential->getServer()->toString(), 'http://www.livejournal.com/openid/server.bml');
        try {
            $credential = OpenIdCredentials::create(HttpUrl::create()->parse('http://www.example.com/'), HttpClientStub::create(HttpResponseStub::create()->setStatus(new HttpStatus(HttpStatus::CODE_404))));
            $this->fail();
        } catch (OpenIdException $e) {
            /* pass */
        } catch (Exception $e) {
            $this->fail();
        }
    }