Example #1
1
$app->post('/contact', function () use($app) {
    $name = $app->request->post('name');
    $email = $app->request->post('email');
    $msg = $app->request->post('msg');
    if (!empty($name) && !empty($email) && !empty($msg)) {
        $cleanName = filter_var($name, FILTER_SANITIZE_STRING);
        $cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
        $cleanMsg = filter_var($msg, FILTER_SANITIZE_STRING);
    } else {
        //message the user that there's a problem
        $app->flash('fail', 'All fields are required.');
        $app->redirect('/contact');
    }
    $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -t');
    $mailer = \Swift_Mailer::newInstance($transport);
    $message = \Swift_Message::newInstance();
    $message->setSubject('Email From Our Website');
    //http://swiftmailer.org/docs/messages.html
    $message->setFrom(array($cleanEmail => $cleanName));
    //if server accepts this email
    $message->setTo(array('*****@*****.**'));
    $message->setBody($cleanMsg);
    $result = $mailer->send($message);
    if ($result > 0) {
        $app->flash('success', 'Thank You! You da best!');
        $app->redirect("/");
    } else {
        $app->flash('fail', 'Something went wrong! Sorry, please try again later.');
        $app->redirect('/contact');
        $log = new Logger('name');
        $log->pushHandler(new StreamHandler('app.txt', Logger::WARNING));
        $log->addWarning('There was a problem with contact us submission');
    }
});
 /**
  * @param SlimWebServiceRegistryCategory $category
  */
 public function AddCategory(SlimWebServiceRegistryCategory $category)
 {
     foreach ($category->Gets() as $registration) {
         $this->slim->get($registration->Route(), $registration->Callback())->name($registration->RouteName());
         $this->SecureRegistration($registration);
     }
     foreach ($category->Posts() as $registration) {
         $this->slim->post($registration->Route(), $registration->Callback())->name($registration->RouteName());
         $this->SecureRegistration($registration);
     }
     foreach ($category->Deletes() as $registration) {
         $this->slim->delete($registration->Route(), $registration->Callback())->name($registration->RouteName());
         $this->SecureRegistration($registration);
     }
     $this->categories[] = $category;
 }
 /**
  * Verify basic behavior of __invoke()
  *
  * @test
  * @covers ::__invoke
  *
  * @return void
  */
 public function invoke()
 {
     $storage = new \OAuth2\Storage\Memory(['client_credentials' => ['testClientId' => ['client_id' => 'testClientId', 'client_secret' => 'testClientSecret']]]);
     $server = new \OAuth2\Server($storage, ['access_lifetime' => 3600], [new \OAuth2\GrantType\ClientCredentials($storage)]);
     $json = json_encode(['client_id' => 'testClientId', 'client_secret' => 'testClientSecret', 'grant_type' => 'client_credentials']);
     \Slim\Environment::mock(['REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json', 'PATH_INFO' => '/token', 'CONTENT_LENGTH' => strlen($json), 'slim.input' => $json]);
     $slim = new \Slim\Slim();
     $slim->post('/token', new Token($slim, $server));
     ob_start();
     $slim->run();
     ob_get_clean();
     $this->assertSame(200, $slim->response->status());
     $actual = json_decode($slim->response->getBody(), true);
     $this->assertSame(['access_token' => $actual['access_token'], 'expires_in' => 3600, 'token_type' => 'Bearer', 'scope' => null], $actual);
 }
    /**
     * Verify basic behavior of __invoke()
     *
     * @test
     * @covers ::__invoke
     *
     * @return void
     */
    public function invoke()
    {
        $storage = new \OAuth2\Storage\Memory(['client_credentials' => ['testClientId' => ['client_id' => 'testClientId', 'client_secret' => 'testClientSecret', 'redirect_uri' => '/receive-code']]]);
        $server = new \OAuth2\Server($storage, ['access_lifetime' => 3600], [new \OAuth2\GrantType\ClientCredentials($storage)]);
        $code = md5(time());
        \Slim\Environment::mock(['REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/json', 'PATH_INFO' => '/receive-code', 'QUERY_STRING' => "code={$code}&state=xyz"]);
        $slim = new \Slim\Slim();
        $slim->post('/receive-code', new ReceiveCode($slim));
        ob_start();
        $slim->run();
        ob_get_clean();
        $this->assertSame(200, $slim->response->status());
        $expected = <<<HTML
<h2>The authorization code is {$code}</h2>

HTML;
        $this->assertSame($expected, $slim->response->getBody());
    }
Example #5
0
 private function runAppPost($action, $actionName, $mw = NULL, $headers = array())
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'POST', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => 80, 'ACCEPT' => 'application/json', 'SCRIPT_NAME' => '/index.php', 'PATH_INFO' => '/' . $actionName));
     $app = new \Slim\Slim();
     if (isset($mw)) {
         $app->add($mw);
     }
     $app->post('/:name', function ($name) use($app, $action) {
         if ($app->request->isHead()) {
             $app->status(204);
             return;
         }
         $app->contentType('application/json');
         $app->response->write(json_encode(array("action" => $action, "method" => "POST", "name" => $name)));
     });
     foreach ($headers as $key => $value) {
         $app->request->headers()->set($key, $value);
     }
     $app->run();
     $this->validate($app, 'POST', $action, $actionName);
     return $app;
 }
Example #6
0
}
/*Slim*/
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
//instantiate slim app (might need to provide arguments)
$app = new \Slim\Slim();
$app->get('/', function () {
    echo "error";
});
$app->get('/getkey/:name', function ($name) {
    echo "" . getKey($name);
});
$app->post('/', function () use($app) {
    $json = $app->request->getBody();
    $creds = json_decode($json, true);
    $username = $creds["username"];
    $password = decrypt(getKey($username), $creds["password"]);
    //echo $creds["password"]." --> $password";
    if (comparePassword($username, $password)) {
        //password is valid
        $sessionID = createSession($username);
        $acceptedPage = "<img src=\"success.jpg\" \n    \t\t\tclass=\"img-circle img-responsive center-block\" width=\"300\"></br>\n    \t\t <h2 class=\"text-center\">Hi there {$username}! Wonderful to see you again!</h2></br></br></br>\n    \t\t <form action=\"logout.php\" method=\"post\"> \n    \t\t \t<input type=\"hidden\" name=\"sessionid\" value=\"{$sessionID}\">\n\t\t\t\t<button class=\"btn btn-lg btn-warning center-block\" type=\"submit\">Log out</button>\n\t\t\t </form>\n    \t\t";
        echo $acceptedPage;
    } else {
        $refusedPage = "<img src=\"fail.jpg\" \n    \t\tclass=\"img-circle img-responsive center-block\"></br>\n    \t\t <h2 class=\"text-center\">Unfortunately your credentials were <b>wrong</b>! Don't be sad, just try again!</h2></br></br></br>\n    \t\t <form action=\"login.html\"> \n\t\t\t\t<button class=\"btn btn-lg btn-primary center-block\" type=\"submit\">Return to login page</button>\n\t\t\t </form>\n    \t\t";
        echo $refusedPage;
    }
});
$app->run();
//close db connection
$conn->close();
Example #7
0
$app->post('/people/:personid', function ($personid) use($app, $person) {
    if (!$person->ContactAdmin) {
        $response['error'] = true;
        $response['errorcode'] = 400;
        $response['message'] = __("Insufficient privilege level");
        echoResponse(200, $response);
        $app->stop();
    }
    $response = array();
    $p = new People();
    $p->PersonID = $personid;
    if (!$p->GetPerson()) {
        $response['error'] = true;
        $response['errorcode'] = 404;
        $response['message'] = __("User not found in database.");
        echoResponse(200, $response);
    } else {
        // Slim Framework will simply return null for any variables that were not passed, so this is safe to call without blowing up the script
        foreach ($p as $prop) {
            $p->{$prop} = $app->request->post($prop);
        }
        $p->Disabled = false;
        if (!$p->UpdatePerson()) {
            $response['error'] = true;
            $response['errorcode'] = 403;
            $response['message'] = __("Unable to update People resource with the given parameters.");
            echoResponse(200, $response);
        } else {
            $response['error'] = false;
            $response['errorcode'] = 200;
            $response['message'] = sprintf(__('People resource for UserID=%1$s updated successfully.'), $p->UserID);
            $response['people'] = $p;
            echoResponse(200, $response);
        }
    }
});
Example #8
0
    }
    return true;
}
$app->group('/', function () use($app, $dbsettings) {
    $username = $app->request()->headers('PHP_AUTH_USER');
    $password = $app->request()->headers('PHP_AUTH_PW');
    if ($username != $dbsettings->dbuser || $password != $dbsettings->dbpass) {
        $app->response()->status(401);
        $app->response()->header('WWW-Authenticate', sprintf('Basic realm="%s"', 'Protected Area'));
        return;
    }
    $app->get('/', function () use($app) {
        $app->render('app.html');
    });
    $app->post('procparams', function () use($app) {
        $entry = json_decode($app->request()->getBody());
        echo getInputParams($entry);
    });
    $app->get('api', function () use($app) {
        $app->render('../../api/api.json');
    });
    $app->post('api', function () use($app) {
        $json = $app->request()->getBody();
        $data = json_decode($json);
        // TODO: CHECK INPUT FOR VALIDITY
        // GENERATE SQL CODE FOR PROCEDURES
        $mysqli = getConnection_mysqli();
        // Set the procedures according to the existing API when an error occurs
        if (!createProcedures($mysqli, $data)) {
            if (file_exists("../api/api.json")) {
                $api = json_decode(file_get_contents("../api/api.json"));
                createProcedures($mysqli, $api);
Example #9
0
<?php 
require 'vendor/autoload.php';
require 'helpers_bp.php';
$app = new \Slim\Slim();
$app->config(array('debug' => true, 'mode' => 'development'));
$app->post('/add_voter', function () use($app) {
    //$userid = $app->request->post('userid');
    $token = $app->request->post('token');
    //Facebook access token
    $userid = id_by_token($token);
    if (!is_null($userid)) {
        //Stores the new validation number and associates with user ID
        //Returns NULL if user id already there
        $random_number = genValidationNumberAndStore($userid);
        if (!is_null($random_number)) {
            $ret = array('success' => true, 'message' => "{$random_number}");
            echo json_encode($ret);
            return json_encode($ret);
        }
    }
    //Else the token was bad, couldn't retrieve user ID
    //OR the user has already requested a validation number in past
    //Perhaps return the same validation number?
    $ret = array('success' => false, 'message' => 'Bad token or user already requested validation number.');
    echo json_encode($ret);
});
$app->post('/vote', function () use($app) {
    $validation_num = $app->request->post('validnum');
    // Validation number given to user
    $userid = $app->request->post('userspecifiedid');
    //User-specified id
Example #10
0
<?php

//http://localhost/apilatihan/index.php/laptop <-(simpan bagian ini di rest essay lalu pilih body dan type POST)
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
//hit parent URL
$app->get("/", function () {
    echo "<h1>Tugas UAS Egi Permana 1342840</h1>";
});
// GET route
$app->get('/laptop', function () {
});
//post data laptop
$app->post('/laptop', function () {
    $laptop = new \Uas\laptop();
    $laptop->tambahLaptop($_POST['brand'], $_POST['model'], $_POST['thn_keluar']);
});
// 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';
});
// GET route kategori
$app->get('/kategori', function () {
Example #11
0
<?php

require_once '../../include/DbHandlers/UserDbHandler.php';
require_once '../../include/DbHandlers/MaterialDbHandler.php';
require '../../libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// User id from db - Global Variable
$user_id = NULL;
// ---------------------------------------------------------------------
// ------ web services -------------------------------------------------
// ---------------------------------------------------------------------
// Creating a new material in db
$app->post('/materials', 'authenticate', 'createMaterials');
// Listing all materials
$app->get('/materials', 'authenticate', 'getAllMaterials');
// Updating all materials included in payload
$app->put('/materials', 'authenticate', 'updateMaterials');
// Deleting a set of materials
$app->delete('/materials', 'authenticate', 'deleteMaterials');
// ---------------------------------------------------------------------
// ------ Auxiliar methods ---------------------------------------------
// ---------------------------------------------------------------------
// Verifying required params posted or not
function verifyRequiredParams($required_fields)
{
    $error = false;
    $error_fields = "";
    $request_params = array();
    $request_params = $_REQUEST;
    // Handling PUT request params
Example #12
0
    }
    echo $twig->render('@page/landing.html', $urls);
});
$app->get('/login/', function () use($app, $twig, $urls) {
    $env = $app->environment();
    if (!$env['ulogovan']['status']) {
        echo $twig->render('@page/login.html', array_merge($urls, $env['ulogovan']));
    } else {
        header('Location: /');
        die;
    }
});
$app->post('/logtest/', function () use($app, $em, $urls) {
    $env = $app->environment();
    if ($env['ulogovan']['status']) {
        echo "{'status': 'ulogovan'}";
    } else {
        echo "{'status': 'nije ulogovan'}";
    }
});
$app->post('/login/', function () use($app, $em, $urls) {
    $env = $app->environment();
    if (!$env['ulogovan']['status']) {
        try {
            $ds = ldap_connect("localhost");
            ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
            ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
            $user_data = explode('@', $_POST['email']);
            $user = $user_data[0];
            $pass = $_POST['pass'];
            $r = ldap_bind($ds, "cn={$user},ou=users,dc=db,dc=etf,dc=lab,dc=ba", $pass);
            $sr = ldap_search($ds, "dc=db,dc=etf,dc=lab,dc=ba", "cn={$user}");
Example #13
0
    } else {
        $app->response->status(500);
        echo json_encode($events["error"]);
        return;
    }
    uasort($events, 'cmp');
    $tags = Postmortem::get_tags();
    if ($tags["status"] == Postmortem::OK) {
        $tags = $tags["values"];
    } else {
        $tags = array();
    }
    include 'views/page.php';
});
$app->post('/timezone', function () use($app) {
    $_SESSION['timezone'] = $app->request->post('timezone');
    $app->redirect($app->request()->getReferrer());
});
$app->post('/events', function () use($app) {
    $title = $app->request->post('title');
    $start_date = $app->request->post('start_date');
    $start_time = $app->request->post('start_time');
    $end_date = $app->request->post('end_date');
    $end_time = $app->request->post('end_time');
    $detect_date = $app->request->post('detect_date');
    $detect_time = $app->request->post('detect_time');
    $status_date = $app->request->post('status_date');
    $status_time = $app->request->post('status_time');
    $timezone = $app->request->post('timezone');
    $severity = $app->request->post('severity');
    $startdate = new DateTime($start_date . " " . $start_time, new DateTimeZone($timezone));
    $enddate = new DateTime($end_date . " " . $end_time, new DateTimeZone($timezone));
    // Alle CDs aus Datenbank holen
    $ctrlCD->GetStats("group-cds-by-year");
});
/**
 * (POST)
 * Speichert eine CD in der Datenbank
 */
$app->post('/cd', function () use($app) {
    // $req = $app->request();
    // $body = $req->getBody();
    // $_request = json_decode($body);
    // Band-Controller instanziieren
    $ctrlCD = new CDController();
    echo json_encode($_REQUEST, JSON_NUMERIC_CHECK);
    // echo json_encode(array('type' => $_REQUEST['type'], 'id' => $_REQUEST['id']), JSON_NUMERIC_CHECK);
    // CD-Info aus Datenbank holen
    // Mögliche Typen ($_REQUEST['type']):
    // - songs
    // - ...
    // $ctrlCD->PostCdInfo((object) array(
    //     'type'    => $_REQUEST['type'],
    //     'id' => $_REQUEST['id']
    // ));
});
// $app->put('/cd/:id', function ($id) use ($db, $app) {
$app->put('/cd/:id', function ($id) use($app) {
    // update data
});
$app->delete('/cd/:id', function ($id) use($db) {
    // delete data
});
    $itens = $pedido->getPedidoItens();
    $resposta = array("status" => "sucesso", "message" => "A lista está vazia", "data" => $itens);
    header("Content-Type: application/json");
    header('HTTP/1.0 200 OK');
    echo json_encode($resposta);
    exit;
});
$app->get('/pedido/:id', function ($id) use($app) {
    $clientenome = $app->request()->get("clientenome");
    $resposta = array("status" => "sucesso", "message" => "Seu código é {$id}", "data" => array("clientenome" => $clientenome));
    header("Content-Type: application/json");
    header('HTTP/1.0 200 OK');
    echo json_encode($resposta);
    exit;
});
$app->post('/pedido', function () use($app) {
    $produtoid = $app->request()->post("produtoid");
    $produtonome = $app->request()->post("produtonome");
    $produtoestoque = $app->request()->post("produtoestoque");
    $produtovalor = $app->request()->post("produtovalor");
    $pedido = new Pedido();
    $produto = new Produto($produtoid, $produtonome, $produtoestoque, $produtovalor);
    $pedido->addItemPedido($produto, 1);
    $pedidoservicos = new PedidoServicos();
    $resposta = array("status" => "sucesso", "message" => $pedidoservicos->salvar($pedido), "data" => array());
    header("Content-Type: application/json");
    header('HTTP/1.0 200 OK');
    echo json_encode($resposta);
    exit;
});
$app->run();
Example #16
0
 $app->get('/checkname/:name', function ($name) use($app, $db) {
     //Verificar si existe un curso con nombre "name"
     $courseController = new \Controllers\Cursos($app, $db);
     $courseController->checkname($name);
 });
 $app->get('/buscar/:usuario_id/:name', function ($usuario_id, $name) use($app, $db) {
     //busqueda de un curso por nombre
     $courseController = new \Controllers\Cursos($app, $db);
     $courseController->buscar($usuario_id, $name);
 });
 $app->post('/alta', function () use($app, $db) {
     //dar de alta un nuevo curso
     try {
         $request = $app->request();
         $courseController = new \Controllers\Cursos($app, $db);
         $courseController->crearCurso($request->post('nombre'), $request->post('descripcion'), $request->post('horarios'), $request->post('usuario_id'));
     } catch (Exception $e) {
         $app->response()->status(400);
         $app->response()->header('X-Status-Reason', $e->getMessage());
     }
 });
 $app->post('/generar_clase/', function () use($app, $db) {
     //generar una clase para un curso
     try {
         $request = $app->request();
         $courseController = new \Controllers\Cursos($app, $db);
         $courseController->generarClase($request->post('curso_id'));
     } catch (Exception $e) {
         $app->response()->status(400);
         $app->response()->header('X-Status-Reason', $e->getMessage());
     }
Example #17
0
<?php

require dirname(__DIR__) . '/vendor/autoload.php';
$app = new Slim\Slim();
$view = new Pug\Example\Simple($app);
// Request전체를 보고자 할때.
$app->get("/status", [$view, 'showStatus']);
$app->post("/status", [$view, 'showStatus']);
$app->put("/status", [$view, 'showStatus']);
$app->delete("/status", [$view, 'showStatus']);
// 일반적인 상황의 로그인과 로그아웃
$app->post('/login', [$view, 'normalLogin']);
$app->get('/me', [$view, 'normalMe']);
// 크로스 도메인의 경우 로그인과 로그아웃 (세션 분리)
$app->post('/cors/login', [$view, 'corsLogin']);
$app->get('/cors/me', [$view, 'corsMe']);
$app->run();
Example #18
0
$oBlogMgr = new BlogMgr();
$oApp = new \Slim\Slim(array('templates.path' => __DIR__ . '/../views'));
date_default_timezone_set('Canada/Saskatchewan');
$oApp->add(new \Slim\Middleware\SessionCookie(array('expires' => '60 minutes', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => false, 'name' => 'slim_session', 'secret' => 'CHANGE_ME', 'cipher' => MCRYPT_RIJNDAEL_256, 'cipher_mode' => MCRYPT_MODE_CBC)));
/***
 * Home page
***/
$oApp->get('/', function () use($oApp, $oProductMgr) {
    $oApp->render('home.phtml', array('title' => '', 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => 'Action', 'productsInGenre' => $oProductMgr->getProductsByGenre('Action'), 'featuredProducts' => $oProductMgr->getFeaturedProducts()));
});
$oApp->get('/home/:genre', function ($sGenre) use($oApp, $oProductMgr) {
    $oApp->render('home.phtml', array('title' => $sGenre, 'userType' => getUserType(), 'genreAll' => $oProductMgr->getGenre(), 'genreSelected' => $sGenre, 'productsInGenre' => $oProductMgr->getProductsByGenre($sGenre), 'featuredProducts' => $oProductMgr->getFeaturedProducts()));
});
// called when user search for items
$oApp->post('/search', function () use($oApp, $oProductMgr) {
    $sKeywords = $oApp->request()->post('keywords');
    $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords));
});
$oApp->get('/search', function () use($oApp, $oProductMgr) {
    $sKeywords = $oApp->request->params('keywords');
    //ChromePhp::info($sKeywords);
    //die();
    $oApp->render('searchResult.phtml', array('title' => $sKeywords, 'userType' => getUserType(), 'products' => $oProductMgr->getProductByKeywords($sKeywords), 'keywords' => $sKeywords));
});
/***
 * Product page
***/
$oApp->get('/product/:productId', function ($nProductId) use($oApp, $oProductMgr) {
    if (isset($_SESSION['cart'][$nProductId])) {
        $numInCart = $_SESSION['cart'][$nProductId];
    } else {
        $numInCart = 0;
Example #19
0
    if (count($datos) > 0) {
        echo json_encode($datos[0]);
    } else {
        echo json_encode('false');
    }
});
/*
* Ruta para crear un producto en la base de datos desde el panel de administración
*/
$app->post('/producto', function () use($app) {
    // conectar con la BD y seleccionar la colección
    $mongo = new MongoClient();
    $database = $mongo->plazamar;
    $collection = $database->productos;
    // recuperar los datos enviados por backbone
    $req = $app->request()->getBody();
    $body = json_decode($req, true);
    $datos = ['titulo' => $body['titulo'], 'autor' => $body['autor'], 'editorial' => $body['editorial'], 'precio' => $body['precio'], 'isbn' => $body['isbn'], 'categoria' => $body['categoria'], 'tieneDescuento' => $body['tieneDescuento'], 'descuento' => $body['descuento'], 'imagen' => 'img/' . $body['imagen']];
    // grabar los datos en mongodb
    $collection->save($datos);
    // devolvemos un json
    echo json_encode($datos);
});
// alta de imagen de producto desde panel de administración (REVISAR)
$app->post('/archivoImagen', function () use($app) {
    $request = $app->request()->getBody();
    $datos = json_decode($request, true);
    // guardamos el archivo subido
    move_uploaded_file($datos, "img/archivo.png");
    echo json_encode($datos);
});
/*
Example #20
0
$LIST_ORDER_LATEST_ACTIVITY = USEARCH_BOL_Service::LIST_ORDER_LATEST_ACTIVITY;
$LIST_ORDER_NEW = USEARCH_BOL_Service::LIST_ORDER_NEW;
$HAMMU_BOL_Service = HAMMU_BOL_Service::getInstance();
$language = OW::getLanguage();
$OWgetDbo = OW::getDbo();
$SKADATE_BOL_AccountTypeToGenderDao = SKADATE_BOL_AccountTypeToGenderDao::getInstance();
//
//
//$getClassInstance = OW::getClassInstance('USEARCH_CLASS_QuickSearchForm');
//$formatBirthdate = UTIL_DateTime::formatBirthdate;
//$autoLink = UTIL_HtmlTag::autoLink;
//$parseDate = UTIL_DateTime::parseDate;
// POST route
//$app->post('/loginapp', 'loginapp');
//$app->post('/loginapp', 'loginapp');
$app->post('/login', 'login');
$app->post('/forgot_password', 'forgot_password');
$app->post('/getAllServices', 'getAllServices');
$app->post('/getAllServicesOrPreferences', 'getAllServicesOrPreferences');
$app->post('/getProfiledetails', 'getProfiledetails');
$app->post('/listing', 'listing');
$app->post('/setProfiledetails', 'setProfiledetails');
$app->post('/advance_search', 'advance_search');
$app->post('/setProfilePic', 'setProfilePic');
$app->post('/sendInvites', 'sendInvites');
$app->post('/getClientInvitesLog', 'getClientInvitesLog');
$app->post('/getEscortInvitesLog', 'getEscortInvitesLog');
$app->post('/acceptInvites', 'acceptInvites');
$app->post('/proposeDateInvitation', 'proposeDateInvitation');
//$app->post('/roseInvites', 'roseInvites');
$app->post('/reArrageInvites', 'reArrageInvites');
Example #21
0
$app->post('/contact', function () use($app) {
    $name = $app->request()->post('name');
    $email = $app->request()->post('email');
    $msg = $app->request()->post('msg');
    if (!empty($name) && !empty($email) && !empty($msg)) {
        $claenName = filter_var($name, FILTER_SANITIZE_STRING);
        $claenEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
        $claenMsg = filter_var($msg, FILTER_SANITIZE_STRING);
    } else {
        $app->redirect('contact');
    }
    // Create the Transport
    $transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, 'ssl')->setUsername('*****@*****.**')->setPassword('LittleRichard');
    //test it!!!!!!!!!
    //$transport = Swift_SmtpTransport::newInstance('mail.matenadaran.am', 465, 'ssl')
    //  ->setUsername('*****@*****.**')
    //  ->setPassword('d_404_igit')
    //  ;
    /*
    You could alternatively use a different transport such as Sendmail or Mail:
    
    // Sendmail
    $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
    
    // Mail
    $transport = Swift_MailTransport::newInstance();
    */
    // Create the Mailer using your created Transport
    $mailer = Swift_Mailer::newInstance($transport);
    // Create a message
    $message = Swift_Message::newInstance('Wonderful Subject');
    $message->setFrom(array($claenEmail => $claenName));
    $message->setTo(array('*****@*****.**' => 'Ara'));
    $message->setBody($claenMsg);
    // Send the message
    $result = $mailer->send($message);
    echo $result . ' I am result';
});
Example #22
0
 /**
  * Test POST route
  */
 public function testPostRoute()
 {
     \Slim\Environment::mock(array('REQUEST_METHOD' => 'POST', 'SCRIPT_NAME' => '/foo', 'PATH_INFO' => '/bar'));
     $s = new \Slim\Slim();
     $mw1 = function () {
         echo "foo";
     };
     $mw2 = function () {
         echo "bar";
     };
     $callable = function () {
         echo "xyz";
     };
     $route = $s->post('/bar', $mw1, $mw2, $callable);
     $s->call();
     $this->assertEquals('foobarxyz', $s->response()->body());
     $this->assertEquals('/bar', $route->getPattern());
     $this->assertSame($callable, $route->getCallable());
 }
Example #23
0
    </html>
EOT;
    echo $template;
    $isJSON = 1;
});
// POST route
$app->post('/post', function () {
    // echo 'This is a POST route';
    // Helpful reference:
    // http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/
    // key change being need to use \Slim\Slim:: not just Slim::
    $request = \Slim\Slim::getInstance()->request();
    // $data = json_encode($request->getBody());
    $data = $request->getBody();
    $allPostVars = json_encode($request->post());
    $file = "post.json";
    $fp = fopen($file, 'w+');
    if (!$fp) {
        exit("Couldn't open file\n                        ");
    }
    fwrite($fp, $allPostVars);
    fclose($fp);
    echo "Posted \n";
    echo $data;
});
//  END POST
$app->get('/get', function () {
    $mydata = file_get_contents("test.json");
    print $mydata;
});
// PUT route
Example #24
0
//tell me stuff
$app = new \Slim\Slim();
$app->get('/home', function () {
});
//so far nothing for home
$app->get('/selection/:job', function ($job) {
    $client = new Indeed("4779755742469402");
    $params = array("q" => $job, "l" => $location, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25");
    $results = $client->search($params);
    echo json_encode($results);
});
$app->get('/selection/:job/:location', function ($job, $location) {
    $client = new Indeed("4779755742469402");
    $params = array("q" => $job, "l" => $location, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25");
    $results = $client->search($params);
    echo json_encode($results);
});
$app->get('/selection/:job/:location/:page', function ($job, $location, $page) {
    $client = new Indeed("4779755742469402");
    $params = array("q" => $job, "l" => $location, "start" => $page * 25, "userip" => $_SERVER['REMOTE_ADDR'], "useragent" => $_SERVER['HTTP_USER_AGENT'], "limit" => "25");
    $results = $client->search($params);
    echo json_encode($results);
});
$app->post('/contact', function () {
    //send message in content
    $message = $_POST['name'];
    $message .= $_POST['phone'];
    $message .= $_POST['message'];
    echo $message;
});
$app->run();
require_once '../service/ContraMedidaService.php';
require_once '../model/ContraMedida.php';
require_once '../Slim/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$contraMedidaService = new ContraMedidaService();
$app->get("/", function () {
    echo "<h1>Hello World</h1>";
});
$app->get("/contraMedida/getall", function () use($app, $contraMedidaService) {
    echo '{"contraMedidas": ' . json_encode($contraMedidaService->buscarContraMedidas()) . '}';
});
$app->get("/contraMedida/:id", function ($id) use($app, $contraMedidaService) {
    echo json_encode($contraMedidaService->buscarContraMedida($id));
});
$app->post("/contraMedida/cadastrar", function () use($app, $contraMedidaService) {
    $app->response()->header("Content-Type", "application/json");
    $resultado = json_decode($app->request()->getBody());
    echo json_encode($contraMedidaService->cadastrarContraMedida($resultado->nomeContraMedida));
});
$app->put("/contraMedida/atualizar", function ($id) use($app, $contraMedidaService) {
    $app->response()->header("Content-Type", "application/json");
    $resultado = json_decode($app->request()->getBody());
    echo json_encode($contraMedidaService->atualizarContraMedida($resultado->idContraMedida, $resultado->nomeContramedida));
});
$app->delete("/contraMedida/remover/:id", function ($id) use($app, $contraMedidaService) {
    $app->response()->header("Content-Type", "application/json");
    $resultado = json_decode($app->request()->getBody());
    echo json_encode($contraMedidaService->removerContraMedida($id));
});
$app->run();
Example #26
0
    // En PDO los parámetros para las consultas se pasan con :nombreparametro (casualmente
    // coincide con el método usado por Slim).
    // No confundir con el parámetro :idusuario que si queremos usarlo tendríamos
    // que hacerlo con la variable $usuarioID
    $consulta = $db->prepare("select * from usuarios where id=:param1");
    // En el execute es dónde asociamos el :param1 con el valor que le toque.
    $consulta->execute(array(':param1' => $usuarioID));
    // Almacenamos los resultados en un array asociativo.
    $resultados = $consulta->fetchAll(PDO::FETCH_ASSOC);
    // Devolvemos ese array asociativo como un string JSON.
    echo json_encode($resultados);
});
// Alta de usuarios en la API REST
$app->post('/usuarios', function () use($db, $app) {
    // Para acceder a los datos recibidos del formulario
    /*
    echo json_encode("$p->id - $p->nombre - $p->apellidos - $p->telefono");
    */
    // Los datos serán accesibles de esta forma:
    $p = json_decode($app->request->getBody());
    //echo json_encode("$p->latitud - $p->nombre - $p->apellidos - $p->telefono");
    // Preparamos la consulta de insert.
    $consulta = $db->prepare("insert into usuarios(id,nombre,apellidos,telefono, latitud, longitud) \n\t\t\t\t\tvalues (:id,:nombre,:apellidos,:telefono, :latitud, :longitud)");
    $estado = $consulta->execute(array(':id' => $p->id, ':nombre' => $p->nombre, ':apellidos' => $p->apellidos, ':telefono' => $p->telefono, ':latitud' => $p->latitud, ':longitud' => $p->longitud));
    if ($estado) {
        echo json_encode(array('estado' => true, 'mensaje' => 'Datos insertados correctamente. '));
    } else {
        echo json_encode(array('estado' => false, 'mensaje' => "Error al insertar datos en la tabla."));
    }
});
$app->run();
        $managerDB->debugManagerDB();
		
    }
);


$app->post(
    '/users',
    function () use($app) {
        
        $paramEmail = $app->request->post('email'); 
        $paramPassword = $app->request->post('password');
        $paramPasswordConfirm = $app->request->post('password_confirmation');
        $paramLogin = $app->request->post('login');
        
        
        //echo $paramEmail."<br>";
        //echo $paramPassword."<br>";
        //echo $paramPasswordConfirm."<br>";
        //echo $paramName."<br>";
        
        $managerDB = new ManagerDB();
        $managerDB->reqUsers($paramEmail, $paramPassword, $paramLogin);
        
    }
);

$app->post(
    '/tokens.json',
    function () use($app) {
        $paramEmail = $app->request->post('email'); 
        $paramPassword = $app->request->post('password');    
Example #28
0
    $consulta = $db->prepare("select * from soporte_usuarios where idusuario=:param1");
    // En el execute es dónde asociamos el :param1 con el valor que le toque.
    $consulta->execute(array(':param1' => $usuarioID));
    // Almacenamos los resultados en un array asociativo.
    $resultados = $consulta->fetchAll(PDO::FETCH_ASSOC);
    // Devolvemos ese array asociativo como un string JSON.
    echo json_encode($resultados);
});
// Alta de usuarios en la API REST
$app->post('/usuarios', function () use($db, $app) {
    // Para acceder a los datos recibidos del formulario
    $datosform = $app->request;
    // Los datos serán accesibles de esta forma:
    // $datosform->post('apellidos')
    // Preparamos la consulta de insert.
    $consulta = $db->prepare("insert into soporte_usuarios(idusuario,nombre,apellidos,email) \n\t\t\t\t\tvalues (:idusuario,:nombre,:apellidos,:email)");
    $estado = $consulta->execute(array(':idusuario' => $datosform->post('idusuario'), ':nombre' => $datosform->post('nombre'), ':apellidos' => $datosform->post('apellidos'), ':email' => $datosform->post('email')));
    if ($estado) {
        echo json_encode(array('estado' => true, 'mensaje' => 'Datos insertados correctamente.'));
    } else {
        echo json_encode(array('estado' => false, 'mensaje' => 'Error al insertar datos en la tabla.'));
    }
});
// Programamos la ruta de borrado en la API REST (DELETE)
$app->delete('/usuarios/:idusuario', function ($idusuario) use($db) {
    $consulta = $db->prepare("delete from soporte_usuarios where idusuario=:id");
    $consulta->execute(array(':id' => $idusuario));
    if ($consulta->rowCount() == 1) {
        echo json_encode(array('estado' => true, 'mensaje' => 'El usuario ' . $idusuario . ' ha sido borrado correctamente.'));
    } else {
        echo json_encode(array('estado' => false, 'mensaje' => 'ERROR: ese registro no se ha encontrado en la tabla.'));
    }
Example #29
0
    return array_map('objectToArray', (array) $object);
}
$app->get('/', function () {
    //存在的价值大概就是判断api服务有没有的拉
    echo '<h1>let barrage fly api</h1>';
});
$app->post('/register', function () use($client) {
    $requset = new OpenimUsersAddRequest();
    $userinfo = new Userinfos();
    $requestBody = json_decode(@file_get_contents('php://input'), true);
    $username = isset($requestBody['username']) && $requestBody['username'] != '' ? $requestBody['username'] : '';
    $password = isset($requestBody['password']) && $requestBody['password'] != '' ? md5($requestBody['password']) : '';
    $userinfo->userid = $username;
    $userinfo->password = $password;
    $requset->setUserinfos(json_encode($userinfo));
    $response = $client->execute($requset);
    $responseArray = objectToArray($response);
    if (isset($responseArray['uid_succ']['string']) && $responseArray['uid_succ']['string'] == $userinfo->userid) {
        //判断是否注册成功,直接返回密码,用来登录,也就是credential
        echo json_encode(array('msg' => 'success register', 'code' => 'success', 'username' => $userinfo->userid, 'password' => $userinfo->password));
    } else {
        throw new \Exception(json_encode($responseArray));
        //        echo json_encode($responseArray);
    }
});
$app->post('/login', function () use($client) {
    $request = new OpenimUsersGetRequest();
    $requestBody = json_decode(@file_get_contents('php://input'), true);
    if ($requestBody == null) {
        $username = isset($_POST['username']) ? $_POST['username'] : '';
        $password = isset($_POST['password']) ? $_POST['password'] : '';
Example #30
-1
    // retrieve user information
    $result = sendQuery("SELECT * FROM Schedules WHERE Timestamp='{$timestamp}'");
    $appointmentInfo = mysqli_fetch_assoc($result);
    // delete record
    sendQuery("DELETE FROM Schedules WHERE Timestamp='{$timestamp}'");
    sendEmail('TokBox Demo', '*****@*****.**', $appointmentInfo['Name'], $appointmentInfo['Email'], "Cancelled: Your TokBox appointment on " . $appointmentInfo['Timestring'], "Your appointment on " . $appointmentInfo['Timestring'] . ". has been cancelled. We are sorry for the inconvenience, please reschedule on " . getBaseURL() . "/index.php/");
    header("Content-Type: application/json");
    echo json_encode($appointmentInfo);
});
$app->post('/schedule', function () use($app, $con, $opentok) {
    $name = $app->request->post("name");
    $email = $app->request->post("email");
    $comment = $app->request->post("comment");
    $timestamp = $app->request->post("timestamp");
    $daystring = $app->request->post("daystring");
    $session = $opentok->createSession();
    $sessionId = $session->getSessionId();
    $timestring = $app->request->post("timestring");
    $query = sprintf("INSERT INTO Schedules (Name, Email, Comment, Timestamp, Daystring, Sessionid, Timestring) VALUES ('%s', '%s', '%s', '%d', '%s', '%s', '%s')", mysqli_real_escape_string($con, $name), mysqli_real_escape_string($con, $email), mysqli_real_escape_string($con, $comment), intval($timestamp), mysqli_real_escape_string($con, $daystring), mysqli_real_escape_string($con, $sessionId), mysqli_real_escape_string($con, $timestring));
    sendQuery($query);
    sendEmail('TokBox Demo', '*****@*****.**', $name, $email, "Your TokBox appointment on " . $timestring, "You are confirmed for your appointment on " . $timestring . ". On the day of your appointment, go here: " . getBaseURL() . "/index.php/chat/" . $sessionId);
    $app->render('schedule.php');
});
$app->get('/rep', function () use($app) {
    $app->render('rep.php');
});
$app->get('/chat/:session_id', function ($session_id) use($app, $con, $apiKey, $opentok) {
    $result = sendQuery("SELECT * FROM Schedules WHERE Sessionid='{$session_id}'");
    $appointmentInfo = mysqli_fetch_assoc($result);
    $token = $opentok->generateToken($session_id);
    $app->render('chat.php', array('name' => $appointmentInfo['Name'], 'email' => $appointmentInfo['Email'], 'comment' => $appointmentInfo['Comment'], 'apiKey' => $apiKey, 'session_id' => $session_id, 'token' => $token));
});