1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112: 113: 114: 115: 116: 117: 118: 119: 120: 121: 122: 123: 124: 125: 126: 127: 128: 129: 130: 131: 132: 133: 134: 135: 136: 137: 138: 139: 140: 141: 142: 143: 144: 145: 146: 147: 148: 149: 150: 151: 152: 153: 154: 155: 156: 157: 158: 159: 160: 161: 162: 163: 164: 165: 166: 167: 168: 169: 170: 171: 172: 173: 174: 175: 176: 177: 178: 179: 180: 181: 182: 183: 184: 185: 186: 187: 188: 189: 190: 191: 192: 193: 194: 195: 196: 197: 198: 199: 200: 201: 202: 203: 204: 205: 206: 207: 208: 209: 210: 211: 212: 213: 214: 215: 216: 217: 218: 219: 220: 221: 222: 223: 224: 225: 226: 227: 228: 229: 230: 231: 232: 233: 234: 235: 236: 237: 238: 239: 240: 241: 242: 243: 244: 245: 246: 247: 248: 249: 250: 251: 252: 253: 254: 255: 256: 257: 258: 259: 260: 261: 262: 263: 264: 265: 266: 267: 268: 269: 270: 271: 272: 273: 274: 275: 276: 277: 278: 279: 280: 281: 282: 283: 284: 285: 286: 287: 288: 289: 290: 291: 292: 293: 294: 295: 296: 297: 298: 299: 300: 301: 302: 303: 304: 305: 306: 307: 308: 309: 310: 311: 312: 313: 314: 315: 316: 317: 318: 319: 320: 321: 322: 323: 324: 325: 326: 327: 328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338: 339: 340: 341: 342: 343: 344: 345: 346: 347: 348: 349: 350: 351: 352: 353: 354: 355: 356: 357: 358: 359: 360: 361: 362: 363: 364: 365: 366: 367: 368: 369: 370: 371: 372: 373: 374: 375: 376: 377: 378: 379: 380: 381: 382: 383: 384: 385: 386: 387: 388: 389: 390: 391: 392: 393: 394: 395: 396: 397: 398: 399: 400: 401: 402: 403: 404: 405: 406: 407: 408: 409: 410: 411: 412: 413: 414: 415: 416: 417: 418: 419: 420: 421: 422: 423: 424: 425: 426: 427: 428: 429: 430: 431: 432: 433: 434: 435: 436: 437: 438: 439: 440: 441: 442: 443: 444: 445: 446: 447: 448: 449: 450: 451: 452: 453: 454: 455: 456: 457: 458: 459: 460: 461: 462: 463: 464: 465: 466: 467: 468: 469: 470: 471: 472: 473: 474: 475: 476: 477: 478: 479: 480: 481: 482: 483: 484: 485: 486: 487: 488: 489: 490: 491: 492: 493: 494: 495: 496: 497: 498: 499: 500: 501: 502: 503: 504: 505: 506: 507: 508: 509: 510: 511: 512: 513: 514: 515: 516: 517: 518: 519: 520: 521: 522: 523: 524: 525: 526: 527: 528: 529: 530: 531: 532: 533: 534: 535: 536: 537: 538: 539: 540: 541: 542: 543: 544: 545: 546: 547: 548: 549: 550: 551: 552: 553: 554: 555: 556: 557: 558: 559: 560: 561: 562: 563: 564: 565: 566: 567: 568: 569: 570: 571: 572: 573: 574: 575: 576: 577: 578: 579: 580: 581: 582: 583: 584: 585: 586: 587: 588: 589: 590: 591: 592: 593: 594: 595: 596: 597: 598: 599: 600: 601: 602: 603: 604: 605: 606: 607: 608: 609: 610: 611: 612: 613: 614: 615: 616: 617: 618: 619: 620: 621: 622: 623: 624: 625: 626: 627: 628: 629: 630: 631: 632: 633: 634: 635: 636: 637: 638: 639: 640: 641: 642: 643: 644: 645: 646: 647: 648: 649: 650: 651: 652: 653: 654: 655: 656: 657: 658: 659: 660: 661: 662: 663: 664: 665: 666: 667: 668: 669: 670: 671: 672: 673: 674: 675: 676: 677: 678: 679: 680: 681: 682: 683: 684: 685: 686: 687: 688: 689: 690: 691: 692: 693: 694: 695: 696: 697: 698: 699: 700: 701: 702: 703: 704: 705: 706: 707: 708: 709: 710: 711: 712: 713: 714: 715: 716: 717: 718: 719: 720: 721: 722: 723: 724: 725: 726: 727: 728: 729: 730: 731: 732: 733: 734: 735: 736: 737: 738: 739: 740: 741: 742: 743: 744: 745: 746: 747: 748: 749: 750: 751: 752: 753: 754: 755: 756: 757: 758: 759: 760: 761: 762: 763: 764: 765: 766: 767: 768: 769: 770: 771: 772: 773: 774: 775: 776: 777: 778: 779: 780: 781: 782: 783: 784: 785: 786: 787: 788: 789: 790: 791: 792: 793: 794: 795: 796: 797: 798: 799: 800: 801: 802: 803: 804: 805: 806: 807: 808: 809: 810: 811: 812: 813: 814: 815: 816: 817: 818: 819: 820: 821: 822: 823: 824: 825: 826: 827: 828: 829: 830: 831: 832: 833: 834: 835: 836: 837: 838: 839: 840: 841: 842: 843: 844: 845: 846: 847: 848: 849: 850: 851: 852: 853: 854: 855: 856: 857: 858: 859: 860: 861: 862: 863: 864: 865: 866: 867: 868: 869: 870: 871: 872: 873: 874: 875: 876: 877: 878: 879: 880: 881: 882: 883: 884: 885: 886: 887: 888: 889: 890: 891: 892: 893: 894: 895: 896: 897: 898: 899: 900: 901: 902: 903: 904: 905: 906: 907: 908: 909: 910: 911: 912: 913: 914: 915: 916: 917: 918: 919: 920: 921: 922: 923: 924: 925: 926: 927: 928: 929: 930: 931: 932: 933: 934: 935: 936: 937: 938: 939: 940: 941: 942: 943: 944: 945: 946: 947: 948: 949: 950: 951: 952: 953: 954: 955: 956: 957: 958: 959: 960: 961: 962: 963: 964: 965: 966: 967: 968: 969: 970: 971: 972: 973: 974: 975: 976: 977: 978: 979:
<?php
namespace Nethgui;
class Framework
{
private $namespaceMap;
private $urlParts;
private $dc;
public function __construct()
{
if (basename(__DIR__) !== __NAMESPACE__) {
throw new \LogicException(sprintf('%s: `%s` is an invalid framework filesystem directory! Must be `%s`.', __CLASS__, basename(__DIR__), __NAMESPACE__), 1322213425);
}
$this->registerNamespace(__DIR__);
$this->urlParts = $this->guessUrlParts();
$nsMap = &$this->namespaceMap;
$urlParts = &$this->urlParts;
$dc = new \Pimple\Container();
$dc['main.default_module'] = '';
$dc['login.forced_redirect'] = '';
$dc['decorator.xhtml.template'] = 'Nethgui\Template\Main';
$dc['user.authenticate'] = $dc->protect(function($user, $password, &$credentials) use ($dc) {
$dc['Log']->warning(sprintf("%s: user.authenticate is not set! Could not authenticate user `%s`.", __CLASS__, $user));
return FALSE;
});
$dc['l10n.available_languages'] = function($c) {
$langs = array();
foreach($c['namespaceMap'] as $ns => $prefix) {
$path = "${prefix}/${ns}/Language/*";
$langs = array_merge($langs, array_map('basename', $c['PhpWrapper']->glob($path, GLOB_ONLYDIR)));
}
return array_unique($langs);
};
$dc['l10n.catalog_resolver'] = $dc->protect(function($lang, $catalog) use ($dc) {
$lang = str_replace('-', '_', $lang);
static $globs;
foreach($dc['namespaceMap'] as $ns => $prefix) {
$path = "${prefix}/${ns}/Language/${lang}/${catalog}.php";
if($dc['PhpWrapper']->file_exists($path)) {
return $path;
}
$shortLang = substr($lang, 0, 2);
if( ! isset($globs["${prefix}:${ns}:${shortLang}"])) {
$globs["${prefix}:${ns}:${shortLang}"] = array_filter(
array_map(
'basename',
$dc['PhpWrapper']->glob("${prefix}/${ns}/Language/${shortLang}_*", GLOB_ONLYDIR)
),
function($e) use ($lang) { return $e !== $lang; }
);
array_unshift($globs["${prefix}:${ns}:${shortLang}"], $shortLang);
}
foreach($globs["${prefix}:${ns}:${shortLang}"] as $altLang) {
$path = "${prefix}/${ns}/Language/${altLang}/${catalog}.php";
if($dc['PhpWrapper']->file_exists($path)) {
return $path;
}
}
}
if($lang !== 'en_US') {
return call_user_func($dc['l10n.catalog_resolver'], 'en_US', $catalog);
}
return '';
});
$dc['Log'] = function($c) {
return new \Nethgui\Log\Syslog($c['log.level']);
};
$dc['PhpWrapper'] = function($c) {
$p = new \Nethgui\Utility\PhpWrapper();
$p->setLog($c['Log']);
return $p;
};
$dc['namespaceMap'] = function ($c) use (&$nsMap) {
return $nsMap;
};
$dc['Session'] = function ($c) {
$s = new \Nethgui\Utility\Session();
$s->setLog($c['Log']);
$s->setSessionSetupRetriever($c['Session.Setup']);
return $s;
};
$dc['Pdp'] = function ($c) {
$pdp = new \Nethgui\Authorization\JsonPolicyDecisionPoint($c['FilenameResolver']);
$pdp->setLog($c['Log']);
foreach ($c['namespaceMap'] as $nsName => $nsPath) {
$pdp->loadPolicy($nsName . '\Authorization\*.json');
}
return $pdp;
};
$dc['User'] = function ($dc) {
$user = $dc['objectInjector'](new \Nethgui\Authorization\User($dc['Session'], $dc['Log']));
$user->setAuthenticationValidator($dc['user.authenticate']);
return $user;
};
$objectInjector = function($o) use ($dc) {
if ($o instanceof \Nethgui\Component\DependencyInjectorAggregate) {
$o->setDependencyInjector($dc['objectInjector']);
}
if ($o instanceof \Nethgui\Component\DependencyConsumer) {
foreach ($o->getDependencySetters() as $key => $setter) {
if ( ! isset($dc[$key])) {
continue;
}
call_user_func($setter, $dc[$key]);
}
}
if ($o instanceof \Nethgui\Log\LogConsumerInterface) {
$o->setLog($dc['Log']);
}
if ($o instanceof \Nethgui\Utility\SessionConsumerInterface) {
$o->setSession($dc['Session']);
}
if ($o instanceof Authorization\PolicyEnforcementPointInterface) {
$o->setPolicyDecisionPoint($dc['Pdp']);
}
if ($o instanceof \Nethgui\System\PlatformConsumerInterface) {
$o->setPlatform($dc['Platform']);
}
return $o;
};
$dc['objectInjector'] = $dc->protect($objectInjector);
$dc['StaticFiles'] = function ($c) {
return $c['objectInjector'](new \Nethgui\Model\StaticFiles(), $c);
};
$dc['UserNotifications'] = function ($c) {
return $c['objectInjector'](new \Nethgui\Model\UserNotifications(), $c);
};
$dc['ValidationErrors'] = function ($c) {
return $c['objectInjector'](new \Nethgui\Model\ValidationErrors(), $c);
};
$dc['SystemTasks'] = function ($c) {
return $c['objectInjector'](new \Nethgui\Model\SystemTasks($c['Log']), $c);
};
$dc['FilenameResolver'] = $this->getFileNameResolver();
$dc['ModuleSet'] = function ($c) {
$moduleSet = new \Nethgui\Module\ModuleLoader($c['objectInjector']);
foreach ($c['namespaceMap'] as $nsName => $nsRoot) {
if ($nsName === 'Nethgui') {
$nsRoot = FALSE;
}
$moduleSet->setNamespace($nsName . '\\Module', $nsRoot);
}
return $c['objectInjector'](new \Nethgui\Authorization\AuthorizedModuleSet($moduleSet, $c['User']), $c);
};
$dc['Platform'] = function ($c) {
return $c['objectInjector'](new \Nethgui\System\NethPlatform($c['User'], $c['SystemTasks']), $c);
};
$dc['Translator'] = function ($c) {
return $c['objectInjector'](new \Nethgui\View\Translator($c['OriginalRequest']->getLocale(), $c['l10n.catalog_resolver']), $c);
};
$dc['HttpResponse'] = function ($c) {
return new \Nethgui\Utility\HttpResponse();
};
$dc['Main.factory'] = $dc->factory(function ($c) {
return $c['objectInjector'](new \Nethgui\Module\Main($c['ModuleSet'], $c['main.default_module']), $c);
});
$dc['View'] = function ($c) use (&$urlParts) {
$rootView = $c['objectInjector'](new \Nethgui\View\View($c['OriginalRequest']->getFormat(), $c['Main'], $c['Translator'], $urlParts), $c);
$rootView->setTemplate(FALSE);
$rootView->commands = $c['objectInjector'](new \Nethgui\View\LegacyCommandBag($rootView, $c), $c);
return $rootView;
};
$dc['decorator.xhtml.params'] = function ($dc) {
return new \ArrayObject(array(
'disableHeader' => FALSE,
'disableMenu' => FALSE,
'disableFooter' => TRUE
));
};
$dc['main.xhtml.template'] = $dc->protect(function (\Nethgui\Renderer\Xhtml $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use ($dc, &$urlParts) {
$decoratorView = $dc['objectInjector'](new \Nethgui\View\View($dc['OriginalRequest']->getFormat(), $dc['Main'], $dc['Translator'], $urlParts), $dc);
$decoratorView->setTemplate($dc['decorator.xhtml.template']);
$decoratorView->copyFrom($renderer);
$decoratorView->copyFrom($dc['decorator.xhtml.params']);
$decoratorView['lang'] = $dc['Translator']->getLanguageCode();
$decoratorView['username'] = $dc['User']->asAuthorizationString();
$decoratorView['currentModuleOutput'] = 'currentModule';
$decoratorView['helpAreaOutput'] = (String) $renderer->panel($renderer::STATE_UNOBTRUSIVE)
->setAttribute('class', 'HelpArea')
->insert(
$renderer->panel()
->setAttribute('class', 'wrap')
->insert(
$renderer->buttonList($renderer::BUTTONSET)->insert($renderer->button('Hide', $renderer::BUTTON_CANCEL))
)
);
$currentModule = $renderer['moduleView']->getModule();
if ($currentModule instanceof \Nethgui\Module\ModuleCompositeInterface) {
$decoratorView['currentModuleOutput'] = (String) $renderer->inset('moduleView');
} else {
$decoratorView['currentModuleOutput'] = (String) $renderer->panel()->setAttribute('class', 'Controller')
->insert($renderer->inset('moduleView', $renderer::INSET_FORM | $renderer::INSET_WRAP)
->setAttribute('class', 'Action')
->setAttribute('receiver', $currentModule->getIdentifier())
);
}
$decoratorView['trackerOutput'] = (String) $renderer->inset('Tracker', $renderer::STATE_UNOBTRUSIVE);
$decoratorView['menuOutput'] = (String) $renderer->inset('Menu');
$decoratorView['notificationOutput'] = (String) $renderer->inset('Notification');
$decoratorView['moduleTitle'] = $dc['Translator']->translate($currentModule, $currentModule->getAttributesProvider()->getTitle());
$security = $dc['Session']->retrieve('SECURITY');
$decoratorView['csrfToken'] = $security['csrfToken'];
return $renderer->spawnRenderer($decoratorView)->render();
});
$dc['main.css.template'] = $dc->protect(function(\Nethgui\Renderer\TemplateRenderer $renderer, $T, \Nethgui\Utility\HttpResponse $httpResponse) use ($dc) {
$content = '';
foreach ($renderer as $value) {
if ($value instanceof \Nethgui\View\ViewInterface) {
$content .= $renderer->spawnRenderer($value)->render();
} else {
$content .= (String) $value;
}
}
return $content;
});
$dc['main.js.template'] = $dc['main.css.template'];
$dc['main.txt.template'] = $dc['main.css.template'];
$dc['Renderer'] = function ($dc) {
$filenameResolver = $dc['FilenameResolver'];
$targetFormat = $dc['OriginalRequest']->getFormat();
if (isset($dc[sprintf('main.%s.template', $targetFormat)])) {
$dc['View']->setTemplate($dc[sprintf('main.%s.template', $targetFormat)]);
}
if ($targetFormat === 'json') {
$renderer = new \Nethgui\Renderer\Json($dc['View']);
} elseif ($targetFormat === 'xhtml') {
$renderer = new \Nethgui\Renderer\Xhtml($dc['View'], $filenameResolver, 0);
} else if ($targetFormat === 'js') {
$renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'application/javascript', 'UTF-8');
} elseif ($targetFormat === 'css') {
$renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/css', 'UTF-8');
} else {
$renderer = new \Nethgui\Renderer\TemplateRenderer($dc['View'], $filenameResolver, 'text/plain', 'UTF-8');
}
$dc['HttpResponse']->addHeader(sprintf('Content-Type: %s', $renderer->getContentType()) . (
$renderer->getCharset() ? sprintf('; charset=%s', $renderer->getCharset()) : '')
);
return $dc['objectInjector']($renderer, $dc);
};
$this->dc = $dc;
}
public function registerNamespace($namespacePath)
{
$nsRoot = dirname($namespacePath);
$nsName = basename($namespacePath);
$this->namespaceMap[$nsName] = $nsRoot;
return $this;
}
private function guessUrlParts()
{
$urlParts = array();
$siteUrl = empty($_SERVER['HTTPS']) ? 'http://' : 'https://';
$siteUrl .= isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost';
if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] != '80') {
$siteUrl .= ':' . $_SERVER['SERVER_PORT'];
}
$urlParts[] = $siteUrl;
$basePath = dirname($_SERVER['SCRIPT_NAME']);
$urlParts[] = ($basePath === '/') ? '/' : ($basePath . '/');
if (isset($_SERVER['PATH_INFO'])) {
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$requestController = substr($requestPath, 0, strlen($requestPath) - strlen($_SERVER['PATH_INFO']));
if ($requestController === $_SERVER['SCRIPT_NAME']) {
$urlParts[] = basename($_SERVER['SCRIPT_NAME']) . '/';
}
} else {
$urlParts[] = basename($_SERVER['SCRIPT_NAME']) . '/';
}
return $urlParts;
}
public function setSiteUrl($siteUrl)
{
$this->urlParts[0] = $siteUrl;
return $this;
}
public function setBasePath($basePath)
{
$this->urlParts[1] = $basePath;
return $this;
}
public function setDefaultModule($moduleIdentifier)
{
$this->dc['main.default_module'] = $moduleIdentifier;
return $this;
}
public function setForcedLoginModule($moduleIdentifier)
{
$this->dc['login.forced_redirect'] = $moduleIdentifier;
return $this;
}
public function setSessionSetupProcedure($f)
{
$dc = $this->dc;
$this->dc['Session.Setup'] = $this->dc->protect(function () use ($dc, $f) {
return call_user_func($f, $dc);
});
return $this;
}
public function setAuthenticationValidator(\Closure $closure)
{
$this->dc['user.authenticate'] = $closure;
return $this;
}
public function setDecoratorTemplate($template)
{
$this->dc['decorator.xhtml.template'] = $template;
return $this;
}
public function setLogLevel($level)
{
$this->dc['log.level'] = $level;
return $this;
}
public function absoluteScriptPath($symbol)
{
$symbol = str_replace('\\', '/', $symbol);
$nsKey = array_head(explode('/', $symbol));
if ( ! isset($this->dc['namespaceMap'][$nsKey])) {
return FALSE;
}
$absolutePath = $this->dc['namespaceMap'][$nsKey] . '/' . $symbol;
if (pathinfo($symbol, PATHINFO_EXTENSION) === '') {
$absolutePath .= '.php';
}
return $absolutePath;
}
private function getFileNameResolver()
{
return array($this, 'absoluteScriptPath');
}
public function dispatch(\Nethgui\Controller\RequestInterface $request, &$output = NULL)
{
$log = $this->dc['Log'];
$this->dc['OriginalRequest'] = $request;
if ($request instanceof \Nethgui\Utility\SessionConsumerInterface) {
$request->setSession($this->dc['Session']);
}
try {
$response = $this->handle($request);
} catch (\Nethgui\Exception\HttpException $ex) {
throw $ex;
} catch (\Nethgui\Exception\AuthorizationException $ex) {
if ($request->getExtension() === 'xhtml' && ! $request->isMutation() && ! $request->getUser()->isAuthenticated()) {
$response = $this->handle($this->createLoginRequest($request));
} else {
$log->error(sprintf('%s: [%d] %s', __CLASS__, $ex->getCode(), $ex->getMessage()));
throw new \Nethgui\Exception\HttpException('Forbidden', 403, 1327681977, $ex);
}
} catch (\Exception $ex) {
$log->exception($ex, NETHGUI_DEBUG);
throw new \Nethgui\Exception\HttpException('Internal server error', 500, 1366796122, $ex);
}
$response->send();
}
private function createLoginRequest(\Nethgui\Controller\Request $originalRequest)
{
$m = $originalRequest->toArray();
unset($m[\Nethgui\array_head($originalRequest->getPath())]);
$r = new \Nethgui\Controller\Request(array_replace_recursive(array('Login' => array('path' => '/' . implode('/', $originalRequest->getPath()))), $m));
$r->setAttribute('locale', $originalRequest->getLocale());
$r->setAttribute('userClosure', $originalRequest->getAttribute('userClosure'));
return $r;
}
private function assertSecurity(\Nethgui\Controller\RequestInterface $request, \Nethgui\Utility\HttpResponse $response)
{
$log = $this->dc['Log'];
$session = $this->dc['Session'];
$security = $session->retrieve('SECURITY');
if(isset($security['reverseProxy']) && $security['reverseProxy'] !== $request->getAttribute('reverseProxy')) {
$log->error(sprintf("%s: Same origin assertion failed. The request %s be proxied.", __CLASS__, $security['reverseProxy'] === TRUE ? 'must' : 'must not'));
throw new \Nethgui\Exception\HttpException('Forbidden', 403, 1504084156, new \RuntimeException("Same origin assertion failed", 1504084157));
}
if( ! $request->getAttribute('sourceOrigin') && ! $request->isMutation() && $_SERVER['QUERY_STRING']) {
$module = implode('/', $request->getPath());
$response
->addHeader(sprintf('Location: %s', $this->dc['View']->getModuleUrl($module)))
->addHeader('Content-Type: text/plain; charset=UTF-8')
->setContent("Redirecting to $module\n")
;
$log->warning(sprintf("%s: The query string was stripped from request URI '%s'", __CLASS__, $_SERVER['REQUEST_URI']));
return TRUE;
}
if($request->getUser()->isAuthenticated()
&& $request->isMutation()
&& ( ! $request->getAttribute('sourceOrigin')
|| $request->getAttribute('sourceOrigin') !== $request->getAttribute('targetOrigin'))) {
$log->error(sprintf("%s: Same origin assertion failed. Source '%s' does not match target '%s'", __CLASS__, $request->getAttribute('sourceOrigin'), $request->getAttribute('targetOrigin')));
throw new \Nethgui\Exception\HttpException('Forbidden', 403, 1504013793, new \RuntimeException("Same origin assertion failed", 1504014085));
}
if($request->getUser()->isAuthenticated() && $request->isMutation() && isset($security['csrfToken']) && $security['csrfToken'] !== $request->getParameter('csrfToken')) {
$log->error(sprintf("%s: CSRF token verification failed!", __CLASS__, $request->getAttribute('sourceOrigin'), $request->getAttribute('targetOrigin')));
throw new \Nethgui\Exception\HttpException('Bad request', 400, 1504102184, new \RuntimeException("CSRF token verification failed", 1504102187));
}
if($request->getUser()->isAuthenticated() && ! $request->isMutation() && ! $request->getAttribute('isXhrRequest') && $request->getAttribute('format') === 'xhtml' && $session instanceof \Nethgui\Utility\Session) {
$session->rotateCsrfToken();
$session->checkHandoff();
}
}
public function handle(\Nethgui\Controller\RequestInterface $request)
{
$dc = $this->dc;
$dc['Main'] = $dc['Main.factory'];
$mainModule = $dc['Main'];
$renderer = $dc['Renderer'];
$response = $dc['HttpResponse'];
if($this->assertSecurity($request, $response)) {
return $response;
}
if ( ! $mainModule->isInitialized()) {
$mainModule->initialize();
}
$mainModule->bind($request);
$mainModule->validate($dc['ValidationErrors']);
if ($dc['ValidationErrors']->hasValidationErrors()) {
$request->setAttribute('isValidated', FALSE);
$response->setStatus(400, 'Request validation error');
$nextPath = FALSE;
} else {
$request->setAttribute('isValidated', TRUE);
$mainModule->process();
$dc['Platform']->runEvents('post-process');
$nextPath = $mainModule->nextPath();
}
$postResponseTask = function () use ($dc, $request) {
if ($request->isValidated()) {
if ($dc['Session']->isStarted()) {
$dc['Session']->unlock();
}
$dc['Platform']->runEvents('post-response');
}
};
$mainModule->prepareView($dc['View']);
if ($nextPath !== FALSE) {
NETHGUI_DEBUG && $dc['Log']->notice('nextPath: ' . $nextPath);
$dc['View']->getCommandList('/Main')->sendQuery($dc['View']->getModuleUrl($nextPath));
}
$response->setContent($renderer->render());
$response->on('post-response', $postResponseTask);
return $response;
}
public function createRequest($type = NULL)
{
return $this->createRequestModApache();
}
private function getClientLocaleDefault()
{
$acceptLanguageHeader = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : 'en-US';
$localeDefault = \extension_loaded('intl') ? \locale_accept_from_http($acceptLanguageHeader) : 'en-US';
if( ! in_array($localeDefault, $this->dc['l10n.available_languages'])) {
$localeDefault = 'en-US';
}
return str_replace('_', '-', $localeDefault);
}
private function createRequestModApache()
{
if (ini_get("magic_quotes_gpc")) {
throw new \LogicException("magic_quotes_gpc directive must be disabled!", 1377176328);
}
$isMutation = FALSE;
$postData = array();
$getData = $_GET;
$pathInfo = array();
$locale = '';
$localeDefault = $this->getClientLocaleDefault();
if (isset($_SERVER['PATH_INFO']) && $_SERVER['PATH_INFO'] != '/') {
$pathInfo = array_rest(explode('/', $_SERVER['PATH_INFO']));
$pathHead = array_head($pathInfo);
if ( ! in_array(str_replace('-', '_', $pathHead), $this->dc['l10n.available_languages'])) {
throw new Exception\HttpException('Language not found', 404, 1377519247);
}
$locale = $pathHead;
$pathInfo = array_rest($pathInfo);
foreach ($pathInfo as $pathPart) {
if ($pathPart === '.' || $pathPart === '..' || $pathPart === '') {
throw new Exception\HttpException('Bad Request', 400, 1322217901);
}
}
}
$format = $this->extractTargetFormat($pathInfo);
$pathInfoMod = array();
$cur = &$pathInfoMod;
foreach ($pathInfo as $pathPart) {
$cur[$pathPart] = array();
$cur = &$cur[$pathPart];
}
$cur = array_merge(array_filter($_GET, 'is_string'), $cur);
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
$isMutation = TRUE;
if (isset($_SERVER['CONTENT_TYPE']) && $_SERVER['CONTENT_TYPE'] == 'application/json; charset=UTF-8') {
$postData = json_decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
if (is_null($postData)) {
throw new \Nethgui\Exception\HttpException('Bad Request', 400, 1322148404);
}
} else {
$postData = $_POST;
}
}
$targetOrigin = \Nethgui\array_head(explode(':', isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : $_SERVER['HTTP_HOST']));
$sourceOrigin = parse_url(isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : FALSE), PHP_URL_HOST);
$dc = $this->dc;
$R = array_replace_recursive($pathInfoMod, $getData, $postData);
$request = new \Nethgui\Controller\Request($R);
$request->setLog($this->dc['Log'])
->setAttribute('isMutation', $isMutation)
->setAttribute('isXhrRequest', !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
->setAttribute('format', $format)
->setAttribute('locale', $locale)
->setAttribute('localeDefault', $localeDefault)
->setAttribute('userClosure', function () use ($dc) {
return $dc['User'];
})
->setAttribute('sourceOrigin', $sourceOrigin)
->setAttribute('targetOrigin', $targetOrigin)
->setAttribute('reverseProxy', isset($_SERVER['HTTP_X_FORWARDED_HOST']))
;
$this->urlParts[] = $request->getLocale() . '/';
return $request;
}
private function extractTargetFormat(&$pathInfo)
{
$lastPart = array_pop($pathInfo);
$ext = '';
if ( ! is_string($lastPart)) {
return '';
}
$dotPos = strrpos($lastPart, '.');
if ($dotPos !== FALSE) {
$ext = substr($lastPart, $dotPos + 1);
if (in_array($ext, array('js', 'css', 'xhtml', 'json', 'txt'))) {
$lastPart = substr($lastPart, 0, $dotPos);
} else {
$ext = 'xhtml';
}
} else {
$ext = 'xhtml';
}
$pathInfo[] = $lastPart;
if (preg_match('/[a-z][a-zA-Z]*/', $ext) === 0) {
throw new \Nethgui\Exception\HttpException('Bad Request', 400, 1324457459);
}
return $ext;
}
public function printHttpException(\Nethgui\Exception\HttpException $ex, $backtrace = TRUE)
{
header(sprintf('HTTP/1.1 %s %s', $ex->getHttpStatusCode(), $ex->getMessage()));
header('Content-Type: text/plain; charset=UTF-8');
$code = $ex->getCode();
$prev = $ex->getPrevious();
if ($prev instanceof \Exception) {
$code .= '+' . $prev->getCode();
}
echo sprintf("Nethgui:\n\n %d - %s\n\n %s\n", $ex->getHttpStatusCode(), $ex->getMessage(), $code);
if ($backtrace) {
if ($prev instanceof \Exception) {
echo sprintf("\n\n%s [%s]:\n\n %s \n\n", get_class($prev), $prev->getCode(), $prev->getMessage());
echo $prev->getTraceAsString() . "\n\n";;
}
echo $ex->getTraceAsString() . "\n";;
}
}
}
if ( ! defined('NETHGUI_ENABLE_TARGET_HASH')) {
define('NETHGUI_ENABLE_TARGET_HASH', TRUE);
}
if ( ! defined('NETHGUI_ENABLE_INCLUDE_WIDGET')) {
define('NETHGUI_ENABLE_INCLUDE_WIDGET', FALSE);
}
if ( ! defined('NETHGUI_ENABLE_HTTP_CACHE_HEADERS')) {
define('NETHGUI_ENABLE_HTTP_CACHE_HEADERS', TRUE);
}
if ( ! defined('NETHGUI_DEBUG')) {
define('NETHGUI_DEBUG', FALSE);
}
function array_head($arr)
{
return reset($arr);
}
function array_end($arr)
{
return end($arr);
}
function array_rest($arr)
{
array_shift($arr);
return $arr;
}