public function runUpdate() { if (Capsule::schema()->hasTable('settings')) { $updateVersion = SettingModel::where('name', 'update_version')->first(); if ($updateVersion && $updateVersion->value == $this->app['version']) { return $this->app->redirect('/'); } } $s = new Seeder($this->app, $this->app['projects.creator']); $s->seedTemplates(); $s->seedLibraries(); if (SettingModel::where('name', 'update_version')->first()) { SettingModel::where('name', 'update_version')->update(array('value' => $this->app['version'])); } else { SettingModel::insert(array('name' => 'update_version', 'value' => $this->app['version'])); } return $this->app->redirect('/'); }
use Rossedman\Teamwork\Factory as Teamwork; use Aura\Sql\ExtendedPdo; $taskFile = sys_get_temp_dir() . '/mtiof.json'; $app = new Silex\Application(); $app['debug'] = true; // @var $app['db'] \Aura\Sql\ExtendedPdo $app['db'] = new ExtendedPdo('mysql:host=localhost;dbname=mtiof', 'mtiof', 'stopdroproll'); $settings = $app['db']->fetchOne('SELECT `url`, `apikey`, `name`, `logo`, `userId` FROM `settings` LIMIT 1'); $people = $app['db']->fetchAll('SELECT * FROM `people` ORDER BY `companyName`=(select companyName from people where userId=' . ($settings['userId'] ?: 999) . ') DESC, `companyName` ASC, `name` ASC;'); $client = new Client(new Guzzle(), $settings['apikey'] ?: '', $settings['url'] ?: ''); $teamwork = new Teamwork($client); $app->post('/setapikey', function () use($app) { $apikey = $_POST['apikey']; // TODO: Get this from the request properly if (empty($apikey)) { return $app->redirect('/?setApiKey=emptyPleaseDoItProperly'); } $result = $app['db']->perform('INSERT INTO `settings` (apikey) VALUES (:apikey)', ['apikey' => $apikey]); if (empty($result)) { return $app->redirect('/?setApiKey=failedToInsertIntoSettings'); } $client = new Client(new Guzzle(), $apikey, ''); $teamwork = new Teamwork($client); $account = $teamwork->authenticate()->authenticate(); if (empty($account)) { return $app->redirect('/?setApiKey=rubbishApiKeySorry'); } $result = $app['db']->perform('UPDATE `settings` SET `url`=:url, `logo`=:logo, `name`=:name, `userId`=:userId', ['url' => $account['account']['URL'], 'logo' => $account['account']['logo'], 'name' => ucwords(trim($account['account']['firstname'] . ' ' . $account['account']['lastname'])), 'userId' => $account['account']['userId']]); if (empty($result)) { return $app->redirect('/?setApiKey=failedToUpdateSettingsWithUrlAndSuch'); }
}); $app->get('/{type}/{key}', function ($type, $key) use($app) { $music_site = new MusicSite(); $data = $music_site->getPage($type, $key); if (is_null($data)) { return $app->abort(404); } return $app['twig']->render($data['page'], $data['params']); }); //ADMIN $app->post('/connection', function (Request $request) use($app) { $pass = $request->get('pass'); if ($pass == "root") { $_SESSION['connected'] = true; } return $app->redirect($request->server->getHeaders()['REFERER']); }); $app->get('/disconnection', function () use($app) { session_destroy(); return $app->redirect(url); }); $app->get('/{type}/{key}/{action}', function ($type, $key, $action) use($app) { if (!$_SESSION['connected']) { return $app->abort(404); } $accepted = array('add', 'set'); if (!in_array($action, $accepted)) { return $app->abort(404); } $music_site = new MusicSite(); $data = $music_site->getPage($type, $key);
$app->get('/', function () use($app) { return $app['twig']->render('welcome.html.twig'); })->bind('welcome'); $app->get('/aboutme', function () use($app) { return $app['twig']->render('aboutme.html.twig'); })->bind('aboutme'); /** * Welcome action */ $app->get('/start/{player}/{sign}', function ($player, $sign) use($app) { $board = new Entity\Board(array()); $player1 = new Entity\Player($board, (int) $sign, $player); $player2 = new Entity\AIPlayer($board, (int) $sign ? 0 : 1); $gameEngineCallback = $app['game_engine']; $gameEngineCallback($player1, $player2, $board); return $app->redirect('/game'); })->bind('start'); /** * Game action */ $app->get('/game', function () use($app) { $gameEngineCallback = $app['game_engine']; $gameEngine = $gameEngineCallback(); if (!\Symstriker\TicTacToe\Engine\GameEngine::isStarted()) { return $app->redirect('/'); } return $app['twig']->render('game.html.twig', ['player1' => $gameEngine->getFirstPlayer(), 'player2' => $gameEngine->getSecondPlayer(), 'board' => $gameEngine->getBoard()]); })->bind('game'); /** * Make move action */
$oauth = $app['session']->get('oauth'); if (empty($oauth)) { $notebooks = null; } else { $notebooks = $app['evernote']->listNotebooks(); foreach ($notebooks as $key => $notebook) { $notebooks[$key] = (array) $notebook; $notebooks[$key]['notes'] = $app['evernote']->listNotes($notebook->guid); } } return $app['twig']->render('layout.twig', array('oauth' => $oauth, 'notebooks' => $notebooks)); })->bind('home'); $app->get('/connect', function () use($app) { $token = $app['oauth']->requestTempCredentials(); $app['session']->set('oauth', $token); return $app->redirect($app['oauth']->makeAuthUrl()); })->bind('connect'); $app->get('/callback', function () use($app) { $verifier = $app['request']->get('oauth_verifier'); if (empty($verifier)) { throw new \InvalidArgumentException("There was no oauth verifier in the request"); } $tempToken = $app['session']->get('oauth'); $token = $app['oauth']->requestAuthCredentials($tempToken['oauth_token'], $tempToken['oauth_token_secret'], $verifier); $app['session']->set('oauth', $token); return $app->redirect($app['url_generator']->generate('home')); })->bind('callback'); $app->get('/reset', function () use($app) { $app['session']->set('oauth', null); return $app->redirect($app['url_generator']->generate('home')); })->bind('reset');
//}); // Iniciando a sessão $app->register(new Silex\Provider\SessionServiceProvider()); $app['session']->start(); $questions = (include 'questions.php'); // Registrando o Logger de SQL apenas para debug //if ($app['debug']) // $app['db.config']->setSQLLogger(new Log\SilexSkeletonLogger($app['session'], $app['monolog'])); // ================================================== // Filtros (antes e depois das requisições) // ================================================== $app->before(function (Request $request) use($app) { $route = $request->attributes->get('_route'); if (!$app['auth.permission']->freePass($route)) { if (!$app['auth.login']->isAuthenticated()) { return $app->redirect('/login'); } if (!$app['auth.permission']->isAuthorized($route)) { return $app->abort(403, $route . ' - Você não pode acessar esta área!'); } } }); // ================================================== // URL's da Aplicação // ================================================== // ------------ AUTH Example ------------------------ $app->get('/login', function () use($app) { return $app['twig']->render('auth/login.twig', array('error' => '')); })->bind('auth.login'); $app->post('/authenticate', function (Request $request) use($app, $questions) { // Modifique o método getUser() em lib/Auth/Authentication.php
$encoded = urlencode($url); $data = curl($url); if (strlen($name) < 1) { $name = generateName(); } mkdir(ARCHIVES . $name); $data = getSources($data, $hit, $name); $timesPath = TIMES . $encoded; $times = []; if (file_exists($timesPath)) { $times = unserialize(file_get_contents($timesPath)); } array_push($times, ['name' => $name, 'time' => time()]); file_put_contents(ARCHIVES . $name . '/0', $data); file_put_contents($timesPath, serialize($times)); return $app->redirect('/' . $name); }); $app->get('{name}/{path}', function ($name, $path) use($app) { $search = archive($name, $path); if (!file_exists($search)) { return 'File not found for: ' . $name; } $mime = mime_content_type($search); echo file_get_contents($search); header('Content-Type: ' . $mime); die; })->assert('path', '(.*)'); $app->get('{name}', function ($name) use($app) { $path = ARCHIVES . $name . '/0'; if (!file_exists($path)) { return 'Archive not found.';
}); $app->post("/logout", function () use($app) { $_SESSION['user_id'] = null; $user = User::find($_SESSION['user_id']); return $app['twig']->render('main.twig', array('user_id' => $_SESSION['user_id'], 'user' => $user)); }); $app->post("/login", function () use($app) { $username = $_POST['signin_username']; $password = $_POST['user_password']; $user = User::authenticatePassword($username, $password); if ($user) { $user_id = $user->getId(); $_SESSION['user_id'] = $user_id; $new_user_is_admin = $user->getAdmin(); $_SESSION['is_admin'] = $new_user_is_admin; return $app->redirect('/user'); } else { return $app['twig']->render('main.twig', array('user' => $user, 'user_id' => $_SESSION['user_id'])); } }); ///////////////////////////////////////////////////////////// //user info $app->get("/user", function () use($app) { $current_user = User::find($_SESSION['user_id']); $admin_status = $_SESSION['is_admin']; return $app['twig']->render('user.twig', array('user' => $current_user, 'is_admin' => $admin_status)); }); $app->post("/user", function () use($app) { $current_user = User::find($_SESSION['user_id']); $admin_status = $_SESSION['is_admin']; return $app['twig']->render('user.twig', array('user' => $current_user, 'is_admin' => $admin_status));
$app = new Silex\Application(); $app->register(new FormServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider(), array('locale' => 'es', 'locale_fallbacks' => array('es'))); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => '', 'charset' => 'utf8', 'password' => ''))); $app->before(function () use($app) { $app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.twig')); }); $app->match('/', function (Request $request) use($app) { $form = $app['form.factory']->createBuilder('form')->add('nombre', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('apellido', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('fecha_nacimiento', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control date-picker')))->add('rut', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('comuna', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('telefono', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('celular', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('email', 'text', array('constraints' => new Assert\Email(), 'attr' => array('class' => 'form-control', 'placeholder' => '*****@*****.**')))->add('codigo', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('tiempo_exp', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 1))), 'attr' => array('class' => 'form-control numero')))->add('formacion_academica', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control')))->add('pretension_renta', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 5))), 'attr' => array('class' => 'form-control numero')))->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $app['db']->insert('profesionales', array('nombre' => $app->escape($data['nombre']), 'apellido' => $app->escape($data['apellido']), 'fecha_nacimiento' => $app->escape($data['fecha_nacimiento']), 'rut' => $data['rut'], 'comuna' => $app->escape($data['comuna']), 'telefono' => $app->escape($data['telefono']), 'celular' => $app->escape($data['celular']), 'email' => $data['email'], 'codigo' => $app->escape($data['codigo']), 'tiempo_exp' => $app->escape($data['tiempo_exp']), 'formacion_academica' => $app->escape($data['formacion_academica']), 'pretension_renta' => $app->escape($data['pretension_renta']), 'created_at' => date("Y-m-d H:i:s"), 'updated_at' => date("Y-m-d H:i:s"))); return $app->redirect('success'); } // display the form return $app['twig']->render('index.twig', array('form' => $form->createView())); }); $app->get('/success', function () use($app) { $objPHPExcel = new PHPExcel(); $estiloTituloReporte = array('font' => array('name' => 'Verdana', 'bold' => true, 'italic' => false, 'strike' => false, 'size' => 16, 'color' => array('rgb' => 'FFFFFF')), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('argb' => 'FF220835')), 'borders' => array('allborders' => array('style' => PHPExcel_Style_Border::BORDER_NONE)), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'rotation' => 0, 'wrap' => TRUE)); $estiloTituloColumnas = array('font' => array('name' => 'Arial', 'bold' => true, 'color' => array('rgb' => '000000')), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR, 'rotation' => 90, 'startcolor' => array('rgb' => 'c47cf2'), 'endcolor' => array('argb' => 'FF431a5d')), 'borders' => array('top' => array('style' => PHPExcel_Style_Border::BORDER_MEDIUM, 'color' => array('rgb' => '143860')), 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_MEDIUM, 'color' => array('rgb' => '143860'))), 'alignment' => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, 'wrap' => TRUE)); $estiloInformacion = new PHPExcel_Style(); $estiloInformacion->applyFromArray(array('font' => array('name' => 'Arial', 'color' => array('rgb' => '000000')), 'fill' => array('type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('argb' => 'FFd9b7f4')), 'borders' => array('left' => array('style' => PHPExcel_Style_Border::BORDER_THIN, 'color' => array('rgb' => '3a2a47'))))); $sql = "SELECT * FROM profesionales"; $post = $app['db']->fetchAll($sql); $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->setTitle("profesionales"); $objPHPExcel->setActiveSheetIndex()->mergeCells('A1:L1');
<?php require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../figo/Connection.php'; require_once __DIR__ . '/../figo/Session.php'; $app = new Silex\Application(); $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views')); $CLIENT_ID = "CaESKmC8MAhNpDe5rvmWnSkRE_7pkkVIIgMwclgzGcQY"; $CLIENT_SECRET = "STdzfv0GXtEj_bwYn7AgCVszN1kKq5BdgEIKOM_fzybQ"; $connection = new Figo\Connection($CLIENT_ID, $CLIENT_SECRET, "http://localhost:3000/callback"); $app->get('/', function () use($app, $connection) { # check whether the user is logged in if (!$app['session']->has('figo_token')) { return $app->redirect($connection->login_url("qweqwe", "accounts=ro transactions=ro balance=ro user=ro")); } $session = new Figo\Session($app['session']->get('figo_token')); return $app['twig']->render('index.twig', array('transactions' => $session->get_transactions(), 'accounts' => $session->get_accounts(), 'current_account' => null, 'user' => $session->get_user())); }); $app->get('/callback', function () use($app, $connection) { # authenticate the call if ($app['request']->query->get('state') != "qweqwe") { throw new Exception("Bogus redirect, wrong state"); } # trade in authentication code for access token $token_dict = $connection->obtain_access_token($app['request']->query->get("code")); # store the access token in our session $app['session']->set('figo_token', $token_dict['access_token']); return $app->redirect("/"); }); $app->get('/logout', function () use($app) {
} if (!validaData2($data_nascimento)) { return new Response('Data inválida<br><br><a href="/editar/' . $id . '">Voltar</a> ', 201); } //update $sql = 'UPDATE funcionario SET cpf = :cpf, nome = :nome, endereco = :endereco, data_nascimento = :data_nascimento where id=:id'; $st = $app['pdo']->prepare($sql); $st->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $st->execute(array(':id' => $id, ':cpf' => $cpf, ':nome' => $nome, ':endereco' => $endereco, ':data_nascimento' => $data_nascimento)); //return new Response($sql, 201); return $app->redirect("/editar/{$id}"); }); //criar novo registro funcionario $app->post('/salvar/', function (Request $request) use($app) { $nome = $request->get('nome'); $cpf = $request->get('cpf'); $endereco = $request->get('endereco'); $data_nascimento = $request->get('data_nascimento'); //validacoes if (!valida_cpf($cpf)) { return new Response('CPF inválido<br><br><a href="/editar/">Voltar</a> ', 201); } if (!validaData2($data_nascimento)) { return new Response('Data inválida<br><br><a href="/editar/">Voltar</a> ', 201); } //insert
<?php require_once __DIR__ . '/../vendor/autoload.php'; $app = new Silex\Application(); // Start the application if (!file_exists(__DIR__ . '/../dbfile.txt')) { $app->redirect('/install'); } R::setup('sqlite:' . __DIR__ . '/../dbfile.txt'); $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../src/Selene/Views')); $app->get('/install', function () use($app) { if (file_exists(__DIR__ . '/../dbfile.txt')) { $app->redirect('/install'); } $install = new Selene\Controller\Install($app); return $install->render(); }); $app->get('/', function () use($app) { $front = new Selene\Controller\Front($app); return $front->render(); }); $app->get('/archive', function () { $archive = new Selene\Controller\Archive(); return $archive->render(); }); $app->get('/comic/{number}', function (Silex\Application $app, $number) { $comic = new Selene\Controller\Comic(); return $comic->render(); }); $app->get('/admin', function () use($app) { $admin = new Selene\Controller\Admin();
$app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app['debug'] = false; $app['db'] = $app->share(function () { return new PDO(HOMER_DNS); }); $app['queue'] = $app->share(function () use($app) { return new Homer\Queue($app['db']); }); $app['search'] = $app->share(function () use($app) { return new Homer\Search($app['db']); }); $app->get('/', function () use($app) { $search = $app['request']->get('search', false); $result = $app['search']->search($search, 20); ob_start(); include 'view/index.phtml'; return ob_get_clean(); })->bind('search'); $app->post('/add', function () use($app) { $url = filter_var($app['request']->get('url', ''), FILTER_VALIDATE_URL); if ($url) { $app['queue']->push($url, HOMER_DEEP); } return $app->redirect($app['url_generator']->generate('search', ['success' => $url !== false])); })->bind('add'); $app->get('/statistic', function () use($app) { ob_start(); include 'view/statistic.phtml'; return ob_get_clean(); })->bind('statistic'); $app->run();
//ini_set('display_errors', 1); //error_reporting(E_ALL); require_once __DIR__ . '/vendor/autoload.php'; require __DIR__ . '/config.inc.php'; $app = new Silex\Application(); $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => $config['db'])); $app['debug'] = false; $app['session.storage.handler'] = null; /** * Authorization * */ $app->match('/auth', function (Silex\Application $app) { if ($app['session']->get('user_id') !== null) { return $app->redirect($app["request"]->getBaseUrl()); } $data = array(); $data['username'] = $app['request']->get('username'); $data['password'] = $app['request']->get('password'); $data['errors'] = array(); if ($data['username'] && $data['password']) { $sql = 'SELECT * FROM users WHERE username = ?'; $user = $app['db']->fetchAssoc($sql, array($data['username'])); if ($user === false) { $data['errors'][] = 'Неправильное имя пользователя или пароль.'; } else { if (password_verify($data['password'], $user['password'])) { $app['session']->set('user_id', $user['id']); return $app->redirect($app["request"]->getBaseUrl()); } else {
// Register the Validator and Translation Service Providers $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider(), array('translator.messages' => array())); // Register the session service provider object $app->register(new Silex\Provider\SessionServiceProvider()); // Register the url generator service provider object $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // Get The DataTank hostname for use in /ui/package $hostname = $this->hostname . $this->subdir; $data['relpath'] = '/' . $this->subdir . 'ui/'; $data['hostname'] = $hostname; // must be included first require_once 'authentication.php'; // If root is asked, redirect to the resource management $app->get('/ui{url}', function () use($app) { return $app->redirect('ui/package'); })->value('url', ''); // The parameters that cannot be edited $app['session']->set('notedible', array('generic_type' => 'generic_type', 'resource_type' => 'resource_type', 'columns' => 'columns', 'column_aliases' => 'column_aliases')); //start with resources management require_once 'packagesandresources.php'; require_once 'usermanagement.php'; require_once 'routemanagement.php'; require_once 'choosefile.php'; require_once 'generictypes.php'; require_once 'puttingfile.php'; require_once 'editpackagesandresources.php'; require_once 'editresource.php'; require_once 'inputfile.php'; require_once 'input.php'; require_once 'addjob.php';
$loader = (require_once __DIR__ . '/../vendor/autoload.php'); define('ROOT_PATH', __DIR__ . '/..'); define('APP_PATH', ROOT_PATH . '/app'); $loader->add('Aixia', ROOT_PATH . '/src'); $app = new Silex\Application(); $app['debug'] = true; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array(__DIR__ . '/../app/Resources', __DIR__ . '/../src/Aixia/PostitBoardFront/Resources/views'), 'twig.cache' => array('cache' => __DIR__ . '/../app/cache'))); $app->before(function () use($app) { $app['twig']->addGlobal('layout', $app['twig']->loadTemplate('layout.html.twig')); }); $app['rest.client'] = new \Aixia\PostitBoardFront\RestClient(); $app->get('/postits', function () use($app) { return $app['twig']->render('default.html.twig', ['postits' => $app['rest.client']->get('postits')]); })->bind('homepage'); $app->get('/', function () use($app) { return $app->redirect('/postits'); }); $app->match('/edit/{id}', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { $id = $request->get('id'); if ($request->isMethod('POST')) { $message = $request->get('message'); $app['rest.client']->patch('postits', $id, ['post_it' => ['message' => utf8_encode($message)]]); } $res = $app['rest.client']->get('postits', $id); return $app['twig']->render('edit.html.twig', ['postit' => $res]); })->bind('edit'); $app->match('/new', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { if ($request->isMethod('POST')) { $message = $request->get('message'); $app['rest.client']->post('postits', ['post_it' => ['message' => utf8_encode($message)]]); return $app->redirect('/postits');
} // @todo move this in the req page if (extension_loaded('json') == false) { $app->abort(500, "php5-json extension must be installed."); } }; // Controllers $app->match('/', function () use($app) { // in order to get a list of countries //var_dump(Symfony\Component\Intl\Intl::getRegionBundle()->getCountryNames()); $languages = array('english' => 'english', 'spanish' => 'spanish', 'french' => 'french'); $request = $app['request']; $form = $app['form.factory']->createBuilder('form')->add('languages', 'choice', array('choices' => $languages, 'required' => true))->add('continue', 'submit', array('attr' => array('class' => 'btn')))->getForm(); if ('POST' == $request->getMethod()) { $url = $app['url_generator']->generate('requirements'); return $app->redirect($url); } return $app['twig']->render('index.tpl', array('form' => $form->createView())); })->bind('welcome')->before($blockInstallation); $app->match('/requirements', function () use($app) { $allowedToContinue = checkRequiredSettings(); $request = $app['request']; $builder = $app['form.factory']->createBuilder('form'); if ($allowedToContinue) { $builder->add('continue', 'submit', array('attr' => array('class' => 'btn-default'))); } else { $message = $app['translator']->trans("You need to check your server settings."); $app['session']->getFlashBag()->add('error', $message); } $form = $builder->getForm(); //$req = display_requirements($app, 'new');
$stmt = $app['db']->prepare('SELECT * FROM custom_urls WHERE code=:code'); $stmt->bindValue("code", $code); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row != false) { return $app->json(array('id' => $row['id'], 'url' => $row['url'], 'generated_date' => $row['generated_date']), 200); } else { return $app->json(array("error" => "Not found", "message" => "The provided code did not match any stored url."), 404); } } else { return $app->json(array("error" => "Unauthorized", "message" => "Trying to access protected data from unofficial StreamCenter app."), 401); } }); $app->get('/oauth/twitch/{uuid}', function (Request $request, $uuid) use($app) { if ($request->query->get("token") === getenv('STREAMCENTER_SECRET')) { return $app->redirect('https://api.twitch.tv/kraken/oauth2/authorize?response_type=code&client_id=' . getenv('TWITCH_CLIENT_ID') . '&redirect_uri=http://streamcenterapp.com/oauth/redirect/twitch&scope=user_read channel_subscriptions user_subscriptions chat_login user_follows_edit&state=' . $uuid); } else { return $app->json(array("error" => "Unauthorized", "message" => "Trying to access protected data from unofficial StreamCenter app."), 401); } }); $app->get('/oauth/twitch/{uuid}/{access_code}', function (Request $request, $uuid, $access_code) use($app) { if ($request->query->get("token") === getenv('STREAMCENTER_SECRET')) { $stmt = $app['db']->prepare('SELECT access_token, refreshed_date FROM oauth_requests WHERE uuid=:uuid AND platform=:platform AND access_code=:access_code'); $stmt->bindValue("uuid", $uuid); $stmt->bindValue("platform", 'TWITCH'); $stmt->bindValue("access_code", $access_code); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); $app['monolog']->addInfo(sprintf("ACCESS TOKEN REQUEST RESULT : %s", var_export($row, true))); if ($row != false) { return $app->json(array('access_token' => $row['access_token'], 'generated_date' => $row['refreshed_date']), 200);
$contact_form = $form_builder->getForm(); // Handle request $contact_form->handleRequest($request); // Is submited if ($contact_form->isSubmitted()) { // Get form data $form_data = $contact_form->getData(); // Is valid if ($contact_form->isValid()) { $message = \Swift_Message::newInstance(); $message->setSubject($form_data['subject'] . ' (' . $form_data['email'] . ')'); $message->setFrom(array($form_data['email'])); $message->setTo(array('*****@*****.**')); $message->setBody($form_data['message']); $app['mailer']->send($message); return $app->redirect($app['url_generator']->generate('about')); } } $data = array('contact_form' => $contact_form->createView()); return $app['twig']->render('pages/about.twig', $data); })->bind('about'); $app->get('/pokemons', function () use($app, $pokemons_model) { $pokemons = $pokemons_model->getAll(); $data = array('pokemons' => $pokemons); return $app['twig']->render('pages/pokemons.twig', $data); })->bind('pokemons'); $app->get('/pokemon/{id}', function ($id) use($app, $pokemons_model, $types_model) { $pokemon = $pokemons_model->getOneById($id); $pokemon->types = $types_model->getAllForPokemonId($pokemon->id); $data = array('pokemon' => $pokemon); return $app['twig']->render('pages/pokemon.twig', $data);
} else { return substr($string, 0, $size) . "..."; } })); // Root page with form $app->get('/', function () use($app) { return $app['twig']->render('form.twig', array()); })->bind('homepage'); // Save the form's data $app->post('/', function (Request $request) use($app) { $story = $request->get('story'); $author = $request->get('author'); $public = $request->get('public') ? 1 : 0; $shortUrl = base_convert(rand(100, 999) . microtime(true), 10, 36); $app['db']->insert('entries', array('shorturl' => $shortUrl, 'author' => $author, 'story' => $story, 'public' => $public)); return $app->redirect('/' . $shortUrl); }); // Get list of latest entries $app->get('/uusimmat', function () use($app) { $entries = $app['db']->query('SELECT * FROM entries WHERE author != "" AND story != "" AND public = true ORDER BY created DESC LIMIT 20'); return $app['twig']->render('list.twig', array('entries' => $entries, 'page_title' => 'Uusimmat')); })->bind('latest'); // Get list of TOP entries $app->get('/top', function () use($app) { $entries = $app['db']->query('SELECT * FROM entries WHERE author != "" AND story != "" AND public = true ORDER BY views DESC LIMIT 20'); return $app['twig']->render('list.twig', array('entries' => $entries, 'page_title' => 'TOP 20')); })->bind('top'); // View saved data $app->get('/{shortUrl}', function ($shortUrl) use($app) { $entry = $app['db']->fetchAssoc('SELECT * FROM entries WHERE shorturl = :shorturl', array('shorturl' => $shortUrl)); if (!$entry) {
$app = new Silex\Application(); // add the current url to the app object. $app['current_url'] = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : null; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); //$app->register(new PhpDorset\Eventbrite\EventbriteProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app['talk.controller'] = $app->share(function () use($app) { return new PhpDorset\Talk\TalkController($app['talk.repo'], $app['twig']); }); $app['talk.repo'] = $app->share(function () { return new PhpDorset\Talk\TalkRepository(json_decode(file_get_contents(__DIR__ . '/database/talks.json'), true)); }); $app->get('/api/v1/talks/{year}/{month}/talks.json', "talk.controller:fetchCuesByYearAndMonth"); $app->get('/', [$app['talk.controller'], 'fetchHomepageTalks']); $app->get('/get-involved', function () use($app) { return $app['twig']->render('get-involved.twig', array()); }); $app->get('/talks/{year}/{month}', [$app['talk.controller'], 'fetchTalksByYearAndMonth']); $app->get('/talks/{year}/{month}/{key}', [$app['talk.controller'], 'fetchTalk']); $app->get('/talks', [$app['talk.controller'], 'fetchTalkList']); $app->get('/talk/create', [$app['talk.controller'], 'createTalk']); $app->get('/contact', function () use($app) { return $app['twig']->render('contact.twig', array()); }); $app->get('/sponsors', function () use($app) { return $app->redirect('/', 301); }); $app->get('/about', function () use($app) { return $app['twig']->render('about.twig', array()); }); return $app;
$app->get('/gateways/{name}', function ($name) use($app) { $gateway = Omnipay\Common\GatewayFactory::create($name); $sessionVar = 'omnipay.' . $gateway->getShortName(); $gateway->initialize((array) $app['session']->get($sessionVar)); return $app['twig']->render('gateway.twig', array('gateway' => $gateway, 'settings' => $gateway->getParameters())); }); // save gateway settings $app->post('/gateways/{name}', function ($name) use($app) { $gateway = Omnipay\Common\GatewayFactory::create($name); $sessionVar = 'omnipay.' . $gateway->getShortName(); $gateway->initialize((array) $app['request']->get('gateway')); // save gateway settings in session $app['session']->set($sessionVar, $gateway->getParameters()); // redirect back to gateway settings page $app['session']->getFlashBag()->add('success', 'Gateway settings updated!'); return $app->redirect($app['request']->getPathInfo()); }); // create gateway authorize $app->get('/gateways/{name}/authorize', function ($name) use($app) { $gateway = Omnipay\Common\GatewayFactory::create($name); $sessionVar = 'omnipay.' . $gateway->getShortName(); $gateway->initialize((array) $app['session']->get($sessionVar)); $params = $app['session']->get($sessionVar . '.authorize', array()); $params['returnUrl'] = str_replace('/authorize', '/completeAuthorize', $app['request']->getUri()); $params['cancelUrl'] = $app['request']->getUri(); $card = new Omnipay\Common\CreditCard($app['session']->get($sessionVar . '.card')); return $app['twig']->render('request.twig', array('gateway' => $gateway, 'method' => 'authorize', 'params' => $params, 'card' => $card->getParameters())); }); // submit gateway authorize $app->post('/gateways/{name}/authorize', function ($name) use($app) { $gateway = Omnipay\Common\GatewayFactory::create($name);
$app['debug'] = true; $app['session.storage.options'] = ['name' => 'PHPSESSID']; $app->register(new Silex\Provider\SessionServiceProvider()); $app['session']->start(); $app['fb'] = new Facebook\Facebook($app['config']['facebook']); $app['user_list'] = new UsersList($app['fb']); $app->get('/', function () use($app) { /** @var Facebook\Facebook $fb */ $fb = $app['fb']; $accessToken = $app['session']->get(ACCESS_TOKEN); if (!$accessToken) { return sprintf('You have to <a href="%s">login</a> first', $fb->getRedirectLoginHelper()->getLoginUrl('http://localhost:8080/login', ['user_events'])); } return implode('<br />', $app['user_list']->get($app['config']['event_id'], $accessToken)); }); $app->get('/login', function () use($app) { /** @var Facebook\Facebook $fb */ $fb = $app['fb']; $helper = $fb->getRedirectLoginHelper(); try { $accessToken = $helper->getAccessToken(); if ($accessToken) { $app['session']->set(ACCESS_TOKEN, (string) $accessToken); return $app->redirect('/'); } return 'You probably deny application permissions'; } catch (Facebook\Exceptions\FacebookSDKException $e) { return $e->getMessage(); } }); $app->run();
$pngfile = '/tmp/saffire.pngfile.' . posix_getpid(); file_put_contents($tmpfile, $_POST['paste']); $command = sprintf('%s %s 2>&1 | grep -v "Reduce at line"', $config['binary'], $tmpfile); $output = shell_exec($command); if (stripos($output, 'Error at line') === false) { $command = sprintf('%1$s %2$s --dot %3$s && dot %3$s -Tpng > %4$s && echo $?', $config['binary'], $tmpfile, $dotfile, $pngfile); $dotoutput = shell_exec($command); if (substr(trim($dotoutput), -1) === '0') { $context = stream_context_create(array('http' => array('method' => 'POST', 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'content' => http_build_query(array('image' => base64_encode(file_get_contents($pngfile)), 'key' => $config['imgur_key'])), 'timeout' => 5))); $imgur = file_get_contents('http://api.imgur.com/2/upload.json', false, $context); $response = json_decode($imgur); if (isset($response->upload->links->original)) { $image = $response->upload->links->original; } } } unlink($tmpfile, $dotfile, $pngfile); /** * Added the name used to a cookie for future use. */ setcookie('name', $_POST['name'], time() + 60 * 60 * 24 * 30); /** * Insert the paste to the database. */ $insert = $db->prepare('INSERT INTO paste ( paste_id, paste, name, added, output, private, image ) VALUES ( :paste_id, :paste, :name, NOW(), :output, :private, :image );'); $result = $insert->execute(array('paste_id' => $paste_id = uniqid(), 'paste' => $_POST['paste'], 'name' => $_POST['name'], 'output' => $output, 'private' => isset($_POST['private']) && $_POST['private'] == 'yes' ? '0' : '1', 'image' => isset($image) ? $image : '')); if ($result !== false) { return $app->redirect('/codepad/' . $paste_id); } }); $app->run();
$texts = $app['db']->fetchAll("select * from text where status in ('pending', 'accepted')"); return $app['twig']->render('list.html.twig', array('texts' => $texts)); })->bind('list'); $app->get('/question', function () use($app) { $form = $app['form.factory']->createBuilder('form')->add('text', 'textarea')->getForm(); return $app['twig']->render('question.html.twig', array('form' => $form->createView())); })->bind('question'); $app->post('/question', function (Request $request) use($app) { $form = $app['form.factory']->createBuilder('form')->add('text')->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $data['status'] = 'pending'; $app['db']->insert('text', $data); $app['session']->getFlashBag()->add('message', 'Ta question a bien été envoyée'); return $app->redirect('/question'); } return $app['twig']->render('question.html.twig', array('form' => $form->createView())); })->bind('post.question'); $app->get('/archive', function (Request $request) use($app) { $textId = $request->get('id'); $app['db']->update('text', array('status' => 'archived'), array('id' => $textId)); return $app->redirect($app['url_generator']->generate('list')); })->bind('archive'); $app->get('/accept', function (Request $request) use($app) { $textId = $request->get('id'); $app['db']->update('text', array('status' => 'accepted'), array('id' => $textId)); return $app->redirect($app['url_generator']->generate('list')); })->bind('accept'); $app->get('/refuse', function (Request $request) use($app) { $textId = $request->get('id');
$app['cache.path'] = __DIR__ . '/../cache'; // Http cache $app['http_cache.cache_dir'] = $app['cache.path'] . '/http'; $app->register(new SessionServiceProvider()); $app->register(new ValidatorServiceProvider()); $app->register(new FormServiceProvider()); $app->register(new UrlGeneratorServiceProvider()); $app->register(new SwiftmailerServiceProvider(), array('swiftmailer.options' => array('host' => $app['mailer.config.host'], 'port' => $app['mailer.config.port'], 'username' => $app['mailer.config.username'], 'password' => $app['mailer.config.password'], 'encryption' => $app['mailer.config.encryption'], 'auth_mode' => $app['mailer.config.auth_mode']))); /** * It should be placed *BEFORE* TranslationServiceProvider registration */ $app->before(function () use($app) { if ($app['request']->get('locale') && in_array($app['request']->get('locale'), $app['supported_languages'])) { $app['locale'] = $app['request']->get('locale'); } else { return $app->redirect($app['url_generator']->generate('homepage', array('locale' => $app['locale.fallback']))); } }); /** * Services: * * translator: An instance of Translator, that is used for translation. * translator.loader: An instance of an implementation of the translation * LoaderInterface, defaults to an ArrayLoader. * translator.message_selector: An instance of MessageSelector. */ $app->register(new TranslationServiceProvider(), array('locale.fallback' => $app['locale_fallback'])); $app['translator'] = $app->share($app->extend('translator', function ($translator, $app) { $translator->addLoader('yaml', new YamlFileLoader()); $translator->addResource('yaml', __DIR__ . '/../resources/locales/en.yml', 'en'); $translator->addResource('yaml', __DIR__ . '/../resources/locales/fr.yml', 'fr');
})->assert('post_id', '\\d+')->bind('post_single'); $app->get('/post/new', function () use($app) { $authorModel = new Author($app['db']); $authorsToDisplay = $authorModel->getAll(); return $app['twig']->render('post_new.html.twig', array('authors' => $authorsToDisplay)); })->bind('post_new'); $app->post('/post/add', function (Request $request) use($app) { $postModel = new Post($app['db']); $authorId = $request->request->get('author_id'); if (!isset($authorId)) { $app->abort(404, 'Author has to be selected. Go back and select author'); } $title = $request->request->get('title'); $message = $request->request->get('message'); $postModel->set($title, $message, $authorId); return $app->redirect($app["url_generator"]->generate("post_index")); })->bind('post_add'); $app->get('/authors', function () use($app) { $authorModel = new Author($app['db']); $authorsToDisplay = $authorModel->getAll(); return $app['twig']->render('author_index.html.twig', array('authors' => $authorsToDisplay)); })->bind('author_index'); $app->get('/author/{author_id}', function ($author_id) use($app) { $authorModel = new Author($app['db']); $authorToDisplay = $authorModel->get($author_id); if (!$authorToDisplay) { $app->abort(404, 'The article could not be found'); } return $app['twig']->render('author_single.html.twig', array('author' => $authorToDisplay)); })->assert('author_id', '\\d+')->bind('author_single'); $app->get('/author/new', function () use($app) {
$sa = [['^/ticket.+$', 'ROLE_USER'], ['^/user.+$', 'ROLE_USER'], ['^/admin.+$', 'ROLE_ADMIN']]; $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views']); $app->register(new Silex\Provider\DoctrineServiceProvider(), ['db.options' => $db]); $app->register(new Silex\Provider\SecurityServiceProvider(), ['security.firewalls' => $sc, 'security.access_rules' => $sa]); $app->before(function ($request) use($app) { $sh = new \Tickets\SecurityProvider($app["db"]); $app["user"] = $sh->loadUserByUsername($app["session"]->get("username")); }); $app->mount('/ticket', new Tickets\TicketProvider()); $app->mount('/user', new Tickets\UserProvider()); $app->mount('/admin', new Tickets\AdminProvider()); $app->get('/', function () use($app) { $user = isset($app["user"]) ? $app["user"] : null; if ($user == null) { return $app->redirect("/login-form"); } if (array_search('ROLE_ADMIN', $user->getRoles()) !== false) { return $app->redirect("/admin/home"); } if (array_search('ROLE_USER', $user->getRoles()) !== false) { return $app->redirect("/user/home"); } return $app->redirect("/login-form"); }); $app->get('/login-form', function () use($app) { $view = new \Zend_View(); $form = new \Zend_Form(); $form->setView($view); $form->setAction("/user/login-save"); $form->addElement("text", "_username", ["label" => "Kullanıcı Adı", "required" => true]);
$user = new \Symfony\Component\Security\Core\User\User('user', array()); $encoder = $app['security.encoder_factory']->getEncoder($user); $password = $encoder->encodePassword($request->get('password'), ''); file_put_contents(PASSWD_FILE, $password); return $app['twig']->render('login.html.twig', array('create_success' => true, 'error' => false)); } else { $error = 'Could not save the password. Please make sure your server can write the directory (<code>/app/config/secure/</code>).'; } } else { $error = 'The provided Passwords do not match.'; } } return $app['twig']->render('set_pwd.html.twig', array('error' => $error)); })->bind("home")->method('POST|GET'); $app->match('/{url}', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { return $app->redirect($app['url_generator']->generate('home')); })->assert('url', '.+'); // Match any route; } else { $app->get('/', function () use($app) { if (!is_readable(CONFIG_FILE)) { throw new \Syonix\LogViewer\Exceptions\ConfigFileMissingException(); } return $app->redirect($app['url_generator']->generate('home')); }); $app->get('/login', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { return $app['twig']->render('login.html.twig', array('create_success' => false, 'error' => $app['security.last_error']($request))); })->bind("login"); $app->get('/logs', function () use($app) { $viewer = new Syonix\LogViewer\LogViewer($app['config']['logs']); $client = $viewer->getFirstClient();
$authPage = array($app['uri']->generate('authenticate'), $app['uri']->generate('de_authenticate')); $app['twig']->addGlobal('uri', $app['uri']); $app['twig']->addGlobal('data', $app['data']); $app['twig']->addGlobal('session', $app['session']); $app['twig']->addGlobal('cache', $app['cache']); $app['twig']->addGlobal('pages', $app['pages']); $app['twig']->addGlobal('store', $app['store']); $app['twig']->addGlobal('config', $app['config']); $app['twig']->addGlobal('utils', $app['utils']); $authRequired = !empty($app['config']['authenticate']) && !empty($app['config']['authenticate']['username']) && !empty($app['config']['authenticate']['password']) ? true : false; if (!in_array($app['request']->getRequestUri(), $authPage)) { if ($authRequired) { $currentUser = $app['session']->get($app['config']['prefix'] . 'authed-user'); $userHash = sha1($app['config']['authenticate']['username'] . $app['config']['authenticate']['password']); if (empty($currentUser) || $currentUser !== $userHash) { return $app->redirect($app['uri']->generate('authenticate')); // not logged in, redirect to auth page } } } elseif (!$authRequired) { // redirect visits to the auth pages to the homepage if no auth is required. return $app->redirect('/'); } }); $app->error(function (\Exception $e, $code) use($app) { switch ($code) { case '404': $template = 'PT/pages/404.html'; break; default: $template = 'PT/pages/error.html';