Inheritance: extends Silex\Application
コード例 #1
0
 /**
  * Invalidate our database check by removing the timestamp file from cache.
  *
  * @return void
  */
 public function invalidate()
 {
     $fileName = $this->getValidityTimestampFilename();
     // delete the cached dbcheck-ts
     if (is_writable($fileName)) {
         unlink($fileName);
     } elseif (file_exists($fileName)) {
         $message = sprintf("The file '%s' exists, but couldn't be removed. Please remove this file manually, and try again.", $fileName);
         $this->app->abort(Response::HTTP_UNAUTHORIZED, $message);
     }
 }
コード例 #2
0
 public function testRegister()
 {
     $app = new Application(array('resources' => new Standard(__DIR__)));
     $provider = new ThumbnailProvider();
     $app->register($provider);
     $this->assertArrayHasKey('files', $app['thumbnails.paths']);
     $this->assertArrayHasKey('theme', $app['thumbnails.paths']);
     $app['request'] = Request::create('/');
     $this->assertInstanceOf('Bolt\\Thumbs\\ThumbnailResponder', $app['thumbnails']);
     $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $app['thumbnails.response']);
 }
コード例 #3
0
 protected function getApp()
 {
     $sessionMock = $this->getMockBuilder('Symfony\\Component\\HttpFoundation\\Session\\Session')->setMethods(array('clear'))->setConstructorArgs(array(new MockFileSessionStorage()))->getMock();
     $config = new Config\ResourceManager(TEST_ROOT);
     $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;
 }
コード例 #4
0
 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;
 }
コード例 #5
0
 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;
 }
コード例 #6
0
ファイル: MenuBuilder.php プロジェクト: jkaan/timOnlineBolt
 /**
  * Updates a menu item to have at least a 'link' key.
  *
  * @param array $item
  *
  * @return array Keys 'link' and possibly 'label', 'title' and 'path'
  */
 private function menuHelper($item)
 {
     // recurse into submenu's
     if (isset($item['submenu']) && is_array($item['submenu'])) {
         $item['submenu'] = $this->menuHelper($item['submenu']);
     }
     if (isset($item['route'])) {
         $param = !empty($item['param']) ? $item['param'] : [];
         $add = !empty($item['add']) ? $item['add'] : '';
         $item['link'] = $this->app->generatePath($item['route'], $param, $add);
     } elseif (isset($item['path'])) {
         $item = $this->resolvePathToContent($item);
     }
     return $item;
 }
コード例 #7
0
ファイル: Storage.php プロジェクト: viyancs/bolt
 /**
  * Split into meta-parameters and contenttype parameters
  * (tightly coupled to $this->getContent())
  *
  * @see $this->decodeContentQuery()
  */
 private function organizeQueryParameters($in_parameters = null)
 {
     $ctype_parameters = array();
     $meta_parameters = array('order' => false);
     // order in meta_parameters check again in line: 1530!
     if (is_array($in_parameters)) {
         foreach ($in_parameters as $key => $value) {
             if (in_array($key, array('page', 'limit', 'offset', 'returnsingle', 'printquery', 'paging', 'order'))) {
                 $meta_parameters[$key] = $value;
             } else {
                 $ctype_parameters[$key] = $value;
             }
         }
     }
     if (!isset($meta_parameters['page'])) {
         $meta_parameters['page'] = 1;
     }
     // oof!
     if (!empty($meta_parameters['paging']) && $this->app->raw('request') instanceof Request) {
         $meta_parameters['page'] = $this->app['request']->get('page', $meta_parameters['page']);
     }
     // oof, part deux!
     if (isset($meta_parameters['order']) && $meta_parameters['order'] == false && $this->app->raw('request') instanceof Request) {
         $meta_parameters['order'] = $this->app['request']->get('order', false);
     }
     return array($meta_parameters, $ctype_parameters);
 }
コード例 #8
0
ファイル: Extensions.php プロジェクト: aleksabp/bolt
 protected function initializeExtension(ExtensionInterface $extension)
 {
     $name = $extension->getName();
     // Attempt to get extension YAML config
     try {
         $extension->getConfig();
     } catch (\Exception $e) {
         $this->logInitFailure('Failed to load YAML config', $name, $e, Logger::ERROR);
         return;
     }
     // Call extension initialize()
     try {
         $extension->initialize();
         // Add an object of this extension to the global Twig scope.
         $namespace = $this->getNamespace($extension);
         if (!empty($namespace)) {
             $this->app['twig'] = $this->app->share($this->app->extend('twig', function (\Twig_Environment $twig) use($namespace, $extension) {
                 $twig->addGlobal($namespace, $extension);
                 return $twig;
             }));
         }
     } catch (\Exception $e) {
         $this->logInitFailure('Initialisation failed', $name, $e, Logger::ERROR);
         return;
     }
     // Flag the extension as initialised
     $this->initialized[$name] = $extension;
     // If an extension makes it known it sends email, increase the counter
     if (is_callable(array($extension, 'sendsMail')) && $extension->sendsMail()) {
         $this->mailsenders++;
     }
     // Get the extension defined snippets
     try {
         $this->getSnippets($name);
     } catch (\Exception $e) {
         $this->logInitFailure('Snippet loading failed', $name, $e, Logger::ERROR);
         return;
     }
     // Add Twig extensions
     if (!is_callable(array($extension, 'getTwigExtensions'))) {
         return;
     }
     /** @var \Twig_Extension[] $extensions */
     $twigExtensions = $extension->getTwigExtensions();
     $addTwigExFunc = array($this, 'addTwigExtension');
     foreach ($twigExtensions as $twigExtension) {
         $this->app['twig'] = $this->app->share($this->app->extend('twig', function (\Twig_Environment $twig) use($addTwigExFunc, $twigExtension, $name) {
             call_user_func($addTwigExFunc, $twig, $twigExtension, $name);
             return $twig;
         }));
         if (!is_callable(array($extension, 'isSafe')) || !$extension->isSafe()) {
             continue;
         }
         $this->app['safe_twig'] = $this->app->share($this->app->extend('safe_twig', function (\Twig_Environment $twig) use($addTwigExFunc, $twigExtension, $name) {
             call_user_func($addTwigExFunc, $twig, $twigExtension, $name);
             return $twig;
         }));
     }
 }
コード例 #9
0
 /**
  * @inheritdoc
  */
 protected function registerServices(Application $app)
 {
     $config = $this->getConfig();
     $app['slugify'] = $app->share(function ($app) use($config) {
         if (!isset($config['regexp'])) {
             $config['regexp'] = '/([^A-Za-z0-9]|-)+/';
         }
         if (!isset($config['lowercase'])) {
             $config['lowercase'] = true;
         }
         $slugify = new Slugify($config['regexp'], array('lowercase' => $config['lowercase']));
         foreach ($config['rules'] as $key => $value) {
             $slugify->addRule($key, $value);
         }
         return $slugify;
     });
 }
コード例 #10
0
ファイル: Config.php プロジェクト: aaleksu/bolt_cm
 /**
  * Cache built configuration parameters.
  */
 protected function saveCache()
 {
     // Store the version number along with the config.
     $this->data['version'] = $this->app->getVersion();
     if ($this->get('general/caching/config')) {
         Lib::saveSerialize($this->app['resources']->getPath('cache') . '/config_cache.php', $this->data);
         return;
     }
     @unlink($this->app['resources']->getPath('cache') . '/config_cache.php');
 }
コード例 #11
0
 /**
  * Get the redirect response object.
  *
  * @param array  $redirect
  * @param string $query
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 private function getRedirectResponse(array $redirect, $query)
 {
     if (strpos($redirect['target'], 'http') === 0) {
         return $this->app->redirect($redirect['target'] . $query);
     } elseif ($redirectpage = $this->app['storage']->getContent($redirect['target'])) {
         return new RedirectResponse($redirectpage->link() . $query);
     }
     // No route found
     return;
 }
コード例 #12
0
ファイル: Manager.php プロジェクト: kaurav/bolt
 /**
  * Ensure any late added ContentTypes have a valid table object in the provider.
  *
  * @param string $contenttype
  *
  * @return \Bolt\Storage\Database\Schema\Table\ContentType
  */
 private function getContentTypeTableObject($contenttype)
 {
     if (!isset($this->app['schema.tables'][$contenttype])) {
         $platform = $this->app['db']->getDatabasePlatform();
         $this->app['schema.tables'][$contenttype] = $this->app->share(function () use($platform) {
             return new ContentType($platform);
         });
     }
     return $this->app['schema.tables'][$contenttype];
 }
コード例 #13
0
 public static function sorttaxonomy(\Bolt\Application $app, $taxonomytype, $slug)
 {
     // First, get some content
     $page = $app['request']->query->get('page', 1);
     $order = $app['request']->query->get('order');
     $amount = $app['config']->get('general/listing_records');
     $order = !empty($order) ? $order : (!empty($contenttype['sort']) ? $contenttype['sort'] : $app['config']->get('general/listing_sort'));
     $content = $app['storage']->getContentByTaxonomy($taxonomytype, $slug, array('limit' => $amount, 'order' => $order, 'page' => $page));
     $taxonomytype = $app['storage']->getTaxonomyType($taxonomytype);
     // No taxonomytype, no possible content..
     if (empty($taxonomytype)) {
         return false;
     } else {
         $taxonomyslug = $taxonomytype['slug'];
     }
     if (!$content) {
         $app->abort(404, "Content for '{$taxonomyslug}/{$slug}' not found.");
     }
     $chosen = "taxonomy";
     // Set the template based on the (optional) setting in taxonomy.yml, or fall back to default listing template
     if ($app['config']->get('taxonomy/' . $taxonomyslug . '/listing_template')) {
         $template = $app['config']->get('taxonomy/' . $taxonomyslug . '/listing_template');
     } else {
         $template = $app['config']->get('general/listing_template');
     }
     $app['logger.system']->debug('template chosen: ' . $app['config']->get('general/theme') . "/{$template} ({$chosen})", array('event' => 'FrontendExt'));
     //$app['log']->setValue('templatechosen', $app['config']->get('general/theme') . "/$template ($chosen)");
     // Fallback: If file is not OK, show an error page
     $filename = $app['paths']['themepath'] . "/" . $template;
     if (!file_exists($filename) || !is_readable($filename)) {
         $error = sprintf("No template for '%s'-listing defined. Tried to use '%s/%s'.", $taxonomyslug, basename($app['config']->get('general/theme')), $template);
         //$app['log']->setValue('templateerror', $error);
         $app['logger.system']->error($error, array('event' => 'FrontendExt'));
         $app->abort(404, $error);
     }
     $name = $slug;
     // Look in taxonomies in 'content', to get a display value for '$slug', perhaps.
     foreach ($content as $record) {
         $flat = \Util::array_flatten($record->taxonomy);
         $key = $app['paths']['root'] . $taxonomytype['slug'] . '/' . $slug;
         if (isset($flat[$key])) {
             $name = $flat[$key];
         }
         $key = $app['paths']['root'] . $taxonomytype['singular_slug'] . '/' . $slug;
         if (isset($flat[$key])) {
             $name = $flat[$key];
         }
     }
     $app['twig']->addGlobal('records', $content);
     $app['twig']->addGlobal('slug', $name);
     $app['twig']->addGlobal('taxonomy', $app['config']->get('taxonomy/' . $taxonomyslug));
     $app['twig']->addGlobal('taxonomytype', $taxonomyslug);
     return $app['render']->render($template);
 }
コード例 #14
0
ファイル: PackageManager.php プロジェクト: nectd/nectd-web
 /**
  * Return the URI for a package's config file edit window.
  *
  * @param string $name
  *
  * @return string
  */
 private function linkConfig($name)
 {
     // Generate the configfilename from the extension $name
     $configfilename = join('.', array_reverse(explode('/', $name))) . '.yml';
     // Check if we have a config file, and if it's readable. (yet)
     $configfilepath = $this->app['resources']->getPath('extensionsconfig/' . $configfilename);
     if (is_readable($configfilepath)) {
         return $this->app->generatePath('fileedit', ['namespace' => 'config', 'file' => 'extensions/' . $configfilename]);
     }
     return null;
 }
コード例 #15
0
 /**
  * Get the redirect response object.
  *
  * @param array  $redirect
  * @param string $query
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|null
  */
 private function getRedirectResponse(array $redirect, $query)
 {
     if (strpos($redirect['target'], 'http') === 0) {
         return $this->app->redirect($redirect['target'] . $query);
     } else {
         try {
             $url = '/' . ltrim($redirect['target'], '/');
             $this->app['url_matcher']->match($url);
             return new RedirectResponse($url . $query);
         } catch (ResourceNotFoundException $e) {
             // No route found… Go home site admin, you're… um… putting a bad route in!
             return;
         }
     }
 }
コード例 #16
0
ファイル: TranslationFile.php プロジェクト: aleksabp/bolt
 /**
  * Checks if translations file is allowed to write to.
  *
  * @return bool
  */
 public function isWriteAllowed()
 {
     $msgRepl = array('%s' => $this->relPath);
     // No file, directory not writable
     if (!file_exists($this->absPath) && !is_writable(dirname($this->absPath))) {
         $msg = Trans::__("The translations file '%s' can't be created. You will have to use your own editor to make modifications to this file.", $msgRepl);
         $this->app['session']->getFlashBag()->add('warning', $msg);
         // Have a file, but not writable
     } elseif (file_exists($this->absPath) && !is_writable($this->absPath)) {
         $msg = Trans::__("The file '%s' is not writable. You will have to use your own editor to make modifications to this file.", $msgRepl);
         $this->app['session']->getFlashBag()->add('warning', $msg);
         // File is not readable: abort
     } elseif (file_exists($this->absPath) && !is_readable($this->absPath)) {
         $msg = Trans::__("The translations file '%s' is not readable.", $msgRepl);
         $this->app->abort(Response::HTTP_NOT_FOUND, $msg);
         // File is writeable
     } else {
         return true;
     }
     return false;
 }
コード例 #17
0
ファイル: Extensions.php プロジェクト: hugin2005/bolt
 /**
  * Add Twig extensions.
  *
  * @param ExtensionInterface $extension
  * @param string             $name
  *
  * @throws \Exception
  */
 private function loadExtensionTwig(ExtensionInterface $extension, $name)
 {
     if (!is_callable([$extension, 'getTwigExtensions'])) {
         return;
     }
     /** @var \Twig_Extension[] $extensions */
     $twigExtensions = $extension->getTwigExtensions();
     $addTwigExFunc = [$this, 'addTwigExtension'];
     foreach ($twigExtensions as $twigExtension) {
         $this->app['twig'] = $this->app->share($this->app->extend('twig', function (\Twig_Environment $twig) use($addTwigExFunc, $twigExtension, $name) {
             call_user_func($addTwigExFunc, $twig, $twigExtension, $name);
             return $twig;
         }));
         if (!is_callable([$extension, 'isSafe']) || !$extension->isSafe()) {
             continue;
         }
         $this->app['safe_twig'] = $this->app->share($this->app->extend('safe_twig', function (\Twig_Environment $twig) use($addTwigExFunc, $twigExtension, $name) {
             call_user_func($addTwigExFunc, $twig, $twigExtension, $name);
             return $twig;
         }));
     }
 }
コード例 #18
0
ファイル: Storage.php プロジェクト: realitygaps/site-v20
 public function searchContentType($contenttypename, array $parameters = array(), &$pager = array())
 {
     $where = array();
     $tablename = $this->getContenttypeTablename($contenttypename);
     $contenttype = $this->app['config']->get('contenttypes/' . $contenttypename);
     // If this contenttype has 'searchable: false', we skip it.
     if (isset($contenttype['searchable']) && $contenttype['searchable'] === false) {
         return array();
     }
     // for all the non-reserved parameters that are fields, we assume people want to do a 'where'
     foreach ($parameters as $key => $value) {
         if (in_array($key, array('order', 'where', 'limit', 'offset'))) {
             continue;
             // Skip this one.
         }
         if (!$this->isValidColumn($key, $contenttype)) {
             continue;
             // Also skip if 'key' isn't a field in the contenttype.
         }
         $where[] = $this->parseWhereParameter($key, $value);
     }
     // @todo update with nice search string
     // If we need to filter, add the WHERE for that.
     // Meh, InnoDB doesn't support full text search.
     if (!empty($parameters['filter'])) {
         $filter = $this->app['db']->quote($parameters['filter']);
         $filterWhere = array();
         foreach ($contenttype['fields'] as $key => $value) {
             if (in_array($value['type'], array('text', 'textarea', 'html', 'markdown'))) {
                 $filterWhere[] = sprintf("%s LIKE '%%%s%%'", $key, $filter);
             }
         }
         if (!empty($filterWhere)) {
             $where[] = '(' . implode(' OR ', $filterWhere) . ')';
         }
     }
     $limit = !empty($parameters['limit']) ? $parameters['limit'] : 9999;
     $page = !empty($parameters['page']) ? $parameters['page'] : 1;
     // If we're allowed to use pagination, use the 'page' parameter.
     if (!empty($parameters['paging']) && $this->app->raw('request') instanceof Request) {
         $page = $this->app['request']->get('page', $page);
     }
     $queryparams = "";
     // implode 'where'
     if (!empty($where)) {
         $queryparams .= sprintf(' WHERE (%s)', implode(" AND ", $where));
     }
     // Order, with a special case for 'RANDOM'.
     if (!empty($parameters['order'])) {
         if ($parameters['order'] == "RANDOM") {
             $dboptions = $this->app['db']->getParams();
             $queryparams .= sprintf(' ORDER BY %s', $dboptions['randomfunction']);
         } else {
             $order = $this->getEscapedSortorder($parameters['order'], false);
             if (!empty($order)) {
                 $queryparams .= sprintf(' ORDER BY %s', $order);
             }
         }
     }
     // Make the query for the pager.
     $pagerquery = sprintf('SELECT COUNT(*) AS count FROM %s %s', $tablename, $queryparams);
     // Add the limit
     $queryparams = $this->app['db']->getDatabasePlatform()->modifyLimitQuery($queryparams, $limit, ($page - 1) * $limit);
     // Make the query to get the results.
     $query = "SELECT * FROM {$tablename}" . $queryparams;
     $rows = $this->app['db']->fetchAll($query);
     // Make sure content is set, and all content has information about its contenttype
     $content = array();
     foreach ($rows as $row) {
         $content[$row['id']] = $this->getContentObject($contenttype, $row);
     }
     // TODO: Check if we need to hydrate here!
     // Make sure all content has their taxonomies and relations
     $this->getTaxonomy($content);
     $this->getRelation($content);
     // Set up the $pager array with relevant values.
     $rowcount = $this->app['db']->executeQuery($pagerquery)->fetch();
     $pager = array('for' => 'search', 'count' => $rowcount['count'], 'totalpages' => ceil($rowcount['count'] / $limit), 'current' => $page, 'showing_from' => ($page - 1) * $limit + 1, 'showing_to' => ($page - 1) * $limit + count($content));
     return $content;
 }
コード例 #19
0
ファイル: Extend.php プロジェクト: ArdKuijpers/bolt
 /**
  * Middleware function to check whether a user is logged on.
  */
 public function before(Request $request, \Bolt\Application $app)
 {
     // Start the 'stopwatch' for the profiler.
     $app['stopwatch']->start('bolt.backend.before');
     // If there's no active session, don't do anything..
     if (!$app['users']->isValidSession()) {
         $app->abort(404, 'You must be logged in to use this.');
     }
     // Most of the 'check if user is allowed' happens here: match the current route to the 'allowed' settings.
     if (!$app['users']->isAllowed('extensions')) {
         $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to view that page.'));
         return redirect('dashboard');
     }
     // Stop the 'stopwatch' for the profiler.
     $app['stopwatch']->stop('bolt.backend.before');
 }
コード例 #20
0
ファイル: Upload.php プロジェクト: ArdKuijpers/bolt
 /**
  * Middleware function to check whether a user is logged on.
  */
 public function before(Request $request, \Bolt\Application $app)
 {
     // Start the 'stopwatch' for the profiler.
     $app['stopwatch']->start('bolt.backend.before');
     // If there's no active session, don't do anything..
     if (!$app['users']->isValidSession()) {
         $app->abort(404, "You must be logged in to use this.");
     }
     // Stop the 'stopwatch' for the profiler.
     $app['stopwatch']->stop('bolt.backend.before');
 }
コード例 #21
0
 /**
  * It is mandatory to disable translation caching, otherwise it creates
  * difficulties with regard to testing in isolation.
  *
  * For example, without disabling translation caching, `testDefaultTranslationLoading()`
  * passes, but the following tests fail, as the cached messages are loaded
  * instead of re-building the whole message catalogue.
  *
  * @param Application $app
  */
 protected function registerTranslationServiceWithCachingDisabled(Application $app)
 {
     $app->register(new \Silex\Provider\TranslationServiceProvider(), ['translator.cache_dir' => null, 'locale_fallbacks' => [Application::DEFAULT_LOCALE]]);
 }
コード例 #22
0
ファイル: Upload.php プロジェクト: aleksabp/bolt
 /**
  * Middleware function to check whether a user is logged on.
  *
  * @return null|\Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function before(Request $request, Application $app)
 {
     // Start the 'stopwatch' for the profiler.
     $app['stopwatch']->start('bolt.backend.before');
     // If there's no active session, don't do anything.
     if (!$app['users']->isValidSession()) {
         $app->abort(Response::HTTP_NOT_FOUND, 'You must be logged in to use this.');
     }
     if (!$app['users']->isAllowed("files:uploads")) {
         $app['session']->getFlashBag()->add('error', Trans::__('You do not have the right privileges to upload.'));
         return Lib::redirect('dashboard');
     }
     // Stop the 'stopwatch' for the profiler.
     $app['stopwatch']->stop('bolt.backend.before');
     return null;
 }
コード例 #23
0
ファイル: Config.php プロジェクト: nectd/nectd-web
 /**
  * Sanity checks for doubles in in contenttypes.
  */
 public function checkConfig()
 {
     $slugs = [];
     $wrongctype = false;
     foreach ($this->data['contenttypes'] as $key => $ct) {
         /**
          * Make sure any field that has a 'uses' parameter actually points to a field that exists.
          *
          * For example, this will show a notice:
          * entries:
          *   name: Entries
          *     singular_name: Entry
          *     fields:
          *       title:
          *         type: text
          *         class: large
          *       slug:
          *         type: slug
          *         uses: name
          */
         foreach ($ct['fields'] as $fieldname => $field) {
             // Verify that the contenttype doesn't try to add fields that are reserved.
             if ($fieldname != 'slug' && in_array($fieldname, $this->reservedFieldNames)) {
                 $error = Trans::__('contenttypes.generic.reserved-name', ['%contenttype%' => $key, '%field%' => $fieldname]);
                 $this->app['logger.flash']->error($error);
                 return;
             }
             // Check 'uses'. If it's an array, split it up, and check the separate parts. We also need to check
             // for the fields that are always present, like 'id'.
             if (is_array($field) && !empty($field['uses'])) {
                 foreach ($field['uses'] as $useField) {
                     if (!empty($field['uses']) && empty($ct['fields'][$useField]) && !in_array($useField, $this->reservedFieldNames)) {
                         $error = Trans::__('contenttypes.generic.wrong-use-field', ['%contenttype%' => $key, '%field%' => $fieldname, '%uses%' => $useField]);
                         $this->app['logger.flash']->error($error);
                         return;
                     }
                 }
             }
             // Make sure the 'type' is in the list of allowed types
             if (!isset($field['type']) || !$this->fields->has($field['type'])) {
                 $error = Trans::__('contenttypes.generic.no-proper-type', ['%contenttype%' => $key, '%field%' => $fieldname, '%type%' => $field['type']]);
                 $this->app['logger.flash']->error($error);
                 $wrongctype = true && $this->app['users']->getCurrentUsername();
             }
         }
         // Keep a running score of used slugs.
         if (!isset($slugs[$ct['slug']])) {
             $slugs[$ct['slug']] = 0;
         }
         $slugs[$ct['slug']]++;
         if (!isset($slugs[$ct['singular_slug']])) {
             $slugs[$ct['singular_slug']] = 0;
         }
         if ($ct['singular_slug'] != $ct['slug']) {
             $slugs[$ct['singular_slug']]++;
         }
     }
     // Check DB-tables integrity
     if (!$wrongctype && $this->app['schema']->needsCheck() && $this->app['schema']->needsUpdate() && $this->app['users']->getCurrentUsername()) {
         $msg = Trans::__("The database needs to be updated/repaired. Go to 'Configuration' > '<a href=\"%link%\">Check Database</a>' to do this now.", ['%link%' => $this->app->generatePath('dbcheck')]);
         $this->app['logger.flash']->error($msg);
         return;
     }
     // Sanity checks for taxonomy.yml
     foreach ($this->data['taxonomy'] as $key => $taxo) {
         // Show some helpful warnings if slugs or keys are not set correctly.
         if ($taxo['slug'] != $key) {
             $error = Trans::__("The identifier and slug for '%taxonomytype%' are the not the same ('%slug%' vs. '%taxonomytype%'). Please edit taxonomy.yml, and make them match to prevent inconsistencies between database storage and your templates.", ['%taxonomytype%' => $key, '%slug%' => $taxo['slug']]);
             $this->app['logger.flash']->error($error);
             return;
         }
     }
     // if there aren't any other errors, check for duplicates across contenttypes.
     if (!$this->app['logger.flash']->has('error')) {
         foreach ($slugs as $slug => $count) {
             if ($count > 1) {
                 $error = Trans::__("The slug '%slug%' is used in more than one contenttype. Please edit contenttypes.yml, and make them distinct.", ['%slug%' => $slug]);
                 $this->app['logger.flash']->error($error);
                 return;
             }
         }
     }
 }
コード例 #24
0
ファイル: UtilsHandlerTest.php プロジェクト: bolt/bolt
 /**
  * Override Symfony's default handler to get the output
  *
  * @param Application $app
  */
 protected function stubVarDumper(Application $app)
 {
     $app['dump'] = $app->protect(function ($var) {
         return $var;
     });
 }
 /**
  * @inheritdoc
  */
 protected function registerServices(Application $app)
 {
     $app['storage.request.edit'] = $app->share(function ($app) {
         return new ContentRequest\CustomEdit($app['storage'], $app['config'], $app['users'], $app['filesystem'], $app['logger.system'], $app['logger.flash']);
     });
 }
コード例 #26
0
ファイル: LowlevelException.php プロジェクト: aleksabp/bolt
 /**
  * Attempt to rebuild extension autoloader when a "Class not found" error
  * occurs.
  *
  * @param \Bolt\Application $app
  * @param array             $error
  */
 private static function attemptExtensionRecovery($app, $error)
 {
     $cwd = getcwd();
     if ($error['type'] === E_ERROR && strpos($error['message'], 'Class') === 0) {
         $path = $_SERVER['PATH_INFO'];
         if (isset($_SERVER['QUERY_STRING'])) {
             if (strpos($_SERVER['QUERY_STRING'], 'rebuild-autoloader') !== false) {
                 header("location: {$path}?rebuild-done");
             } elseif (strpos($_SERVER['QUERY_STRING'], 'rebuild-done') !== false) {
                 chdir($cwd);
                 return;
             }
         }
         restore_error_handler();
         $html = self::$html;
         $html = str_replace('%error_title%', 'PHP Fatal Error: Bolt Extensions Class Loader', $html);
         $message = '<b>Attempting to rebuild extension autoloader</b>';
         $message .= "<p>Redirecting to <a href='{$path}?rebuild-autoloader'>{$path}</a> on completion.</p>";
         $message .= "<script>window.setTimeout(function () { window.location='{$path}?rebuild-autoloader'; }, 5000);</script>";
         $message = nl2br($message);
         $html = str_replace('%error%', $message, $html);
         $html = str_replace('%info%', '', $html);
         if (php_sapi_name() == 'cli') {
             $html = self::cleanHTML($html) . "\n\n";
         }
         echo $html;
         $app['extend.enabled'] = false;
         $app['extensions']->checkLocalAutoloader(true);
         $html = '<div style="max-width: 640px; margin: auto;"><p class="status-ok">Completed rebuild… Attempting reload!</p>';
         if (php_sapi_name() == 'cli') {
             $html = self::cleanHTML($html) . "\n\n";
         }
         echo $html;
         // Reboot the application and retry loading
         chdir($cwd);
         $app->boot();
         $app->abort(Response::HTTP_MOVED_PERMANENTLY);
     }
 }
コード例 #27
0
ファイル: bootstrap.php プロジェクト: jkaan/timOnlineBolt
    // Resolve Bolt-root
    $boltRootPath = realpath(__DIR__ . '/..');
    // Look for the autoloader in known positions relative to the Bolt-root,
    // and autodetect an appropriate configuration class based on this
    // information. (autoload.php path maps to a configuration class)
    $autodetectionMappings = array($boltRootPath . '/vendor/autoload.php' => 'Standard', $boltRootPath . '/../../autoload.php' => 'Composer');
    foreach ($autodetectionMappings as $autoloadPath => $configType) {
        if (file_exists($autoloadPath)) {
            $loader = (require $autoloadPath);
            $configClass = '\\Bolt\\Configuration\\' . $configType;
            $config = new $configClass($loader);
            break;
        }
    }
    // None of the mappings matched, error
    if (!isset($config)) {
        throw new LowlevelException("Configuration autodetection failed because The file " . "<code>vendor/autoload.php</code> doesn't exist. Make sure " . "you've installed the required components with Composer.");
    }
    // Register a PHP shutdown function to catch fatal error
    register_shutdown_function(array('\\Bolt\\Exception\\LowlevelException', 'catchFatalErrors'));
    /**
     * @var $config Configuration\ResourceManager
     */
    $config->verify();
    $config->compat();
    // Create the 'Bolt application'
    $app = new Application(array('resources' => $config));
    // Initialize the 'Bolt application': Set up all routes, providers, database, templating, etc..
    $app->initialize();
    return $app;
});