$app->match('/oauth/authorize', function (\Symfony\Component\HttpFoundation\Request $request) use($app, $db) { //the login form was submitted if ($request->isMethod("POST")) { //validate the user by attempting to load them from the db if (!($user = $db->users->findOne(array('username' => $request->request->get('username'), 'password' => $request->request->get('password'))))) { return "Invalid Login"; } //check if we came here from an OAuth client (MemberFuse) //the redirect_uri would be set in the query string if so if ($redirect_uri = $request->query->get('redirect_uri')) { //generate an authorization code //How you do this is up to you. You should use a technique more random and secure than below $auth_code = sha1(uniqid()); //save the code associated with the user //this will be retrieved by the token endpoint $db->auth_codes->save(array('code' => $auth_code, 'user_id' => $user['_id'])); //append our code to the redirect uri //be careful to respect if the redirect uri already had a query string component if (parse_url($redirect_uri, PHP_URL_QUERY)) { $redirect_uri .= '&'; } else { $redirect_uri .= '?'; } $redirect_uri .= 'code=' . urldecode($auth_code); //MemberFuse will also send a "state" parameter when redirecting the user //you must send the exact state back. This is to help against CSRF attacks $redirect_uri .= '&state=' . urlencode($request->query->get('state')); //send the user along return $app->redirect($redirect_uri); } //the user must have come here on their own, just welcome them :) return "Welcome " . $user['firstname']; } //Render a very simple page with a login form $html = <<<HTML <html> <head> <title>Login</title> </head> <body> <p>Please login below</p> <form method="POST"> <label>Username</label> <input type="text" name="username" /> <label>Password</label> <input type="password" name="password" /> <input type="submit" value="Login" /> </form> </body> </html> HTML; return $html; })->method("GET|POST");
use App\Controller\CategoriesController; use App\Controller\CategoryAdd; use App\Controller\ArticlesController; use App\Controller\ArticleAddController; use Igorw\Silex\ConfigServiceProvider; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../app/views', 'twig.class_path' => __DIR__ . '/../vendor/twig/lib')); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\FormServiceProvider()); $app->register(new Silex\Provider\TranslationServiceProvider()); $app->register(new Silex\Provider\SessionServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => $db_config)); $app->register(new ConfigServiceProvider(__DIR__ . "/../app/config/routes.yml")); foreach ($app["config.routes"] as $name => $route) { $app->match($route["path"], $route["defaults"]["_controller"])->bind($name)->method(isset($route["methods"]) ? $route["methods"] : "GET"); } $app['controller.home'] = $app->share(function () use($app) { return new HomeController($app); }); $app['controller.categories'] = $app->share(function () use($app) { return new CategoriesController($app); }); $app['controller.categoryAdd'] = $app->share(function () use($app) { return new CategoryAdd($app); }); $app['controller.articles'] = $app->share(function () use($app) { return new ArticlesController($app); }); $app['controller.articleAdd'] = $app->share(function () use($app) { return new ArticleAddController($app);
$app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('admin' => array('pattern' => '^/logs', 'form' => array('login_path' => '/login', 'check_path' => '/logs/login_check'), 'users' => array('user' => array('ROLE_USER', is_file(PASSWD_FILE) ? file_get_contents(PASSWD_FILE) : null)), 'logout' => array('logout_path' => '/logs/logout'))))); $app['security.encoder.digest'] = $app->share(function ($app) { return new \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder(10); }); if (!is_file(PASSWD_FILE)) { $app->match('/', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { $error = ""; if ($request->getMethod() == "POST") { if ($request->get('password') == $request->get('password-repeat')) { if (is_writable(PASSWD_DIR)) { $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) {
$extension = array_pop($arr); $mime = "text/plain"; if ($extension === "css") { $mime = "text/css"; } else { if ($extension === "js") { $mime = "application/javascript"; } else { if ($extension === "html") { $mime = "text/html"; } } } return $app->sendFile($filePath, 200, array('Content-Type' => $mime)); })->assert('fileName', '.+'); } // Development routes $app->get('/devStatic/{lang}/{fileName}', 'DevStaticController::getDevFile')->assert('fileName', '.+'); $app->get('/dev/', 'DevDashboardController::devIndex'); $app->get('/dev/js/bench/{id}', 'DevDashboardController::devJSBench'); $app->get('/dev/js/{type}/{id}', 'DevDashboardController::devJSExample'); $app->match('/dev/php/{type}/{id}', 'DevDashboardController::devPHPExample'); $app->match('/dev/html/{type}/{id}', 'DevDashboardController::devHTMLExample'); $app->match('/dev/test/{id}', 'DevDashboardController::devTest'); $app->match('/docs/{fileName}', 'DevStaticController::devDocs')->assert('fileName', '.+'); // Production routes $app->get('/', 'DevDashboardController::prodIndex'); $app->get('/dashboard/js/{type}/{id}', 'DevDashboardController::prodJSExample'); $app->match('/dashboard/php/{type}/{id}', 'DevDashboardController::prodPHPExample'); $app->match('/dashboard/test/{id}', 'DevDashboardController::prodTest'); $app->run();
/** ** Load the front end that contains the JS app via app/index.php */ $app->get('/', function () use ($app) { $text = file_get_contents(__DIR__ . "/app/index.php"); return $text; }); // // Document NON_REST interface // $app->match('/api/v1.0/document/{method}/{name}', function ($name, $method) use ($app) { $controller = new \Controller\Json(); if(method_exists($controller, $method)) { return $controller->$method($name); } return new Response("method : ".$method. " not found ", 404); }); // // Document REST interface // $app->post('api/v1.0/document/{name}', function($name) use ($app) { $controller = new \Controller\Json(); return $controller->createFile($name); return json_encode(['status'=>"got here POST", 'name' => $name]); }); $app->get('api/v1.0/document/{name}', function($name) use ($app) { $controller = new \Controller\Json(); return $controller->openFile($name);
} if (api_check_php_version() == false) { $app->abort(500, "Incorrect PHP version."); } // @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); }
$app->match('/about', function (Request $request) use($app) { // Create builder $form_builder = $app['form.factory']->createBuilder(); // Set method and action $form_builder->setMethod('post'); $form_builder->setAction($app['url_generator']->generate('about')); // Add input $form_builder->add('name', 'text', array('label' => 'Your name', 'trim' => true, 'max_length' => 50, 'required' => true, 'constraints' => array(new Constraints\NotEqualTo(array('value' => 'f**k', 'message' => 'Be polite you s******d'))))); $form_builder->add('email', 'email', array('label' => 'Your email', 'trim' => true, 'max_length' => 50, 'required' => true)); $form_builder->add('subject', 'choice', array('label' => 'Subject', 'required' => true, 'empty_value' => 'Choose a subject', 'choices' => array('Informations' => 'Informations', 'Proposition' => 'Proposition', 'Other' => 'Other'))); $form_builder->add('message', 'textarea', array('label' => 'Message', 'trim' => true, 'max_length' => 50, 'required' => true)); $form_builder->add('submit', 'submit'); // Create form $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');
* 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 { $data['errors'][] = 'Неправильное имя пользователя или пароль.'; } } } include __DIR__ . '/templates/auth.tpl.php'; return ''; })->method('GET|POST'); /** * Application main page *
$app->match('/', function (Request $request) use($app) { $form = $app['form.factory']->createBuilder('form')->add('attachment', 'file', array('label' => 'Source File:'))->getForm(); $stats_raw = $app['db']->fetchAll("SELECT name,value FROM " . STAT_TABLE); $stats = array(); foreach ($stats_raw as $s) { $stats[$s['name']] = $s['value']; } if ('POST' == $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $file = $form['attachment']->getData(); $ext = $file->guessExtension(); if (!$ext) { $ext = 'junk'; } $newFile = time() . '-' . rand(1, 9999) . '.' . $ext; $filename = __DIR__ . '/../tmp/' . $newFile; $file->move(__DIR__ . '/../tmp', $newFile); // Do some stuff $file_contents = file_get_contents($filename); if (strpos($file_contents, 'CostumePart')) { // We have a .costume file $costumes = dataFromCostume($filename); $sql = "UPDATE " . STAT_TABLE . " SET value=value+1 WHERE name='numCostumes'"; $stats['numCostumes'] += 1; $app['db']->executeUpdate($sql); unlink($filename); } elseif (strpos($file_contents, '<costumes count')) { // We have a Titan .xml file $costumes = dataFromTitan($filename); $sql = "UPDATE " . STAT_TABLE . " SET value=value+1 WHERE name='numTitans'"; $stats['numTitans'] += 1; $app['db']->executeUpdate($sql); unlink($filename); } else { // No idea what we have unlink($filename); return $app['twig']->render('index.twig', array('form' => $form->createView(), 'error' => "Yeah, I'm pretty sure that file you gave me was crap.", 'stats' => $stats)); } return $app['twig']->render('step2.twig', array('costumes' => $costumes, 'stats' => $stats)); } } return $app['twig']->render('index.twig', array('form' => $form->createView(), 'stats' => $stats)); });
foreach ($dir as $fileinfo) { if (!in_array($fileinfo->getFilename(), array('.', '..', 'pages', 'images'))) { if (strpos($fileinfo->getFilename(), 'json') === FALSE) { $files[$fileinfo->getMTime()] = $fileinfo->getFilename(); } } } //krsort will sort in reverse order krsort($files); $app['files'] = $files; $app->match('/', function (Request $request) use($app) { $form = $app['form.factory']->createBuilder('form')->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); // do something with the data // redirect somewhere return $app->redirect('/'); } // display the form return $app['twig']->render('index.html.twig', array('form' => $form->createView(), 'files' => $app['files'])); }); $app->post('/upload', function (Silex\Application $app) { extract($_FILES); if ($file['error']) { die("Error uploading file! code {$error}.\n"); } if (!empty($file)) { $moved = move_uploaded_file($file['tmp_name'], dirname(__FILE__) . '/../uploads/' . sha1(time()) . "-" . $file['name']); if ($moved) { return new Response(json_encode(array('message' => 'Upload Successful!')), '200'); } else {
$app['security.access_rules'] = array(array('^/', 'IS_AUTHENTICATED_ANONYMOUSLY')); $app->before(function (Request $request) use($app) { $app['twig']->addGlobal('active', $request->get("_route")); }); $app->get('/', function () use($app) { $app['monolog']->addDebug('logging output.'); return $app['twig']->render('pages/index.twig', array('error' => 'Contact us using the form below and we\'ll get back in touch with you')); })->bind('home'); $app->match('/contact', function (Request $request) use($app) { $sent = false; $default = array('name' => '', 'email' => '', 'message' => '', 'verify' => ''); $form = $app['form.factory']->createBuilder('form', $default)->add('name', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 3))), 'attr' => array('class' => 'form-control', 'placeholder' => 'Your Name', 'error' => 'Name should be greater than 3 characters')))->add('email', 'email', array('constraints' => new Assert\Email(), 'attr' => array('class' => 'form-control', 'placeholder' => '*****@*****.**', 'error' => 'Please verify your email. Eg.Your@email.com ')))->add('message', 'textarea', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 20))), 'attr' => array('class' => 'form-control', 'placeholder' => 'Enter Your Message', 'error' => 'Please enter your query here.')))->add('verify', 'text', array('constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 1))), 'attr' => array('class' => 'form-control', 'placeholder' => '2 + 7 = ?', 'error' => 'Please calculate the addition of capcha and validate you are a human.')))->add('Enquire Now', 'submit', array('attr' => array('class' => 'btn btn-default btn-primary')))->getForm(); $form->handleRequest($request); if ($form->isValid()) { $data = $form->getData(); $exit = false; if (!$exit) { if ($data["verify"] == 9) { $message = \Swift_Message::newInstance()->setSubject('Sai Prasar Nivara Feedback11')->setFrom(array($data['email'] => strip_tags($data['name'])))->setTo(array('*****@*****.**'))->setBody(strip_tags($data['message'])); $app['mailer']->send($message); $sent = true; } else { //do something $exit = true; $sent = false; } } } return $app['twig']->render('pages/contact.twig', array('form' => $form->createView(), 'sent' => $sent)); })->bind('contact'); $app->run();
$app->match('/upload.html', function () use($app, $credentials) { // A simple, minimalist, personal file/image hosting script. - version 0.7 // Only you can upload a file or image, using the password(s) ($passwords). // Anyone can see the images or download the files. // Files are stored in a subdirectory (see $subdir). // This script is public domain. // Original source: http://sebsauvage.net/wiki/doku.php?id=php:imagehosting $passwords = $credentials['upload']; $subdir = 'files'; // subdirectory where to store files and images. if (!is_dir($subdir)) { mkdir($subdir, 0705); chmod($subdir, 0705); $h = fopen($subdir . '/.htaccess', 'w') or die("Can't create subdir/.htaccess file."); fwrite($h, "Options -ExecCGI\nAddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi"); fclose($h); $h = fopen($subdir . '/index.html', 'w') or die("Can't create subdir/index.html file."); fwrite($h, '<html><head><meta http-equiv="refresh" content="0;url=' . $_SERVER["SCRIPT_NAME"] . '"></head><body></body></html>'); fclose($h); } $scriptname = basename($_SERVER["SCRIPT_NAME"]); $flash = NULL; if (isset($_FILES['filetoupload']) && isset($_POST['filetoupload_url']) && isset($_POST['password'])) { sleep(3); // Reduce brute-force attack effectiveness. /** * Determines filename. * @param string $filename The input filename * @param string $newFileData The content of the new file (used to compare files' contents) * @param bool $secondIsURL Is the second parameter an URL to the file? * @return string|array The new filename, or an array who contains the filename if this file has already been uploaded. */ function determineFilename($filename, $newFileData, $secondIsURL = false) { $beforeFilename = str_replace(basename($filename), NULL, $filename); if (!file_exists($filename)) { return $filename; } else { if (!$secondIsURL && sha1_file($filename) == sha1($newFileData) || $secondIsURL && sha1_file($filename) == sha1_file($newFileData)) { return array($filename); } else { $i = 1; do { $newFilename = $beforeFilename . $i . '-' . basename($filename); $i++; } while (file_exists($newFilename) && (!$secondIsURL && sha1_file($filename) != sha1($newFileData) || $secondIsURL && sha1_file($filename) != sha1_file($newFileData))); $i = $i - 2; $ext = $i <= 0 ? NULL : $i . '-'; if (sha1_file($beforeFilename . $ext . basename($filename)) == sha1($newFileData)) { return array($beforeFilename . $ext . basename($filename)); } return basename($newFilename); } } } /** * Return the complete file's URL from the file's path. */ function getFileURL($filename, $subdir) { $subdir .= '/'; if (strpos($filename, $subdir) === 0) { // If the filename already contains the sub-directory, we don't add it. $subdir = NULL; } $serverport = ''; if ($_SERVER["SERVER_PORT"] != '80') { $serverport = ':' . $_SERVER["SERVER_PORT"]; } return 'http://' . $_SERVER["SERVER_NAME"] . $serverport . dirname($_SERVER["SCRIPT_NAME"]) . '/' . $subdir . $filename; } $downloader; if (!empty($_POST['filetoupload_url'])) { require_once 'vendor/Downloader.php'; $downloader = new Downloader(); } $filename; if (isset($_FILES['filetoupload']) && $_FILES['filetoupload']['error'] != UPLOAD_ERR_NO_FILE) { $filename = $_FILES['filetoupload']['name']; } else { $filename = basename($_POST['filetoupload_url']); } $filename = $subdir . '/' . $filename; if (!in_array($_POST['password'], $passwords)) { $flash['type'] = 'error'; $flash['title'] = 'Wrong password.'; $flash['text'] = 'Foreigners are forbidden here!'; } else { if ($_FILES['filetoupload']['error'] == UPLOAD_ERR_NO_FILE && empty($_POST['filetoupload_url'])) { $flash['type'] = 'error'; $flash['title'] = 'No file.'; $flash['text'] = 'Hey, if you want to upload a file, you need to send it! We can\'t imagine it ;) .'; } else { if ($_FILES['filetoupload']['error'] == UPLOAD_ERR_FORM_SIZE) { $flash['type'] = 'error'; $flash['title'] = 'This file is too big.'; $flash['text'] = 'We do not accept overweight files... Max size is 256 Mo.'; } else { if (!empty($_POST['filetoupload_url']) && ($file_content = $downloader->get($_POST['filetoupload_url'], array(), 'curl'))) { $file_content_data = $file_content['body']; $filename = determineFilename($subdir . '/' . basename($file_content['infos']['url']), $file_content_data); if (is_array($filename)) { $fileurl = getFileURL($filename[0], $subdir); $flash['type'] = 'success'; $flash['title'] = 'Well done!'; $flash['text'] = 'You have already uploaded this file. For the record, the file was uploaded to <a href="' . $fileurl . '">' . $fileurl . '</a>.'; } else { if ($file_content['HTTPCode'] != 200) { $flash['type'] = 'error'; $flash['title'] = 'Oh snap!'; $flash['text'] = 'There was an error while downloading the file. The server returned a <strong>' . $file_content['HTTPCode'] . '</strong> HTTP Status Code. Please try again!'; } else { if (!($file = fopen($subdir . '/' . basename($filename), 'w'))) { $flash['type'] = 'error'; $flash['title'] = 'Oh snap!'; $flash['text'] = 'There was an error while creating the file on the disk, please try again!'; } else { if (!fwrite($file, $file_content_data)) { $flash['type'] = 'error'; $flash['title'] = 'Oh snap!'; $flash['text'] = 'There was an error while writing the file on the disk, please try again!'; } else { fclose($file); $fileurl = getFileURL($filename, $subdir); $flash['type'] = 'success'; $flash['title'] = 'Well done!'; $flash['text'] = 'The file was uploaded to <a href="' . $fileurl . '">' . $fileurl . '</a>.'; } } } } } else { if (is_array(determineFilename($filename, $_FILES['filetoupload']['tmp_name'], true))) { $flash['type'] = 'error'; $flash['title'] = 'Oh snap!'; $flash['text'] = 'This file already exists. Please change his name ;) .'; } else { if (move_uploaded_file($_FILES['filetoupload']['tmp_name'], $filename)) { $fileurl = getFileURL($filename, $subdir); $flash['type'] = 'success'; $flash['title'] = 'Well done!'; $flash['text'] = 'The file was uploaded to <a href="' . $fileurl . '">' . $fileurl . '</a>.'; } else { $flash['type'] = 'error'; $flash['title'] = 'Oh snap!'; $flash['text'] = 'There was an error uploading the file, please try again!'; } } } } } } } return $app['twig']->render('upload.html.twig', array('section' => 'upload', 'scriptname' => $scriptname, 'flash' => $flash)); })->bind('upload');
$sql = "\n SELECT * \n FROM comments c\n WHERE c.post_id = :id\n "; $comments = $app['db']->fetchAll($sql, [':id' => $id]); return $app['twig']->render('post.html.twig', ['post' => $post, 'comments' => $comments]); }); //Защищенный паролем вход для добавления поста //>Используем формочку $app->match('/admin/add', function () use($app) { $form = $app['form.factory']->createBuilder('form')->add('title')->add('content', 'textarea')->getForm(); $form->handleRequest($app['request']); if ($form->isValid()) { $data = $form->getData(); //#####А это - *домашнее задание !* var_dump($data); // do something with the data // $sql = "INSERT ..."; $sql = "\n INSERT INTO posts (title, description)\n VALUES (:title, :content)\n "; $stmt = $app['db']->prepare($sql); $stmt->bindValue(":title", $data['title']); $stmt->bindValue(":content", $data['content']); $stmt->execute(); //redirect somewhere return $app->redirect('/blog/web'); } return $app['twig']->render('add.html.twig', ['form' => $form->createView()]); }); //Дальше понятно, но не успел... //Эксперименты с phpDocumentor не удались - он хотел документироватьь и Сайлекс)) //*phpDocumentor* хорош для случаев, когда создается много классов и их надо визуализировать //DOCCO - наше все ;-) http://jashkenas.github.io/docco/ $app->get('/admin/edit/{id}', function ($id) use($app) { return '';
$app->match('/playlist', function (Request $request) use($app) { $app->register(new FormServiceProvider()); $app->register(new TranslationServiceProvider()); $app->register(new ValidatorServiceProvider(), array('translator.messages' => array())); PlaylistService::init(); $pldata = array(); foreach (PlaylistService::getData() as $pld) { $pldata[$pld['id']] = $pld['name']; } $form = $app['form.factory']->createBuilder('form')->add('playlist', 'choice', array('choices' => $pldata, 'expanded' => true, 'constraints' => $request->request->get('stop') ? array() : array(new Assert\Choice(array_keys($pldata)), new Assert\NotNull())))->add('security', 'password', array('constraints' => array(new Security()), 'attr' => array('placeholder' => 'Biztonsági kód'), 'label' => 'Biztonsági kód'))->getForm(); if ('POST' == $request->getMethod()) { $form->bind($request); if ($form->isValid()) { $data = $form->getData(); $saved = false; if ($request->request->get('stop')) { PlaylistService::disablePlaylist(true); $saved = PlaylistService::savePlaylist(); } if ($request->request->get('play')) { PlaylistService::disablePlaylist(true); PlaylistService::enablePlaylist($data['playlist']); $saved = PlaylistService::savePlaylist(); } if ($saved) { $daemon = new Kiosk\Daemon(); $daemon->reload(); } // return $app->redirect('/playlist'); } } // display the form return $app['twig']->render('playlist.twig', array('form' => $form->createView(), 'permission_error' => !PlaylistService::isWritable())); });
$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'); } return $app['twig']->render('new.html.twig'); })->bind('new'); $app->match('/delete/{id}', function (\Symfony\Component\HttpFoundation\Request $request) use($app) { $app['rest.client']->delete('postits', $request->get('id')); return $app->redirect('/postits');
$app['assetic.filter_manager'] = $app->share($app->extend('assetic.filter_manager', function ($fm, $app) { $fm->set('lessphp', new Assetic\Filter\LessphpFilter()); return $fm; })); $app['assetic.asset_manager'] = $app->share($app->extend('assetic.asset_manager', function ($am, $app) { $am->set('styles', new Assetic\Asset\AssetCache(new Assetic\Asset\GlobAsset($app['assetic.input.path_to_css'], array($app['assetic.filter_manager']->get('lessphp'))), new Assetic\Cache\FilesystemCache($app['assetic.path_to_cache']))); $am->get('styles')->setTargetPath($app['assetic.output.path_to_css']); $am->set('scripts', new Assetic\Asset\AssetCache(new Assetic\Asset\GlobAsset($app['assetic.input.path_to_js']), new Assetic\Cache\FilesystemCache($app['assetic.path_to_cache']))); $am->get('scripts')->setTargetPath($app['assetic.output.path_to_js']); return $am; })); } // ----------------------------------------------- // Controllers $app->match('/', function () use($app) { return $app->redirect('/0'); })->bind('homepage'); $app->match('/{res}', function ($res) use($app) { $content = $app['md.finder']->getContent($res); if ($content) { $html = $app['md.parser']->transform($content); $title = $app['md.parser']->getTitle($content); return $app['twig']->render('markdown.html.twig', array('menu' => $app['md.finder']->getList(), 'current' => $res, 'html' => $html, 'title' => $title)); } return new Response("Sorry, the requested page could not be found.", 404); }); $app->error(function (\Exception $e, $code) use($app) { if ($app['debug']) { return; } $message = "[{$code}] ";
$params['paymentDatetime'] = date('Y-m-d\\TH:i:sP'); $checkData = \Yandex\Kassa\HttpNotification\PaymentAvisoParams::createWithArray($params); $params['md5'] = $checkData->signWithPassword($app['kassa.config']['shopPassword']); return $params; }; $makeSuccessData = function ($requestData) use($app, $makeCheckData) { $params = $makeCheckData($requestData); $params['action'] = 'PaymentSuccess'; $params['paymentDatetime'] = date('Y-m-d\\TH:i:sP'); return $params; }; $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views')); $app->match('/eshop.xml', function (Request $request) use($app, $makeCheckData, $makeAvisoData, $makeSuccessData) { $requestData = $request->request->getIterator()->getArrayCopy(); $checkData = $makeCheckData($requestData); $avisoData = $makeAvisoData($requestData); $successData = $makeSuccessData($requestData); return $app['twig']->render('eshop.html.twig', ['request' => $requestData, 'checkData' => $checkData, 'avisoData' => $avisoData, 'successData' => $successData]); }); $app->match('/notify/{what}', function ($what, Request $request) use($app) { $data = $request->get('data'); if (!in_array($what, ['paymentAvisoUrl', 'checkOrderUrl'])) { return sprintf('Неверный URL %s. Верные урлы: %s', $what, 'paymentAvisoUrl, checkOrderUrl'); } $url = $app['kassa.config'][$what]; $data = json_decode($data, true); if ($request->get('update_md5')) { $checkClass = $what == 'paymentAvisoUrl' ? 'PaymentAvisoParams' : 'CheckOrderParams'; $checkClass = sprintf('\\Yandex\\Kassa\\HttpNotification\\%s', $checkClass); $checkData = $checkClass::createWithArray($data); $data['md5'] = $checkData->signWithPassword($app['kassa.config']['shopPassword']);
//ALL CATEGORIES $app->get('/list', function () { global $app; global $snippets_model; $data = array('title' => 'all categories', 'snippets' => $snippets_model->get()); return $app['twig']->render('list.twig', $data); })->bind('list'); // PAGE CONTACT $app->match('/contact', function () { global $app; global $contact_model; $data = array('title' => 'contact page'); if (!empty($_POST)) { $state = $contact_model->insert($_POST); if (isset($state['sent'])) { $data['state_contact'] = $state['sent']; } else { if (isset($state['wrong_email'])) { $data['state_contact'] = $state['wrong_email']; } } } return $app['twig']->render('contact.twig', $data); })->bind('contact'); // Pagination $app->get('/page/{page}', function ($page) { // return 'Page ' .$page; global $app; global $snippets_model; $data = array('title' => 'Page', 'snippets' => $snippets_model->get_by_page($page), 'pages' => $snippets_model->get_pages($page)); return $app['twig']->render('page.twig', $data); })->assert('page', '\\d+')->bind('page');
<?php $loader = (include 'vendor/autoload.php'); $loader->add('', 'src'); $app = new Silex\Application(); $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); $app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/views']); // Fait remonter les erreurs $app['debug'] = true; $app['model'] = new Cinema\Model('localhost', 'cinema', 'root', 'root'); // Page d'accueil $app->match('/', function () use($app) { return $app['twig']->render('home.html.twig'); })->bind('home'); // Liste des films $app->match('/films', function () use($app) { return $app['twig']->render('films.html.twig', ['films' => $app['model']->getFilms()]); })->bind('films'); // Fiche film $app->match('/film/{id}', function ($id) use($app) { $request = $app['request']; if ($request->getMethod() == 'POST') { $post = $request->request; if ($post->has('nom') && $post->has('note') && $post->has('critique')) { // XXX: A faire } } return $app['twig']->render('film.html.twig', ['film' => $app['model']->getFilm($id), 'casting' => $app['model']->getCasting($id)]); })->bind('film'); // Genres $app->match('/genres', function () use($app) {
use Symfony\Component\Validator\Constraints as Assert; $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");
// Controller $app->match('/', function (Request $request) use($app) { date_default_timezone_set('Europe/Paris'); $startDate = new \DateTime('midnight first day of this month'); $endDate = new \DateTime('23:59:59 last day of +4 months'); $form = $app['form.factory']->create(new UserType()); if ($request->getMethod() === 'POST') { $form->bindRequest($request); if ($form->isValid()) { $data = $form->getData(); $data['startDate'] = $startDate; $data['endDate'] = $endDate; try { $client = new Client($data['login'], $data['password']); $events = $client->fetchEvents($data['startDate'], $data['endDate']); if (count($events) > 0) { return CalendarResponse::create($events); } $error = 'No event was found in your calendar.'; } catch (AuthenticationException $e) { $error = 'Your login or password is incorrect. Please try again.'; } catch (\Exception $e) { $error = 'There was an error (cas.tem-tsp.eu or si-etudiants.it-sudparis.eu might be offline). Please try again later.'; } if (isset($error)) { $form->addError(new FormError($error)); } } } return $app['twig']->render('layout.html.twig', array('form' => $form->createView(), 'startDate' => $startDate, 'endDate' => $endDate, 'formHasErrors' => $form->hasErrors())); }); return $app;
return $app['twig']->render('search.twig', array('search' => 'true')); })->bind('searchpage'); $app->match('/result-search', function (Request $request) use($app) { $key = $request->get('key'); $sql = "SELECT * FROM page WHERE title LIKE ? or text LIKE ? ORDER BY title"; $results = $app['db']->fetchAll($sql, array('%' . $key . '%', '%' . $key . '%')); $arrayObj = []; foreach ($results as $value) { $myObject = new myObject(); $myObject->setId($value['id']); $myObject->setTitle($value['title']); $myObject->setSummary($value['url']); $myObject->setText($value['text']); $arrayObj[] = $myObject; } $keyword = $request->get('keyword'); $sql = "SELECT * FROM object WHERE title LIKE ? ORDER BY title"; $produits = $app['db']->fetchAll($sql, array('%' . $key . '%')); $arrayObjProduit = []; foreach ($produits as $value) { $myObject = new myObject(); $myObject->setId($value['id']); $myObject->setTitle($value['title']); $myObject->setSummary($value['summary']); $myObject->setText($value['text']); $myObject->setImg($value['img']); $arrayObjProduit[] = $myObject; } return $app['twig']->render('result-search.twig', array('search' => 'true', 'key' => $key, 'arrayObj' => $arrayObj, 'arrayObjProduit' => $arrayObjProduit)); })->bind('resultsearchpage'); $app->get('/commande', function (Request $request) use($app) { return $app['twig']->render('commande.twig', array('commande' => 'true'));
$posts = $app['db']->fetchAll($sql); return $app['twig']->render('index.html.twig', ['posts' => $posts]); }); $app->get('/post/{id}', function ($id) use($app) { $sql = "\n SELECT * \n FROM posts p\n WHERE p.id = :id\n "; $post = $app['db']->fetchAssoc($sql, [':id' => $id]); $sql = "\n SELECT * \n FROM comments c\n WHERE c.post_id = :id\n "; $comments = $app['db']->fetchAll($sql, [':id' => $id]); return $app['twig']->render('post.html.twig', ['post' => $post, 'comments' => $comments]); }); $app->match('/admin/add', function () use($app) { $form = $app['form.factory']->createBuilder('form')->add('title')->add('content', 'textarea')->getForm(); $form->handleRequest($app['request']); if ($form->isValid()) { $data = $form->getData(); // do something with the data $sql = "INSERT ..."; // redirect somewhere return $app->redirect('/'); } return $app['twig']->render('add.html.twig', ['form' => $form->createView()]); }); $app->get('/admin/edit/{id}', function ($id) use($app) { return ''; }); $app->get('/admin/delete/{id}/', function ($id) use($app) { return ''; }); $app->get('/add-comment', function () use($app) { return ''; }); $app->get('/edit-comment/{id}', function ($id) use($app) {
$card = $app['request']->get('card'); // save POST data into session $app['session']->set($sessionVar . '.purchase', $params); $app['session']->set($sessionVar . '.card', $card); $params['card'] = $card; $params['clientIp'] = $app['request']->getClientIp(); $response = $gateway->purchase($params)->send(); return $app['twig']->render('response.twig', array('gateway' => $gateway, 'response' => $response)); }); // gateway purchase return // this won't work for gateways which require an internet-accessible URL (yet) $app->match('/gateways/{name}/completePurchase', function ($name) use($app) { $gateway = Omnipay\Common\GatewayFactory::create($name); $sessionVar = 'omnipay.' . $gateway->getShortName(); $gateway->initialize((array) $app['session']->get($sessionVar)); // load request data from session $params = $app['session']->get($sessionVar . '.purchase', array()); $params['clientIp'] = $app['request']->getClientIp(); $response = $gateway->completePurchase($params)->send(); return $app['twig']->render('response.twig', array('gateway' => $gateway, 'response' => $response)); }); // create gateway create Credit Card $app->get('/gateways/{name}/create-card', 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 . '.create', array()); $card = new Omnipay\Common\CreditCard($app['session']->get($sessionVar . '.card')); return $app['twig']->render('request.twig', array('gateway' => $gateway, 'method' => 'createCard', 'params' => $params, 'card' => $card->getParameters())); }); // submit gateway create Credit Card $app->post('/gateways/{name}/create-card', function ($name) use($app) {
$app->match('/libro/{ident}/change/', function (Request $request, $ident) use($app) { $sent = false; /*include 'dbcon.php'; while($row = $STH->fetch()){ if($row['id']=$ident){ $default = array( 'id' => ''.$row['id'].'', 'title' => ''.$row['title'].'', 'price' => ''.$row['price'].'', 'description' => ''.$row['description'].'', ); } } $form = $app['form.factory']->createBuilder('form', $default) ->add('title') ->add('price') ->add('description') ->getForm(); $form->handleRequest($request);*/ $link = mysql_connect('localhost', 'root', '') or die('Can not connect to server: ' . mysql_error()); mysql_select_db('books') or die('Can not select the data base.'); mysql_query("SET NAMES 'utf8'"); $query = mysql_query("SELECT * FROM `books` WHERE `id`={$ident}"); $default = mysql_fetch_row($query); $default = array('id' => $default[0], 'title' => $default[1], 'price' => $default[2], 'description' => $default[3]); $form = $app['form.factory']->createBuilder('form', $default)->add('title')->add('price')->add('description')->getForm(); $form->handleRequest($request); if ('POST' == $request->getMethod()) { if ($form->isValid()) { $default = $form->getData(); $sid = $default['id']; $stitle = mysql_real_escape_string($default['title']); $sprice = filter_var($default['price'], FILTER_VALIDATE_FLOAT); $sdesc = mysql_real_escape_string($default['description']); $link = mysql_connect('localhost', 'root', '') or die('Can not connect to server: ' . mysql_error()); mysql_select_db('books') or die('Can not select the data base.'); mysql_query("SET NAMES 'utf8'"); $query = "UPDATE `books` SET `title` = '{$stitle}', `price` = '{$sprice}', `description` = '{$sdesc}' WHERE `books`.`id` = '{$sid}'"; $result = mysql_query($query) or die('Error!: ' . mysql_error()); if ($result) { echo "Ready."; echo "<br>"; return "<a href=\"/bootcamp/wtwo/\">Home</a>"; } mysql_close($link); } } return $app['twig']->render('index.twig', array('form' => $form->createView())); echo "<br>"; });
require_once __DIR__ . '/../vendor/autoload.php'; $app = new Silex\Application(); $app['debug'] = true; // Hello world handler with name parameter. $app->get('/', function (\Symfony\Component\HttpFoundation\Request $request) { $name = $request->get('name', 'world'); return new \Symfony\Component\HttpFoundation\Response('Hello ' . $name); }); // Simple POST form. $app->match('/form', function (\Symfony\Component\HttpFoundation\Request $request) { return new \Symfony\Component\HttpFoundation\Response(' <html> <body> <p>Method: ' . var_export($request->getMethod(), true) . '</p> <p>POST values: ' . var_export($request->request->all(), true) . '</p> <form method="POST"> <input type="text" name="foo" value="bar" /> <input type="submit" value="Send" /> </form> </body> </html> '); }); // Simple file upload. $app->match('/fileupload', function (\Symfony\Component\HttpFoundation\Request $request) { /** @var $file \Symfony\Component\HttpFoundation\File\UploadedFile */ $file = $request->files->get('aFile'); $fileContent = ''; if ($file) { $fileContent = file_get_contents($file->getPathname()); } return new \Symfony\Component\HttpFoundation\Response('
$app['guzzle'] = $app->share(function () use($app) { return new Guzzle\Http\Client(); }); $app->register(new Silex\Provider\ServiceControllerServiceProvider()); $app->register(new Silex\Provider\ValidatorServiceProvider()); $app['home'] = $app->share(function () use($app) { return new Controllers\Home(); }); $app['versions'] = $app->share(function () use($app) { $versions = new Models\Versions($app['db']); return new Controllers\Versions($versions); }); $app->before(function (Request $request, Silex\Application $app) { if (extension_loaded('newrelic')) { newrelic_name_transaction(current(explode('?', $_SERVER['REQUEST_URI']))); } }); $app->after(function (Request $request, Response $response) { $response->headers->set('Access-Control-Allow-Origin', '*'); $response->headers->set('Access-Control-Allow-Methods', 'GET,POST,HEAD,DELETE,PUT,OPTIONS'); $response->headers->set('Access-Control-Allow-Headers', 'Content-Type'); if ($response->getStatusCode() == 200) { $response->headers->set('Content-Type', 'application/json; charset=UTF-8'); } }); $app->match("{url}", function ($url) use($app) { return "OK"; })->assert('url', '.*')->method("OPTIONS"); $app->get('/projects/{project}/latest', 'versions:latest'); $app->get('/', 'home:index'); $app->run();
<?php use Inventis\WebStandards\NodeRouter; use Inventis\WebStandards\Twig\Extension\FileInclude; use Inventis\WebStandards\WebStandardsServiceProvider; use Symfony\Component\HttpFoundation\Request; ini_set('display_errors', 'On'); require_once __DIR__ . '/../vendor/autoload.php'; $app = new Silex\Application(); $app['debug'] = true; // Web Standards $app->register(new WebStandardsServiceProvider(__DIR__ . '/../resources/views/')); // Routing $app->match('/', function (Request $request) use($app) { $app['web-standards']->addPath(__DIR__ . '/docs/home', NodeRouter::VISIBILITY_HIDDEN)->addPath(__DIR__ . '/docs/standards', NodeRouter::VISIBILITY_DEV)->addPath(__DIR__ . '/docs/pages', NodeRouter::VISIBILITY_DEV)->addPath(__DIR__ . '/docs/examples', NodeRouter::VISIBILITY_DEV)->addPath(__DIR__ . '/docs/partials')->addPath(__DIR__ . '/docs/miscellaneous')->addPath(__DIR__ . '/docs/checklists'); $page = $request->query->get('p', 'home/home.md'); if ($request->query->getBoolean('iframe', false) == true) { return $app['web-standards']->renderIframeContent($page); } else { return $app['web-standards']->renderPage($page); } }); $app->run();
require_once __DIR__ . '/../vendor/autoload.php'; define('GOOGLE_API_KEY', '389361308386-0lc02qa6gs3q0pf7j86hhj169to93jh9.apps.googleusercontent.com'); define('GOOGLE_API_SECRET', 'nijEu5O05kXBLQv9pawzrF9Z'); $app = new Silex\Application(); error_reporting(E_ALL); ini_set('display_errors', 1); $app['debug'] = true; $app->register(new Gigablah\Silex\OAuth\OAuthServiceProvider(), array('oauth.services' => array('Google' => array('key' => GOOGLE_API_KEY, 'secret' => GOOGLE_API_SECRET, 'scope' => array('https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile'), 'user_endpoint' => 'https://www.googleapis.com/oauth2/v1/userinfo')))); // Provides URL generation $app->register(new Silex\Provider\UrlGeneratorServiceProvider()); // Provides CSRF token generation $app->register(new Silex\Provider\FormServiceProvider()); // Provides session storage $app->register(new Silex\Provider\SessionServiceProvider(), array('session.storage.save_path' => __DIR__ . '/../cache')); // Provides Twig template engine $app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__)); $app->register(new Silex\Provider\SecurityServiceProvider(), array('security.firewalls' => array('default' => array('pattern' => '^/', 'anonymous' => true, 'oauth' => array('failure_path' => '/', 'with_csrf' => true), 'logout' => array('logout_path' => '/logout', 'with_csrf' => true), 'users' => new Gigablah\Silex\OAuth\Security\User\Provider\OAuthInMemoryUserProvider())), 'security.access_rules' => array(array('^/auth', 'ROLE_USER')))); $app->before(function (Symfony\Component\HttpFoundation\Request $request) use($app) { $token = $app['security']->getToken(); $app['user'] = null; if ($token && !$app['security.trust_resolver']->isAnonymous($token)) { $app['user'] = $token->getUser(); } }); $app->get('/', function () use($app) { return $app['twig']->render('index.twig', array('login_paths' => $app['oauth.login_paths'], 'logout_path' => $app['url_generator']->generate('logout', array('_csrf_token' => $app['oauth.csrf_token']('logout'))))); }); $app->match('/logout', function () { })->bind('logout'); $app->run();
$app->match('/parse/url', function (Request $request) { $response = new Response(); $input = $request->get('input', NULL); if ($input !== NULL) { // Create the URL object $url = parse_url($input); if (isset($url['query'])) { parse_str($url['query'], $query); ksort($query); $url['query'] = $query; } // Create the Goutte client/crawler object $client = new Client(); //$client->setHeader('User-Agent', 'facebookexternalhit/1.1 (+https://www.facebook.com/externalhit_uatext.php)'); // Amazon hides the Open Graph data from everyone except Facebook $crawler = $client->request('GET', $input); // Create the OGP object $ogp = new OpenGraph(); // Set the OGP URL $ogpUrl = $crawler->filterXPath('//head//meta[@property="og:url"]'); if (count($ogpUrl) > 0) { $ogp->setUrl($ogpUrl->attr('content')); } $ogpUrl = $ogp->getUrl(); if ($ogpUrl == NULL) { $ogp->setUrl($url); } // Set the OGP title $ogpTitle = $crawler->filterXPath('//head//meta[@property="og:title"]'); if (count($ogpTitle) > 0) { $ogp->setTitle($ogpTitle->attr('content')); } $ogpTitle = $ogp->getTitle(); if ($ogpTitle == NULL) { $ogpTitle = $crawler->filter('title'); if (count($ogpTitle) > 0) { $ogp->setTitle($ogpTitle->text()); } } // Set the OGP image $ogpImage = $crawler->filterXPath('//head//meta[@property="og:image"]'); if (count($ogpImage) > 0) { $ogp->setImage($ogpImage->attr('content')); } $response->headers->set('Content-type', 'application/json'); $response->setContent($ogp->json()); } else { $response->setStatusCode(400); } return $response; })->method('GET|POST');