/** * Show the password form. If the visitor gives the correct password, they * are redirected to the page they came from, if any. * * @return \Twig_Markup */ public function passwordForm() { // Set up the form. $form = $this->app['form.factory']->createBuilder('form', $data)->add('password', 'password')->getForm(); if ($this->app['request']->getMethod() == 'POST') { $form->bind($this->app['request']); $data = $form->getData(); if ($form->isValid() && $data['password'] == $this->config['password']) { // Set the session var, so we're authenticated.. $this->app['session']->set('passwordprotect', 1); // Print a friendly message.. printf("<p class='message-correct'>%s</p>", $this->config['message_correct']); $returnto = $this->app['request']->get('returnto'); // And back we go, to the page we originally came from.. if (!empty($returnto)) { simpleredirect($returnto); } } else { // Remove the session var, so we can test 'logging off'.. $this->app['session']->set('passwordprotect', 0); // Print a friendly message.. printf("<p class='message-wrong'>%s</p>", $this->config['message_wrong']); } } // Render the form, and show it it the visitor. $this->app['twig.loader.filesystem']->addPath(__DIR__); $html = $this->app['twig']->render('assets/passwordform.twig', array('form' => $form->createView())); return new \Twig_Markup($html, 'UTF-8'); }
public static function record(Silex\Application $app, $contenttypeslug, $slug) { $contenttype = $app['storage']->getContentType($contenttypeslug); $slug = makeSlug($slug, -1); // First, try to get it by slug. $content = $app['storage']->getContent($contenttype['slug'], array('slug' => $slug, 'returnsingle' => true)); if (!$content && is_numeric($slug)) { // And otherwise try getting it by ID $content = $app['storage']->getContent($contenttype['slug'], array('id' => $slug, 'returnsingle' => true)); } // No content, no page! if (!$content) { // There's one special edge-case we check for: if the request is for the backend, without trailing // slash and it is intercepted by custom routing, we forward the client to that location. if ($slug == trim($app['config']->get('general/branding/path'), "/")) { simpleredirect($app['config']->get('general/branding/path') . "/"); } $app->abort(404, "Page {$contenttypeslug}/{$slug} not found."); } // Then, select which template to use, based on our 'cascading templates rules' $template = $content->template(); // 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' defined. Tried to use '%s/%s'.", $content->getTitle(), basename($app['config']->get('general/theme')), $template); $app['log']->setValue('templateerror', $error); $app->abort(404, $error); } // Setting the canonical path and the editlink. $app['canonicalpath'] = $content->link(); $app['paths'] = getPaths($app); $app['editlink'] = path('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => $content->id)); $app['edittitle'] = $content->getTitle(); // Make sure we can also access it as {{ page.title }} for pages, etc. We set these in the global scope, // So that they're also available in menu's and templates rendered by extensions. $app['twig']->addGlobal('record', $content); $app['twig']->addGlobal($contenttype['singular_slug'], $content); // Render the template and return. return $app['render']->render($template); }
function getPaths($original = array()) { // If we passed the entire $app, set the $config if ($original instanceof \Bolt\Application) { if (!empty($original['canonicalpath'])) { $canonicalpath = $original['canonicalpath']; } $config = $original['config']; } else { $config = $original; } // Make sure $config is not empty. This is for when this function is called from lowlevelError(). // Temp fix! @todo: Fix this properly. if ($config instanceof \Bolt\Config) { if (!$config->get('general/theme')) { $config->set('general/theme', 'base-2013'); } if (!$config->get('general/theme_path')) { $config->set('general/theme_path', '/theme'); } if (!$config->get('general/canonical') && isset($_SERVER['HTTP_HOST'])) { $config->set('general/canonical', $_SERVER['HTTP_HOST']); } // Set the correct mountpoint. if ($config->get('general/branding/path')) { $mountpoint = substr($config->get('general/branding/path'), 1) . "/"; } else { $mountpoint = "bolt/"; } $theme = $config->get('general/theme'); $theme_path = $config->get('general/theme_path'); $canonical = $config->get('general/canonical', ""); } else { if (empty($config['general']['theme'])) { $config['general']['theme'] = 'base-2013'; } if (empty($config['general']['theme_path'])) { $config['general']['theme_path'] = '/theme'; } if (empty($config['general']['canonical']) && isset($_SERVER['HTTP_HOST'])) { $config['general']['canonical'] = $_SERVER['HTTP_HOST']; } // Set the correct mountpoint.. if (!empty($config['general']['branding']['path'])) { $mountpoint = substr($config['general']['branding']['path'], 1) . "/"; } else { $mountpoint = "bolt/"; } $theme = $config['general']['theme']; $theme_path = $config['general']['theme_path']; $canonical = isset($config['general']['canonical']) ? $config['general']['canonical'] : ""; } $theme_path = trim($theme_path, '/'); // Set the root $path_prefix = dirname($_SERVER['PHP_SELF']) . "/"; $path_prefix = preg_replace("/^[a-z]:/i", "", $path_prefix); $path_prefix = str_replace("//", "/", str_replace("\\", "/", $path_prefix)); if (empty($path_prefix) || 'cli-server' === php_sapi_name()) { $path_prefix = "/"; } // Make sure we're not trying to access bolt as "/index.php/bolt/", because all paths will be broken. if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], "/index.php/") !== false) { simpleredirect(str_replace("/index.php", "", $_SERVER['REQUEST_URI'])); } // Set the current protocol. Default to http, unless otherwise.. $protocol = "http"; if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' || !empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] == 'on')) { $protocol = "https"; } elseif (empty($_SERVER["SERVER_PROTOCOL"])) { $protocol = "cli"; } $hostname = empty($_SERVER['HTTP_HOST']) ? 'localhost' : $_SERVER['HTTP_HOST']; $currentpath = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : "/"; if (empty($canonicalpath)) { $canonicalpath = $currentpath; } // Set the paths $paths = array('hostname' => $hostname, 'root' => $path_prefix, 'rootpath' => BOLT_PROJECT_ROOT_DIR, 'theme' => str_replace('//', '/', $path_prefix . '/' . $theme_path . '/' . $theme . '/'), 'themepath' => BOLT_WEB_DIR . '/' . $theme_path . '/' . $theme, 'app' => $path_prefix . (BOLT_COMPOSER_INSTALLED ? 'bolt-public/' : 'app/'), 'apppath' => realpath(__DIR__ . '/..'), 'extensions' => $path_prefix . 'app/extensions/', 'extensionspath' => realpath(__DIR__ . '/../extensions'), 'bolt' => $path_prefix . $mountpoint, 'async' => $path_prefix . 'async/', 'files' => $path_prefix . 'files/', 'filespath' => BOLT_WEB_DIR . '/files', 'canonical' => $canonical, 'current' => $currentpath, 'hosturl' => sprintf('%s://%s', $protocol, $hostname), 'rooturl' => sprintf('%s://%s%s', $protocol, $canonical, $path_prefix), 'canonicalurl' => sprintf('%s://%s%s', $protocol, $canonical, $canonicalpath), 'currenturl' => sprintf('%s://%s%s', $protocol, $hostname, $currentpath)); // Set it in $app, optionally. if ($original instanceof \Bolt\Application) { $original['paths'] = $paths; $original['twig']->addGlobal('paths', $paths); } return $paths; }
/** * Check if a user is logged in, and has the proper required permission. If * not, we redirect the user to the dashboard. * * @param string $permission * @return bool True if permission allowed */ public function requireUserPermission($permission = 'dashboard') { if ($this->app['users']->isAllowed($permission)) { return true; } else { simpleredirect($this->app['config']->get('general/branding/path')); return false; } }
/** * Redirect the browser to another page. */ public function redirect($path) { // Nope! We're not allowing user-supplied content to issue redirects. if ($this->safe) { return null; } simpleredirect($path); $result = $this->app->redirect($path); return $result; }
private function abort($slug) { // There's one special edge-case we check for: if the request is for the backend, without trailing // slash and it is intercepted by custom routing, we forward the client to that location. if ($slug == trim($this->app['config']->get('general/branding/path'), "/")) { simpleredirect($this->app['config']->get('general/branding/path') . "/"); } $this->app->abort(404, "Page {$contenttypeslug}/{$slug} not found."); }
/** * Edit a unit of content, or create a new one. */ public function editcontent($contenttypeslug, $id, Silex\Application $app, Request $request) { // Make sure the user is allowed to see this page, based on 'allowed contenttypes' // for Editors. if (empty($id)) { $perm = "contenttype:{$contenttypeslug}:create"; } else { $perm = "contenttype:{$contenttypeslug}:edit:{$id}"; } if (!$app['users']->isAllowed($perm)) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } // set the editreferrer in twig if it was not set yet. $tmpreferrer = getReferrer($app['request']); if (strpos($tmpreferrer, '/overview/') !== false || $tmpreferrer == $app['paths']['bolt']) { $app['twig']->addGlobal('editreferrer', $tmpreferrer); } $contenttype = $app['storage']->getContentType($contenttypeslug); if ($request->getMethod() == "POST") { if (!$app['users']->checkAntiCSRFToken()) { $app->abort(400, __("Something went wrong")); } if (!empty($id)) { // Check if we're allowed to edit this content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$id}")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } } else { // Check if we're allowed to create content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to create a new record.')); return redirect('dashboard'); } } if ($id) { $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id)); $oldStatus = $content['status']; $newStatus = $content['status']; } else { $content = $app['storage']->getContentObject($contenttypeslug); $oldStatus = ''; } // Add non successfull control values to request values // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2 $request_all = $request->request->all(); foreach ($contenttype['fields'] as $key => $values) { if (!isset($request_all[$key])) { switch ($values['type']) { case 'select': if (isset($values['multiple']) and $values['multiple'] == true) { $request_all[$key] = array(); } break; case 'checkbox': $request_all[$key] = 0; break; } } } // To check whether the status is allowed, we act as if a status // *transition* were requested. $content->setFromPost($request_all, $contenttype); $newStatus = $content['status']; $statusOK = $app['users']->isContentStatusTransitionAllowed($oldStatus, $newStatus, $contenttype['slug'], $id); // Don't try to spoof the $id.. if (!empty($content['id']) && $id != $content['id']) { $app['session']->getFlashBag()->set('error', "Don't try to spoof the id!"); return redirect('dashboard'); } // Save the record, and return to the overview screen, or to the record (if we clicked 'save and continue') if ($statusOK && $app['storage']->saveContent($content, $contenttype['slug'])) { if (!empty($id)) { $app['session']->getFlashBag()->set('success', __('The changes to this %contenttype% have been saved.', array('%contenttype%' => $contenttype['singular_name']))); } else { $app['session']->getFlashBag()->set('success', __('The new %contenttype% has been saved.', array('%contenttype%' => $contenttype['singular_name']))); } $app['log']->add($content->getTitle(), 3, $content, 'save content'); // If 'returnto is set', we return to the edit page, with the correct anchor. if ($app['request']->get('returnto')) { // We must 'return to' the edit page. In which case we must know the Id, so let's fetch it. $id = $app['storage']->getLatestId($contenttype['slug']); return redirect('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => $id), "#" . $app['request']->get('returnto')); } // No returnto, so we go back to the 'overview' for this contenttype. // check if a pager was set in the referrer - if yes go back there $editreferrer = $app['request']->get('editreferrer'); if ($editreferrer) { return simpleredirect($editreferrer); } else { return redirect('overview', array('contenttypeslug' => $contenttype['slug'])); } } else { $app['session']->getFlashBag()->set('error', __('There was an error saving this %contenttype%.', array('%contenttype%' => $contenttype['singular_name']))); $app['log']->add("Save content error", 3, $content, 'error'); } } if (!empty($id)) { $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id)); if (empty($content)) { $app->abort(404, __('The %contenttype% you were looking for does not exist. It was probably deleted, or it never existed.', array('%contenttype%' => $contenttype['singular_name']))); } // Check if we're allowed to edit this content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$content['id']}")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } $title = sprintf("<strong>%s</strong> » %s", __('Edit %contenttype%', array('%contenttype%' => $contenttype['singular_name'])), htmlencode($content->getTitle())); $app['log']->add("Edit content", 1, $content, 'edit'); } else { // Check if we're allowed to create content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to create a new record.')); return redirect('dashboard'); } $content = $app['storage']->getEmptyContent($contenttype['slug']); $title = sprintf("<strong>%s</strong>", __('New %contenttype%', array('%contenttype%' => $contenttype['singular_name']))); $app['log']->add("New content", 1, $content, 'edit'); } $oldStatus = $content['status']; $allStatuses = array('published', 'held', 'draft', 'timed'); $allowedStatuses = array(); foreach ($allStatuses as $status) { if ($app['users']->isContentStatusTransitionAllowed($oldStatus, $status, $contenttype['slug'], $id)) { $allowedStatuses[] = $status; } } $app['twig']->addGlobal('title', $title); $duplicate = $app['request']->query->get('duplicate'); if (!empty($duplicate)) { $content->setValue('id', ""); $content->setValue('slug', ""); $content->setValue('datecreated', ""); $content->setValue('datepublish', ""); $content->setValue('datedepublish', "1900-01-01 00:00:00"); // Not all DB-engines can handle a date like '0000-00-00' $content->setValue('datechanged', ""); $content->setValue('username', ""); $content->setValue('ownerid', ""); $app['session']->getFlashBag()->set('info', __("Content was duplicated. Click 'Save %contenttype%' to finalize.", array('%contenttype%' => $contenttype['singular_name']))); } // Set the users and the current owner of this content. // For brand-new items, the creator becomes the owner. // For existing items, we'll just keep the current owner. if (empty($id)) { // A new one! $contentowner = $app['users']->getCurrentUser(); } else { $contentowner = $app['users']->getUser($content['ownerid']); } return $app['render']->render('editcontent.twig', array('contenttype' => $contenttype, 'content' => $content, 'allowedStatuses' => $allowedStatuses, 'contentowner' => $contentowner)); }
/** * Edit a unit of content, or create a new one. */ public function editContent($contenttypeslug, $id, Silex\Application $app, Request $request) { // Make sure the user is allowed to see this page, based on 'allowed contenttypes' // for Editors. if (empty($id)) { $perm = "contenttype:{$contenttypeslug}:create"; $new = true; } else { $perm = "contenttype:{$contenttypeslug}:edit:{$id}"; $new = false; } if (!$app['users']->isAllowed($perm)) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } // set the editreferrer in twig if it was not set yet. $tmpreferrer = getReferrer($app['request']); if (strpos($tmpreferrer, '/overview/') !== false || $tmpreferrer == $app['paths']['bolt']) { $app['twig']->addGlobal('editreferrer', $tmpreferrer); } $contenttype = $app['storage']->getContentType($contenttypeslug); if ($request->getMethod() == "POST") { if (!$app['users']->checkAntiCSRFToken()) { $app->abort(400, __("Something went wrong")); } if (!empty($id)) { // Check if we're allowed to edit this content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$id}")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } } else { // Check if we're allowed to create content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to create a new record.')); return redirect('dashboard'); } } // If we have an ID now, this is an existing record if ($id) { $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id)); $oldStatus = $content['status']; $newStatus = $content['status']; } else { $content = $app['storage']->getContentObject($contenttypeslug); $oldStatus = ''; } // Add non successfull control values to request values // http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2 $request_all = $request->request->all(); foreach ($contenttype['fields'] as $key => $values) { if (!isset($request_all[$key])) { switch ($values['type']) { case 'select': if (isset($values['multiple']) and $values['multiple'] == true) { $request_all[$key] = array(); } break; case 'checkbox': $request_all[$key] = 0; break; } } } // To check whether the status is allowed, we act as if a status // *transition* were requested. $content->setFromPost($request_all, $contenttype); $newStatus = $content['status']; // Don't try to spoof the $id.. if (!empty($content['id']) && $id != $content['id']) { $app['session']->getFlashBag()->set('error', "Don't try to spoof the id!"); return redirect('dashboard'); } // Save the record, and return to the overview screen, or to the record (if we clicked 'save and continue') $statusOK = $app['users']->isContentStatusTransitionAllowed($oldStatus, $newStatus, $contenttype['slug'], $id); if ($statusOK) { // Get the associate record change comment $comment = $request->request->get('changelog-comment'); // Save the record $id = $app['storage']->saveContent($content, $comment); // Log the change $app['log']->add($content->getTitle(), 3, $content, 'save content'); if ($new) { $app['session']->getFlashBag()->set('success', __('The new %contenttype% has been saved.', array('%contenttype%' => $contenttype['singular_name']))); } else { $app['session']->getFlashBag()->set('success', __('The changes to this %contenttype% have been saved.', array('%contenttype%' => $contenttype['singular_name']))); } /* * Bolt 2: * We now only get a returnto parameter if we are saving a new * record and staying on the same page, i.e. "Save {contenttype}" */ if ($app['request']->get('returnto')) { if ($app['request']->get('returnto') == "new") { return redirect('editcontent', array('contenttypeslug' => $contenttype['slug'], 'id' => $id), "#" . $app['request']->get('returnto')); } elseif ($app['request']->get('returnto') == "ajax") { /* * Flush any buffers from saveConent() dispatcher hooks * and make sure our JSON output is clean. * * Currently occurs due to a 404 exception being generated * in \Bolt\Storage::saveContent() dispatchers: * $this->app['dispatcher']->dispatch(StorageEvents::PRE_SAVE, $event); * $this->app['dispatcher']->dispatch(StorageEvents::POST_SAVE, $event); */ if (ob_get_length()) { ob_end_clean(); } // Get our record after POST_SAVE hooks are dealt with and return the JSON $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id, 'returnsingle' => true)); return new JsonResponse($content->values); } } // No returnto, so we go back to the 'overview' for this contenttype. // check if a pager was set in the referrer - if yes go back there $editreferrer = $app['request']->get('editreferrer'); if ($editreferrer) { simpleredirect($editreferrer); } else { return redirect('overview', array('contenttypeslug' => $contenttype['slug'])); } } else { $app['session']->getFlashBag()->set('error', __('There was an error saving this %contenttype%.', array('%contenttype%' => $contenttype['singular_name']))); $app['log']->add("Save content error", 3, $content, 'error'); } } // We're doing a GET if (!empty($id)) { $content = $app['storage']->getContent($contenttype['slug'], array('id' => $id)); if (empty($content)) { $app->abort(404, __('The %contenttype% you were looking for does not exist. It was probably deleted, or it never existed.', array('%contenttype%' => $contenttype['singular_name']))); } // Check if we're allowed to edit this content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:edit:{$content['id']}")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to edit that record.')); return redirect('dashboard'); } $app['log']->add("Edit content", 1, $content, 'edit'); } else { // Check if we're allowed to create content.. if (!$app['users']->isAllowed("contenttype:{$contenttype['slug']}:create")) { $app['session']->getFlashBag()->set('error', __('You do not have the right privileges to create a new record.')); return redirect('dashboard'); } $content = $app['storage']->getEmptyContent($contenttype['slug']); $app['log']->add("New content", 1, $content, 'edit'); } $oldStatus = $content['status']; $allStatuses = array('published', 'held', 'draft', 'timed'); $allowedStatuses = array(); foreach ($allStatuses as $status) { if ($app['users']->isContentStatusTransitionAllowed($oldStatus, $status, $contenttype['slug'], $id)) { $allowedStatuses[] = $status; } } $duplicate = $app['request']->query->get('duplicate'); if (!empty($duplicate)) { $content->setValue('id', ""); $content->setValue('slug', ""); $content->setValue('datecreated', ""); $content->setValue('datepublish', ""); $content->setValue('datedepublish', "1900-01-01 00:00:00"); // Not all DB-engines can handle a date like '0000-00-00' $content->setValue('datechanged', ""); $content->setValue('username', ""); $content->setValue('ownerid', ""); $app['session']->getFlashBag()->set('info', __("Content was duplicated. Click 'Save %contenttype%' to finalize.", array('%contenttype%' => $contenttype['singular_name']))); } // Set the users and the current owner of this content. if (empty($id)) { // For brand-new items, the creator becomes the owner. $contentowner = $app['users']->getCurrentUser(); } else { // For existing items, we'll just keep the current owner. $contentowner = $app['users']->getUser($content['ownerid']); } $context = array('contenttype' => $contenttype, 'content' => $content, 'allowed_status' => $allowedStatuses, 'contentowner' => $contentowner, 'fields' => $app['config']->fields->fields()); return $app['render']->render('editcontent/editcontent.twig', array('context' => $context)); }
/** * Redirect the browser to another page. */ public function redirect($path) { simpleredirect($path); $result = $this->app->redirect($path); return $result; }
function getPaths($original = array()) { // If we passed the entire $app, set the $config if ($original instanceof \Bolt\Application) { if (!empty($original['canonicalpath'])) { $canonicalpath = $original['canonicalpath']; } $config = $original['config']; } else { $config = $original; } // Make sure $config is not empty. This is for when this function is called // from lowlevelError(). // Temp fix! @todo: Fix this properly. if ($config instanceof \Bolt\Config) { if (!$config->get('general/theme')) { $config->set('general/theme', 'base-2013'); } if (!$config->get('general/canonical') && isset($_SERVER['HTTP_HOST'])) { $config->set('general/canonical', $_SERVER['HTTP_HOST']); } // Set the correct mountpoint.. if ($config->get('general/branding/path')) { $mountpoint = substr($config->get('general/branding/path'), 1) . "/"; } else { $mountpoint = "bolt/"; } $theme = $config->get('general/theme'); $canonical = $config->get('general/canonical', ""); } else { if (empty($config['general']['theme'])) { $config['general']['theme'] = 'base-2013'; } if (empty($config['general']['canonical']) && isset($_SERVER['HTTP_HOST'])) { $config['general']['canonical'] = $_SERVER['HTTP_HOST']; } // Set the correct mountpoint.. if (!empty($config['general']['branding']['path'])) { $mountpoint = substr($config['general']['branding']['path'], 1) . "/"; } else { $mountpoint = "bolt/"; } $theme = $config['general']['theme']; $canonical = isset($config['general']['canonical']) ? $config['general']['canonical'] : ""; } // Set the root $path_prefix = dirname($_SERVER['PHP_SELF']) . "/"; $path_prefix = preg_replace("/^[a-z]:/i", "", $path_prefix); $path_prefix = str_replace("//", "/", str_replace("\\", "/", $path_prefix)); if (empty($path_prefix) || 'cli-server' === php_sapi_name()) { $path_prefix = "/"; } // make sure we're not trying to access bolt as "/index.php/bolt/", because all paths will be broken. if (!empty($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], "/index.php") !== false) { simpleredirect(str_replace("/index.php", "", $_SERVER['REQUEST_URI'])); } if (!empty($_SERVER["SERVER_PROTOCOL"])) { $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"], 0, 5)) == 'https' ? 'https' : 'http'; } else { $protocol = "cli"; } $currentpath = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : "/"; if (empty($canonicalpath)) { $canonicalpath = $currentpath; } // Set the paths $paths = array('hostname' => !empty($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : "localhost", 'root' => $path_prefix, 'rootpath' => realpath(__DIR__ . "/../../"), 'theme' => $path_prefix . "theme/" . $theme . "/", 'themepath' => realpath(__DIR__ . "/../../theme/" . $theme), 'app' => $path_prefix . "app/", 'apppath' => realpath(__DIR__ . "/.."), 'bolt' => $path_prefix . $mountpoint, 'async' => $path_prefix . "async/", 'files' => $path_prefix . "files/", 'filespath' => realpath(__DIR__ . "/../../files"), 'canonical' => $canonical, 'current' => $currentpath); $paths['hosturl'] = sprintf("%s://%s", $protocol, $paths['hostname']); $paths['rooturl'] = sprintf("%s://%s%s", $protocol, $paths['canonical'], $paths['root']); $paths['canonicalurl'] = sprintf("%s://%s%s", $protocol, $paths['canonical'], $canonicalpath); $paths['currenturl'] = sprintf("%s://%s%s", $protocol, $paths['hostname'], $currentpath); // Temp fix! @todo: Fix this properly. if ($config instanceof \Bolt\Config) { if ($config->get('general/theme_path')) { $paths['themepath'] = BOLT_PROJECT_ROOT_DIR . $config->get('general/theme_path'); } } else { if (isset($config['general']['theme_path'])) { $paths['themepath'] = BOLT_PROJECT_ROOT_DIR . $config['general']['theme_path']; } } if (BOLT_COMPOSER_INSTALLED) { $paths['app'] = $path_prefix . "bolt-public/"; } // Set it in $app, optionally. if ($original instanceof \Bolt\Application) { $original['paths'] = $paths; $original['twig']->addGlobal('paths', $paths); } return $paths; }
/** * Create a simple Form. * * @param string $formname * @internal param string $name * @return string */ function simpleForm($formname = "") { $this->app['twig.loader.filesystem']->addPath(__DIR__); // Select which form to use.. if (isset($this->config[$formname])) { $formconfig = $this->config[$formname]; } else { return "Simpleforms notice: No form known by name '{$formname}'."; } // Set the mail configuration for empty fields to the global defaults if they exist foreach ($this->global_fields as $configkey) { if (!array_key_exists($configkey, $formconfig) && !empty($this->config[$configkey])) { $formconfig[$configkey] = $this->config[$configkey]; } elseif (!array_key_exists($configkey, $formconfig) && empty($this->config[$configkey])) { $formconfig[$configkey] = false; } } // tanslate labels if labels extension exists if ($this->labelsenabled) { $this->labelfields($formconfig); } if ($formconfig['debugmode'] == true) { \util::var_dump($formconfig); \util::var_dump($formname); \util::var_dump($this->app['paths']); } $message = ""; $error = ""; $sent = false; $form = $this->app['form.factory']->createBuilder('form', null, array('csrf_protection' => $this->config['csrf'])); foreach ($formconfig['fields'] as $name => $field) { $options = array(); if ($field['type'] == "ip" || $field['type'] == "timestamp") { // we're storing IP and timestamp later. continue; } if (!empty($field['label'])) { $options['label'] = $field['label']; } if (!empty($field['value'])) { $options['attr']['value'] = $field['value']; } if (!empty($field['allow_override']) && !empty($_GET[$name])) { $value = strip_tags($_GET[$name]); // Note Symfony's form also takes care of escaping this. $options['attr']['value'] = $value; } if (!empty($field['read_only'])) { $options['read_only'] = $field['read_only']; } if (!empty($field['placeholder'])) { $options['attr']['placeholder'] = $field['placeholder']; } if (!empty($field['class'])) { $options['attr']['class'] = $field['class']; } if (!empty($field['prefix'])) { $options['attr']['prefix'] = $field['prefix']; } if (!empty($field['postfix'])) { $options['attr']['postfix'] = $field['postfix']; } if (!empty($field['required']) && $field['required'] == true) { $options['required'] = true; $options['constraints'][] = new Assert\NotBlank(); } else { $options['required'] = false; } if (!empty($field['choices']) && is_array($field['choices'])) { // Make the keys more sensible. $options['choices'] = array(); foreach ($field['choices'] as $option) { $options['choices'][safeString($option)] = $option; } } if (!empty($field['expanded'])) { $options['expanded'] = $field['expanded']; } if (!empty($field['multiple'])) { $options['multiple'] = $field['multiple']; } // Make sure $field has a type, or the form will break. if (empty($field['type'])) { $field['type'] = "text"; } elseif ($field['type'] == "email") { // if the field is email, check for a valid email address $options['constraints'][] = new Assert\Email(); } elseif ($field['type'] == "file") { // if the field is file, make sure we set the accept properly. $accept = array(); // Don't accept _all_ types. If nothing set in config.yml, set some sensilbe defaults. if (empty($field['filetype'])) { $field['filetype'] = array('jpg', 'jpeg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx'); } foreach ($field['filetype'] as $ext) { $accept[] = "." . $ext; } $options['attr']['accept'] = implode(",", $accept); } // Yeah, this feels a bit flakey, but I'm not sure how I can get the form type in the template // in another way. $options['attr']['type'] = $field['type']; $form->add($name, $field['type'], $options); } $form = $form->getForm(); // Include the ReCaptcha PHP Library require_once 'recaptcha-php-1.11/recaptchalib.php'; if ('POST' == $this->app['request']->getMethod()) { $isRecaptchaValid = true; // to prevent recpatcha check if not enabled if ($this->config['recaptcha_enabled']) { $isRecaptchaValid = false; // by Default $resp = recaptcha_check_answer($this->config['recaptcha_private_key'], $this->getRemoteAddress(), $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); $isRecaptchaValid = $resp->is_valid; } if ($isRecaptchaValid) { $form->bind($this->app['request']); if ($form->isValid()) { $res = $this->processForm($formconfig, $form, $formname); if ($res) { $message = $formconfig['message_ok']; $sent = true; // If redirect_on_ok is set, redirect to that page when succesful. if (!empty($formconfig['redirect_on_ok'])) { $content = $this->app['storage']->getContent($formconfig['redirect_on_ok']); simpleredirect($content->link(), false); } } else { $error = $formconfig['message_technical']; } } else { $error = $formconfig['message_error']; } } else { $error = $this->config['recaptcha_error_message']; } } $formhtml = $this->app['render']->render($formconfig['template'], array("submit" => "Send", "form" => $form->createView(), "message" => $message, "error" => $error, "sent" => $sent, "formname" => $formname, "recaptcha_html" => $this->config['recaptcha_enabled'] ? recaptcha_get_html($this->config['recaptcha_public_key']) : '', "recaptcha_theme" => $this->config['recaptcha_enabled'] ? $this->config['recaptcha_theme'] : '', "button_text" => $formconfig['button_text'])); return new \Twig_Markup($formhtml, 'UTF-8'); }
/** * Create a simple Form. * * @param string $formname * @internal param string $name * @return string */ public function simpleForm($formname = "", $with = array()) { $this->app['twig.loader.filesystem']->addPath(__DIR__); // Select which form to use.. if (isset($this->config[$formname])) { $formconfig = $this->config[$formname]; } else { return "Simpleforms notice: No form known by name '{$formname}'."; } // Set the mail configuration for empty fields to the global defaults if they exist foreach ($this->global_fields as $configkey) { if (!array_key_exists($configkey, $formconfig) && !empty($this->config[$configkey])) { $formconfig[$configkey] = $this->config[$configkey]; } elseif (!array_key_exists($configkey, $formconfig) && empty($this->config[$configkey])) { $formconfig[$configkey] = false; } } // translate labels if labels extension exists if ($this->labelsenabled) { $this->labelfields($formconfig); } if ($formconfig['debugmode'] == true) { \Dumper::dump('Building ' . $formname); \Dumper::dump($formconfig); //\Dumper::dump($this->app['paths']); } $message = ""; $error = ""; $sent = false; $form = $this->app['form.factory']->createNamedBuilder($formname, 'form', null, array('csrf_protection' => $this->config['csrf'])); foreach ($formconfig['fields'] as $name => $field) { $options = $this->buildField($name, $field, $with); // only add known fields with options to the form if ($options) { $form->add($name, $options['attr']['type'], $options); } } $form = $form->getForm(); require_once 'recaptcha-php-1.11/recaptchalib.php'; if ('POST' == $this->app['request']->getMethod()) { if (!$this->app['request']->request->has($formname)) { // we're not submitting this particular form if ($formconfig['debugmode'] == true) { $error .= "we're not submitting this form: " . $formname; } $sent = false; } else { // ok we're really submitting this form $isRecaptchaValid = true; // to prevent ReCaptcha check if not enabled if ($this->config['recaptcha_enabled']) { $isRecaptchaValid = false; // by Default $resp = recaptcha_check_answer($this->config['recaptcha_private_key'], $this->getRemoteAddress(), $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); $isRecaptchaValid = $resp->is_valid; } if ($isRecaptchaValid) { $form->bind($this->app['request']); if ($form->isValid()) { $res = $this->processForm($formconfig, $form, $formname); if ($res) { $message = $formconfig['message_ok']; $sent = true; // If redirect_on_ok is set, redirect to that page when succesful. if (!empty($formconfig['redirect_on_ok'])) { $content = $this->app['storage']->getContent($formconfig['redirect_on_ok']); simpleredirect($content->link(), false); } } else { $error = $formconfig['message_technical']; } } else { $error = $formconfig['message_error']; } } else { $error = $this->config['recaptcha_error_message']; } } } $formhtml = $this->app['render']->render($formconfig['template'], array("submit" => "Send", "form" => $form->createView(), "message" => $message, "error" => $error, "sent" => $sent, "formname" => $formname, "recaptcha_html" => $this->config['recaptcha_enabled'] ? recaptcha_get_html($this->config['recaptcha_public_key']) : '', "recaptcha_theme" => $this->config['recaptcha_enabled'] ? $this->config['recaptcha_theme'] : '', "button_text" => $formconfig['button_text'])); return new \Twig_Markup($formhtml, 'UTF-8'); }