public function testAdminNavigation() { \Slim\Environment::mock(array('SCRIPT_NAME' => '', 'PATH_INFO' => '/admin')); $app = new \Slim\Slim(); $app->view(new \Slim\View()); $app->get('/admin', function () { echo 'Success'; }); $auththenticationService = $this->getMock('Zend\\Authentication\\AuthenticationService'); $auththenticationService->expects($this->once())->method('hasIdentity')->will($this->returnValue(true)); $mw = new Navigation($auththenticationService); $mw->setApplication($app); $mw->setNextMiddleware($app); $mw->call(); $response = $app->response(); $navigation = $app->view()->getData('navigation'); $this->assertNotNull($navigation); $this->assertInternalType('array', $navigation); $this->assertEquals(4, count($navigation)); $this->assertEquals('Home', $navigation[0]['caption']); $this->assertEquals('/', $navigation[0]['href']); $this->assertEquals('', $navigation[0]['class']); $this->assertEquals('Admin', $navigation[1]['caption']); $this->assertEquals('/admin', $navigation[1]['href']); $this->assertEquals('active', $navigation[1]['class']); $this->assertEquals('Settings', $navigation[2]['caption']); $this->assertEquals('/admin/settings', $navigation[2]['href']); $this->assertEquals('', $navigation[2]['class']); $this->assertEquals('Logout', $navigation[3]['caption']); $this->assertEquals('/logout', $navigation[3]['href']); $this->assertEquals('', $navigation[3]['class']); }
/** * create slim app */ function create_app($name) { $app = new \Slim\Slim(array('templates.path' => ROOT . 'templates/', 'cookies.lifetime' => '2 days', 'cookies.secret_key' => 'livehubsecretkey')); $app->configureMode('development', function () use($app) { $app->config(array('debug' => true, 'log.enable' => true, 'log.level' => \Slim\Log::DEBUG, 'cookies.lifetime' => '2 days', 'cookies.secret_key' => 'livehubsecretkey')); }); $app->configureMode('production', function () use($app) { $app - config(array('log.level' => \Slim\Log::ERROR, 'cookies.lifetime' => '2 days', 'cookies.encrypt' => true, 'cookies.secret_key' => 'livehubsecretkey')); }); $app->container->singleton('log', function () use($name) { $log = new \Monolog\Logger($name); $log->pushHandler(new \Monolog\Handler\StreamHandler(ROOT . "logs/{$name}.log", \Monolog\Logger::DEBUG)); return $log; }); $app->view(new \Slim\Views\Twig()); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('templates/cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); $app->setName($name); return $app; }
<?php require_once __DIR__ . '\\vendor\\autoload.php'; //$log = new Monolog\Logger('name'); //$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::WARNING)); //$log->addWarning('Foo'); $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig())); $view = $app->view(); $view->parserOptions = array('debug' => true, 'cache' => dirname(__FILE__) . '/cache'); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); //dont ovveriden view /* $app = new \Slim\Slim(); */ //first example /* $app->get('/hello/:name', function ($name) { echo "Hello, $name"; }); */ $app->get('/', function () use($app) { $app->render('about.twig'); }); $app->get('/contact', function () use($app) { //DEBUG check it with name function $app->render('contact.twig'); }); $app->post('/contact', function () use($app) { $name = $app->request()->post('name'); $email = $app->request()->post('email'); $msg = $app->request()->post('msg');
'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'app_session_name', 'secret' => md5('appsecretkey'), 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC ))); */ /* * SET some globally available view data */ $resourceUri = $_SERVER['REQUEST_URI']; $rootUri = $app->request()->getRootUri(); $assetUri = $rootUri; $app->view()->appendData(array('app' => $app, 'rootUri' => $rootUri, 'assetUri' => $assetUri, 'resourceUri' => $resourceUri)); foreach (glob(ROOT . '/app/controllers/*.php') as $router) { include $router; } // Disable fluid mode in production environment $app->configureMode(SLIM_MODE_PRO, function () use($app) { // note, transactions will be auto-committed in fluid mode R::freeze(true); }); /* |-------------------------------------------------------------------------- | Configure Twig |-------------------------------------------------------------------------- | | The application uses Twig as its template engine. This script configures | the template paths and adds some extensions.
<?php function __autoload($class_name) { echo $class_name; if (file_exists(BASE_PATH . '_app/libraries/' . $class_name . '.php')) { include_once BASE_PATH . '_app/libraries/' . $class_name . '.php'; } } require_once BASE_PATH . '_app/function.php'; require_once BASE_PATH . '_app/model.php'; require_once BASE_PATH . '_app/libraries/Yacms.php'; require_once BASE_PATH . '_app/libraries/Tiny.php'; $app = new \Slim\Slim(); $app->config = Yacms::loadConfigs(); foreach ($app->config as $key => $value) { $app->config($key, $value); } $template_engine = $app->config['template_engine']; if (file_exists(BASE_PATH . '/_app/libraries/template_engine/' . $template_engine . '.php')) { require_once BASE_PATH . '/_app/libraries/template_engine/' . $template_engine . '.php'; } $app->view(new $template_engine()); $app->add(new \Zeuxisoo\Whoops\Provider\Slim\WhoopsMiddleware()); $app->add(new \Slim\Middleware\SessionCookie(array('expires' => $app->config['cookies.lifetime'], 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'session', 'secret' => $app->config['session_secret'], 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC))); $app->model = new DB(); require_once __DIR__ . '/admin_routes.php'; require_once __DIR__ . '/routes.php'; return $app;
// ========== COMPOSER ========== require ROOT_PATH . '/vendor/autoload.php'; // ========== CONFIGURATION ========== $config = (require APP_PATH . '/src/config.php'); // ========== PHP (from configuration) ========== // time zone date_default_timezone_set($config['PHP']['default_timezone']); // errors ini_set('display_errors', $config['PHP']['display_errors']); ini_set('display_startup_errors', $config['PHP']['display_startup_errors']); ini_set('log_errors', $config['PHP']['log_errors']); // session if (true === $config['PHP']['need_session']) { session_cache_limiter(false); session_set_cookie_params(0, '/', '', $config['PHP']['session_cookie_secure'], true); session_start(); } unset($config['PHP']); // ========== SLIM ========== $app = new \Slim\Slim($config['Slim']); $app->config('app', $config['App']); $app->view()->setData('config', $app->config('app')); require APP_PATH . '/src/dependencies.php'; require APP_PATH . '/src/middlewares.php'; require APP_PATH . '/src/routes.php'; // Error handler $app->error(function (\Exception $e) use($app) { $app->getLog()->error($e); $app->render('errors/error.twig'); }); $app->run();
R::setup('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD); R::freeze(DB_FREEZE); // Slim app instance $app = new \Slim\Slim(['view' => new EnhancedView()]); // Slim Config $app->config(['templates.path' => 'app/views', 'debug' => APP_DEBUG]); // Add support for JSON posts $app->add(new \Slim\Middleware\ContentTypes()); // JSON view function function APIrequest() { $app = \Slim\Slim::getInstance(); $app->view(new \JsonView()); $app->view->clear(); } // Set webroot for portable $app->hook('slim.before', function () use($app) { $app->wroot = $app->request->getUrl() . $app->request->getRootUri(); $app->view()->appendData(['wroot' => $app->wroot]); }); // Load routes $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(dirname(__FILE__) . '/routes/')); foreach ($iterator as $file) { $fname = $file->getFilename(); if (preg_match('%\\.php$%', $fname)) { require $file->getPathname(); } } // Errors require 'sys/errors.php'; $app->run();
<?php /** * @author: Sohel Rana * @URI: http://sohelrana.me */ define('APP_DIR', __DIR__ . DIRECTORY_SEPARATOR); mb_internal_encoding('UTF-8'); mb_http_output('UTF-8'); date_default_timezone_set('Asia/Dhaka'); session_start(); require APP_DIR . 'vendor/autoload.php'; use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule(); $capsule->addConnection(['driver' => 'mysql', 'host' => 'localhost', 'database' => 'bbund', 'username' => 'root', 'password' => 'ltqpsmr7', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '']); use Illuminate\Events\Dispatcher; use Illuminate\Container\Container; $capsule->setEventDispatcher(new Dispatcher(new Container())); $capsule->setAsGlobal(); $capsule->bootEloquent(); $app = new \Slim\Slim(array('templates.path' => APP_DIR . 'templates')); $app->view()->setData(array('title' => 'Bbund'));
<?php require 'vendor/autoload.php'; $app = new \Slim\Slim(array('debug' => true, 'templates.path' => './controllers')); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('./cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $header = array('file' => 'header.php', 'params' => array("title" => "!Bangs", "description" => "Add the !Bang effect to your favourite search engine!", "content" => "")); $favicon = '<link rel="icon" type="image/png" href="https://www.google.com/s2/favicons?domain=http://duckduckgo.com"/>'; $domain = 'https://bangs.bonduel.net/'; $app->hook('slim.before', function () use($app, $domain) { $app->view()->appendData(array('baseUrl' => '')); $app->view()->appendData(array('domain' => $domain)); }); $app->post('/', function () use($app, $header) { $ddgSuggestion = $app->request->post('ddgSuggestions') == "on" ? true : false; $app->render('generate.php', array('app' => $app, 'type' => $app->request->post('type'), 'ddgSuggestion' => $ddgSuggestion, 'content' => $app->request->post('content'), 'header' => $header)); }); $app->get('/', function () use($app, $header, $favicon, $domain) { if (!isset($_SERVER['HTTPS']) || empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'off') { header("HTTP/1.1 301 Moved Permanently"); header("Location: " . $domain); die; } $header['params']['content'] .= $favicon; $app->render('template.php', array('app' => $app, 'content' => array('nav' => 'home', 'file' => 'forms.php', 'params' => array()), 'header' => $header)); }); $app->get('/su/:url', function ($url) use($app, $header, $favicon) { $header['params']['content'] .= $favicon; $app->render('template.php', array('app' => $app, 'content' => array('nav' => 'home', 'file' => 'forms.php', 'params' => array('url' => htmlspecialchars($url, ENT_QUOTES, 'UTF-8'))), 'header' => $header)); }); $app->get('/about', function () use($app, $header, $favicon) { $header['params']['content'] .= $favicon;
<?php // start setup require "../vendor/autoload.php"; spl_autoload_register(function ($classname) { include __DIR__ . "/../lib/" . $classname . ".php"; }); $app = new \Slim\Slim(); $container = new \Pimple\Container(); $container['db'] = function ($c) { return new PDO("mysql:host=localhost;dbname=joindin", "joindin", "joindin"); }; $app->config('container', $container); // end setup // start view setup $app->view(new View()); $app->response->headers->set("Content-Type", "application/json"); // end view setup // start events list $app->get('/events', function () use($app) { $db = $app->config('container')['db']; $data = array(); $model = new EventModel($db); $data['events'] = $model->getSomeEvents(); $app->render("foo.php", array("mydata" => $data)); }); // end events list // start one event $app->get('/events/:event_id', function ($event_id) use($app) { $db = $app->config('container')['db']; $data = array();
$app->redirect('welcome'); } } }); // LOGIN FOR ANONS $app->get('/login/anon', function () use($app, $Validator, $Miner) { $_SESSION["UserId"] = 1; $_SESSION["UserType"] = 1; $_SESSION["Activo"] = 1; $_SESSION["UserName"] = '******'; $app->redirect('../welcome'); }); // WELCOME PAGE $app->get('/welcome', function () use($app, $Validator, $Miner) { $users = $Miner->getUserList(array('UserId' => $_SESSION["UserId"])); $app->view()->setData(array('Tipo' => $_SESSION["UserType"], 'Activo' => $_SESSION["Activo"], 'UserName' => $_SESSION["UserName"], 'users' => $users)); $app->render('welcome.php'); }); // ADMIN PANEL $app->get('/admin/', function () use($app, $Validator, $Miner) { if ($_SESSION["UserId"] && $_SESSION["UserType"] == 2) { $data['UserId'] = 1; // Exclude anon $app->view()->setData(array('users' => $Miner->getUserList($data))); $app->render('admin.php'); } }); $app->get('/admin/enable/:id', function ($id) use($app, $Validator, $Miner) { if ($_SESSION["UserId"] && $_SESSION["UserType"] == 2) { if ($Validator->isNumeric($id)) { $data['UserId'] = $id;
use RedBeanPHP\Facade as R; // Load Config require 'app/config.php'; // Autoload require 'vendor/autoload.php'; // RedBeanPHP setup R::setup('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD); R::freeze(DB_FREEZE); // Slim app instance $app = new \Slim\Slim(); // Slim Config $app->config(['templates.path' => 'app/views', 'debug' => APP_DEBUG]); // Set webroot for portable $app->hook('slim.before', function () use($app) { $app->wroot = $app->request->getUrl() . $app->request->getRootUri(); $app->view()->appendData(array('wroot' => $app->wroot)); }); // HybridAuth instance $app->container->singleton('hybridInstance', function ($app) { $config = ["base_url" => $app->wroot . "/cb", "providers" => ["Facebook" => ["enabled" => true, "keys" => ["id" => FB_ID, "secret" => FB_SECRET], "scope" => "email, user_about_me, user_birthday, user_location", "trustForwarded" => false], "Twitter" => ["enabled" => true, "keys" => ["key" => TW_KEY, "secret" => TW_SECRET]]], "debug_mode" => HYBRIDAUTH_DEBUG_MODE, "debug_file" => HYBRIDAUTH_DEBUG_FILE]; $instance = new Hybrid_Auth($config); return $instance; }); // Auth Check $authenticate = function ($app) { return function () use($app) { $app->hybridInstance; $u_ses = Hybrid_Auth::storage()->get('user'); if (is_null($u_ses) && $app->request()->getPathInfo() != '/login/') { $app->redirect($app->wroot . '/login/'); }
}; $checkclaim = function ($app) { return function () use($app) { global $dispenseTime, $recaptchaPub; $address = $_SESSION['address']; $ip = getIP(); $sql = "SELECT dispensed FROM dispenses WHERE email='{$address}' OR ip='{$ip}' "; $sql .= "ORDER BY id DESC LIMIT 1"; $lastclaim_query = sql_query($sql); $canclaim = true; if ($lastclaim_query->num_rows) { $lastclaim = fetch_one($lastclaim_query); $lastclaim = strtotime($lastclaim); if ($lastclaim + $dispenseTime > time()) { $canclaim = false; $app->view()->setData('nextclaim', relative_time($lastclaim + $dispenseTime)); } } $app->view()->setData('canclaim', $canclaim); if ($canclaim) { $app->view()->setData('recaptcha', recaptcha_get_html($recaptchaPub)); } }; }; $app->hook('slim.before.dispatch', function () use($app) { global $siteName, $squareAds, $textAds, $bannerAds, $rewards, $links; global $cashout; $address = null; if (isset($_SESSION['address'])) { $address = $_SESSION['address']; }
<?php require 'vendor/autoload.php'; require 'lib/idiorm.php'; require 'config.php'; $pdf_enable = file_exists($WKHTMLTOPDF_BIN_PATH) ? TRUE : FALSE; define('PROJECT_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR); define('WKHTMLTOPDF_BIN_PATH', $WKHTMLTOPDF_BIN_PATH); define('PDF_ENABLE', $pdf_enable); ORM::configure("mysql:dbname={$DB_NAME};host={$DB_HOST}"); ORM::configure('username', $DB_USER); ORM::configure('password', $DB_PASS); ORM::configure('driver_options', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); ORM::configure('id_column_overrides', array('customer' => 'customer_id', 'quotation' => 'quotation_id', 'option' => 'option_id')); $app = new \Slim\Slim(array('mode' => 'production', 'debug' => false, 'log.enable' => true, 'templates.path' => 'tpl')); \Slim\Extras\Views\Twig::$twigOptions = array('charset' => 'utf-8', 'cache' => realpath('./tpl_cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view(new \Slim\Extras\Views\Twig()); require 'app.php'; $app->run();
<?php require '../vendor/autoload.php'; $config = (require_once __DIR__ . '/../config.php'); use Slim\Views\Twig; use Slim\Views\TwigExtension; // Prepare app $app = new Slim\Slim($config['slim']); // Prepare view $app->view(new Twig()); $app->view->parserOptions = $config['twig']; $app->view->parserExtensions = array(new TwigExtension()); // Define routes $app->get('/', function () use($app) { $app->render('index.html'); }); // Run app $app->run();
<?php error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED); require 'vendor/autoload.php'; $db = new PDO('sqlite:db.sqlite3'); $app = new \Slim\Slim(); $app->view(new \JsonApiView()); $app->add(new \JsonApiMiddleware()); define('secret', 'secret'); $app->add(new \Slim\Middleware\JwtAuthentication(array('secure' => false, 'path' => '/api/members', 'secret' => constant('secret')))); $app->config('debug', false); $app->get('/', function () use($app) { $app->render(200, array('msg' => 'Welcome to Jom Web Johor!')); }); $app->get('/jwj', function () use($app) { $key = constant('secret'); $token = array("facebook" => "https://facebook.com/groups/jomwebjohor", "github" => "https://github.com/jomwebjohor"); $jwt = JWT::encode($token, $key); $app->render(200, array('token' => $jwt)); }); $app->get('/api', function () use($app) { $app->render(200, array('msg' => 'Welcome to my json API!')); }); $app->get('/api/members', function () use($app, $db) { // Return all members $members = $db->query("SELECT * FROM members;")->fetchAll(PDO::FETCH_CLASS); if ($members) { $app->response->setStatus(200); $app->response->headers->set('Content-Type', 'application/json'); $app->response->setBody(json_encode($members)); } else {
//-- définition du user if (isset($_POST["login"]) && !isset($_GET["login"])) { $_SESSION["loginUsr"] = $_POST["login"]; } elseif (isset($_GET["login"]) && !isset($_POST["login"])) { $_SESSION["loginUsr"] = $_GET["login"]; } \fbx\Fab\Utilisateur::init(); putenv("LC_MESSAGES=" . $language); setlocale(LC_MESSAGES, $language . ".utf8"); if (function_exists('bindtextdomain') && function_exists('textdomain')) { bindtextdomain("messages", APPLICATION_ROOT . "/locale"); textdomain("messages"); bind_textdomain_codeset("messages", "UTF-8"); } $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => '../templates')); $twig = $app->view(); $twig->parserOptions = array('debug' => true); $twig->parserExtensions = array(new Twig_Extensions_Extension_I18n(), new Twig_Extension_Debug()); if (!isset($_GET["async"])) { $app->render("head.twig"); } $app->get('/', function () use($app) { $controller = new \fbx\Fab\Controller(""); if ($controller->getNavBar() != "") { $app->render($controller->getNavBar()); } $app->render($controller->getTemplate()); $app->render("foot.twig"); }); $app->get('/:name', function ($name) use($app) { $controller = new \fbx\Fab\Controller($name, $_GET);
date_default_timezone_set('Europe/Paris'); # enable in development mode: #error_reporting(E_ALL); # get hostname from request if possible - or define your own $serverName = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; define('DOMAIN', str_replace('www.', '', $serverName)); // URI-Redirector Prefix (leave empty for direct links) define('URI_REDIRECT_PREFIX', "http://www.redirect.am/?"); // --- end of CONFIG // setup slim & twig $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => 'app/templates', 'slim.url_scheme' => 'https')); $app->error(function (\Exception $e) use($app) { error_log($e->getMessage()); $app->callErrorHandler($e); }); $app->view()->parserOptions = array('cache' => __DIR__ . '/cache'); $app->view()->parserExtensions = array(new \Slim\Views\TwigExtension(), new DisposableEmail\AutoLinkTwigExtension()); // add html2Text filter $app->view()->getInstance()->addFilter(new Twig_SimpleFilter('html2Text', function ($string) { $convert = new \Html2Text\Html2Text($string); return $convert->get_text(); })); // redirect to random address $app->get('/', function () use($app) { $wordLength = rand(3, 8); $container = new PronounceableWord_DependencyInjectionContainer(); $generator = $container->getGenerator(); $word = $generator->generateWordOfGivenLength($wordLength); $nr = rand(51, 91); $name = $word . $nr; $app->redirect($app->urlFor('read', array('name' => $name)));
<?php chdir(__DIR__ . '/../../../'); ini_set('session.use_cookies', 0); require 'vendor/autoload.php'; \Caco\MiniAR::setDefaultPdo($pdo = new \PDO('sqlite:database/app.sqlite3')); $pdo->exec('PRAGMA foreign_keys = ON'); $app = new \Slim\Slim(); $app->view(new \Caco\Slim\JsonView()); $app->add($auth = new \Caco\Slim\Auth\Basic()); $auth->setRealm('Caco Cloud'); $app->group('/password', function () use($app) { $app->get('/:key/:id', '\\Caco\\Password\\REST:one')->conditions(['id' => '\\d+']); $app->get('/:key', '\\Caco\\Password\\REST:all'); $app->post('/:key', '\\Caco\\Password\\REST:add'); $app->delete('/:key/:id', '\\Caco\\Password\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:key/:id', '\\Caco\\Password\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/bookmark', function () use($app) { $app->get('/:id', '\\Caco\\Bookmark\\REST:one')->conditions(['id' => '\\d+']); $app->get('', '\\Caco\\Bookmark\\REST:all'); $app->post('', '\\Caco\\Bookmark\\REST:add'); $app->delete('/:id', '\\Caco\\Bookmark\\REST:delete')->conditions(['id' => '\\d+']); $app->put('/:id', '\\Caco\\Bookmark\\REST:edit')->conditions(['id' => '\\d+']); }); $app->group('/config', function () use($app) { $app->get('/:key', '\\Caco\\Config\\REST:one'); $app->get('', '\\Caco\\Config\\REST:all'); $app->post('', '\\Caco\\Config\\REST:add'); $app->delete('/:key', '\\Caco\\Config\\REST:delete'); $app->put('/:key', '\\Caco\\Config\\REST:edit');
// Twig i18n config \Slim\Extras\Views\Twig::$twigExtensions = array('Twig_Extensions_Extension_I18n'); $locality = $site_cfg['website']['i18n']; // locality should be determined here require_once APP_PATH . 'config/locales.php'; // Setup $app $app = new \Slim\Slim(array('templates.path' => APP_PATH . 'views/' . $site_cfg['website']['theme'] . '/', 'locales.path' => APP_PATH . 'i18n/', 'debug' => true, 'view' => new \Slim\Extras\Views\Twig(), 'log.enabled' => false, 'log.writer' => new \Slim\Extras\Log\DateTimeFileWriter(array('path' => ROOT_PATH . 'logs', 'name_format' => 'Y-m-d', 'message_format' => '%label% - %date% - %message%')))); // Cookie $app->add(new \Slim\Middleware\SessionCookie(array('expires' => '40 minutes', 'path' => '/', 'domain' => 'slim', 'secure' => false, 'httponly' => false, 'encrypt' => false, 'name' => 'slimblog', 'secret' => md5($site_cfg['website']['secret'])))); // Authenticate $app->add(new \SlimBasicAuth('', 'admin')); $app->add(new \CsrfGuard()); // Set our app name $app->setName($site_cfg['website']['name']); // Template Globals $twig = $app->view()->getEnvironment(); $twig->addGlobal('SITE_NAME', $site_cfg['website']['name']); $twig->addGlobal('SITE_VER', $site_cfg['website']['version']); $twig->addGlobal('SITE_AUTHOR', $site_cfg['website']['author']); $twig->addGlobal('LICENCE', $site_cfg['website']['licence']); $twig->addGlobal('LICENCE_URL', $site_cfg['website']['licence_url']); if (isset($site_cfg['website']['ua_id']) && !empty($site_cfg['website']['ua_id'])) { $twig->addGlobal('GOOGLE_UA_ID', $site_cfg['website']['ua_id']); } // Load Controllers if (!is_dir(APP_PATH . 'controllers/')) { throw new Exception('Invalid controller path: ' . APP_PATH . 'controllers/'); } if ($cdh = opendir(APP_PATH . 'controllers')) { while (false !== ($file = readdir($cdh))) { if ($file != "." && $file != "..") {
$app->container->singleton('install.license', function () use($app) { /** @var \Shopware\Recovery\Install\Database $database */ $database = $app->container->get('install.database'); if (!$database->setDatabase()) { throw new \Exception($database->getError()); } $pdo = $database->getDatabase(); $license = new \Shopware\Recovery\Install\License($pdo); return $license; }); $app->config('install.configuration', new \Shopware\Recovery\Install\Configuration()); $app->config('install.requirements', new \Shopware\Recovery\Install\Requirements(__DIR__ . '/../data/System.xml')); $app->config('install.requirementsPath', new \Shopware\Recovery\Install\RequirementsPath(SW_PATH, __DIR__ . '/../data/Path.xml')); $app->config('install.language', $selectedLanguage); // Set global variables $app->view()->setData("selectedLanguage", $selectedLanguage); $app->view()->setData("language", $language); $app->view()->setData("baseUrl", Utils::getBaseUrl($app)); $app->view()->setData("app", $app); $app->view()->setData("error", false); $app->view()->setData("parameters", $_SESSION["parameters"]); $app->error(function (Exception $e) use($app) { if (!$app->request()->isAjax()) { throw $e; } $response = $app->response(); $data = array('code' => $e->getCode(), 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString()); $response['Content-Type'] = 'application/json'; $response->body(json_encode($data)); }); // Step 1: Select language
//Acces DB $user = '******'; $pass = '******'; $dbname = 'BelVins'; //$db = new PDO('mysql:host=localhost;dbname=' . $dbname, $user, $pass); //REDBEAN define('LIB_PATH', __DIR__ . '../../RedBean/'); require LIB_PATH . 'rb.php'; R::setup('mysql:host=localhost;dbname=' . $dbname, $user, $pass); //Twig // Create app $app = new \Slim\Slim(['view' => new \Slim\Views\Twig(), 'templates.path' => '../templates']); $app->get('/', function () use($app) { $pageTitle = 'hello world'; $body = 'sup world'; $app->view()->setData(array('title' => $pageTitle, 'body' => $body)); $app->render('index.html'); }); //Routing $app->get('/contact/:name', function ($name) use($app) { $app->render('contact.php', compact('name')); })->name('contact'); //Page de formulaire d'ajout $app->get('/form', function () use($app) { $app->render('form.php', compact('app')); })->name('formAjoutVins'); //Chercher tout les vins $app->get('/api/wine', function () use($app, $db) { $donneeJSON = R::findAll('wine'); R::close(); $app->render('listing.html', compact('donneeJSON'));
* its default settings. However, you will usually configure * your Slim application now by passing an associative array * of setting names and values into the application constructor. */ $app = new \Slim\Slim(); /** * Step 3: Define the Slim application routes * * Here we define several Slim application routes that respond * to appropriate HTTP request methods. In this example, the second * argument for `Slim::get`, `Slim::post`, `Slim::put`, `Slim::patch`, and `Slim::delete` * is an anonymous function. */ $app->get('/', function () use($app) { $posts = \Slim\DB::getInstance()->select()->from('post')->orderBy('created', 'desc')->execute()->fetchAll(PDO::FETCH_OBJ); $app->view('Slim\\View\\Layout'); $app->render('index.php', ['posts' => $posts]); })->name('home'); $app->get('/post/:id', function ($id) use($app) { $posts = \Slim\DB::getInstance()->select()->from('post')->where('id', '=', $id)->orderBy('created', 'desc')->execute()->fetchAll(PDO::FETCH_OBJ); if ($posts) { $app->view('Slim\\View\\Layout'); $app->render('post.php', ['post' => $posts[0]]); } else { $app->notFound(); } })->name('post'); /* Admin area*/ $app->get('/admin', 'Slim\\Admin:indexAction')->name('admin-home'); $app->get('/admin/new', 'Slim\\Admin:newAction')->name('post-new'); $app->post('/admin/save', 'Slim\\Admin:saveAction')->name('post-save');
<?php require_once dirname(__FILE__) . '/../vendor/autoload.php'; $app = new \Slim\Slim(array('debug' => true, 'log.level' => \Slim\Log::DEBUG, 'templates.path' => '../app/view')); $app->view()->appendData(array('baseUrl' => '/~clientelp/')); $app->get('/hello/:name', 'Controller\\Foo:bar'); $app->get('/', 'Controller\\IndexController:indexAction'); $app->get('/cadastroareas', 'Controller\\IndexController:cadastroAreaAction'); $app->get('/cadastroequipamentos', 'Controller\\IndexController:cadastroEquipamentoAction'); $app->get('/cadastrousuarios', 'Controller\\IndexController:cadastroUsuarioAction'); $app->get('/api/v1/areas', 'Controller\\AreaController:listAreasAction'); $app->get('/api/v1/areas/filter', 'Controller\\AreaController:filterAreasAction'); $app->get('/api/v1/areas/:id', 'Controller\\AreaController:getAreaAction')->name('area_by_id'); $app->post('/api/v1/areas', 'Controller\\AreaController:postAreaAction')->name('post_area'); $app->put('/api/v1/areas/:id', 'Controller\\AreaController:putAreaAction')->name('put_area'); $app->delete('/api/v1/areas/:id', 'Controller\\AreaController:deleteAreaAction')->name('delete_area'); $app->get('/api/v1/users', 'Controller\\UserController:listAction'); $app->get('/api/v1/users/:id', 'Controller\\UserController:getAction')->name('user_by_id'); $app->post('/api/v1/users', 'Controller\\UserController:postAction')->name('post_user'); $app->put('/api/v1/users', 'Controller\\UserController:putAction')->name('put_user'); $app->delete('/api/v1/users/:id', 'Controller\\UserController:deleteAction')->name('delete_user'); $app->get('/api/v1/equipments', 'Controller\\EquipmentController:listEquipmentsAction'); $app->get('/api/v1/equipments/area/:id', 'Controller\\EquipmentController:listEquipmentsByAreaIdAction')->name('equipments_by_area_id'); $app->get('/api/v1/equipments/:id', 'Controller\\EquipmentController:getEquipmentAction')->name('equipment_by_id'); $app->post('/api/v1/equipments', 'Controller\\EquipmentController:postEquipmentAction')->name('post_equipment'); $app->put('/api/v1/equipments', 'Controller\\EquipmentController:putEquipmentAction')->name('put_equipment'); $app->delete('/api/v1/equipments/:id', 'Controller\\EquipmentController:deleteEquipmentAction')->name('delete_equipment'); $app->get('/api/v1/equipments/:equipmentId/events', 'Controller\\EventController:listEventByEquipmentIdAction')->name('list_events_by_equipment_id'); $app->get('/api/v1/events/:id', 'Controller\\EventController:getEventAction')->name('list_events_by_id'); /* $app->get('/api/v1/brands', 'Controller\BrandController:listBrandsAction'); * $app->get('/api/v1/brands/:id', 'Controller\BrandController:getBrandAction')->name('brand_by_id');
<?php require_once __DIR__ . '/../vendor/autoload.php'; // Prepare app $app = new \Slim\Slim(array('templates.path' => '../app/templates')); // Create monolog logger and store logger in container as singleton $app->container->singleton('log', function () { $log = new \Monolog\Logger('Phexecute'); $log->pushHandler(new \Monolog\Handler\StreamHandler('../logs/app.log', \Monolog\Logger::DEBUG)); return $log; }); // Prepare view $app->view(new \Slim\Views\Twig()); $app->view->parserOptions = array('charset' => 'utf-8', 'cache' => realpath('../app/templates/cache'), 'auto_reload' => true, 'strict_variables' => false, 'autoescape' => true); $app->view->parserExtensions = array(new \Slim\Views\TwigExtension()); // Define routes $app->get('/', function () use($app) { $systemDir = __DIR__ . '/../storage/data/system'; $snippetsDir = __DIR__ . '/../storage/data/snippets'; $packageDir = __DIR__ . '/../storage/data/packages'; $systemFiles = glob($systemDir . '/*.txt'); $snippetFiles = glob($snippetsDir . '/*.txt'); $packageFiles = glob($packageDir . '/*.txt'); $data['system_entries'] = buildMenu($systemFiles); $data['snippet_entries'] = buildMenu($snippetFiles); $data['package_entries'] = buildMenu($packageFiles); $app->render('home.twig', $data); }); function buildMenu($files) { $menu = array();
require 'vendor/autoload.php'; $app = new \Slim\Slim(); // ActiveRecord\Config::initialize(function($cfg){ // $cfg->set_model_directory('models'); // $cfg->set_connections(array( // 'development' => 'mysql://*****:*****@localhost/kampus')); // }); $app->get('/', function () { echo 'Hello Slim :)'; }); $app->get('/halo(/:nama)', function ($nama = null) { echo "Hallo " . $nama . "!"; }); $app->get('/home(/:nama)', function ($nama = null) use($app) { $app->view()->appendData(array('nama' => $nama)); $app->render("home.php"); }); $app->get('/show', function () use($app) { // with activerecord // $data = Mahasiswa::all(); // echo json_encode(array_map(function($res){ // return $res->to_array(); // },$data)); // // with elequent echo Mahasiswa::all()->toJson(); }); $app->post('/insert', function () use($app) { $mhs = new Mahasiswa(); $mhs->nama = $app->request->post('nama');
/** * Test view data is transferred to newer view */ public function testViewDataTransfer() { $data = array('foo' => 'bar'); $s = new \Slim\Slim(); $s->view()->setData($data); $s->view('CustomView'); $this->assertSame($data, $s->view()->getData()); }
$app->post('/oauth/token', function () use($server) { $response = $server->handleTokenRequest(OAuth2\Request::createFromGlobals()); if ($response->getStatusCode() == 200) { $code = $_POST['code']; $responseJson = json_decode($response->getResponseBody()); $hash = DB::queryFirstField("SELECT hash FROM authorization_codes_map WHERE authorization_code = '{$code}'"); $hash = \Aums\Encryption::encode(\Aums\Encryption::decode($hash, $code), $responseJson->access_token); DB::insert('access_tokens_map', ['access_token' => $responseJson->access_token, 'hash' => $hash]); $response->send(); } }); $app->get('/oauth/authorize', function () use($app, $server) { $request = OAuth2\Request::createFromGlobals(); $response = new OAuth2\Response(); if (!$server->validateAuthorizeRequest($request, $response)) { $app->view()->setData(['response' => json_decode($response->getResponseBody())]); $app->render('error.php'); } else { $appName = DB::queryFirstField('SELECT client_app_name FROM oauth_clients WHERE client_id = %s', $_GET['client_id']); $app->view()->setData(['app_name' => $appName, 'error' => isset($_GET['auth_error']) && $_GET['auth_error'] == 'incorrect' ? true : false]); $app->render('authorization_page.php'); } }); $app->post('/oauth/authorize', function () use($app, $server) { $request = OAuth2\Request::createFromGlobals(); $response = new OAuth2\Response(); if (!$server->validateAuthorizeRequest($request, $response)) { $app->view()->setData(['response' => json_decode($response->getResponseBody())]); $app->render('error.php'); } else { $api = new \Aums\API(trim($_POST['username']), trim($_POST['password']));
require '../../lib/util.php'; require '../../lib/command.php'; require '../../lib/Classes/Config.php'; $slim = new \Slim\Slim(array('debug' => true, 'view' => new \Slim\Views\Twig())); // $slim->add(new \Slim\Middleware\SessionCookie(array( // 'expires' => false, // 'path' => '/', // 'domain' => null, // 'httponly' => false, // 'name' => 'wfm-session', // 'cookies.encrypt' => true, // 'secret' => "123123", //$settings['auth_secret'], // 'cipher' => MCRYPT_RIJNDAEL_256, // 'cipher_mode' => MCRYPT_MODE_CBC // ))); $view = $slim->view(); $view->parserOptions = array('debug' => true); $view->parserExtensions = array(new \Slim\Views\TwigExtension()); /** Root URL */ $slim->put('/', function () use($slim) { $body = $slim->request->getBody(); if (!isset($body) || strlen($body) == 0) { $app->response()->status(401); // not authorised } else { $plist = new \CFPropertyList\CFPropertyList(); $plist->parse($body); $message = $plist->toArray(); $udid = $message["UDID"];
<?php require __DIR__ . '/vendor/autoload.php'; $app = new \Slim\Slim(array('view' => new \Slim\Views\Twig(), 'templates.path' => __DIR__ . '/views')); $app->view()->parserOptions = array('debug' => true, 'cache' => __DIR__ . '/tmp/compiled'); $app->view()->parserExtensions = array(new \Slim\Views\TwigExtension()); require __DIR__ . '/config/database.php'; $app->container->set('postRepo', function () { return new \PhpBelfast\Repos\PostRepo(); });