Esempio n. 1
0
    $app->get('/', function() use($app){
        return $app['twig']->render('index.twig');
    });

    $app->get('/proizvod/new', function() use($app){
        return $app['twig']->render('proizvod-edit.twig');
    });

    $app->get('/api/proizvodi', function() use($app){
        $result = ORM::for_table('proizvodi')
            ->select('*')
            ->select('proizvodi.naziv')
            ->select('tip.naziv','nazivTip')
            ->join('tip', 'tip.id = proizvodi.tipId')
            ->find_array();
        return $app->json($result);

        
    });

    $app->get('/api/alergeni', function() use($app){
        $result = ORM::for_table('alergen')
            ->select('*')
            ->find_array();
        return $app->json($result);        
    });

    $app->get('/api/tipovi', function() use($app){
        $result = ORM::for_table('tip')
            ->select('*')
            ->find_array();
Esempio n. 2
0
});
$app->post('/customurl', function (Request $request) use($app) {
    $csrfCheck = $request->get('csrfToken') === $app['session']->get('csrf_token');
    if ($csrfCheck) {
        $url = $request->get('urlInput');
        if (!filter_var($url, FILTER_VALIDATE_URL) === false) {
            $stmt = $app['db']->prepare('SELECT addNewCustomURL(:url)');
            $stmt->bindValue("url", $url);
            $stmt->execute();
            $code = $stmt->fetchColumn(0);
            return $app['twig']->render('displayCode.twig', array('accessCode' => $code));
        } else {
            return $app['twig']->render('displayError.twig', array("message" => "Provided url is invalid", "backUrl" => "/customurl"));
        }
    } else {
        return $app->json(array("error" => "Bad request", "message" => "Invalid CSRF token"), 400);
    }
});
$app->get('/customurl/{code}', function (Request $request, $code) use($app) {
    if ($request->query->get("token") === getenv('STREAMCENTER_SECRET')) {
        $stmt = $app['db']->prepare('SELECT * FROM custom_urls WHERE code=:code');
        $stmt->bindValue("code", $code);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row != false) {
            return $app->json(array('id' => $row['id'], 'url' => $row['url'], 'generated_date' => $row['generated_date']), 200);
        } else {
            return $app->json(array("error" => "Not found", "message" => "The provided code did not match any stored url."), 404);
        }
    } else {
        return $app->json(array("error" => "Unauthorized", "message" => "Trying to access protected data from unofficial StreamCenter app."), 401);
$app['users'] = function () use($app) {
    $users = ['admin' => array('roles' => array('ROLE_ADMIN'), 'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==', 'enabled' => true)];
    return new InMemoryUserProvider($users);
};
$app['security.firewalls'] = array('login' => ['pattern' => 'login|register|oauth', 'anonymous' => true], 'secured' => array('pattern' => '^.*$', 'logout' => array('logout_path' => '/logout'), 'users' => $app['users'], 'jwt' => array('use_forward' => true, 'require_previous_session' => false, 'stateless' => true)));
$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\SecurityJWTServiceProvider());
$app->post('/api/login', function (Request $request) use($app) {
    $vars = json_decode($request->getContent(), true);
    try {
        if (empty($vars['_username']) || empty($vars['_password'])) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        }
        /**
         * @var $user User
         */
        $user = $app['users']->loadUserByUsername($vars['_username']);
        if (!$app['security.encoder.digest']->isPasswordValid($user->getPassword(), $vars['_password'], '')) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        } else {
            $response = ['success' => true, 'token' => $app['security.jwt.encoder']->encode(['name' => $user->getUsername()])];
        }
    } catch (UsernameNotFoundException $e) {
        $response = ['success' => false, 'error' => 'Invalid credentials'];
    }
    return $app->json($response, $response['success'] == true ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST);
});
$app->get('/api/protected_resource', function () use($app) {
    return $app->json(['hello' => 'world']);
});
$app->run();
);

$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\SecurityJWTServiceProvider());
*/
$app->get('/eventos/', function (Request $request) use($app) {
    $filtro = $request->get('q', null);
    $db = $app['db'];
    if ($filtro) {
        $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) {
Esempio n. 5
0
    $resources = $app['bookmark.repository']->findAll();
    return json_encode($resources);
});
$app->post('/', function (Request $request) use($app) {
    $bookmark = new App\Bookmark(Uuid::uuid4(), new App\Url($request->request->get('url')));
    $app['bookmark.repository']->save($bookmark);
    $message = json_encode((object) array('event' => 'bookmark_has_been_created', 'uuid' => (string) $bookmark->getUuid(), 'url' => (string) $bookmark->getUrl()));
    // publish to RabbitMQ
    $connection = new AMQPStreamConnection('rabbitmq', 5672, 'guest', 'guest');
    $channel = $connection->channel();
    $channel->queue_declare('bookmark', false, false, false, false);
    $msg = new AMQPMessage($message);
    $channel->basic_publish($msg, '', 'bookmark');
    $channel->close();
    $connection->close();
    return $app->json($bookmark, 201);
});
// @todo restrict to internal calls only
$app->post('/{uuid}', function (Request $request, $uuid) use($app) {
    $bookmark = $app['bookmark.repository']->find(Uuid::fromString($uuid));
    $imageUrl = $request->request->get('imageUrl');
    $videoUrl = $request->request->get('videoUrl');
    $bookmark->complete($request->request->get('type'), $request->request->get('title'), $request->request->get('description'), null === $imageUrl ? null : new App\Url($imageUrl), null === $videoUrl ? null : new App\Url($videoUrl));
    $app['bookmark.repository']->update($bookmark);
    return $app->json($bookmark, 200);
});
$app->post('/{uuid}/delete', function (Request $request, $uuid) use($app) {
    $bookmark = $app['bookmark.repository']->remove(Uuid::fromString($uuid));
    return $app->json($bookmark, 200);
});
$app->run();
Esempio n. 6
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();
}
Esempio n. 7
0
// web/index.php
require_once __DIR__ . '/../vendor/autoload.php';
use PredictionIO\PredictionIOClient;
use Symfony\Component\HttpFoundation\Request;
$client = PredictionIOClient::factory(['apiurl' => 'http://192.168.33.20:8000', 'appkey' => 'fXcxZlrBYZUxzd6wgeZhIQruai8OfUuUDaQGQyZVeigdfn4gQv48A3Q4Dml5Jfpq']);
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get('/', function () use($app) {
    return $app['twig']->render('index.html.twig', []);
});
$app->post('/user', function (Request $request) use($app, $client) {
    $command = $client->getCommand('create_user', ['pio_uid' => $request->get('user')]);
    $response = $client->execute($command);
    return $app->json(['message' => sprintf('Created user "%s".', $request->get('user'))]);
});
$app->post('/show', function (Request $request) use($app, $client) {
    $command = $client->getCommand('create_item', ['pio_iid' => $request->get('show'), 'pio_itypes' => 1]);
    $response = $client->execute($command);
    $client->identify($request->get('user'));
    $command = $client->getCommand('record_action_on_item', ['pio_action' => 'like', 'pio_iid' => $request->get('show')]);
    $client->execute($command);
    return $app->json(['message' => sprintf('You liked %s', $request->get('show'))]);
});
$app->post('/recommend', function (Request $request) use($app, $client) {
    try {
        $client->identify($request->get('user'));
        $command = $client->getCommand('itemrec_get_top_n', ['pio_engine' => 'itemrec', 'pio_n' => 5]);
        $rec = $client->execute($command);
        return $app->json($rec['pio_iids']);
<?php

require_once __DIR__ . '/../../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
define('TMP_DIR', sys_get_temp_dir() . '/testarstatic');
$app->get('/{application}/{slug}', function ($application, $slug) use($app) {
    $file = TMP_DIR . '/' . $application . '/' . $slug;
    if (!file_exists($file)) {
        return $app->json(null, 404);
    }
    return new Symfony\Component\HttpFoundation\BinaryFileResponse($file);
});
$app->delete('/{application}/{slug}', function ($application, $slug) use($app) {
    $file = TMP_DIR . '/' . $application . '/' . $slug;
    if (!file_exists($file)) {
        return $app->json('', 404);
    }
    unlink($file);
    return $app->json('', 204);
});
$app->post('/{application}', function ($application) use($app) {
    $request = $app['request'];
    @mkdir(TMP_DIR);
    @mkdir(TMP_DIR . '/' . $application);
    $request->files->get('file')->move(TMP_DIR . '/' . $application, $request->request->get('slug'));
    return '';
});
$app->run();
Esempio n. 9
0
 * @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
 * @returns string
 */
$app->post('/items', function (Silex\Application $app) {
    if ($app['session']->get('user_id') === null) {
        $app->abort(403, "Request is not allowed.");
        exit;
    }
    $content = json_decode($app['request']->getContent(), true);
    $data = array();
    $data['idp'] = !empty($content['idp']) ? $content['idp'] : '';
    $data['login'] = !empty($content['login']) ? $content['login'] : '';
Esempio n. 10
0
<?php

//toDo: Remove hard coded timezone.
use Symfony\Component\HttpFoundation\Request;
ini_set('date.timezone', 'Europe/Berlin');
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__));
$productList = [['id' => 4711, 'description' => 'Segelschiff', 'price' => 19.95], ['id' => 4712, 'description' => 'MacBook Air', 'price' => 999.99], ['id' => 4713, 'description' => 'iPod Touch', 'price' => 109.95], ['id' => 4714, 'description' => 'Chromecast', 'price' => 0.99], ['id' => 4715, 'description' => 'Apple TV 2nd generation', 'price' => 179.99], ['id' => 4716, 'description' => 'A glass of wine', 'price' => 7.95], ['id' => 4717, 'description' => 'Toyota Rav4 Hybrid', 'price' => 30000], ['id' => 4718, 'description' => 'PHP Elephant', 'price' => 10.99]];
$app->view(function (array $controllerResult) use($app) {
    return $app->json($controllerResult);
});
$app->get('/products', function (Request $request) use($productList) {
    $term = $request->get('term');
    return array_values(array_filter($productList, function ($product) use($term) {
        if (strpos(strtolower($product['description']), strtolower($term)) !== false) {
            return $product;
        }
    }));
});
$app->get('/', function () use($app) {
    return $app['twig']->render('uiGridCrud.html');
});
$app->run();
Esempio n. 11
0
        // 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 );
    $image_url = $query->get('image_url');
    if (!$api_key) {
        $error = array('message' => 'The required env var API_KEY is missing.');
        return $app->json($error, 400);
    }
    if (!$image_url) {
        $error = array('message' => 'The required {image_url} parameter is missing.');
        return $app->json($error, 400, array('Content-Type' => CS_JSON));
    }
    $client = new Cloudsight_Http_Client($api_key, getenv('CS_MOCK'));
    $post_data = array('remote_image_url' => $image_url, 'locale' => $query->get('locale', 'en-US'), 'language' => $query->get('language', 'en'));
    $resp = $client->postImageRequests($post_data);
    if ($app['debug']) {
        $client->debugHeaders();
    }
    return $app->json($resp, $client->getStatus(), array('Content-Type' => CS_JSON));
});
/** Poll the image response endpoint.
 *
        if (empty($vars['_username']) || empty($vars['_password'])) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        }
        /**
         * @var $user User
         */
        $user = $app['users']->loadUserByUsername($vars['_username']);
        if (!$app['security.encoder.digest']->isPasswordValid($user->getPassword(), $vars['_password'], '')) {
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $vars['_username']));
        } else {
            $response = ['success' => true, 'token' => $app['security.jwt.encoder']->encode(['name' => $user->getUsername()])];
        }
    } catch (UsernameNotFoundException $e) {
        $response = ['success' => false, 'error' => 'Invalid credentials'];
    }
    return $app->json($response, $response['success'] == true ? Response::HTTP_OK : Response::HTTP_BAD_REQUEST);
});
$app->get('/api/protected_resource', function () use($app) {
    $jwt = 'no';
    $token = $app['security.token_storage']->getToken();
    if ($token instanceof Silex\Component\Security\Http\Token\JWTToken) {
        $jwt = 'yes';
    }
    $granted = 'no';
    if ($app['security.authorization_checker']->isGranted('ROLE_ADMIN')) {
        $granted = 'yes';
    }
    $granted_user = '******';
    if ($app['security.authorization_checker']->isGranted('ROLE_USER')) {
        $granted_user = '******';
    }
Esempio n. 13
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
try {
    $pdo = new PDO("mysql:host=localhost;dbname=benchmark", "root");
} catch (Exception $e) {
    echo $e->getMessage();
    exit;
}
$app->get('/', function () use($app, $pdo) {
    $sth = $pdo->prepare("INSERT INTO product (name) values (:name)");
    $sth->bindParam(':name', uniqid("product"), PDO::PARAM_STR);
    $sth->execute();
    return $app->json([id => $pdo->lastInsertId()]);
});
$app->error(function ($err) {
    return new Response($err->getMessage());
});
$app['debug'] = true;
$app->run();
        $token = json_decode($client->getAccessToken());
        // You can read the Google user ID in the ID token.
        // "sub" represents the ID token subscriber which in our case
        // is the user ID. This sample does not use the user ID.
        $attributes = $client->verifyIdToken($token->id_token, CLIENT_ID)->getAttributes();
        $gplus_id = $attributes["payload"]["sub"];
        // Store the token in the session for later use.
        $app['session']->set('token', json_encode($token));
        $response = 'Successfully connected with token: ' . print_r($token, true);
    }
    return new Response($response, 200);
});
// Get list of people user has shared with this app.
$app->get('/people', function () use($app, $client, $plus) {
    $token = $app['session']->get('token');
    if (empty($token)) {
        return new Response('Unauthorized request', 401);
    }
    $client->setAccessToken($token);
    $people = $plus->people->listPeople('me', 'visible', array());
    return $app->json($people);
});
// Revoke current user's token and reset their session.
$app->post('/disconnect', function () use($app, $client) {
    $token = json_decode($app['session']->get('token'))->access_token;
    $client->revokeToken($token);
    // Remove the credentials from the user's session.
    $app['session']->set('token', '');
    return new Response('Successfully disconnected', 200);
});
$app->run();
Esempio n. 15
0
<?php

/**
 * Created by PhpStorm.
 * User: anderson.mota
 * Date: 02/09/2015
 * Time: 18:12
 *
 * @author Anderson Mota <*****@*****.**>
 */
// web/index.php
require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$app->register(new Silex\Provider\TwigServiceProvider(), ['twig.path' => __DIR__ . '/../views']);
$app->get('/', function () use($app) {
    return $app['twig']->render('home.twig');
});
$app->post('/upload', function () use($app) {
    $upload = new App\Upload(__DIR__ . '/data/upload');
    $upload->imageValidation();
    $file_info = $upload->info();
    try {
        $upload->run();
    } catch (\Exception $e) {
        $errors = $upload->file->getErrors();
        return $app->json(['status' => 'tra_error', 'errors' => $errors, 'exception' => $e], 301);
    }
    return $app->json(['status' => 'tra_success', 'file' => $file_info]);
});
$app->run();
Esempio n. 16
0
        $request->request->replace(is_array($data) ? $data : array());
    }
});
// Define a custom encoder for Security/Authentication
$app['security.encoder.digest'] = $app->share(function ($app) {
    // uses the password-compat encryption
    return new BCryptPasswordEncoder(10);
});
// Default error handler
$app->error(function (\Exception $e, $code) use($app) {
    $app['monolog']->addError($e->getMessage());
    $message = 'The server encountered an error.';
    if ($app['debug'] === true) {
        $message = $e->getMessage();
    }
    return $app->json($message, 403);
});
// General Service Provder for Controllers
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app['controller.user'] = $app->share(function () use($app) {
    return new Pfmgr\Controller\User();
});
$app->get('/user/{id}', "controller.user:fetchAction");
$app->post('/user/create', "controller.user:createAction");
$app['controller.account'] = $app->share(function () use($app) {
    return new Pfmgr\Controller\Account();
});
$app->post('/account/create', "controller.account:createAction");
$app['controller.currency'] = $app->share(function () use($app) {
    return new Pfmgr\Controller\Currency();
});
Esempio n. 17
0
|
*/
if ($config['auth']) {
    require_once __DIR__ . '/../bootstrap/auth.php';
}
/*
|--------------------------------------------------------------------------
| Provide all of our various routes
|--------------------------------------------------------------------------
|
| These are the various post authentication paths that will return results.
| We prefer to use mount points instead of routes right in this file.
|
*/
$app->get('/discovery', function () use($app) {
    return $app->json(array("server_id" => require_once __DIR__ . '/../config/server_id.php', "hostname" => trim(`hostname`)));
});
if (!in_array('/tools', $config['disabled'])) {
    $app->mount('/tools', new Snapr\Routers\ToolsController());
}
if (!in_array('/haproxy/stats', $config['disabled'])) {
    $app->mount('/haproxy/stats', new Snapr\Routers\HAProxyStatsController());
}
if (!in_array('/haproxy/program', $config['disabled'])) {
    $app->mount('/haproxy/program', new Snapr\Routers\HAProxyProgramController());
}
/*
|--------------------------------------------------------------------------
| Run the app
|--------------------------------------------------------------------------
|
Esempio n. 18
0
File: index.php Progetto: amireh/rgx
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with rgx. If not, see <http://www.gnu.org/licenses/>.
# -----------------------------------------------------------------------------
require_once __DIR__ . '/../vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
// Show all errors
// error_reporting(E_ALL);
$app = new Silex\Application();
$flags = ["i" => "Caseless: letters in the pattern match both upper and lower case letters", "m" => "Multiline", "s" => "Dot-all: a dot metacharacter in the pattern matches all characters, including newlines.", "x" => "Extended: if this modifier is set, whitespace data characters in the " . "pattern are totally ignored except when escaped or inside a character " . "class, and characters between an unescaped # outside a character class " . "and the next newline character, inclusive, are also ignored.", "U" => "Ungreedy: This modifier inverts the \"greediness\" of the quantifiers " . "so that they are not greedy by default, but become greedy if followed by ?", "X" => "Extra: Any backslash in a pattern that is followed by a letter that " . "has no special meaning causes an error, thus reserving these " . "combinations for future expansion.", "u" => "UTF-8: pattern strings are treated as UTF-8.", "J" => "DUPNAMES: Allow duplicate names for subpatterns"];
$app->get('/flags', function () use($app, $flags) {
    return $app->json($flags);
});
$app->post('/', function (Request $request) use($app) {
    $rc = null;
    $err = null;
    $data = json_decode($request->getContent());
    $ptrn = $data->pattern;
    $subj = $data->subject;
    $flags = $data->flags;
    if (!$ptrn || !$subj) {
        return new Response('Missing pattern or subject.', 400);
    }
    if ($flags) {
        $ptrn = '(?' . $flags . ':' . $ptrn . ')';
    }
    $ptrn = '/' . $ptrn . '/';
Esempio n. 19
0
    $admin_status = $_SESSION['is_admin'];
    return $app['twig']->render('add_person.twig', array('user' => $current_user, 'is_admin' => $admin_status));
});
$app->post("/deletePerson", function () use($app) {
    $current_user = Attendees::find($_POST['id']);
    $current_user->delete();
    return $app->redirect('/attendees');
});
//Updates the here status of a person
$app->post("/here", function () use($app) {
    $current_user = Attendees::find($_POST['id']);
    $current_user->updatePerson($_POST['here']);
});
$app->get("/here", function () use($app) {
    $attendees = Attendees::getAllNonObject();
    return $app->json($attendees);
});
$app->get("/raffle", function () use($app) {
    $attendees_list = Attendees::getAllHere();
    return $app['twig']->render('raffle.twig', array('all_here' => $attendees_list));
});
$app->get("/raffleWinner", function () use($app) {
    $attendees_list = Attendees::getAllHere();
    $choices = [];
    $picks = array_rand($attendees_list, 2);
    array_push($choices, $attendees_list[$picks[0]]);
    $attendeePicked = $choices[0];
    $current_user = Attendees::find($attendeePicked['id']);
    $current_user->updatePersonWin();
    return $app->json($attendeePicked);
});
Esempio n. 20
0
$app = new Silex\Application();
$app['debug'] = true;
$app['db'] = function () {
    return new \PDO('mysql:host=localhost;dbname=angular-curso', 'root', '');
};
$app->get('/', function () use($app) {
    return new Response(file_get_contents('pessoas/templates/template.html'), 200);
});
$app->post('/pessoas', function (Request $request) use($app) {
    $data = $request->getContent();
    parse_str($data, $out);
    $stmt = $app['db']->prepare("insert into pessoas(nome,email) value(:nome, :email)");
    $stmt->bindParam('nome', $out['nome']);
    $stmt->bindParam('email', $out['email']);
    $stmt->execute();
    return $app->json(array('success' => true));
});
$app->get('/pessoas', function () use($app) {
    $stmt = $app['db']->query("Select * from pessoas");
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $app->json($result);
});
$app->get('/pessoas/{id}', function ($id) use($app) {
    $stmt = $app['db']->prepare("Select * from pessoas where id=:id");
    $stmt->bindParam('id', $id);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $app->json($result);
});
$app->put('/pessoas/{id}', function (Request $request, $id) use($app) {
    $data = $request->getContent();
Esempio n. 21
0
require_once __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$app = new Silex\Application();
$app['debug'] = true;
require 'config.php';
$app->after(function (Request $request, Response $response) {
    $response->headers->set('Access-Control-Allow-Origin', '*');
});
$app->get('/films', function () use($app) {
    $films = $app['db']->fetchAll("SELECT films.tmdbid, title, titlefr, titleen, titlefrslug, YEAR(release_date) AS date, production, popularity, release_date, genres\n    FROM films\n    LEFT JOIN filmsf\n    ON filmsf.tmdbid = films.tmdbid\n    LEFT JOIN fichiers\n    ON fichiers.id = filmsf.fichier\n    LEFT JOIN serveurs\n    ON serveurs.nom = fichiers.serveur\n    LEFT JOIN ierreurs\n    ON ierreurs.fichier = filmsf.fichier\n    WHERE fichiers.supprime = 0 AND serveurs.online=1 AND serveurs.supprime=0\n    GROUP BY films.tmdbid\n    HAVING COUNT(*)/COUNT(DISTINCT filmsf.fichier) < 5\n    ORDER BY popularity DESC");
    foreach ($films as &$f) {
        $f['popularity'] = (int) $f['popularity'];
    }
    return $app->json($films);
});
$app->get('/films/full', function () use($app) {
    $films = $app['db']->fetchAll("SELECT films.tmdbid, title, titlefr, titleen, titlefrslug, YEAR(release_date) AS date, production, popularity, release_date, overview, runtime, genres, vote\n    FROM films\n    LEFT JOIN filmsf\n    ON filmsf.tmdbid = films.tmdbid\n    LEFT JOIN fichiers\n    ON fichiers.id = filmsf.fichier\n    LEFT JOIN serveurs\n    ON serveurs.nom = fichiers.serveur\n    LEFT JOIN ierreurs\n    ON ierreurs.fichier = filmsf.fichier\n    WHERE fichiers.supprime = 0 AND serveurs.online=1 AND serveurs.supprime=0\n    GROUP BY films.tmdbid\n    HAVING COUNT(*)/COUNT(DISTINCT filmsf.fichier) < 5\n    ORDER BY popularity DESC");
    foreach ($films as &$f) {
        $f['popularity'] = (int) $f['popularity'];
    }
    return $app->json($films);
});
$app->get('/series', function () use($app) {
    $series = $app['db']->fetchAll("SELECT id, nom, tmdbid, tfirstdate, tlastdate, tnbseasons, (SELECT COUNT(*) FROM series_saisons AS sa WHERE sa.serie = series.tmdbid) AS nbseasons, tpopularity AS popularity, nom AS title, tfirstdate AS release_date\n    FROM series\n    ORDER BY tpopularity DESC");
    foreach ($series as &$f) {
        $f['popularity'] = (int) $f['popularity'];
    }
    return $app->json($series);
});
Esempio n. 22
0
File: api.php Progetto: bazylu/web
}
$DataProvider = new DataProvider($app['db']);
/*===============================
=            CLIENTS            =
===============================*/
$app->get('/clients', function () use($app, $DataProvider) {
    $clients = $DataProvider->getClients();
    $response = new JsonResponse();
    $response->setEncodingOptions(JSON_NUMERIC_CHECK);
    $response->setData($clients);
    return $response;
});
$app->get('/client/{clientId}', function ($clientId) use($app, $DataProvider) {
    $clientDetails = $DataProvider->getClient($clientId);
    if (!$clientDetails) {
        return $app->json(['errorMessage' => 'Client Not Found'], 404);
    }
    return $app->json($clientDetails);
});
$app->put('/client/{clientId}', function (Request $request, $clientId) use($app, $DataProvider) {
    $clientDetails = $DataProvider->getClient($clientId);
    if (!$clientDetails) {
        return $app->json(['errorMessage' => 'Client Not Found'], 404);
    }
    $updateData = $DataProvider->getRequestData();
    $result = $DataProvider->updateClient($clientId, $updateData);
    return $app->json(['message' => 'Client updated!']);
});
$app->post('/client', function (Request $request) use($app, $DataProvider) {
    $insertData = $DataProvider->getRequestData();
    $newClientId = $DataProvider->saveNewClient($insertData);
Esempio n. 23
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
$app = new Silex\Application();
$app['debug'] = true;
$arr = [0 => ['date' => date('Y-m-d'), 'author' => 'Abdonor', 'title' => 'Using Silex', 'body' => "This is the sample of using Silex! <br> Try also: <b> <a href='/user'> /user  </a> </b>"]];
$app->get('/', function () use($arr) {
    $output = '';
    foreach ($arr as $post) {
        $output .= '<H1>' . $post['title'] . '</H1>';
        $output .= '<br />';
        $output .= $post['body'];
    }
    return $output;
});
$app->get('/user', function () use($arr, $app) {
    $output = ['people' => [['name' => 'Albert Abdonor', 'age' => '31', 'profession' => 'Software Engineer', 'adjective' => 'Handsome', 'login' => 'albert.abdonor', 'password' => 'holland2016'], ['name' => 'Jair Bolsonaro', 'age' => '61', 'profession' => 'Politician', 'adjective' => 'Honest', 'login' => 'jair.myth', 'password' => 'turndownforwhat'], ['name' => 'Tiririca', 'age' => '50', 'profession' => 'Clown, politician', 'adjective' => 'funny', 'login' => 'florentina.florentina', 'password' => 'piorquetanaofica']]];
    return $app->json($output, 200);
});
$app->run();
Esempio n. 24
0
<?php

// static file handling
$info = parse_url($_SERVER['REQUEST_URI']);
$path = __DIR__ . $info['path'];
if (file_exists($path) && is_file($path)) {
    return false;
}
// composer
require_once __DIR__ . '/../vendor/autoload.php';
// create app
$app = new \Silex\Application(['debug' => true]);
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../views'));
$app->get('/', function () use($app) {
    return $app['twig']->render('index.twig');
});
$app->post('upload', function () use($app) {
    $uploader = new \Sokil\Upload\Handler();
    try {
        $uploader->moveLocal(__DIR__ . '/uploads/');
    } catch (\Exception $e) {
        return $app->json(['server' => $_SERVER, 'message' => $e->getMessage()], 500);
    }
    return $app->json(['transport' => $uploader->getTransportName(), 'server' => $_SERVER, 'get' => $_GET, 'post' => $_POST, 'files' => $_FILES]);
});
$app->run();
Esempio n. 25
0
    } else {
        $response = 'Already connected';
    }
    return new Response($response, 200);
});
// Get list of people user has shared with this app.
$app->get('/people', function () use($app, $client, $plus) {
    $token = $app['session']->get('token');
    if (empty($token)) {
        return new Response('Unauthorized request', 401);
    }
    $client->setAccessToken($token);
    $people = $plus->people->listPeople('me', 'visible', array());
    /*
     * Note (Gerwin Sturm):
     * $app->json($people) ignores the $people->items not returning this array
     * Probably needs to be fixed in the Client Library
     * items isn't listed as public property in Google_Service_Plus_Person
     * Using ->toSimpleObject for now to get a JSON-convertible object
     */
    return $app->json($people->toSimpleObject());
});
// Revoke current user's token and reset their session.
$app->post('/disconnect', function () use($app, $client) {
    $token = json_decode($app['session']->get('token'))->access_token;
    $client->revokeToken($token);
    // Remove the credentials from the user's session.
    $app['session']->set('token', '');
    return new Response('Successfully disconnected', 200);
});
$app->run();
Esempio n. 26
0
//Register database
if (!file_exists($dbConfigFile = __DIR__ . "/../app/config/database.json")) {
    echo 'Cannot find database config file. Please create the file.';
    exit;
}
$dbConfig = json_decode(file_get_contents($dbConfigFile), true);
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => $dbConfig));
$app->register(new Silex\Provider\TwigServiceProvider(), array('twig.path' => __DIR__ . '/../src/Ressource/views'));
$app->register(new Silex\Provider\FormServiceProvider());
$app->register(new Silex\Provider\TranslationServiceProvider());
$app->register(new Silex\Provider\UrlGeneratorServiceProvider());
$app->register(new Silex\Provider\SessionServiceProvider());
$app->get('/', function (Request $request) use($app) {
    $text = $app['db']->fetchAssoc("select t.* from text t where t.status = 'accepted' order by t.created_at asc limit 1");
    if ($request->isXmlHttpRequest()) {
        return $app->json($text);
    }
    return $app['twig']->render('display.html.twig', array('text' => $text));
})->bind('display');
$app->get('/list', function () use($app) {
    $texts = $app['db']->fetchAll("select * from text where status in ('pending', 'accepted')");
    return $app['twig']->render('list.html.twig', array('texts' => $texts));
})->bind('list');
$app->get('/question', function () use($app) {
    $form = $app['form.factory']->createBuilder('form')->add('text', 'textarea')->getForm();
    return $app['twig']->render('question.html.twig', array('form' => $form->createView()));
})->bind('question');
$app->post('/question', function (Request $request) use($app) {
    $form = $app['form.factory']->createBuilder('form')->add('text')->getForm();
    $form->handleRequest($request);
    if ($form->isValid()) {
Esempio n. 27
0
// production environment - false; test environment - true
$app['debug'] = true;
//handling CORS preflight request
$app->before(function (Symfony\Component\HttpFoundation\Request $request) {
    if ($request->getMethod() === "OPTIONS") {
        $response = new \Symfony\Component\HttpFoundation\ResponseHeaderBag();
        $response->headers->set("Access-Control-Allow-Origin", "*");
        $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
        $response->headers->set("Access-Control-Allow-Headers", "Content-Type");
        $response->setStatusCode(200);
        return $response->send();
    }
}, \Silex\Application::EARLY_EVENT);
//handling CORS respons with right headers
$app->after(function (Symfony\Component\HttpFoundation\Request $request, Symfony\Component\HttpFoundation\Response $response) {
    $response->headers->set("Access-Control-Allow-Origin", "*");
    $response->headers->set("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
});
// setting up json request data
$app->before(function (Symfony\Component\HttpFoundation\Request $request) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $data = json_decode($request->getContent(), true);
        $request->request->replace(is_array($data) ? $data : array());
    }
});
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
$app->register(new Silex\Provider\DoctrineServiceProvider(), $config['db']);
$app->error(function (\Exception $e, $code) use($app) {
    return $app->json(array("error" => $e->getMessage()), $code);
});
return $app;
Esempio n. 28
0
password (string): Password to use when connecting to the database.
host (string): Hostname of the database to connect to.
port (integer): Port of the database to connect to.
dbname (string): Name of the database/schema to connect to.
servicename (string): Optional name by which clients can connect to the database instance. Will be used as Oracle’s SID connection parameter if given and defaults to Doctrine’s dbname connection parameter value.
service (boolean): Whether to use Oracle’s SERVICE_NAME connection parameter in favour of SID when connecting. The value for this will be read from Doctrine’s servicename if given, dbname otherwise.
pooled (boolean): Whether to enable database resident connection pooling.
charset (string): The charset used when connecting to the database.
instancename (string): Optional parameter, complete whether to add the INSTANCE_NAME parameter in the connection. It is generally used to connect to an Oracle RAC server to select the name of a particular instance.
*/
$app->register(new Silex\Provider\DoctrineServiceProvider(), array('db.options' => array('driver' => 'oci8', 'host' => 'localhost', 'port' => '1521', 'user' => 'buku555', 'password' => 'buku555', 'servicename' => 'XE')));
// route for "/countries" URI: load countries list and return it in JSON format
$app->get('/users', function () use($app) {
    $sql = "SELECT * FROM b_trxs";
    $users = $app['db']->fetchAll($sql);
    return $app->json($users);
});
// route for "/countries/{id}" URI: load specific country info and return it in JSON format
/*
$app->get('/countries/{id}', function ($id) use ($app) {
    $sql = "SELECT id, cities FROM countries WHERE id = ?";
    $country = $app['db']->fetchAssoc($sql, array((int) $id));

    return $app->json($country);
})->assert('id', '\d+');
*/
// default route
$app->get('/', function () {
    return "List of avaiable methods:\n  - /countries - returns list of existing countries;\n\n  - /countries/{id} - returns list of country's cities by id;";
});
$app->run();
Esempio n. 29
-1
 *
 */
$app->before(function (Request $request) use($app) {
    if (0 === strpos($request->headers->get('Content-Type'), 'application/json')) {
        $app['data'] = json_decode($request->getContent(), true);
    }
});
/***
 *
 * Endpoints.
 * @see https://github.com/okfn/annotator/wiki/Storage
 *
 */
$app->get('/', function () use($app) {
    $out = array('name' => "Annotator Store API (PHP)", 'version' => '1.0.0', 'author' => 'julien-c');
    return $app->json($out);
});
$app->get('/annotations', function () use($app) {
    $out = array();
    $m = new Mongo();
    $c = $m->annotator->annotations->find();
    foreach ($c as $post) {
        $post['id'] = (string) $post['_id'];
        unset($post['_id']);
        $out[] = $post;
    }
    return $app->json($out);
});
$app->post('/annotations', function () use($app) {
    $post = $app['data'];
    $m = new Mongo();
    // Grab the uploaded file
    $file = $request->files->get('upload');
    // Extract some information about the uploaded file
    $info = new SplFileInfo($file->getClientOriginalName());
    // Create a quasi-random filename
    $filename = sprintf('%d.%s', time(), $info->getExtension());
    // Copy the file
    $file->move(__DIR__ . '/../uploads', $filename);
    // Instantiate the Tessearct library
    $tesseract = new TesseractOCR(__DIR__ . '/../uploads/' . $filename);
    // Perform OCR on the uploaded image
    $text = $tesseract->recognize();
    return $app['twig']->render('results.twig', ['text' => $text]);
});
$app->post('/identify-telephone-number', function (Request $request) use($app) {
    // Grab the uploaded file
    $file = $request->files->get('upload');
    // Extract some information about the uploaded file
    $info = new SplFileInfo($file->getClientOriginalName());
    // Create a quasi-random filename
    $filename = sprintf('%d.%s', time(), $info->getExtension());
    // Copy the file
    $file->move(__DIR__ . '/../uploads', $filename);
    // Instantiate the Tessearct library
    $tesseract = new TesseractOCR(__DIR__ . '/../uploads/' . $filename);
    // Perform OCR on the uploaded image
    $text = $tesseract->recognize();
    $number = findPhoneNumber($text, 'GB');
    return $app->json(['number' => $number]);
});
$app->run();