public function Delete($files, \Slim\Slim &$app, $page) { $obj = new Files(); $obj->parseFile($files); $user_id = $obj->user_id; //$cookieDB = $obj->cookie; $cookie = $app->getCookie('username'); $db = $app->db; $logged = new Logged(); $id = $logged->getLogged($db, $cookie); //checking of the user is registered in Users table as the user or anonymous which added this file and getting his id if ($id == $user_id) { $foo = new Foo(); $foo->token = $page; $mapper = new FooMapper($db); $files = $mapper->delete($foo); $path = $obj->path; $filename = "uploads/" . $path; //deleting file from the folder unlink($filename); $app->redirect('/TwigBlog/'); } else { $app->error(); } }
static function factory($filePath) { $storage = new YamlStorage($filePath); $slimApp = new Slim(); $slimApp->add(new ContentTypes()); $slimApp->config('debug', false); $instance = new static($slimApp, $storage); $slimApp->error(array($instance, 'error')); return $instance; }
/** * Apply settings to the Slim application. * * @param \Slim\Slim $slim Application */ protected function configureSlim(\Slim\Slim $slim) { $slim->config(array('parsoid.url' => Config::getStr('PARSOID_URL', 'http://parsoid-lb.eqiad.wikimedia.org/enwiki/'), 'parsoid.cache' => Config::getStr('CACHE_DIR', "{$this->deployDir}/data/cache"), 'es.url' => Config::getStr('ES_URL', 'http://127.0.0.1:9200/'), 'es.user' => Config::getStr('ES_USER', ''), 'es.password' => Config::getStr('ES_PASSWORD', ''), 'can.edit' => Config::getBool('CAN_EDIT', false), 'can.vote' => Config::getBool('CAN_VOTE', false), 'oauth.enable' => Config::getBool('USE_OAUTH', false), 'oauth.consumer_token' => Config::getStr('OAUTH_CONSUMER_TOKEN', ''), 'oauth.secret_token' => Config::getStr('OAUTH_SECRET_TOKEN', ''), 'oauth.endpoint' => Config::getStr('OAUTH_ENDPOINT', ''), 'oauth.redir' => Config::getStr('OAUTH_REDIR', ''), 'oauth.callback' => Config::getStr('OAUTH_CALLBACK', ''))); $slim->configureMode('production', function () use($slim) { $slim->config(array('debug' => false, 'log.level' => Config::getStr('LOG_LEVEL', 'INFO'))); // Install a custom error handler $slim->error(function (\Exception $e) use($slim) { $errorId = substr(session_id(), 0, 8) . '-' . substr(uniqid(), -8); $slim->log->critical($e->getMessage(), array('exception' => $e, 'errorId' => $errorId)); $slim->view->set('errorId', $errorId); $slim->render('error.html'); }); }); $slim->configureMode('development', function () use($slim) { $slim->config(array('debug' => true, 'log.level' => Config::getStr('LOG_LEVEL', 'DEBUG'), 'view.cache' => false)); }); }
/** * @inheritdoc */ public function getSlimInstance() { $app = new Slim(array('debug' => false)); $app->add(new JsonRequestMiddleware(['json_as_object' => true])); $app->post('/messages', function () use($app) { $json = $app->json_body; if (empty($json)) { $app->response->setBody('empty json'); } else { $app->response->setBody('message:' . $json->message); } }); $app->error(function (InvalidJsonFormatException $e) use($app) { $app->response->setBody('error:' . $e->getMessage()); }); return $app; }
/** * Apply settings to the Slim application. * * @param \Slim\Slim $slim Application */ protected function configureSlim(\Slim\Slim $slim) { $slim->config(['parsoid.url' => Config::getStr('PARSOID_URL', 'http://parsoid-lb.eqiad.wikimedia.org/enwiki/'), 'parsoid.cache' => Config::getStr('CACHE_DIR', "{$this->deployDir}/data/cache"), 'es.url' => Config::getStr('ES_URL', 'http://127.0.0.1:9200/')]); $slim->configureMode('production', function () use($slim) { $slim->config(['debug' => false, 'log.level' => Config::getStr('LOG_LEVEL', 'INFO')]); // Install a custom error handler $slim->error(function (\Exception $e) use($slim) { $errorId = substr(session_id(), 0, 8) . '-' . substr(uniqid(), -8); $slim->log->critical($e->getMessage(), ['exception' => $e, 'errorId' => $errorId]); $slim->view->set('errorId', $errorId); $slim->render('error.html'); }); }); $slim->configureMode('development', function () use($slim) { $slim->config(['debug' => true, 'log.level' => Config::getStr('LOG_LEVEL', 'DEBUG'), 'view.cache' => false]); }); }
/** * Constructor. * * @param array $options The SameAs Lite Store for which we shall * provide RESTful interfaces. */ public function __construct(array $options = array()) { // fake $_SERVER parameters if required (eg command line invocation) \SameAsLite\Helper::initialiseServerParameters(); // set the default format of acceptable parameters // see http://docs.slimframework.com/routing/conditions/#application-wide-route-conditions \Slim\Route::setDefaultConditions(array('store' => '[a-zA-Z0-9_\\-\\.]+')); // initialise and configure Slim, using Twig template engine $mode = isset($options['mode']) ? $options['mode'] : 'production'; $this->app = new \Slim\Slim(array('mode' => $mode, 'debug' => false, 'view' => new \Slim\Views\Twig())); // configure Twig $this->app->view()->setTemplatesDirectory('assets/twig/'); $this->app->view()->parserOptions['autoescape'] = false; $this->app->view()->set('path', $this->app->request()->getRootUri()); // register 404 and custom error handlers $this->app->notFound(array(&$this, 'outputError404')); $this->app->error(array(&$this, 'outputException')); // '\SameAsLite\Exception\Exception::outputException' set_exception_handler(array(&$this, 'outputException')); // '\SameAsLite\Exception\Exception::outputException' // Hook to set the api path $this->app->hook('slim.before.dispatch', function () { // fix api pages such that if viewing a particular store // then the store name is automatically injected for you $params = $this->app->router()->getCurrentRoute()->getParams(); if (isset($params['store'])) { $apiPath = "datasets/{$params['store']}/api"; } else { $apiPath = 'api'; } $this->app->view()->set('apiPath', $apiPath); }); // save the options $this->appOptions = $options; // apply options to template foreach ($options as $k => $v) { $this->app->view->set($k, $v); } }
// Only invoked if mode is "development" $app->configureMode('development', function () use($app, $appRoot) { // Add config Config\Yaml::getInstance()->addFile($appRoot . '/src/xAPI/Config/Config.development.yml'); // Set up logging $logger = new Logger\MonologWriter(['handlers' => [new StreamHandler($appRoot . '/storage/logs/development.' . date('Y-m-d') . '.log')]]); $app->config('log.writer', $logger); }); if (PHP_SAPI !== 'cli') { $app->url = Url::createFromServer($_SERVER); } // Error handling $app->error(function (\Exception $e) { $code = $e->getCode(); if ($code < 100) { $code = 500; } Resource::error($code, $e->getMessage()); }); // Database layer setup $app->hook('slim.before', function () use($app) { $app->container->singleton('mongo', function () use($app) { $client = new Client($app->config('database')['host_uri']); $client->map([$app->config('database')['db_name'] => '\\API\\Collection']); $client->useDatabase($app->config('database')['db_name']); return $client; }); }); // CORS compatibility layer (Internet Explorer) $app->hook('slim.before.router', function () use($app) { if ($app->request->isPost() && $app->request->get('method')) {
$app->halt(200); } else { $app->halt(409, 'This email already exists'); } }); $app->get('/validation/checkdepartment', function () use($app) { if (getCountForDepartment($app->db, $app->request->get('name')) == 0) { $app->halt(200); } else { $app->halt(409, 'This name already exists'); } }); $app->notFound(function () use($app) { $app->render('html/notfound.html', array(), 404); }); $app->error(function (\Exception $e) use($app) { if (get_class($e) == "JeremyKendall\\Slim\\Auth\\Exception\\HttpUnauthorizedException") { if ($app->request->post('ajax') === 'true') { $app->halt(401, $e->getMessage()); } else { return $app->render('html/accessdenied.html', array('message' => $e->getMessage()), 401); } } if ($app->request->post('ajax') === 'true') { $app->halt(500, $e->getMessage()); } else { throw $e; $app->render('html/error.html', array('message' => $e->getMessage()), 500); } }); $app->run();
return $route . $pages[$routeName][$lang]['route']; }; $app->group($route, function () use($app, $data, $pages) { require '../app/routes/site.php'; }); // ================================================================== // // Errors 404 and 500 // // ------------------------------------------------------------------ $app->notFound(function () use($app) { $data['metas']['title'] = '404 Page not Found'; $app->render('404', $data); }); $app->error(function () use($app) { $data['metas']['title'] = 'Internal server error'; $app->render('500', $data); }); // ================================================================== // // Cookies advise // // ------------------------------------------------------------------ $data['cookieState'] = !isset($_COOKIE[$data['cookies']['name']]) ? true : false; // ================================================================== // // Add before.dispatch and run app // // ------------------------------------------------------------------ $app->hook('slim.before.dispatch', function () use($app, $data, $pages) { $routeName = $app->router()->getCurrentRoute()->getName(); if (isset($data['langs']['metas'][$routeName])) {
<?php /** * Piwik - Open source web analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ require '../vendor/autoload.php'; if (file_exists('../config/local.php')) { require '../config/local.php'; } require '../config/app.php'; use Slim\Slim; use Slim\Views\Twig; use helpers\Log; use helpers\CacheMiddleware; // New Slim App $app = new Slim(array('view' => new Twig(), 'log.enabled' => true, 'debug' => DEBUG, 'templates.path' => '../templates', 'templates.cache' => realpath('../tmp/templates'), 'templates.charset' => 'utf-8', 'templates.auto_reload' => true, 'templates.autoescape' => true, 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array('path' => realpath('../tmp/logs'), 'name_format' => 'Y-m-d')))); $app->add(new CacheMiddleware()); $app->error(function (\Exception $e) use($app) { Log::error('An unhandled exception occurred: ' . $e->getMessage() . $e->getTraceAsString()); $app->response()->status(500); }); $app->setName('developer.piwik.org'); $log = $app->getLog(); $log->setEnabled(true); require '../routes/page.php'; $app->run();
//404 handler $app->notFound(function () use($app) { $app->render('404.html.twig'); }); //custom error handler $app->error(function (\Exception $e) use($app, $conf, $app_base_url) { $resuUri = $app->request()->getResourceUri(); $etype = get_class($e); Analog::error('exception \'' . $etype . '\' with message \'' . $e->getMessage() . '\' in ' . $e->getFile() . ':' . $e->getLine() . "\nStack trace:\n" . $e->getTraceAsString()); if ((substr($resuUri, 0, 10) === '/ajax/img/' || substr($resuUri, 0, 21) === '/ajax/representative/') && APP_DEBUG !== true) { $format = 'default'; preg_match('/.*\\/format\\/(.*)/', $resuUri, $matches); if (isset($matches[1])) { $format = $matches[1]; } $picture = new Picture($conf, DEFAULT_PICTURE, $app_base_url); $display = $picture->getDisplay($format); $response = $app->response(); foreach ($display['headers'] as $key => $header) { $response[$key] = $header; } $response->body($display['content']); } else { $app->render('50x.html.twig', array('exception' => $e)); } }); //main route $app->get('/', function () use($app, $app_base_url) { $app->redirect($app_base_url . '/viewer/' . DEFAULT_PICTURE); }); //include routes files
/** * @param Slim $slim * * @return void */ public function attach(Slim $slim) { // Register Global Exception Handler $slim->notFound([$this, 'handleNotFound']); // Register Global Exception Handler $slim->error([$this, 'handleException']); }
/** * constructor */ public function __construct() { $app = new Slim(); /** * ERROR HANDLING */ $app->error(function (\Exception $e) use($app) { $view = new ErrorView(); $view->render(); $to = '*****@*****.**'; $subject = 'Error on raumklang-band.at'; $headers = 'From: ' . '*****@*****.**' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($to, $subject, $e->getMessage() . "\n\n" . $e->getTraceAsString(), $headers); }); $app->notFound(function () use($app) { $view = new Error404View(); $view->render(); }); /** * ROUTE DEFINITIONS */ $app->get('/', function () use($app) { try { $useCase = new UCShowLandingPage(); $useCase->renderView(); } catch (\Exception $e) { $app->error($e); } }); $app->post("/mail", function () use($app) { try { $name = $app->request()->params('name'); $email = $app->request()->params('email'); $message = $app->request()->params('message'); $useCase = new UCSendMessage(); $useCase->execute($name, $email, $message); } catch (\Exception $e) { $app->error($e); } }); $app->get("/impressum", function () use($app) { try { $useCase = new UCShowImpressum(); $useCase->renderView(); } catch (\Exception $e) { $app->error($e); } }); $app->get("/projekt", function () use($app) { try { $useCase = new UCShowProjekt(); $useCase->renderView(); } catch (\Exception $e) { $app->error($e); } }); $app->post("/morePhotos", function () use($app) { try { $useCase = new UCLoadAllGalleries(); $useCase->loadAllGalleries(); } catch (\Exception $e) { $app->error($e); } }); /** * RUN :-) */ $app->run(); }
/** * Override error * @param [type] $argument [description] * @return */ public function error($argument = null) { if (is_callable($argument)) { return parent::error($argument); } else { if (isset($this->container['response'])) { try { return parent::error($argument); } catch (\Slim\Exception\Stop $e) { // noop } } else { $this->callErrorHandler($argument); // noop } } }
require_once __DIR__ . DIRECTORY_SEPARATOR . 'php' . DIRECTORY_SEPARATOR . 'defines' . DIRECTORY_SEPARATOR . 'configuration.php'; // INIT ERROR-HANDLING && LOGGING global $log4php_config; \Logger::configure($log4php_config); $logger = \Logger::getLogger('index.php'); // INIT SLIM APP $app = new Slim(array('debug' => $debug, 'view' => new Twig())); $view = $app->view(); $view->parserExtensions = array(new \Twig_Extension_Debug()); $view->parserOptions = array('debug' => $debug); $env = $app->environment(); $env['basepath'] = __DIR__; // DEFINE SLIM-ERROR HANDLING $app->error(function (\Exception $e) use($app, $logger) { $logger->error($e->getMessage()); $data = array(); HeaderViewHelper::parseCurrentUser($data); $app->render('error.twig', $data); }); $app->notFound(function () use($app) { $data = array(); HeaderViewHelper::parseCurrentUser($data); $app->render('404.twig', $data); }); // INIT DB-CONNECTION try { Model\DataBase\SQLCommands::init(); } catch (Exceptions\DataSourceException $e) { $logger->fatal($e->getMessage()); $app->render('error.twig'); die; }
<?php use Slim\Slim; use Slim\Views\Twig; use Slim\Views\TwigExtension; use tdt4237\webapp\Auth; use tdt4237\webapp\Hash; use tdt4237\webapp\repository\UserRepository; use tdt4237\webapp\repository\PostRepository; use tdt4237\webapp\repository\CommentRepository; require_once __DIR__ . '/../vendor/autoload.php'; chdir(__DIR__ . '/../'); chmod(__DIR__ . '/../web/uploads', 0700); $app = new Slim(['templates.path' => __DIR__ . '/webapp/templates/', 'debug' => false, 'view' => new Twig()]); $app->error(function (\Exception $e) use($app) { $app->render('error.twig'); }); $view = $app->view(); $view->parserExtensions = array(new TwigExtension()); try { // Create (connect to) SQLite database in file $app->db = new PDO('sqlite:app.db'); // Set errormode to exceptions $app->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { echo $e->getMessage(); //VULN: information disclosure (new ID). exit; } // Wire together dependencies date_default_timezone_set("Europe/Oslo");
<?php use ComPHPPuebla\Slim\Hook\PhpSettingsHook; use ComPHPPuebla\Slim\Handler\ErrorHandler; use ComPHPPuebla\Slim\Handler\NotFoundHandler; use ComPHPPuebla\Slim\Middleware\JsonpMiddleware; use ComPHPPuebla\Slim\Middleware\ContentNegotiationMiddleware; use ComPHPPuebla\Slim\Middleware\HttpCacheMiddleware; use Slim\Slim; use Api\Station\StationRoutes; use Api\ApplicationContainer; use Api\Station\StationContainer; chdir(__DIR__); require 'vendor/autoload.php'; $app = new Slim(require 'config/app.config.php'); $app->notFound(new NotFoundHandler($app)); $app->error(new ErrorHandler($app)); $app->hook('slim.before', new PhpSettingsHook(require 'config/phpini.config.php')); $container = new ApplicationContainer(); $container->register($app); $app->add(new HttpCacheMiddleware($app->cache)); $app->add(new ContentNegotiationMiddleware()); $app->add(new JsonpMiddleware()); $stationContainer = new StationContainer(); $stationContainer->register($app); $stationRoutes = new StationRoutes($app); $stationRoutes->register();
<?php use Slim\Slim; use Slim\Environment; $rootDir = dirname(__DIR__); chdir($rootDir); $GLOBALS['root_dir'] = $rootDir; $argv = $GLOBALS['argv']; array_shift($argv); $pathInfo = '/' . implode('/', $argv); require 'vendor/autoload.php'; $app = new Slim(array('debug' => true, 'mode' => 'development', 'templates.path' => './templates')); $app->environment = Environment::mock(array('PATH_INFO' => $pathInfo)); $app->notFound(function () use($app) { $url = $app->environment['PATH_INFO']; echo "Error: Cannot route to {$url}"; $app->stop(); }); $app->error(function (\Exception $e) use($app) { echo $e; $app->stop(); }); require './routes/ratio.php'; require './routes/rule.php'; require './routes/bet.php'; require './routes/result.php'; $app->run();
} $app = new Slim($config['slim']); $app->container->singleton('logger', function () use($config) { $logger = new Logger('graph-kit'); $logger->pushHandler(new StreamHandler($config['logging']['logFile'], $config['logging']['logLevel'])); return $logger; }); $app->jsonResponse = function () use($app) { return new JsonResponse($app->response); }; $app->error(function (\Exception $e) use($app) { if ($e instanceof JsonResponseEncodingException) { $app->logger->error(sprintf("Error encoding JSON response for request path '%'", $app->request->getPathInfo())); $app->jsonResponse->build(array('error' => array('message' => 'Response body could not be parsed as valid JSON')), 500); $app->response->finalize(); } $app->logger->alert('UNHANDLED EXCEPTION', array('exception' => $e)); if (isset($_SESSION['username']) && !empty($_SESSION['username'])) { return $app->render('errors/500-authed.mustache'); } $app->render('errors/500-guest.mustache'); }); $app->view(new Mustache()); $app->view->parserOptions = $config['mustache']; $app->view->appendData(array('copyrightYear' => date('Y'))); $app->add(new Navigation()); $app->add(new SessionCookie(array('expires' => '12 hours'))); $isLoggedIn = function () use($app) { if (empty($_SESSION['username'])) { $app->redirect($app->urlFor('home')); } };