Exemplo n.º 1
0
 public function run()
 {
     $configuration = ['settings' => ['displayErrorDetails' => false]];
     $c = new \Slim\Container($configuration);
     $c['notFoundHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(404)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'not_found', 'pretty_error' => 'Could not find the specified endpoint.'), JSON_PRETTY_PRINT));
         };
     };
     $c['errorHandler'] = function ($c) {
         return function ($request, $response) use($c) {
             return $c['response']->withStatus(500)->withHeader('Content-type', 'application/json')->write(json_encode(array('status' => 404, 'error' => 'internal_error', 'pretty_error' => 'An internal error has occured, please contact the site administrator.'), JSON_PRETTY_PRINT));
         };
     };
     $app = new \Slim\App($c);
     $app->add(new AuthenticationMiddleware());
     $app->get('/oauth/v2/authorize', 'PleioRest\\Controllers\\Authentication::authorize');
     $app->post('/oauth/v2/token', 'PleioRest\\Controllers\\Authentication::getToken');
     $app->get('/api/users/me', 'PleioRest\\Controllers\\User:me');
     $app->post('/api/users/me/register_push', 'PleioRest\\Controllers\\User:registerPush');
     $app->post('/api/users/me/deregister_push', 'PleioRest\\Controllers\\User:deregisterPush');
     $app->post('/api/users/me/generate_token', 'PleioRest\\Controllers\\User:generateToken');
     $app->get('/api/users/me/login_token', 'PleioRest\\Controllers\\User:loginToken');
     $app->get('/api', 'PleioRest\\Controllers\\Version:getVersion');
     $app->get('/api/doc', 'PleioRest\\Controllers\\Documentation:getDocumentation');
     $app->get('/api/doc/swagger', 'PleioRest\\Controllers\\Documentation:getSwagger');
     $app->get('/api/sites', 'PleioRest\\Controllers\\Sites:getAll');
     $app->get('/api/sites/mine', 'PleioRest\\Controllers\\Sites:getMine');
     $app->get('/api/groups', 'PleioRest\\Controllers\\Groups:getAll');
     $app->get('/api/groups/mine', 'PleioRest\\Controllers\\Groups:getMine');
     $app->get('/api/groups/{guid}/activities', 'PleioRest\\Controllers\\Activities:getGroup');
     $app->post('/api/groups/{guid}/activities/mark_read', 'PleioRest\\Controllers\\Activities:markRead');
     $app->get('/api/groups/{guid}/events', 'PleioRest\\Controllers\\Events:getGroup');
     $app->get('/api/groups/{guid}/members', 'PleioRest\\Controllers\\Members:getGroup');
     $app->get('/api/groups/{guid}/files', 'PleioRest\\Controllers\\Files:getGroup');
     $app->run();
 }
Exemplo n.º 2
0
    } else {
        return json_encode(array('success' => false, 'message' => 'Email o password invalid.'));
    }
});
$app->get('/get', function ($request, $response, $args) {
    $csrf_result = $request->getAttribute('csrf_result');
    if (null === $csrf_result) {
        return json_encode(array('success' => false));
    } else {
        return json_encode(array('success' => true));
    }
});
$app->post('/post', function ($request, $response, $args) {
    $csrf_result = $request->getAttribute('csrf_result');
    if (null === $csrf_result) {
        return json_encode(array('success' => false));
    } else {
        return json_encode(array('success' => true));
    }
});
$app->run();
/**
 * Request params
 */
function getParams($request)
{
    // POST or PUT
    $params = $request->getParsedBody();
    // GET
    if (empty($params)) {
        $params = $request->getQueryParams();
    }
Exemplo n.º 3
0
$app->get("/todos", function ($request, $response, $arguments) {
    $todos = $this->spot->mapper("App\\Todo")->all();
    $fractal = new Manager();
    $fractal->setSerializer(new ArraySerializer());
    $resource = new Collection($todos, new TodoTransformer());
    $data = $fractal->createData($resource)->toArray();
    /* Fractal collections are always namespaced. Apparently a feature and */
    /* not a bug. Thus we need to return $data["data"] for TodoMVC examples. */
    /* https://github.com/thephpleague/fractal/issues/110 */
    return $response->withStatus(200)->withHeader("Content-Type", "application/json")->write(json_encode($data["data"], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->post("/todos", function ($request, $response, $arguments) {
    $body = $request->getParsedBody();
    $todo = new Todo($body);
    $this->spot->mapper("App\\Todo")->save($todo);
    $fractal = new Manager();
    $fractal->setSerializer(new ArraySerializer());
    $resource = new Item($todo, new TodoTransformer());
    $data = $fractal->createData($resource)->toArray();
    return $response->withStatus(201)->withHeader("Content-Type", "application/json")->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->get("/todos/{uid}", function ($request, $response, $arguments) {
    $todo = $this->spot->mapper("App\\Todo")->first(["uid" => $arguments["uid"]]);
    $fractal = new Manager();
    $fractal->setSerializer(new ArraySerializer());
    $resource = new Item($todo, new TodoTransformer());
    $data = $fractal->createData($resource)->toArray();
    return $response->withStatus(200)->withHeader("Content-Type", "application/json")->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->patch("/todos/{uid}", function ($request, $response, $arguments) {
    $body = $request->getParsedBody();
    $todo = $this->spot->mapper("App\\Todo")->first(["uid" => $arguments["uid"]]);
Exemplo n.º 4
0
*verifier  et securiser les données
**/
$app->post('/api/add/wines', function (Request $request, Response $response) {
    $request = $app->request();
    //   or $app = \Slim\Slim::getInstance();
    $body = $request->getBody();
    //      $allPostVars = $app->request->post(); renvoie null si non trouvé
    $input = json_decode($body);
    //      $name = $allPostVars['name'];
    $sql = "INSERT INTO wine(name,grapes,country,region,year,description) VALUES(:name, :grapes, :country, :region, :year, :description)";
    try {
        $db = thisConnection();
        $stmt = $db->prepare($sql) or exit(print_r($db->errorInfo()));
        $stmt->bindParam("name", $input->name);
        //remplacer $input->name par $name etc.
        $stmt->bindParam("grapes", $input->grapes);
        $stmt->bindParam("country", $input->country);
        $stmt->bindParam("region", $input->region);
        $stmt->bindParam("year", $input->year);
        $stmt->bindParam("description", $input->description);
        $stmt->execute();
        $input->id = $db->lastInsertId();
        $response->getBody()->write(json_encode($input));
    } catch (PDOException $e) {
        $response->getBody()->write('{"error":' . $e->getMessage() . '}');
        die;
    }
    return $response;
});
$app->put('/api/wines/{id}', function (Request $request, Response $response, $args) {
    $request = $app->request();
Exemplo n.º 5
0
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require_once 'vendor/autoload.php';
$app = new \Slim\App();
//API function:POST:Login
$app->post('/login', function (Request $request, Response $response) use($app) {
    //decode JSON data into object and assign its proteprties into $user variable for further usage
    $tmp = json_decode($request->getBody());
    $user['login'] = $tmp->username;
    $user['pass'] = $tmp->password;
    //set output header: content-type
    $newresponse = $response->withHeader('Content-type', 'application/json');
    //try login
    $loginresult = login($user['login'], $user['pass']);
    if ($loginresult !== false) {
        //login successful
        //encode token and other user data and send them to client
        $output = json_encode(array("token" => $loginresult['token'], 'user_id' => $loginresult['user_id']));
        $newresponse = $newresponse->withStatus(200);
        $body = $newresponse->getBody();
        $body->write($output);
    } else {
        //login unsuccessful
        $newresponse = $newresponse->withStatus(401);
    }
    return $newresponse;
});
//API function:GET:Get file list
$app->get('/getfilelist/{token}/{user_id}', function (Request $request, Response $response, $args) use($app) {
    //set output header: content-type
    $newresponse = $response->withHeader('Content-type', 'application/json');
    //check if token is expired or invalid
Exemplo n.º 6
0
    if (!$this->server->verifyResourceRequest($this->server->getRequest())) {
        $this->server->getResponse()->send();
        die;
        // Important, otherwise Slim overrides HTTP headers
    }
    $response = $next($request, $response);
    return $response;
};
// Homepage
$app->get('/', function ($request, $response, $args) {
    return $response->write("homepage");
});
// Token request
$app->post('/token', function ($request, $response, $args) {
    // Handle a request for an OAuth2.0 Access Token and send the response to the client
    $this->server->handleTokenRequest($this->server->getRequest())->send();
    die;
    // Important, otherwise Slim overrides HTTP headers
});
// Sync request
$app->post('/sync', function ($request, $response, $args) {
    $token = $this->server->getAccessTokenData($this->server->getRequest());
    $deviceNotes = $this->db->getDeviceNotesFromJson($request->getParam('notes'));
    $devices = $this->db->getDevices($token['user_id']);
    $cloudNotes = $this->db->getNotesToSync($token['user_id'], $token['device_id']);
    $this->db->insertNotesFromDevice($deviceNotes);
    $this->db->setToSyncForOtherDevices($devices, $deviceNotes, $token['device_id']);
    $this->db->setSyncOKForDevice($cloudNotes, $token['device_id']);
    $this->db->cleanNotes($token['device_id']);
    return $response->withJson($cloudNotes);
})->add($oAuthMiddleware);
// Run app
Exemplo n.º 7
0
$app->put('/user/{uid}/pass', function ($request, $response, $args) {
    $member = new \Models\Member();
    $response->write($member->updatePassword($args['uid'], $request->getParsedBody(), \Middleware\Authenticate::$requestUid));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
})->add($auth);
$app->put('/user/{uid}/groups', function ($request, $response, $args) {
    $member = new \Models\Member();
    $response->write($member->updateGroupSort($request->getParsedBody(), $args['uid'], \Middleware\Authenticate::$requestUid));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
})->add($auth);
$app->post('/user', function ($request, $response, $args) {
    $member = new \Models\Member();
    //    error_log( print_r($request->getParsedBody(), 1));
    $response->write($member->addNewMember($request->getParsedBody()));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
});
$app->post('/emailexists', function ($request, $response, $args) {
    $member = new \Models\Member();
    $response->write($member->emailExists($request->getParsedBody()));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
});
$app->delete('/user', function ($request, $response, $args) {
    $member = new \Models\Member();
    $response->write($member->deleteMember($request->getParsedBody(), \Middleware\Authenticate::$requestUid));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
})->add($auth);
Exemplo n.º 8
0
        $resource = AbstractResource::load($resource, $request, $response, $this);
        return $response->withJson($formatter->getSuccess($resource->get($id)));
    } catch (StatusException $e) {
        return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode());
    } catch (Exception $e) {
        return $response->withStatus(500);
    }
});
// Post
$app->post('/{resource}', function (ServerRequestInterface $request, Response $response, $resource) {
    /**
     * @var ResponseDataFormatter $formatter
     */
    $formatter = $this->get('dataFormatter');
    try {
        $resource = AbstractResource::load($resource, $request, $response, $this);
        return $response->withJson($formatter->getSuccess($resource->post()));
    } catch (StatusException $e) {
        return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode());
    } catch (Exception $e) {
        return $response->withStatus(500);
    }
});
// Put
$app->put('/{resource}/{id}', function (ServerRequestInterface $request, Response $response, $resource, $id = null) {
    /**
     * @var ResponseDataFormatter $formatter
     */
    $formatter = $this->get('dataFormatter');
    try {
        $resource = AbstractResource::load($resource, $request, $response, $this);
        return $response->withJson($formatter->getSuccess($resource->put($id)));
Exemplo n.º 9
0
 $app->get('/catalog[/{table}]', function ($req, $res, $args) {
     $table = isset($args['table']) ? $args['table'] : null;
     $result = Store::catalog($table);
     if (!$result) {
         return $res->withStatus(404)->write(JsonHelper::fail('Tabella inesistente.'));
     }
     return $res->write(JsonHelper::success($result));
 });
 /**
  *
  */
 $app->post('/autenticazione', function ($req, $res) {
     $body = $req->getParsedBody();
     $codiceFiscale = isset($body['codice_fiscale']) ? $body['codice_fiscale'] : '';
     $password = isset($body['password']) ? $body['password'] : '';
     $result = Auth::authenticate($codiceFiscale, $password);
     if (!$result) {
         return $res->withStatus(403)->write(JsonHelper::fail('Codice Fiscale e/o Password errati.'));
     }
     return $res->write(JsonHelper::success($result));
 });
 /**
  *
  */
 $app->get('/profilo/{id_utenza:\\d}', function ($req, $res, $args) {
     $idUtenza = $args['id_utenza'];
     $tipologia = $args['_tipologia'];
     $queryParams = $req->getQueryParams();
     $incsQuery = isset($queryParams['include']) ? $queryParams['include'] : '';
     $result = Store::getProfilo($idUtenza, $tipologia, $incsQuery);
     $res->write(JsonHelper::success($result));
 })->add(new SetACL())->add(new VerifyToken());
Exemplo n.º 10
0
        $page = $query['page'];
    }
    if (isset($query['booksPerPage'])) {
        $booksPerPage = $query['booksPerPage'];
    }
    $responseBody = $response->getBody();
    $responseBody->write(json_encode($library->listOfBooks($page, $booksPerPage)));
    return $response->withHeader('Content-Type', 'application/json')->withStatus(200)->withBody($responseBody);
});
//Create reservation for book
$app->post('/reservations', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app, $reservationDataValidator) {
    $reservationId = Uuid::uuid4();
    $requestBody = $request->getParsedBody();
    if ($reservationDataValidator($requestBody) == false) {
        return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
    }
    $bookId = Uuid::fromString($requestBody['bookId']);
    $library->createReservation($reservationId, $bookId, $requestBody['email']);
    $responseBody = $response->getBody();
    $responseBody->write(json_encode(['id' => (string) $reservationId]));
    return $response->withHeader('Content-Type', 'application/json')->withStatus(201);
});
//Give away reservation for book
$app->patch('/reservations/{reservationId}', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app, $givenAwayValidator) {
    $reservationId = Uuid::fromString($args['reservationId']);
    $requestBody = $request->getParsedBody();
    if ($givenAwayValidator($requestBody) == false) {
        return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
    }
    try {
        $library->giveAwayBookInReservation($reservationId, new \DateTime($requestBody['givenAwayAt']));
    } catch (BookInReservationAlreadyGivenAway $e) {
Exemplo n.º 11
0
        $jobReady = null;
        $statsTube = [];
        $stats = [];
        $tubes = [];
    }
    $r = $res->withHeader('Content-Type', 'application/json');
    $r->write(json_encode(['isServiceListening' => $isServiceListening, 'jobBuried' => $jobBuried, 'jobDelayed' => $jobDelayed, 'jobReady' => $jobReady, 'serverAddress' => $config['beanstalk_server'], 'statsTube' => $statsTube, 'stats' => $stats, 'tubes' => $tubes]));
    return $r;
});
$app->post('/cmd/delete', function ($req, $res) use($pheanstalk) {
    $job_id = $req->getParam('job_id');
    try {
        v::numeric()->setName('job_id')->check($job_id);
    } catch (ValidationExceptionInterface $e) {
        return $res->withStatus(400)->write($e->getMainMessage());
    }
    try {
        $job = new \Pheanstalk\Job($job_id, []);
        $pheanstalk->delete($job);
    } catch (\Pheanstalk\Exception\ServerException $e) {
        return $res->withStatus(400)->write($e->getMessage());
    }
});
$app->post('/cmd/kick', function ($req, $res) use($pheanstalk) {
    $job_id = $req->getParam('job_id');
    try {
        v::numeric()->setName('job_id')->check($job_id);
    } catch (ValidationExceptionInterface $e) {
        return $res->withStatus(400)->write($e->getMainMessage());
    }
    try {
        $job = new \Pheanstalk\Job($job_id, []);
Exemplo n.º 12
0
// Login
$app->post('/login', function ($request, $response, $args) {
    $body = json_decode($request->getBody(), true);
    $db = $this->dbConnection;
    $sql = "SELECT * FROM user WHERE login=:login AND password=:password LIMIT 1;";
    $stmt = $db->prepare($sql);
    $stmt->bindValue(':login', $body['alias']);
    $stmt->bindValue(':password', $body['password']);
    $success = $stmt->execute();
    if ($success && $stmt->rowCount()) {
        $userId = $stmt->fetch(PDO::FETCH_ASSOC)['id'];
        // Create SessionToken
        $token = hash('sha256', date('Ymdhis', time()) . $body['alias']);
        $sql = "INSERT INTO session (token, expire, userid) VALUES (:token, :expire, :user);";
        $stmt = $db->prepare($sql);
        $stmt->bindValue(':token', $token);
        $stmt->bindValue(':expire', time() + 30 * 60);
        $stmt->bindValue(':user', $userId);
        $stmt->execute();
        // todo if error
        $response->getBody()->write(json_encode(array('token' => $token)));
    } else {
        if (!$success) {
            throw new Exception($stmt->errorInfo()[2]);
        } else {
            $response->withStatus(401);
            $response->getBody()->write(json_encode(array('error' => 'Nutzername oder Passwort falsch')));
        }
    }
    return $response;
});
/***********************************************************************************************************************
Exemplo n.º 13
0
    return $response->withStatus(401);
};
$app->get('/', function ($request, $response, $args) {
    $response->write("Welcome to Slim!");
    return $response;
});
$app->get('/register', function ($request, $response, $args) {
    render('views/registration.php');
    return $response;
});
$app->post('/registration', function ($request, $response, $args) {
    $data = $request->getParsedBody();
    $user = new User(db::getInstance());
    $result = $user->addUser($data['username'], $data['password'], $data['email']);
    if ($result) {
        $response->write("Registration successful");
    } else {
        $response->write("Error: wrong data format");
    }
    return $response;
});
$app->post('/login', function ($request, $response, $args) {
    $data = $request->getParsedBody();
    $user = new User(db::getInstance());
    $result = $user->checkUser($data['username'], $data['password']);
    if ($result === false) {
        $response->write(json_encode(array('error' => array('message' => 'Wrong login information.'))));
    } else {
        $response->write(json_encode(array('token' => $result)));
    }
    return $response;
Exemplo n.º 14
0
<?php

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require 'vendor/autoload.php';
// Create the base app
$app = new \Slim\App();
// Define the app routes
$app->get('/', 'home');
$app->get('/get/emojis', 'getEmojis');
$app->post('/create/emoji', 'createEmoji');
// Run the application
$app->run();
// Define the API functions
function home()
{
    echo 'No direct access, sorry :(';
}
function createEmoji($dbh)
{
    $request = Slim::getInstance()->request();
    $emoji = json_decode($request->getBody());
    $sql = "INSERT INTO checkins (lattitude, longitud, emoji) VALUES (:lattitude, :longitud, :emoji)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("lattitude", $emoji->lattitude);
        $stmt->bindParam("longitud", $emoji->longitud);
        $stmt->bindParam("emoji", $emoji->emoji);
        $stmt->execute();
        $emoji->id = $db->lastInsertId();
Exemplo n.º 15
0
//the project parameter of Slim app.
$projectParameters = array('setting' => array('displayErrorDetails' => true, 'debug' => AppConfig::SLIM_APP_DEBUG_MODEL, 'log.enabled' => AppConfig::SLIM_APP_LOGS_MODEL, 'mode' => 'development'));
//instance of Slim App
$app = new Slim\App($projectParameters);
/**
$app->get('/hello[/{name}]', function ($request, $response, $args) {
    $response->write("Hello, " . $args['name']);
    return $response;
})->setArgument('name', 'World! Missing the name!');
*/
$app->get('/status/{server_host}/{server_port}', function (Request $request, Response $response, $arguments) {
    $response->write(TinyCacheService::getServerStatus($arguments));
    return $response;
});
$app->post('/status', function (Request $request, Response $response) {
    $response->write(TinyCacheService::getMultiServerStatus($request->getParsedBody()));
    return $response;
});
$app->get('/getAllItems/{server_host}/{server_port}', function (Request $request, Response $response, $arguments) {
    $response->write(TinyCacheService::getAllCacheItems($arguments));
    return $response;
});
$app->post('/cacheList', function (Request $request, Response $response) {
    $response->write(TinyCacheService::getUserCacheServerList($request->getParsedBody()));
    return $response;
});
$app->post('/cacheDetail', function (Request $request, Response $response) {
    $response->write(TinyCacheService::getResultCacheDetailAction($request->getParsedBody()));
    return $response;
});
$app->post('/cacheFilter', function (Request $request, Response $response) {
    $response->write(TinyCacheService::getCacheFilterList($request->getParsedBody()));
Exemplo n.º 16
0
    $dbuser = '';
    $dbpass = '';
    $dbh = new PDO('mysql:host=localhost;dbname=', $dbuser, $dbpass);
    $dbh->exec('set names utf8');
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbh;
}
$app = new Slim\App();
$app->post('/login', function ($request, $response) {
    $data = $request->getParsedBody();
    $sql = "SELECT CASE WHEN usuario=:usuario AND password=:password THEN 1 ELSE 0 END acess FROM users";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam('usuario', $data['un'], PDO::PARAM_STR);
        $stmt->bindParam('password', $data['pw'], PDO::PARAM_STR);
        $stmt->execute();
        $resp = $stmt->fetch(PDO::FETCH_OBJ);
        $db = null;
        $response->getBody()->write(json_encode($resp, JSON_NUMERIC_CHECK));
    } catch (PDOException $e) {
        $response->getBody()->write(json_encode($e->getMessage()));
    }
});
$app->post('/suporte', function ($request, $response) {
    $data = $request->getParsedBody();
    $headers = "MIME-Version: 1.0\r\n";
    $headers .= "Content-type: text/html; charset=utf-8\r\n";
    $headers .= "From: {$data['nome']} <{$data['email']}>\r\n";
    mail('*****@*****.**', 'Suporte SGF', $data[mensagem], $headers);
});
$app->add(new \Slim\Middleware\HttpBasicAuthentication(['path' => '/app', 'authenticator' => function ($arguments) {
Exemplo n.º 17
0
$app->get('/', function ($request, $response, $args) {
    return $this->view->render($response, 'index.phtml');
})->setName('index');
$app->get('/util', "jra\\HomeController:dispatch");
$app->map(['GET', 'POST'], '/util/photodata', function ($request, $response, $args) {
    $path = './assets/images/photodata/';
    $filename = $_FILES['file']['name'];
    $fileManager = new FileManager();
    $fileManager->uploadFile($path . $filename);
    $imageFactory = new ImageFactory();
    //Don't see why I need to call this again even though it's
    //called in the constructor?
    $imageFactory->populateImages();
    return $this->view->render($response, 'photodata.phtml', ['title' => 'Exif Data Viewer', 'images' => $imageFactory->images, 'stylesheet' => '/assets/css/components/cards/card-1/card-1.css', 'sweetalertcss' => '/libraries/sweetalert/dist/sweetalert.css', 'sweetalertjs' => '/libraries/sweetalert/dist/sweetalert.min.js', 'script' => '/assets/js/photodata.js']);
});
$app->map(['GET', 'POST'], '/util/rawtext', function ($request, $response, $args) {
    return $this->view->render($response, 'rawtext.phtml', ['title' => 'Raw Text', 'input' => json_encode($_POST['input'])]);
});
$app->get('/util/webgrep', function ($request, $response, $args) {
    return $this->view->render($response, 'webgrep.phtml', ['title' => 'Grep The Web!']);
});
$app->get('/util/imagemaker', function ($request, $response, $args) {
    return $this->view->render($response, 'imagemaker.phtml', ['title' => 'Imagemaker']);
});
$app->post('/util/imagemaker', function ($request, $response, $args) {
    return $response->getBody()->write(var_dump($_POST));
});
$app->get('/snippets/{snippet}', function ($request, $response, $args) {
    return $this->view->render($response, $args['snippet'] . '.phtml', ['title' => ucwords($args['snippet'])]);
});
$app->run();
Exemplo n.º 18
0
// get reply kaka by question
$app->get("/replyKakaByQuestion[/{id_question}]", function ($request, $response, $args) use($app, $db) {
    $reply = $db->tbl_reply_kaka()->where("id_question", $args['id_question']);
    if ($value = $reply->fetch()) {
        $rep["data"] = array('id' => $value['id'], 'id_kaka' => $value['id_kaka'], 'id_question' => $value['id_question'], 'reply' => $value['reply'], 'date' => $value['date'], 'status' => $value['status']);
        echo json_encode(array("status" => 200, "message" => "data found", "response" => $rep["data"]));
    } else {
        echo json_encode(array("status" => 400, "message" => "No Data"));
    }
});
// insert adik
$app->post("/adik", function ($request) use($app, $db) {
    $adik = $request->getParsedBody();
    $result = $db->tbl_adik()->insert($adik);
    if ($result) {
        echo json_encode(array("status" => 200, "message" => "success"));
    } else {
        echo json_encode(array("status" => 400, "message" => "failed"));
    }
});
// insert kaka
$app->post("/kaka", function ($request) use($app, $db) {
    $kaka = $request->getParsedBody();
    $result = $db->tbl_kaka()->insert($kaka);
    if ($result) {
        echo json_encode(array("status" => 200, "message" => "success"));
    } else {
        echo json_encode(array("status" => 400, "message" => "failed"));
    }
});
// insert questions
Exemplo n.º 19
0
<?php

/**
 * Created by PhpStorm.
 * User: RDuuke
 * Date: 03/11/2015
 * Time: 08:07 PM
 */
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
$app = new Slim\App();
$app->get('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:index');
$app->post('/users', '\\RDuuke\\Mdn\\Controllers\\UsersController:store');
$app->get('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:show');
$app->put('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:update');
$app->delete('/users/{id}', '\\RDuuke\\Mdn\\Controllers\\UsersController:destroy');
$app->run();
Exemplo n.º 20
0
$app->post('/process', function ($request, $response, $args) {
    $sanitize_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    // Validate the email address
    $email = trim(filter_var($sanitize_email, FILTER_VALIDATE_EMAIL));
    // Throw different messages based on address
    if (empty($sanitize_email) || !$email) {
        if (empty($sanitize_email)) {
            $message = "Please enter an email address.";
        } else {
            $message = $sanitize_email . " is not a valid email.";
        }
        $response = array("status" => 400, "details" => $message);
    } else {
        $hash = MD5(strtolower($email));
        $data = array('status' => 'subscribed', 'email_address' => $email);
        if (isset($_POST['interested'])) {
            $interests = $_POST['interested'];
            foreach ($interests as $interest) {
                $groups[$interest] = true;
            }
            $data['interests'] = $groups;
        }
        $subscribe = $this->mailchimp->request("PUT", "/lists/bc9233b42a/members/" . $hash, $data);
        if ($subscribe->status != "subscribed") {
            $response = array("status" => $subscribe->status, "details" => "There was an problem. Please try again.");
        } else {
            $detail = $email . " was subscribed";
            $response = array("status" => 200, "details" => $detail);
        }
    }
    echo json_encode($response);
});
Exemplo n.º 21
0
{
    $app = \Slim\Slim::getInstance();
    if (API_TOKEN != $_POST['token']) {
        $app->halt(401);
    }
}
//print_r($app->request()); exit;
//echo "hi".$app->request->getUri(); exit;
$app->post('/login', function ($request, $response, $args) {
    validate_user($request->getParsedBody());
    $post_data = $request->getParsedBody();
    $username = $post_data['username'];
    $password = $post_data['password'];
    $obj = SchoolAppClass::set_instance();
    $response = $obj->login($username, $password, $post_data['device_token']);
    $obj->log_api($post_data, $_SERVER['REQUEST_URI'], $response);
    if ($response['is_success']) {
        // echo "test";
        //session_start();
        $_SESSION['logged_in'] = 1;
        //echo $_SESSION['logged_in'];
    }
    echo json_encode($response);
});
$app->post('/create_user', function ($request, $response, $args) {
    validate_user($request->getParsedBody());
    $obj = SchoolAppClass::set_instance();
    $response = $obj->create_user($request->getParsedBody());
    $obj->log_api($request->getParsedBody(), $_SERVER['REQUEST_URI'], $response);
    echo json_encode($response);
});
$app->post('/list_users', function ($request, $response, $args) {
Exemplo n.º 22
0
<?php

use Charger\Controllers\PaymentController;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
require '../vendor/autoload.php';
$app = new Slim\App();
$app->post('/payment', function (ServerRequestInterface $request, ResponseInterface $response) {
    return (new PaymentController())->payment($request, $response);
});
$app->run();
Exemplo n.º 23
0
<?php

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
use GuzzleHttp\Client;
require '../vendor/autoload.php';
$configuration = ['settings' => ['displayErrorDetails' => true]];
$container = new \Slim\Container($configuration);
$app = new \Slim\App($container);
$app->post('/', function (Request $request, Response $response) {
    $text = $request->getParsedBody()['text'];
    $rightGifResponse = (new Client())->request('POST', 'https://rightgif.com/search/web', ['json' => ['text' => $text]]);
    $rightGif = json_decode($rightGifResponse->getBody(), 1)['url'];
    $giphyResponse = (new Client())->request('GET', 'http://api.giphy.com/v1/gifs/search?q=' . urlencode($text) . '&api_key=dc6zaTOxFJmzC&limit=1&offset=0');
    $gif = json_decode($giphyResponse->getBody(), 1);
    $giphyGif = $gif['data'][0]['images']['original']['url'];
    $guzzleResponse = (new Client())->request('POST', getenv('CALLBACK'), ['json' => ['text' => '*Gif duel:* _' . $text . '_', 'attachments' => [['fallback' => $text, 'text' => 'Rightgif', 'image_url' => $rightGif], ['fallback' => $text, 'text' => 'Giphy', 'image_url' => $giphyGif]]]]);
    return $response->withStatus(200);
});
$app->run();
Exemplo n.º 24
0
$app->get('/', function ($request, $response) {
    $data = ["home" => "/", "list" => "/list"];
    $response = $this->formatter->render($response, $data);
    return $response;
});
$app->get("/list", function ($request, $response) {
    // fetch items
    $items = [];
    $fp = fopen('../items.csv', 'r');
    while (false !== ($data = fgetcsv($fp))) {
        $items[] = current($data);
    }
    $data = ["items" => $items, "count" => count($items)];
    $response = $this->formatter->render($response, $data);
    return $response;
});
$app->post("/list", function ($request, $response) {
    $data = $request->getParsedBody();
    if (isset($data) && isset($data['item']) && !empty($data['item'])) {
        $this->logger->addInfo("Adding data item: " . $data['item']);
        // save item
        $fp = fopen('../items.csv', 'a');
        fputcsv($fp, [$data['item']]);
        $response = $response->withStatus(201)->withHeader("Location", "/list");
        $response = $this->formatter->render($response);
        return $response;
    }
    // if we got this far, something went really wrong
    throw new UnexpectedValueException("Item could not be parsed");
});
$app->run();
Exemplo n.º 25
0
    $idCountry = getId($args['idCountry'], 'countries');
    $idLan = getId($args['idLan'], 'languages');
    $name = clearStr($put['Name']);
    if ($idCity && $idCountry && $idLan) {
        updateId($idLan['id'], 'languages', $name);
        return $response->withJson(array('status' => 1, 'message' => "Language updated sucsesfully", 'args' => $args, 'put' => $put));
    } else {
        return $response->withJson(array('status' => 0, 'message' => "Country ID {$args['idCountry']} or City {$args['idCity']} or Language {$args['idLan']} does not exists"));
    }
});
/* Add new country */
$app->post("/country/", function ($request, $response, $args) use($link) {
    $post = $request->getParsedBody();
    $name = clearStr($post['Name']);
    if ($id = insertItem('countries', $name)) {
        return $response->withJson(array("id" => $id));
    } else {
        $response->withJson(array('status' => 0, 'message' => "Failed to insert country"));
    }
});
/* Add new city */
$app->post("/country/{idCountry}/city/", function ($request, $response, $args) use($link) {
    if ($idCountry = getId($args['idCountry'], 'countries')) {
        $post = $request->getParsedBody();
        $name = clearStr($post['Name']);
        $id = insertItem('cities', $name);
        if (bindItems('ccities', 'Id_Country', 'Id_city', $idCountry['id'], $id)) {
            return $response->withJson(array("id" => $id, 'idcountry' => $idCountry));
        }
    }
    return $response->withJson(array('status' => 0, 'message' => "Failed to insert city"));
Exemplo n.º 26
0
$app->post('/', function (Request $request, Response $response) {
    //flag
    $id = false;
    try {
        //Recup & Initializing data
        $name = strtoupper($_POST["name"]);
        $grapes = $_POST["grapes"];
        $country = $_POST["country"];
        $region = $_POST["region"];
        $year = $_POST["year"];
        $description = $_POST["description"];
        if (isset($_POST["picture"])) {
            $img = $_POST["picture"];
        } else {
            $img = "default.jpg";
        }
        //Create a newWine
        $newWine = R::dispense('wine');
        //Add properties
        $newWine->name = $name;
        $newWine->grapes = $grapes;
        $newWine->country = $country;
        $newWine->region = $region;
        $newWine->year = $year;
        $newWine->description = $description;
        $newWine->picture = $img;
        //Store in the database
        $id = R::store($newWine);
        //Return data
        if ($id !== false) {
            echo "valid";
        } else {
            echo "unvalid";
        }
        //IF 404 - 500
    } catch (ResourceNotFoundException $e) {
        echo "404";
    } catch (Exception $e) {
        echo "400";
    }
});
<?php

require '../vendor/autoload.php';
require 'bootEloquent.php';
use Slim\Views\PhpRenderer;
$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);
$container = $app->getContainer();
$container['view'] = new PhpRenderer(__DIR__ . '/../views/');
$app->get('/', function ($request, $response, $args) {
    return $this->view->render($response, 'hello.php', ['pessoas' => Pessoa::all()]);
});
$app->post('/pessoas', function ($request, $response, $args) {
    $pessoa = new Pessoa();
    $pessoa->nome = $request->getParam('nome');
    $pessoa->save();
    return $response->withRedirect('/');
});
$app->run();
Exemplo n.º 28
0
}
function parseJsonBody($request)
{
    return json_decode($request->getBody(), true);
}
function putJsonBody($body, $status, $response)
{
    return $response->withStatus($status)->withHeader('Content-Type', 'application/json')->write(json_encode($body));
}
function putError($body, $code, $response)
{
    return putJsonBody(array('error' => true, 'error_code' => $code, 'msg' => $body), 400, $response);
}
/* Handle new user */
$app->post('/user/new', function ($request, $response) {
    $data = parseJsonBody($request);
    return Users::create($response, $data);
});
/* Handle authenticate user */
$app->post('/user/me', function ($request, $response) {
    $data = parseJsonBody($request);
    return Users::auth($response, $data);
});
/* Handle delete current user */
$app->delete('/user/me', function ($request, $response) {
    $token = parseToken($request);
    return Users::delete($response, $token);
});
/* Handle get user info */
$app->get('/user/{id:[0-9]+}/info', function ($request, $response, $args) {
    $token = parseToken($request);
    $friend_id = $args['id'];
Exemplo n.º 29
0
# IMPORT
require __DIR__ . "/vendor/autoload.php";
use KarabowId\Api\Orm\OrmManager;
use KarabowId\Api\ParamHandler;
use KarabowId\Api\Messages;
# SETUP
$configuration = ['settings' => ['displayErrorDetails' => true]];
$config = new \Slim\Container($configuration);
$app = new Slim\App($config);
$ormManager = new OrmManager();
$app->any("/", function ($request, $response, $args) {
    $reponse->getBody()->write("No Request Made. Should we throw an exception? or just tell the user to go learn how to consume this api?");
});
# CREATE NEW USER
$app->post("/user/new", function ($request, $response, $args) use($app) {
    return $response;
});
# GET USER INFO
$app->get("/user", function ($request, $response, $args) use($app) {
    return $response;
});
# MODIFY USER INFO
$app->put("/user/edit", function ($request, $response, $args) use($app) {
    return $response;
});
# DELETE USER FROM DB
$app->delete("/user/delete", function ($request, $response, $args) use($app) {
    return $response;
});
# RUN
$app->run();
Exemplo n.º 30
0
/* Require Slim and NotORM */
require 'vendor/autoload.php';
$app = new \Slim\App();
/* Database Configuration */
$dbhost = 'localhost';
$dbuser = '******';
$dbpass = '******';
$dbname = 'car_park';
$dbmethod = 'mysql:dbname=';
$dsn = $dbmethod . $dbname;
$pdo = new PDO($dsn, $dbuser, $dbpass);
$db = new NotORM($pdo);
$app->post('/car', function ($req, $res, $args) use($db) {
    $car = $req->getParsedBody();
    $result = $db->cars->insert($car);
    return $res->write($result['id']);
});
$app->get('/cars', function ($req, $res, $args) use($db) {
    $cars = array();
    foreach ($db->cars() as $car) {
        $cars[] = array('number' => $car['number'], 'region' => $car['region'], 'ticket' => $car['ticket']);
    }
    return $res->withHeader('Content-Type', 'application/json')->write(json_encode($cars));
});
$app->delete('/car/{num}/{region}', function ($req, $res, $args) use($db) {
    $num = $args['num'];
    $region = $args['region'];
    $car = $db->cars()->where(array("number" => $num, "region" => $region));
    if ($car->fetch()) {
        $result = $car->delete();