Ejemplo n.º 1
0
 /**
  * @param $template
  */
 public function render($template)
 {
     if (!$this->path) {
         $app = new \Silex\Application();
         $app->abort(500, "Path not defined!");
     }
     $file = $this->path . strtolower($template) . $this->extension;
     if (file_exists($file)) {
         $this->render = $file;
     } else {
         header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
         die('Template ' . $template . ' not found!');
     }
     $this->data['app'] = $this->app;
     extract($this->data);
     include $this->render;
 }
Ejemplo n.º 2
0
$app->get('/', function (Silex\Application $app) {
    // Match the root route (/) and supply the application as argument
    $project = array();
    foreach ($app['recipes'] as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            $projects[] = $folder;
        }
    }
    return $app['twig']->render('projects-list.html.twig', array('projects' => $projects));
});
//edition d'un projet
$app->get('/projects/{name}', function (Silex\Application $app, $name) {
    $project = array();
    $project['name'] = $name;
    if (!in_array($name, $app['recipes'])) {
        $app->abort(404, 'The project could not be found');
    }
    //on vérifie que le fichier déploiement existe sino on le créé
    $file_path = RECIPES_FOLDER . '/' . $name . '/deploy.php';
    if (!file_exists($file_path)) {
        touch($file_path);
        chmod($file_path, 0755);
    }
    $myfile = fopen($file_path, "r");
    $filesize = filesize($file_path);
    $project['deploy_file_content'] = $filesize > 0 ? fread($myfile, $filesize) : "";
    fclose($myfile);
    return $app['twig']->render('project-single.html.twig', array('project' => $project));
    return $output;
    // Return it to so it gets displayed by the browser
})->bind('project_edit');
Ejemplo n.º 3
0
 });
 $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();
     $log = $client->getFirstLog();
     return $app->redirect($app['url_generator']->generate('log', array('clientSlug' => $client->getSlug(), 'logSlug' => $log->getSlug())));
 })->bind("home");
 $app->get('/logs/{clientSlug}', function ($clientSlug) use($app) {
     $viewer = new Syonix\LogViewer\LogViewer($app['config']['logs']);
     $client = $viewer->getClient($clientSlug);
     $log = $client->getFirstLog();
     if (is_null($log)) {
         $app->abort(404, "Client not found");
     }
     return $app->redirect($app['url_generator']->generate('log', array('clientSlug' => $clientSlug, 'logSlug' => $log->getSlug())));
 })->bind("client");
 $controller_log = function (\Symfony\Component\HttpFoundation\Request $request, $clientSlug, $logSlug) use($app) {
     try {
         $viewer = new Syonix\LogViewer\LogViewer($app['config']['logs']);
         $clients = $viewer->getClients();
         $client = $viewer->getClient($clientSlug);
         if ($client === null || !$client->logExists($logSlug)) {
             $app->abort(404, "Log file not configured");
         }
         $log = $client->getLog($logSlug)->load();
         $minLogLevel = $request->query->get('m');
         $currentLogger = $request->query->get('l');
         if ($currentLogger && !$log->getLoggers()->contains($currentLogger)) {
Ejemplo n.º 4
0
$app['debug'] = true;
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'starappleblog', 'username' => 'root', 'password' => 'root')));
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
//$twig = new Twig_Environment($loader, array('debug' => true));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../templates', 'twig.options' => array('cache' => false)));
$app->get('/', function () use($app) {
    $postModel = new Post($app['db']);
    $postsToDisplay = $postModel->getAll();
    return $app['twig']->render('post_index.html.twig', array('posts' => $postsToDisplay));
})->bind('post_index');
// name the route so it can be referred to
$app->get('/post/{post_id}', function ($post_id) use($app) {
    $postModel = new Post($app['db']);
    $postToDisplay = $postModel->get($post_id);
    if (!$postToDisplay) {
        $app->abort(404, 'The article could not be found');
    }
    return $app['twig']->render('post_single.html.twig', array('post' => $postToDisplay));
})->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');
 public function feed($contenttypeslug = '')
 {
     // jQuery not required
     $this->app['extensions']->disableJquery();
     // Clear snippet list. There's no clear any more, so just set to null
     $this->app['extensions']->clearSnippetQueue();
     $this->app['debugbar'] = false;
     // Defaults for later
     $defaultFeedRecords = 5;
     $defaultTemplate = 'rss.twig';
     $content = array();
     $contenttypes = array();
     // If we're on the front page, use sitewide configuration
     if ($contenttypeslug == '') {
         $contenttypeslug = 'sitewide';
     }
     if (!isset($this->config[$contenttypeslug]['enabled']) || $this->config[$contenttypeslug]['enabled'] != 'true') {
         $this->app->abort(404, "Feed for '{$contenttypeslug}' not found.");
     }
     // Better safe than sorry: abs to prevent negative values
     $amount = (int) abs(!empty($this->config[$contenttypeslug]['feed_records']) ? $this->config[$contenttypeslug]['feed_records'] : $defaultFeedRecords);
     // How much to display in the description. Value of 0 means full body!
     $contentLength = (int) abs(!empty($this->config[$contenttypeslug]['content_length']) ? $this->config[$contenttypeslug]['content_length'] : 0);
     // Get our content
     if ($contenttypeslug == 'sitewide') {
         foreach ($this->config[$contenttypeslug]['content_types'] as $types) {
             $contenttypes[] = $this->app['storage']->getContentType($types);
         }
     } else {
         $contenttypes[] = $this->app['storage']->getContentType($contenttypeslug);
     }
     // Get content for each contenttype we've selected as an assoc. array
     // by content type
     foreach ($contenttypes as $contenttype) {
         $content[$contenttype['slug']] = $this->app['storage']->getContent($contenttype['slug'], array('limit' => $amount, 'order' => 'datepublish desc'));
     }
     // Now narrow our content array to $amount based on date
     $tmp = array();
     foreach ($content as $slug => $recordid) {
         if (!empty($recordid)) {
             foreach ($recordid as $record) {
                 $key = strtotime($record->values['datepublish']) . $slug;
                 $tmp[$key] = $record;
             }
         }
     }
     // Sort the array and return a reduced one
     krsort($tmp);
     $content = array_slice($tmp, 0, $amount);
     if (!$content) {
         $this->app->abort(404, "Feed for '{$contenttypeslug}' not found.");
     }
     // Then, select which template to use, based on our
     // 'cascading templates rules'
     if (!empty($this->config[$contenttypeslug]['feed_template'])) {
         $template = $this->config[$contenttypeslug]['feed_template'];
     } else {
         $template = $defaultTemplate;
     }
     $this->app['twig.loader.filesystem']->addPath(dirname(__DIR__) . '/assets/');
     $body = $this->app['render']->render($template, array('records' => $content, 'content_length' => $contentLength, $contenttype['slug'] => $content));
     $response = new Response($body, Response::HTTP_OK);
     $response->setCharset('utf-8')->setPublic()->setSharedMaxAge(3600)->headers->set('Content-Type', 'application/rss+xml');
     return $response;
 }
Ejemplo n.º 6
0
Archivo: app.php Proyecto: pixlr/SZES
$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
    $user_name = $request->get('user');
    if (!empty($user_name)) {
        $user = $app['auth.login']->getUser();
Ejemplo n.º 7
0
}));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => array('templates'), 'twig.options' => array('debug' => $app['debug'], 'charset' => 'utf-8', 'strict_variables' => false, 'autoescape' => true, 'cache' => false, 'optimizations' => -1)));
use Knp\Provider\ConsoleServiceProvider;
$app->register(new ConsoleServiceProvider(), array('console.name' => 'Chamilo', 'console.version' => '1.0.0', 'console.project_directory' => __DIR__ . '/..'));
// Adding commands.
/** @var Knp\Console\Application $console */
$console = $app['console'];
$console->addCommands(array(new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(), new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\DiffCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\ExecuteCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\GenerateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\MigrateCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\StatusCommand(), new \Doctrine\DBAL\Migrations\Tools\Console\Command\VersionCommand(), new Chash\Command\Installation\UpgradeCommand(), new Chash\Command\Installation\InstallCommand(), new Chash\Command\Files\CleanDataFilesCommand(), new Chash\Command\Files\CleanTempFolderCommand(), new Chash\Command\Files\CleanConfigFilesCommand(), new Chash\Command\Files\MailConfCommand(), new Chash\Command\Files\SetPermissionsAfterInstallCommand(), new Chash\Command\Files\GenerateTempFileStructureCommand()));
$helpers = array('configuration' => new Chash\Helpers\ConfigurationHelper());
$helperSet = $console->getHelperSet();
foreach ($helpers as $name => $helper) {
    $helperSet->set($helper, $name);
}
$blockInstallation = function () use($app) {
    if (file_exists($app['root_sys'] . 'config/configuration.php') || file_exists($app['root_sys'] . 'config/configuration.yml')) {
        return $app->abort(500, "A Chamilo installation was found. You can't reinstall.");
    }
    $defaultTimeZone = ini_get('date.timezone');
    if (empty($defaultTimeZone)) {
        $app->abort(500, "Please set your 'date.timezone' setting in your php.ini file");
    }
    // Check the PHP version.
    if (api_check_php_version() == false) {
        $app->abort(500, "Incorrect PHP version.");
    }
    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.");
Ejemplo n.º 8
0
$app['debug'] = getenv('CS_DEBUG');
/** Sanity check.
 */
$app->get('/hello/{name}', function ($name) use($app) {
    return 'Hello ' . $app->escape($name) . ' - ' . date('H:m:i');
});
/** HTML test page 'cs.html'
 *
 * @return object HTML response.
 */
$app->get('/cs{any}', function () use($app) {
    return $app->sendFile(__DIR__ . '/app-cs.html');
});
$app->get('/files/{path}', function ($path) use($app) {
    if (!file_exists(__DIR__ . '/' . $path)) {
        $app->abort(404);
    }
    if (!preg_match('/^[\\w\\-]+\\.(html|js|css|png)$/', $path)) {
        $app->abort(403);
        // Security!
    }
    return $app->sendFile(__DIR__ . '/' . $path);
});
/** Use the image request endpoint to start the transaction.
 *
 * @return JsonResponse JSON, including a `token`.
 */
$app->get('/api/image_requests', function (Request $request) use($app) {
    $api_key = getenv('CS_API_KEY');
    $query = $request->query;
    //$is_mock = $request->get( 'mock', true );
Ejemplo n.º 9
0
$app->register(new Silex\Provider\TranslationServiceProvider());
//De dang ki twig path
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => ROOT . '/resources/views/'));
// De su dung asset trong twig
$app['twig'] = $app->share($app->extend('twig', function ($twig, $app) {
    $twig->addFunction(new \Twig_SimpleFunction('asset', function ($asset) {
        return sprintf(BASE_URL . '/%s', ltrim($asset, '/'));
    }));
    return $twig;
}));
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Silex\Provider\TranslationServiceProvider(), array('translator.domains' => array()));
$app->register(new Silex\Provider\SessionServiceProvider());
// Register controllers
$app["user.controller"] = $app->share(function () use($app) {
    return new SampleApp\Controller\UserController($app);
});
$app["post.controller"] = $app->share(function () use($app) {
    return new SampleApp\Controller\PostController($app);
});
$app['debug'] = true;
// Register ServiceProvider for every Objects
$app->register(new SampleApp\Providers\UserServiceProvider($app));
$app->register(new SampleApp\Providers\PostServiceProvider($app));
//
$app->mount('/user', new SampleApp\Providers\UserControllerProvider());
$app->get('/', function () use($app) {
    return $app->abort(404, "Page not found");
});
$app->mount('/posts', new SampleApp\Providers\PostControllerProvider());
return $app;
Ejemplo n.º 10
0
 * Authenticates a user via either a Bearer access token or the users credentials
 * If valid authentication, a json representation of the user is returned in the response
 */
$app->get('/api/user', function (\Symfony\Component\HttpFoundation\Request $request) use($app, $db) {
    $user = null;
    //if an access token was presented, attempt to authenticate with that
    //this could have been from the SSO workflow with MemberFuse
    if ($request->headers->has('authorization')) {
        //split the header value into its parts... Bearer and the actual token
        $auth = explode(' ', $request->headers->get('authorization'));
        if ($auth[0] == 'Bearer') {
            $token = $auth[1];
            //look for the token in our db. this will have been
            //created during the last step of the SSO workflow
            if (!($token = $db->tokens->findOne(array('token' => $token)))) {
                $app->abort(401, 'invalid_token');
            }
            //tokens are associated to a user so use the token to find the
            //correct user to return
            if (!($user = $db->users->findOne(array('_id' => $token['user_id'])))) {
                $app->abort(401, 'unauthorized_token');
            }
        } else {
            $app->abort(400, 'invalid authorization type. must be Bearer ' . $auth[0] . ' given');
        }
    }
    //if above didn't produce a user try with user credentials from the basic auth
    //This is supporting the External Authentication function
    if (!$user) {
        if (!($user = $db->users->findOne(array('username' => $request->getUser(), 'password' => $request->getPassword())))) {
            $app->abort(401, 'user credentials authentication failed');
Ejemplo n.º 11
0
            $e['infraestrutura'] = $estatistica['quantidade'];
        }
        if ($estatistica['tipo'] == 'outros') {
            $e['outros'] = $estatistica['quantidade'];
        }
    }
    return $app->json(array('data' => $e));
});
$app->get('/eventos/{id}', function ($id) use($app) {
    $db = Database::open();
    $query = $db->executeQuery('SELECT * FROM eventos WHERE id = ?', array($id));
    $evento = $query->fetch();
    if ($evento) {
        return $app->json(array('data' => $evento));
    } else {
        return $app->abort(404);
    }
});
$app->post('/eventos/{id}', function ($id, Request $request) use($app) {
    $evento = json_decode($request->getContent());
    $db = Database::open();
    if ($evento->id == 0) {
        $r = $db->executeUpdate('INSERT INTO eventos(nome, estado, cidade) VALUES(?, ?, ?)', array($evento->nome, $evento->estado, $evento->cidade));
        $evento->id = $db->lastInsertId();
    } else {
        $r = $db->executeUpdate('UPDATE eventos SET nome = ?, estado = ?, cidade = ? WHERE id = ?', array($evento->nome, $evento->estado, $evento->cidade, $evento->id));
    }
    return $app->json(array('data' => $evento));
});
$app->delete('/eventos/{id}', function ($id) use($app) {
    $db = Database::open();
Ejemplo n.º 12
0
$app['books_db'] = new FileDB($data_file);
// Books validator
$app['book_schema'] = json_decode(file_get_contents('../schemas/books.json'));
$app['json_schema_validator'] = new JsonSchema\Validator();
// Error management
$app->error(function (Exception $e, $code) use($app) {
    $message = $e->getMessage();
    if (!$message) {
        $message = Response::$statusTexts[$code];
    }
    return $app->json($message, $code);
});
// Only accept JSON
$checkJSON = function (Request $request) use($app) {
    if (0 !== strpos($request->headers->get('Content-Type'), 'application/json')) {
        return $app->abort(400, 'application/json required');
    }
    $data = json_decode($request->getContent(), true);
    if (is_null($data)) {
        return $app->abort(400, 'valid non-null JSON expected');
    }
};
// Only accept valid book
$checkBook = function (Request $request) use($app) {
    $book = json_decode($request->getContent());
    $validator = $app['json_schema_validator'];
    $validator->check($book, $app['book_schema']);
    if (!$validator->isValid()) {
        return $app->json($validator->getErrors(), 400);
    }
};
Ejemplo n.º 13
0
            }
            echo "}" . "<br>";
        }
        echo "<a href='/users/new'>Retry</a><br>";
        return "Form contains errors..";
    }
    return new Response("User created! <a href='/users/" . $resp->id . "'>check out</a>", 201);
});
//get
$app->get('users/{id}', function (Silex\Application $app, $id) {
    // Add a parameter for an ID in the route, and it will be supplied as argument in the function
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET', "https://basic-rails-api.herokuapp.com/api/v1/users/" . $id);
    $user = json_decode($res->getBody());
    if (!$user->status) {
        $app->abort(404, 'The user could not be found');
    }
    return $app['twig']->render('user.html.twig', array('user' => $user->data, 'id' => $id));
})->assert('id', '\\d+')->bind('user');
// name the route so it can be referred to later in the section 'Generating routes'
//edit form
$app->get('/users/{id}/edit', function (Silex\Application $app, $id) {
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET', "https://basic-rails-api.herokuapp.com/api/v1/users/" . $id);
    $user = json_decode($res->getBody());
    if (!$user->status) {
        $app->abort(404, 'The user could not be found');
    }
    return $app['twig']->render('edit-user.html.twig', array('user' => $user->data, 'id' => $id));
    // return "Lets edit".$id;
})->bind("edit-user");
Ejemplo n.º 14
0
    // 		'curl' => [
    // 		        CURLOPT_SSL_VERIFYHOST => false,
    // 		        CURLOPT_VERBOSE => true
    // 		    ],
    // 		'verify' => false,
    // 		debug => true
    // 	]
    // 	);
    $res = \Requests::get('http://alltheragefaces.com/api/search/' . $search);
    $json = json_decode($res->body);
    // $json   = json_decode( $res->getBody() );
    if ($json && is_array($json)) {
        $img = $json[array_rand($json)];
        return $img;
    }
    $app->abort(200, 'Failed to fetch anything from the API :(');
};
$app->get('/', function (\Silex\Application $app) {
    $img = $app['fetch_rage'];
    return sprintf('<img src="%s" alt="%s" />', $app->escape($img->png), $app->escape($img->title));
});
$app->post('/', function (\Silex\Application $app) {
    $img = $app['fetch_rage'];
    // check for slack data
    $token = $app['request']->get('token');
    if ($token && isset($app['webhooks'][$token])) {
        // check if user chat or channel
        $channel = $app['request']->get('channel_name') === 'directmessage' ? $app['request']->get('channel_id') : '#' . $app['request']->get('channel_name');
        $payload = json_encode(['text' => '/rage ' . $app['request']->get('text'), 'channel' => $channel, 'username' => $app['request']->get('user_name'), 'icon_url' => 'http://cdn.alltheragefaces.com/img/faces/png/troll-troll-face.png', 'attachments' => [['title' => $img->title, 'fallback' => $img->title, 'image_url' => $img->png]]]);
        // $client  = new \GuzzleHttp\Client();
        // $promise = $client->postAsync( $app['webhooks'][ $token ], [ 'body' => $payload ] );
Ejemplo n.º 15
0
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;
/**
 * Get services list
 * @param object $app
 * @param int $page
 * @returns string
 */
$app->get('/items/{page}', function (Silex\Application $app, $page) {
    if ($app['session']->get('user_id') === null) {
        $app->abort(403, "Request is not allowed.");
        exit;
    }
    $pageSize = 10;
    $page = intval($page);
    $qb = $app['db']->createQueryBuilder()->select('*')->from('services')->orderBy('id', 'DESC')->setFirstResult($pageSize * ($page - 1))->setMaxResults($pageSize);
    $data = $qb->execute()->fetchAll();
    $total_q = $app['db']->createQueryBuilder()->select('count(*)')->from('services')->execute()->fetch();
    $total = intval(current($total_q));
    $result['data'] = $data;
    $result['total'] = $total;
    return $app->json($result);
});
/**
 * Save new service item
 * @param object $app
Ejemplo n.º 16
0
$app->get('/', function () use($app, $db, $getRecent) {
    return $app['twig']->render('home.html.twig', array('recent' => $getRecent($db), 'name' => isset($_COOKIE['name']) ? $_COOKIE['name'] : ''));
});
/**
 * Display the codepad.
 */
$app->get('/codepad', function () use($app, $db, $getRecent) {
    return $app['twig']->render('new-paste.html.twig', array('recent' => $getRecent($db), 'name' => isset($_COOKIE['name']) ? $_COOKIE['name'] : ''));
});
/**
 * Display a specific paste in the codepad.
 */
$app->get('/codepad/{id}', function ($id) use($app, $db, $getRecent, $getPaste) {
    $paste = $getPaste($db, $id);
    if ($paste === false) {
        $app->abort(404, 'Paste does not exist');
    }
    return $app['twig']->render('paste.html.twig', array('recent' => $getRecent($db), 'paste' => $paste, 'name' => isset($_COOKIE['name']) ? $_COOKIE['name'] : ''));
})->assert('id', '[^.]+');
$app->post('/codepad', function () use($app, $db, $config) {
    /**
     * Write the content to a temporary file, execute it
     * and delete the temporary file.
     */
    $tmpfile = '/tmp/saffire.codepad.' . posix_getpid();
    $dotfile = '/tmp/saffire.dotfile.' . posix_getpid();
    $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) {
Ejemplo n.º 17
0
    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 {
            return new Response(json_encode(array('message' => 'File upload error!')), '500');
        }
    }
});
$app->get('pages/{id}', function (Silex\Application $app, $id) {
    // Add a parameter for an ID in the route, and it will be supplied as argument in the function
    if (!array_key_exists($id, $app['files'])) {
        $app->abort(404, 'The PDF file could not be found');
    }
    $file = $app['files'][$id];
    $parser = new \Smalot\PdfParser\Parser();
    $filepath = dirname(__FILE__) . '/../uploads/' . $file;
    $document = $parser->parseFile($filepath);
    $details = $document->getDetails();
    $dir = dirname(__FILE__) . '/../uploads/pages/' . $id;
    if (!file_exists($dir)) {
        $dirCreate = mkdir($dir);
        for ($i = 1; $i <= $details['Pages']; $i++) {
            $fpdi = new FPDI();
            $fpdi->setSourceFile($filepath);
            $tpl = $fpdi->importPage($i);
            $size = $fpdi->getTemplateSize($tpl);
            $orientation = $size['h'] > $size['w'] ? 'P' : 'L';
Ejemplo n.º 18
0
define('APP_DIR', __DIR__);
require_once APP_DIR . '/../vendor/autoload.php';
$app = new Silex\Application();
/**
 * Register database service
 */
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('dbname' => 'mydb', 'user' => 'user', 'password' => 'secret', 'host' => 'localhost', 'driver' => 'pdo_mysql')));
/**
 * router
 */
$app->post('/translate', '\\SlackBotService\\Controller\\Translate::translate');
$app->post('/zingmp3', '\\SlackBotService\\Controller\\ZingMp3::post');
$app->post('/meme/generate', '\\SlackBotService\\Controller\\Meme::generate');
$app->post('/meme/list', '\\SlackBotService\\Controller\\Meme::memoList');
$app->post('/quote', '\\SlackBotService\\Controller\\Quote::post');
$app->post('/horoscope', '\\SlackBotService\\Controller\\Horoscope::post');
$app->post('/funnyimage/random', '\\SlackBotService\\Controller\\FunnyImage::post');
$app->get('/public/meme/{filename}', function (Silex\Application $app, $filename) {
    $filePath = APP_DIR . '/public/meme/' . $filename;
    if (!file_exists($filePath)) {
        $app->abort(404, $filePath . ' not found.');
    }
    return $app->sendFile($filePath);
});
/**
 * Error handler
 */
$app->error(function (\Exception $e, $code) {
    return new JsonResponse(array('errorCode' => $code, 'message' => $e->getMessage()));
});
$app->run();
Ejemplo n.º 19
0
$app['debug'] = API_DEUG;
//Роуты
//Корень - редирект на /api/users
$app->get('/', function () use($app) {
    return $app->redirect('index.html');
});
//Корень API - редирект на страницу документации
$app->get('/api/', function () use($app) {
    return 'Phonebook API works!';
});
//Получить список пользователей
$app->get('/api/users/', function () use($app) {
    $sql = 'SELECT * FROM phonebook';
    $users = $app['db']->fetchAll($sql);
    if (!$users) {
        return $app->abort(201, 'No content');
    }
    return $app->json(array('status' => 'ok', 'data' => $users));
});
//Получить данные пользователя
$app->get('/api/users/search/{name}', function ($name) use($app) {
    $sql = 'SELECT * FROM phonebook WHERE name = ?';
    $user = $app['db']->fetchAll($sql, array($name));
    if (!$user) {
        return $app->abort(201, 'Specified content not found');
    }
    return $app->json(array('status' => 'ok', 'data' => $user));
});
//Добавить пользователя
$app->post('/api/users/', function () use($app) {
    $name = $app['request']->get('name');
Ejemplo n.º 20
0
$app->get('/users', function () use($app, $users) {
    $app['monolog']->addInfo("ad1");
    $arrayOfUsers = array();
    foreach ($users as $name => $myarray) {
        $app['monolog']->addDebug($name);
        $arrayOfUsers[] = $myarray;
    }
    $app['monolog']->addInfo(sizeof($arrayOfUsers));
    $output = array_values($arrayOfUsers);
    return json_encode($output);
});
//Find one user from the user array
$app->get('/users/{name}', function (Silex\Application $app, $name) use($app, $users) {
    if ($name) {
        if (!isset($users[$name])) {
            $app->abort(404, "Post {$id} does not exist.");
        } else {
            $output = json_encode($users[$name]);
        }
    }
    return $output;
});
//Hello world.
$app->get('/hellojson', function () use($app) {
    $output = '{"message": "Hello World From Silex"}';
    return $output;
});
//Exception handelling
use Symfony\Component\HttpFoundation\Response;
$app->error(function (\Exception $e, $code) {
    return new Response($e);
Ejemplo n.º 21
0
})->bind('b_admin_static_pages');
//ДОБАВЛЕНИЕ УДАЛЕНИЕ РЕДАКТИРОВАНИЕ GGGGGEEEEEEEETTTT
$silex_app->get('/admin/{method}/{type}/{id}', function ($type, $method, $id) use($silex_app, $products, $categories, $static_pages) {
    if (null === ($user = $silex_app['session']->get('user'))) {
        return $silex_app->redirect($silex_app['url_generator']->generate('b_admin'));
    }
    $signs = Signs::getSignsForThis($method, $type);
    if ($method == 'add' || $method == 'edit') {
        if ($id == 'new') {
            //ненадежно каэш, но пока так
            if ($type == 'product') {
                $id = array_pop($products)['id'] + 1;
            } elseif ($type == 'category') {
                $id = array_pop($categories)['id'] + 1;
            } else {
                $silex_app->abort(404, "Вы пытаетесь создать/изменить что-то, что не следует создавать/изменять");
            }
            $record = ['id' => $id];
        } elseif (is_numeric($id)) {
            if ($type == 'product') {
                $record = $products[$id];
            } elseif ($type == 'category') {
                $record = $categories[$id];
            } elseif ($type == 'page') {
                $record = $static_pages[$id];
            }
        } else {
            $silex_app->abort(404, "Что-то не так с ID");
        }
        //на всякий случай
        $required_keys = ['id', 'title', 'slug', 'description', 'price', 'category_id', 'content', 'created_at', 'updated_at'];
Ejemplo n.º 22
0
<?php

$autoLoader = (require_once __DIR__ . '/../vendor/autoload.php');
Symfony\Component\HttpKernel\Debug\ErrorHandler::register();
$app = new Silex\Application();
$app['__ENV__'] = $_SERVER['__ENV__'] ?: 'prod';
require __DIR__ . '/config/' . $app['__ENV__'] . '.php';
if ($app['app.prerequisite.enforce']) {
    $reqMsg = 'Unmet Dependencies for ' . $app['app.title'] . ' v' . $app['app.version'] . '[codeName ' . $app['app.namespace'] . ']: ';
    version_compare(PHP_VERSION, $app['app.prerequisite.phpVersion'], '>=') || $app->abort(400, $reqMsg . 'PHP v' . $app['app.prerequisite.phpVersion'] . '+ [RUNTIME: ' . PHP_VERSION . ']');
}
$autoLoader->add($app['app.namespace'], __DIR__ . '/model');
$app->register(new Silex\Provider\HttpCacheServiceProvider());
$app->register(new Silex\Provider\SessionServiceProvider(), array('session.storage.options.name' => $app['session.storage.options.name'], 'session.storage.options.id' => $app['session.storage.options.id'], 'session.storage.options.http_only' => $app['session.storage.options.http_only']));
$app->register(new Silex\Provider\MonologServiceProvider(), array('monolog.logfile' => $app['monolog.logfile'], 'monolog.name' => $app['monolog.name'], 'monolog.level' => $app['monolog.level']));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.options' => array('cache' => $app['twig.options.cache'] ?: false, 'strict_variables' => true, 'debug' => $app['twig.options.debug']), 'twig.path' => $app['twig.path']));
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => $app['db.options']));
$app->register(new Silex\Provider\TranslationServiceProvider(), array('locale_fallback' => 'en'));
$app->register(new Silex\Provider\ValidatorServiceProvider());
$app->register(new Silex\Provider\FormServiceProvider());
$app['monolog']->addDebug('Bootstrap Completed');
Ejemplo n.º 23
0
<?php

require __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app['menu'] = $app->share(function ($app) {
    $data = (require __DIR__ . '/../src/menus.php');
    return new Ratchet\Menu($app['request'], $data);
});
$app->get('/{page}', function ($page) use($app) {
    $page = rtrim($page, '/');
    if (!file_exists(__DIR__ . '/../views/' . $page . '.html.twig')) {
        $app->abort(404);
    }
    return $app['twig']->render($page . '.html.twig');
})->assert('page', '[a-zA-Z0-9\\/_-]+')->value('page', 'index');
$app->error(function ($e, $code) use($app) {
    if (404 === $code) {
        return $app['twig']->render('404.html.twig');
    }
});
$app->run();
Ejemplo n.º 24
0
    $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
 */
$app->get('/move/{row}/{col}', function ($row, $col) use($app) {
    $gameEngineCallback = $app['game_engine'];
    $gameEngine = $gameEngineCallback();
    if (!\Symstriker\TicTacToe\Engine\GameEngine::isStarted()) {
        $app->abort(403, 'Game is forbidden, that\'s because game engine is not started!');
    }
    $opponentMove = $gameEngine->makeMove((int) $row, (int) $col);
    $winner = $gameEngine->whoWon();
    $winner = $winner ? $winner->getGameSign() : false;
    return new \Symfony\Component\HttpFoundation\JsonResponse(['row' => $opponentMove[0], 'col' => $opponentMove[1], 'winner' => $winner]);
})->bind('make_move');
$app->run();
Ejemplo n.º 25
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../templates'));
$app->register(new Silex\Provider\URLGeneratorServiceProvider());
$app['articles'] = array(array('title' => 'Lorem ipsum dolor sit amet', 'contents' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis vestibulum ultricies. Sed sit amet sagittis nisl. Nulla leo metus, efficitur non risus ut, tempus convallis sem. Mauris pharetra sagittis ligula pharetra accumsan. Cras auctor porta enim, a eleifend enim volutpat vel. Nam volutpat maximus luctus. Phasellus interdum elementum nulla, nec mollis justo imperdiet ac. Duis arcu dolor, ultrices eu libero a, luctus sollicitudin diam. Phasellus finibus dictum turpis, nec tincidunt lacus ullamcorper et. Praesent laoreet odio lacus, nec lobortis est ultrices in. Etiam facilisis elementum lorem ut blandit. Nunc faucibus rutrum nulla quis convallis. Fusce molestie odio eu mauris molestie, a tempus lorem volutpat. Sed eu lacus eu velit tincidunt sodales nec et felis. Nullam velit ex, pharetra non lorem in, fringilla tristique dolor. Mauris vel erat nibh.', 'author' => 'Sammy', 'date' => '2014-12-18'), array('title' => 'Duis ornare', 'contents' => 'Duis ornare, odio sit amet euismod vulputate, purus dui fringilla neque, quis eleifend purus felis ut odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque bibendum pretium ante, eu aliquet dolor feugiat et. Pellentesque laoreet est lectus, vitae vulputate libero sollicitudin consequat. Vivamus finibus interdum egestas. Nam sagittis vulputate lacus, non condimentum sapien lobortis a. Sed ligula ante, ultrices ut ullamcorper nec, facilisis ac mi. Nam in vehicula justo. In hac habitasse platea dictumst. Duis accumsan pellentesque turpis, nec eleifend ex suscipit commodo.', 'author' => 'Sammy', 'date' => '2014-11-08'));
$app->get('/', function (Silex\Application $app) {
    return $app['twig']->render('index.html.twig', array('articles' => $app['articles']));
})->bind('index');
$app->get('/{id}', function (Silex\Application $app, $id) {
    if (!array_key_exists($id, $app['articles'])) {
        $app->abort(404, 'The article could not be found');
    }
    $article = $app['articles'][$id];
    return $app['twig']->render('single.html.twig', array('article' => $article));
})->assert('id', '\\d+')->bind('single');
$app->run();
Ejemplo n.º 26
0
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
$app->get('/resources/{type}/{key}', function ($type, $key) use($app) {
    switch ($type) {
        case 'artist':
        case 'album':
        case 'genre':
            $folder = 'img';
            $extension = 'jpg';
            break;
        case 'track':
            $folder = 'msc';
            $extension = 'mp3';
            break;
        default:
            return $app->abort(404, "La source demandée n'existe pas");
    }
    $file = project_path . "/{$folder}/{$type}/{$key}.{$extension}";
    if (!file_exists($file)) {
        $app->abort(404, "La ressource demandée n'existe pas");
    }
    if ($type != 'track') {
        return $app->sendFile($file, 200, ['Content-Type' => 'image/jpeg']);
    } else {
        return $app->sendFile($file, 200, ['Content-Type' => 'audio/mp3']);
    }
});
$app->get('/services/{type}/{key}', function ($type, $key) use($app) {
    $manager = ManagerFactory::getManager($type);
    if (is_null($manager)) {
        return null;
Ejemplo n.º 27
0
        $filtro = '%' . $filtro . '%';
        $query = $db->executeQuery('SELECT * FROM eventos WHERE nome like ? OR cidade like ? OR estado like ?', array($filtro, $filtro, $filtro));
    } else {
        $query = $db->executeQuery('SELECT * FROM eventos');
    }
    $eventos = $query->fetchAll();
    return $app->json(array('data' => $eventos));
});
$app->get('/eventos/{id}', function ($id) use($app) {
    $db = Database::open();
    $query = $db->executeQuery('SELECT * FROM eventos WHERE id = ?', array($id));
    $evento = $query->fetch();
    if ($evento) {
        return $app->json(array('data' => $evento));
    } else {
        return $app->abort(404);
    }
});
$app->post('/eventos/{id}', function ($id, Request $request) use($app) {
    $evento = json_decode($request->getContent());
    $db = Database::open();
    if ($evento->id == 0) {
        $r = $db->executeUpdate('INSERT INTO eventos(nome, estado, cidade) VALUES(?, ?, ?)', array($evento->nome, $evento->estado, $evento->cidade));
        $evento->id = $db->lastInsertId();
    } else {
        $r = $db->executeUpdate('UPDATE eventos SET nome = ?, estado = ?, cidade = ? WHERE id = ?', array($evento->nome, $evento->estado, $evento->cidade, $evento->id));
    }
    return $app->json(array('data' => $evento));
});
$app->delete('/eventos/{id}', function ($id) use($app) {
    $db = Database::open();
Ejemplo n.º 28
0
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => __DIR__ . '/../app/cache/', 'http_cache.options' => ['default_ttl' => $app['cache_ttl']]));
$app->get('/', function () use($app) {
    return $app['twig']->render('index.html.twig');
})->bind('home');
$app->get('/swagger.json', function () use($app) {
    return new Symfony\Component\HttpFoundation\Response($app['twig']->render('swagger.json.twig'), 200, ['Content-Type' => 'application/json']);
})->bind('swagger');
$app->get('/apis.json', function () use($app) {
    return new Symfony\Component\HttpFoundation\Response($app['twig']->render('apis.json.twig'), 200, ['Content-Type' => 'application/json']);
})->bind('apisjson');
$app->get('/subnet/{ip}/{mask}', function ($ip, $mask) use($app) {
    $subnet = $ip . '/' . $mask;
    try {
        $subnet_info = IPTools\Network::parse($subnet)->info;
        unset($subnet_info['class']);
    } catch (Exception $e) {
        $app->abort(400, $e->getMessage());
    }
    return $app->json($subnet_info, 200, ['Cache-Control' => 's-maxage=' . $app['cache_ttl'] . ', public', 'ETag' => md5($subnet), 'Access-Control-Allow-Origin', '*']);
})->assert('ip', '[\\w\\.\\:]+')->assert('mask', '[0-9]+')->bind('api');
$app->after(function (Symfony\Component\HttpFoundation\Request $request, Symfony\Component\HttpFoundation\Response $response) {
    $response->headers->set('Access-Control-Allow-Origin', '*');
});
$app->error(function (\Exception $e, $code) use($app) {
    return $app->json(['error' => $e->getMessage()]);
});
if ($app['debug']) {
    $app->run();
} else {
    $app['http_cache']->run();
}
Ejemplo n.º 29
0
$app['repositories'] = array('packagist' => 'https://packagist.org');
$app['cache_dir'] = __DIR__ . '/web/proxy';
$app['browser'] = $app->share(function () {
    $client = new Buzz\Client\Curl();
    $client->setTimeout(20);
    return new Buzz\Browser($client);
});
$app->register(new Silex\Provider\HttpCacheServiceProvider(), array('http_cache.cache_dir' => __DIR__ . '/cache/'));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/views'));
$app->get('/', function () use($app) {
    $body = $app['twig']->render('index.html.twig', array('app' => $app));
    return new Response($body, 200, array('Cache-Control' => 's-maxage=3600,public'));
});
$app->get('/proxy/{rep}/packages.json', function ($rep) use($app) {
    if (!isset($app['repositories'][$rep])) {
        $app->abort(404, "Not Found");
    }
    $url = $app['repositories'][$rep] . "/packages.json";
    $response = $app['browser']->get($url);
    if (!$response->isOk()) {
        $app->abort($response->getStatusCode(), "");
    }
    $responseJson = json_decode($response->getContent(), true);
    // convert
    unset($responseJson['notify']);
    unset($responseJson['notify-batch']);
    unset($responseJson['search']);
    $responseJson['providers-url'] = "/proxy/" . $rep . "/p/%package%\$%hash%.json";
    $dir = $app['cache_dir'] . "/" . $rep;
    if (!is_dir($dir)) {
        @mkdir($dir, 0777, true);