public function testDefaultManagers() { $config = new Config\ResourceManager($this->loader); $config->compat(); $bolt = $this->getApp(); $this->assertInstanceOf('League\\Flysystem\\Filesystem', $bolt['filesystem']->getManager()); $this->assertInstanceOf('League\\Flysystem\\Filesystem', $bolt['filesystem']->getManager('config')); }
/** * @param string $locale * @param string $fileContent * @param ResourceManager $resources */ protected function initializeFakeTranslationFiles($locale, $fileContent, ResourceManager $resources) { $fakeAppRoot = $resources->getPath('cache'); $fakeTranslationDir = "{$fakeAppRoot}/app/resources/translations/{$locale}"; (new Filesystem())->mkdir($fakeTranslationDir); file_put_contents("{$fakeTranslationDir}/messages.{$locale}.yml", $fileContent); $resources->setPath('root', $fakeAppRoot); }
public function testDefaultManagers() { $config = new Config\ResourceManager(new \Pimple(['rootpath' => TEST_ROOT, 'pathmanager' => new PlatformFileSystemPathFactory()])); $config->compat(); $bolt = $this->getApp(); $this->assertInstanceOf('Bolt\\Filesystem\\Filesystem', $bolt['filesystem']->getFilesystem('root')); $this->assertInstanceOf('Bolt\\Filesystem\\Filesystem', $bolt['filesystem']->getFilesystem('config')); }
public function setUp() { $this->_filesystem = PHPUnit_Extension_FunctionMocker::start($this, 'Symfony\\Component\\Filesystem')->mockFunction('file_exists')->mockFunction('is_dir')->mockFunction('is_readable')->mockFunction('is_writable')->mockFunction('rmdir')->mockFunction('touch')->mockFunction('unlink')->getMock(); $this->_validation = PHPUnit_Extension_FunctionMocker::start($this, 'Bolt\\Configuration\\Validation')->mockFunction('extension_loaded')->mockFunction('file_exists')->mockFunction('get_magic_quotes_gpc')->mockFunction('ini_get')->mockFunction('is_dir')->mockFunction('is_readable')->mockFunction('is_writable')->mockFunction('rmdir')->mockFunction('touch')->mockFunction('unlink')->getMock(); $this->extensionController = $this->prophesize(Controller\Exception::class); $this->config = $this->prophesize(Config::class); $this->resourceManager = $this->prophesize(ResourceManager::class); $this->validator = new Validator($this->extensionController->reveal(), $this->config->reveal(), $this->resourceManager->reveal()); }
/** * {@inheritdoc} */ public function check(ExceptionControllerInterface $exceptionController) { $path = $this->resourceManager->getPath('cache'); if (!is_dir($path)) { return $exceptionController->systemCheck(Validator::CHECK_CACHE, [], ['path' => $path]); } if (!is_writable($path)) { return $exceptionController->systemCheck(Validator::CHECK_CACHE, [], ['path' => $path]); } return null; }
protected function initializeResponder($request) { $config = new ResourceManager(__DIR__); $config->setPath('cache', 'tmp/cache'); $config->setPath('files', 'images'); $config->compat(); $app = new Application(array('resources' => $config)); $app->register(new \Bolt\Provider\CacheServiceProvider()); $responder = new ThumbnailResponder($app, $request); $responder->initialize(); return $responder; }
protected function getApp() { $sessionMock = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Session\\Session')->setMethods(array('clear'))->setConstructorArgs(array(new MockFileSessionStorage()))->getMock(); $config = new Config\ResourceManager($this->loader); $config->compat(); $bolt = new Application(array('resources' => $config)); $bolt['config']->set('general/database', array('driver' => 'sqlite', 'databasename' => 'test', 'username' => 'test', 'memory' => true)); $bolt['session'] = $sessionMock; $bolt['resources']->setPath('files', __DIR__ . "/files"); $bolt->initialize(); return $bolt; }
protected function initializeResponder($request) { $container = new Pimple(array('rootpath' => __DIR__, 'pathmanager' => new PlatformFileSystemPathFactory())); $config = new ResourceManager($container); $config->setPath('cache', 'tmp/cache'); $config->setPath('files', 'images'); $config->compat(); $app = new Application(array('resources' => $config)); $app->register(new CacheServiceProvider()); $responder = new ThumbnailResponder($app, $request); $responder->initialize(); return $responder; }
/** * Add base snippets to the response. */ protected function addSnippets() { $this->queue->add(Target::END_OF_HEAD, '<meta name="generator" content="Bolt">'); if ($this->config->get('general/canonical')) { $canonical = $this->resources->getUrl('canonicalurl'); $this->queue->add(Target::END_OF_HEAD, $this->encode('<link rel="canonical" href="%s">', $canonical)); } if ($favicon = $this->config->get('general/favicon')) { $host = $this->resources->getUrl('hosturl'); $theme = $this->resources->getUrl('theme'); $this->queue->add(Target::END_OF_HEAD, $this->encode('<link rel="shortcut icon" href="%s%s%s">', $host, $theme, $favicon)); } }
/** * This check looks for the presence of the .htaccess file inside the web directory. * It is here only as a convenience check for users that install the basic version of Bolt. * * If you see this error and want to disable it, call $config->getVerifier()->disableApacheChecks(); * inside your bootstrap.php file, just before the call to $config->verify(). * * {@inheritdoc} */ public function check(ExceptionControllerInterface $exceptionController) { $request = Request::createFromGlobals(); $serverSoftware = $request->server->get('SERVER_SOFTWARE', ''); $isApache = strpos($serverSoftware, 'Apache') !== false; if ($this->resourceManager->getVerifier()->disableApacheChecks === true || !$isApache) { return null; } $path = $this->resourceManager->getPath('web/.htaccess'); if (is_readable($path)) { return null; } return $exceptionController->systemCheck(Validator::CHECK_APACHE); }
/** * @param Config\ResourceManager $config */ protected function setAppPaths($config) { $config->setPath('app', PHPUNIT_WEBROOT . '/app'); $config->setPath('config', PHPUNIT_WEBROOT . '/app/config'); $config->setPath('cache', PHPUNIT_WEBROOT . '/app/cache'); $config->setPath('web', PHPUNIT_WEBROOT . '/'); $config->setPath('files', PHPUNIT_WEBROOT . '/files'); $config->setPath('themebase', PHPUNIT_WEBROOT . '/theme/'); $config->setPath('extensionsconfig', PHPUNIT_WEBROOT . '/config/extensions'); $config->setPath('extensions', PHPUNIT_WEBROOT . '/extensions'); }
/** * Returns [route name, route params] for url generation, or null for various reasons. * * @return array|null */ public function getRouteNameAndParams() { if (empty($this->app)) { $this->app = ResourceManager::getApp(); } if (empty($this->id)) { return null; } // No links for records that are 'viewless' if (isset($this->contenttype['viewless']) && $this->contenttype['viewless'] == true) { return null; } list($name, $config) = $this->getRouteConfig(); if (!$config) { return null; } $slug = $this->getLinkSlug(); $availableParams = array_filter(array_merge($config['defaults'] ?: [], $this->getRouteRequirementParams($config), ['contenttypeslug' => $this->contenttype['singular_slug'], 'id' => $this->id, 'slug' => $slug])); /** @var Route|null $route */ $route = $this->app['routes']->get($name); if (!$route) { return null; } // Needed params as array keys $pathVars = $route->compile()->getPathVariables(); $neededKeys = array_flip($pathVars); // Set the values of neededKeys from the availableParams. // This removes extra parameters that are not needed for url generation. $params = array_replace($neededKeys, array_intersect_key($availableParams, $neededKeys)); return [$name, $params]; }
/** * Creates a URL for the content record. * * @return string */ public function link() { if (empty($this->app)) { $this->app = ResourceManager::getApp(); } if (empty($this->id)) { return null; } // No links for records that are 'viewless' if (isset($this->contenttype['viewless']) && $this->contenttype['viewless'] == true) { return null; } list($binding, $route) = $this->getRoute(); if (!$route) { return null; } $slug = $this->values['slug']; if (empty($slug)) { $slug = $this->id; } $link = $this->app['url_generator']->generate($binding, array_filter(array_merge($route['defaults'] ?: [], $this->getRouteRequirementParams($route), ['contenttypeslug' => $this->contenttype['singular_slug'], 'id' => $this->id, 'slug' => $slug]))); // Strip the query string generated by supplementary parameters. // since our $params contained all possible arguments and the ->generate() // added all $params which it didn't need in the query-string we can // safely strip the query-string. // NB. this does mean we don't support routes with query strings return preg_replace('/^([^?]*).*$/', '\\1', $link); }
private static function getValidityTimestampFilename() { // If 'invalidate()' was called statically, we don't have the // $integrityCachePath yet, so we set it here. if (empty(self::$integrityCachePath)) { $app = \Bolt\Configuration\ResourceManager::getApp(); self::$integrityCachePath = $app['resources']->getPath('cache'); } return self::$integrityCachePath . '/' . self::INTEGRITY_CHECK_TS_FILENAME; }
/** * @param ClassLoader|string $loader ClassLoader or root path * @param Request $request */ public function __construct($loader, Request $request = null) { $container = new \Pimple(); if ($loader instanceof ClassLoader) { $container['classloader'] = $loader; } else { $container['rootpath'] = $loader; } $container['pathmanager'] = new PlatformFileSystemPathFactory(); $container['request'] = $request; parent::__construct($container); }
public function testUpdate() { $this->allowLogin($this->getApp()); $checkResponse = new SchemaCheck(); $check = $this->getMockSchemaManager(['update']); $check->expects($this->any())->method('update')->will($this->returnValue($checkResponse)); $this->setService('schema', $check); ResourceManager::$theApp = $this->getApp(); $this->setRequest(Request::create('/bolt/dbupdate', 'POST')); $response = $this->controller()->update($this->getRequest()); $this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode()); $this->assertEquals('/bolt/dbupdate_result', $response->getTargetUrl()); }
public function testCheckDir() { $fakeLocation = "/path/to/nowhere"; $config = new Composer(TEST_ROOT); $verifier = new ComposerChecks($config); $app['resources'] = $config; ResourceManager::$theApp = $app; // Check we get an exception if the directory isn't writable $this->php->expects($this->at(0))->method('is_dir')->will($this->returnValue(true)); $this->php->expects($this->at(1))->method('is_dir')->will($this->returnValue(true)); $this->php->expects($this->any())->method('is_writable')->will($this->returnValue(false)); $this->setExpectedException('Bolt\\Exception\\LowlevelException'); $this->expectOutputRegex("/Bolt - Fatal Error/"); $verifier->checkDir($fakeLocation); }
/** * Insert jQuery, if it's not inserted already. * * Some of the patterns that 'match' are: * - jquery.js * - jquery.min.js * - jquery-latest.js * - jquery-latest.min.js * - jquery-1.8.2.min.js * - jquery-1.5.js * * @param Request $request * @param Response $response */ protected function addJquery(Request $request, Response $response) { if (!$this->config->get('general/add_jquery', false) && !$this->config->get('theme/add_jquery', false)) { return; } if (Zone::isFrontend($request) === false) { return; } $html = $response->getContent(); $regex = '/<script(.*)jquery(-latest|-[0-9\\.]*)?(\\.min)?\\.js/'; if (!preg_match($regex, $html)) { $jqueryfile = $this->resources->getPath('app/view/js/jquery-2.2.4.min.js'); $asset = (new Snippet())->setLocation(Target::BEFORE_JS)->setCallback('<script src="' . $jqueryfile . '"></script>'); $this->injector->inject($asset, $asset->getLocation(), $response); } }
/** * Insert jQuery, if it's not inserted already. * * Some of the patterns that 'match' are: * - jquery.js * - jquery.min.js * - jquery-latest.js * - jquery-latest.min.js * - jquery-1.8.2.min.js * - jquery-1.5.js * * @param string $html * * @return string HTML */ protected function addJquery($html) { if (!$this->config->get('general/add_jquery', false) && !$this->config->get('theme/add_jquery', false)) { return $html; } $zone = Zone::FRONTEND; if ($request = $this->requestStack->getCurrentRequest()) { $zone = Zone::get($request); } $regex = '/<script(.*)jquery(-latest|-[0-9\\.]*)?(\\.min)?\\.js/'; if ($zone === Zone::FRONTEND && !preg_match($regex, $html)) { $jqueryfile = $this->resources->getPath('app/view/js/jquery-2.1.4.min.js'); $asset = (new Snippet())->setLocation(Target::BEFORE_JS)->setCallback('<script src="' . $jqueryfile . '"></script>'); $html = $this->injector->inject($asset, $asset->getLocation(), $html); } return $html; }
protected function doDatabaseSqliteCheck(Controller\Exception $exceptionController, array $dbConfig) { if (extension_loaded('pdo_sqlite') === false) { return $exceptionController->databaseDriver('missing', 'SQLite', 'pdo_sqlite'); } // If in-memory connection, skip path checks if (isset($dbConfig['memory']) && $dbConfig['memory'] === true) { return null; } $fs = new Filesystem(); $file = $dbConfig['path']; // If the file is present, make sure it is writable if ($fs->exists($file)) { try { $fs->touch($file); } catch (IOException $e) { return $exceptionController->databasePath('file', $file, 'is not writable'); } return null; } // If the file isn't present, make sure the directory // exists and is writable so the file can be created $dir = dirname($file); if (!$fs->exists($dir)) { // At this point, it is possible that the site has been moved and // the configured Sqlite database file path is no longer relevant // to the site's root path $cacheJson = $this->resourceManager->getPath('cache/config-cache.json'); if ($fs->exists($cacheJson)) { $fs->remove($cacheJson); $this->config->initialize(); if (!$fs->exists($dir)) { return $exceptionController->databasePath('folder', $dir, 'does not exist'); } } else { return $exceptionController->databasePath('folder', $dir, 'does not exist'); } } try { $fs->touch($dir); } catch (IOException $e) { return $exceptionController->databasePath('folder', $dir, 'is not writable'); } return null; }
public function testCheckDir() { $fakeLocation = '/path/to/nowhere'; $config = new Composer(TEST_ROOT); $verifier = new ComposerChecks($config); $app['resources'] = $config; ResourceManager::$theApp = $app; // Check we get an exception if the directory isn't writable $this->php->expects($this->at(0))->method('is_dir')->will($this->returnValue(true)); $this->php->expects($this->at(1))->method('is_dir')->will($this->returnValue(true)); $this->php->expects($this->any())->method('is_writable')->will($this->returnValue(false)); try { $verifier->checkDir($fakeLocation); $this->fail('Bolt\\Exception\\LowlevelException not thrown'); } catch (LowlevelException $e) { $this->assertRegExp("/The default folder \\/path\\/to\\/nowhere isn't writable. Make sure it's writable to the user that the webserver is using/", $e->getMessage()); $this->assertRegExp('/When using Bolt as a Composer package it will need to have access to the following folders/', $e->getMessage()); $this->assertRegExp('/Bolt - Fatal Error/', $e::$screen); } }
public function testUpdate() { $this->allowLogin($this->getApp()); $checkResponse = new \Bolt\Storage\Database\Schema\CheckResponse(); $check = $this->getMock('Bolt\\Storage\\Database\\Schema\\Manager', ['repairTables'], [$this->getApp()]); $check->expects($this->any())->method('repairTables')->will($this->returnValue($checkResponse)); $this->setService('schema', $check); ResourceManager::$theApp = $this->getApp(); $this->setRequest(Request::create('/bolt/dbupdate', 'POST', ['return' => 'edit'])); $response = $this->controller()->update($this->getRequest()); $this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode()); $this->assertEquals('/bolt/file/edit/config/contenttypes.yml', $response->getTargetUrl()); $this->assertNotEmpty($this->getFlashBag()->get('success')); $this->setRequest(Request::create('/bolt/dbupdate', 'POST', ['return' => 'edit'])); $response = $this->controller()->update($this->getRequest()); $this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode()); $this->assertEquals('/bolt/file/edit/config/contenttypes.yml', $response->getTargetUrl()); $this->assertNotEmpty($this->getFlashBag()->get('success')); $this->setRequest(Request::create('/bolt/dbupdate', 'POST')); $response = $this->controller()->update($this->getRequest()); $this->assertEquals(Response::HTTP_FOUND, $response->getStatusCode()); $this->assertEquals('/bolt/dbupdate_result', $response->getTargetUrl()); }
/** * @runInSeparateProcess */ public function testEarlyStaticFails() { $this->setExpectedException('RuntimeException'); $app = ResourceManager::getApp(); }
public function testStaticApp() { $config = new Standard(PHPUNIT_WEBROOT); $app = new Application(['resources' => $config]); $app2 = ResourceManager::getApp(); $this->assertEquals($app, $app2); }
/** * @deprecated Don't use! Will probably refactored out soon * * @param Application $app */ public function setApp(Application $app) { $this->app = $app; ResourceManager::$theApp = $app; }
/** * Returns translated contenttype name with fallback to name/slug from 'contenttypes.yml'. * * @param string $contenttype The contentype * @param bool $singular Singular or plural requested? * @param string $locale Translate to this locale * * @return string */ private static function transContenttypeName($contenttype, $singular, $locale) { $key = 'contenttypes.' . $contenttype . '.name.' . ($singular ? 'singular' : 'plural'); $name = self::trans($key, [], 'contenttypes', $locale); if ($name === $key) { $app = ResourceManager::getApp(); $name = $app['config']->get('contenttypes/' . $contenttype . ($singular ? '/singular_name' : '/name')); if (empty($name)) { $name = ucfirst($app['config']->get('contenttypes/' . $contenttype . ($singular ? '/singular_slug' : '/slug'), $contenttype)); } // Escape names coming from 'contenttypes.yml' $name = htmlspecialchars($name, ENT_QUOTES); } return $name; }
/** * Create a simple redirect to a page / path. * * @param string $path * @param bool $abort * * @return string */ public static function simpleredirect($path, $abort = false) { $app = ResourceManager::getApp(); if (empty($path)) { $path = '/'; } header("location: {$path}"); echo "<p>Redirecting to <a href='{$path}'>{$path}</a>.</p>"; echo "<script>window.setTimeout(function () { window.location='{$path}'; }, 500);</script>"; if (!$abort) { return $path; } $app->abort(Response::HTTP_SEE_OTHER, "Redirecting to '{$path}'."); }
static function enqueueScript($handle, $src = false, $deps = array(), $ver = false, $in_footer = false) { if (!is_array(self::$scriptQueue)) { self::$scriptQueue = ['head' => [], 'footer' => []]; } if ($in_footer) { $location = 'footer'; } else { $location = 'head'; } if ($src != false) { $script = sprintf("<script type='text/javascript' src='%s%s' type='text/css'></script>\n", $src, !empty($ver) ? '?ver=' . $ver : ''); self::$scriptQueue[$location][$handle] = $script; } if (in_array('jquery', $deps)) { $app = ResourceManager::getApp(); $jqueryfile = sprintf('%s%s/%s/wordpress-theme/assets/jquery-2.2.3.min.js', $app['paths']['extensions'], basename(dirname(dirname(dirname(__DIR__)))), basename(dirname(dirname(__DIR__)))); self::enqueueScript('jquery', $jqueryfile); } }
/** * i18n made right, second attempt... * * Instead of calling directly $app['translator']->trans(), we check * for the presence of a placeholder named '%contentype%'. * * If one is found, we replace it with the contenttype.name parameter, * and try to get a translated string. If there is not, we revert to * the generic (%contenttype%) string, which must have a translation. */ function __() { $app = ResourceManager::getApp(); $num_args = func_num_args(); if (0 == $num_args) { return null; } $args = func_get_args(); if ($num_args > 4) { $fn = 'transChoice'; } elseif ($num_args == 1 || is_array($args[1])) { // If only 1 arg or 2nd arg is an array call trans $fn = 'trans'; } else { $fn = 'transChoice'; } $tr_args = null; if ($fn == 'trans' && $num_args > 1) { $tr_args = $args[1]; } elseif ($fn == 'transChoice' && $num_args > 2) { $tr_args = $args[2]; } // Check for contenttype(s) placeholder if ($tr_args) { $keytype = '%contenttype%'; $keytypes = '%contenttypes%'; $have_singular = array_key_exists($keytype, $tr_args); $have_plural = array_key_exists($keytypes, $tr_args); if ($have_singular || $have_plural) { // have a %contenttype% placeholder, try to find a specialized translation if ($have_singular) { $text = str_replace($keytype, $tr_args[$keytype], $args[0]); unset($tr_args[$keytype]); } else { $text = str_replace($keytypes, $tr_args[$keytypes], $args[0]); unset($tr_args[$keytypes]); } //echo "\n" . '<!-- contenttype replaced: '.htmlentities($text)." -->\n"; if ($fn == 'transChoice') { $trans = $app['translator']->transChoice($text, $args[1], htmlencode_params($tr_args), isset($args[3]) ? $args[3] : 'contenttypes', isset($args[4]) ? $args[4] : $app['request']->getLocale()); } else { $trans = $app['translator']->trans($text, htmlencode_params($tr_args), isset($args[2]) ? $args[2] : 'contenttypes', isset($args[3]) ? $args[3] : $app['request']->getLocale()); } //echo '<!-- translation : '.htmlentities($trans)." -->\n"; if ($text != $trans) { return $trans; } } } //try { if (isset($args[1])) { $args[1] = htmlencode_params($args[1]); } switch ($num_args) { case 5: return $app['translator']->transChoice($args[0], $args[1], $args[2], $args[3], $args[4]); case 4: //echo "<!-- 4. call: $fn($args[0], $args[1], $args[2], $args[3]) -->\n"; return $app['translator']->{$fn}($args[0], $args[1], $args[2], $args[3]); case 3: //echo "<!-- 3. call: $fn($args[0], $args[1], $args[2]) -->\n"; return $app['translator']->{$fn}($args[0], $args[1], $args[2]); case 2: //echo "<!-- 2. call: $fn($args[0],$args[1] -->\n"; return $app['translator']->{$fn}($args[0], $args[1]); case 1: //echo "<!-- 1. call: $fn($args[0]) -->\n"; return $app['translator']->{$fn}($args[0]); } /*} catch (\Exception $e) { echo "<!-- ARGHH !!! -->\n"; //return $args[0]; die($e->getMessage()); }*/ }
/** * Translates contentype specific messages and falls back to building generic message or fallback locale. * * @param string $genericKey * @param array $params * @param string $id * @param boolean $singular * @param mixed $locale * * @return boolean */ private static function transContenttype($genericKey, array $params, $id, $singular, $locale) { $contenttype = $params[$id]; $encParams = self::htmlencodeParams($params, $id); $key = 'contenttypes.' . $contenttype . '.text.' . substr($genericKey, 21); // Try to get a real translation from contenttypes.xx_XX.yml $trans = self::trans($key, $encParams, 'contenttypes', $locale, false); $app = ResourceManager::getApp(); $localeFallbacks = $app['locale_fallbacks']; $transFallback = self::trans($key, $encParams, 'contenttypes', reset($localeFallbacks), false); // We don't want fallback translation here if ($trans === $transFallback) { $trans = false; } // No translation found, build string from generic translation pattern if ($trans === false) { // Get generic translation with name replaced $encParams[$id] = self::transContenttypeName($contenttype, $singular, $locale); $transGeneric = self::trans($genericKey, $encParams, 'messages', $locale, false); } else { $transGeneric = false; } // Return: translation => generic translation => fallback translation => key if ($trans !== false) { return $trans; } elseif ($transGeneric !== false) { return $transGeneric; } elseif ($transFallback !== false) { return $transFallback; } else { return $genericKey; } }