Exemplo n.º 1
0
    if ($givenAwayValidator($requestBody) == false) {
        return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
    }
    try {
        $library->giveAwayBookInReservation($reservationId, new \DateTime($requestBody['givenAwayAt']));
    } catch (BookInReservationAlreadyGivenAway $e) {
        return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
    }
    return $response->withHeader('Content-Type', 'application/json')->withStatus(200);
});
//Give back book from reservation
$app->delete('/reservations/{reservationId}', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app, $reservationDataValidator) {
    $reservationId = Uuid::fromString($args['reservationId']);
    try {
        $library->giveBackBookFromReservation($reservationId);
    } catch (CannotGiveBackReservationWhichWasNotGivenAway $e) {
        return $response->withHeader('Content-Type', 'application/json')->withStatus(400);
    }
    return $response->withStatus(204);
});
//List reservations for book
$app->get('/reservations', function (ServerRequestInterface $request, ResponseInterface $response, $args = []) use($library, $app, $reservationDataValidator) {
    $query = $request->getQueryParams();
    if (!isset($query['bookId'])) {
        $responseBody = $response->getBody();
        $responseBody->write(json_encode([]));
        return $response->withHeader('Content-Type', 'application/json')->withStatus(200)->withBody($responseBody);
    }
    $bookId = Uuid::fromString($query['bookId']);
    $responseBody = $response->getBody();
    $responseBody->write(json_encode($library->listReservationsForBook($bookId)));
Exemplo n.º 2
0
        return $response->withStatus(500)->withHeader('Location', '/slimapi/index.php/beards');
    }
});
// Create action .json
$app->post('/beards.json', function ($request, $response) {
    $body = $request->getParsedBody();
    // $_POST associative array
    $beardDb = new Beard();
    $beard = $beardDb->createBeard($body);
    return renderJSON($response, 201, $beard);
});
// Create action
$app->post('/beards', function ($request, $response) {
    $body = $request->getParsedBody();
    // $_POST associative array
    $beardDb = new Beard();
    $beardDb->createBeard($body);
    return $response->withStatus(302)->withHeader('Location', '/slimapi/index.php/beards');
});
$app->delete('/beards/{id}', function ($request, $response, $args) {
    $id = $args['id'];
    $beardDB = new Beard();
    $beard = $beardDB->deleteBeard($id);
    if ($beard) {
        return $response->withStatus(302)->withHeader('Location', '/slimapi/index.php/beards');
    } else {
        return $response->withStatus(500)->withHeader('Location', '/slimapi/index.php/beards');
    }
});
// Run app
$app->run();
Exemplo n.º 3
0
    $stmt->bindValue(':place', $meeting['place']);
    $stmt->bindValue(':meeting_nr', $meeting['meeting_nr']);
    $stmt->bindValue(':category', $meeting['category']);
    $stmt->bindValue(':stadium', $meeting['stadium']);
    $stmt->bindValue(':time_measurement', $meeting['time_measurement']);
    $stmt->execute();
    $response->getBody()->write(json_encode($meeting));
    return $response;
});
$app->delete('/meeting/{id}', function ($request, $response, $args) {
    $db = $this->dbConnection;
    $sql = "DELETE FROM meeting_information WHERE meeting_id=:meeting_id limit 1;";
    // TODO constraints to delete everything from db
    $stmt = $db->prepare($sql);
    $stmt->bindValue(":meeting_id", $args['id'], PDO::PARAM_INT);
    $stmt->execute();
    if (!$stmt->rowCount()) {
        $response->getBody()->write(json_encode(array('error' => 'Kein Wettkampf gefunden.')));
        $response->withStatus(400);
    }
    return $response;
});
/***********************************************************************************************************************
*************************************************** Competitions *******************************************************
***********************************************************************************************************************/
$app->get('/competitions/', function ($request, $response, $args) {
    $db = $this->dbConnection;
    $stmt = $db->prepare('SELECT * FROM competition WHERE meeting_id=:id;');
    // todo join with competition_participants
    $stmt->bindValue(':id', $this->meetingId, PDO::PARAM_INT);
    if ($stmt->execute()) {
Exemplo n.º 4
0
    if ($idCity = getId($args['idCity'], 'cities')) {
        $post = $request->getParsedBody();
        $name = clearStr($post['Name']);
        $id = insertItem('languages', $name);
        if (bindItems('clanguages', 'Id_City', 'Id_Language', $idCity['id'], $id)) {
            return $response->withJson(array("id" => $id));
        }
    }
    return $response->withJson(array('status' => 0, 'message' => "Failed to insert city"));
});
/* Delete country by Id */
$app->delete("/country/{id}/", function ($request, $response, $args) use($link) {
    $id = getId($args['id'], 'countries');
    if ($id) {
        deleteId($id['id'], 'ccities', 'Id_Country', 'i');
        deleteId($id['id'], 'countries', 'Id', 'i');
        return $response->withJson(array('status' => 1, 'message' => "Country deleted sucsesfully"));
    } else {
        return $response->withJson(array('status' => 0, 'message' => "Country ID {$args['id']} does not exists"));
    }
});
/* Delete city by Id */
$app->delete("/city/{id}/", function ($request, $response, $args) use($link) {
    $id = getId($args['id'], 'cities');
    if ($id) {
        deleteId($id['id'], 'ccities', 'Id_City', 'i');
        deleteId($id['id'], 'clanguages', 'Id_City', 'i');
        deleteId($id['id'], 'cities', 'Id', 'i');
        return $response->withJson(array('status' => 1, 'message' => "City deleted sucsesfully"));
    } else {
        return $response->withJson(array('status' => 0, 'message' => "City ID {$args['id']} does not exists"));
    }
Exemplo n.º 5
0
});
$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"]]);
    $todo->data($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(200)->withHeader("Content-Type", "application/json")->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
$app->delete("/todos/{uid}", function ($request, $response, $arguments) {
    $todo = $this->spot->mapper("App\\Todo")->first(["uid" => $arguments["uid"]]);
    $this->spot->mapper("App\\Todo")->delete($todo);
    return $response->withStatus(204)->withHeader("Content-Type", "application/json")->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
/* In real life this this is probably a bad idea. */
$app->delete("/todos", function ($request, $response, $arguments) {
    $this->spot->mapper("App\\Todo")->delete();
    return $response->withStatus(204);
});
$app->run();
Exemplo n.º 6
0
$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();
        $responseBody = json_encode(array("status" => true, "message" => "Car deleted successfully."));
    } else {
        $responseBody = json_encode(array("status" => false, "message" => "Car with {$num} number and {$region} region does not exist."));
    }
    return $res->withHeader('Content-Type', 'application/json')->write($responseBody);
});
/* Run the application */
$app->run();
Exemplo n.º 7
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.º 8
0
/**
 * Created by PhpStorm.
 * User: moribus
 * Date: 04/01/2016
 * Time: 19:02
 */
require_once __DIR__ . '/autoload.php';
// Chargement automatique des classes Ousse
require_once 'vendor/autoload.php';
// Chargement automatique des classes provenant des dépendances (Slim, Doctrine, ..)
require_once __DIR__ . '/bootstrap.php';
// Inclusion de $entityManager pour manipuler les entités
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$container = new \Ousse\WebService\DefaultContainer();
$app = new Slim\App($container);
$app->add(new \Ousse\WebService\Middleware\AuthService($entityManager));
$app->get("/{entite}/where/{whereParams:.*}/equals/{equalsParams:.*}", new \Ousse\WebService\Middleware\EntitesGetService($entityManager));
$app->get('/ping', new \Ousse\WebService\Middleware\PingService());
$app->post('/check_auth', new Ousse\WebService\Middleware\AuthCheckService());
$app->get('/parametres/{banque}', new \Ousse\WebService\Middleware\ParamsService($entityManager));
$app->post('/silos', new \Ousse\WebService\Middleware\SiloPostService($entityManager));
$app->get('/silos/{id}', new \Ousse\WebService\Middleware\SiloGetService($entityManager));
$app->get('/silos/{id}/coffres', new \Ousse\WebService\Middleware\CoffresGetAllService($entityManager));
$app->get('/items/{id}/{data}', new \Ousse\WebService\Middleware\ItemGetService($entityManager));
$app->get('/coffres/{x}/{y}/{z}', new \Ousse\WebService\Middleware\CoffreGetService($entityManager));
$app->get('/coffres/{x}/{y}/{z}/stacks', new \Ousse\WebService\Middleware\ItemStackGetAllService($entityManager));
$app->delete('/banque/{nom}', new \Ousse\WebService\Middleware\BanqueResetService($entityManager));
$app->run();
Exemplo n.º 9
0
        $stmt->bindParam("name", $parsedBody['name']);
        $stmt->bindParam("description", $parsedBody['description']);
        $stmt->bindParam("url", $parsedBody['url']);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        $jsonResponse = $response->withHeader('Content-type', 'application/json');
        $jsonResponse->getBody()->write(true);
        return $jsonResponse;
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});
$app->delete('/v1/bookmarks/{delete_id}', function (Request $request, Response $response) {
    $sql = "DELETE FROM bookmarks WHERE id=:id";
    try {
        $delete_id = $request->getAttribute('delete_id');
        $db = getDB();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("id", $delete_id);
        $stmt->execute();
        $db = null;
        $jsonResponse = $response->withHeader('Content-type', 'application/json');
        $jsonResponse->getBody()->write($delete_id);
        return $jsonResponse;
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});
init_db();
$app->run();
Exemplo n.º 10
0
//routes
$app->get('/user/', function ($request, $response, $args) {
    echo 'list<br>';
    $controller = new LoginController();
    $logins = $controller->getList();
    print_r($logins);
});
$app->get('/user/{id}', function ($request, $response, $args) {
    echo 'one<br>';
    $controller = new LoginController();
    $login = $controller->getLogin($args['id']);
    print_r($login);
});
$app->put('/user/', function ($request, $response, $args) {
    $l = $request->getParsedBody()['login'];
    $controller = new LoginController();
    $resp = $controller->addLogin($l);
    print_r($resp);
});
$app->post('/user/', function ($request, $response, $args) {
    $l = $request->getParsedBody()['login'];
    $controller = new LoginController();
    $resp = $controller->editLogin($l);
    print_r($resp);
});
$app->delete('/user/{id}', function ($request, $response, $args) {
    $controller = new LoginController();
    $resp = $controller->removeLogin($args['id']);
    print_r($resp);
});
$app->run();
Exemplo n.º 11
0
    //Retourne l'annonce demandée
    $app->get('/{id}', function ($req, $res, $args) use($app) {
        $id = $args['id'];
        $controller = new Controller\AnnonceController($req, $res, $app);
        return $controller->getAnnonceById($id);
    });
    //Retourne la catégorie de l'annonce demandée
    $app->get('/{id}/categorie', function ($req, $res, $args) use($app) {
        $id = $args['id'];
        $controller = new Controller\CategorieController($req, $res, $app);
        return $controller->getCategorieByAnnonce($id);
    });
    //Supprime une annonce
    $app->delete('/{id}', function ($req, $res, $args) use($app) {
        $id = $args['id'];
        $controller = new Controller\AnnonceController($req, $res, $app);
        return $controller->deleteAnnonceById($id);
    });
    //Retourne les coordonnées de l'annonceur sur l'annonce demandée
    $app->get('/{id}/annonceur', function ($req, $res, $args) use($app) {
        $id = $args['id'];
        $controller = new Controller\AnnonceController($req, $res, $app);
        return $controller->getAnnonceur($id);
    });
    //Création d'une annonce
    $app->post('', function ($req, $res) use($app) {
        $createdannounce = new Controller\AnnonceController($req, $res, $app);
        return $createdannounce->postAnnonce();
    });
});
$app->run();
Exemplo n.º 12
0
        return respond($response, false, 'Must supply valid access_token');
    }
    $id = $request->getAttribute('id');
    $media = Pepys\Media::where('id', '=', $id)->first();
    try {
        populateModelFromRequest($media, $request);
    } catch (Exception $e) {
        return respond($response, false, $e->getMessage());
    }
    return respond($response, true);
});
$app->delete('/media/{id}', function (Request $request, Response $response) {
    if (!hasValidAccessToken($request)) {
        return respond($response, false, 'Must supply valid access_token');
    }
    $id = $request->getAttribute('id');
    $media = Pepys\Media::where('id', '=', $id)->first();
    $media->delete();
    return respond($response, true);
});
/**** ACTIVITY ****/
$app->get('/activities', function (Request $request, Response $response) {
    $activities = Pepys\Activity::with('media', 'media.type')->orderBy('date', 'asc')->orderBy('order', 'asc')->get();
    return respond($response, true, array('activities' => $activities->toArray()));
});
$app->get('/activities/{id}', function (Request $request, Response $response) {
    $id = $request->getAttribute('id');
    $activity = Pepys\Activity::with('media', 'media.type')->where('id', '=', $id)->first();
    return respond($response, true, array('activity' => $activity->toArray()));
});
$app->post('/activities', function (Request $request, Response $response) {
Exemplo n.º 13
0
    $newContact = $request->getParsedBody();
    $contact = new Contact();
    $contact->name = $newContact['name'];
    $contact->email = $newContact['email'];
    $contact->number = $newContact['number'];
    $contact->save();
    return $response;
});
$app->get('/contacts', function ($request, $response, $args) {
    $response->withJson(Contact::all());
    return $response;
});
$app->get('/contacts/{id}', function ($request, $response, $args) {
    $contact = Contact::find($args['id']);
    $response->write($contact->toJson());
    return $response;
});
$app->put('/contacts/{id}', function ($request, $response, $args) {
    $editedContact = $request->getParsedBody();
    $contact = Contact::find($args['id']);
    $contact->name = $editedContact['name'];
    $contact->email = $editedContact['email'];
    $contact->number = $editedContact['number'];
    $contact->save();
    return $response;
});
$app->delete('/contacts/{id}', function ($request, $response, $args) {
    Contact::delete($args['id']);
    return $response;
});
$app->run();
Exemplo n.º 14
0
require './vendor/autoload.php';
use RedBeanPHP\R;
R::setup('sqlite:smplog.db');
$app = new Slim\App();
require 'app-setup.php';
Auth::CreateInitialAdmin($container);
Auth::CreateJwtKey();
$app->post('/admin/login', 'Auth:login');
$app->post('/admin/logout', 'Auth:logout');
$app->post('/admin/authenticate', 'Auth:authenticate');
$app->get('/admin/authors', 'Admin:getAuthors');
$app->post('/admin/authors', 'Admin:addAuthor');
$app->get('/admin/authors/{id}', 'Admin:getAuthor');
$app->post('/admin/authors/{id}', 'Admin:updateAuthor');
$app->delete('/admin/authors/{id}', 'Admin:removeAuthor');
$app->post('/admin/details', 'Admin:updateDetails');
$app->get('/admin/posts', 'Admin:getPosts');
// (by requesting author/user)
$app->post('/admin/posts', 'Admin:addPost');
$app->post('/admin/posts/{id}', 'Admin:updatePost');
$app->delete('/admin/posts/{id}', 'Admin:removePost');
$app->post('/admin/posts/{id}/publish', 'Admin:publishPost');
$app->post('/admin/posts/{id}/unpublish', 'Admin:unpublishPost');
$app->get('/details', 'Details:getDetails');
$app->get('/posts', 'Posts:getPosts');
$app->get('/posts/{slug}', 'Posts:getPost');
$app->get('/authors', 'Authors:getAuthors');
$app->get('/authors/{id}', 'Authors:getAuthor');
$app->get('/authors/{id}/posts', 'Authors:getPosts');
$app->run();
Exemplo n.º 15
0
        //IF 404 - 500
    } catch (ResourceNotFoundException $e) {
        echo "404";
    } catch (Exception $e) {
        echo "400";
    }
});
/**     Function DeleteWine - DELETE   **/
$app->delete('/{id}', function (Request $request, Response $response) {
    $id = false;
    try {
        //Recup data
        $id = $request->getAttribute('id');
        $idWine = (int) $id;
        //Load the wine by id
        $wineToDelete = R::load('wine', $idWine);
        //Delete in the database
        $id = R::trash($wineToDelete);
        if ($id !== false) {
            echo "valid";
        } else {
            echo "unvalid";
        }
        //IF 404 - 500
    } catch (ResourceNotFoundException $e) {
        echo "404";
    } catch (Exception $e) {
        echo "400";
    }
});
$app->run();
Exemplo n.º 16
0
        return $response;
    } else {
        $response->write("Test Player cannot be updated. Please insert another RA.");
        return $response;
    }
});
// delete User
$app->delete('/users/{ra}', function ($request, $response, $args) use($db) {
    if ($args['ra'] != 0) {
        // Remove user from castle
        $qry = "UPDATE castle_owners SET user_ra = 0 WHERE user_ra = " . $args['ra'];
        $db->run($qry, 0);
        // Delete user query
        $qry = "DELETE FROM user WHERE `user_ra` = " . $args['ra'];
        $db->run($qry, 0);
        // return id data to client
        $qry = "SELECT * FROM user WHERE user_ra = " . $args['ra'];
        $output = $db->run($qry, 1);
        $response->write($output);
    } else {
        $response->write("Test Player cannot be deleted. Please insert another RA.");
        return $response;
    }
});
//Selecting Castles
$app->get('/castles/', function ($request, $response, $args) use($db) {
    // return all users data to client query
    $qry = "SELECT * FROM castle_owners";
    $output = $db->run($qry, 1);
    $response->write($output);
    return $response;
Exemplo n.º 17
0
{
    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'];
    return UsersInfo::get($response, $token, $friend_id);
});
/* Handle get my info */
$app->get('/user/me/info', function ($request, $response) {
    $token = parseToken($request);
    return UsersInfo::get($response, $token, null);
});
/* Handle update my info */
$app->put('/user/me/info', function ($request, $response) {
    $token = parseToken($request);
Exemplo n.º 18
0
							year=:year, 
							description=:description 
							WHERE id=:id');
    $resultat = $stmt->execute(array(':name' => strtoupper($_REQUEST['name']), ':grapes' => $_REQUEST['grapes'], ':country' => $_REQUEST['country'], ':region' => $_REQUEST['region'], ':year' => $_REQUEST['year'], ':description' => $_REQUEST['description'], ':id' => $args['id']));
    // Si la modification s'est bien passée, on retourne un message de réussite
    if ($resultat !== false) {
        return json_encode(['reponse' => 'Le vin a bien été modifié']);
    }
});
// Supprime le vin dont on possède l'id
$app->delete('/api/wines/{id}', function (Request $request, Response $response, $args) {
    // Connection à la DB
    $pdo = database();
    // On tente de supprimer dans la DB le vin dont on possède l'id
    $stmt = $pdo->prepare('DELETE FROM wine WHERE id = :id');
    $resultat = $stmt->execute(array(':id' => $args['id']));
    // Si la suppression s'est bien passée, on retourne un message de réussite
    if ($resultat !== false) {
        return json_encode(['reponse' => 'Le vin a bien été supprimé']);
    }
});
// Fonction permettant de se connecter à la DB
function database()
{
    try {
        return new PDO('mysql:host=localhost;dbname=cavavin', 'root', 'root');
    } catch (PDOException $e) {
        die('Erreur de connection à la base de données !');
    }
}
$app->run();
Exemplo n.º 19
0
        return $response->withJson($formatter->getSuccess($resource->put($id)));
    } catch (StatusException $e) {
        return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode());
    } catch (Exception $e) {
        return $response->withStatus(500);
    }
});
// Delete
$app->delete('/{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);
        $resource->delete();
        return $response->withJson($formatter->getSuccess());
    } catch (StatusException $e) {
        return $response->withJson($formatter->getFailure($e->getMessage()), $e->getCode());
    } catch (Exception $e) {
        return $response->withStatus(500);
    }
});
// Options
$app->options('/{resource}', function (ServerRequestInterface $request, Response $response, $resource, $id = null) {
    try {
        $resource = AbstractResource::load($resource, $request, $response, $this);
        return $resource->options();
    } catch (StatusException $e) {
        return $response->withStatus($e->getCode());
    }
Exemplo n.º 20
0
    } else {
        echo json_encode(false);
    }
});
$app->delete('/users/{id}', function ($request, $response, $args) {
    $server_params = $request->getServerParams();
    if (preg_match("/Basic\\s+(.*)\$/i", $server_params["REDIRECT_HTTP_AUTHORIZATION"], $matches)) {
        list($user, $password) = explode(":", base64_decode($matches[1]));
    }
    if ($args['id'] == $user) {
        $user = User::getUserByMtrklNr($args['id']);
        $groups = User::getAllGroupsOfUser($args['id']);
        foreach ($groups as $group) {
            $group->removeMember($user);
            if (empty($group->users)) {
                Group::deleteGroupById($group->id);
            }
            if ($group->owner == $args['id']) {
                $group->owner = $group->users[0];
            }
        }
        $deleted = User::deleteUserByMtrklNr($args['id']);
        echo json_encode($deleted);
    } else {
        echo json_encode(false);
    }
});
$app->get('/users/{id}/groups', function ($request, $response, $args) {
    $server_params = $request->getServerParams();
    if (preg_match("/Basic\\s+(.*)\$/i", $server_params["REDIRECT_HTTP_AUTHORIZATION"], $matches)) {
        list($user, $password) = explode(":", base64_decode($matches[1]));
Exemplo n.º 21
0
$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);
$app->post('/user/forgetpwd', function ($request, $response, $args) {
    $member = new \Models\Member();
    $response->write($member->forgetPwd($request->getParsedBody()));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
});
$app->post('/group', function ($request, $response, $args) {
    $group = new \Models\Group();
    //error_log( print_r($request->getParsedBody(), 1));
    $response->write($group->addNewGroup($request->getParsedBody(), \Middleware\Authenticate::$requestUid));
    $newResponse = $response->withHeader('Content-type', 'application/json');
    return $newResponse;
})->add($auth);
Exemplo n.º 22
0
});
*/
$app->get('/servicios', 'getServicios');
$app->get('/servicios/{id}', function (Request $req, Response $res) {
    $id = $req->getAttribute('id');
    $rs_data = getServicio($id);
    if ($rs_data === false) {
        return $res->withStatus(400)->withHeader('Content-Type', 'application/json')->write(json_encode(responseHandler(400, 'ERR_DATABASE', 'Error al consultar la base de datos.')));
    } else {
        return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(responseHandler(200, '', '', getServicio($id))));
    }
});
$app->get('/servicios/search/:query', 'findServicioByName');
$app->post('/servicios', 'addServicio');
$app->put('/servicios/:id', 'updateServicio');
$app->delete('/servicios/:id', 'deleteServicio');
$app->post('/datos', function (Request $req, Response $res, $args = []) {
    $args = $req->getParsedBody();
    //var_dump($args);
    //echo $args['usr'];
    /*
    return $res->withHeader(
            'Content-Type',
            'application/json'
        );
    */
    //$cnxn = getCnxn();
    //var_dump($cnxn);
    return $res->withStatus(200)->withHeader('Content-Type', 'application/json')->write(json_encode(array("success" => 1, "data" => $args)));
});
$app->get('/orm', function () {
Exemplo n.º 23
0
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $response->getBody()->write(json_encode($input));
    } catch (PDOException $e) {
        $response->getBody()->write('{"error":' . $e->getMessage() . '}');
        die;
    }
    return $response;
});
$app->delete('/api/wines/{id}', function (Request $request, Response $response, $args) {
    $id = $args['id'];
    try {
        $db = thisConnection();
        $stmt = $db->prepare("DELETE FROM wine WHERE id=:id");
        $stmt->bindParam("id", $id);
        $lignes = $stmt->execute();
        $response->getBody()->write($lignes . ' ligne(s) supprimée(s)');
    } catch (PDOException $e) {
        $response->getBody()->write('{"error":' . $e->getMessage() . '}');
        die;
    }
    return $response;
});
$app->run();
function thisConnection()
{
    $dbhost = "localhost";
    $dbuser = "******";
    $dbmdp = "";
    $dbname = "cavavin";
    $connection = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbmdp);
    return $connection;
Exemplo n.º 24
0
        if ($rows) {
            $response->withStatus(200)->withHeader('Content-Type', 'application/json; charset=UTF-8')->write(json_encode($rows));
            $db = null;
        } else {
            throw new PDOException('No records found.');
        }
    } catch (PDOException $e) {
        $response->withStatus(404)->write('{"error":{"text":' . $e->getMessage() . '}}');
    }
});
$app->delete('/produtos/:id', function ($id) {
    $sql = "DELETE FROM produtos WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
});
//$app->contentType('text/html; charset=utf-8'); //ainda não consegui fazer funcionar
$app->run();
function getConnection()
{
    $dbhost = getenv('IP');
    $dbuser = "******";
    $dbpass = "";
    $dbname = "smpd";
    $dbh = new PDO("mysql:host={$dbhost};dbname={$dbname}", $dbuser, $dbpass);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Exemplo n.º 25
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.º 26
0
                </p>
                <p><a href="https://github.com/codeguy/Slim-Extras" target="_blank">Browse the Extras Repository</a></p>
            </section>
        </body>
    </html>
EOT;
    echo $template;
});
// POST route
$app->post('/post', function () {
    echo 'This is a POST route';
});
// PUT route
$app->put('/put', function () {
    echo 'This is a PUT route';
});
// PATCH route
$app->patch('/patch', function () {
    echo 'This is a PATCH route';
});
// DELETE route
$app->delete('/delete', function () {
    echo 'This is a DELETE route';
});
/**
 * Step 4: Run the Slim application
 *
 * This method should be called last. This executes the Slim application
 * and returns the HTTP response to the HTTP client.
 */
$app->run();